问:
Usage of += operator with lambda operator
I have the following code:

```<code>recognizer = new GestureRecognizer();
recognizer.Tapped += (args) =>
{
    // Send an OnSelect message to the focused object and its ancestors.
    if (FocusedObject != null)
    {
        FocusedObject.SendMessageUpwards("OnSelect",
            SendMessageOptions.DontRequireReceiver);
    }
};
</code>```

I am working in a project for Unity and I am not that experienced with the syntax of this operation:

```<code>recognizer.Tapped += (args) =>
{
    // Send an OnSelect message to the focused object and its ancestors.
    if (FocusedObject != null)
    {
        FocusedObject.SendMessageUpwards("OnSelect",
            SendMessageOptions.DontRequireReceiver);
    }
</code>```

I understand that Tapped is the event listener for taps. However, I don't understand the following things:

1) Why are they using a += operator to add a lambda function. How can you add a lambda function like that? I've always used += on primitive types.

2) Where does "args" come from?

3) When does that lambda function run?

答:
Basically, it is a lambda event listener. Rather than define it as a function like:

function void myEvent(object o, EventArgs args){};
 recognizer.Tapped += myEvent;

It's defined and assigned in the same place.

The reason that += is used is because you can have multiple event handlers assigned to the same event like so:

```<code>function void myEvent(object o, EventArgs args){};
function void yourEvent(object o, EventArgs args){};
recognizer.Tapped += myEvent;
recognizer.Tapped += yourEvent;
</code>```

If you wanted to remove the assigned event you could use -= like so:

recognizer.Tapped -= myEvent;

The args are part of the event handler definition that is requited for all events

Body:
I have the following code:

recognizer = new GestureRecognizer();
recognizer.Tapped += (args) =>
{
    // Send an OnSelect message to the focused object and its ancestors.
    if (FocusedObject != null)
    {
        FocusedObject.SendMessageUpwards("OnSelect",
            SendMessageOptions.DontRequireReceiver);
    }
};

I am working in a project for Unity and I am not that experienced with the syntax of this operation:

recognizer.Tapped += (args) =>
{
    // Send an OnSelect message to the focused object and its ancestors.
    if (FocusedObject != null)
    {
        FocusedObject.SendMessageUpwards("OnSelect",
            SendMessageOptions.DontRequireReceiver);
    }

I understand that Tapped is the event listener for taps. However, I don't understand the following things:

1) Why are they using a += operator to add a lambda function. How can you add a lambda function like that? I've always used += on primitive types.

2) Where does "args" come from?

3) When does that lambda function run?

Body:
Basically, it is a lambda event listener. Rather than define it as a function like:

function void myEvent(object o, EventArgs args){};
 recognizer.Tapped += myEvent;

It's defined and assigned in the same place.

The reason that += is used is because you can have multiple event handlers assigned to the same event like so:

function void myEvent(object o, EventArgs args){};
function void yourEvent(object o, EventArgs args){};
recognizer.Tapped += myEvent;
recognizer.Tapped += yourEvent;

If you wanted to remove the assigned event you could use -= like so:

recognizer.Tapped -= myEvent;

The args are part of the event handler definition that is requited for all events


来源: stackexchange

问:
Efficiently convert an unsigned short to a char*
What would be an efficient, portable way to convert a unsigned short to a char* (i.e. convert 25 to '25').

I'd like to avoid things such as getting (std::string) strings involved.  Performance is important in this case since this conversion will need to happen quickly and often.

I was looking into things such as using sprintf but would like to explorer any and all ideas.

答:
An array of strings such that

```<code>array[25] = "25";
array[26] = "26";

array[255] = "255";
</code>```

maybe? You could write a small program that generates the table source code for you quite easily, and then use this file in your project.

Edit: I don't get what you mean by you don't want to ge strings involved.

ContentLicense: CC BY-SA 2.5

Body:
An array of strings such that

array[25] = "25";
array[26] = "26";

array[255] = "255";

maybe? You could write a small program that generates the table source code for you quite easily, and then use this file in your project.

Edit: I don't get what you mean by you don't want to ge strings involved.


问:
Search multiple columns for multiple values
Very new to R
Have a very large data frame (ie looking to avoid using a loop for efficiency) with many columns. I want to scan multiple columns (ex ss1:ss15) for a vector of characters (ex c(‘9515’,’8231’)). If any of these are true/match I am trying to get a new column in the data frame with value 1 if any in that row are true and 0 if not. I’m stuck on how to even begin going about this...</p>

答:
We can either use grep, by looping through the columns of interest by subsetting the dataset, then Reduceing the list of logical vectors into a single logical vector  and subsequently converting to binary with as.integer

```<code>cols <- paste0('ss', 1:15)
vect <- c(‘9515’,’8231’)
as.integer(Reduce('|', lapply(df1[cols], grepl, pattern = paste(vect, collapse="|"))))
</code>```

If the 'vect' elements to be searched are fixed and not substrings, we can also use %in%

```<code>as.integer(Reduce('|', lapply(df1[cols], '%in%', vect)))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We can either use grep, by looping through the columns of interest by subsetting the dataset, then Reduceing the list of logical vectors into a single logical vector  and subsequently converting to binary with as.integer

cols <- paste0('ss', 1:15)
vect <- c(‘9515’,’8231’)
as.integer(Reduce('|', lapply(df1[cols], grepl, pattern = paste(vect, collapse="|"))))

If the 'vect' elements to be searched are fixed and not substrings, we can also use %in%

as.integer(Reduce('|', lapply(df1[cols], '%in%', vect)))


问:
What's the best neural network type for guessing the next number of a sequence?
I want to create a simple neural network that can guess the next number based on a set of numbers given, so something like

```<code>1,2,3,4,5,6,7,8,
</code>```

will give an output of

```<code>9
</code>```

(after training it with test data, of course)
As there are a ton of AI algorithms, what is the most efficient, algorithm in order to accomplish something like this?

答:
You can try with Genetic Algorithm. It is very fun and there is bunch of tutorials out there that can help you.

Advantage of this is that your program will not get old if you give him some complex arrays, but he will self learn and improve.

Body:
I want to create a simple neural network that can guess the next number based on a set of numbers given, so something like

1,2,3,4,5,6,7,8,

will give an output of

9

(after training it with test data, of course)
As there are a ton of AI algorithms, what is the most efficient, algorithm in order to accomplish something like this?


问:
dynamic sql not parsing correctly
I am writing a dynamic sql statement that will check if the index exist and drop it. Getting compile error Could somebody tell what the problem is . I double checked the ticks but cant understand </p>

```<code>declare @startyear int = 2000
declare @startQuarter int = 1
declare @sql nvarchar(max)
declare @tableName varchar(50)

if @startYear is null
    set @startYear = 2000;
set @startQuarter = 1;
while @startYear <= year(getdate())
    begin
        set @startQuarter = 1;

        while @startQuarter < 5
        begin
            set @tableName = 'FinData' + cast(@startYear as varchar) + '_' + cast(@startQuarter as varchar);
            set @sql = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(' + @tableName + ') AND NAME = ' + '.idx_' + @tableName
            drop  index' + @tableName + '.idx_' + @tableName

            print  @sql

            set @startQuarter += 1
        end
        set @startYear += 1;

    end
</code>```

答:
Two issues: this isn't adding anything before the .idx, it's just concatenating the strings together:

```<code>') AND NAME = ' + '.idx_'
</code>```

And then there's a single-quote missing at the end of that line. It looks like your indexes are named after the table's name: tablename.idx_tablename, so try this:

```<code>DECLARE @startyear INT = 2000;
DECLARE @startQuarter INT = 1;
DECLARE @sql NVARCHAR(MAX);
DECLARE @tableName VARCHAR(50);

IF @startyear IS NULL
    SET @startyear = 2000;
SET @startQuarter = 1;
WHILE @startyear <= YEAR(GETDATE())
BEGIN
    SET @startQuarter = 1;

    WHILE @startQuarter < 5
    BEGIN
        SET @tableName = 'FinData' + CAST(@startyear AS VARCHAR) + '_'
            + CAST(@startQuarter AS VARCHAR);
        SET @sql = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('
            + @tableName + ') AND NAME = ' + @tableName + '.idx_' + @tableName + '
            drop  index' + @tableName + '.idx_' + @tableName;

        PRINT @sql;

        SET @startQuarter += 1;
    END;
    SET @startyear += 1;

END;
</code>```

Title: dynamic sql not parsing correctly

Body:
I am writing a dynamic sql statement that will check if the index exist and drop it. Getting compile error Could somebody tell what the problem is . I double checked the ticks but cant understand

declare @startyear int = 2000
declare @startQuarter int = 1
declare @sql nvarchar(max)
declare @tableName varchar(50)

if @startYear is null
    set @startYear = 2000;
set @startQuarter = 1;
while @startYear <= year(getdate())
    begin
        set @startQuarter = 1;

        while @startQuarter < 5
        begin
            set @tableName = 'FinData' + cast(@startYear as varchar) + '_' + cast(@startQuarter as varchar);
            set @sql = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(' + @tableName + ') AND NAME = ' + '.idx_' + @tableName
            drop  index' + @tableName + '.idx_' + @tableName

            print  @sql

            set @startQuarter += 1
        end
        set @startYear += 1;

    end

Body:
Two issues: this isn't adding anything before the .idx, it's just concatenating the strings together:

') AND NAME = ' + '.idx_'

And then there's a single-quote missing at the end of that line. It looks like your indexes are named after the table's name: tablename.idx_tablename, so try this:

DECLARE @startyear INT = 2000;
DECLARE @startQuarter INT = 1;
DECLARE @sql NVARCHAR(MAX);
DECLARE @tableName VARCHAR(50);

IF @startyear IS NULL
    SET @startyear = 2000;
SET @startQuarter = 1;
WHILE @startyear <= YEAR(GETDATE())
BEGIN
    SET @startQuarter = 1;

    WHILE @startQuarter < 5
    BEGIN
        SET @tableName = 'FinData' + CAST(@startyear AS VARCHAR) + '_'
            + CAST(@startQuarter AS VARCHAR);
        SET @sql = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('
            + @tableName + ') AND NAME = ' + @tableName + '.idx_' + @tableName + '
            drop  index' + @tableName + '.idx_' + @tableName;

        PRINT @sql;

        SET @startQuarter += 1;
    END;
    SET @startyear += 1;

END;


问:
Why isnt this regex working?
I'm trying to have a regex pattern for an address similar to the one below but I cant get the test method to return true, what am I doing wrong here?</p>

```<code>       let reg=/[0-9]{3}\b[a-z]{1}\b\d{2}[a-z]{2}\b[a-z]{2}\b[a-z}{6}\b[a-z]{10}\b[0-9]{5}/;

       let fakeAddress="925 s 10th st tacoma washington 98405";
        reg.test(fakeAddress);
</code>```

答:
There are no word boundaries between letters and digits and between digits and letters, you wanted to match whitespace between them. Remember that \b, a word boundary, is a zero-width assertion that does not consume any chars.  So, you need to replace all \b with \s+ (1 or more whitespace chars). Also, [a-z} is a typo. it should be [a-z].

Use

```<code>/\d{3}\s+[a-z]\s+\d{2}[a-z]{2}\s+[a-z]{2}\s+[a-z]{6}\s+[a-z]{10}\s+[0-9]{5}/
</code>```

See the regex demo

Title: Why isnt this regex working?

Body:
I'm trying to have a regex pattern for an address similar to the one below but I cant get the test method to return true, what am I doing wrong here?

       let reg=/[0-9]{3}\b[a-z]{1}\b\d{2}[a-z]{2}\b[a-z]{2}\b[a-z}{6}\b[a-z]{10}\b[0-9]{5}/;

       let fakeAddress="925 s 10th st tacoma washington 98405";
        reg.test(fakeAddress);

Body:
There are no word boundaries between letters and digits and between digits and letters, you wanted to match whitespace between them. Remember that \b, a word boundary, is a zero-width assertion that does not consume any chars.  So, you need to replace all \b with \s+ (1 or more whitespace chars). Also, [a-z} is a typo. it should be [a-z].

Use

/\d{3}\s+[a-z]\s+\d{2}[a-z]{2}\s+[a-z]{2}\s+[a-z]{6}\s+[a-z]{10}\s+[0-9]{5}/

See the regex demo


问:
Does Urban Airship support all the features of Blackberry Push Plus?
My team needs to send a push notification to BlackBerry devices and know (as soon as possible) whether the push notification got to the app. The BlackBerry Push Plus (as opposed to the BlackBerry Push Essentials) gives us this capability. We now are looking to develop this, but we found out about this company that has support for BlackBerry, iPhone and Android push notifications: Urban Airship. While it's clear that we can send the Push notifications to the BB device using their service, what's not clear is whether there's a way for us to be notified whether the push notification did reach the BlackBerry app.</p>

答:
Urban Airship doesn't currently support the return receipt functionality that BlackBerry Push Plus provides.

You're correct that Urban Airship does support the basic push functionality across the various BlackBerry Push services.

(I work for Urban Airship, feel free to contact us with more specific feedback and details on your use-case if you'd like.)


问:
Select specific column based on data supplied using Powershell
I have a csv file that may have unknown headers, one of the columns will contain email addresses for example.

Is there a way to select only the column that contains the email addresses and save it as a list to a variable?

One csv could have the header say email, another could say emailaddresses, another could say email addresses another file might not even have the word email in the header. As you can see, the headers are different. So I want to be able to detect the correct column first and use that data further in the script. Once the column is identified based on the data it contains, select that column only.

I've tried the where-object and select-string cmdlets. With both, the output is the entire array and not just the data in the column I am wanting.

```<code>$CSV = import-csv file.csv
$CSV | Where {$_ -like "*@domain.com"}
</code>```

This outputs the entire array as all rows will contain this data.

答:
Sample Data for visualization

```<code>id,first_name,bagel,last_name
1,Base,bcruikshank0@homestead.com,Cruikshank
2,Regan,rbriamo1@ebay.co.uk,Briamo
3,Ryley,rsacase2@mysql.com,Sacase
4,Siobhan,sdonnett3@is.gd,Donnett
5,Patty,pesmonde4@diigo.com,Esmonde
</code>```

Bagel is obviously what we are trying to find. And we will play pretend in that we have no knowledge of the columns name or position ahead of time.

Find column dynamically

```<code># Import the CSV
$data = Import-CSV $path

# Take the first row and get its columns
$columns = $data[0].psobject.properties.name

# Cycle the columns to find the one that has an email address for a row value
# Use a VERY crude regex to validate an email address.
$emailColumn = $columns | Where-Object{$data[0].$_ -match ".*@*.\..*"}

# Example of using the found column(s) to display data.
$data | Select-Object $emailColumn
</code>```

Basically read in the CSV like normal and use the first columns data to try and figure out where the email address column is. There is a caveat that if there is more than one column that matches it will get returned.

To enforce only 1 result a simple pipe to Select-Object -First 1 will handle that. Then you just have to hope the first one is the "right" one.

Body:
I have a csv file that may have unknown headers, one of the columns will contain email addresses for example.

Is there a way to select only the column that contains the email addresses and save it as a list to a variable?

One csv could have the header say email, another could say emailaddresses, another could say email addresses another file might not even have the word email in the header. As you can see, the headers are different. So I want to be able to detect the correct column first and use that data further in the script. Once the column is identified based on the data it contains, select that column only.

I've tried the where-object and select-string cmdlets. With both, the output is the entire array and not just the data in the column I am wanting.

$CSV = import-csv file.csv
$CSV | Where {$_ -like "*@domain.com"}

This outputs the entire array as all rows will contain this data.

Body:
Sample Data for visualization

id,first_name,bagel,last_name
1,Base,bcruikshank0@homestead.com,Cruikshank
2,Regan,rbriamo1@ebay.co.uk,Briamo
3,Ryley,rsacase2@mysql.com,Sacase
4,Siobhan,sdonnett3@is.gd,Donnett
5,Patty,pesmonde4@diigo.com,Esmonde

Bagel is obviously what we are trying to find. And we will play pretend in that we have no knowledge of the columns name or position ahead of time.

Find column dynamically

# Import the CSV
$data = Import-CSV $path

# Take the first row and get its columns
$columns = $data[0].psobject.properties.name

# Cycle the columns to find the one that has an email address for a row value
# Use a VERY crude regex to validate an email address.
$emailColumn = $columns | Where-Object{$data[0].$_ -match ".*@*.\..*"}

# Example of using the found column(s) to display data.
$data | Select-Object $emailColumn

Basically read in the CSV like normal and use the first columns data to try and figure out where the email address column is. There is a caveat that if there is more than one column that matches it will get returned.

To enforce only 1 result a simple pipe to Select-Object -First 1 will handle that. Then you just have to hope the first one is the "right" one.


问:
Best Output for table data (object oriented programming, numpy, drill down results, GUI)
Trying to take my calculations in python, and put them into an interactive table. I assume object oriented programming key for this behind the scene, using Pandas and Numpy.

So how do I create something lets with a grid of results with people and taxes paid as rows and columns.  If I were to click one of the values in the table, I would get an option to see the underlying values/variables used to calculate that particular field.  This sounds like a GUI, perhaps using GT or Tkinter, but wanted to see what people had for thoughts.

答:
These are usually BI Analyst or Data analyst tools. Tableau, Spotfire, Jump, etc, are purpose built for analyzing and plotting tabular data exactly as you're describing. Here's an answer showing a few free alternatives to these analyst tools.

But to answer your question, yes this would definitely be a GUI. The GUI framework that you use (Tkinter, GT, QT, or maybe even matplotlib) is up to your preference since they're all capable of doing this (some with more effort). PandasTable and PreDator could be used as reference.


问:
java.io.FileNotFoundException for Cloud Iot core Code
I am presently working on program on Android Things for connecting to Google Cloud IoT Core. I used to sample maven code provided by Google and modified it for Gradle(with all the imports and stuff). After doing every kind of check, whenever I am trying to run the program on a Raspberry Pi3 running Android Things it keeps giving this error

```<code>W/System.err: java.io.FileNotFoundException: com/example/adityaprakash/test/rsa_private.pem (No such file or directory)
</code>```

telling me that the private key file that I am supposed to use for the JWT doesn't exist despite the fact it does and I have given the path for the pem file.Here are my java codes

```<code>package com.example.adityaprakash.test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        Log.i("#########","######");
        MqttExample mqtt = new MqttExample();
        try {
            mqtt.Start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

The MqttExample.java

```<code>package com.example.adityaprakash.test;
// [END cloudiotcore_mqtt_imports]
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import org.joda.time.DateTime;

import java.io.BufferedReader;
import java.io.FileReader;

import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;

import android.util.Base64;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class MqttExample {

    // [START cloudiotcore_mqtt_createjwt]
    /** Create a Cloud IoT Core JWT for the given project id, signed with the given RSA key. */
    public static String createJwtRsa(String projectId, String privateKeyFile) throws Exception {
        DateTime now = new DateTime();

        String strKeyPEM = "";
        BufferedReader br = new BufferedReader(new FileReader(privateKeyFile));
        String line;
        while ((line = br.readLine()) != null) {
            strKeyPEM += line + "\n";
        }
        br.close();
        // Create a JWT to authenticate this device. The device will be disconnected after the token
        // expires, and will have to reconnect with a new token. The audience field should always be set
        // to the GCP project id.
        JwtBuilder jwtBuilder =
                Jwts.builder()
                        .setIssuedAt(now.toDate())
                        .setExpiration(now.plusMinutes(20).toDate())
                        .setAudience(projectId);
        String privateKeyPEM = strKeyPEM;
        privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----\n", "");
        privateKeyPEM = privateKeyPEM.replace("-----END PRIVATE KEY-----", "");
        byte[] encoded = Base64.decode(privateKeyPEM,Base64.DEFAULT);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");

        return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
    }

    /** Parse arguments, configure MQTT, and publish messages. */
    public void Start() throws Exception {
        // [START cloudiotcore_mqtt_configuremqtt]
        MqttExampleOptions options = MqttExampleOptions.values();
        if (options == null) {
            // Could not parse.
            System.exit(1);
        }
        // Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL
        // connections are accepted. For server authentication, the JVM's root certificates
        // are used.
        final String mqttServerAddress =
                String.format("ssl://%s:%s", options.mqttBridgeHostname, options.mqttBridgePort);

        // Create our MQTT client. The mqttClientId is a unique string that identifies this device. For
        // Google Cloud IoT Core, it must be in the format below.
        final String mqttClientId =
                String.format(
                        "projects/%s/locations/%s/registries/%s/devices/%s",
                        options.projectId, options.cloudRegion, options.registryId, options.deviceId);

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        // Note that the the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we
        // explictly set this. If you don't set MQTT version, the server will immediately close its
        // connection to your device.
        connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

        // With Google Cloud IoT Core, the username field is ignored, however it must be set for the
        // Paho client library to send the password field. The password field is used to transmit a JWT
        // to authorize the device.
        connectOptions.setUserName("unused");

        System.out.println(options.algorithm);
        if (options.algorithm.equals("RS256")) {
            connectOptions.setPassword(
                    createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
        }else {
            throw new IllegalArgumentException(
                    "Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
        }
        // [END cloudiotcore_mqtt_configuremqtt]

        // [START cloudiotcore_mqtt_publish]
        // Create a client, and connect to the Google MQTT bridge.
        MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());
        try {
            client.connect(connectOptions);

            // Publish to the events or state topic based on the flag.
            String subTopic = options.messageType.equals("event") ? "events" : options.messageType;

            // The MQTT topic that this device will publish telemetry data to. The MQTT topic name is
            // required to be in the format below. Note that this is not the same as the device registry's
            // Cloud Pub/Sub topic.
            String mqttTopic = String.format("/devices/%s/%s", options.deviceId, subTopic);

            // Publish numMessages messages to the MQTT bridge, at a rate of 1 per second.
            for (int i = 1; i <= options.numMessages; ++i) {
                String payload = String.format("%s/%s-payload number-%d", options.registryId, options.deviceId, i);
                System.out.format(
                        "Publishing %s message %d/%d: '%s'\n",
                        options.messageType, i, options.numMessages, payload);

                // Publish "payload" to the MQTT topic. qos=1 means at least once delivery. Cloud IoT Core
                // also supports qos=0 for at most once delivery.
                MqttMessage message = new MqttMessage(payload.getBytes());
                message.setQos(1);
                client.publish(mqttTopic, message);

                if (options.messageType.equals("event")) {
                    // Send telemetry events every second
                    Thread.sleep(1000);
                }
                else {
                    // Note: Update Device state less frequently than with telemetry events
                    Thread.sleep(5000);
                }
            }
        } finally {
            // Disconnect the client and finish the run.
            client.disconnect();
        }
        System.out.println("Finished loop successfully. Goodbye!");
        // [END cloudiotcore_mqtt_publish]
    }

}
</code>```

and the MqttExampleOptions.java code:

```<code>package com.example.adityaprakash.test;

public class MqttExampleOptions {
    String projectId;
    String registryId;
    String deviceId;
    String privateKeyFile;
    String algorithm;
    String cloudRegion;
    int numMessages;
    String mqttBridgeHostname;
    short mqttBridgePort;
    String messageType;

    /** Construct an MqttExampleOptions class. */
    public static MqttExampleOptions values() {

        try {

            MqttExampleOptions res = new MqttExampleOptions();

            res.projectId = "_";
            res.registryId = "_";
            res.deviceId = "_";
            res.privateKeyFile = "com/example/adityaprakash/test/rsa_private.pem";
            res.algorithm = "RS256";
            res.cloudRegion = "asia-east1";
            res.numMessages = 100;
            res.mqttBridgeHostname = "mqtt.googleapis.com";
            res.mqttBridgePort = 8883;
            res.messageType = "event";
            return res;

        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        }
    }
}
</code>```

Please can anyone give a solution to this problem.

P.S. I know the code looks totally crappy.I don't have experience with Android programming,so please let it go.

答:
On AndroidThings, it is easier to provide the authentication credentials in an Android Resource. See my fork of the WeatherStation sample to see how this works.

First, copy the private key file (e.g. rsa_private_pkcs8) to app/src/main/res/raw/privatekey.txt

Next, you can load the key used to calculate your JWT as:

```<code>Context mContext;
int resIdPk = getResources().getIdentifier("privatekey", "raw", getPackageName());

...

InputStream privateKey = mContext.getResources().openRawResource(resIdPk);
byte[] keyBytes = inputStreamToBytes(privateKey);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("EC");
</code>```

One final note, it appears that you're referencing a file that is not in pkcs8 format, which will cause issues with Java. Make sure to use a key that is packaged in PKCS8 when opening credentials on Android (Java).

Body:
I am presently working on program on Android Things for connecting to Google Cloud IoT Core. I used to sample maven code provided by Google and modified it for Gradle(with all the imports and stuff). After doing every kind of check, whenever I am trying to run the program on a Raspberry Pi3 running Android Things it keeps giving this error

W/System.err: java.io.FileNotFoundException: com/example/adityaprakash/test/rsa_private.pem (No such file or directory)

telling me that the private key file that I am supposed to use for the JWT doesn't exist despite the fact it does and I have given the path for the pem file.Here are my java codes

package com.example.adityaprakash.test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        Log.i("#########","######");
        MqttExample mqtt = new MqttExample();
        try {
            mqtt.Start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The MqttExample.java

package com.example.adityaprakash.test;
// [END cloudiotcore_mqtt_imports]
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import org.joda.time.DateTime;

import java.io.BufferedReader;
import java.io.FileReader;

import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;

import android.util.Base64;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class MqttExample {

    // [START cloudiotcore_mqtt_createjwt]
    /** Create a Cloud IoT Core JWT for the given project id, signed with the given RSA key. */
    public static String createJwtRsa(String projectId, String privateKeyFile) throws Exception {
        DateTime now = new DateTime();

        String strKeyPEM = "";
        BufferedReader br = new BufferedReader(new FileReader(privateKeyFile));
        String line;
        while ((line = br.readLine()) != null) {
            strKeyPEM += line + "\n";
        }
        br.close();
        // Create a JWT to authenticate this device. The device will be disconnected after the token
        // expires, and will have to reconnect with a new token. The audience field should always be set
        // to the GCP project id.
        JwtBuilder jwtBuilder =
                Jwts.builder()
                        .setIssuedAt(now.toDate())
                        .setExpiration(now.plusMinutes(20).toDate())
                        .setAudience(projectId);
        String privateKeyPEM = strKeyPEM;
        privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----\n", "");
        privateKeyPEM = privateKeyPEM.replace("-----END PRIVATE KEY-----", "");
        byte[] encoded = Base64.decode(privateKeyPEM,Base64.DEFAULT);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");

        return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
    }

    /** Parse arguments, configure MQTT, and publish messages. */
    public void Start() throws Exception {
        // [START cloudiotcore_mqtt_configuremqtt]
        MqttExampleOptions options = MqttExampleOptions.values();
        if (options == null) {
            // Could not parse.
            System.exit(1);
        }
        // Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL
        // connections are accepted. For server authentication, the JVM's root certificates
        // are used.
        final String mqttServerAddress =
                String.format("ssl://%s:%s", options.mqttBridgeHostname, options.mqttBridgePort);

        // Create our MQTT client. The mqttClientId is a unique string that identifies this device. For
        // Google Cloud IoT Core, it must be in the format below.
        final String mqttClientId =
                String.format(
                        "projects/%s/locations/%s/registries/%s/devices/%s",
                        options.projectId, options.cloudRegion, options.registryId, options.deviceId);

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        // Note that the the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we
        // explictly set this. If you don't set MQTT version, the server will immediately close its
        // connection to your device.
        connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

        // With Google Cloud IoT Core, the username field is ignored, however it must be set for the
        // Paho client library to send the password field. The password field is used to transmit a JWT
        // to authorize the device.
        connectOptions.setUserName("unused");

        System.out.println(options.algorithm);
        if (options.algorithm.equals("RS256")) {
            connectOptions.setPassword(
                    createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
        }else {
            throw new IllegalArgumentException(
                    "Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
        }
        // [END cloudiotcore_mqtt_configuremqtt]

        // [START cloudiotcore_mqtt_publish]
        // Create a client, and connect to the Google MQTT bridge.
        MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());
        try {
            client.connect(connectOptions);

            // Publish to the events or state topic based on the flag.
            String subTopic = options.messageType.equals("event") ? "events" : options.messageType;

            // The MQTT topic that this device will publish telemetry data to. The MQTT topic name is
            // required to be in the format below. Note that this is not the same as the device registry's
            // Cloud Pub/Sub topic.
            String mqttTopic = String.format("/devices/%s/%s", options.deviceId, subTopic);

            // Publish numMessages messages to the MQTT bridge, at a rate of 1 per second.
            for (int i = 1; i <= options.numMessages; ++i) {
                String payload = String.format("%s/%s-payload number-%d", options.registryId, options.deviceId, i);
                System.out.format(
                        "Publishing %s message %d/%d: '%s'\n",
                        options.messageType, i, options.numMessages, payload);

                // Publish "payload" to the MQTT topic. qos=1 means at least once delivery. Cloud IoT Core
                // also supports qos=0 for at most once delivery.
                MqttMessage message = new MqttMessage(payload.getBytes());
                message.setQos(1);
                client.publish(mqttTopic, message);

                if (options.messageType.equals("event")) {
                    // Send telemetry events every second
                    Thread.sleep(1000);
                }
                else {
                    // Note: Update Device state less frequently than with telemetry events
                    Thread.sleep(5000);
                }
            }
        } finally {
            // Disconnect the client and finish the run.
            client.disconnect();
        }
        System.out.println("Finished loop successfully. Goodbye!");
        // [END cloudiotcore_mqtt_publish]
    }

}

and the MqttExampleOptions.java code:

package com.example.adityaprakash.test;

public class MqttExampleOptions {
    String projectId;
    String registryId;
    String deviceId;
    String privateKeyFile;
    String algorithm;
    String cloudRegion;
    int numMessages;
    String mqttBridgeHostname;
    short mqttBridgePort;
    String messageType;

    /** Construct an MqttExampleOptions class. */
    public static MqttExampleOptions values() {

        try {

            MqttExampleOptions res = new MqttExampleOptions();

            res.projectId = "_";
            res.registryId = "_";
            res.deviceId = "_";
            res.privateKeyFile = "com/example/adityaprakash/test/rsa_private.pem";
            res.algorithm = "RS256";
            res.cloudRegion = "asia-east1";
            res.numMessages = 100;
            res.mqttBridgeHostname = "mqtt.googleapis.com";
            res.mqttBridgePort = 8883;
            res.messageType = "event";
            return res;

        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        }
    }
}

Please can anyone give a solution to this problem.

P.S. I know the code looks totally crappy.I don't have experience with Android programming,so please let it go.

Body:
On AndroidThings, it is easier to provide the authentication credentials in an Android Resource. See my fork of the WeatherStation sample to see how this works.

First, copy the private key file (e.g. rsa_private_pkcs8) to app/src/main/res/raw/privatekey.txt

Next, you can load the key used to calculate your JWT as:

Context mContext;
int resIdPk = getResources().getIdentifier("privatekey", "raw", getPackageName());

...

InputStream privateKey = mContext.getResources().openRawResource(resIdPk);
byte[] keyBytes = inputStreamToBytes(privateKey);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("EC");

One final note, it appears that you're referencing a file that is not in pkcs8 format, which will cause issues with Java. Make sure to use a key that is packaged in PKCS8 when opening credentials on Android (Java).


问:
Looping inside the json in stored proc DocumentDB
I have big json that I pass to stored procedure in Cosmos DB. I need to split the json document and create multiple documents. How do I loop to the json inside the stored procedure.

Example: Using Json below I need to create a separate document for each children and another one without Children nodes. A total of 3 documents. How can I loop and split it inside the stored procedure?

```<code>{
  "id": "d93af7d3706e4f28882920366c017cd7",
  "FamilyId": 989,
  "LastName": "Andersen",
  "Parents": [
    {
      "FamilyName": null,
      "FirstName": "Thomas"
    },
    {
      "FamilyName": null,
      "FirstName": "Mary Kay"
    }
  ],
  "Children": [
    {
      "ChildId":001,
      "FamilyName": null,
      "FirstName": "Henriette Thaulow",
      "Gender": "female",
      "Grade": 5,
      "Pets": [
        {
          "GivenName": "Fluffy"
        }
      ]
    },
    {
      "ChildId":002
      "FamilyName": null,
      "FirstName": "Maria Thaulow",
      "Gender": "female",
      "Grade": 12,
      "Pets": [
        {
          "GivenName": "Grizzly"
        }
      ]
    }
  ],
  "Address": {
    "State": "WA",
    "County": "King",
    "City": "Seattle"
  },
  "IsRegistered": false
}
</code>```

答: Take a look at this sample: https://github.com/Azure/azure-documentdb-js-server/blob/master/samples/stored-procedures/BulkImport.js. Note that currently stored procedure can run within context of one partition key (which is provided in request options to execute the sproc), i.e. if there are multiple PK values in your docs, the docs need to be grouped by PK value.

Body:
I have big json that I pass to stored procedure in Cosmos DB. I need to split the json document and create multiple documents. How do I loop to the json inside the stored procedure.

Example: Using Json below I need to create a separate document for each children and another one without Children nodes. A total of 3 documents. How can I loop and split it inside the stored procedure?

{
  "id": "d93af7d3706e4f28882920366c017cd7",
  "FamilyId": 989,
  "LastName": "Andersen",
  "Parents": [
    {
      "FamilyName": null,
      "FirstName": "Thomas"
    },
    {
      "FamilyName": null,
      "FirstName": "Mary Kay"
    }
  ],
  "Children": [
    {
      "ChildId":001,
      "FamilyName": null,
      "FirstName": "Henriette Thaulow",
      "Gender": "female",
      "Grade": 5,
      "Pets": [
        {
          "GivenName": "Fluffy"
        }
      ]
    },
    {
      "ChildId":002
      "FamilyName": null,
      "FirstName": "Maria Thaulow",
      "Gender": "female",
      "Grade": 12,
      "Pets": [
        {
          "GivenName": "Grizzly"
        }
      ]
    }
  ],
  "Address": {
    "State": "WA",
    "County": "King",
    "City": "Seattle"
  },
  "IsRegistered": false
}


问:
Image collection in DIV
I want to get the images sources, but my code doesn't work.
my code:

function imagiesFun(){
    var container = document.getElementById("imagiesCollectionExampleDiv");
    var collection = container.images;
    document.getElementById("imagiesResult").innerHTML = ;
    var result = "";
    var i;
    for(i = 0; i < 3; i++){
        result = result + container[i].src + "
";
    }

    document.getElementById("imagiesResult").innerHTML = result;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="imagiesCollectionExampleDiv">
 <img style="width: 20%" src="alfa.img">
 <img style="width: 20%" src="beta.img">
 <img style="width: 20%" src="gamma.img">
</div>
<button onclick="imagiesFun()">Show sources</button>
<p id="imagiesResult"></p></code>```

 maybe someone tell me why, please

答:
Use document.querySelectorAll() instead to get all the images collection :

```<code>var collection = document.querySelectorAll("#imagiesCollectionExampleDiv img");
</code>```

But if you want really to use .images you should call it on document like :

```<code>var collection = document.images;
</code>```

NOTE : You don't need to clear the result part since you init the result on every click.

Hope this helps.

function imagiesFun() {
  var collection = document.querySelectorAll("#imagiesCollectionExampleDiv img");
  //OR
  //var collection = document.images;

  var result = "";

  for (var i = 0; i < collection.length; i++) {
    result = result + collection[i].src + "
";
  }

  document.getElementById("imagiesResult").innerHTML = result;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="imagiesCollectionExampleDiv">
  <img style="width: 20%" src="alfa.img">
  <img style="width: 20%" src="beta.img">
  <img style="width: 20%" src="gamma.img">
</div>
<button onclick="imagiesFun()">Show sources</button>
<p id="imagiesResult"></p></code>```

Title: Image collection in DIV

Body:
I want to get the images sources, but my code doesn't work.
my code:

function imagiesFun(){
    var container = document.getElementById("imagiesCollectionExampleDiv");
    var collection = container.images;
    document.getElementById("imagiesResult").innerHTML = ;
    var result = "";
    var i;
    for(i = 0; i < 3; i++){
        result = result + container[i].src + "
";
    }

    document.getElementById("imagiesResult").innerHTML = result;
}

<button onclick="imagiesFun()">Show sources</button>

 maybe someone tell me why, please

Body:
Use document.querySelectorAll() instead to get all the images collection :

var collection = document.querySelectorAll("#imagiesCollectionExampleDiv img");

But if you want really to use .images you should call it on document like :

var collection = document.images;

NOTE : You don't need to clear the result part since you init the result on every click.

Hope this helps.

function imagiesFun() {
  var collection = document.querySelectorAll("#imagiesCollectionExampleDiv img");
  //OR
  //var collection = document.images;

  var result = "";

  for (var i = 0; i < collection.length; i++) {
    result = result + collection[i].src + "<br>";
  }

  document.getElementById("imagiesResult").innerHTML = result;
}

<div id="imagiesCollectionExampleDiv">
  <img style="width: 20%" src="alfa.img">
  <img style="width: 20%" src="beta.img">
  <img style="width: 20%" src="gamma.img">
</div>
<button onclick="imagiesFun()">Show sources</button>
<p id="imagiesResult"></p>


问:
Is It Possible to Create a Vertical Meter With HTML5?
Normally, if I create:

```<code><meter value="30" max="100">Low</meter>
</code>```

I'll end up with a horizontal meter/bar if viewed on a browser that supports the html5 meter element.

Is it possible to create a vertical meter with html5?

The only solution I've been able to come up with so far is using CSS3 rotation (transform).

答:
Yeah transform is the only way to do this..</p>

```<code>-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
transform: rotate(90deg);
</code>```

Body:
Normally, if I create:

<meter value="30" max="100">Low</meter>

I'll end up with a horizontal meter/bar if viewed on a browser that supports the html5 meter element.

Is it possible to create a vertical meter with html5?

The only solution I've been able to come up with so far is using CSS3 rotation (transform).

Body:
Yeah transform is the only way to do this..

-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
transform: rotate(90deg);


问:
Router Navigate to ngx-bootstrap tabs Angular 4
I have a component with four tabs (using ngx-bootstrap tabs) myprod,mysettings,etc. and I created four different routing for each tab(pointed to same component). and I used the below code for show the right tab on page load.

```<code>[routerLink]="['/user/my-account']" [routerLinkActive]="'active is-active'"
</code>```

but unfortunately everytime the active class will add to the first to tab not the right one. If I use any other class name instead of active it works as I expected, please help.

答:
try this </p>

```<code> <tab
  [routerLink]="['/user/my-account']"
  routerLinkActive
  #ads="routerLinkActive"
  [active]="ads.isActive">
</tab>
</code>```

Body:
I have a component with four tabs (using ngx-bootstrap tabs) myprod,mysettings,etc. and I created four different routing for each tab(pointed to same component). and I used the below code for show the right tab on page load.

[routerLink]="['/user/my-account']" [routerLinkActive]="'active is-active'"

but unfortunately everytime the active class will add to the first to tab not the right one. If I use any other class name instead of active it works as I expected, please help.

Body:
try this

 <tab
  [routerLink]="['/user/my-account']"
  routerLinkActive
  #ads="routerLinkActive"
  [active]="ads.isActive">
</tab>

ContentLicense: CC BY-SA 4.0


问:
webRTC : SimplePeer ignore the iceServer config
I'm trying to configure a visioconference system beetwen two person with webRTC. For this i'm using the SimplePeer package : https://github.com/feross/simple-peer

Everything work fine on my own network. I want now to connect using my stun server but no matter what address I enter for the stun server it doesn't change. The config of the iceServers seems to be ignored.

Here is my code :

```<code>navigator.getUserMedia({
    video: true,
    audio: true
}, function (stream) {
    let p = new SimplePeer({
        initiator: initiator,
        stream: stream,
        trickle: false,
        config: { iceServers: [{ url: 'stun:---:1' }]}
    })
    bindEvents(p)
}, function (err) {
    console.log('error', err)
})
</code>```

Can someone help me on that ?

答:
WebRTC by default will add your local ip address, which is why your connection works on your local network.  That's a good place to start.  Most likely your stun server isn't configured properly.  You can test it out at this page.

https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/

The default stun server on that page is a free public server from google which you can use.

Also, it looks like your trying to connect to your stun server on port 1.  That's a reserved port.  Don't do that.

Also, I think I read recently that trickle ice should be used.

Body:
I'm trying to configure a visioconference system beetwen two person with webRTC. For this i'm using the SimplePeer package : https://github.com/feross/simple-peer

Everything work fine on my own network. I want now to connect using my stun server but no matter what address I enter for the stun server it doesn't change. The config of the iceServers seems to be ignored.

Here is my code :

navigator.getUserMedia({
    video: true,
    audio: true
}, function (stream) {
    let p = new SimplePeer({
        initiator: initiator,
        stream: stream,
        trickle: false,
        config: { iceServers: [{ url: 'stun:---:1' }]}
    })
    bindEvents(p)
}, function (err) {
    console.log('error', err)
})

Can someone help me on that ?


问:
Restrict different type of admins to access each other routes
I am working on admin panel and I have different levels of admins. I have a field "admin_type" in the database to represent the level of the admin. The levels are 1,2,3. Now I want to implement some restrictions so that admin level 1 can't access route that is only for admin level 2.

I have searched google a lot and found this blog post helpful http://bjedrocha.com/rails/2015/03/18/role-based-routing-in-rails/
But When I implemented this it is not working and giving hell of errors
This is the route code. I want this route only accessible by admin level 2

```<code>constraints RouteConstraint.new do
    get 'admins/donation_analysis' => 'admins#donation_analysis'
end
</code>```

This is the constraint class

```<code>class RouteConstraint
  def matches?(request)
    user = current_user(request)
    ##render plain: user.inspect
    user.present? && user.admin_type?(:2)
  end

  def current_user(request)
    User.find_by_id(request.session[:user_id])
  end
end
</code>```

routes are

```<code>constraints RouteConstraint.new do
    get 'admins/donation_analysis' => 'admins#donation_analysis'
  end
  #get 'admins/active_account/:token' => 'admins#active_account'
  get 'admins/link_expiry' => 'admins#link_expiry'
  get 'admins/edit_profile' => 'admins#edit_profile'
  post 'admins/update_profile' => 'admins#update_profile'
  match '/admins/create_account', to: 'admins#create_account', via: 'post'
  match '/admins/:id', to: 'admins#destroy', via: 'get' , as: 'admin_destroy'

  resources :admins
</code>```

But it is not working

答:
```<code>class RouteConstraint
  def matches?(request)
    user = current_user(request)
    ##render plain: user.inspect
    user.present? && user.admin_type == "2"
  end

  def current_user(request)
    User.find_by_id(request.session[:user_id])
  end
end
</code>```

Body:
I am working on admin panel and I have different levels of admins. I have a field "admin_type" in the database to represent the level of the admin. The levels are 1,2,3. Now I want to implement some restrictions so that admin level 1 can't access route that is only for admin level 2.

I have searched google a lot and found this blog post helpful http://bjedrocha.com/rails/2015/03/18/role-based-routing-in-rails/
But When I implemented this it is not working and giving hell of errors
This is the route code. I want this route only accessible by admin level 2

constraints RouteConstraint.new do
    get 'admins/donation_analysis' => 'admins#donation_analysis'
end

This is the constraint class

class RouteConstraint
  def matches?(request)
    user = current_user(request)
    ##render plain: user.inspect
    user.present? && user.admin_type?(:2)
  end

  def current_user(request)
    User.find_by_id(request.session[:user_id])
  end
end

routes are

constraints RouteConstraint.new do
    get 'admins/donation_analysis' => 'admins#donation_analysis'
  end
  #get 'admins/active_account/:token' => 'admins#active_account'
  get 'admins/link_expiry' => 'admins#link_expiry'
  get 'admins/edit_profile' => 'admins#edit_profile'
  post 'admins/update_profile' => 'admins#update_profile'
  match '/admins/create_account', to: 'admins#create_account', via: 'post'
  match '/admins/:id', to: 'admins#destroy', via: 'get' , as: 'admin_destroy'

  resources :admins

But it is not working


问:
Not able to automate using appium for android version 7.1.2 (Redmi 4)
I am running automation on android real devices. The automation works successfully across devices which has version less than 7. But when I try to run automation on devices which has version greater than 7(Redmi-note4, Redmi 4), I am getting a below error.

```<code>[TestNG] Running:
  C:\Users\sandeepraju\AppData\Local\Temp\testng-eclipse-819864143\testng-customsuite.xml

FAILED: newRegistrationIn
org.openqa.selenium.SessionNotCreatedException: A new session could not be created. (Original error: Command failed: C:\Windows\system32\cmd.exe /s /c "C:\Users\sandeepraju\AppData\Local\Android\sdk1\platform-tools\adb.exe shell "stop; sleep 2; setprop sys.boot_completed 0; start""
stop: must be root
start: must be root
) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 9.96 seconds
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
System info: host: 'SandeepDell', ip: '192.168.234.2', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_101'
Driver info: io.appium.java_client.android.AndroidDriver
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
    at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:180)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:158)
    at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:109)
    at io.appium.java_client.android.AndroidDriver.<init>(AndroidDriver.java:39)
    at com.gdi.basemodule.LaunchApp.launchApplication(LaunchApp.java:51)
    at com.gdi.modules.Modules.newRegistrationIn(Modules.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
    at org.testng.TestRunner.privateRun(TestRunner.java:774)
    at org.testng.TestRunner.run(TestRunner.java:624)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
    at org.testng.SuiteRunner.run(SuiteRunner.java:261)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
    at org.testng.TestNG.run(TestNG.java:1048)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:126)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:152)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:57)

===============================================
    Default test
    Tests run: 1, Failures: 1, Skips: 0
===============================================
</code>```

Please refer the below code.

```<code>    public  AndroidDriver launchApplication(String appName,ExtentTest testReport) throws MalformedURLException, InterruptedException

{
        DesiredCapabilities cap= new DesiredCapabilities();
        File appDir=new File("apps");
        File app= new File(appDir,appName);
        cap.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
        cap.setCapability(MobileCapabilityType.PLATFORM_NAME,MobilePlatform.ANDROID);
        cap.setCapability(MobileCapabilityType.PLATFORM_VERSION,"6.0.1");
        cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Redmi4");
        AndroidDriver androidDriver = new AndroidDriver(new URL("http://0.0.0.0:4723/wd/hub"),cap);
        System.out.println(androidDriver);
        cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, "100");
        androidDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        testReport.log(LogStatus.INFO, "Launch application");
        if(androidDriver!=null)
        {
            testReport.log(LogStatus.PASS, "Successfully launched the application");
        }
}
</code>```

Please help me to run my automation android real devices 7.0

答: Update your Appium. The problem was well-known for quite some time, but they apparently finally fixed it not too long ago. I had the same problem and had to restrict all my tests to API's < 7 but now it runs on all API's without any code changes.</p>

Body:
I am running automation on android real devices. The automation works successfully across devices which has version less than 7. But when I try to run automation on devices which has version greater than 7(Redmi-note4, Redmi 4), I am getting a below error.

[TestNG] Running:
  C:\Users\sandeepraju\AppData\Local\Temp\testng-eclipse-819864143\testng-customsuite.xml

FAILED: newRegistrationIn
org.openqa.selenium.SessionNotCreatedException: A new session could not be created. (Original error: Command failed: C:\Windows\system32\cmd.exe /s /c "C:\Users\sandeepraju\AppData\Local\Android\sdk1\platform-tools\adb.exe shell "stop; sleep 2; setprop sys.boot_completed 0; start""
stop: must be root
start: must be root
) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 9.96 seconds
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
System info: host: 'SandeepDell', ip: '192.168.234.2', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_101'
Driver info: io.appium.java_client.android.AndroidDriver
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
    at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:180)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:158)
    at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:109)
    at io.appium.java_client.android.AndroidDriver.<init>(AndroidDriver.java:39)
    at com.gdi.basemodule.LaunchApp.launchApplication(LaunchApp.java:51)
    at com.gdi.modules.Modules.newRegistrationIn(Modules.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
    at org.testng.TestRunner.privateRun(TestRunner.java:774)
    at org.testng.TestRunner.run(TestRunner.java:624)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
    at org.testng.SuiteRunner.run(SuiteRunner.java:261)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
    at org.testng.TestNG.run(TestNG.java:1048)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:126)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:152)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:57)

===============================================
    Default test
    Tests run: 1, Failures: 1, Skips: 0
===============================================

Please refer the below code.

    public  AndroidDriver launchApplication(String appName,ExtentTest testReport) throws MalformedURLException, InterruptedException

{
        DesiredCapabilities cap= new DesiredCapabilities();
        File appDir=new File("apps");
        File app= new File(appDir,appName);
        cap.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
        cap.setCapability(MobileCapabilityType.PLATFORM_NAME,MobilePlatform.ANDROID);
        cap.setCapability(MobileCapabilityType.PLATFORM_VERSION,"6.0.1");
        cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Redmi4");
        AndroidDriver androidDriver = new AndroidDriver(new URL("http://0.0.0.0:4723/wd/hub"),cap);
        System.out.println(androidDriver);
        cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, "100");
        androidDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        testReport.log(LogStatus.INFO, "Launch application");
        if(androidDriver!=null)
        {
            testReport.log(LogStatus.PASS, "Successfully launched the application");
        }
}

Please help me to run my automation android real devices 7.0


问:
PostgreSQL BEFORE INSERT trigger locking behavior in a concurrent environment
I have a general function that can manipulate the sequence of any table (why is irrelevant to my question). It reads the current value, works out the new value, sets it, and returns its calculation, which is what's inserted. This is obviously a multi-step process.

I call it from a BEFORE INSERT trigger on tables where I need it.

All I need to know is am I guaranteed that the function will be called by only one caller at a time in a multi-user environment?

Specifically, does the BEFORE INSERT trigger have to complete before it is called again by another caller?

Logically, I would assume yes, but one never knows what may be going on under the hood.

If the answer is no, what minimal locking would I need on the function to guarantee I can read and write the sequence in a "thread-safe" manner?

I'm using PG 10.

EDIT

Here is the function updated with a lock:

```<code>CREATE OR REPLACE FUNCTION public.uts_set()
RETURNS TRIGGER AS
$$
DECLARE
  sv        int8;
  seq       text := format('%I.%I_uts_seq', tg_table_schema, tg_table_name);
BEGIN
  EXECUTE   format('LOCK TABLE %I IN ROW EXCLUSIVE MODE;', tg_table_name);
  EXECUTE   'SELECT last_value+1 FROM ' || seq INTO sv; -- currval(seq) isn't useable
  PERFORM   setval(seq, GREATEST(sv, (EXTRACT(epoch FROM localtimestamp) * 1000000)::int8), false);
  RETURN    NULL;
END;
$$ LANGUAGE plpgsql;
</code>```

However, a SELECT already acquires ROW EXCLUSIVE, so this statement may be redundant and a stronger lock may be needed. Or, conversely, it may mean no lock is needed.

UPDATE

If I am reading this SO question correctly, my original version without the LOCK should work since the trigger acquires the same lock my updated function is redundantly taking.

答:
All I need to know is am I guaranteed that the function will be called by only one caller at a time in a multi-user environment?

No. Not related to calling functions itself, but you can achieve this behaviour with SERIALIZABLE transaction isolation level:

This level emulates serial transaction execution for all committed
  transactions; as if transactions had been executed one after another,
  serially, rather than concurrently

But this approach would introduce several tradeoffs, such preparing your application to retry transactions with serialization failure.

Maybe a missed something, but I really believe that you just need NEXTVAL, something like below:

```<code>CREATE OR REPLACE FUNCTION public.uts_set()
RETURNS TRIGGER AS
$$
DECLARE
  sv        int8;
  -- First, use %I wildcard for identifiers instead of %s
  seq       text := format('%I.%I', tg_table_schema, tg_table_name || '_uts_seq');
BEGIN
  -- Second, you couldn't call CURRVAL on a session
  -- that you didn't issued NEXTVAL before
  sv := NEXTVAL(seq);

  -- Do your logic here...

  -- Result is ignored since this is an STATEMENT trigger
  RETURN    NULL;
END;
$$ LANGUAGE plpgsql;
</code>```

Remember that CURRVAL acts on session local scope and NEXTVAL on global scope, so you have a reliable thread-safe mechanism in hands.

Body:
I have a general function that can manipulate the sequence of any table (why is irrelevant to my question). It reads the current value, works out the new value, sets it, and returns its calculation, which is what's inserted. This is obviously a multi-step process.

I call it from a BEFORE INSERT trigger on tables where I need it.

All I need to know is am I guaranteed that the function will be called by only one caller at a time in a multi-user environment?

Specifically, does the BEFORE INSERT trigger have to complete before it is called again by another caller?

Logically, I would assume yes, but one never knows what may be going on under the hood.

If the answer is no, what minimal locking would I need on the function to guarantee I can read and write the sequence in a "thread-safe" manner?

I'm using PG 10.

EDIT

Here is the function updated with a lock:

CREATE OR REPLACE FUNCTION public.uts_set()
RETURNS TRIGGER AS
$$
DECLARE
  sv        int8;
  seq       text := format('%I.%I_uts_seq', tg_table_schema, tg_table_name);
BEGIN
  EXECUTE   format('LOCK TABLE %I IN ROW EXCLUSIVE MODE;', tg_table_name);
  EXECUTE   'SELECT last_value+1 FROM ' || seq INTO sv; -- currval(seq) isn't useable
  PERFORM   setval(seq, GREATEST(sv, (EXTRACT(epoch FROM localtimestamp) * 1000000)::int8), false);
  RETURN    NULL;
END;
$$ LANGUAGE plpgsql;

However, a SELECT already acquires ROW EXCLUSIVE, so this statement may be redundant and a stronger lock may be needed. Or, conversely, it may mean no lock is needed.

UPDATE

If I am reading this SO question correctly, my original version without the LOCK should work since the trigger acquires the same lock my updated function is redundantly taking.

Body:
All I need to know is am I guaranteed that the function will be called by only one caller at a time in a multi-user environment?

No. Not related to calling functions itself, but you can achieve this behaviour with SERIALIZABLE transaction isolation level:

This level emulates serial transaction execution for all committed
  transactions; as if transactions had been executed one after another,
  serially, rather than concurrently

But this approach would introduce several tradeoffs, such preparing your application to retry transactions with serialization failure.

Maybe a missed something, but I really believe that you just need NEXTVAL, something like below:

CREATE OR REPLACE FUNCTION public.uts_set()
RETURNS TRIGGER AS
$$
DECLARE
  sv        int8;
  -- First, use %I wildcard for identifiers instead of %s
  seq       text := format('%I.%I', tg_table_schema, tg_table_name || '_uts_seq');
BEGIN
  -- Second, you couldn't call CURRVAL on a session
  -- that you didn't issued NEXTVAL before
  sv := NEXTVAL(seq);

  -- Do your logic here...

  -- Result is ignored since this is an STATEMENT trigger
  RETURN    NULL;
END;
$$ LANGUAGE plpgsql;

Remember that CURRVAL acts on session local scope and NEXTVAL on global scope, so you have a reliable thread-safe mechanism in hands.


答:
You can use the querySelectorAll() method, or update your code to use getElementsByTagName, for example:

function imagiesFun()
{
    var container  = document.getElementById("imagiesCollectionExampleDiv"),
        collection = container.getElementsByTagName('img');

    var i, result = "";

    for(i = 0; i < 3; i++)
    {
        result+= collection[i].src + "
";
    }

    document.getElementById("imagiesResult").innerHTML = result;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="imagiesCollectionExampleDiv">
   <img style="width: 20%" src="alfa.img">
   <img style="width: 20%" src="beta.img">
   <img style="width: 20%" src="gamma.img">
</div>

<button onclick="imagiesFun()">Show sources</button>

<p id="imagiesResult"></p></code>```

Notice also that I modified the following areas of your code:

You were referencing container inside of your for loop, when you should have referenced collection.

You had a blank assignment (which is invalid) when attempting to clear the content of #imagiesResult (which is actually completely redundant anyway).

Title: Image collection in DIV

Body:
You can use the querySelectorAll() method, or update your code to use getElementsByTagName, for example:

function imagiesFun()
{
    var container  = document.getElementById("imagiesCollectionExampleDiv"),
        collection = container.getElementsByTagName('img');

    var i, result = "";

    for(i = 0; i < 3; i++)
    {
        result+= collection[i].src + "<br>";
    }

    document.getElementById("imagiesResult").innerHTML = result;
}

<div id="imagiesCollectionExampleDiv">
   <img style="width: 20%" src="alfa.img">
   <img style="width: 20%" src="beta.img">
   <img style="width: 20%" src="gamma.img">
</div>

<button onclick="imagiesFun()">Show sources</button>

<p id="imagiesResult"></p>

Notice also that I modified the following areas of your code:

You were referencing container inside of your for loop, when you should have referenced collection.

You had a blank assignment (which is invalid) when attempting to clear the content of #imagiesResult (which is actually completely redundant anyway).


问:
Moving an object from one class to another in Swift
there was a similar problem:
There is an object addinAprel in the class ViewController, also there is a class SecondController, it is necessary to transfer this object from one class to another in Swift.

Example programs:

Function in the ViewController class:

```<code>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print("Selected item is", current_arr[row])
active_textField.text = current_arr[row]
let realm = try! Realm()
let events = realm.objects(EventsDB.self)

if ((text_field_months.text) == "Апрель")
{
    if ((text_field_days.text) == "8")
    {
    let addinAprel=print(events.filter("dataMonth == %@ && dataDay ==%@",months_arr[3], days_arr[7]))
        print("very good")
        return addinAprel
    }
    if ((text_field_days.text) == "1")
    {
    let addinAprel=print(events.filter("dataMonth == %@ && dataDay ==%@",months_arr[3], days_arr[0]))
        print("very good")
        return addinAprel
    }
    print("good")
}
else{
    print("very bad")
}
}
</code>```

Class SecondController:

```<code>import Foundation
import UIKit
import RealmSwift

class SecondController: UIViewController, UITableViewDelegate {
let realm = try! Realm()

override func viewDidLoad() {
super.viewDidLoad()

}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You select \(massiv[indexPath.row])")

}
}
</code>```

答:
It depends on the flow.
There are multiple options like:

Delegate pattern

Notifications

Passing via segue/unwind segue

Passing via shared entity or service (Singleton for example)

Referencing a ViewController directly

Using storage (UserDefaults, databases etc.)

To answer the question you should provide more context.

From what I see you can use Option 5:
Instantiate SecondController from ViewController (may keep it as a reference in class scope), set the property you want and present/push it. It's the most simple option.

I advise you to read about ViewControllers, Protocols/Delegation, Notifications more.

Body:
there was a similar problem:
There is an object addinAprel in the class ViewController, also there is a class SecondController, it is necessary to transfer this object from one class to another in Swift.

Example programs:

Function in the ViewController class:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print("Selected item is", current_arr[row])
active_textField.text = current_arr[row]
let realm = try! Realm()
let events = realm.objects(EventsDB.self)

if ((text_field_months.text) == "Апрель")
{
    if ((text_field_days.text) == "8")
    {
    let addinAprel=print(events.filter("dataMonth == %@ && dataDay ==%@",months_arr[3], days_arr[7]))
        print("very good")
        return addinAprel
    }
    if ((text_field_days.text) == "1")
    {
    let addinAprel=print(events.filter("dataMonth == %@ && dataDay ==%@",months_arr[3], days_arr[0]))
        print("very good")
        return addinAprel
    }
    print("good")
}
else{
    print("very bad")
}
}

Class SecondController:

import Foundation
import UIKit
import RealmSwift

class SecondController: UIViewController, UITableViewDelegate {
let realm = try! Realm()

override func viewDidLoad() {
super.viewDidLoad()

}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You select \(massiv[indexPath.row])")

}
}


问:
Compare two datetime values in a stored procedure using SQL Server?
Inside the stored procedure's SELECT statement, I have to get the max datetime value.

```<code>((SELECT MAX(MyDateTime)
  FROM MyTable
  WHERE MyId = MM.MyId)) as RecentDateTime,
</code>```

This works. I see the new column with the datetime value in the SQL Server Management Studio grid.

However, I need to compare this value with another datetime value to see if they are equal. I get a syntax error for the following statement inside the SELECT statement

```<code>((SELECT MAX(MyDateTime)
  FROM MyTable
  WHERE MyId = MM.MyId) = MM.MyDateTime) as RecentDateTime,
</code>```

Or:

```<code>@RecentDateTime = ((SELECT MAX(MyDateTime)
                    FROM MyTable
                    WHERE MyId = MM.MyId) = MM.MyDateTime)
</code>```

If I can store the result of the comparison to a variable, I can take this value and compare it to another value.

Not sure why I keep getting the syntax error or how to fix this. Any help is appreciated by a newbie.

答:
I think you want something like

```<code>  DECLARE @maxDate DATETIME
  Select @maxDate = MAX(MyDateTime) from MyTable where MyId = testIdValue
</code>```

Now you can compare with anyother date value using =, < > operators

Body:
Inside the stored procedure's SELECT statement, I have to get the max datetime value.

((SELECT MAX(MyDateTime)
  FROM MyTable
  WHERE MyId = MM.MyId)) as RecentDateTime,

This works. I see the new column with the datetime value in the SQL Server Management Studio grid.

However, I need to compare this value with another datetime value to see if they are equal. I get a syntax error for the following statement inside the SELECT statement

((SELECT MAX(MyDateTime)
  FROM MyTable
  WHERE MyId = MM.MyId) = MM.MyDateTime) as RecentDateTime,

Or:

@RecentDateTime = ((SELECT MAX(MyDateTime)
                    FROM MyTable
                    WHERE MyId = MM.MyId) = MM.MyDateTime)

If I can store the result of the comparison to a variable, I can take this value and compare it to another value.

Not sure why I keep getting the syntax error or how to fix this. Any help is appreciated by a newbie.

Body:
I think you want something like

  DECLARE @maxDate DATETIME
  Select @maxDate = MAX(MyDateTime) from MyTable where MyId = testIdValue

Now you can compare with anyother date value using =, < > operators


问:
Lua script to C++ code
I am writing C functions for Lua.
I have many calls like lua_gettable, lua_touserdata, etc

My C function may receive complex structures like table with tables as fields.

It is hard for me to program stacked machine.

Is there way to write Lua script that would be converted to C code.

Or some other tools that may help me to code such C functions for lua scripts.

Thanks.

PS

Here is example:-

```<code>local data = {}
data.x = {}
data.x.y = 1
myCfunc(data)
</code>```

```<code>int myCfunc(lua_State * L){
 lua_pushstring(L, "x");
 lua_gettable(L, 2);
 lua_pushstring(L, "y");
 lua_gettable(L, -2);
 double y = lua_tonumber(L, -1);
 lua_pop(L, 2);
}
</code>```

instead of

```<code>function myCfunc(data)
 y = data.x.y
end
</code>```

My real code is much more complex and I am looking for some
automated code generation that will help me.

答: Try LuaToCee.</p>

Title: Lua script to C++ code

Body:
I am writing C functions for Lua.
I have many calls like lua_gettable, lua_touserdata, etc

My C function may receive complex structures like table with tables as fields.

It is hard for me to program stacked machine.

Is there way to write Lua script that would be converted to C code.

Or some other tools that may help me to code such C functions for lua scripts.

Thanks.

PS

Here is example:-

local data = {}
data.x = {}
data.x.y = 1
myCfunc(data)

int myCfunc(lua_State * L){
 lua_pushstring(L, "x");
 lua_gettable(L, 2);
 lua_pushstring(L, "y");
 lua_gettable(L, -2);
 double y = lua_tonumber(L, -1);
 lua_pop(L, 2);
}

instead of

function myCfunc(data)
 y = data.x.y
end

My real code is much more complex and I am looking for some
automated code generation that will help me.

Body: Try LuaToCee.


问:
Error deploying thin jar via xldeploy and jenkins on linux server
I have a spring boot/ batch application which is throwing errors when being deployed using jenkins and xldeploy. Its a gradle application.

When I deploy it as a fat jar directly on the server it just works fine, but when I deploy that jar via jenkins and xldeploy it gives me the following error.

Error creating bean with name 'jobOperator' defined in class path
  resource
  [com/one/RetirementConversionImport/standalone/BatchConfiguration.class]:
  Initialization of bean failed; nested exception is
  org.springframework.aop.framework.AopConfigException: Could not
  generate CGLIB subclass of class [class
  com.one.RetirementConversionImport.standalone.BatchConfiguration$1]:
  Common causes of this problem include using a final class or a
  non-visible class; nested exception is
  org.springframework.cglib.core.CodeGenerationException:
  java.lang.reflect.InvocationTargetException-->null
          at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562)
  ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
          at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
  ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
          at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
  ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
          at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
          at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
          at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
  ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
          at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754)
  ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
          at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
  ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
          at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
  ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
          at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
  [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
          at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
  [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
  [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
          at com.paychex.RetirementConversionImport.standalone.RetirementConversionImport.main(RetirementConversionImport.java:85)
  [RetirementConversionImport.jar:?]
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_131]
          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  ~[?:1.8.0_131]
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  ~[?:1.8.0_131]
          at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_131]
          at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
  [spring-boot-devtools-1.4.2.RELEASE.jar:1.4.2.RELEASE] Caused by:
  org.springframework.aop.framework.AopConfigException: Could not
  generate CGLIB subclass of class [class
  com.paychex.RetirementConversionImport.standalone.BatchConfiguration$1]:
  Common causes of this problem include using a final class or a
  non-visible class; nested exception is
  org.springframework.cglib.core.CodeGenerationException:
  java.lang.reflect.InvocationTargetException-->null

答: The root cause was having spring-boot-devtools in the classpath. Removing devtools solved the problem.So basically in this case problem was with AOP proxy .For some reason we have to turn off the AOP proxy which will ensure that it uses a JDK proxy which could be done by removing the spring-boot-devtools jar, the removal of which will start it to  use the native JDK proxy and fix this error.</p>


问:
Background image as banner and the related text to it query
I am here to know where I'm going wrong with the code, I am new to HTML/CSS and trying to Google but no luck.

Issue :

Unable to place image and text as needed.

Image is not replacing itself with mobile version when I'm using media query.

Break-point is around 819px and below for mobile.

This is my code

.main-wrapper {
  max-width: 1300px;
}

img {
  max-width: 100%;
}

.banner-container {
  padding: 150px 0;
  background-repeat: no-repeat !important;
  background-size: cover;
  background-position: center right !important;
  .banner-content {
    color: #3A1F17;
  }
}

@media (max-width: 819px) {
  .banner-container {
    background-image: url("https://serving.photos.photobox.com/00758490381c3770325173d6abe930e9148d8f0582ad2407e9e775d8fe03b471331704e1.jpg") !important;
  }
  .banner-content {
    text-align: center;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='main-wrapper'>
  <div class="banner-container" style="background: url('https://serving.photos.photobox.com/65771836f3f64d3b55f2ce69b7a8e93c69a822788f766366b80f47332a7b4c69dc47e4ef.jpg')">
    <div class="banner-content">
      <h1>Auto-Delivery</h1>
      <p>NEVER RUN OUT OF YOUR FAVORITE MOROCCANOIL <br>PRODUCTS AGAIN.</p>
    </div>
  </div>
</div></code>```

My final design should look like this :

For desktop :

For mobile :

答:
The inline style set on the div itself is overwriting the change you make inside the media query. The easiest (but maybe not cleanest) way to fix this is to add an '!important' flag to the property within the media query like so:</p>

```<code>background-image: url(<url>) !important;
</code>```

Body:
I am here to know where I'm going wrong with the code, I am new to HTML/CSS and trying to Google but no luck.

Issue :

Unable to place image and text as needed.

Image is not replacing itself with mobile version when I'm using media query.

Break-point is around 819px and below for mobile.

This is my code

.main-wrapper {
  max-width: 1300px;
}

img {
  max-width: 100%;
}

.banner-container {
  padding: 150px 0;
  background-repeat: no-repeat !important;
  background-size: cover;
  background-position: center right !important;
  .banner-content {
    color: #3A1F17;
  }
}

@media (max-width: 819px) {
  .banner-container {
    background-image: url("https://serving.photos.photobox.com/00758490381c3770325173d6abe930e9148d8f0582ad2407e9e775d8fe03b471331704e1.jpg") !important;
  }
  .banner-content {
    text-align: center;
  }
}

Auto-Delivery

NEVER RUN OUT OF YOUR FAVORITE MOROCCANOIL
PRODUCTS AGAIN.

My final design should look like this :

For desktop :

For mobile :

Body:
The inline style set on the div itself is overwriting the change you make inside the media query. The easiest (but maybe not cleanest) way to fix this is to add an '!important' flag to the property within the media query like so:

background-image: url(<url>) !important;


问:
Design function so variables get assigned values without large if/else block
There must be a better way to do this:

```<code>def map_leds(self, i):
        if i[0] == 1:
            self.ledg_1_1.setVisible(True)
            self.ledr_1_1.setVisible(False)
        else:
            self.ledg_1_1.setVisible(False)
            self.ledr_1_1.setVisible(True)

###############################################

        if int(i[1]) == 1:
            self.ledg_1_2.setVisible(True)
            self.ledr_1_2.setVisible(False)
        else:
            self.ledg_1_2.setVisible(False)
            self.ledr_1_2.setVisible(True)

###############################################

        if int(i[2]) == 1:
            self.ledg_1_3.setVisible(True)
            self.ledr_1_3.setVisible(False)
        else:
            self.ledg_1_3.setVisible(False)
            self.ledr_1_3.setVisible(True)

###############################################

        if int(i[3]) == 1:
            self.ledg_2_1.setVisible(True)
            self.ledr_2_1.setVisible(False)
        else:
            self.ledg_2_1.setVisible(False)
            self.ledr_2_1.setVisible(True)

###############################################

        if int(i[4]) == 1:
            self.ledg_2_2.setVisible(True)
            self.ledr_2_2.setVisible(False)
        else:
            self.ledg_2_2.setVisible(False)
            self.ledr_2_2.setVisible(True)

###############################################

        if int(i[5]) == 1:
            self.ledg_2_3.setVisible(True)
            self.ledr_2_3.setVisible(False)
        else:
            self.ledg_2_3.setVisible(False)
            self.ledr_2_3.setVisible(True)

###############################################

        if int(i[6]) == 1:
            self.ledg_3_1.setVisible(True)
            self.ledr_3_1.setVisible(False)
        else:
            self.ledg_3_1.setVisible(False)
            self.ledr_3_1.setVisible(True)

###############################################

        if int(i[7]) == 1:
            self.ledg_3_2.setVisible(True)
            self.ledr_3_2.setVisible(False)
        else:
            self.ledg_3_2.setVisible(False)
            self.ledr_3_2.setVisible(True)

###############################################

if int(i[8]) == 1:
            self.ledg_3_3.setVisible(True)
            self.ledr_3_3.setVisible(False)
        else:
            self.ledg_3_3.setVisible(False)
            self.ledr_3_3.setVisible(True)
</code>```

I have 9 LEDS, and I my function map_leds is fed an list of len 9 populated with 0s and 1s. If the first value is 1, the first LED should be green (this is a GUI, so an LED is actually a picture and I have to switch between both pictures, hence the "setVisible" function). If the first value is 0, then the LED (that should be displayed) is the red one. And so on for all the other values.

There must be a better way to actually do all this than have a huge if-else statement block, right?

答:
You want to do three things:

to use the indices

to transform a flat vector into a 3x3 array

to transform int values to boleans

First of all, initialize your led_r as an array:

```<code>self.led_r = []
for i in range(3):
    self.led_r[i] = [your_obj_constructor() for j in range(3)]
</code>```

Now you can use a two-liner:

```<code>for x in range(9):
    self.led_r[x // 3][x % 3].setVisible(i[x] == 1)
</code>```

Body:
There must be a better way to do this:

def map_leds(self, i):
        if i[0] == 1:
            self.ledg_1_1.setVisible(True)
            self.ledr_1_1.setVisible(False)
        else:
            self.ledg_1_1.setVisible(False)
            self.ledr_1_1.setVisible(True)

###############################################

        if int(i[1]) == 1:
            self.ledg_1_2.setVisible(True)
            self.ledr_1_2.setVisible(False)
        else:
            self.ledg_1_2.setVisible(False)
            self.ledr_1_2.setVisible(True)

###############################################

        if int(i[2]) == 1:
            self.ledg_1_3.setVisible(True)
            self.ledr_1_3.setVisible(False)
        else:
            self.ledg_1_3.setVisible(False)
            self.ledr_1_3.setVisible(True)

###############################################

        if int(i[3]) == 1:
            self.ledg_2_1.setVisible(True)
            self.ledr_2_1.setVisible(False)
        else:
            self.ledg_2_1.setVisible(False)
            self.ledr_2_1.setVisible(True)

###############################################

        if int(i[4]) == 1:
            self.ledg_2_2.setVisible(True)
            self.ledr_2_2.setVisible(False)
        else:
            self.ledg_2_2.setVisible(False)
            self.ledr_2_2.setVisible(True)

###############################################

        if int(i[5]) == 1:
            self.ledg_2_3.setVisible(True)
            self.ledr_2_3.setVisible(False)
        else:
            self.ledg_2_3.setVisible(False)
            self.ledr_2_3.setVisible(True)

###############################################

        if int(i[6]) == 1:
            self.ledg_3_1.setVisible(True)
            self.ledr_3_1.setVisible(False)
        else:
            self.ledg_3_1.setVisible(False)
            self.ledr_3_1.setVisible(True)

###############################################

        if int(i[7]) == 1:
            self.ledg_3_2.setVisible(True)
            self.ledr_3_2.setVisible(False)
        else:
            self.ledg_3_2.setVisible(False)
            self.ledr_3_2.setVisible(True)

###############################################

if int(i[8]) == 1:
            self.ledg_3_3.setVisible(True)
            self.ledr_3_3.setVisible(False)
        else:
            self.ledg_3_3.setVisible(False)
            self.ledr_3_3.setVisible(True)

I have 9 LEDS, and I my function map_leds is fed an list of len 9 populated with 0s and 1s. If the first value is 1, the first LED should be green (this is a GUI, so an LED is actually a picture and I have to switch between both pictures, hence the "setVisible" function). If the first value is 0, then the LED (that should be displayed) is the red one. And so on for all the other values.

There must be a better way to actually do all this than have a huge if-else statement block, right?

Body:
You want to do three things:

to use the indices

to transform a flat vector into a 3x3 array

to transform int values to boleans

First of all, initialize your led_r as an array:

self.led_r = []
for i in range(3):
    self.led_r[i] = [your_obj_constructor() for j in range(3)]

Now you can use a two-liner:

for x in range(9):
    self.led_r[x // 3][x % 3].setVisible(i[x] == 1)


问:
Understanding Rabbitmq
I recently came across rabbitmq and after reading some of the docs I had a couple questions that would help me understand how it works.

I was looking at the work queue model, A producer queues a message in to the broker and a worker picks it up, I don't get however how a worker is implemented in a real life situation, does a worker live on a server instance or can a server instance have multiple workers. For example a producer sends a message about an image that needs resizing, will a free server instance listen to the task and preform it?

答:
You really need to kick the tires and try it out to understand more about how the RabbitMQ model works. AMQP is a fairly big standard, so the way in which you use it can vary considerably, there's a lot of flexibility there. The model you outline is just one of many that could work.

A worker's job can be as simple as pulling messages from a queue and performing the work with no other communication. You can attach multiple workers to the same queue to have the work delegated to the first available worker.

If your worker blocks on processing then you'll get the first available worker. If your worker is non-blocking you'll need to be careful to rate-limit how many jobs it accepts or one worker might get greedy and starve all the others for work.

You'll need to experiment with how to do this as it varies considerably based on what RabbitMQ library you're using.

Title: Understanding Rabbitmq


问:
how to accept part of variable(string) as dynamic value in cobol?
I have a field in working storage section WS_CONTRACT_NUM , this has few hard-coded values of leght 15 characters.But first 5 characters could be anything, my question is how can i declare this variable in that case.

```<code>WORKING STORAGE
 01 WS_CONTRACT_NUM PIC X(15) VALUE '?????9999999999' --- > instead of '?' what can i give so that dynamic value can be substituted in my query.
</code>```

And i am performing select query like this :

```<code>EXEC SQL
  SELECT * FROM TABLE WHERE CONTRACT_NUM = :WS_CONTRACT_NUM
END-EXEC
</code>```

Thanks in advance!

答:
You're looking for SQL LIKE, see IBM docs, where

The underscore character (_) represents any single character.
  The percent sign (%) represents a string of zero or more characters.

To use this in COBOL you'd either

```<code>MOVE '_____9999999999' TO WS_CONTRACT_NUM
EXEC SQL
  SELECT * FROM TABLE WHERE CONTRACT_NUM LIKE :WS_CONTRACT_NUM
END-EXEC
</code>```

or (less likely that you want to do it)

```<code>EXEC SQL
  SELECT * FROM TABLE WHERE CONTRACT_NUM LIKE '%9999999999'
END-EXEC
</code>```

or maybe (I have no option to tests this, please report back)

```<code>MOVE '%9999999999' TO WS_CONTRACT_NUM
*> this may search for the trailing spaces,
*> if it does define a smaller variable
EXEC SQL
  SELECT * FROM TABLE WHERE CONTRACT_NUM LIKE :WS_CONTRACT_NUM
END-EXEC
</code>```

Body:
I have a field in working storage section WS_CONTRACT_NUM , this has few hard-coded values of leght 15 characters.But first 5 characters could be anything, my question is how can i declare this variable in that case.

WORKING STORAGE
 01 WS_CONTRACT_NUM PIC X(15) VALUE '?????9999999999' --- > instead of '?' what can i give so that dynamic value can be substituted in my query.

And i am performing select query like this :

EXEC SQL
  SELECT * FROM TABLE WHERE CONTRACT_NUM = :WS_CONTRACT_NUM
END-EXEC

Thanks in advance!

Body:
You're looking for SQL LIKE, see IBM docs, where

The underscore character (_) represents any single character.
  The percent sign (%) represents a string of zero or more characters.

To use this in COBOL you'd either

MOVE '_____9999999999' TO WS_CONTRACT_NUM
EXEC SQL
  SELECT * FROM TABLE WHERE CONTRACT_NUM LIKE :WS_CONTRACT_NUM
END-EXEC

or (less likely that you want to do it)

EXEC SQL
  SELECT * FROM TABLE WHERE CONTRACT_NUM LIKE '%9999999999'
END-EXEC

or maybe (I have no option to tests this, please report back)

MOVE '%9999999999' TO WS_CONTRACT_NUM
*> this may search for the trailing spaces,
*> if it does define a smaller variable
EXEC SQL
  SELECT * FROM TABLE WHERE CONTRACT_NUM LIKE :WS_CONTRACT_NUM
END-EXEC