问:
Setup an MQTT Connection in Android
I am totally new to using MQTT with Android, I am trying this code :

```<code>public class MQTTActivity extends AppCompatActivity {
private HistoryAdapter mAdapter;
MqttAndroidClient mqttAndroidClient;

final String serverUri = "tcp://iot.eclipse.org:1883";

String clientId = "ExampleAndroidClient";
final String subscriptionTopic = "exampleAndroidTopic";
final String publishTopic = "exampleAndroidPublishTopic";
final String publishMessage = "Hello World!";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scrolling);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            publishMessage();
        }
    });

    RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.history_recycler_view);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new HistoryAdapter(new ArrayList<String>());
    mRecyclerView.setAdapter(mAdapter);

    clientId = clientId + System.currentTimeMillis();

    mqttAndroidClient = new MqttAndroidClient(getApplicationContext(), serverUri, clientId);
    mqttAndroidClient.setCallback(new MqttCallbackExtended() {
        @Override
        public void connectComplete(boolean reconnect, String serverURI) {

            if (reconnect) {
                addToHistory("Reconnected to : " + serverURI);
                // Because Clean Session is true, we need to re-subscribe
                subscribeToTopic();
            } else {
                addToHistory("Connected to: " + serverURI);
            }
        }

        @Override
        public void connectionLost(Throwable cause) {
            addToHistory("The Connection was lost.");
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            addToHistory("Incoming message: " + new String(message.getPayload()));
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    });

    MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
    mqttConnectOptions.setAutomaticReconnect(true);
    mqttConnectOptions.setCleanSession(false);

    try {
        //addToHistory("Connecting to " + serverUri);
        mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                disconnectedBufferOptions.setBufferEnabled(true);
                disconnectedBufferOptions.setBufferSize(100);
                disconnectedBufferOptions.setPersistBuffer(false);
                disconnectedBufferOptions.setDeleteOldestMessages(false);
                mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                subscribeToTopic();
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                addToHistory("Failed to connect to: " + serverUri);
            }
        });

    } catch (MqttException ex){
        ex.printStackTrace();
    }

}

private void addToHistory(String mainText){
    System.out.println("LOG: " + mainText);
    mAdapter.add(mainText);
    Snackbar.make(findViewById(android.R.id.content), mainText, Snackbar.LENGTH_LONG)
            .setAction("Action", null).show();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement

    return super.onOptionsItemSelected(item);
}

public void subscribeToTopic(){
    try {
        mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                addToHistory("Subscribed!");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                addToHistory("Failed to subscribe");
            }
        });

        // THIS DOES NOT WORK!
        mqttAndroidClient.subscribe(subscriptionTopic, 0, new IMqttMessageListener() {
            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                // message Arrived!
                System.out.println("Message: " + topic + " : " + new String(message.getPayload()));
            }
        });

    } catch (MqttException ex){
        System.err.println("Exception whilst subscribing");
        ex.printStackTrace();
    }
}

public void publishMessage(){

    try {
        MqttMessage message = new MqttMessage();
        message.setPayload(publishMessage.getBytes());
        mqttAndroidClient.publish(publishTopic, message);
        addToHistory("Message Published");
        if(!mqttAndroidClient.isConnected()){
            addToHistory(mqttAndroidClient.getBufferedMessageCount() + " messages in buffer.");
        }
    } catch (MqttException e) {
        System.err.println("Error Publishing: " + e.getMessage());
        e.printStackTrace();
    }
}}
</code>```

I am getting this exception :

```<code>FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x8000010 (has extras) } in org.eclipse.paho.android.service.MqttService$NetworkConnectionIntentReceiver@41c79f18
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:810)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.SecurityException: Neither user 10083 nor current process has android.permission.WAKE_LOCK.
at android.os.Parcel.readException(Parcel.java:1428)
at android.os.Parcel.readException(Parcel.java:1382)
at android.os.IPowerManager$Stub$Proxy.acquireWakeLock(IPowerManager.java:301)
at android.os.PowerManager$WakeLock.acquireLocked(PowerManager.java:746)
at android.os.PowerManager$WakeLock.acquire(PowerManager.java:715)
at org.eclipse.paho.android.service.MqttService$NetworkConnectionIntentReceiver.onReceive(MqttService.java:821)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:800)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
at dalvik.system.NativeStart.main(Native Method)
</code>```

I already added the Network and the Internet Connection permessions.
I added the mqtt service to my manifest.

I can't seem to get where the code is going wrong ?

答:
The problem is this line from the stack trace:

```<code>Caused by: java.lang.SecurityException: Neither user 10083 nor current process has android.permission.WAKE_LOCK.
</code>```

You need to request the WAKE_LOCK in the manifest as well as the network access.

Title: Setup an MQTT Connection in Android

Body:
I am totally new to using MQTT with Android, I am trying this code :

public class MQTTActivity extends AppCompatActivity {
private HistoryAdapter mAdapter;
MqttAndroidClient mqttAndroidClient;

final String serverUri = "tcp://iot.eclipse.org:1883";

String clientId = "ExampleAndroidClient";
final String subscriptionTopic = "exampleAndroidTopic";
final String publishTopic = "exampleAndroidPublishTopic";
final String publishMessage = "Hello World!";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scrolling);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            publishMessage();
        }
    });

    RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.history_recycler_view);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new HistoryAdapter(new ArrayList<String>());
    mRecyclerView.setAdapter(mAdapter);

    clientId = clientId + System.currentTimeMillis();

    mqttAndroidClient = new MqttAndroidClient(getApplicationContext(), serverUri, clientId);
    mqttAndroidClient.setCallback(new MqttCallbackExtended() {
        @Override
        public void connectComplete(boolean reconnect, String serverURI) {

            if (reconnect) {
                addToHistory("Reconnected to : " + serverURI);
                // Because Clean Session is true, we need to re-subscribe
                subscribeToTopic();
            } else {
                addToHistory("Connected to: " + serverURI);
            }
        }

        @Override
        public void connectionLost(Throwable cause) {
            addToHistory("The Connection was lost.");
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            addToHistory("Incoming message: " + new String(message.getPayload()));
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    });

    MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
    mqttConnectOptions.setAutomaticReconnect(true);
    mqttConnectOptions.setCleanSession(false);

    try {
        //addToHistory("Connecting to " + serverUri);
        mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                disconnectedBufferOptions.setBufferEnabled(true);
                disconnectedBufferOptions.setBufferSize(100);
                disconnectedBufferOptions.setPersistBuffer(false);
                disconnectedBufferOptions.setDeleteOldestMessages(false);
                mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                subscribeToTopic();
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                addToHistory("Failed to connect to: " + serverUri);
            }
        });

    } catch (MqttException ex){
        ex.printStackTrace();
    }

}

private void addToHistory(String mainText){
    System.out.println("LOG: " + mainText);
    mAdapter.add(mainText);
    Snackbar.make(findViewById(android.R.id.content), mainText, Snackbar.LENGTH_LONG)
            .setAction("Action", null).show();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement

    return super.onOptionsItemSelected(item);
}

public void subscribeToTopic(){
    try {
        mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                addToHistory("Subscribed!");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                addToHistory("Failed to subscribe");
            }
        });

        // THIS DOES NOT WORK!
        mqttAndroidClient.subscribe(subscriptionTopic, 0, new IMqttMessageListener() {
            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                // message Arrived!
                System.out.println("Message: " + topic + " : " + new String(message.getPayload()));
            }
        });

    } catch (MqttException ex){
        System.err.println("Exception whilst subscribing");
        ex.printStackTrace();
    }
}

public void publishMessage(){

    try {
        MqttMessage message = new MqttMessage();
        message.setPayload(publishMessage.getBytes());
        mqttAndroidClient.publish(publishTopic, message);
        addToHistory("Message Published");
        if(!mqttAndroidClient.isConnected()){
            addToHistory(mqttAndroidClient.getBufferedMessageCount() + " messages in buffer.");
        }
    } catch (MqttException e) {
        System.err.println("Error Publishing: " + e.getMessage());
        e.printStackTrace();
    }
}}

I am getting this exception :

FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x8000010 (has extras) } in org.eclipse.paho.android.service.MqttService$NetworkConnectionIntentReceiver@41c79f18
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:810)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.SecurityException: Neither user 10083 nor current process has android.permission.WAKE_LOCK.
at android.os.Parcel.readException(Parcel.java:1428)
at android.os.Parcel.readException(Parcel.java:1382)
at android.os.IPowerManager$Stub$Proxy.acquireWakeLock(IPowerManager.java:301)
at android.os.PowerManager$WakeLock.acquireLocked(PowerManager.java:746)
at android.os.PowerManager$WakeLock.acquire(PowerManager.java:715)
at org.eclipse.paho.android.service.MqttService$NetworkConnectionIntentReceiver.onReceive(MqttService.java:821)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:800)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
at dalvik.system.NativeStart.main(Native Method)

I already added the Network and the Internet Connection permessions.
I added the mqtt service to my manifest.

I can't seem to get where the code is going wrong ?

Body:
The problem is this line from the stack trace:

Caused by: java.lang.SecurityException: Neither user 10083 nor current process has android.permission.WAKE_LOCK.

You need to request the WAKE_LOCK in the manifest as well as the network access.


来源: stackexchange

问:
How to remove files from Caches directory in swift 2.3?
The cache.db-wal file have the sensitive information in my application.Need to remove the cache files in Caches directory.</p>

答:
I could find a solution for the above question.</p>

```<code> func removeNetworkCache() {
        let caches = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0])
        let appId = NSBundle.mainBundle().infoDictionary!["CFBundleIdentifier"] as! String
        let path = String(format:"%@/%@/Cache.db-wal",caches, appId)
        do {
            try NSFileManager.defaultManager().removeItemAtPath(path)
        } catch {
           print("ERROR DESCRIPTION: \(error)")
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I could find a solution for the above question.

 func removeNetworkCache() {
        let caches = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0])
        let appId = NSBundle.mainBundle().infoDictionary!["CFBundleIdentifier"] as! String
        let path = String(format:"%@/%@/Cache.db-wal",caches, appId)
        do {
            try NSFileManager.defaultManager().removeItemAtPath(path)
        } catch {
           print("ERROR DESCRIPTION: \(error)")
        }
    }


问:
How to insert multiple, increasing by 1, rows to mysql database with php
I want to add 30 rows to my SQL database. The table has 3 columns: "Year", "Month", "Day". The rows should by added to "Day" column. I use the following code, as I want to do it once. When I post it through RESTeasy I can see in PHPmyadmin that only last row was added, in this case: "2017" "1" "31".

```<code>// Add days in month
$app->post('/api/calendar/add', function (Request $request, Response $response) {
    $year = $request->getParam('Year');
    $month = $request->getParam('Month');
    $day = $request->getParam('Day');

    $day = 1;
    while($day < 31) {
        $day = $day + 1;
        $sql = "INSERT INTO `days` (`Year`, `Month`, `Day`) VALUES ('2017', '1', '$day')";
        };

    try {
        // Get DB Object
        $dbcalendar = new dbcalendar();
        // Connect
        $dbcalendar = $dbcalendar->connect();

        $stmt = $dbcalendar->prepare($sql);

        $stmt->bindParam(':Year', $year);
        $stmt->bindParam('Month', $month);
        $stmt->bindParam('Day', $day);

        $stmt->execute();

        echo '{"notice": {"text": "Days Added"}';

    } catch(PDOException $e) {
        echo '{"error": {"text": '.$e->getMessage().'}';
    }
</code>```

答:
Your $sql variable is being overwritten in each execution of your while loop. Hence, after 31 executions, it looks like :

```<code>INSERT INTO `days` (`Year`, `Month`, `Day`) VALUES ('2017', '1', '31')
</code>```

I can think of at least two different approaches to fix this :

Either put your try...catch statement inside your while. This way, each time the request is built, it is executed.

Or transform your $sql var into an array and add every values set as a new entry, then implode it. This way, you'll have a single SQL request and execution :

```<code>$sql_array = array();
while($day < 31) {
    $day = $day + 1;
    $sql_array[] = "('2017', '1', '$day')";
};
$sql = 'INSERT INTO `days` (`Year`, `Month`, `Day`) VALUES ' . implode(', ', $sql_array);
</code>```

While the first method might be easier to understand, the second one will definitely require less resources and have a shorter execution time.

Body:
I want to add 30 rows to my SQL database. The table has 3 columns: "Year", "Month", "Day". The rows should by added to "Day" column. I use the following code, as I want to do it once. When I post it through RESTeasy I can see in PHPmyadmin that only last row was added, in this case: "2017" "1" "31".

// Add days in month
$app->post('/api/calendar/add', function (Request $request, Response $response) {
    $year = $request->getParam('Year');
    $month = $request->getParam('Month');
    $day = $request->getParam('Day');

    $day = 1;
    while($day < 31) {
        $day = $day + 1;
        $sql = "INSERT INTO `days` (`Year`, `Month`, `Day`) VALUES ('2017', '1', '$day')";
        };

    try {
        // Get DB Object
        $dbcalendar = new dbcalendar();
        // Connect
        $dbcalendar = $dbcalendar->connect();

        $stmt = $dbcalendar->prepare($sql);

        $stmt->bindParam(':Year', $year);
        $stmt->bindParam('Month', $month);
        $stmt->bindParam('Day', $day);

        $stmt->execute();

        echo '{"notice": {"text": "Days Added"}';

    } catch(PDOException $e) {
        echo '{"error": {"text": '.$e->getMessage().'}';
    }

Body:
Your $sql variable is being overwritten in each execution of your while loop. Hence, after 31 executions, it looks like :

INSERT INTO `days` (`Year`, `Month`, `Day`) VALUES ('2017', '1', '31')

I can think of at least two different approaches to fix this :

Either put your try...catch statement inside your while. This way, each time the request is built, it is executed.

Or transform your $sql var into an array and add every values set as a new entry, then implode it. This way, you'll have a single SQL request and execution :

$sql_array = array();
while($day < 31) {
    $day = $day + 1;
    $sql_array[] = "('2017', '1', '$day')";
};
$sql = 'INSERT INTO `days` (`Year`, `Month`, `Day`) VALUES ' . implode(', ', $sql_array);

While the first method might be easier to understand, the second one will definitely require less resources and have a shorter execution time.


问:
MATLAB find cell array substrings in a cell array of strings
Let's say we have a cell array of substrings arrayOfSubstrings = {substr1;substr2} and a cell array of strings arrayOfStrings = {string1;string2;string3;stirng4}. How can I get a logical map into the cell array of strings where at least one of the substrings is found? I have tried

cellfun('isempty',regexp(arrayOfSubstrings ,arrayOfStrings ))

and

cellfun('isempty', strfind(arrayOfSubstrings , arrayOfStrings ))

and some other permutations of functions, but am not getting anywhere.

答:
The issue is that with both strfind and regexp is that you can't provide two cell arrays and have them automatically apply all patterns to all strings. You will need to loop through one or the other to make it work.

You can do this with an explicit loop

```<code>strings = {'ab', 'bc', 'de', 'fa'};
substrs = {'a', 'b', 'c'};

% First you'll want to escape the regular expressions
substrs = regexptranslate('escape', substrs);

matches = false(size(strings));

for k = 1:numel(strings)
    matches(k) = any(~cellfun('isempty', regexp(strings{k}, substrs)));
end

% 1  1  0  1
</code>```

Or if you are for loop-averse you can use cellfun

```<code>cellfun(@(s)any(~cellfun('isempty', regexp(s, substrs))), strings)
% 1  1  0  1
</code>```

A Different Approach

Alternately, you could combine your sub-strings into a single regular expression

```<code>pattern = ['(', strjoin(regexptranslate('escape', substrs), '|'), ')'];
%   (a|b|c)

output = ~cellfun('isempty', regexp(strings, pattern));
%   1  1  0  1
</code>```

Body:
The issue is that with both strfind and regexp is that you can't provide two cell arrays and have them automatically apply all patterns to all strings. You will need to loop through one or the other to make it work.

You can do this with an explicit loop

strings = {'ab', 'bc', 'de', 'fa'};
substrs = {'a', 'b', 'c'};

% First you'll want to escape the regular expressions
substrs = regexptranslate('escape', substrs);

matches = false(size(strings));

for k = 1:numel(strings)
    matches(k) = any(~cellfun('isempty', regexp(strings{k}, substrs)));
end

% 1  1  0  1

Or if you are for loop-averse you can use cellfun

cellfun(@(s)any(~cellfun('isempty', regexp(s, substrs))), strings)
% 1  1  0  1

A Different Approach

Alternately, you could combine your sub-strings into a single regular expression

pattern = ['(', strjoin(regexptranslate('escape', substrs), '|'), ')'];
%   (a|b|c)

output = ~cellfun('isempty', regexp(strings, pattern));
%   1  1  0  1


问:
Observer won't run update in JavaFX GUI
I read much about the JavaFX GUI Model, Plattform->RunLater and Threads, but I still do not figure out how to get this right. I had a JavaFX GUI which on a button click executed a process and updated a Progress Bar and Label. This was running well with Threading and Platform, but I had to Change this to an Observer Model.

I invoke a Progress Tracker in a Singleton Model, which gets updated by the class executing the process and is Observable. I implemented an Observer as well which should update the two UI Elements.

GUI Controller with Button Event

```<code>private void createKeyPressed(ActionEvent event) {

    // Make Progressbar visible
    pbKeyProgress.visibleProperty().set(true);

    if (!Check.keyFileExistant() || cbKeyOverwrite.selectedProperty().get()) {
        ProgressTracker.getTracker().addObserver(new ProgressObserver(pbKeyProgress, lblKeyProgress));
        Creator.createKey(cbKeyLength.getValue());
    } else {
    }
}
</code>```

Progress Observer

```<code>public class ProgressObserver implements Observer {

    private final ProgressBar progressBar;
    private final Label statusLabel;

    public ProgressObserver(ProgressBar progressBar, Label statusLabel) {

        this.progressBar = progressBar;
        this.statusLabel = statusLabel;
    }

    @Override

    public void update(Observable o, Object o1) {
        Platform.runLater(() -> {
            System.out.println("Tracker set to "+ProgressTracker.getProgress() + " " + ProgressTracker.getStatus());
            progressBar.setProgress(ProgressTracker.getProgress());
            statusLabel.setText(ProgressTracker.getStatus());
        });

    }

}
</code>```

Progress Tracker

```<code>    public synchronized void setTracker(int currentStep, String currentStatus) {

    checkInstance();
    instance.step = currentStep;
    instance.status = currentStatus;
    instance.notifyObservers();
    System.out.println(instance.countObservers());
}
</code>```

Creator

```<code>public static void createKey(String length) {

    Task<Void> task;
    task = new Task<Void>() {
        @Override
        public Void call() throws Exception {
            initTracker(0,"Start");
            doStuff();
            ProgressTracker.getTracker().setTracker(1,"First");
            doStuff();
            ProgressTracker.getTracker().setTracker(2,"Second");
            // and so on

            return null;

        }
    };

    new Thread(task)
            .start();

}
</code>```

The Print within the ProgressTracker gets executed. However, if I add a print within the update of the Observer nothing will be printed. If I check within the Progresstracker, the Observer Count is 1.

Why does the Observer not get notified or execute anything, even if the Notify is called? Did I get the Threading and Execution Modell wrong?
The Progress Bar and the Label will also stay on their initial values.

答:
Don't reinvent the wheel. The JavaFX Properties Pattern is a ready-made implementation of the Observable pattern: there is no need to implement it yourself. Additionally, Task already defines methods for updating various properties, which can be called from any thread but will schedule the actual updates on the FX Application Thread. See updateProgress() and updateMessage(), for example.

So you can do, for example:

```<code>public static Task<Void> createKey(String length) {

    Task<Void> task;
    task = new Task<Void>() {

        final int totalSteps = ... ;
        @Override
        public Void call() throws Exception {
            updateProgress(0, totalSteps);
            updateMessage("Start");
            doStuff();
            updateProgress(1, totalSteps);
            updateMessage("First");
            doStuff();
            updateProgress(2, totalSteps);
            updateMessage("Second");
            // and so on

            return null;

        }
    };

    new Thread(task)
            .start();

    return task ;

}
</code>```

and

```<code>private void createKeyPressed(ActionEvent event) {

    // Make Progressbar visible
    pbKeyProgress.visibleProperty().set(true);

    if (!Check.keyFileExistant() || cbKeyOverwrite.selectedProperty().get()) {
        Task<Void> task = Creator.createKey(cbKeyLength.getValue());
        pbKeyProgress.progressProperty().bind(task.progressProperty());
        lblKeyProgress.textProperty().bind(task.messageProperty());
    } else {
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Observer won't run update in JavaFX GUI

Body:
I read much about the JavaFX GUI Model, Plattform->RunLater and Threads, but I still do not figure out how to get this right. I had a JavaFX GUI which on a button click executed a process and updated a Progress Bar and Label. This was running well with Threading and Platform, but I had to Change this to an Observer Model.

I invoke a Progress Tracker in a Singleton Model, which gets updated by the class executing the process and is Observable. I implemented an Observer as well which should update the two UI Elements.

GUI Controller with Button Event

private void createKeyPressed(ActionEvent event) {

    // Make Progressbar visible
    pbKeyProgress.visibleProperty().set(true);

    if (!Check.keyFileExistant() || cbKeyOverwrite.selectedProperty().get()) {
        ProgressTracker.getTracker().addObserver(new ProgressObserver(pbKeyProgress, lblKeyProgress));
        Creator.createKey(cbKeyLength.getValue());
    } else {
    }
}

Progress Observer

public class ProgressObserver implements Observer {

    private final ProgressBar progressBar;
    private final Label statusLabel;

    public ProgressObserver(ProgressBar progressBar, Label statusLabel) {

        this.progressBar = progressBar;
        this.statusLabel = statusLabel;
    }

    @Override

    public void update(Observable o, Object o1) {
        Platform.runLater(() -> {
            System.out.println("Tracker set to "+ProgressTracker.getProgress() + " " + ProgressTracker.getStatus());
            progressBar.setProgress(ProgressTracker.getProgress());
            statusLabel.setText(ProgressTracker.getStatus());
        });

    }

}

Progress Tracker

    public synchronized void setTracker(int currentStep, String currentStatus) {

    checkInstance();
    instance.step = currentStep;
    instance.status = currentStatus;
    instance.notifyObservers();
    System.out.println(instance.countObservers());
}

Creator

public static void createKey(String length) {

    Task<Void> task;
    task = new Task<Void>() {
        @Override
        public Void call() throws Exception {
            initTracker(0,"Start");
            doStuff();
            ProgressTracker.getTracker().setTracker(1,"First");
            doStuff();
            ProgressTracker.getTracker().setTracker(2,"Second");
            // and so on

            return null;

        }
    };

    new Thread(task)
            .start();

}

The Print within the ProgressTracker gets executed. However, if I add a print within the update of the Observer nothing will be printed. If I check within the Progresstracker, the Observer Count is 1.

Why does the Observer not get notified or execute anything, even if the Notify is called? Did I get the Threading and Execution Modell wrong?
The Progress Bar and the Label will also stay on their initial values.

Body:
Don't reinvent the wheel. The JavaFX Properties Pattern is a ready-made implementation of the Observable pattern: there is no need to implement it yourself. Additionally, Task already defines methods for updating various properties, which can be called from any thread but will schedule the actual updates on the FX Application Thread. See updateProgress() and updateMessage(), for example.

So you can do, for example:

public static Task<Void> createKey(String length) {

    Task<Void> task;
    task = new Task<Void>() {

        final int totalSteps = ... ;
        @Override
        public Void call() throws Exception {
            updateProgress(0, totalSteps);
            updateMessage("Start");
            doStuff();
            updateProgress(1, totalSteps);
            updateMessage("First");
            doStuff();
            updateProgress(2, totalSteps);
            updateMessage("Second");
            // and so on

            return null;

        }
    };

    new Thread(task)
            .start();

    return task ;

}

and

private void createKeyPressed(ActionEvent event) {

    // Make Progressbar visible
    pbKeyProgress.visibleProperty().set(true);

    if (!Check.keyFileExistant() || cbKeyOverwrite.selectedProperty().get()) {
        Task<Void> task = Creator.createKey(cbKeyLength.getValue());
        pbKeyProgress.progressProperty().bind(task.progressProperty());
        lblKeyProgress.textProperty().bind(task.messageProperty());
    } else {
    }
}


问:
Request Tracker 4.2.8 PHP REST API download attachment
I am trying to download attachments from RT 4.2.8 tickets using PHP REST API (https://github.com/dersam/RTPHPLib).
I've used Ticket Attachment Content and Ticket Attachment. They return some kind of string or array like this (basically it outputs the file content):

```<code>   Array
(
    [%PDF-1.4
%����
] =>
    [10 0 obj
<>
endobj

] =>
    [15 0 obj
<>/Filter/FlateDecode/ID[<4DCDA9C01A05A34BB7A89B62345FD905><4DCDA9C01A05A34BB7A89B62345FD905>]/Index[10 7]/Info 9 0 R/Length 36/Prev 805889/Root 11 0 R/Size 17/Type/XRef/W[1 2 0]>>stream
] =>
    [h�bbd`b`�db`�eb`����^��"��
] =>
    [endstream
endobj
startxref
] =>
    [0
] =>
    [%%EOF
] =>
    [16 0 obj
<>stream
] =>
    [h�b```f``����33 �������L f(f`�ca```h�o�1���iF �`�] =>
    [O
] =>
    [endstream
endobj
11 0 obj
<>
endobj
12 0 obj
<>>>/Rotate 270/Type/Page>>
endobj
</code>```

I've tried to write this with php fwrite/file_put_contents to a tmp file and then download it, but it won't open.

How can I download the ticket attachments locally? I want this to be dynamic (no matter the file extension)

答:
For binary content, it is necessary to make an additional call to getAttachmentContent. This will return the file contents in their original encoding.

The issue comes from RT using UTF-8 in its response, which also encodes the Content section. Unfortunately, RT does not store the original encoding of the attachment, resulting in an unreliable Content section, making it impossible for RTPHPLib to guess intelligently.

See https://github.com/dersam/RTPHPLib/issues/66 for some recent discussion on this.

Body:
I am trying to download attachments from RT 4.2.8 tickets using PHP REST API (https://github.com/dersam/RTPHPLib).
I've used Ticket Attachment Content and Ticket Attachment. They return some kind of string or array like this (basically it outputs the file content):

   Array
(
    [%PDF-1.4
%����
] =>
    [10 0 obj
<>
endobj

] =>
    [15 0 obj
<>/Filter/FlateDecode/ID[<4DCDA9C01A05A34BB7A89B62345FD905><4DCDA9C01A05A34BB7A89B62345FD905>]/Index[10 7]/Info 9 0 R/Length 36/Prev 805889/Root 11 0 R/Size 17/Type/XRef/W[1 2 0]>>stream
] =>
    [h�bbd`b`�db`�eb`����^��"��
] =>
    [endstream
endobj
startxref
] =>
    [0
] =>
    [%%EOF
] =>
    [16 0 obj
<>stream
] =>
    [h�b```f``����33 �������L f(f`�ca```h�o�1���iF �`�] =>
    [O
] =>
    [endstream
endobj
11 0 obj
<>
endobj
12 0 obj
<>>>/Rotate 270/Type/Page>>
endobj

I've tried to write this with php fwrite/file_put_contents to a tmp file and then download it, but it won't open.

How can I download the ticket attachments locally? I want this to be dynamic (no matter the file extension)


问:
Converting date in excel
I need to convert the below date format in excel.

Currently I have: Fri Jan 06 05:10:31 2017

Current Format : ddd MMM dd hh:mm:ss yyyy

I wanted to be in the following format: dd/mm/yyyy hh:mm:ss

答:
If you are running into trouble with regional DMY vs. MDY system settings, parse it out longhand so no interpretation is performed; i.e. give the conversion no options.

```<code>=DATEVALUE(REPLACE(MID(A2, 4, LEN(A2)), 8, 9, ","))+TIMEVALUE(MID(A2, 12, 8))
</code>```

Title: Converting date in excel

Body:
If you are running into trouble with regional DMY vs. MDY system settings, parse it out longhand so no interpretation is performed; i.e. give the conversion no options.

=DATEVALUE(REPLACE(MID(A2, 4, LEN(A2)), 8, 9, ","))+TIMEVALUE(MID(A2, 12, 8))


问:
Click event doesn't work after append
I want to dynamic click on first click of paragraph but its not working.

$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = 'Youre clicked';
    $('body').append(append_code);
    $(".hrefclick").click();

    $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="newclass">
  Hit me!
</p></code>```

js Fiddle

答:
$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = 'Youre clicked';
    $('body').append(append_code);
    $(".hrefclick").click();

    $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });
    $('.hrefclick').trigger('click');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="newclass">
  Hit me!
</p></code>```

Title: Click event doesn't work after append

Body:
I want to dynamic click on first click of paragraph but its not working.

$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = 'Youre clicked';
    $('body').append(append_code);
    $(".hrefclick").click();

    $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });
  });
});

  Hit me!

js Fiddle

Body:
$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>';
    $('body').append(append_code);
    $(".hrefclick").click();

    $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });
    $('.hrefclick').trigger('click');
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="newclass">
  Hit me!
</p>


答:
Correct query </p>

```<code>SELECT
         p1.onr,
         p1.prSh,
         p1.liteNr,
         p1.seqNr,
         p1.planQty
    FROM
        pf_pqs p1
        INNER JOIN (
            SELECT
                onr,
                liteNr,
                MAX(seqNr) AS seqNr
            FROM
                pf_pqs
            GROUP BY
                liteNr
        ) p2 ON
        p2.liteNr = p1.liteNr
        AND p2.seqNr = p1.seqNr
        AND p2.onr=p1.onr
</code>```

Title: MySQL select distinct and max with all columns

Body:
I have a db table: pf_pqs:

+----------+------+--------+-------+---------+
|    onr   | prSh | liteNr | seqNr | planQty |
+----------+------+--------+-------+---------+
| 10347006 | HEG  |    1   |    0  |   5     |
| 10347006 | TEH  |    1   |    1  |   5     |
| 10347006 | KAR  |    1   |    2  |   5     |
| 10347006 | LEN  |    1   |    3  |   5     |
| 10347006 | HEG  |    2   |    0  |   5     |
| 10347006 | LEN  |    2   |    1  |   5     |
| 10347006 | HEG  |    3   |    0  |   5     |
| 10347006 | TEH  |    3   |    1  |   5     |
| 10347006 | KAR  |    3   |    2  |   5     |
| 10347006 | LEN  |    3   |    3  |   5     |

Result must include biggest seqNr in every liteNr and all other corresponding fields correctly; like this:

+----------+------+--------+-------+---------+
|    onr   | prSh | liteNr | seqNr | planQty |
+----------+------+--------+-------+---------+
| 10347006 | LEN  |    1   |    3  |   5     |
| 10347006 | LEN  |    2   |    1  |   5     |
| 10347006 | LEN  |    3   |    3  |   5     |

I tried different queries with joins and grouping but no luck so far :(.
Thanks in advance.

Body:
Correct query

SELECT
         p1.onr,
         p1.prSh,
         p1.liteNr,
         p1.seqNr,
         p1.planQty
    FROM
        pf_pqs p1
        INNER JOIN (
            SELECT
                onr,
                liteNr,
                MAX(seqNr) AS seqNr
            FROM
                pf_pqs
            GROUP BY
                liteNr
        ) p2 ON
        p2.liteNr = p1.liteNr
        AND p2.seqNr = p1.seqNr
        AND p2.onr=p1.onr


问:
Reorganize/reshape data frame
I have a data frame of live trapping. There are two systems, each with different status. The week and the number of individuals in each status is given.

```<code>df <- data.frame (sys = rep(c("a","b"), each=3),
              sta = rep(c("L","T","P"), times=2),
              w01 = c("0","2","5","2","2","5"),
              w02 = c("3","2","2","4","6","1"),
              w03 = c("4","1","0","5","3","0"))
df
sys  sta  w01  w02  w03
a    L    0    3    4
a    T    2    2    1
a    P    5    2    0
b    L    2    4    5
b    T    2    6    3
b    P    5    1    0
</code>```

I want a data frame showing for each number the system and status. The Result would look like this:

```<code>sys sta Num
a   L   0
a   L   3
a   L   4
a   T   2
a   T   2
a   T   1
a   P   5
a   P   2
a   P   0
b   L   2
b   L   4
b   L   5
b   T   2
b   T   6
b   T   3
b   P   5
b   P   1
b   P   0
</code>```

I have absolutely no idea how doing this. I found this two questions/answers
Reorganise 2x36 dataframe to a 6x6 dataframe. Dice throw visualisation
Reshaping data.frame from wide to long format
but cannot find a way to fit it for my problem.
Also i tried reshape but direction = "wide" does not give the output I need and I am sucked with the varying part of direction = "long". Here is what I tried, but did not work...

```<code>a <- as.vector(colnames(df[-c(1,2)]))
df2 <- reshape(df, idvar = "sys", timevar = "sta", varying = a , direction = "long")
</code>```

Any suggestions how I can solve this problem?
Thank you all and kind regards!

P.S.: I need the "new format" of my dataset for a friedman test (friedman.test). Will it work out in this way?

答:
With tidyr and dplyr:

```<code>library(tidyr)
library(dplyr)

df %>%
    gather(key, value, -sys, -sta) %>%
    select(-key) %>%
    arrange(sys, sta)

#>    sys sta value
#> 1    a   L     0
#> 2    a   L     3
#> 3    a   L     4
#> 4    a   P     5
#> 5    a   P     2
#> 6    a   P     0
#> 7    a   T     2
#> 8    a   T     2
#> 9    a   T     1
#> 10   b   L     2
#> 11   b   L     4
#> 12   b   L     5
#> 13   b   P     5
#> 14   b   P     1
#> 15   b   P     0
#> 16   b   T     2
#> 17   b   T     6
#> 18   b   T     3
</code>```

Title: Reorganize/reshape data frame

Body:
I have a data frame of live trapping. There are two systems, each with different status. The week and the number of individuals in each status is given.

df <- data.frame (sys = rep(c("a","b"), each=3),
              sta = rep(c("L","T","P"), times=2),
              w01 = c("0","2","5","2","2","5"),
              w02 = c("3","2","2","4","6","1"),
              w03 = c("4","1","0","5","3","0"))
df
sys  sta  w01  w02  w03
a    L    0    3    4
a    T    2    2    1
a    P    5    2    0
b    L    2    4    5
b    T    2    6    3
b    P    5    1    0

I want a data frame showing for each number the system and status. The Result would look like this:

sys sta Num
a   L   0
a   L   3
a   L   4
a   T   2
a   T   2
a   T   1
a   P   5
a   P   2
a   P   0
b   L   2
b   L   4
b   L   5
b   T   2
b   T   6
b   T   3
b   P   5
b   P   1
b   P   0

I have absolutely no idea how doing this. I found this two questions/answers
Reorganise 2x36 dataframe to a 6x6 dataframe. Dice throw visualisation
Reshaping data.frame from wide to long format
but cannot find a way to fit it for my problem.
Also i tried reshape but direction = "wide" does not give the output I need and I am sucked with the varying part of direction = "long". Here is what I tried, but did not work...

a <- as.vector(colnames(df[-c(1,2)]))
df2 <- reshape(df, idvar = "sys", timevar = "sta", varying = a , direction = "long")

Any suggestions how I can solve this problem?
Thank you all and kind regards!

P.S.: I need the "new format" of my dataset for a friedman test (friedman.test). Will it work out in this way?

Body:
With tidyr and dplyr:

library(tidyr)
library(dplyr)

df %>%
    gather(key, value, -sys, -sta) %>%
    select(-key) %>%
    arrange(sys, sta)

#>    sys sta value
#> 1    a   L     0
#> 2    a   L     3
#> 3    a   L     4
#> 4    a   P     5
#> 5    a   P     2
#> 6    a   P     0
#> 7    a   T     2
#> 8    a   T     2
#> 9    a   T     1
#> 10   b   L     2
#> 11   b   L     4
#> 12   b   L     5
#> 13   b   P     5
#> 14   b   P     1
#> 15   b   P     0
#> 16   b   T     2
#> 17   b   T     6
#> 18   b   T     3


问:
how to write rspec for method
I have following code in programmability folder

```<code>module Programmability
  module Parameter
    class Input < Parameter::Base
      attr_reader :args

  def initialize(name, type, **args)
    super(name, type)
    @args = args
  end

  def value=(val)
    if val
      val = convert_true_false(val)
--- some code ----
    end
    @value = val
  end

  def convert_true_false(val)
    return val unless @args[:limit] == 1
    if [:char].include?(@type) && val == 'true'
      'Y'
    elsif [:char].include?(@type) && val == 'false'
      'N'
    elsif [:bit].include?(@type) && val == 'true'
      1
    elsif [:bit].include?(@type) && val == 'false'
      0
    end
  end
end
  end
end
</code>```

I am trying to write rspec for method convert_true_false. I am new to rspec. any help is appreciated.

I tried doing this

```<code>   context 'returns Y if passed true'
    input = Programmability::Parameter::Input.new(name, type, limit)

      it 'returns Y' do
        name = 'unregister_series'
        type = ':char'
        limit = 1

        expect(input.value = 'true' ).to eq('Y')
      end
  end
</code>```

but its not picking up limit value. when it reaches convert_true_false method it comes out of it since @args[:limit] is nil

Thanks

答:
The issue is that setters always return the value passed:

```<code>class Test
  def foo=(foo)
    @foo = foo + 100
    return 42
  end
end

puts (Test.new.foo = 69) # 69
</code>```

To resolve it, simply check the value after you assigned it:

```<code># instead of
expect(input.value = 'true').to eq 'Y'

# do
input.value = 'true'
expect(input.value).to eq 'Y'
</code>```

Title: how to write rspec for method

Body:
I have following code in programmability folder

module Programmability
  module Parameter
    class Input < Parameter::Base
      attr_reader :args

  def initialize(name, type, **args)
    super(name, type)
    @args = args
  end

  def value=(val)
    if val
      val = convert_true_false(val)
--- some code ----
    end
    @value = val
  end

  def convert_true_false(val)
    return val unless @args[:limit] == 1
    if [:char].include?(@type) && val == 'true'
      'Y'
    elsif [:char].include?(@type) && val == 'false'
      'N'
    elsif [:bit].include?(@type) && val == 'true'
      1
    elsif [:bit].include?(@type) && val == 'false'
      0
    end
  end
end
  end
end

I am trying to write rspec for method convert_true_false. I am new to rspec. any help is appreciated.

I tried doing this

   context 'returns Y if passed true'
    input = Programmability::Parameter::Input.new(name, type, limit)

      it 'returns Y' do
        name = 'unregister_series'
        type = ':char'
        limit = 1

        expect(input.value = 'true' ).to eq('Y')
      end
  end

but its not picking up limit value. when it reaches convert_true_false method it comes out of it since @args[:limit] is nil

Thanks

Body:
The issue is that setters always return the value passed:

class Test
  def foo=(foo)
    @foo = foo + 100
    return 42
  end
end

puts (Test.new.foo = 69) # 69

To resolve it, simply check the value after you assigned it:

# instead of
expect(input.value = 'true').to eq 'Y'

# do
input.value = 'true'
expect(input.value).to eq 'Y'


问:
Build directory structure from file list with windows components and scripting tools
I need some help with building of directory structure from the list of files. It should be some graphic view (html or windows form), support unicode and be quick. File list is not exact files/directories structure, just some random files in some random folders.

Let's say I have a file where file names listed:

\\srv1\ndisk\finance\1.xtx

\\srv1\ndisk\finance\2.xtx

\\srv1\ndisk\bookkeepers\3.xtx

\\srv1\ndisk\bookkeepers\4.xtx

\\srv1\ndisk\ceo\5.xtx

And I want to get something like this:

```<code>-srv1
   -ndisk
      -finance
          1.xtx
          2.xtx
      -bookkeepers
          3.xtx
          4.xtx
      -ceo
          5.xtx
</code>```

I'm not developer actually, so I should rely on scripting languages, like powershell, vbs and so on. Maybe there are some components that can just build this tree from file list that I have?

答:
Use the tree commandline instruction, from within a standard windows commandline prompt. E.g.

```<code>TREE /F C:\Temp
</code>```

Body:
I need some help with building of directory structure from the list of files. It should be some graphic view (html or windows form), support unicode and be quick. File list is not exact files/directories structure, just some random files in some random folders.

Let's say I have a file where file names listed:

\\srv1\ndisk\finance\1.xtx

\\srv1\ndisk\finance\2.xtx

\\srv1\ndisk\bookkeepers\3.xtx

\\srv1\ndisk\bookkeepers\4.xtx

\\srv1\ndisk\ceo\5.xtx

And I want to get something like this:

-srv1
   -ndisk
      -finance
          1.xtx
          2.xtx
      -bookkeepers
          3.xtx
          4.xtx
      -ceo
          5.xtx

I'm not developer actually, so I should rely on scripting languages, like powershell, vbs and so on. Maybe there are some components that can just build this tree from file list that I have?

Body:
Use the tree commandline instruction, from within a standard windows commandline prompt. E.g.

TREE /F C:\Temp


问:
getting this error "Missing compatible node-ios-device library" in appcelator studio
Missing compatible node-ios-device library
2017-01-12T14:10:20.735Z | TRACE  | Error: Missing compatible node-ios-device library
   at loadIosDeviceModule (/Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/node_modules/node-ios-device/ios-device.js:49:9)
   at Object.devices (/Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/node_modules/node-ios-device/ios-device.js:66:2)
   at Object.detect (/Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/lib/device.js:68:12)
   at devices (/Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/index.js:102:11)
   at /Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/node_modules/async/lib/async.js:570:21
   at /Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/node_modules/async/lib/async.js:249:17
   at /Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/node_modules/async/lib/async.js:125:13
   at Array.forEach (native)
   at _each (/Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/node_modules/async/lib/async.js:46:24)
   at async.each (/Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/node_modules/async/lib/async.js:124:9)
   at _asyncMap (/Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/node_modules/async/lib/async.js:248:13)
   at Object.map (/Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/node_modules/async/lib/async.js:219:23)
   at _parallel (/Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/node_modules/async/lib/async.js:568:20)
   at Object.async.parallel (/Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/node_modules/async/lib/async.js:598:9)
   at Object.detect (/Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/node_modules/ioslib/index.js:94:8)

   at iOSBuilder. (/Users/salam/Library/Application Support/Titanium/mobilesdk/osx/3.5.0.GA/iphone/cli/commands/_build.js:292:10)

at Object.run (/Users/salam/.appcelerator/install/6.1.0/package/node_modules/node-appc/lib/subprocess.js:59:8)
   at find (/Users/salam/.appcelerator/install/6.1.0/package/node_modules/node-appc/lib/subprocess.js:96:14)
   at /Users/salam/.appcelerator/install/6.1.0/package/node_modules/async/lib/async.js:987:13
   at Immediate.q.process [as _onImmediate] (/Users/salam/.appcelerator/install/6.1.0/package/node_modules/async/lib/async.js:953:21)
   at processImmediate [as _immediateCallback] (timers.js:383:17)

答: I found this post. See if it helps. Reinstalling Appcelerator</p>


问:
Angular 2 - How can I alert a value from @Input()
I pass an object to my component using:

```<code>@Input() passValues;
</code>```

Further down in that object I have a nested object called "charts".

How can I alert the key of "balance" on ngOnInit of the component. I.e.

```<code>ngOnInit() {
alert(passValues.charts.balance);
}
</code>```

Doing it like the above causes errors.

答:
Try using AfterViewInit

```<code>input { AfterViewInit } from '@angular/core';
</code>```

and then in your component:

```<code>ngAfterViewInit () {
    alert(passValues.charts.balance);
}
</code>```

Body:
I pass an object to my component using:

@Input() passValues;

Further down in that object I have a nested object called "charts".

How can I alert the key of "balance" on ngOnInit of the component. I.e.

ngOnInit() {
alert(passValues.charts.balance);
}

Doing it like the above causes errors.

Body:
Try using AfterViewInit

input { AfterViewInit } from '@angular/core';

and then in your component:

ngAfterViewInit () {
    alert(passValues.charts.balance);
}


问:
Capture everything enclosed by parenthesis
I am trying to build a regex that captures successfully the following bolded text:

background-image: url(
  https://domain/adress/with/other/stuff?alsoaquerystring=whynot );

Expected output is:

https://domain/adress/with/other/stuff?alsoaquerystring=whynot

And this is what I have tried so far, but I can't manage to say "capture everything that's inside here, no matter what characters it has got".

```<code>/background-image: url\((?P<image>)+\)/;
</code>```

It needs to be compatible with PHP preg_replace().

答:
You can use:

```<code>background-image: url\((.*?)\);
</code>```

By using ( ) you are creating a capture group in regex.

See https://regex101.com/r/VNsTPU/1/ as an example. It's a very basic example, you can improve to strip out white space between parentheses or just trim after you are done.

See this answer about using capture groups with PHP, if you are unfamiliar.

Update: If you are trying to do it with preg_replace this is how you would do it:

```<code>$regex = = 'background-image: url\((.*?)\);';
$var = 'background-image: url( https://domain/adress/with/other/stuff?alsoaquerystring=whynot )';
preg_replace($regex,'$1',$var);
</code>```

Body:
I am trying to build a regex that captures successfully the following bolded text:

background-image: url(
  https://domain/adress/with/other/stuff?alsoaquerystring=whynot );

Expected output is:

https://domain/adress/with/other/stuff?alsoaquerystring=whynot

And this is what I have tried so far, but I can't manage to say "capture everything that's inside here, no matter what characters it has got".

/background-image: url\((?P<image>)+\)/;

It needs to be compatible with PHP preg_replace().

Body:
You can use:

background-image: url\((.*?)\);

By using ( ) you are creating a capture group in regex.

See https://regex101.com/r/VNsTPU/1/ as an example. It's a very basic example, you can improve to strip out white space between parentheses or just trim after you are done.

See this answer about using capture groups with PHP, if you are unfamiliar.

Update: If you are trying to do it with preg_replace this is how you would do it:

$regex = = 'background-image: url\((.*?)\);';
$var = 'background-image: url( https://domain/adress/with/other/stuff?alsoaquerystring=whynot )';
preg_replace($regex,'$1',$var);


问:
using indexers in c# to get values from struct
I have defined a struct as follows:

```<code>using System;
using System.Collections.Generic;
public struct PacketPenetration
{
    private Dictionary<double, double[,]> penetration;
    public PacketPenetration(Dictionary<double, double[,]> penetration)
    {
        this.penetration = penetration;
    }

    public Dictionary<double, double[,]> Penetration { get { return penetration; } }

    public double this[double index1, int index2, int index3]
    {
        get
        {
            return this.penetration[index1][index2,index3];
        }
    }
}
</code>```

and instantiated like this:

```<code>var penetration = new PacketPenetration();
</code>```

my goal is to be able to add items to penetration and be able to get values from it using the indexer defined in the struct. However The following line of code does not work:

```<code>penetration.Add(3.5, testArray);
</code>```

testArray is a double[,]
Where is the problem?

答:
You have two things to first:

var penetration = new PacketPenetration(); ==> var penetration = new PacketPenetration(initializedDictionary);
Calling parameter-less constructor will not initialize penetration dictionary. Hence NullReferenceException

penetration.Add(3.5, testArray); ==> penetration.Penetration.Add(3.5, testArray);
Or define Add method for the struct

Body:
I have defined a struct as follows:

using System;
using System.Collections.Generic;
public struct PacketPenetration
{
    private Dictionary<double, double[,]> penetration;
    public PacketPenetration(Dictionary<double, double[,]> penetration)
    {
        this.penetration = penetration;
    }

    public Dictionary<double, double[,]> Penetration { get { return penetration; } }

    public double this[double index1, int index2, int index3]
    {
        get
        {
            return this.penetration[index1][index2,index3];
        }
    }
}

and instantiated like this:

var penetration = new PacketPenetration();

my goal is to be able to add items to penetration and be able to get values from it using the indexer defined in the struct. However The following line of code does not work:

penetration.Add(3.5, testArray);

testArray is a double[,]
Where is the problem?


问:
With a single 6-faced dice, calculate the possible ways to reach a certain number
I have the following Java assignment. In a board game I can roll a 6-faced dice and move forward the same number of spaces. If the goal is “n” spaces away from the starting point, how do I implement a program that calculates all possible ways there are to arrive exactly at the "n"? I'm squeezing my head but I can't find the solution, I have searched the net but nothing is what I want exactly. I know it's not that hard, I just can't find the correct way to do it.

Thanks in advance.

答:
There are multiple ways to do this, so I'm going to keep it generic.
Determine all possible permutations, storing the values. Generate a roll, getting the total. Sift through the permutations that match the total.</p>

```<code>class Roll {
    int first;
    int second;
    int total;

    public Roll(int first, int second) {
        this.first = first;
        this.second = second;
        this.total = first + second;
     }

 List<Roll> permutations = new ArrayList<>();
 for (int ii = 1; ii < 7; ii++)
     for (int jj = 1; jj < 7; jj++)
         permutations.add(new Roll(ii,jj);

 roll the dice, determine the total;
 now loop through the permutations to find the
   total matching the roll total. These are your combinations.
   This solution doesn't handle duplicate rolls. For example 1,6 and 6,1;
</code>```

Body:
There are multiple ways to do this, so I'm going to keep it generic.
Determine all possible permutations, storing the values. Generate a roll, getting the total. Sift through the permutations that match the total.

class Roll {
    int first;
    int second;
    int total;

    public Roll(int first, int second) {
        this.first = first;
        this.second = second;
        this.total = first + second;
     }

 List<Roll> permutations = new ArrayList<>();
 for (int ii = 1; ii < 7; ii++)
     for (int jj = 1; jj < 7; jj++)
         permutations.add(new Roll(ii,jj);

 roll the dice, determine the total;
 now loop through the permutations to find the
   total matching the roll total. These are your combinations.
   This solution doesn't handle duplicate rolls. For example 1,6 and 6,1;


问:
Opening document from a stream
Is there a way to open a presentation from a stream, memory file or isolated storage?

I have a presentation file that I want to open in PowerPoint, but do not want to allow user to access the file itself. Unfortunately the Presentations.Open() function of PowerPoint (and Open() of all other Office applications) only accepts a path parameter, which means I must save the file somewhere on the disk and then open it in PowerPoint, which will consequently give user access to the file.

Has anyone done this in any Office application?

答:
You can use the OpenXML SDK to open documents from a stream, but not from within an Office application.

But, if you're motivated enough, you could delete the file after it's closed. It's pretty simple, you just need to create a separate process and wait for the file to not be locked for writing any more. Or, if you know when it's closed (e.g. if you do the closing in code), you may not need a separate process.

Title: Opening document from a stream


问:
Excel: Lookup matching cell in a table and return the value of the first cell in the row
Here is a picture to demonstrate:

So from this, we can see Item 9 belongs to Category C. I want to find a formulas to automate this process. Where if I provide excel with a number, say 12, it will be able to give me "D."

Unfortunately, this is not possible with VLookUp nor HLookUp as they require the matching value to be on the left side of the table. I've tried with Index / Match, but that seems to spit out an error instead.

Am I approaching this wrong? Should I reformat the table or is there a better formula to use?

答:
Use INDEX with AGGREGATE:

```<code>=INDEX(A:A,AGGREGATE(15,6,ROW($B$2:$E$5)/($B$2:$E$5 = 12),1))
</code>```

You can change the 12 to a cell reference to make it more dynamic.

Body:
Use INDEX with AGGREGATE:

=INDEX(A:A,AGGREGATE(15,6,ROW($B$2:$E$5)/($B$2:$E$5 = 12),1))

You can change the 12 to a cell reference to make it more dynamic.


问:
Compile subsection of Jinja2 AST
Can one compile or revert a portion of the Jinja2 AST?

For example, is it possible to call a function or method from jinja2.environment or jinja2.compiler.generate or some equivalent on a list of nodes extracted from within a template?

For example, given a template y.html:

```<code>avant-tag
{% xyz %}
tag content {{ 3 + 5 }}
{% endxyz %}
apres-tag
</code>```

and an extension y.py:

```<code># -*- coding: utf-8 -*-
from jinja2 import nodes, Environment, FileSystemLoader
from jinja2.ext import Extension

class YExtension(Extension):
    tags = set(['y'])

    def __init__(self, environment):
        super(YExtension, self).__init__(environment)

    def parse(self, parser):
        tag = parser.stream.next()
        body = parser.parse_statements(['name:endy'], drop_needle=True)
        return nodes.Const("<!-- slurping: %s -->" % str(body))

env = Environment(
    loader      = FileSystemLoader('.'),
    extensions  = [YExtension],
    )

print env.get_template('x.html').render()
</code>```

Running python y.py results in the expected output of:

```<code>avant-tag
 <!-- slurping: [Output(nodes=[TemplateData(data=u'\n    tag-content '),
   Add(left=Const(value=3), right=Const(value=5)),
   TemplateData(data=u'\n ')])] -->
sous-tag
</code>```

In the parse method, how can one either:

compile body to unicode (i.e. tag-content 8); or, alternatively

revert body to its original source (i.e. tag-content {{ 3 + 5 }}).

As a matter of background, this question relates to two prior questions:

Jinja2 compile extension after includes; and

Insert javascript at top of including file in Jinja 2

Thank you for reading.

Brian

答:
Compiling to unicode is not yet possible in the parse() method since you don't have the context available at that point. You can hack around it ofcourse but it would probably not be the best way to go.

Note that the parse() step is normally only executed once on a html file, after that it will use the parsed bytecode to render the template. The results of the parse step can be rendered given an environment.

You simply don't have the context available there, and getting the context in there... quite difficult ;)

To get the original source however... not much easier without hacking, but the hacking isn't too bad ;)

```<code>class YExtension(Extension):
    tags = set(['y'])

    def preprocess(self, source, name, filename=None):
        # insert some code here that replaces '{% xyz %}foo bar{% endxyz %}'
        # with something like: '{% xyz %}foo bar{% raw %}foo bar{% endraw %}{% endxyz %}'
        return source
</code>```

After that you can read the text as the value from the {% raw %} node. Be sure to trash it after that or it will show in your template.

ContentLicense: CC BY-SA 2.5

Title: Compile subsection of Jinja2 AST

Body:
Can one compile or revert a portion of the Jinja2 AST?

For example, is it possible to call a function or method from jinja2.environment or jinja2.compiler.generate or some equivalent on a list of nodes extracted from within a template?

For example, given a template y.html:

avant-tag
{% xyz %}
tag content {{ 3 + 5 }}
{% endxyz %}
apres-tag

and an extension y.py:

# -*- coding: utf-8 -*-
from jinja2 import nodes, Environment, FileSystemLoader
from jinja2.ext import Extension

class YExtension(Extension):
    tags = set(['y'])

    def __init__(self, environment):
        super(YExtension, self).__init__(environment)

    def parse(self, parser):
        tag = parser.stream.next()
        body = parser.parse_statements(['name:endy'], drop_needle=True)
        return nodes.Const("" % str(body))

env = Environment(
    loader      = FileSystemLoader('.'),
    extensions  = [YExtension],
    )

print env.get_template('x.html').render()

Running python y.py results in the expected output of:

avant-tag

sous-tag

In the parse method, how can one either:

compile body to unicode (i.e. tag-content 8); or, alternatively

revert body to its original source (i.e. tag-content {{ 3 + 5 }}).

As a matter of background, this question relates to two prior questions:

Jinja2 compile extension after includes; and

Insert javascript at top of including file in Jinja 2

Thank you for reading.

Brian

Body:
Compiling to unicode is not yet possible in the parse() method since you don't have the context available at that point. You can hack around it ofcourse but it would probably not be the best way to go.

Note that the parse() step is normally only executed once on a html file, after that it will use the parsed bytecode to render the template. The results of the parse step can be rendered given an environment.

You simply don't have the context available there, and getting the context in there... quite difficult ;)

To get the original source however... not much easier without hacking, but the hacking isn't too bad ;)

class YExtension(Extension):
    tags = set(['y'])

    def preprocess(self, source, name, filename=None):
        # insert some code here that replaces '{% xyz %}foo bar{% endxyz %}'
        # with something like: '{% xyz %}foo bar{% raw %}foo bar{% endraw %}{% endxyz %}'
        return source

After that you can read the text as the value from the {% raw %} node. Be sure to trash it after that or it will show in your template.


问:
two view controllers are not segue same view controller one is working another is not working swift 3
i have two view controller both are of same type and both have some detail view page view. and both have different segue name but one is going to the detail page and another isnt going throwing some error.
can somebody help me with this problem ?

Segue which is not working

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "showQueueDetails"){

        let indexPath = self.tableView.indexPathForSelectedRow!

        // sending data from tableviews to DetailTableView
        let passingData = segue.destination as! QueueDetailViewController
        // Getting the complete CoreData Object and passing it to the detail view
        passingData.data = coreDataArray[indexPath.row]

        self.tableView.deselectRow(at: indexPath, animated: true)
    }
}
</code>```

segue which is working

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "showDetails"){

        // var upcoming: NewViewController = segue.destination as! NewViewController
        let indexPath = self.tableView.indexPathForSelectedRow!
        //let titleString = self.objects.objects(at: sender.row) as? String

        // sending data from tableviews to DetailTableView
        let passingData = segue.destination as! RecentScansDetailViewController
        // Getting the complete CoreData Object and passing it to the detail view
        passingData.data = coreDataArray[indexPath.row]

        // upcoming.titleString = titleString
        self.tableView.deselectRow(at: indexPath, animated: true)
    }
}
</code>```

error which i am getting

storyboard

i want to have same controller to go to another view controller
but while coming back it should automatically know which view controller it should go back

答:
Your output indicates that your seque with identifier "showQueueDetails" has a targetViewController of type "RecentScansDetailViewController" (the same you got for the seque "showDetails".

Make sure that the seque with Identifier "showQueueDetails" really points to the targetViewController of type "QueueDetailViewController" as you also cast it to in your code.

Go back to your storyboard and have a look for

the seque itself

the targetViewController's Class of your seque with identifier "showQueueDetails" - maybe you copied your "RecentScansDetailViewController"-ViewController and did not update its class.

Body:
i have two view controller both are of same type and both have some detail view page view. and both have different segue name but one is going to the detail page and another isnt going throwing some error.
can somebody help me with this problem ?

Segue which is not working

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "showQueueDetails"){

        let indexPath = self.tableView.indexPathForSelectedRow!

        // sending data from tableviews to DetailTableView
        let passingData = segue.destination as! QueueDetailViewController
        // Getting the complete CoreData Object and passing it to the detail view
        passingData.data = coreDataArray[indexPath.row]

        self.tableView.deselectRow(at: indexPath, animated: true)
    }
}

segue which is working

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "showDetails"){

        // var upcoming: NewViewController = segue.destination as! NewViewController
        let indexPath = self.tableView.indexPathForSelectedRow!
        //let titleString = self.objects.objects(at: sender.row) as? String

        // sending data from tableviews to DetailTableView
        let passingData = segue.destination as! RecentScansDetailViewController
        // Getting the complete CoreData Object and passing it to the detail view
        passingData.data = coreDataArray[indexPath.row]

        // upcoming.titleString = titleString
        self.tableView.deselectRow(at: indexPath, animated: true)
    }
}

error which i am getting

storyboard

i want to have same controller to go to another view controller
but while coming back it should automatically know which view controller it should go back


答:
You are doing everything correct except one thing - You are declaring event handler of your second click after the click itself. So, when second click is triggered, you don't have handler declared yet and you don't see any alert.
I rearranged it below. Trying running the below snippet.

$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = 'Youre clicked';
    $('body').append(append_code);

      //on click event handler should be declared first before clicking
     $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });

    $(".hrefclick").click();

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="newclass">
  Hit me!
</p></code>```

Title: Click event doesn't work after append

Body:
I want to dynamic click on first click of paragraph but its not working.

$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = 'Youre clicked';
    $('body').append(append_code);
    $(".hrefclick").click();

    $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });
  });
});

  Hit me!

js Fiddle

Body:
You are doing everything correct except one thing - You are declaring event handler of your second click after the click itself. So, when second click is triggered, you don't have handler declared yet and you don't see any alert.
I rearranged it below. Trying running the below snippet.

$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>';
    $('body').append(append_code);

      //on click event handler should be declared first before clicking
     $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });

    $(".hrefclick").click();

  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="newclass">
  Hit me!
</p>


问:
How do you make a custom auto complete component in Flex?
I need to make an auto complete component in flex that fetches the auto complete results from a remote database using a webservice.  I have the webservice and querying part worked out.  I've already made custom components in action script by extending VBoxes.  However I cannot figure out how to generate the popup window that is supposed to show under the text input in my auto complete text box.

Currently I am using something like

```<code>PopUpManager.addPopUp(popup, parentComponent);
</code>```

My popup class extends VBox and it extends the createChildren method as follows

```<code>protected override function createChildren():void
{
  for (var i:int = 0; i < results.length; i++) {
    var itemC:UIComponent =
        factory.getComponent(results[i]);
    addChild(itemC);
    itemC.addEventListener(MouseEvent.CLICK,
        getClickFunction(i));
}

private function getClickFunction(index:int):Function {
    return function (event:MouseEvent):void
        {
            selectedIndex = index;
        };
}
</code>```

Unfortunately when the webservice retrieves its results and addPopUp is called, nothing shows up.

Currently the factory.getComponent method is executing this code

```<code>public function getComponent(user:Object):UIComponent
{
    var email:Label = new Label();
    email.text = user.email;
    var name:Label = new Label();
    name.text = user.displayName;
    var vbox:VBox = new VBox();
    vbox.addChild(name);
    vbox.addChild(email);
    return vbox;
}
</code>```

答:
I think you ought to look for someone who has already implemented this.  While your issue is probably related to not positioning and sizing the component before calling addPopup() even if we helped you solve that you still have a lot more work todo.  (BTW call super.createChildren in your override or else bad things will happen).  Anyway, check this out:

http://www.adobe.com/cfusion/exchange/index.cfm?event=extensionDetail&extid=1047291

Body:
I need to make an auto complete component in flex that fetches the auto complete results from a remote database using a webservice.  I have the webservice and querying part worked out.  I've already made custom components in action script by extending VBoxes.  However I cannot figure out how to generate the popup window that is supposed to show under the text input in my auto complete text box.

Currently I am using something like

PopUpManager.addPopUp(popup, parentComponent);

My popup class extends VBox and it extends the createChildren method as follows

protected override function createChildren():void
{
  for (var i:int = 0; i < results.length; i++) {
    var itemC:UIComponent =
        factory.getComponent(results[i]);
    addChild(itemC);
    itemC.addEventListener(MouseEvent.CLICK,
        getClickFunction(i));
}

private function getClickFunction(index:int):Function {
    return function (event:MouseEvent):void
        {
            selectedIndex = index;
        };
}

Unfortunately when the webservice retrieves its results and addPopUp is called, nothing shows up.

Currently the factory.getComponent method is executing this code

public function getComponent(user:Object):UIComponent
{
    var email:Label = new Label();
    email.text = user.email;
    var name:Label = new Label();
    name.text = user.displayName;
    var vbox:VBox = new VBox();
    vbox.addChild(name);
    vbox.addChild(email);
    return vbox;
}


问:
DataStudio holds connections to DB2 database
I run my queries on DB2 Datastudio. I start with "connect"ing to the database... and over a period of time.. say, I run 100+ queries on the same connection over multiple days.

On the database side, we see 100+ connections coming from me. I don't understand how 1 connection on my side can become 100+ connections on the database side? I use DataStudio v4.1.0.1. Please help..

答: In your SQL editor, head to configuration and pick "Use the existing connection". That should help fix it.</p>


问:
How can I allow a method to accept either a string or int?
Using C# 4.0, is there a way to allow a method (without creating an overload) to accept a string or an int and then allow me to detect what type was passed in?</p>

答:
I would think a method overload would be a straightforward solution, if you want to stay away from stuff like reflection or checking types.</p>

```<code>public void MethodName(string foo)
{
     int bar = 0;
     if(int.tryparse(foo))
        return MethodName(bar);//calls int overload
}
</code>```

Body:
I would think a method overload would be a straightforward solution, if you want to stay away from stuff like reflection or checking types.

public void MethodName(string foo)
{
     int bar = 0;
     if(int.tryparse(foo))
        return MethodName(bar);//calls int overload
}


问:
How to make .BAT file delete it self after completion?
How to make .BAT file delete it self after completion? I have a simple bat file that terminates a process. I want that .BAT file to delete itself.</p>

答:
You could also direct the output of the DEL "%~f0"  to NULL output like so...

```<code>@ECHO OFF
SETLOCAL
SET someOtherProgram=SomeOtherProgram.exe
TASKKILL /IM "%someOtherProgram%"
DEL "%~f0" > NUL
</code>```

Body:
You could also direct the output of the DEL "%~f0"  to NULL output like so...

@ECHO OFF
SETLOCAL
SET someOtherProgram=SomeOtherProgram.exe
TASKKILL /IM "%someOtherProgram%"
DEL "%~f0" > NUL


问:
Declaring a Task Property and awaiting it
I'm stuck in something I thought so simple that it drives me out of myself.

I need to declare a Task in some point and run it later, I thought of:

```<code>Task T1 { get; set; }

public async Task CreateAndAwaitAsync()
{
    T1 = new Task(() => {
        // time consuming work like:
        System.Threading.Thread.Sleep(1000);
    }

    await T1;
}
</code>```

Of course the body of the lambda AND the method are just for the sake of this example (as I said I need to run it later), but no matter what, with await T1 I just cannot make it into the lambda! What am I missing?? I feel stupid because I have been using the async-await paradigm for quite the few years already that I didn't even imagine this wouldn't work!

答:
Unless you are doing CPU-bound work you almost never need to call Task.Run but can just use async/await like:

```<code>  public async Task DelayMe()
  {
    await Task.Delay(1000);
    await MoreAsyncThings();
  }

  Task T1 { get; set; }

  public async Task CreateAndAwaitAsync()
  {
    T1 = DelayMe();
    await T1;
  }
</code>```

Update:

To store code for later execution I would propose to simple use a lambda like:

```<code>Func<Task> SomeWorkFactory()
{
  return async () =>
  {
    await AsyncStuff();
    // More Stuff
  };
}

var deferedWork = SomeWorkFactory();

// later somewhere else

await deferedWork();
</code>```

So basically calling "SomeWorkFactory" creates the work package but only calling the Func executes it and also returns an awaitable Task.

Maybe relevant:

If you provide methods which do CPU-bound work (like calculating something as opposed to waiting for a callback) you should not offer an async signature at all but leave the execution mode to the caller. Mainly because asynchronism and concurrency are different concepts. Mads Torgersen gave some insights on this here: https://channel9.msdn.com/Events/TechEd/NorthAmerica/2014/DEV-B362 and calls it "library methods should not lie" (From minute 42)

Body:
I'm stuck in something I thought so simple that it drives me out of myself.

I need to declare a Task in some point and run it later, I thought of:

Task T1 { get; set; }

public async Task CreateAndAwaitAsync()
{
    T1 = new Task(() => {
        // time consuming work like:
        System.Threading.Thread.Sleep(1000);
    }

    await T1;
}

Of course the body of the lambda AND the method are just for the sake of this example (as I said I need to run it later), but no matter what, with await T1 I just cannot make it into the lambda! What am I missing?? I feel stupid because I have been using the async-await paradigm for quite the few years already that I didn't even imagine this wouldn't work!

Body:
Unless you are doing CPU-bound work you almost never need to call Task.Run but can just use async/await like:

  public async Task DelayMe()
  {
    await Task.Delay(1000);
    await MoreAsyncThings();
  }

  Task T1 { get; set; }

  public async Task CreateAndAwaitAsync()
  {
    T1 = DelayMe();
    await T1;
  }

Update:

To store code for later execution I would propose to simple use a lambda like:

Func<Task> SomeWorkFactory()
{
  return async () =>
  {
    await AsyncStuff();
    // More Stuff
  };
}

var deferedWork = SomeWorkFactory();

// later somewhere else

await deferedWork();

So basically calling "SomeWorkFactory" creates the work package but only calling the Func executes it and also returns an awaitable Task.

Maybe relevant:

If you provide methods which do CPU-bound work (like calculating something as opposed to waiting for a callback) you should not offer an async signature at all but leave the execution mode to the caller. Mainly because asynchronism and concurrency are different concepts. Mads Torgersen gave some insights on this here: https://channel9.msdn.com/Events/TechEd/NorthAmerica/2014/DEV-B362 and calls it "library methods should not lie" (From minute 42)


问:
Example to read from KafkaSpout and write same back to Kafka Bolt
I am trying to write a Storm based code which reads the message from one topic and writes back to another topic. Input topic has data in ProtoBuf format and output will have JSON format. I am not able to achieve it.

This is code which build the topology:

```<code>    Config conf = new Config();
    //set producer properties.
    Properties props = new Properties();
    props.put("bootstrap.servers", "localhost:9093");
    props.put("request.required.acks", "1");
    props.put("key.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
    props.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
    conf.put("kafka.broker.config", props);
    conf.put(KafkaBolt.TOPIC, "out-storm");
    KafkaBolt bolt = new KafkaBolt()
            .withProducerProperties(props)
            .withTopicSelector(new DefaultTopicSelector("out-storm")).withTupleToKafkaMapper(new FieldNameBasedTupleToKafkaMapper<String, String>());

    BrokerHosts hosts = new ZkHosts("localhost:2181");
    SpoutConfig spoutConfig = new SpoutConfig(hosts, "incoming-server", "/" + "incoming-server",
            UUID.randomUUID().toString());
    spoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme());
    KafkaSpout kafkaSpout = new KafkaSpout(spoutConfig);
    TopologyBuilder builder = new TopologyBuilder();
    builder.setSpout("kafka-spout", kafkaSpout);
    builder.setBolt("lookup-bolt", new ReportBolt(),4).shuffleGrouping("kafka-spout");
    builder.setBolt("kafka-producer-spout", bolt).shuffleGrouping("lookup-bolt");
    LocalCluster cluster = new LocalCluster();
    Config config = new Config();
    config.setDebug(true);
    config.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, 1);
    config.put("kafka.broker.config", props);
    config.put(KafkaBolt.TOPIC, "out-storm");
    cluster.submitTopology("KafkaStormSample", config, builder.createTopology());
    Thread.sleep(1000000);
</code>```

In report Bolt I have done this:

```<code>    System.out.println("HELLO " + input);
    JSONObject jo= new JSONObject();
    for (String f:input.getFields()){
        jo.put(f, input.getValueByField(f));
    }
    collector.ack(input);
    List<Object> list = new ArrayList<Object>();
    list.add(jo);
    collector.emit(list);
</code>```

When I am starting getting this error:

```<code>      5207 [main] WARN  o.a.s.d.nimbus - Topology submission exception. (topology name='KafkaStormSample') #error {
 :cause nil
 :via
 [{:type org.apache.storm.generated.InvalidTopologyException
   :message nil
   :at [org.apache.storm.daemon.common$validate_structure_BANG_ invoke common.clj 181]}]
 :trace
 [[org.apache.storm.daemon.common$validate_structure_BANG_ invoke common.clj 181]
  [org.apache.storm.daemon.common$system_topology_BANG_ invoke common.clj 360]
  [org.apache.storm.daemon.nimbus$fn__7064$exec_fn__2461__auto__$reify__7093 submitTopologyWithOpts nimbus.clj 1512]
  [org.apache.storm.daemon.nimbus$fn__7064$exec_fn__2461__auto__$reify__7093 submitTopology nimbus.clj 1544]
  [sun.reflect.NativeMethodAccessorImpl invoke0 NativeMethodAccessorImpl.java -2]
  [sun.reflect.NativeMethodAccessorImpl invoke NativeMethodAccessorImpl.java 62]
  [sun.reflect.DelegatingMethodAccessorImpl invoke DelegatingMethodAccessorImpl.java 43]
  [java.lang.reflect.Method invoke Method.java 497]
  [clojure.lang.Reflector invokeMatchingMethod Reflector.java 93]
  [clojure.lang.Reflector invokeInstanceMethod Reflector.java 28]
  [org.apache.storm.testing$submit_local_topology invoke testing.clj 301]
  [org.apache.storm.LocalCluster$_submitTopology invoke LocalCluster.clj 49]
  [org.apache.storm.LocalCluster submitTopology nil -1]
  [com.mediaiq.StartStorm main StartStorm.java 81]]}
</code>```

答: I think that the problem is that you are referencing the wrong port on your bootstrap.server config. Try changing it to the 9092.</p>

Body:
I am trying to write a Storm based code which reads the message from one topic and writes back to another topic. Input topic has data in ProtoBuf format and output will have JSON format. I am not able to achieve it.

This is code which build the topology:

    Config conf = new Config();
    //set producer properties.
    Properties props = new Properties();
    props.put("bootstrap.servers", "localhost:9093");
    props.put("request.required.acks", "1");
    props.put("key.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
    props.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
    conf.put("kafka.broker.config", props);
    conf.put(KafkaBolt.TOPIC, "out-storm");
    KafkaBolt bolt = new KafkaBolt()
            .withProducerProperties(props)
            .withTopicSelector(new DefaultTopicSelector("out-storm")).withTupleToKafkaMapper(new FieldNameBasedTupleToKafkaMapper<String, String>());

    BrokerHosts hosts = new ZkHosts("localhost:2181");
    SpoutConfig spoutConfig = new SpoutConfig(hosts, "incoming-server", "/" + "incoming-server",
            UUID.randomUUID().toString());
    spoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme());
    KafkaSpout kafkaSpout = new KafkaSpout(spoutConfig);
    TopologyBuilder builder = new TopologyBuilder();
    builder.setSpout("kafka-spout", kafkaSpout);
    builder.setBolt("lookup-bolt", new ReportBolt(),4).shuffleGrouping("kafka-spout");
    builder.setBolt("kafka-producer-spout", bolt).shuffleGrouping("lookup-bolt");
    LocalCluster cluster = new LocalCluster();
    Config config = new Config();
    config.setDebug(true);
    config.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, 1);
    config.put("kafka.broker.config", props);
    config.put(KafkaBolt.TOPIC, "out-storm");
    cluster.submitTopology("KafkaStormSample", config, builder.createTopology());
    Thread.sleep(1000000);

In report Bolt I have done this:

    System.out.println("HELLO " + input);
    JSONObject jo= new JSONObject();
    for (String f:input.getFields()){
        jo.put(f, input.getValueByField(f));
    }
    collector.ack(input);
    List<Object> list = new ArrayList<Object>();
    list.add(jo);
    collector.emit(list);

When I am starting getting this error:

      5207 [main] WARN  o.a.s.d.nimbus - Topology submission exception. (topology name='KafkaStormSample') #error {
 :cause nil
 :via
 [{:type org.apache.storm.generated.InvalidTopologyException
   :message nil
   :at [org.apache.storm.daemon.common$validate_structure_BANG_ invoke common.clj 181]}]
 :trace
 [[org.apache.storm.daemon.common$validate_structure_BANG_ invoke common.clj 181]
  [org.apache.storm.daemon.common$system_topology_BANG_ invoke common.clj 360]
  [org.apache.storm.daemon.nimbus$fn__7064$exec_fn__2461__auto__$reify__7093 submitTopologyWithOpts nimbus.clj 1512]
  [org.apache.storm.daemon.nimbus$fn__7064$exec_fn__2461__auto__$reify__7093 submitTopology nimbus.clj 1544]
  [sun.reflect.NativeMethodAccessorImpl invoke0 NativeMethodAccessorImpl.java -2]
  [sun.reflect.NativeMethodAccessorImpl invoke NativeMethodAccessorImpl.java 62]
  [sun.reflect.DelegatingMethodAccessorImpl invoke DelegatingMethodAccessorImpl.java 43]
  [java.lang.reflect.Method invoke Method.java 497]
  [clojure.lang.Reflector invokeMatchingMethod Reflector.java 93]
  [clojure.lang.Reflector invokeInstanceMethod Reflector.java 28]
  [org.apache.storm.testing$submit_local_topology invoke testing.clj 301]
  [org.apache.storm.LocalCluster$_submitTopology invoke LocalCluster.clj 49]
  [org.apache.storm.LocalCluster submitTopology nil -1]
  [com.mediaiq.StartStorm main StartStorm.java 81]]}


问:
Unit Testing Visual Studio Online Selenium ChromeDriver Exception
I use Selenium ChromeDriver in a Unit Test project to test some action on a web page ...

var chromeDriver = new ChromeDriver();
 chromeDriver.Navigate().GoToUrl("https://www.google.com");

Chrome driver has been installed from nuget

Install-Package Selenium.WebDriver.ChromeDriver -Version 2.28.0.

When build my project in Visual Studio Online I receive some error:

System.InvalidOperationException: unknown error: cannot find Chrome binary
  (Driver info: chromedriver=2.28.455520

Any solution to solve this?

答:
I don't use the command line to install things for NuGet, I use the menu option in VS.

Open VS and click on your project in the Solution Explorer.

Click on Project > Manage NuGet Packages... from the menu,

See what shows as installed here and if there are any updates. You might try uninstalling and reinstall via the menu I described above and see if it helps. I use NuGet as described all the time and don't have this issue.


问:
How to animate SVG polygon points?
I have created a line chart with SVG (polygon points) that I would like animated.

I would like the points to all start animating from the X axis, and when finished animating, the result to look like the following image.

It seems there is no simple way to achieve this, with the googling I have done. Any tips would be most appreciated, thanks.

答:
What do you mean by "animating from the X axis" exactly?  Do you mean start flat and grow upwards to this shape?

If so, it is actually very easy.

<svg viewBox="0 0 2040 352">
  <defs>
  </defs>

  <polygon points="" fill="red">
     <animate attributeName="points" dur="1s" fill="freeze"
              from="0,352, 550,352, 1240,352, 1592,352, 1880,352, 2040,352,
                   2040,352,0,352"
              to="0,292, 550,232, 1240,258, 1592,158, 1880,168, 2040,0,
                   2040,352,0,352"/>
  </polygon>
</svg>```

This example uses vanilla SVG SMIL animations.  You can also use one of a number of SVG graphing or animation libraries.

Title: How to animate SVG polygon points?

Body:
What do you mean by "animating from the X axis" exactly?  Do you mean start flat and grow upwards to this shape?

If so, it is actually very easy.

<svg viewBox="0 0 2040 352">
  <defs>
  </defs>

  <polygon points="" fill="red">
     <animate attributeName="points" dur="1s" fill="freeze"
              from="0,352, 550,352, 1240,352, 1592,352, 1880,352, 2040,352,
                   2040,352,0,352"
              to="0,292, 550,232, 1240,258, 1592,158, 1880,168, 2040,0,
                   2040,352,0,352"/>
  </polygon>
</svg>

This example uses vanilla SVG SMIL animations.  You can also use one of a number of SVG graphing or animation libraries.


问:
XSD : how to validate this xml, with sequences depending on the value of the first one?
I have 3 kinds of XML blocks, containing no "filter" block, or "filter" with "invalidation" whose first value is either "fixed1" or "fixed2"; if "fixed1": nothing else, if "fixed2", this sequence A1,A2,A3 (see below) :

```<code>        <filter>
          <invalidation>fixed1</invalidation>
        </filter>

        <filter>
          <invalidation>fixed2</invalidation>
          <A1>string...</A1>
          <A2>string...</A2>
          <A2>string...</A3>
        </filter>
</code>```

How to validate this ? I feel that there is some solution using xs:choice, but I couldn't find.

The only (poor) solution I found is :

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
...
<xs:simpleType name="invalidation">
  <xs:restriction base="xs:string">
    <xs:pattern value="fixed1|fixed2"/>
  </xs:restriction>
</xs:simpleType>
...
<xs:element name="filter" minOccurs="0">
  <xs:complexType>
    <xs:all>
      <xs:element name="invalidation" type="invalidation"/>
      <xs:element name="A1" type="xs:string" minOccurs="0"/>
      <xs:element name="A2" type="xs:string" minOccurs="0"/>
      <xs:element name="A3" type="xs:string" minOccurs="0"/>
    </xs:all>
  </xs:complexType>
</xs:element>
</code>```

答:
This cannot be done in XSD 1.0.

It can be done in XSD 1.1 using assertions. Define the structure as a sequence with the content model (invalidation, (A1, A2, A3)?) and then define an assertion: not(invalidation='fixed1' and exists(A1)).

XSD 1.1 is supported in Altova, Saxon, and Apache Xerces, but not in other products such as the built-in validators in Java and .NET.

Body:
I have 3 kinds of XML blocks, containing no "filter" block, or "filter" with "invalidation" whose first value is either "fixed1" or "fixed2"; if "fixed1": nothing else, if "fixed2", this sequence A1,A2,A3 (see below) :

        <filter>
          <invalidation>fixed1</invalidation>
        </filter>

        <filter>
          <invalidation>fixed2</invalidation>
          <A1>string...</A1>
          <A2>string...</A2>
          <A2>string...</A3>
        </filter>

How to validate this ? I feel that there is some solution using xs:choice, but I couldn't find.

The only (poor) solution I found is :

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
...
<xs:simpleType name="invalidation">
  <xs:restriction base="xs:string">
    <xs:pattern value="fixed1|fixed2"/>
  </xs:restriction>
</xs:simpleType>
...
<xs:element name="filter" minOccurs="0">
  <xs:complexType>
    <xs:all>
      <xs:element name="invalidation" type="invalidation"/>
      <xs:element name="A1" type="xs:string" minOccurs="0"/>
      <xs:element name="A2" type="xs:string" minOccurs="0"/>
      <xs:element name="A3" type="xs:string" minOccurs="0"/>
    </xs:all>
  </xs:complexType>
</xs:element>


问:
Scalling site to mobile scale
How to make scaling div? (look screenshots)
i want to make background on all device this same scale.

enter image description here

enter image description here

I'm trying
 and to div in css add background-size in % or give auto but dont work

答:
https://plnkr.co/edit/vtV1sxA85EKCUPlRpoRo?p=preview

the following properties makes your picture occupy the entire div on which the background is applied

```<code>background: #ffffff url("https://placebear.com/700/700") no-repeat
center center fixed;
background-size:100% 100%;
</code>```

let me know if it this is what you wanted

Title: Scalling site to mobile scale

Body:
https://plnkr.co/edit/vtV1sxA85EKCUPlRpoRo?p=preview

the following properties makes your picture occupy the entire div on which the background is applied

background: #ffffff url("https://placebear.com/700/700") no-repeat
center center fixed;
background-size:100% 100%;

let me know if it this is what you wanted