问:
How to delete data from a table in mysql Using a subquery
I have this query with returned rows a alias and in keyword in mysql.I would like to delete all returned row that value is less or equal to 0 in the same table.

```<code> delete from tblmusterproject where final in(
 SELECT final from (select sum(Crowd+Review+Lp+additions+deductions+monthly) as final,
 employeeno FROM tblmusterproject
 group by employeeno) as b) <=0;
</code>```

am get this Error "Unknown column 'final' in 'IN/ALL/ANY subquery'"
How can i do it.

答:
You have <=0 that seems in wrong position   and yout

If you want delete the employeeno when filter value (alias  the sum) <= 0 then you could use having  in subquery for get the employeeid you need

and instead of a in clause you could use a join

```<code> delete t
 from tblmusterproject t
 INNER JOIN  (
    Select sum(Crowd+Review+Lp+additions+deductions+monthly) as final, employeeno
    FROM tblmusterproject
    group by employeeno
    HAVING final = <=0
)  b on b.employeeno = t.employeeno
</code>```

Body:
I have this query with returned rows a alias and in keyword in mysql.I would like to delete all returned row that value is less or equal to 0 in the same table.

 delete from tblmusterproject where final in(
 SELECT final from (select sum(Crowd+Review+Lp+additions+deductions+monthly) as final,
 employeeno FROM tblmusterproject
 group by employeeno) as b) <=0;

am get this Error "Unknown column 'final' in 'IN/ALL/ANY subquery'"
How can i do it.

Body:
You have <=0 that seems in wrong position   and yout

If you want delete the employeeno when filter value (alias  the sum) <= 0 then you could use having  in subquery for get the employeeid you need

and instead of a in clause you could use a join

 delete t
 from tblmusterproject t
 INNER JOIN  (
    Select sum(Crowd+Review+Lp+additions+deductions+monthly) as final, employeeno
    FROM tblmusterproject
    group by employeeno
    HAVING final = <=0
)  b on b.employeeno = t.employeeno


来源: stackexchange

答:
I would go with</p>

```<code>import numpy as np
# Your code here
res = np.empty((0,))
for i in range(1, len(x)):
    delta = int((x[i] - x[i-1]) / interval)
    res = np.append(res, np.linspace(y2[i-1], y2[i], delta, endpoint=False))
print(res)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Is it possible to divide the value of a list in a certain amount of times

Body:
Hi I am trying to split the values in a (y2)list into (inv) amount of parts.

x = [0,100,200,300,400,500,600,700,800,900,1000,1100]
y2 = [58,55,49,12,6,5,4,4.5,35,48,56,58]
interval = 5
inv = (x[0] + x[1])/interval

I will like to split y2 into inv parts so my answer should be:

[58 57.85 57.7 57.55 57.4 57.25 57.1 56.95 56.8 56.65 56.5 56.35 56.2 56.05 55.9 55.75 55.6 55.45 55.3 55.15 55...…….49...…………..12...….6 ………...5...……..]

I will like to mention that inv will always be (x[0] + x[1])/interval

Body:
I would go with

import numpy as np
# Your code here
res = np.empty((0,))
for i in range(1, len(x)):
    delta = int((x[i] - x[i-1]) / interval)
    res = np.append(res, np.linspace(y2[i-1], y2[i], delta, endpoint=False))
print(res)


问:
How to get IMEI in android 10
For security purposes, I want to store the IMEI number of app users but I am getting the following error

```<code>2020-02-14 13:29:36.620 14794-14794/com.udaan.android.creditoperations E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.udaan.android.creditoperations, PID: 14794
    java.lang.SecurityException: getImeiForSlot: The user 10643 does not meet the requirements to access device identifiers.
        at android.os.Parcel.createException(Parcel.java:2071)
        at android.os.Parcel.readException(Parcel.java:2039)
        at android.os.Parcel.readException(Parcel.java:1987)
        at com.android.internal.telephony.ITelephony$Stub$Proxy.getImeiForSlot(ITelephony.java:10471)
        at android.telephony.TelephonyManager.getImei(TelephonyManager.java:1754)
        at android.telephony.TelephonyManager.getImei(TelephonyManager.java:1715)
</code>```

Is there any way to access IMEI number including latest android devices?

答:
Have you tried to add permission to AndroidManifest file?</p>

```<code><uses-permission android:name="android.permission.READ_PHONE_STATE" />
</code>```

Title: How to get IMEI in android 10

Body:
For security purposes, I want to store the IMEI number of app users but I am getting the following error

2020-02-14 13:29:36.620 14794-14794/com.udaan.android.creditoperations E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.udaan.android.creditoperations, PID: 14794
    java.lang.SecurityException: getImeiForSlot: The user 10643 does not meet the requirements to access device identifiers.
        at android.os.Parcel.createException(Parcel.java:2071)
        at android.os.Parcel.readException(Parcel.java:2039)
        at android.os.Parcel.readException(Parcel.java:1987)
        at com.android.internal.telephony.ITelephony$Stub$Proxy.getImeiForSlot(ITelephony.java:10471)
        at android.telephony.TelephonyManager.getImei(TelephonyManager.java:1754)
        at android.telephony.TelephonyManager.getImei(TelephonyManager.java:1715)

Is there any way to access IMEI number including latest android devices?

Body:
Have you tried to add permission to AndroidManifest file?

<uses-permission android:name="android.permission.READ_PHONE_STATE" />


问:
Custom gRPC command for Dropwizard exits immediately
I've created an application using Dropwizard that starts a gRPC server. I do not use the regular server, and want to start my application using java -jar my-fat.jar grpc config.yml instead.

I've come as far as to add the command as the only available command during startup by overriding the corresponding method in the application class:

public class App extends Application<Configuration> {

    public static void main(String[] args) throws Exception {
        new App().run(args);
    }

    @Override
    protected void addDefaultCommands(final Bootstrap<Configuration> bootstrap) {
        bootstrap.addCommand(new GrpcCommand(this));
    }
}
```

<p>I can launch my application using <code>java -jar my-fat.jar grpc config.yml</code>. My command looks like this:</p>

<pre class="lang-java prettyprint-override"><code>public class GrpcCommand extends EnvironmentCommand<Configuration> {

    public GrpcCommand(Application<Configuration> application) {
        this(application, "grpc", "Runs the Dropwizard application as a gRPC server");
    }

    /**
     * Creates a new environment command.
     *
     * @param application the application providing this command
     * @param name        the name of the command, used for command line invocation
     * @param description a description of the command's purpose
     */
    protected GrpcCommand(final Application<Configuration> application, final String name, final String description) {
        super(application, name, description);
    }

    @Override
    protected void run(final Environment environment, final Namespace namespace, final Configuration configuration) throws Exception {
        final var certificateService = AzureCertificateService.createWithClients(
                AzureSecretClient.create(configuration.getKeyVaultConfiguration()),
                AzureCertificateClient.create(configuration.getKeyVaultConfiguration())
        );

        final var validationService = CertificateValidationService.create(certificateService);
        final var signingService = CertificateSigningService.create(certificateService);

        final Pair<X509Certificate, KeyPair> certificate = certificateService.getSigningCertificateWithKeyPair();

        final BaseApiImpl baseApi = new BaseApiImpl(validationService, signingService);
        final GrpcServer grpcServer = GrpcServer.newBuilder()
                .withBaseApi(baseApi)
                .withConfiguration(configuration.getGrpcConfiguration())
                .withCertificate(certificate.getLeft())
                .withPrivateKey(certificate.getRight().getPrivate())
                .build();

        new Thread(() -> {
            try {
                grpcServer.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).run();

        environment.healthChecks().register("grpc-server", new GrpcServerHealthCheck(grpcServer));
    }
}
</code>```

The way that thread is started is not for production use, I'm just trying to get forward. The start method for the GrpcServer class:

@Override
public void start() throws Exception {
    final NettyServerBuilder nettyServerBuilder = NettyServerBuilder.forPort(configuration.getPort())
            .addService(baseApi)
            .intercept(new OriginInterceptor());

    if (certificate != null && privateKey != null) {
        LOG.info("Got certificate and private key, enabling SSL");
        nettyServerBuilder.sslContext(buildSslContext());
    }

    server = nettyServerBuilder
            .build()
            .start();

    LOG.info("Server started at port {}", server.getPort());
}
```

And I see the message GrpcServer: Server started at port 50441 in my log when I start. However, the application does not stay open. What am I missing? Shouldn't my use of the thread create a thread that stops the application from exiting? How can I keep the application running after the gRPC server has started?

答:
When I disabled the server command, Jetty isn't started either (of course), which kept the application alive previously.

I found the simplest solution in the gRPC Hello World Example.

My start method now looks like this:

public void start() throws Exception {
    // Everything else as above

    Runtime.getRuntime().addShutdownHook(new Thread(GrpcServer.this::stop));
    LOG.info("Server started at port {}", server.getPort());
    blockUntilShutdown();
}

private void blockUntilShutdown() throws InterruptedException {
    if (server != null) {
        server.awaitTermination();
    }
}
```

Body:
I've created an application using Dropwizard that starts a gRPC server. I do not use the regular server, and want to start my application using java -jar my-fat.jar grpc config.yml instead.

I've come as far as to add the command as the only available command during startup by overriding the corresponding method in the application class:

public class App extends Application<Configuration> {

    public static void main(String[] args) throws Exception {
        new App().run(args);
    }

    @Override
    protected void addDefaultCommands(final Bootstrap<Configuration> bootstrap) {
        bootstrap.addCommand(new GrpcCommand(this));
    }
}

I can launch my application using java -jar my-fat.jar grpc config.yml. My command looks like this:

public class GrpcCommand extends EnvironmentCommand<Configuration> {

    public GrpcCommand(Application<Configuration> application) {
        this(application, "grpc", "Runs the Dropwizard application as a gRPC server");
    }

    /**
     * Creates a new environment command.
     *
     * @param application the application providing this command
     * @param name        the name of the command, used for command line invocation
     * @param description a description of the command's purpose
     */
    protected GrpcCommand(final Application<Configuration> application, final String name, final String description) {
        super(application, name, description);
    }

    @Override
    protected void run(final Environment environment, final Namespace namespace, final Configuration configuration) throws Exception {
        final var certificateService = AzureCertificateService.createWithClients(
                AzureSecretClient.create(configuration.getKeyVaultConfiguration()),
                AzureCertificateClient.create(configuration.getKeyVaultConfiguration())
        );

        final var validationService = CertificateValidationService.create(certificateService);
        final var signingService = CertificateSigningService.create(certificateService);

        final Pair<X509Certificate, KeyPair> certificate = certificateService.getSigningCertificateWithKeyPair();

        final BaseApiImpl baseApi = new BaseApiImpl(validationService, signingService);
        final GrpcServer grpcServer = GrpcServer.newBuilder()
                .withBaseApi(baseApi)
                .withConfiguration(configuration.getGrpcConfiguration())
                .withCertificate(certificate.getLeft())
                .withPrivateKey(certificate.getRight().getPrivate())
                .build();

        new Thread(() -> {
            try {
                grpcServer.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).run();

        environment.healthChecks().register("grpc-server", new GrpcServerHealthCheck(grpcServer));
    }
}

The way that thread is started is not for production use, I'm just trying to get forward. The start method for the GrpcServer class:

@Override
public void start() throws Exception {
    final NettyServerBuilder nettyServerBuilder = NettyServerBuilder.forPort(configuration.getPort())
            .addService(baseApi)
            .intercept(new OriginInterceptor());

    if (certificate != null && privateKey != null) {
        LOG.info("Got certificate and private key, enabling SSL");
        nettyServerBuilder.sslContext(buildSslContext());
    }

    server = nettyServerBuilder
            .build()
            .start();

    LOG.info("Server started at port {}", server.getPort());
}

And I see the message GrpcServer: Server started at port 50441 in my log when I start. However, the application does not stay open. What am I missing? Shouldn't my use of the thread create a thread that stops the application from exiting? How can I keep the application running after the gRPC server has started?


问:
How to get UTM paramters in activity when Clicked on Dynamic link
I am using Firebase Dynamic link when I click on it I get the deep link in activity, but how to get UTM parameters inside activity like how I get the deep link</p>

答:
try the following code for getting UTM parameters</p>

```<code>        FirebaseDynamicLinks.getInstance()
                .getDynamicLink(getIntent())
                .addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
                    @Override
                    public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
                        Uri deepLink = null;
                        if (pendingDynamicLinkData != null) {
                            deepLink = pendingDynamicLinkData.getLink();
                        }
                        if (deepLink != null
                                && deepLink.getBooleanQueryParameter("utm_param1", false)) {
                            String utm_param1 = deepLink.getQueryParameter("utm_param1");
                        }
                    }
                });
</code>```

Body:
try the following code for getting UTM parameters

        FirebaseDynamicLinks.getInstance()
                .getDynamicLink(getIntent())
                .addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
                    @Override
                    public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
                        Uri deepLink = null;
                        if (pendingDynamicLinkData != null) {
                            deepLink = pendingDynamicLinkData.getLink();
                        }
                        if (deepLink != null
                                && deepLink.getBooleanQueryParameter("utm_param1", false)) {
                            String utm_param1 = deepLink.getQueryParameter("utm_param1");
                        }
                    }
                });


问:
Zend: Using Row model method inside partialLoop
Zend talk.I have a view called "article" with a partialLoop inside,for displaying all comments in DB for that post:

```<code>[..]
echo $this->partialLoop('_comments.phtml',$this->comments);
</code>```

this is _comments.phtml:

```<code><li><?= $this->text." ".$this->datetime;?></li>
</code>```

Since the structure of comments DB table is:

```<code>id(PK) | text | datetime | authorId
</code>```

I wanted to retrieve the author name from "authors" DB table, with a CommentRow's method, from within _comments.phtml.

this is CommentRow model:

```<code>class CommentRow extends Zend_Db_Table_Row_Abstract
{
 function getAuthor()
 {
   $author=new Author();
   $q=$author->select('name');
   $q->where('id',$this->authorid);
   $result=$comment->fetchRow($q);
   return $result;
 }
</code>```

}

How can I iterate through the array of comments(which are object of type CommentRow),passed to the partial loop,calling the getAuthor() method to display the comment's author name?

thanks
Luca

答:
The Partial View Helper expects to you pass in a key/value structure. That can either be an associative array or an object. If you pass in an object any public properties will be considered unless the object has an toArray method returning an associative array with the desired keys and values. The keys and values passed to the helper will be made available in the partial. That means your Zend_Db_Rowset no longer exists in the partial. Read below how to pass it properly.

Quoting the Reference Guide for the Partial View Helper:

If your model is an object, you may want to have it passed as an object to the partial script, instead of serializing it to an array of variables. You can do this by setting the 'objectKey' property of the appropriate helper:

```<code>// Tell partial to pass objects as 'model' variable
  $view->partial()->setObjectKey('model');

// Tell partial to pass objects from partialLoop as 'model' variable
  // in final partial view script:
  $view->partialLoop()->setObjectKey('model');
</code>```

This technique is particularly useful when passing Zend_Db_Table_Rowsets to partialLoop(), as you then have full access to your row objects within the view scripts, allowing you to call methods on them (such as retrieving values from parent or dependent rows).

ContentLicense: CC BY-SA 3.0

Body:
Zend talk.I have a view called "article" with a partialLoop inside,for displaying all comments in DB for that post:

[..]
echo $this->partialLoop('_comments.phtml',$this->comments);

this is _comments.phtml:

<?= $this->text." ".$this->datetime;?>

Since the structure of comments DB table is:

id(PK) | text | datetime | authorId

I wanted to retrieve the author name from "authors" DB table, with a CommentRow's method, from within _comments.phtml.

this is CommentRow model:

class CommentRow extends Zend_Db_Table_Row_Abstract
{
 function getAuthor()
 {
   $author=new Author();
   $q=$author->select('name');
   $q->where('id',$this->authorid);
   $result=$comment->fetchRow($q);
   return $result;
 }

}

How can I iterate through the array of comments(which are object of type CommentRow),passed to the partial loop,calling the getAuthor() method to display the comment's author name?

thanks
Luca

Body:
The Partial View Helper expects to you pass in a key/value structure. That can either be an associative array or an object. If you pass in an object any public properties will be considered unless the object has an toArray method returning an associative array with the desired keys and values. The keys and values passed to the helper will be made available in the partial. That means your Zend_Db_Rowset no longer exists in the partial. Read below how to pass it properly.

Quoting the Reference Guide for the Partial View Helper:

If your model is an object, you may want to have it passed as an object to the partial script, instead of serializing it to an array of variables. You can do this by setting the 'objectKey' property of the appropriate helper:

// Tell partial to pass objects as 'model' variable
  $view->partial()->setObjectKey('model');

// Tell partial to pass objects from partialLoop as 'model' variable
  // in final partial view script:
  $view->partialLoop()->setObjectKey('model');

This technique is particularly useful when passing Zend_Db_Table_Rowsets to partialLoop(), as you then have full access to your row objects within the view scripts, allowing you to call methods on them (such as retrieving values from parent or dependent rows).


问:
How to send data from React template to Flask API?
I want to use a sign in template, but I'm not sure how to send data from this template to my Flask API. I read that states are only in components. Is that true? I tried calling the Register function inside render from another file that has a component, but I got an error about invalid hooks.

Flask API

```<code>from flask import Blueprint, jsonify
from flask import request, make_response
import sqlite3
from sqlite3 import Error
import os.path
import json

main = Blueprint('main', __name__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "database.db")

def connection():
    try:
        conn = sqlite3.connect(db_path)
    except Error as e:
        print(e)
    return conn

@main.route('/add_review', methods=['POST'])
def add_review():
    conn = connection()
    cur = conn.cursor()

    req = request.get_json()
    busID = req.get('busID')
    userID = req.get('userID')
    review = req.get('review')
    rating = req.get('rating')

    sql = "INSERT INTO Review (businessID, userID, review, rating) VALUES (?, ?, ?, ?)"
    data = (busID, userID, review, rating)
    cur.execute(sql, data)

    conn.commit()
    cur.close()

    return 'Done', 201

@main.route('/reviews')
def reviews():
    conn = connection()
    cur = conn.cursor()
    name = "Halal Guys"
    cur.execute("SELECT * FROM Review where businessID = (SELECT id FROM Business where name = \'{}\')".format(name))
    reviews = cur.fetchall()

    reviews_dict = []
    for review in reviews:
        content = {"id": review[0], "busID": review[1], "userID": review[2],
                    "review": review[3], "rating": review[4]}
        reviews_dict.append(content)

    return json.dumps(reviews_dict)

@main.route('/createUser', methods=['POST', 'OPTIONS'])
def createUser():
    # handle option request
    if request.method == "OPTIONS":
        response = make_response()
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers[
            "Access-Control-Allow-Headers"
        ] = "Origin, Accept, Content-Type"
        response.headers["Access-Control-Allow-Methods"] = "POST,OPTIONS"
        response.headers["Access-Control-Allow-Credentials"] = "true"
        return response

    if request.method == "POST":
        # do your SQL stuff
        conn = connection()
        cur = conn.cursor()

        req = request.get_json()
        first = req.get("FirstName")
        last = req.get("LastName")
        email = req.get("Email")
        pw = req.get("Password")

        sql = (
            "INSERT INTO User (first, last, emailAddress, password) VALUES (?, ?, ?, ?)"
        )
        data = (first, last, email, pw)
        cur.execute(sql, data)

        conn.commit()
        cur.close()

        # make response
        response = make_response("{}")  # return empty JSON response
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers[
            "Content-Type"
        ] = "application/json"  # set response type to JSON
        return response

    return "", 405

</code>```

Sign in template

```<code>import React from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Link from '@material-ui/core/Link';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';

function Copyright() {
  return (
    <Typography variant="body2" color="textSecondary" align="center">
      {'Copyright © '}
      <Link color="inherit" href="https://material-ui.com/">
        Your Website
      </Link>{' '}
      {new Date().getFullYear()}
      {'.'}
    </Typography>
  );
}

const useStyles = makeStyles(theme => ({
  paper: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.secondary.main,
  },
  form: {
    width: '100%', // Fix IE 11 issue.
    marginTop: theme.spacing(3),
  },
  submit: {
    margin: theme.spacing(3, 0, 2),
  },
}));

export default function Register() {
  const classes = useStyles();

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <Avatar className={classes.avatar}>
        </Avatar>
        <Typography component="h1" variant="h5">
          Sign up
        </Typography>
        <form className={classes.form} noValidate>
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6}>
              <TextField
                autoComplete="fname"
                name="firstName"
                variant="outlined"
                required
                fullWidth
                id="firstName"
                label="First Name"
                autoFocus
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="lastName"
                label="Last Name"
                name="lastName"
                autoComplete="lname"
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="email"
                label="Email Address"
                name="email"
                autoComplete="email"
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                name="password"
                label="Password"
                type="password"
                id="password"
                autoComplete="current-password"
              />
            </Grid>
            <Grid item xs={12}>
              <FormControlLabel
                control={<Checkbox value="allowExtraEmails" color="primary" />}
                label="I want to receive inspiration, marketing promotions and updates via email."
              />
            </Grid>
          </Grid>
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
          >
            Sign Up
          </Button>
          <Grid container justify="flex-end">
            <Grid item>
              <Link href="/login" variant="body2">
                Already have an account? Sign in
              </Link>
            </Grid>
          </Grid>
        </form>
      </div>
      <Box mt={5}>
        <Copyright />
      </Box>
    </Container>
  );
}
</code>```

答: Try to look at how react handles forms. https://reactjs.org/docs/forms.html</p>

Body:
I want to use a sign in template, but I'm not sure how to send data from this template to my Flask API. I read that states are only in components. Is that true? I tried calling the Register function inside render from another file that has a component, but I got an error about invalid hooks.

Flask API

from flask import Blueprint, jsonify
from flask import request, make_response
import sqlite3
from sqlite3 import Error
import os.path
import json

main = Blueprint('main', __name__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "database.db")

def connection():
    try:
        conn = sqlite3.connect(db_path)
    except Error as e:
        print(e)
    return conn

@main.route('/add_review', methods=['POST'])
def add_review():
    conn = connection()
    cur = conn.cursor()

    req = request.get_json()
    busID = req.get('busID')
    userID = req.get('userID')
    review = req.get('review')
    rating = req.get('rating')

    sql = "INSERT INTO Review (businessID, userID, review, rating) VALUES (?, ?, ?, ?)"
    data = (busID, userID, review, rating)
    cur.execute(sql, data)

    conn.commit()
    cur.close()

    return 'Done', 201

@main.route('/reviews')
def reviews():
    conn = connection()
    cur = conn.cursor()
    name = "Halal Guys"
    cur.execute("SELECT * FROM Review where businessID = (SELECT id FROM Business where name = \'{}\')".format(name))
    reviews = cur.fetchall()

    reviews_dict = []
    for review in reviews:
        content = {"id": review[0], "busID": review[1], "userID": review[2],
                    "review": review[3], "rating": review[4]}
        reviews_dict.append(content)

    return json.dumps(reviews_dict)

@main.route('/createUser', methods=['POST', 'OPTIONS'])
def createUser():
    # handle option request
    if request.method == "OPTIONS":
        response = make_response()
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers[
            "Access-Control-Allow-Headers"
        ] = "Origin, Accept, Content-Type"
        response.headers["Access-Control-Allow-Methods"] = "POST,OPTIONS"
        response.headers["Access-Control-Allow-Credentials"] = "true"
        return response

    if request.method == "POST":
        # do your SQL stuff
        conn = connection()
        cur = conn.cursor()

        req = request.get_json()
        first = req.get("FirstName")
        last = req.get("LastName")
        email = req.get("Email")
        pw = req.get("Password")

        sql = (
            "INSERT INTO User (first, last, emailAddress, password) VALUES (?, ?, ?, ?)"
        )
        data = (first, last, email, pw)
        cur.execute(sql, data)

        conn.commit()
        cur.close()

        # make response
        response = make_response("{}")  # return empty JSON response
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers[
            "Content-Type"
        ] = "application/json"  # set response type to JSON
        return response

    return "", 405

Sign in template

import React from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Link from '@material-ui/core/Link';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';

function Copyright() {
  return (
    <Typography variant="body2" color="textSecondary" align="center">
      {'Copyright © '}
      <Link color="inherit" href="https://material-ui.com/">
        Your Website
      </Link>{' '}
      {new Date().getFullYear()}
      {'.'}
    </Typography>
  );
}

const useStyles = makeStyles(theme => ({
  paper: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.secondary.main,
  },
  form: {
    width: '100%', // Fix IE 11 issue.
    marginTop: theme.spacing(3),
  },
  submit: {
    margin: theme.spacing(3, 0, 2),
  },
}));

export default function Register() {
  const classes = useStyles();

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />

        <Avatar className={classes.avatar}>
        </Avatar>
        <Typography component="h1" variant="h5">
          Sign up
        </Typography>
        <form className={classes.form} noValidate>
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6}>
              <TextField
                autoComplete="fname"
                name="firstName"
                variant="outlined"
                required
                fullWidth
                id="firstName"
                label="First Name"
                autoFocus
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="lastName"
                label="Last Name"
                name="lastName"
                autoComplete="lname"
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="email"
                label="Email Address"
                name="email"
                autoComplete="email"
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                name="password"
                label="Password"
                type="password"
                id="password"
                autoComplete="current-password"
              />
            </Grid>
            <Grid item xs={12}>
              <FormControlLabel
                control={<Checkbox value="allowExtraEmails" color="primary" />}
                label="I want to receive inspiration, marketing promotions and updates via email."
              />
            </Grid>
          </Grid>
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
          >
            Sign Up
          </Button>
          <Grid container justify="flex-end">
            <Grid item>
              <Link href="/login" variant="body2">
                Already have an account? Sign in
              </Link>
            </Grid>
          </Grid>
        </form>

      <Box mt={5}>
        <Copyright />
      </Box>
    </Container>
  );
}


问:
boostrap 3.3.6 navbar doesnt work
cant find the reason why when i cant use the button when i make my web browser smaller?

i tried looking in the internet but u cant find a solution

```<code><nav class="navbar navbar-inverse navbar-fixed-top">
            <div class="container-fluid">
                <div class="navbar-header">
                    <button class="navbar-toggler  navbar-toggler-right" type="button" aria-controls="#ex1" aria-expanded="false" aria-label="Toggle navigation" data-toggle="collapse" data-target="ex1">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#">לוגו</a>
                </div>

                <div class="collapse navbar-collapse" id="ex1">
                    <ul class="nav navbar-nav navbar-right">
                        <li class="active"><a class="nav-link" href="#">דף הבית</a></li>
                        <li class="nav-item"><a class="nav-link" href="#">Link</a></li>
                        <li class="nav-item"><a class="nav-link" href="#">Link</a></li>
                        <li class="nav-item"><a class="nav-link" href="#">Link</a></li>
                        <li class="nav-item"><a class="nav-link" href="#">Link</a></li>
                    </ul>
                </div>
            </div>
        </nav>
</code>```

答:
Make sure you added this three scripts in exact this order:

```<code><script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</code>```

It is jQuery, than popper.js, than the bootstrap.min.js
It is important that you load jQuery at first and bootstrap.min.js at last, while popper.js is in between

Title: boostrap 3.3.6 navbar doesnt work

Body:
cant find the reason why when i cant use the button when i make my web browser smaller?

i tried looking in the internet but u cant find a solution

                    <button class="navbar-toggler  navbar-toggler-right" type="button" aria-controls="#ex1" aria-expanded="false" aria-label="Toggle navigation" data-toggle="collapse" data-target="ex1">

                    </button>
                    לוגו

דף הבית

Link

Link

Link

Link

Body:
Make sure you added this three scripts in exact this order:

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

It is jQuery, than popper.js, than the bootstrap.min.js
It is important that you load jQuery at first and bootstrap.min.js at last, while popper.js is in between


问:
Updating pandas dataframe with new column
I want to create a new column with all the distinct values across the rows. Each value in a row is a string(not list).

This is how dataframe looks like:

```<code>+-----------------------------+-------------------------+---------------------------------------------+
|         first               |            second       |           third                             |
+-----------------------------+-------------------------+---------------------------------------------+
|['able', 'shovel', 'door']   |['shovel raised']        |['shovel raised', 'raised', 'door', 'shovel']|
|['grade control']            |['grade']                |['grade']                                    |
|['light telling', 'love']    |['would love', 'closed'] |['closed', 'light']                          |
+-----------------------------+-------------------------+---------------------------------------------+
</code>```

This is how the dataframe should look like after creating a new column with distinct values.

df = pd.DataFrame({'first': "['able', 'shovel', 'door']" , 'second': "['shovel raised']", 'third': "['shovel raised', 'raised', 'door', 'shovel']", "Distinct_set": "['able', 'shovel', 'door', 'shovel raised', 'raised']" }, index = [0])```

How can I do it?

答:
You can try out below snippet</p>

```<code>import json
def get_list_from_str(s):
    return json.loads(s.replace("'", '"'))

def flatten_list_rows(row):
    return (set(
        get_list_from_str(row['first']) +
        get_list_from_str(row['second']) +
        get_list_from_str(row['third'])
    ))

df['Distinct_set'] = df.apply(flatten_list_rows, axis=1)
</code>```

Body:
I want to create a new column with all the distinct values across the rows. Each value in a row is a string(not list).

This is how dataframe looks like:

+-----------------------------+-------------------------+---------------------------------------------+
|         first               |            second       |           third                             |
+-----------------------------+-------------------------+---------------------------------------------+
|['able', 'shovel', 'door']   |['shovel raised']        |['shovel raised', 'raised', 'door', 'shovel']|
|['grade control']            |['grade']                |['grade']                                    |
|['light telling', 'love']    |['would love', 'closed'] |['closed', 'light']                          |
+-----------------------------+-------------------------+---------------------------------------------+

This is how the dataframe should look like after creating a new column with distinct values.

df = pd.DataFrame({'first': "['able', 'shovel', 'door']" , 'second': "['shovel raised']", 'third': "['shovel raised', 'raised', 'door', 'shovel']", "Distinct_set": "['able', 'shovel', 'door', 'shovel raised', 'raised']" }, index = [0])

How can I do it?

Body:
You can try out below snippet

import json
def get_list_from_str(s):
    return json.loads(s.replace("'", '"'))

def flatten_list_rows(row):
    return (set(
        get_list_from_str(row['first']) +
        get_list_from_str(row['second']) +
        get_list_from_str(row['third'])
    ))

df['Distinct_set'] = df.apply(flatten_list_rows, axis=1)


问:
How to make two divs inline react

// Get a hook function
const {useState, useEffect} = React;

const Slider = props => {
const { innerWidth: width, innerHeight: height } = window;
  const urls = [
    "https://www.imb.com.au/templates/client/images/header/IMB-logo.svg",
    "https://www.mkmcapital.com.au/wp-content/uploads/2016/08/MKM_logo-2.png",
    "https://www.pnbank.com.au/Static/Theme/assets/images/pnbank-logo-narrow--7465fe2f1d3e10cf7acfc008991cebef.svg",
    "https://www.provident.com.au/images/logo-blue.png",
    "https://www.adelaidebank.com.au/globalassets/globalresources/brand-logos/abl-logo.png",
    "https://www.amp.com.au/content/dam/amp-au/data/icons/amp-logo-reversed.svg",
    "https://www.anz.com.au//content/dam/anzconz/images/common/promopages/logo-promo-anz-small.png",
    "https://www.bt.com.au//content/dam/public/btfg-bt/images/logo/bt_financial_group_logo_mob-2x1.png",
    "https://www.commbank.com.au/content/dam/commbank/commBank-logo.svg",
    "https://www.collinshomeloans.com.au/hs-fs/hubfs/collins-logo-shedow.png?width=230&name=collins-logo-shedow.png",
    "https://depositpower.com.au/wp-content/uploads/2019/01/DepositPower_stacked_white.png",
    "https://www.latrobefinancial.com.au//Images/Logos/Logo-LTF_v2.jpg",
    "https://d2ttwt9gu7swv4.cloudfront.net/assets/images/logo.svg",
    "https://www.mebank.com.au/MEBank/Assets/Images/me-logo.svg",
    "https://www.nab.com.au//etc/designs/nabrwd/clientlibs/images/logo.png",
    "https://www.pepper.com.au//siteassets/logos/pepper-money-logo.png",
    "https://www.suncorp.com.au//content/dam/suncorp/corporate/images/logos/Suncorp_New_Logo_2x.png",
    "https://www.equifax.com.au/sites/all/themes/vedacorporate/logo.png"
  ];
  let totalWidth = urls.length * 120;
  let [ left, setLeft ] = useState(0);
  let [ secondLeft, setSecondLeft ] = useState(-(width+300));

  useEffect(() => {
    const interval = setInterval(() => {
      setLeft(left => left + 1);
      setSecondLeft(secondLeft => secondLeft + 1);
      //console.log('left ' + left + ' sleft ' + secondLeft);
      if (left == 0) {
        setSecondLeft(-(totalWidth))
      }
      if(secondLeft == 0){
          setLeft(-(totalWidth))
      }
    }, 5);
    return () => {
      clearInterval(interval);
    };
  }, [left, secondLeft]);

  return (

        {urls.map((u, i) => {
          return (

          );
        })}

        {urls.map((u, i) => {
          return (

          );
        })}

  );
};

// Render it
ReactDOM.render(
  <Slider/>,
  document.getElementById("react")
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div></code>```

Its like this one below another

But I want it to be in one line. How can I do that

答:
Do it with styles, if you want to do it through js... well give it styles with js, but its better doing it with css</p>

```<code>display: flex;
flex-wrap: nowrap;
</code>```

Title: How to make two divs inline react

Body:
// Get a hook function
const {useState, useEffect} = React;

const Slider = props => {
const { innerWidth: width, innerHeight: height } = window;
  const urls = [
    "https://www.imb.com.au/templates/client/images/header/IMB-logo.svg",
    "https://www.mkmcapital.com.au/wp-content/uploads/2016/08/MKM_logo-2.png",
    "https://www.pnbank.com.au/Static/Theme/assets/images/pnbank-logo-narrow--7465fe2f1d3e10cf7acfc008991cebef.svg",
    "https://www.provident.com.au/images/logo-blue.png",
    "https://www.adelaidebank.com.au/globalassets/globalresources/brand-logos/abl-logo.png",
    "https://www.amp.com.au/content/dam/amp-au/data/icons/amp-logo-reversed.svg",
    "https://www.anz.com.au//content/dam/anzconz/images/common/promopages/logo-promo-anz-small.png",
    "https://www.bt.com.au//content/dam/public/btfg-bt/images/logo/bt_financial_group_logo_mob-2x1.png",
    "https://www.commbank.com.au/content/dam/commbank/commBank-logo.svg",
    "https://www.collinshomeloans.com.au/hs-fs/hubfs/collins-logo-shedow.png?width=230&name=collins-logo-shedow.png",
    "https://depositpower.com.au/wp-content/uploads/2019/01/DepositPower_stacked_white.png",
    "https://www.latrobefinancial.com.au//Images/Logos/Logo-LTF_v2.jpg",
    "https://d2ttwt9gu7swv4.cloudfront.net/assets/images/logo.svg",
    "https://www.mebank.com.au/MEBank/Assets/Images/me-logo.svg",
    "https://www.nab.com.au//etc/designs/nabrwd/clientlibs/images/logo.png",
    "https://www.pepper.com.au//siteassets/logos/pepper-money-logo.png",
    "https://www.suncorp.com.au//content/dam/suncorp/corporate/images/logos/Suncorp_New_Logo_2x.png",
    "https://www.equifax.com.au/sites/all/themes/vedacorporate/logo.png"
  ];
  let totalWidth = urls.length * 120;
  let [ left, setLeft ] = useState(0);
  let [ secondLeft, setSecondLeft ] = useState(-(width+300));

  useEffect(() => {
    const interval = setInterval(() => {
      setLeft(left => left + 1);
      setSecondLeft(secondLeft => secondLeft + 1);
      //console.log('left ' + left + ' sleft ' + secondLeft);
      if (left == 0) {
        setSecondLeft(-(totalWidth))
      }
      if(secondLeft == 0){
          setLeft(-(totalWidth))
      }
    }, 5);
    return () => {
      clearInterval(interval);
    };
  }, [left, secondLeft]);

  return (

        {urls.map((u, i) => {
          return (

          );
        })}

        {urls.map((u, i) => {
          return (

          );
        })}

  );
};

// Render it
ReactDOM.render(
  <Slider/>,
  document.getElementById("react")
);

Its like this one below another

But I want it to be in one line. How can I do that

Body:
Do it with styles, if you want to do it through js... well give it styles with js, but its better doing it with css

display: flex;
flex-wrap: nowrap;


问:
How to load properties on util class
I defined my properties file location on XML, and register my custom util class as bean. (with factory-method is “getInstance”)

What I want is I want to load my properties value before my Custom util construction us called.

```<code>class AUtil
{
   private static AUtil instance;

   @Value("something")
   private m;

   private AUtil() {}

   public static AUtil() {
       if (instance == null) instance = new AUtil();

       return instance;
   }
}
</code>```

答:
I think you should use @PostConstruct as:
when the constructor is called, the bean is not yet initialized - i.e. no dependencies are injected. In the @PostConstruct method the bean is fully initialized and you can use the dependencies. </p>

Title: How to load properties on util class

Body:
I defined my properties file location on XML, and register my custom util class as bean. (with factory-method is “getInstance”)

What I want is I want to load my properties value before my Custom util construction us called.

class AUtil
{
   private static AUtil instance;

   @Value("something")
   private m;

   private AUtil() {}

   public static AUtil() {
       if (instance == null) instance = new AUtil();

       return instance;
   }
}


问:
API design Python
I have found a very nice talk by Joshua Bloch:

http://www.youtube.com/watch?v=aAb7hSCtvGw

http://lcsd05.cs.tamu.edu/slides/keynote.pdf

While it is fairly general, some comments are only valid to statically typed languages. I am looking for something equivalent for Python.
(This talk looks promising but has not been given yet)

答:
Perhaps one of these (or both).

PyCon 2011: API Design: Lessons Learned by Hettinger

PyCon 2011: API Design anti-patterns by Alex Martelli

Title: API design Python


问:
User input to call function always ends with process 0
I am trying to make a program which shows an exp or log function depending on what the user wants to see. So if the user wants to have exp fun, then he writes 1. If log fun, then 2.

The problem is that after inputting the program always ends with "Process finished with exit code 0" and it shows no functions.

What can be the solution?

Code:

```<code>import matplotlib.pyplot as plt
import numpy as np

class the_process(object):
 def logfun(self):
    a = 2
    q = 0
    x = np.linspace(-2, 4, 100)
    y = np.log(a ** (np.add(x, q)))

    plt.figure()
    plt.plot(x, y)
    plt.ylabel('$\log(x)$')
    plt.grid(True)
    plt.show()

def expfun(self):
    a = 2
    q = 0
    x = np.linspace(-2, 4, 100)
    y = np.add(np.power(a, x), q)

    plt.figure()
    plt.plot(x, y)
    plt.ylabel('$\exp(x)$')
    plt.grid(True)
    plt.show()

def __init__(self):
    self.a = input(
        "Which function do you want to use? \n\n 1) The first one. \n\n 2) The second one. \n\n Please enter the corresponding number and hit enter >>>>> ")

    if self.a == 1:
        self.expfun()
    elif self.a == 2:
        self.logfun()

a = the_process();
</code>```

答:
Indentation in your example is wrong. expfun() and __init__() are not indented. Also, input() returns a string, so you should cast it to int to compare it in your if

```<code>import matplotlib.pyplot as plt
import numpy as np

class the_process(object):
    def logfun(self):
        a = 2
        q = 0
        x = np.linspace(-2, 4, 100)
        y = np.log(a ** (np.add(x, q)))

        plt.figure()
        plt.plot(x, y)
        plt.ylabel('$\log(x)$')
        plt.grid(True)
        plt.show()

    def expfun(self):
        a = 2
        q = 0
        x = np.linspace(-2, 4, 100)
        y = np.add(np.power(a, x), q)

        plt.figure()
        plt.plot(x, y)
        plt.ylabel('$\exp(x)$')
        plt.grid(True)
        plt.show()

    def __init__(self):
        self.a = int(input(
            "Which function do you want to use? \n\n 1) The first one. \n\n 2) The second one. \n\n Please enter the corresponding number and hit enter >>>>> "))

        if self.a == 1:
            self.expfun()
        elif self.a == 2:
            self.logfun()

a = the_process()
</code>```

Finally, in my opinion, your problem shouldn't be structured as a class, so you could consider this one instead:

```<code>import matplotlib.pyplot as plt
import numpy as np

class TheProcess(object):
    def log_fun(self):
        a = 2
        q = 0
        x = np.linspace(-2, 4, 100)
        y = np.log(a ** (np.add(x, q)))

        plt.figure()
        plt.plot(x, y)
        plt.ylabel("$\log(x)$")
        plt.grid(True)
        plt.show()

    def exp_fun(self):
        a = 2
        q = 0
        x = np.linspace(-2, 4, 100)
        y = np.add(np.power(a, x), q)

        plt.figure()
        plt.plot(x, y)
        plt.ylabel("$\exp(x)$")
        plt.grid(True)
        plt.show()

chosen_option = int(
    input(
        "Which function do you want to use? \n\n 1) The first one. \n\n 2) The second one. \n\n Please enter the corresponding number and hit enter >>>>> "
    )
)
my_process = TheProcess()
if chosen_option == 1:
    my_process.exp_fun()
elif chosen_option == 2:
    my_process.log_fun()
else:
    print("Exiting...")
</code>```

Body:
I am trying to make a program which shows an exp or log function depending on what the user wants to see. So if the user wants to have exp fun, then he writes 1. If log fun, then 2.

The problem is that after inputting the program always ends with "Process finished with exit code 0" and it shows no functions.

What can be the solution?

Code:

import matplotlib.pyplot as plt
import numpy as np

class the_process(object):
 def logfun(self):
    a = 2
    q = 0
    x = np.linspace(-2, 4, 100)
    y = np.log(a ** (np.add(x, q)))

    plt.figure()
    plt.plot(x, y)
    plt.ylabel('$\log(x)$')
    plt.grid(True)
    plt.show()

def expfun(self):
    a = 2
    q = 0
    x = np.linspace(-2, 4, 100)
    y = np.add(np.power(a, x), q)

    plt.figure()
    plt.plot(x, y)
    plt.ylabel('$\exp(x)$')
    plt.grid(True)
    plt.show()

def __init__(self):
    self.a = input(
        "Which function do you want to use? \n\n 1) The first one. \n\n 2) The second one. \n\n Please enter the corresponding number and hit enter >>>>> ")

    if self.a == 1:
        self.expfun()
    elif self.a == 2:
        self.logfun()

a = the_process();

Body:
Indentation in your example is wrong. expfun() and __init__() are not indented. Also, input() returns a string, so you should cast it to int to compare it in your if

import matplotlib.pyplot as plt
import numpy as np

class the_process(object):
    def logfun(self):
        a = 2
        q = 0
        x = np.linspace(-2, 4, 100)
        y = np.log(a ** (np.add(x, q)))

        plt.figure()
        plt.plot(x, y)
        plt.ylabel('$\log(x)$')
        plt.grid(True)
        plt.show()

    def expfun(self):
        a = 2
        q = 0
        x = np.linspace(-2, 4, 100)
        y = np.add(np.power(a, x), q)

        plt.figure()
        plt.plot(x, y)
        plt.ylabel('$\exp(x)$')
        plt.grid(True)
        plt.show()

    def __init__(self):
        self.a = int(input(
            "Which function do you want to use? \n\n 1) The first one. \n\n 2) The second one. \n\n Please enter the corresponding number and hit enter >>>>> "))

        if self.a == 1:
            self.expfun()
        elif self.a == 2:
            self.logfun()

a = the_process()

Finally, in my opinion, your problem shouldn't be structured as a class, so you could consider this one instead:

import matplotlib.pyplot as plt
import numpy as np

class TheProcess(object):
    def log_fun(self):
        a = 2
        q = 0
        x = np.linspace(-2, 4, 100)
        y = np.log(a ** (np.add(x, q)))

        plt.figure()
        plt.plot(x, y)
        plt.ylabel("$\log(x)$")
        plt.grid(True)
        plt.show()

    def exp_fun(self):
        a = 2
        q = 0
        x = np.linspace(-2, 4, 100)
        y = np.add(np.power(a, x), q)

        plt.figure()
        plt.plot(x, y)
        plt.ylabel("$\exp(x)$")
        plt.grid(True)
        plt.show()

chosen_option = int(
    input(
        "Which function do you want to use? \n\n 1) The first one. \n\n 2) The second one. \n\n Please enter the corresponding number and hit enter >>>>> "
    )
)
my_process = TheProcess()
if chosen_option == 1:
    my_process.exp_fun()
elif chosen_option == 2:
    my_process.log_fun()
else:
    print("Exiting...")


问:
Ms Access - Delete all tables, queries, forms, reports and modules
I want to make a self destroyed button in my database, for security reasons. I need to modified my code so it can loop in all my tables, queries, forms, reports, module and delete them. If an error occurred, to move to the next one.

Now I am using the following code, which is an example:

```<code> On error Resume Next
 DoCmd.DeleteObject acTable, "tblExtra"
 DoCmd.DeleteObject acTable, "tblFinances"
 DoCmd.DeleteObject acTable, "tblHealth"
 ....
</code>```

As you will see, I am using DoCmd.DeleteObject for each item I want to delete.

Thank you.

答:
As for Access 2016, Graham's answer randomly fails (automation error) while deleting objects.

It is safer to delete objects by index, from last to first.
The checkonly parameter is just for testing purposes, in case you erase any important object.

I've tested both solutions in Access 2016 MSO (16.0.8431.2110) 32 bits.

```<code>Public Sub deleteObjects(Optional ByVal CheckOnly As Boolean = True)

    Dim obj     As AccessObject
    Dim i       As Long

    With CurrentProject
        For i = .AllReports.count - 1 To 0 Step -1
            Set obj = .AllReports(i)
            Debug.Print "Deleting " & obj.Name
            If Not CheckOnly Then
                DoCmd.Close ObjectType:=acReport, ObjectName:=obj.Name, Save:=acSaveNo
                DoCmd.DeleteObject acReport, obj.Name
            End If
        Next

        For i = .AllForms.count - 1 To 0 Step -1
            Set obj = .AllForms(i)
            If obj.Name <> "myImportantForm" Then
                Debug.Print "Deleting " & obj.Name
                If Not CheckOnly Then
                    DoCmd.Close ObjectType:=acForm, ObjectName:=obj.Name, Save:=acSaveNo
                    DoCmd.DeleteObject acForm, obj.Name
                End If
            End If
        Next

        For i = .AllModules.count - 1 To 0 Step -1
            Set obj = .AllModules(i)
            If obj.Name <> "myImportantModule" Then
                Debug.Print "Deleting " & obj.Name
                If Not CheckOnly Then
                    DoCmd.DeleteObject acModule, obj.Name
                End If
            End If
        Next
    End With

    With CurrentData
        For i = .AllQueries.count - 1 To 0 Step -1
            Set obj = .AllQueries(i)
            Debug.Print "Deleting " & obj.Name
            If Not CheckOnly Then
                DoCmd.Close ObjectType:=acQuery, ObjectName:=obj.Name, Save:=acSaveNo
                DoCmd.DeleteObject acQuery, obj.Name
            End If
        Next

        For i = .AllTables.count - 1 To 0 Step -1
            Set obj = .AllTables(i)
            If Not obj.Name Like "MSys*" Then
                Debug.Print "Deleting " & obj.Name
                If Not CheckOnly Then
                    DoCmd.Close ObjectType:=acTable, ObjectName:=obj.Name, Save:=acSaveNo
                    DoCmd.DeleteObject acTable, obj.Name
                End If
            End If
        Next
    End With

End Sub
</code>```

Body:
I want to make a self destroyed button in my database, for security reasons. I need to modified my code so it can loop in all my tables, queries, forms, reports, module and delete them. If an error occurred, to move to the next one.

Now I am using the following code, which is an example:

 On error Resume Next
 DoCmd.DeleteObject acTable, "tblExtra"
 DoCmd.DeleteObject acTable, "tblFinances"
 DoCmd.DeleteObject acTable, "tblHealth"
 ....

As you will see, I am using DoCmd.DeleteObject for each item I want to delete.

Thank you.

Body:
As for Access 2016, Graham's answer randomly fails (automation error) while deleting objects.

It is safer to delete objects by index, from last to first.
The checkonly parameter is just for testing purposes, in case you erase any important object.

I've tested both solutions in Access 2016 MSO (16.0.8431.2110) 32 bits.

Public Sub deleteObjects(Optional ByVal CheckOnly As Boolean = True)

    Dim obj     As AccessObject
    Dim i       As Long

    With CurrentProject
        For i = .AllReports.count - 1 To 0 Step -1
            Set obj = .AllReports(i)
            Debug.Print "Deleting " & obj.Name
            If Not CheckOnly Then
                DoCmd.Close ObjectType:=acReport, ObjectName:=obj.Name, Save:=acSaveNo
                DoCmd.DeleteObject acReport, obj.Name
            End If
        Next

        For i = .AllForms.count - 1 To 0 Step -1
            Set obj = .AllForms(i)
            If obj.Name <> "myImportantForm" Then
                Debug.Print "Deleting " & obj.Name
                If Not CheckOnly Then
                    DoCmd.Close ObjectType:=acForm, ObjectName:=obj.Name, Save:=acSaveNo
                    DoCmd.DeleteObject acForm, obj.Name
                End If
            End If
        Next

        For i = .AllModules.count - 1 To 0 Step -1
            Set obj = .AllModules(i)
            If obj.Name <> "myImportantModule" Then
                Debug.Print "Deleting " & obj.Name
                If Not CheckOnly Then
                    DoCmd.DeleteObject acModule, obj.Name
                End If
            End If
        Next
    End With

    With CurrentData
        For i = .AllQueries.count - 1 To 0 Step -1
            Set obj = .AllQueries(i)
            Debug.Print "Deleting " & obj.Name
            If Not CheckOnly Then
                DoCmd.Close ObjectType:=acQuery, ObjectName:=obj.Name, Save:=acSaveNo
                DoCmd.DeleteObject acQuery, obj.Name
            End If
        Next

        For i = .AllTables.count - 1 To 0 Step -1
            Set obj = .AllTables(i)
            If Not obj.Name Like "MSys*" Then
                Debug.Print "Deleting " & obj.Name
                If Not CheckOnly Then
                    DoCmd.Close ObjectType:=acTable, ObjectName:=obj.Name, Save:=acSaveNo
                    DoCmd.DeleteObject acTable, obj.Name
                End If
            End If
        Next
    End With

End Sub


问:
Detect if iOS app hacked
My friend got a jailbroken iPad. When he installed Business Model Generation App from Installous and tried to use it, the application showed a UIAlertView with the following message:

Does anybody know how to do that?

I have 2 ideas:

If there is some set flag when you download app from the App Store, then you can use this flag: if flag = NO, you show the UIAlertView.

Something with a server (but in this case, you should know all device IDs and who installed your application from the App Store).

Am I right? How can I implement this feature?

答:
I'm using this code on swift:</p>

```<code>if Bundle.main.infoDictionary?["SignerIdentity"] != nil
     || !FileManager.default.fileExists(atPath: ("\(Bundle.main.bundlePath)/SC_Info"))
     || !FileManager.default.fileExists(atPath: ("\(Bundle.main.bundlePath)/iTunesMetadata.plist")){
        // Jailbroken
}
</code>```

Title: Detect if iOS app hacked

Body:
I'm using this code on swift:

if Bundle.main.infoDictionary?["SignerIdentity"] != nil
     || !FileManager.default.fileExists(atPath: ("\(Bundle.main.bundlePath)/SC_Info"))
     || !FileManager.default.fileExists(atPath: ("\(Bundle.main.bundlePath)/iTunesMetadata.plist")){
        // Jailbroken
}


问:
Implementation of Factory design pattern in Swift 3.0
I would like to implement the factory design pattern in Swift 3.0.

The basic solution that I am thinking of is:

Define a protocol that define as object creation method

Implement the protocol within the Object

Is this a sound approach?

Or are there alternative design patterns in Swift?

答:
You can try to use this implementation as a reference.
https://redflowerinc.com/implementing-factory-design-pattern-in-swift/

import UIKit
import PlaygroundSupport

enum Maps : Int {
    case google = 1
    case apple
}

protocol Display {
    func showMap()
}

class Map {
    let type : Int = 0
    func showMap(type : Maps) -> Display {
        switch type {
        case Maps.apple :
            return AppleMap()
        case Maps.google :
            fallthrough
        default:
            return GoogleMap()
        }
    }
}

class AppleMap : Display {
    func showMap() {
        print("showing apple map")
    }
}

class GoogleMap : Display {
    func showMap() {
        print("showing google map")
    }
}

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let label = UILabel()
        label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
        label.text = "Hello World!"
        label.textColor = .black

        view.addSubview(label)
        self.view = view

        let map = Map()
        map.showMap(type: Maps.google)
        map.showMap(type: Maps.apple)
    }
}
```


问:
WPF Adorner Overlay Problem
I am trying to achieve functionality similar to that of a Popup, without using a Popup, but instead adorning my ContentControl with a basic adorner.  Basically, I want the ContentControl to have an "overlay" effect, whereby it is the topmost object, above all other elements - similiar to that of the Popup control.

Here is the problem that I am running into, and I am hoping that someone can point out where I am going wrong:

I have a stand grid with two row definitions.  The first row contains a UI element - for example, a rectangle.  The second row contains a custom control that I have developed to emulate the functionality of a "drawer" sliding out.  Basically, when I click on button, I am going to animate a TranslateTransform to "slide" my ContentControl "up".  This works fine - except that it gets cropped underneath the rectange in the first row of the grid.  If I remove the row definitions in the grid, then when the desired behavior is achieved - the ContentControl is moved "up" and partially "on top" of the rectangle.  The rectangle is merely a place holder for what I am trying to achieve.  I basically want to have a drawer type control that can slide out and be on top of all other controls.

I am somewhat new to using the Adorner class, so, I am hoping that someone can please point out where I am going wrong.

Thanks.

Chris

答: Change the parent of the adorner to the full grid, and not just your control.  If you put a control in a grid row, and set the adorner to adorn the control, it will usually be clipped to that row because the control is.</p>

Title: WPF Adorner Overlay Problem


问:
Flutter packages pub global run webdev serve Error
I have followed this tutorial step by step https://www.youtube.com/watch?v=K_kBzJN8pAY and I am 100% sure that I did everything correctly but unfortunately I am getting this error:

PS C:\MyApps\firstapp> flutter packages pub global run webdev serve
  webdev could not run for this project. You must have a dependency on
  build_runner in pubspec.yaml.

pubspec.yaml dev_dependencies:   build_runner: >=1.6.2 <2.0.0 You must have a dependency on build_web_compilers in pubspec.yaml.

pubspec.yaml dev_dependencies:   build_web_compilers: >=1.2.0 <3.0.0 You have a dependency on cupertino_icons which is not supported for

flutter_web tech preview. See https://flutter.dev/web for more
  details. You have a dependency on flutter which is not supported for
  flutter_web tech preview. See https://flutter.dev/web for more
  details. You have a dependency on flutter_test which is not
  supported for flutter_web tech preview. See https://flutter.dev/web
  for more details. pub finished with exit code 78

答:
If you follow that video exactly and did not change anything then you are on stable channel in flutter.

If You want to run flutter web then you have to move to beta channel.

Flutter web is under development, so it is only available on that channel.

check out here: https://flutter.dev/web

You can check channel by Following command.

flutter channel

you can see Following output.

```<code>Flutter channels:
* master
  dev
  beta
  stable
</code>```

In Your case may be star is in front of stable.

Run Following command to move to beta channel.

Flutter channel beta

Now run following command to upgrade flutter.

flutter upgrade

Now You are good to go.

Body:
If you follow that video exactly and did not change anything then you are on stable channel in flutter.

If You want to run flutter web then you have to move to beta channel.

Flutter web is under development, so it is only available on that channel.

check out here: https://flutter.dev/web

You can check channel by Following command.

flutter channel

you can see Following output.

Flutter channels:
* master
  dev
  beta
  stable

In Your case may be star is in front of stable.

Run Following command to move to beta channel.

Flutter channel beta

Now run following command to upgrade flutter.

flutter upgrade

Now You are good to go.


问:
Laravel session bug?
Why is that even though I forget a session already it stills prints its value when I press back button ?
Is this kind of a bug in laravel or am i doing something wrong with my code ?

here is how i forget the session

```<code>session()->forget('user_role');
session()->forget('user_id');
</code>```

but even if i do that it still prints the value in the console when I press the back button.
I've tried other methods already , such as the pull method and reassigning new values but the problem still exists.

答:
The session()->forget('user_role') is performing well. However, You are still able to view/print because browser has cached that page and instead of making a network call, request just heats the cache.

To identify and disable cached for a while, Open up the dev tools and disable cache while dev tool is open and refresh the page. After that, you'll no longer be able to see that data stored in the session key. For your reference, The page you are seeing is browser cached one.
This is the temporary solution if you want to check the value being washed or not. However, if you don't want your user to have this behavior, You can try given solutions.

For the browser-based cache control, you should try setting the Cache-Control, Pragma and Expires header with your page response as given,

$contents = View::make('viewname');
return response($contents)-> withHeaders([
    'Cache-Control' => 'no-cache, no-store, must-revalidate',
    'Pragma' => 'no-cache',
    'Expires' => 0
]);
```

this will allow you to control the page being cached in browser. Setting the Expires to 0 means the page never gonna be cached. You can refer the Official MDN Docs here.

You should also try disabling the Laravel blade view cache if the problem still persists or other solution doesn't give satisfactory outcome.

Title: Laravel session bug?

Body:
Why is that even though I forget a session already it stills prints its value when I press back button ?
Is this kind of a bug in laravel or am i doing something wrong with my code ?

here is how i forget the session

session()->forget('user_role');
session()->forget('user_id');

but even if i do that it still prints the value in the console when I press the back button.
I've tried other methods already , such as the pull method and reassigning new values but the problem still exists.

Body:
The session()->forget('user_role') is performing well. However, You are still able to view/print because browser has cached that page and instead of making a network call, request just heats the cache.

To identify and disable cached for a while, Open up the dev tools and disable cache while dev tool is open and refresh the page. After that, you'll no longer be able to see that data stored in the session key. For your reference, The page you are seeing is browser cached one.
This is the temporary solution if you want to check the value being washed or not. However, if you don't want your user to have this behavior, You can try given solutions.

For the browser-based cache control, you should try setting the Cache-Control, Pragma and Expires header with your page response as given,

$contents = View::make('viewname');
return response($contents)-> withHeaders([
    'Cache-Control' => 'no-cache, no-store, must-revalidate',
    'Pragma' => 'no-cache',
    'Expires' => 0
]);

this will allow you to control the page being cached in browser. Setting the Expires to 0 means the page never gonna be cached. You can refer the Official MDN Docs here.

You should also try disabling the Laravel blade view cache if the problem still persists or other solution doesn't give satisfactory outcome.


问:
binding buffers multiple times in openGL
While learning opengl, one bit of confusion is whether it is necessary to bind buffers like VAO
 or texture IDs multiple times without unbinding them?

With reference to the above link and the full source code , I have come across 2 scenerios a bit distinct from each other.

First, the author creates a VAO(outside the maindraw loop) and binds the VAO using the  glBindVertexArray(VAO) then he doesn't unbind it using glBindVertexArray(0); , but he binds it again in the maindraw loop. My confusion, Is this really necessary? Isn't the currently bound VAO already ... bound? Why bind it when it is already the active VAO?

And,

Second, the author creates texture ID using:

```<code>glGenTextures(1, &texture1);
glBindTexture(GL_TEXTURE_2D, texture1);
//some more code
glGenTextures(1, &texture2);
glBindTexture(GL_TEXTURE_2D, texture2);
</code>```

outside the main draw loop , but does this again *inside the main draw loop:  *

```<code> glActiveTexture(GL_TEXTURE0);
 glBindTexture(GL_TEXTURE_2D, texture1);
 glActiveTexture(GL_TEXTURE1);
 glBindTexture(GL_TEXTURE_2D, texture2);
</code>```

Two things that I don't understand in what he does is:

Why does he bind the texture ID again in the mainloop when he has
done it outside of the mainloop?(This one is similar to VAO but I
don't know yet if unbinding is possible in here)

Why does he select the active texture unit (using glActiveTexture)
inside the loop? Couldn't it be done outside the main draw loop?

答:
glBindTexture binds a texture to specified target and the current texture unit. The current texture unit is set by glActiveTexture. The current texture unit is a global state, and glBindTexture considers that state.

That meas when you do

glBindTexture(GL_TEXTURE_2D, texture1);
glBindTexture(GL_TEXTURE_2D, texture2);
glActiveTexture(GL_TEXTURE0);
glActiveTexture(GL_TEXTURE1);
```

<p>after that <code>texture2</code> is bound to the current texture unit (<code>GL_TEXTURE0</code> by default) and the current texture unit is <code>GL_TEXTURE1</code>. Note <code>texture1</code><br>
is just bound for a short moment, but the binding is lost, when <code>texture2</code> is bound.</p>

<p>In compare, when you do</p>

<pre class="lang-cpp prettyprint-override"><code>glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
</code>```

The current texture unit is explicitly set to GL_TEXTURE0 and texture1 is bound to texture texture unit 0. After that the current texture unit is switched to GL_TEXTURE1 and  texture2 is bound to texture unit 1 (because it is current at this moment).

Note, with the use of Direct State Access and glBindTextureUnit (since OpenGL 4.5) a texture can be bound to a texture unit directly. e.g.:

glBindTextureUnit(GL_TEXTURE0, texture1);
glBindTextureUnit(GL_TEXTURE1, texture2);
```

Body:
While learning opengl, one bit of confusion is whether it is necessary to bind buffers like VAO
 or texture IDs multiple times without unbinding them?

With reference to the above link and the full source code , I have come across 2 scenerios a bit distinct from each other.

First, the author creates a VAO(outside the maindraw loop) and binds the VAO using the  glBindVertexArray(VAO) then he doesn't unbind it using glBindVertexArray(0); , but he binds it again in the maindraw loop. My confusion, Is this really necessary? Isn't the currently bound VAO already ... bound? Why bind it when it is already the active VAO?

And,

Second, the author creates texture ID using:

glGenTextures(1, &texture1);
glBindTexture(GL_TEXTURE_2D, texture1);
//some more code
glGenTextures(1, &texture2);
glBindTexture(GL_TEXTURE_2D, texture2);

outside the main draw loop , but does this again *inside the main draw loop:  *

 glActiveTexture(GL_TEXTURE0);
 glBindTexture(GL_TEXTURE_2D, texture1);
 glActiveTexture(GL_TEXTURE1);
 glBindTexture(GL_TEXTURE_2D, texture2);

Two things that I don't understand in what he does is:

Why does he bind the texture ID again in the mainloop when he has
done it outside of the mainloop?(This one is similar to VAO but I
don't know yet if unbinding is possible in here)

Why does he select the active texture unit (using glActiveTexture)
inside the loop? Couldn't it be done outside the main draw loop?

Body:
glBindTexture binds a texture to specified target and the current texture unit. The current texture unit is set by glActiveTexture. The current texture unit is a global state, and glBindTexture considers that state.

That meas when you do

glBindTexture(GL_TEXTURE_2D, texture1);
glBindTexture(GL_TEXTURE_2D, texture2);
glActiveTexture(GL_TEXTURE0);
glActiveTexture(GL_TEXTURE1);

after that texture2 is bound to the current texture unit (GL_TEXTURE0 by default) and the current texture unit is GL_TEXTURE1. Note texture1

is just bound for a short moment, but the binding is lost, when texture2 is bound.

In compare, when you do

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);

The current texture unit is explicitly set to GL_TEXTURE0 and texture1 is bound to texture texture unit 0. After that the current texture unit is switched to GL_TEXTURE1 and  texture2 is bound to texture unit 1 (because it is current at this moment).

Note, with the use of Direct State Access and glBindTextureUnit (since OpenGL 4.5) a texture can be bound to a texture unit directly. e.g.:

glBindTextureUnit(GL_TEXTURE0, texture1);
glBindTextureUnit(GL_TEXTURE1, texture2);


问:
Get image in http payload
I am trying to return image as response to http POST request. Image should be returned in payload of http response. Response string:

When convert this string to Blob and save, result file is not valid. Converting code:

```<code>const blob = new Blob([data], { type: headers['content-type'] });
</code>```

答:
I finnaly find out reason. To download blob you have to specify that response payload is binary.
Example for axios:</p>

```<code>axios.post(endpoint, formData, {
        responseType: 'blob'
    })
</code>```

Title: Get image in http payload

Body:
I am trying to return image as response to http POST request. Image should be returned in payload of http response. Response string:

When convert this string to Blob and save, result file is not valid. Converting code:

const blob = new Blob([data], { type: headers['content-type'] });

Body:
I finnaly find out reason. To download blob you have to specify that response payload is binary.
Example for axios:

axios.post(endpoint, formData, {
        responseType: 'blob'
    })


问:
Java 8: Where is TriFunction (and kin) in java.util.function? Or what is the alternative?
I see java.util.function.BiFunction, so I can do this:

```<code>BiFunction<Integer, Integer, Integer> f = (x, y) -> { return 0; };
</code>```

What if that is not good enough and I need TriFunction?  It doesn't exist!

```<code>TriFunction<Integer, Integer, Integer, Integer> f = (x, y, z) -> { return 0; };
</code>```

I guess I should add that I know I can define my own TriFunction, I'm just trying to understand the rationale behind not including it in the standard library.

答:
You can't always stop at TriFunction. Sometimes, you may need to pass n number of parameters to your functions. Then support team will have to create an QuadFunction to fix your code.
Long term solution would be to create an Object with the extra parameters and then use the ready-made Function or BiFunction.</p>

Body:
I see java.util.function.BiFunction, so I can do this:

BiFunction<Integer, Integer, Integer> f = (x, y) -> { return 0; };

What if that is not good enough and I need TriFunction?  It doesn't exist!

TriFunction<Integer, Integer, Integer, Integer> f = (x, y, z) -> { return 0; };

I guess I should add that I know I can define my own TriFunction, I'm just trying to understand the rationale behind not including it in the standard library.


问:
Select the first word in a

How can I get this output in CSS or jQuery.

::first-letter or
CSS is (equal to) === "Some Value e.g. ' (1)(a)(I)(2)'"  to get output background-color:red;

Sample HTML:

```<code><p>(1)</p>
<p>(a)</p>
<p>(b)</p>
<p>(2)</p>
<p>(a)</p>
<p>(i)</p>
<p>(ii)</p>
<p>(iii)</p>
</code>```

Output should be:

```<code><p>(1)</p> <--Background-color RED
<p>(a)</p> <--Background-color GREEN
<p>(b)</p> <--Background-color GREEN
<p>(2)</p> <--Background-color RED
<p>(a)</p> <--Background-color GREEN
<p>(i)</p> <--Background-color YELLOw
<p>(ii)</p> <--Background-color YELLOw
<p>(iii)</p> <--Background-color YELLOw
</code>```

答:
You can try something like this

HTML

```<code><div id="clr-change">
 <p>(1)</p>
 <p>(a)</p>
 <p>(2)</p>
 <p>(i)</p>
</div>
</code>```

JQUERY

```<code>$( document ).ready(function() {
 $("#clr-change p").each(function(){
 if($( this ).html() == '(1)' || $( this ).html() == '(2)'){
 $( this ).css({'background-color':'#ff0000'});
    }else if('condition for green'){
    }
})
});
</code>```

Title: Select the first word in a <P>

Body:
How can I get this output in CSS or jQuery.

::first-letter or
CSS is (equal to) === "Some Value e.g. ' (1)(a)(I)(2)'"  to get output background-color:red;

Sample HTML:

(1)

(a)

(b)

(2)

(a)

(i)

(ii)

(iii)

Output should be:

(1)
 <--Background-color RED

(a)
 <--Background-color GREEN

(b)
 <--Background-color GREEN

(2)
 <--Background-color RED

(a)
 <--Background-color GREEN

(i)
 <--Background-color YELLOw

(ii)
 <--Background-color YELLOw

(iii)
 <--Background-color YELLOw

Body:
You can try something like this

HTML

<div id="clr-change">
 <p>(1)</p>
 <p>(a)</p>
 <p>(2)</p>
 <p>(i)</p>
</div>

JQUERY

$( document ).ready(function() {
 $("#clr-change p").each(function(){
 if($( this ).html() == '(1)' || $( this ).html() == '(2)'){
 $( this ).css({'background-color':'#ff0000'});
    }else if('condition for green'){
    }
})
});


问:
psql: FATAL: Ident authentication failed for user "postgres"
I have installed PostgreSQL and pgAdminIII on my Ubuntu Karmic box.

I am able to use pgAdminIII successfully (i.e. connect/log on), however when I try to login to the server using the same username/pwd on the command line (using psql), I get the error:

```<code>psql: FATAL:  Ident authentication failed for user "postgres"
</code>```

Does anyone now how to resolve this issue?

答:
For Windows if you dont want to edit pb_gba.conf ie leave the method to MD5(default), create a new user, by running this query in Query tool in PGadmin

```<code>CREATE USER admin WITH PASSWORD 'secret'
</code>```

then in cmd

```<code>psql "dbname=Main_db host=127.0.0.1 user=admin password=secret port=5432
</code>```

where dbname is your db in postgresql

Body:
I have installed PostgreSQL and pgAdminIII on my Ubuntu Karmic box.

I am able to use pgAdminIII successfully (i.e. connect/log on), however when I try to login to the server using the same username/pwd on the command line (using psql), I get the error:

psql: FATAL:  Ident authentication failed for user "postgres"

Does anyone now how to resolve this issue?

Body:
For Windows if you dont want to edit pb_gba.conf ie leave the method to MD5(default), create a new user, by running this query in Query tool in PGadmin

CREATE USER admin WITH PASSWORD 'secret'

then in cmd

psql "dbname=Main_db host=127.0.0.1 user=admin password=secret port=5432

where dbname is your db in postgresql


问:
HelloWorld example (sbt new sbt/scala-seed.g8) not working
After having installed sbt version 0.13.13 (with brew) on Mac 10.12.2 with scala 2.12.0, I tried the first example on the documentation (as per subject sbt new sbt/scala-seed.g8).

The result is:

```<code>...
[info] Set current project to hello (in build file:/scratch/hello/)
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
org.eclipse.jgit.api.errors.TransportException: http://github.com/sbt/scala-seed.g8.git: 301 Moved Permanently
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:139)
...
</code>```

I'm absolutely new on sbt, just wondering if this is an issue due to my inexperience...

答:
I've experienced similar problem.  The way I solved is
by installing sdkman:

```<code>curl -s "https://get.sdkman.io" | bash
</code>```

Then, instead of my system package manager, I use sdkman to install the scala stuff:

```<code>sdk install java
sdk install sbt
sdk install scala
</code>```

After that, the examples from the documentation works fine in my machine.

Body:
After having installed sbt version 0.13.13 (with brew) on Mac 10.12.2 with scala 2.12.0, I tried the first example on the documentation (as per subject sbt new sbt/scala-seed.g8).

The result is:

...
[info] Set current project to hello (in build file:/scratch/hello/)
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
org.eclipse.jgit.api.errors.TransportException: http://github.com/sbt/scala-seed.g8.git: 301 Moved Permanently
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:139)
...

I'm absolutely new on sbt, just wondering if this is an issue due to my inexperience...

Body:
I've experienced similar problem.  The way I solved is
by installing sdkman:

curl -s "https://get.sdkman.io" | bash

Then, instead of my system package manager, I use sdkman to install the scala stuff:

sdk install java
sdk install sbt
sdk install scala

After that, the examples from the documentation works fine in my machine.


问:
how do i get a bunch of squares to look like the border of Croatia?
I decided to use SVGs to generate squares and images I need. SVGs are flexible and that should work with me.

I can't figure out how can I generate squares to fit inside the border of Croatia. End result I'd like to have can be seen in (see image below).

IMAGE :

It's pretty easy to generate squares in some rectangular shape. Since border of Croatia is not rectangular the only thing I have in mind is to do it manually, but this is not flexible. What if I want to create bigger or smaller squares just to test it out and fit them within borders.

答:
It's usually a mistake to hand-implement low-level graphics primitives like this.  Dealing with wavy or nested borders and edge conditions is bug-attracting code.

I'd suggest creating a small HTML canvas, drawing Croatia on it with path primitives and fill, then reading back its content with getImageData.  Each fully black pixel corresponds to a square you want to draw.  (Size the canvas to ensure this.)

(Or, if you just want the aesthetic, use an SVG pattern fill.  That'd be less work.)


问:
How to give hyperlink action in UIAlertController?
I'm unable to click hyperlink in UIAlertController. I want to open the external browser on hyperlink click.

```<code>-(void)viewDidAppear:(BOOL) animated {
    NSString *htmlString = @"Welcom to AlertView for more information <A href=\"https://www.google.com\"> Click Here </A>";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                     message:htmlString
                                                              preferredStyle:UIAlertControllerStyleAlert];
    NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
               options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                         NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
    documentAttributes:nil error:nil];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        // OK button tappped.
        [self dismissViewControllerAnimated:YES completion:^{ }];
    }];
    [alert setValue:attributedStr forKey: @"attributedMessage"];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:true completion:nil];
}
</code>```

on click on "Click Here" then should open the external browser. Is possible to get hyperlink click action in UIAlertView?

答:
I think it's possible but I think it's not recommanded by the Apple guidelines.
Instead, you should set the title with "Welcome to this AlertView, for more information check our website" with two buttons "Ok" and "No thanks" for example.
The user used to click on the native button instead of a text inside an alert controller. Hope it helps.</p>

Body:
I'm unable to click hyperlink in UIAlertController. I want to open the external browser on hyperlink click.

-(void)viewDidAppear:(BOOL) animated {
    NSString *htmlString = @"Welcom to AlertView for more information  Click Here ";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                     message:htmlString
                                                              preferredStyle:UIAlertControllerStyleAlert];
    NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
               options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                         NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
    documentAttributes:nil error:nil];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        // OK button tappped.
        [self dismissViewControllerAnimated:YES completion:^{ }];
    }];
    [alert setValue:attributedStr forKey: @"attributedMessage"];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:true completion:nil];
}

on click on "Click Here" then should open the external browser. Is possible to get hyperlink click action in UIAlertView?


问:
Convert digits in string to ints and then back to string
Say I have a string: formula = "C3H12O4"

How can I convert the digit chars in the string to ints?
My end goal is to do something along the lines of:

formula * 4

Once converted formula chars to an int, it would be best to report the result back to a string, thus

outputting as:

"C12H48O16"

答:
If you had many conversions to do it might be worthwhile to include the following in a benchmark of different methods:

```<code>h = (0..9).each_with_object({}) { |n,h| h[n.to_s] = (4*n).to_s }
  #=> {"0"=>"0", "1"=>"4", "2"=>"8", "3"=>"12", "4"=>"16",
  #    "5"=>"20", "6"=>"24", "7"=>"28", "8"=>"32", "9"=>"36"}
</code>```

Then for each string of interest the following calculation would be performed:

```<code>"C3H12O4".gsub(/\d/, h)
  #=> "C12H48O16"
"99Ra$32".gsub(/\d/, h)
  #=> "3636Ra$128"
</code>```

This uses the form of String#gsub that employs a hash to make the substitutions.

A variant of this is the following.

```<code>"C3H12O4".gsub(/./) { |c| h.fetch(c, c) }
  #=> "C12H48O16"
</code>```

Here gsub matches every character, which it passes to the block to be held by the block variable c. Hash#fetch is then used to look up and return h[c], provided h has a key c. If h does not have a key c, fetch's second argument (c) is returned.

The use of the hash avoids the need to convert back and forth between integers and strings, except in the creation of the hash, of course, but that is done only once.

Body:
If you had many conversions to do it might be worthwhile to include the following in a benchmark of different methods:

h = (0..9).each_with_object({}) { |n,h| h[n.to_s] = (4*n).to_s }
  #=> {"0"=>"0", "1"=>"4", "2"=>"8", "3"=>"12", "4"=>"16",
  #    "5"=>"20", "6"=>"24", "7"=>"28", "8"=>"32", "9"=>"36"}

Then for each string of interest the following calculation would be performed:

"C3H12O4".gsub(/\d/, h)
  #=> "C12H48O16"
"99Ra$32".gsub(/\d/, h)
  #=> "3636Ra$128"

This uses the form of String#gsub that employs a hash to make the substitutions.

A variant of this is the following.

"C3H12O4".gsub(/./) { |c| h.fetch(c, c) }
  #=> "C12H48O16"

Here gsub matches every character, which it passes to the block to be held by the block variable c. Hash#fetch is then used to look up and return h[c], provided h has a key c. If h does not have a key c, fetch's second argument (c) is returned.

The use of the hash avoids the need to convert back and forth between integers and strings, except in the creation of the hash, of course, but that is done only once.


答:
Use regex or substring to get first word from
 tag. Add class based upon that text like below.

var $par = $("p");
$par.each(function(index, element) {
  var str = $(this).text().trim();
  var i = str.indexOf(" ");
  var txt = i == -1 ? str : str.substring(0, i);

  if (txt == '(1)' || txt == '(2)')
    $(this).addClass('red');
  if (txt == '(a)' || txt == '(b)')
    $(this).addClass('green');
  if (txt == '(ii)' || txt == '(iii)' || txt == '(i)')
    $(this).addClass('yellow')
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red {
  background-color: red;
}

.green {
  background-color: green;
}

.yellow {
  background-color: yellow;
}</code>```

  (1) 1st paragraph
  (1) 1st paragraph
  (1) 1st paragraph
  next line

(a) 2nd paragraph

(b)

(2)

(a)

(i)

(ii)

(iii)
```

Title: Select the first word in a <P>

Body:
Use regex or substring to get first word from  <p> tag. Add class based upon that text like below.

var $par = $("p");
$par.each(function(index, element) {
  var str = $(this).text().trim();
  var i = str.indexOf(" ");
  var txt = i == -1 ? str : str.substring(0, i);

  if (txt == '(1)' || txt == '(2)')
    $(this).addClass('red');
  if (txt == '(a)' || txt == '(b)')
    $(this).addClass('green');
  if (txt == '(ii)' || txt == '(iii)' || txt == '(i)')
    $(this).addClass('yellow')
});

.red {
  background-color: red;
}

.green {
  background-color: green;
}

.yellow {
  background-color: yellow;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  (1) 1st paragraph
  (1) 1st paragraph
  (1) 1st paragraph
  next line
</p>
<p>(a) 2nd paragraph</p>
<p>(b)</p>
<p>(2)</p>
<p>(a)</p>
<p>(i)</p>
<p>(ii)</p>
<p>(iii)</p>


问:
Catching errors when querying in Django of fields that do not exist in the database or model
I am trying to catch errors of fields that do not exist either in the model or database. To do that I follow EAFP approach.

But it doesn't work, I get the following error:

Cannot resolve keyword 'bin_height_mm_desc' into field. Choices are:

```<code>def DeviceDetailView(request, device_id):
    tbl_dict = {}
    try:
        tbl_dict  = Bin.objects.values('bin_height_mm_desc', 'received_at_ymd', 'received_at_hm')
    except (ValueError, TypeError, AttributeError) as e:
         tbl_dict = e

   context = {
        'tbl_data' : tbl_dict,
    }

return render(request, 'applications/device.detail.html', context)
</code>```

答:
You should use a django.core.exceptions.FieldError.

```<code>    def DeviceDetailView(request,device_id):
        tbl_dict = {}
        try:
            tbl_dict  = Bin.objects.values('bin_height_mm_desc','received_at_ymd','received_at_hm')
        except FieldError as e:
             tbl_dict = e

        context = {
        'tbl_data' : tbl_dict,
       }
</code>```

This class is a sub class of NameError so you could also catch NameError. To find out what kind of exception is raised you can try something like below.

```<code>try:
    tbl_dict  = Bin.objects.values('bin_height_mm_desc','received_at_ymd','received_at_hm')
except Exception as e:
    print(e.__name__)
    print(e.__class__)
</code>```

Body:
I am trying to catch errors of fields that do not exist either in the model or database. To do that I follow EAFP approach.

But it doesn't work, I get the following error:

Cannot resolve keyword 'bin_height_mm_desc' into field. Choices are:

def DeviceDetailView(request, device_id):
    tbl_dict = {}
    try:
        tbl_dict  = Bin.objects.values('bin_height_mm_desc', 'received_at_ymd', 'received_at_hm')
    except (ValueError, TypeError, AttributeError) as e:
         tbl_dict = e

   context = {
        'tbl_data' : tbl_dict,
    }

return render(request, 'applications/device.detail.html', context)

Body:
You should use a django.core.exceptions.FieldError.

    def DeviceDetailView(request,device_id):
        tbl_dict = {}
        try:
            tbl_dict  = Bin.objects.values('bin_height_mm_desc','received_at_ymd','received_at_hm')
        except FieldError as e:
             tbl_dict = e

        context = {
        'tbl_data' : tbl_dict,
       }

This class is a sub class of NameError so you could also catch NameError. To find out what kind of exception is raised you can try something like below.

try:
    tbl_dict  = Bin.objects.values('bin_height_mm_desc','received_at_ymd','received_at_hm')
except Exception as e:
    print(e.__name__)
    print(e.__class__)