问:
C: sorting 2d arrays row by row using qsort
So, what I'm trying to achieve here, is to use the C implementation of qsort in a 2d array, in witch I want only the rows to be sorted based on the its first element, for example:

```<code>        int arr[3][2]={{65,1},
                       {45,2},
                       {66,3}}
</code>```

I want the output to be:

```<code>        int arr[3][2]={{45,2},
                       {65,1},
                       {66,3}}
</code>```

Is there a way of doing this without implementing quicksort myself? If so, how?

EDIT

This is what my code looks like:

```<code>int f(int a, int b)
{
return a-b;
}

qsort(arr[0],3,sizeof(int),f);
</code>```

答:
Here is the problem:

```<code>qsort(arr[0],3,sizeof(int),f);
</code>```

This function take size_t as the second argument. You have passed 3. Thats not the size, thats count of elements in the array arr. In a crude way, you need something like 3*sizeof(int). Or better sizeof(arr) / sizeof *arr.
So, change it to

```<code>qsort(arr, sizeof(arr) / sizeof *arr, sizeof(int), sizeof *arr, comparator);
</code>```

With:

```<code>int comparator(const void *p, const void *q)
{
    // Get the values at given addresses
    int l = *(const int *)p;
    int r = *(const int *)q;

    // both odd, put the greater of two first.
    if ((l&1) && (r&1))
        return (r-l);

    // both even, put the smaller of two first
    if ( !(l&1) && !(r&1) )
        return (l-r);

    // l is even, put r first
    if (!(l&1))
        return 1;

    // l is odd, put l first
    return -1;
}
</code>```

Body:
So, what I'm trying to achieve here, is to use the C implementation of qsort in a 2d array, in witch I want only the rows to be sorted based on the its first element, for example:

        int arr[3][2]={{65,1},
                       {45,2},
                       {66,3}}

I want the output to be:

        int arr[3][2]={{45,2},
                       {65,1},
                       {66,3}}

Is there a way of doing this without implementing quicksort myself? If so, how?

EDIT

This is what my code looks like:

int f(int a, int b)
{
return a-b;
}

qsort(arr[0],3,sizeof(int),f);

Body:
Here is the problem:

qsort(arr[0],3,sizeof(int),f);

This function take size_t as the second argument. You have passed 3. Thats not the size, thats count of elements in the array arr. In a crude way, you need something like 3*sizeof(int). Or better sizeof(arr) / sizeof *arr.
So, change it to

qsort(arr, sizeof(arr) / sizeof *arr, sizeof(int), sizeof *arr, comparator);

With:

int comparator(const void *p, const void *q)
{
    // Get the values at given addresses
    int l = *(const int *)p;
    int r = *(const int *)q;

    // both odd, put the greater of two first.
    if ((l&1) && (r&1))
        return (r-l);

    // both even, put the smaller of two first
    if ( !(l&1) && !(r&1) )
        return (l-r);

    // l is even, put r first
    if (!(l&1))
        return 1;

    // l is odd, put l first
    return -1;
}


来源: stackexchange

问:
Set Context properties when receive FtpDownload stream
I'm working on a solution to create a scheduled task in BizTalk with the taskscheduler adapter.
With a C# component I've created the FTPDownload function which returns a stream.

I'm now running into the following problem.
I need to get the filename as a mark on the stream, so I can read this in another solution to get the right output filename.

For the solution to read out the filename I make use of the context properties of the BizTalk message and it would be great if I can set the filename back into the context properties when I read the FTP into the stream.

```<code>public class FTPReceive : IScheduledTaskStreamProvider
    {
        private readonly string TASK_COMPONENT_NAME = "ScheduledTask FTPReceive";

        public Type GetParameterType()
        {
            return typeof(FTPReceiveArguments);
        }

        public Stream GetStream(object args)
        {
            int retryCounter = 1;
            bool isDownloaded = false;
            Stream responseStream = null;

            FTPReceiveArguments parameter = (FTPReceiveArguments) args;

            if (string.IsNullOrWhiteSpace(parameter.Url))
            {
                throw new ArgumentNullException(TASK_COMPONENT_NAME, "URL is null or Empty");
            }

            while (!isDownloaded && retryCounter <= parameter.RetryCount)
            {
                try
                {
                    FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(@parameter.Url);
                    ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                    ftpRequest.Credentials = new NetworkCredential(parameter.Username, parameter.Password);

                    FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                    ftpResponse.Headers.Add("Content-disposition", "inline; filename=fileName.ext");
                    //ftpResponse.Headers.Add("fileNameTest.xml");
                    responseStream = ftpResponse.GetResponseStream();
                    //responseStream.
                    isDownloaded = true;
                }
                catch (WebException wex)
                {
                    if ((retryCounter +1) <= parameter.RetryCount)
                    {
                        Thread.Sleep(parameter.RetryInterval * 60000);
                    }
                    else
                    {
                        // Only Log Information to prevent the adapter will be disabled!
                    }

                    retryCounter++;
                }
                catch (Exception ex)
                {
                    // Do nothing, otherwise the adapter will be disabled!
                }
            }

            if (isDownloaded && responseStream != null)
            {

                return responseStream;
            }

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

答:
Unfortunately, the out of the box STA does not have the ability to pass Context values from the provider to the Message.

You can however modify the Adapter to do this by modifying (Non)TransactionalTasks and your provider to return an Object containing both the stream and property bag.

You then write the properties to the created Message.

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a solution to create a scheduled task in BizTalk with the taskscheduler adapter.
With a C# component I've created the FTPDownload function which returns a stream.

I'm now running into the following problem.
I need to get the filename as a mark on the stream, so I can read this in another solution to get the right output filename.

For the solution to read out the filename I make use of the context properties of the BizTalk message and it would be great if I can set the filename back into the context properties when I read the FTP into the stream.

public class FTPReceive : IScheduledTaskStreamProvider
    {
        private readonly string TASK_COMPONENT_NAME = "ScheduledTask FTPReceive";

        public Type GetParameterType()
        {
            return typeof(FTPReceiveArguments);
        }

        public Stream GetStream(object args)
        {
            int retryCounter = 1;
            bool isDownloaded = false;
            Stream responseStream = null;

            FTPReceiveArguments parameter = (FTPReceiveArguments) args;

            if (string.IsNullOrWhiteSpace(parameter.Url))
            {
                throw new ArgumentNullException(TASK_COMPONENT_NAME, "URL is null or Empty");
            }

            while (!isDownloaded && retryCounter <= parameter.RetryCount)
            {
                try
                {
                    FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(@parameter.Url);
                    ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                    ftpRequest.Credentials = new NetworkCredential(parameter.Username, parameter.Password);

                    FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                    ftpResponse.Headers.Add("Content-disposition", "inline; filename=fileName.ext");
                    //ftpResponse.Headers.Add("fileNameTest.xml");
                    responseStream = ftpResponse.GetResponseStream();
                    //responseStream.
                    isDownloaded = true;
                }
                catch (WebException wex)
                {
                    if ((retryCounter +1) <= parameter.RetryCount)
                    {
                        Thread.Sleep(parameter.RetryInterval * 60000);
                    }
                    else
                    {
                        // Only Log Information to prevent the adapter will be disabled!
                    }

                    retryCounter++;
                }
                catch (Exception ex)
                {
                    // Do nothing, otherwise the adapter will be disabled!
                }
            }

            if (isDownloaded && responseStream != null)
            {

                return responseStream;
            }

            return null;
        }
    }

ContentLicense: CC BY-SA 3.0


问:
python: bluetootherror: (111, 'connection refused')

Hi everyone!

There seems to be a problem with connecting the cellphone to the raspberry pi 3 via Bluetooth.
I think have a problem with my code.

Here is my code

```<code>import bluetooth

from bluetooth import  *

serverMAC = 'xx:xx:xx:xx:xx:xx'

port = 1

s = blutooth.BluetoothScocket(bluetooth.RFCOMM)

s.connnect((serverMAC, port)
</code>```

I would like to receive the value from the cell phone to Raspberry Pi.

```<code>bluetooth.btcommon.BluetoothError: (111, 'Connection refused')
</code>```

答:
Before trying the code below, make sure the BT adapter on your script-running device is turned on and the target Bluetooth Device is in Discoverable mode (it's adapter is turned on and it's broadcasting capabilities on discovery).

Make sure you use the correct port for the target device. You can do that by running a discover on your available devices, then matching your MAC to one of the found devices and issuing a find_service on the address. Source:Sending messages or datas with bluetooth via python

Tried this on a local machine, mind the MACs will change, so will the profiles, so if you want RFCOMM make sure your device exposes it before trying to connect:

```<code>from bluetooth import *
devices = discover_devices()
for device in devices:
    print([_ for _ in find_service(address=device) if 'RFCOMM' in _['protocol'] ])
# now manually select the desired device or hardcode its name/mac whatever in the script
bt_addr = ...
port = [_ for _ in find_service(address=bt_addr) if 'RFCOMM' in _['protocol']][0]['port']
s = BluetoothSocket(RFCOMM)
s.connect((bt_addr, port))
</code>```

Body:
Hi everyone!

There seems to be a problem with connecting the cellphone to the raspberry pi 3 via Bluetooth.
I think have a problem with my code.

Here is my code

import bluetooth

from bluetooth import  *

serverMAC = 'xx:xx:xx:xx:xx:xx'

port = 1

s = blutooth.BluetoothScocket(bluetooth.RFCOMM)

s.connnect((serverMAC, port)

I would like to receive the value from the cell phone to Raspberry Pi.

bluetooth.btcommon.BluetoothError: (111, 'Connection refused')

Body:
Before trying the code below, make sure the BT adapter on your script-running device is turned on and the target Bluetooth Device is in Discoverable mode (it's adapter is turned on and it's broadcasting capabilities on discovery).

Make sure you use the correct port for the target device. You can do that by running a discover on your available devices, then matching your MAC to one of the found devices and issuing a find_service on the address. Source:Sending messages or datas with bluetooth via python

Tried this on a local machine, mind the MACs will change, so will the profiles, so if you want RFCOMM make sure your device exposes it before trying to connect:

from bluetooth import *
devices = discover_devices()
for device in devices:
    print([_ for _ in find_service(address=device) if 'RFCOMM' in _['protocol'] ])
# now manually select the desired device or hardcode its name/mac whatever in the script
bt_addr = ...
port = [_ for _ in find_service(address=bt_addr) if 'RFCOMM' in _['protocol']][0]['port']
s = BluetoothSocket(RFCOMM)
s.connect((bt_addr, port))


问:
How can I use until in janusgraph?
```<code>gremlin> a = graph.addVertex("name", "alice")
gremlin> b = graph.addVertex("name", "bobby")
gremlin> c = graph.addVertex("name", "cindy")
gremlin> d = graph.addVertex("name", "david")
gremlin> e = graph.addVertex("name", "eliza")
gremlin> a.addEdge("rates",b,"tag","ruby","value",9)
gremlin> b.addEdge("rates",c,"tag","ruby","value",8)
gremlin> c.addEdge("rates",d,"tag","ruby","value",7)
gremlin> d.addEdge("rates",e,"tag","ruby","value",6)
gremlin> e.addEdge("rates",a,"tag","java","value",9)

g.V().has('name', 'alice').repeat(out()).times(6).cyclicPath().path().by('name')
</code>```

I want to end with alice node. and I want to repeat all the step not want to specify time as 6. The requirement is I want to get all the loop from alice or get all the loops from the graph.

答:
You can refer to the Cycle Detection section in the TinkerPop Recipes - it adapts fairly easily to your sample graph:</p>

```<code>gremlin> g.V().has('name', 'alice').as('a').
......1>   repeat(out().simplePath()).
......2>     emit(loops().is(gt(1))).
......3>   both().where(eq('a')).
......4>   path().
......5>     by('name').
......6>   dedup().
......7>     by(unfold().order().dedup().fold())
==>[alice,bobby,cindy,david,eliza,alice]
</code>```

Title: How can I use until in janusgraph?

Body:
gremlin> a = graph.addVertex("name", "alice")
gremlin> b = graph.addVertex("name", "bobby")
gremlin> c = graph.addVertex("name", "cindy")
gremlin> d = graph.addVertex("name", "david")
gremlin> e = graph.addVertex("name", "eliza")
gremlin> a.addEdge("rates",b,"tag","ruby","value",9)
gremlin> b.addEdge("rates",c,"tag","ruby","value",8)
gremlin> c.addEdge("rates",d,"tag","ruby","value",7)
gremlin> d.addEdge("rates",e,"tag","ruby","value",6)
gremlin> e.addEdge("rates",a,"tag","java","value",9)

g.V().has('name', 'alice').repeat(out()).times(6).cyclicPath().path().by('name')

I want to end with alice node. and I want to repeat all the step not want to specify time as 6. The requirement is I want to get all the loop from alice or get all the loops from the graph.

Body:
You can refer to the Cycle Detection section in the TinkerPop Recipes - it adapts fairly easily to your sample graph:

gremlin> g.V().has('name', 'alice').as('a').
......1>   repeat(out().simplePath()).
......2>     emit(loops().is(gt(1))).
......3>   both().where(eq('a')).
......4>   path().
......5>     by('name').
......6>   dedup().
......7>     by(unfold().order().dedup().fold())
==>[alice,bobby,cindy,david,eliza,alice]


问:
How Can make this JSX compact?
```<code>{
  this.state.isLoadingInputDropDown &&
  <option value="-1" disabled >Loading...</option >
}

{/* TODO : was not able to combine below statements */}
{
  !this.state.isLoadingInputDropDown
  && <option value="-1" >--Select a Accessorial Charge first --</option>
}
{
  !this.state.isLoadingInputDropDown
  && this.state.allInputs.length > 0
  && this.state.allInputs.map(
    (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
  )
}
</code>```

trying to make this JSX one-liner or something compact.
I tried every possible (which I can think of) structure

答:
Ideally, split the whole function into two parts:

```<code>let options;

if (this.state.isLoadingInputDropDown) {
   const defaultOption = <option value="-1" disabled >Loading...</option>;
   options = [defaultOption];
} else {
   const defaultOption = <option value="-1" >--Select a Accessorial Charge first --</option>;
   const choices = this.state.allInputs.map(
       (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
   )
   options = [defaultOption, ...choices];
}

return (
   <select>
      {options}
   </select>
);
</code>```

The this.state.allInputs.length > 0 check is not necessary.

Don't try to make this a one-liner. It's not important how long code is. The important thing is to make it readable. You should actually consider splitting this piece of code into multiple functions.

Title: How Can make this JSX compact?

Body:
{
  this.state.isLoadingInputDropDown &&
  <option value="-1" disabled >Loading...</option >
}

{/* TODO : was not able to combine below statements */}
{
  !this.state.isLoadingInputDropDown
  && <option value="-1" >--Select a Accessorial Charge first --</option>
}
{
  !this.state.isLoadingInputDropDown
  && this.state.allInputs.length > 0
  && this.state.allInputs.map(
    (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
  )
}

trying to make this JSX one-liner or something compact.
I tried every possible (which I can think of) structure

Body:
Ideally, split the whole function into two parts:

let options;

if (this.state.isLoadingInputDropDown) {
   const defaultOption = <option value="-1" disabled >Loading...</option>;
   options = [defaultOption];
} else {
   const defaultOption = <option value="-1" >--Select a Accessorial Charge first --</option>;
   const choices = this.state.allInputs.map(
       (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
   )
   options = [defaultOption, ...choices];
}

return (
   <select>
      {options}
   </select>
);

The this.state.allInputs.length > 0 check is not necessary.

Don't try to make this a one-liner. It's not important how long code is. The important thing is to make it readable. You should actually consider splitting this piece of code into multiple functions.


问:
how to get every instance of a word( i.e alphanumeric) from a string and change it?
I have a string such as:

```<code>{
    props: {
        options: {
            type: Array
        }
    }
}
</code>```

Now i want to change props into "props" and option into "option" and similarly every word which this whole string might have.

I am doing this because in the original format JSON.parse() is throwing error as this is not in JSON string which should look like this:

```<code>{
    "props": {
        "options": {
            "type": "Array"
        }
    }
}
</code>```

If you have any suggestion don't hesitate to share. Thank you.

答:
You can use a regex to match all occurrences and replace them:</p>

```<code>var str = `{
    props: {
        options: {
            type: Array
        }
    }
}`;
var jsonString = str.replace(/(\w+)/g, '"$1"');
var obj = JSON.parse(jsonString);
</code>```

Body:
I have a string such as:

{
    props: {
        options: {
            type: Array
        }
    }
}

Now i want to change props into "props" and option into "option" and similarly every word which this whole string might have.

I am doing this because in the original format JSON.parse() is throwing error as this is not in JSON string which should look like this:

{
    "props": {
        "options": {
            "type": "Array"
        }
    }
}

If you have any suggestion don't hesitate to share. Thank you.

Body:
You can use a regex to match all occurrences and replace them:

var str = `{
    props: {
        options: {
            type: Array
        }
    }
}`;
var jsonString = str.replace(/(\w+)/g, '"$1"');
var obj = JSON.parse(jsonString);


问:
Example: Communication between Activity and Service using Messaging
I couldn't find any examples of how to send messages between an activity and a service, and I have spent far too many hours figuring this out. Here is an example project for others to reference.

This example allows you to start or stop a service directly, and separately bind/unbind from the service. When the service is running, it increments a number at 10 Hz. If the activity is bound to the Service, it will display the current value. Data is transferred as an Integer and as a String so you can see how to do that two different ways. There are also buttons in the activity to send messages to the service (changes the increment-by value).

Screenshot:

AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.exampleservice"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    <service android:name=".MyService"></service>
    </application>
    <uses-sdk android:minSdkVersion="8" />
</manifest>
</code>```

res\values\strings.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ExampleService</string>
    <string name="service_started">Example Service started</string>
    <string name="service_label">Example Service Label</string>
</resources>
</code>```

res\layout\main.xml:

```<code><RelativeLayout
    android:id="@+id/RelativeLayout01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Service" >
    </Button>

    <Button
        android:id="@+id/btnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Stop Service" >
    </Button>
</RelativeLayout>

<RelativeLayout
    android:id="@+id/RelativeLayout02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnBind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bind to Service" >
    </Button>

    <Button
        android:id="@+id/btnUnbind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Unbind from Service" >
    </Button>
</RelativeLayout>

<TextView
    android:id="@+id/textStatus"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Status Goes Here"
    android:textSize="24sp" />

<TextView
    android:id="@+id/textIntValue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Integer Value Goes Here"
    android:textSize="24sp" />

<TextView
    android:id="@+id/textStrValue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="String Value Goes Here"
    android:textSize="24sp" />

<RelativeLayout
    android:id="@+id/RelativeLayout03"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnUpby1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Increment by 1" >
    </Button>

    <Button
        android:id="@+id/btnUpby10"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Increment by 10" >
    </Button>
</RelativeLayout>
</code>```

src\com.exampleservice\MainActivity.java:

```<code>package com.exampleservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    Button btnStart, btnStop, btnBind, btnUnbind, btnUpby1, btnUpby10;
    TextView textStatus, textIntValue, textStrValue;
    Messenger mService = null;
    boolean mIsBound;
    final Messenger mMessenger = new Messenger(new IncomingHandler());

    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MyService.MSG_SET_INT_VALUE:
                textIntValue.setText("Int Message: " + msg.arg1);
                break;
            case MyService.MSG_SET_STRING_VALUE:
                String str1 = msg.getData().getString("str1");
                textStrValue.setText("Str Message: " + str1);
                break;
            default:
                super.handleMessage(msg);
            }
        }
    }
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = new Messenger(service);
            textStatus.setText("Attached.");
            try {
                Message msg = Message.obtain(null, MyService.MSG_REGISTER_CLIENT);
                msg.replyTo = mMessenger;
                mService.send(msg);
            }
            catch (RemoteException e) {
                // In this case the service has crashed before we could even do anything with it
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
            mService = null;
            textStatus.setText("Disconnected.");
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStart = (Button)findViewById(R.id.btnStart);
        btnStop = (Button)findViewById(R.id.btnStop);
        btnBind = (Button)findViewById(R.id.btnBind);
        btnUnbind = (Button)findViewById(R.id.btnUnbind);
        textStatus = (TextView)findViewById(R.id.textStatus);
        textIntValue = (TextView)findViewById(R.id.textIntValue);
        textStrValue = (TextView)findViewById(R.id.textStrValue);
        btnUpby1 = (Button)findViewById(R.id.btnUpby1);
        btnUpby10 = (Button)findViewById(R.id.btnUpby10);

        btnStart.setOnClickListener(btnStartListener);
        btnStop.setOnClickListener(btnStopListener);
        btnBind.setOnClickListener(btnBindListener);
        btnUnbind.setOnClickListener(btnUnbindListener);
        btnUpby1.setOnClickListener(btnUpby1Listener);
        btnUpby10.setOnClickListener(btnUpby10Listener);

        restoreMe(savedInstanceState);

        CheckIfServiceIsRunning();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("textStatus", textStatus.getText().toString());
        outState.putString("textIntValue", textIntValue.getText().toString());
        outState.putString("textStrValue", textStrValue.getText().toString());
    }
    private void restoreMe(Bundle state) {
        if (state!=null) {
            textStatus.setText(state.getString("textStatus"));
            textIntValue.setText(state.getString("textIntValue"));
            textStrValue.setText(state.getString("textStrValue"));
        }
    }
    private void CheckIfServiceIsRunning() {
        //If the service is running when the activity starts, we want to automatically bind to it.
        if (MyService.isRunning()) {
            doBindService();
        }
    }

    private OnClickListener btnStartListener = new OnClickListener() {
        public void onClick(View v){
            startService(new Intent(MainActivity.this, MyService.class));
        }
    };
    private OnClickListener btnStopListener = new OnClickListener() {
        public void onClick(View v){
            doUnbindService();
            stopService(new Intent(MainActivity.this, MyService.class));
        }
    };
    private OnClickListener btnBindListener = new OnClickListener() {
        public void onClick(View v){
            doBindService();
        }
    };
    private OnClickListener btnUnbindListener = new OnClickListener() {
        public void onClick(View v){
            doUnbindService();
        }
    };
    private OnClickListener btnUpby1Listener = new OnClickListener() {
        public void onClick(View v){
            sendMessageToService(1);
        }
    };
    private OnClickListener btnUpby10Listener = new OnClickListener() {
        public void onClick(View v){
            sendMessageToService(10);
        }
    };
    private void sendMessageToService(int intvaluetosend) {
        if (mIsBound) {
            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, MyService.MSG_SET_INT_VALUE, intvaluetosend, 0);
                    msg.replyTo = mMessenger;
                    mService.send(msg);
                }
                catch (RemoteException e) {
                }
            }
        }
    }

    void doBindService() {
        bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
        textStatus.setText("Binding.");
    }
    void doUnbindService() {
        if (mIsBound) {
            // If we have received the service, and hence registered with it, then now is the time to unregister.
            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, MyService.MSG_UNREGISTER_CLIENT);
                    msg.replyTo = mMessenger;
                    mService.send(msg);
                }
                catch (RemoteException e) {
                    // There is nothing special we need to do if the service has crashed.
                }
            }
            // Detach our existing connection.
            unbindService(mConnection);
            mIsBound = false;
            textStatus.setText("Unbinding.");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            doUnbindService();
        }
        catch (Throwable t) {
            Log.e("MainActivity", "Failed to unbind from the service", t);
        }
    }
}
</code>```

src\com.exampleservice\MyService.java:

```<code>package com.exampleservice;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class MyService extends Service {
    private NotificationManager nm;
    private Timer timer = new Timer();
    private int counter = 0, incrementby = 1;
    private static boolean isRunning = false;

    ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
    int mValue = 0; // Holds last value set by a client.
    static final int MSG_REGISTER_CLIENT = 1;
    static final int MSG_UNREGISTER_CLIENT = 2;
    static final int MSG_SET_INT_VALUE = 3;
    static final int MSG_SET_STRING_VALUE = 4;
    final Messenger mMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler.

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }
    class IncomingHandler extends Handler { // Handler of incoming messages from clients.
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_REGISTER_CLIENT:
                mClients.add(msg.replyTo);
                break;
            case MSG_UNREGISTER_CLIENT:
                mClients.remove(msg.replyTo);
                break;
            case MSG_SET_INT_VALUE:
                incrementby = msg.arg1;
                break;
            default:
                super.handleMessage(msg);
            }
        }
    }
    private void sendMessageToUI(int intvaluetosend) {
        for (int i=mClients.size()-1; i>=0; i--) {
            try {
                // Send data as an Integer
                mClients.get(i).send(Message.obtain(null, MSG_SET_INT_VALUE, intvaluetosend, 0));

                //Send data as a String
                Bundle b = new Bundle();
                b.putString("str1", "ab" + intvaluetosend + "cd");
                Message msg = Message.obtain(null, MSG_SET_STRING_VALUE);
                msg.setData(b);
                mClients.get(i).send(msg);

            }
            catch (RemoteException e) {
                // The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
                mClients.remove(i);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("MyService", "Service Started.");
        showNotification();
        timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 0, 100L);
        isRunning = true;
    }
    private void showNotification() {
        nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.service_started);
        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.icon, text, System.currentTimeMillis());
        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);
        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        nm.notify(R.string.service_started, notification);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyService", "Received start id " + startId + ": " + intent);
        return START_STICKY; // run until explicitly stopped.
    }

    public static boolean isRunning()
    {
        return isRunning;
    }

    private void onTimerTick() {
        Log.i("TimerTick", "Timer doing work." + counter);
        try {
            counter += incrementby;
            sendMessageToUI(counter);

        }
        catch (Throwable t) { //you should always ultimately catch all exceptions in timer tasks.
            Log.e("TimerTick", "Timer Tick Failed.", t);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {timer.cancel();}
        counter=0;
        nm.cancel(R.string.service_started); // Cancel the persistent notification.
        Log.i("MyService", "Service Stopped.");
        isRunning = false;
    }
}
</code>```

答:
Look at the LocalService example.

Your Service returns an instance of itself to consumers who call onBind. Then you can directly interact with the service, e.g. registering your own listener interface with the service, so that you can get callbacks.

Body:
I couldn't find any examples of how to send messages between an activity and a service, and I have spent far too many hours figuring this out. Here is an example project for others to reference.

This example allows you to start or stop a service directly, and separately bind/unbind from the service. When the service is running, it increments a number at 10 Hz. If the activity is bound to the Service, it will display the current value. Data is transferred as an Integer and as a String so you can see how to do that two different ways. There are also buttons in the activity to send messages to the service (changes the increment-by value).

Screenshot:

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.exampleservice"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    <service android:name=".MyService"></service>
    </application>
    <uses-sdk android:minSdkVersion="8" />
</manifest>

res\values\strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ExampleService</string>
    <string name="service_started">Example Service started</string>
    <string name="service_label">Example Service Label</string>
</resources>

res\layout\main.xml:

<RelativeLayout
    android:id="@+id/RelativeLayout01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Service" >
    </Button>

    <Button
        android:id="@+id/btnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Stop Service" >
    </Button>
</RelativeLayout>

<RelativeLayout
    android:id="@+id/RelativeLayout02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnBind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bind to Service" >
    </Button>

    <Button
        android:id="@+id/btnUnbind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Unbind from Service" >
    </Button>
</RelativeLayout>

<TextView
    android:id="@+id/textStatus"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Status Goes Here"
    android:textSize="24sp" />

<TextView
    android:id="@+id/textIntValue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Integer Value Goes Here"
    android:textSize="24sp" />

<TextView
    android:id="@+id/textStrValue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="String Value Goes Here"
    android:textSize="24sp" />

<RelativeLayout
    android:id="@+id/RelativeLayout03"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnUpby1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Increment by 1" >
    </Button>

    <Button
        android:id="@+id/btnUpby10"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Increment by 10" >
    </Button>
</RelativeLayout>

src\com.exampleservice\MainActivity.java:

package com.exampleservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    Button btnStart, btnStop, btnBind, btnUnbind, btnUpby1, btnUpby10;
    TextView textStatus, textIntValue, textStrValue;
    Messenger mService = null;
    boolean mIsBound;
    final Messenger mMessenger = new Messenger(new IncomingHandler());

    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MyService.MSG_SET_INT_VALUE:
                textIntValue.setText("Int Message: " + msg.arg1);
                break;
            case MyService.MSG_SET_STRING_VALUE:
                String str1 = msg.getData().getString("str1");
                textStrValue.setText("Str Message: " + str1);
                break;
            default:
                super.handleMessage(msg);
            }
        }
    }
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = new Messenger(service);
            textStatus.setText("Attached.");
            try {
                Message msg = Message.obtain(null, MyService.MSG_REGISTER_CLIENT);
                msg.replyTo = mMessenger;
                mService.send(msg);
            }
            catch (RemoteException e) {
                // In this case the service has crashed before we could even do anything with it
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
            mService = null;
            textStatus.setText("Disconnected.");
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStart = (Button)findViewById(R.id.btnStart);
        btnStop = (Button)findViewById(R.id.btnStop);
        btnBind = (Button)findViewById(R.id.btnBind);
        btnUnbind = (Button)findViewById(R.id.btnUnbind);
        textStatus = (TextView)findViewById(R.id.textStatus);
        textIntValue = (TextView)findViewById(R.id.textIntValue);
        textStrValue = (TextView)findViewById(R.id.textStrValue);
        btnUpby1 = (Button)findViewById(R.id.btnUpby1);
        btnUpby10 = (Button)findViewById(R.id.btnUpby10);

        btnStart.setOnClickListener(btnStartListener);
        btnStop.setOnClickListener(btnStopListener);
        btnBind.setOnClickListener(btnBindListener);
        btnUnbind.setOnClickListener(btnUnbindListener);
        btnUpby1.setOnClickListener(btnUpby1Listener);
        btnUpby10.setOnClickListener(btnUpby10Listener);

        restoreMe(savedInstanceState);

        CheckIfServiceIsRunning();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("textStatus", textStatus.getText().toString());
        outState.putString("textIntValue", textIntValue.getText().toString());
        outState.putString("textStrValue", textStrValue.getText().toString());
    }
    private void restoreMe(Bundle state) {
        if (state!=null) {
            textStatus.setText(state.getString("textStatus"));
            textIntValue.setText(state.getString("textIntValue"));
            textStrValue.setText(state.getString("textStrValue"));
        }
    }
    private void CheckIfServiceIsRunning() {
        //If the service is running when the activity starts, we want to automatically bind to it.
        if (MyService.isRunning()) {
            doBindService();
        }
    }

    private OnClickListener btnStartListener = new OnClickListener() {
        public void onClick(View v){
            startService(new Intent(MainActivity.this, MyService.class));
        }
    };
    private OnClickListener btnStopListener = new OnClickListener() {
        public void onClick(View v){
            doUnbindService();
            stopService(new Intent(MainActivity.this, MyService.class));
        }
    };
    private OnClickListener btnBindListener = new OnClickListener() {
        public void onClick(View v){
            doBindService();
        }
    };
    private OnClickListener btnUnbindListener = new OnClickListener() {
        public void onClick(View v){
            doUnbindService();
        }
    };
    private OnClickListener btnUpby1Listener = new OnClickListener() {
        public void onClick(View v){
            sendMessageToService(1);
        }
    };
    private OnClickListener btnUpby10Listener = new OnClickListener() {
        public void onClick(View v){
            sendMessageToService(10);
        }
    };
    private void sendMessageToService(int intvaluetosend) {
        if (mIsBound) {
            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, MyService.MSG_SET_INT_VALUE, intvaluetosend, 0);
                    msg.replyTo = mMessenger;
                    mService.send(msg);
                }
                catch (RemoteException e) {
                }
            }
        }
    }

    void doBindService() {
        bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
        textStatus.setText("Binding.");
    }
    void doUnbindService() {
        if (mIsBound) {
            // If we have received the service, and hence registered with it, then now is the time to unregister.
            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, MyService.MSG_UNREGISTER_CLIENT);
                    msg.replyTo = mMessenger;
                    mService.send(msg);
                }
                catch (RemoteException e) {
                    // There is nothing special we need to do if the service has crashed.
                }
            }
            // Detach our existing connection.
            unbindService(mConnection);
            mIsBound = false;
            textStatus.setText("Unbinding.");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            doUnbindService();
        }
        catch (Throwable t) {
            Log.e("MainActivity", "Failed to unbind from the service", t);
        }
    }
}

src\com.exampleservice\MyService.java:

package com.exampleservice;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class MyService extends Service {
    private NotificationManager nm;
    private Timer timer = new Timer();
    private int counter = 0, incrementby = 1;
    private static boolean isRunning = false;

    ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
    int mValue = 0; // Holds last value set by a client.
    static final int MSG_REGISTER_CLIENT = 1;
    static final int MSG_UNREGISTER_CLIENT = 2;
    static final int MSG_SET_INT_VALUE = 3;
    static final int MSG_SET_STRING_VALUE = 4;
    final Messenger mMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler.

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }
    class IncomingHandler extends Handler { // Handler of incoming messages from clients.
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_REGISTER_CLIENT:
                mClients.add(msg.replyTo);
                break;
            case MSG_UNREGISTER_CLIENT:
                mClients.remove(msg.replyTo);
                break;
            case MSG_SET_INT_VALUE:
                incrementby = msg.arg1;
                break;
            default:
                super.handleMessage(msg);
            }
        }
    }
    private void sendMessageToUI(int intvaluetosend) {
        for (int i=mClients.size()-1; i>=0; i--) {
            try {
                // Send data as an Integer
                mClients.get(i).send(Message.obtain(null, MSG_SET_INT_VALUE, intvaluetosend, 0));

                //Send data as a String
                Bundle b = new Bundle();
                b.putString("str1", "ab" + intvaluetosend + "cd");
                Message msg = Message.obtain(null, MSG_SET_STRING_VALUE);
                msg.setData(b);
                mClients.get(i).send(msg);

            }
            catch (RemoteException e) {
                // The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
                mClients.remove(i);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("MyService", "Service Started.");
        showNotification();
        timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 0, 100L);
        isRunning = true;
    }
    private void showNotification() {
        nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.service_started);
        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.icon, text, System.currentTimeMillis());
        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);
        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        nm.notify(R.string.service_started, notification);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyService", "Received start id " + startId + ": " + intent);
        return START_STICKY; // run until explicitly stopped.
    }

    public static boolean isRunning()
    {
        return isRunning;
    }

    private void onTimerTick() {
        Log.i("TimerTick", "Timer doing work." + counter);
        try {
            counter += incrementby;
            sendMessageToUI(counter);

        }
        catch (Throwable t) { //you should always ultimately catch all exceptions in timer tasks.
            Log.e("TimerTick", "Timer Tick Failed.", t);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {timer.cancel();}
        counter=0;
        nm.cancel(R.string.service_started); // Cancel the persistent notification.
        Log.i("MyService", "Service Stopped.");
        isRunning = false;
    }
}


问:
Messaging vs RPC in a distributed system (Openstack vs K8s/Swarm)
OpenStack uses messaging (RabbitMQ by default I think ?) for the communication between the nodes. On the other hand Kubernetes (lineage of Google's internal Borg) uses RPC. Docker's swarm uses RPC as well. Both are gRPC/protofbuf based which seems to be used heavily inside Google as well.

I understand that messaging platforms like Kafka are widely used for streaming data and log aggregation. But systems like OpenStack, Kubernetes, Docker Swarm etc. need specific interactions between the nodes and RPC seems like a natural choice because it allows APIs to be defined for specific operations.

Did OpenStack chose messaging after evaluating the pros and cons of messaging vs RPC? Are there any good blogs/system reviews comparing the success of large scale systems using messaging vs RPC? Does messaging offer any advantage over RPC in scaled distributed systems?

答:
Does messaging offer any advantage over RPC in scaled distributed systems ?

Mostly persistence is a big advantage for messaging system. Another point is broadcasting. You need to implement this into gRPC by yourself. Service Discovery and Security can be another reason. In Messaging System you just need to keep one system highly secure, while with gRPC you might have many points where somebody could break into the system. Message queue systems usually already have some kind of service discovery implemented. With gRPC you have to use at least another library for this.

Are there any good literate comparing the success of large scale systems using messaging vs RPC ?

It's not a vs. There are different use cases. Messaging Systems are generally slower than RPC protocols. Not only slower than gRPC. The reason for this is also simple. You just introduce a middleware between two or more nodes. But they provide persistence, broadcasting, Pub/Sub etc.

Did Openstack chose messaging after evaluating the pros cons of messaging vs RPC ?
Probably

Does messaging offer any advantage over RPC in scaled distributed systems ?

Ready to use solution, just use a client

Persistence

Ready to use Service Discovery

Pub/Sub Pattern

Failure tolerance

Most of the points needs to be implemented with gRPC by yourself.


问:
HTML5 folder drag and drop but single file selection on click
I have a drag & drop zone on my web application. The drag & drop zone accepts folders

```<code><input type="file" multiple="multiple" webkitdirectory mozdirectory />
</code>```

I can easily drag and drop folders, a selection of folders, single files and a selection of files. Everything works as expected.

When I click on the drag & drop zone I get the standard Windows modal popup asking me to select a folder, not single files.

What I'd like to have is: when I click on the drag and drop zone I want to see the normal Windows file selection modal, not the folder one

couldn't find any solution for it, is it even possible?

答:
That's what webkitDirectory does, it limits your INPUT to accept only FOLDERS:

https://wicg.github.io/entries-api/#dom-htmlinputelement-webkitdirectory

The webkitdirectory attribute is a boolean attribute that indicates
  whether the user is to be allowed to select a directory rather than a
  file or files.

To support file selection and drag&drop of either files or folder, you'll need to change your approach, you need a drag&drop zone:

https://jsfiddle.net/atfLe15b/

Example from https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/webkitGetAsEntry.

Body:
I have a drag & drop zone on my web application. The drag & drop zone accepts folders

<input type="file" multiple="multiple" webkitdirectory mozdirectory />

I can easily drag and drop folders, a selection of folders, single files and a selection of files. Everything works as expected.

When I click on the drag & drop zone I get the standard Windows modal popup asking me to select a folder, not single files.

What I'd like to have is: when I click on the drag and drop zone I want to see the normal Windows file selection modal, not the folder one

couldn't find any solution for it, is it even possible?


问:
PowerShell Logging Function Usage
I am trying to log the output from a PowerShell script, the script is a simple list of Cmdlets run in series, here's an example of one

```<code>New-AzureRmVirtualNetworkGateway -Name VNet1GW -ResourceGroupName My-Resource-Group -Location 'West US' -IpConfigurations $gwipconfig -GatewayType Vpn -VpnType RouteBased -GatewaySku standard
</code>```

I found this logging function, but I am not sure how to use it or call it so that I can get all the output from each Cmdlet in series

```<code>Function Write-Log {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $False)]
        [ValidateSet("INFO", "WARN", "ERROR", "FATAL", "DEBUG")]
        [String]
        $Level = "INFO",

        [Parameter(Mandatory = $True)]
        [string]
        $Message,

        [Parameter(Mandatory = $False)]
        [string]
        $logfile
    )

    $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
    $Line = "$Stamp $Level $Message"
    If ($logfile) {
        Add-Content $logfile -Value $Line
    }
    Else {
        Write-Output $Line
    }
}
</code>```

I would like to use this logging for debugging my scripts as the output from the scripts is very vague

答:
Rather than complicate things with a bespoke logging function, is it not feasible to use a built-in cmdlet such as Out-File?

Out-File C:\filename.txt

Title: PowerShell Logging Function Usage

Body:
I am trying to log the output from a PowerShell script, the script is a simple list of Cmdlets run in series, here's an example of one

New-AzureRmVirtualNetworkGateway -Name VNet1GW -ResourceGroupName My-Resource-Group -Location 'West US' -IpConfigurations $gwipconfig -GatewayType Vpn -VpnType RouteBased -GatewaySku standard

I found this logging function, but I am not sure how to use it or call it so that I can get all the output from each Cmdlet in series

Function Write-Log {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $False)]
        [ValidateSet("INFO", "WARN", "ERROR", "FATAL", "DEBUG")]
        [String]
        $Level = "INFO",

        [Parameter(Mandatory = $True)]
        [string]
        $Message,

        [Parameter(Mandatory = $False)]
        [string]
        $logfile
    )

    $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
    $Line = "$Stamp $Level $Message"
    If ($logfile) {
        Add-Content $logfile -Value $Line
    }
    Else {
        Write-Output $Line
    }
}

I would like to use this logging for debugging my scripts as the output from the scripts is very vague


问:
How to make a Volley class a public method
I have to call web service in multiple classes I am using Volley. so what should I do in onresponse method to trigger the other class for the response?
I want to make syncData as a generic function for my all classes.

```<code>  public String syncData(Context mContext, String url) {
    try {
        RequestQueue queue = Volley.newRequestQueue(mContext);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    jsonResponse=response.toString();//what I should do here to trigger another class that responds achieved

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                try {
                    Log.e("Response", "error");
                    //  updateForecastUI(isCentigradeType);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
                Constants.MY_SOCKET_TIMEOUT_MS,
                Constants.MAX_RETRY,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        jsonObjectRequest.setShouldCache(false);
        queue.add(jsonObjectRequest);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return  jsonResponse;
}
</code>```

答:
Simple, use Volley as Singleton.

So that you can hit web service in multiple classes.

your work will be done.

Body:
I have to call web service in multiple classes I am using Volley. so what should I do in onresponse method to trigger the other class for the response?
I want to make syncData as a generic function for my all classes.

  public String syncData(Context mContext, String url) {
    try {
        RequestQueue queue = Volley.newRequestQueue(mContext);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    jsonResponse=response.toString();//what I should do here to trigger another class that responds achieved

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                try {
                    Log.e("Response", "error");
                    //  updateForecastUI(isCentigradeType);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
                Constants.MY_SOCKET_TIMEOUT_MS,
                Constants.MAX_RETRY,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        jsonObjectRequest.setShouldCache(false);
        queue.add(jsonObjectRequest);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return  jsonResponse;
}


问:
jquery ui dialog fixed positioning
I needed the dialog to maintain its position fixed even if the page scrolled, so i used the
 extension at http://forum.jquery.com/topic/dialog-position-fixed-12-1-2010 but there's 2 problems with it:

it flickers in IE and Firefox on page scroll (in Safari/Chrome it's fine)

on closing and then reopening, it looses its stickyness and scrolls along with the page.

Here's the code i'm using for creating the dialog:

```<code>$('<div id="'+divpm_id+'"><div id="inner_'+divpm_id+'"></div><textarea class="msgTxt" id="txt'+divpm_id+'" rows="2"></textarea></div>')
                .dialog({
                autoOpen: true,
                title: user_str,
                height: 200,
                stack: true,
                sticky: true //uses ui dialog extension to keep it fixed
     });
</code>```

And here's the code i'm using for reopening it:

```<code>jQuery('#'+divpm_id).parent().css('display','block');
</code>```

Suggestions/solutions?

Thanks

答:
As i wrote in my blog https://xbrowser.altervista.org/informatica-portata/jquery-easyui-bug-fix-window-dialog-position-widget/
I've found a bug in “window” element or “dialog” element.
When you instantiate this widget, it go out of the main window browser, in particular in top and left position (when you drag o resize it).
To resolve this problem i’ve implemented this solution.

You can read the source code below:

```<code>$(dialog).window({
   onMove: function(left, top) {
   if (left < 0 || top < 0) {
     left = (left < 0) ? 0 : left;
     top = (top < 0) ? 0 : top;
     $(this).window('move', {left: left, top: top});
   }
},
onResize: function(width, height) {
  var opt = $(this).window("options");
  var top = opt.top;
  var left = opt.left;
  if (top < 0) {
    top = (top < 0) ? 0 : top;
    $(this).window('move', {left: left, top: top});
  }
}
}).window("open");

The same code is for dialog:

$(dialog).dialog({
  onMove: function(left, top) {
  if (left < 0 || top < 0) {
     left = (left < 0) ? 0 : left;
     top = (top < 0) ? 0 : top;
     $(this).dialog('move', {left: left, top: top});
  }
},
onResize: function(width, height) {
   var opt = $(this).window("options");
   var top = opt.top;
   var left = opt.left;
   if (top < 0) {
     top = (top < 0) ? 0 : top;
     $(this).dialog('move', {left: left, top: top});
   }
}
}).dialog("open");
</code>```

Futhermore, when you call “$(this).window(“options”);” inside “onResize” method, and start your App,
you don’t see the window; so i must insert the “.window(“open”);” at the and of declaration of dialog.

I hope to help you.

ContentLicense: CC BY-SA 2.5

Title: jquery ui dialog fixed positioning

Body:
I needed the dialog to maintain its position fixed even if the page scrolled, so i used the
 extension at http://forum.jquery.com/topic/dialog-position-fixed-12-1-2010 but there's 2 problems with it:

it flickers in IE and Firefox on page scroll (in Safari/Chrome it's fine)

on closing and then reopening, it looses its stickyness and scrolls along with the page.

Here's the code i'm using for creating the dialog:

$('

<textarea class="msgTxt" id="txt'+divpm_id+'" rows="2"></textarea>
')
                .dialog({
                autoOpen: true,
                title: user_str,
                height: 200,
                stack: true,
                sticky: true //uses ui dialog extension to keep it fixed
     });

And here's the code i'm using for reopening it:

jQuery('#'+divpm_id).parent().css('display','block');

Suggestions/solutions?

Thanks

Body:
As i wrote in my blog https://xbrowser.altervista.org/informatica-portata/jquery-easyui-bug-fix-window-dialog-position-widget/
I've found a bug in “window” element or “dialog” element.
When you instantiate this widget, it go out of the main window browser, in particular in top and left position (when you drag o resize it).
To resolve this problem i’ve implemented this solution.

You can read the source code below:

$(dialog).window({
   onMove: function(left, top) {
   if (left < 0 || top < 0) {
     left = (left < 0) ? 0 : left;
     top = (top < 0) ? 0 : top;
     $(this).window('move', {left: left, top: top});
   }
},
onResize: function(width, height) {
  var opt = $(this).window("options");
  var top = opt.top;
  var left = opt.left;
  if (top < 0) {
    top = (top < 0) ? 0 : top;
    $(this).window('move', {left: left, top: top});
  }
}
}).window("open");

The same code is for dialog:

$(dialog).dialog({
  onMove: function(left, top) {
  if (left < 0 || top < 0) {
     left = (left < 0) ? 0 : left;
     top = (top < 0) ? 0 : top;
     $(this).dialog('move', {left: left, top: top});
  }
},
onResize: function(width, height) {
   var opt = $(this).window("options");
   var top = opt.top;
   var left = opt.left;
   if (top < 0) {
     top = (top < 0) ? 0 : top;
     $(this).dialog('move', {left: left, top: top});
   }
}
}).dialog("open");

Futhermore, when you call “$(this).window(“options”);” inside “onResize” method, and start your App,
you don’t see the window; so i must insert the “.window(“open”);” at the and of declaration of dialog.

I hope to help you.


问:
Django - How to only save form to database if a specific field is NOT filled out (honeypot trap for signup spam)
I have recently been having some trouble with fake signups on my website signup form. I've decided the best way to deal with this is to create an 'invisible' honeypot form field.

I have created this new 'fake' form field in my models.py and forms.py, I have rendered the field in my template, and I have hidden the field from real users using 'display: none' in my CSS. What I want to be able to do now is only save the form to the database if the 'fake' field is NOT filled out.

For example, I want to do something like this:

```<code>    if form.is_valid() and fakeformfield.is_null():
            instance = form.save(commit=False)
            instance.save()
            return redirect('thankyou')
</code>```

If you need to see my code just say and I will update the question.

Any help would be much appreciated!

答:
```<code>if form.is_valid():
    fake_field_value = form.cleaned_data.get('fakeformfield')
    if not fake_field_value:
        instance = form.save(commit=False)
        instance.save()
return redirect('thankyou')
</code>```

This would give what you are looking for. But i am not sure how could it prevent the fake submissions. If it is somebody trying to do it using a crawler, he can simply see that this field is hidden and would avoid filling the value. Consider using a captcha.

Body:
I have recently been having some trouble with fake signups on my website signup form. I've decided the best way to deal with this is to create an 'invisible' honeypot form field.

I have created this new 'fake' form field in my models.py and forms.py, I have rendered the field in my template, and I have hidden the field from real users using 'display: none' in my CSS. What I want to be able to do now is only save the form to the database if the 'fake' field is NOT filled out.

For example, I want to do something like this:

    if form.is_valid() and fakeformfield.is_null():
            instance = form.save(commit=False)
            instance.save()
            return redirect('thankyou')

If you need to see my code just say and I will update the question.

Any help would be much appreciated!

Body:
if form.is_valid():
    fake_field_value = form.cleaned_data.get('fakeformfield')
    if not fake_field_value:
        instance = form.save(commit=False)
        instance.save()
return redirect('thankyou')

This would give what you are looking for. But i am not sure how could it prevent the fake submissions. If it is somebody trying to do it using a crawler, he can simply see that this field is hidden and would avoid filling the value. Consider using a captcha.


问:
Reading LAZ to Dask dataframe using delayed loading
Action
Reading multiple LAZ point cloud files to a Dask DataFrame.

Problem
Unzipping LAZ (compressed) to LAS (uncompressed) requires a lot of memory. Varying filesizes and multiple processes created by Dask result in MemoryError's.

Attempts

I tried limiting the number of workers following the guide, but it does not seem to work.

```<code>from distributed import Client, LocalCluster
cluster = LocalCluster(n_workers=3)
client = Client(cluster)

dfs = [load(file) for file in lasfiles]
df = dd.from_delayed(dfs, meta=meta)
df = df.repartition(npartitions=len(df) // part_size)
df.to_parquet('/raw', compression='GZIP')
</code>```

Question
How to go about loading such large amount of data in a non-standard format?

Example

Following example is my current implementation. It groups all input files per 5 to limit max 5 parallel uncompressing processes. Then repartitions and write to Parquet to enable further processing. To me this implementation seems to totally miss the point of Dask.

```<code>from laspy.file import File
import numpy as np
import pandas as pd
import dask.dataframe as dd
from dask.delayed import delayed

@delayed
def load(file):
    with File(file.as_posix(), mode='r') as las_data:
        las_df = pd.DataFrame(las_data.points['point'], dtype=float)
        return las_df

meta = pd.DataFrame(np.empty(0, dtype=[('X',float),('Y',float),('Z',float),('intensity',float),('raw_classification',int)]))

lasfile_dir = Path('/data/las/')
lasfiles = sorted(list(lasfile_dir.glob('*.laz')))

part_size = 5000000

for idx, sublasfiles in enumerate([lasfiles[i:i+5] for i in range(0,len(lasfiles),5)]):
    try:
        dfs = [load(file) for file in sublasfiles]
        df = dd.from_delayed(dfs, meta=meta)
        df = df.repartition(npartitions=len(df) // part_size)
        df.to_parquet('/data/las/parquet/'+str(idx), compression='GZIP')
</code>```

答:
Your implementation seems mostly fine to me.

The one thing I would change here is that I would avoid the call to len(df), which will force a computation of the entire dataframe (there is no way to determine the length of the dataframe without reading through all of the files).

Just to be clear, Dask will not be able to parallelize within your load function (it has no concept of LAZ files), so your parallelism will be limited by the number of files that you have.

Body:
Action
Reading multiple LAZ point cloud files to a Dask DataFrame.

Problem
Unzipping LAZ (compressed) to LAS (uncompressed) requires a lot of memory. Varying filesizes and multiple processes created by Dask result in MemoryError's.

Attempts

I tried limiting the number of workers following the guide, but it does not seem to work.

from distributed import Client, LocalCluster
cluster = LocalCluster(n_workers=3)
client = Client(cluster)

dfs = [load(file) for file in lasfiles]
df = dd.from_delayed(dfs, meta=meta)
df = df.repartition(npartitions=len(df) // part_size)
df.to_parquet('/raw', compression='GZIP')

Question
How to go about loading such large amount of data in a non-standard format?

Example

Following example is my current implementation. It groups all input files per 5 to limit max 5 parallel uncompressing processes. Then repartitions and write to Parquet to enable further processing. To me this implementation seems to totally miss the point of Dask.

from laspy.file import File
import numpy as np
import pandas as pd
import dask.dataframe as dd
from dask.delayed import delayed

@delayed
def load(file):
    with File(file.as_posix(), mode='r') as las_data:
        las_df = pd.DataFrame(las_data.points['point'], dtype=float)
        return las_df

meta = pd.DataFrame(np.empty(0, dtype=[('X',float),('Y',float),('Z',float),('intensity',float),('raw_classification',int)]))

lasfile_dir = Path('/data/las/')
lasfiles = sorted(list(lasfile_dir.glob('*.laz')))

part_size = 5000000

for idx, sublasfiles in enumerate([lasfiles[i:i+5] for i in range(0,len(lasfiles),5)]):
    try:
        dfs = [load(file) for file in sublasfiles]
        df = dd.from_delayed(dfs, meta=meta)
        df = df.repartition(npartitions=len(df) // part_size)
        df.to_parquet('/data/las/parquet/'+str(idx), compression='GZIP')


问:
Turning NSData back to plain text NSString
I have a simple NSString and I'm converting it to NSData :

```<code>NSData *data = [[NSData dataWithBytes:[[NSString stringWithFormat:@",%@",self.targetId] dataUsingEncoding:NSASCIIStringEncoding]
                              length:[[NSString stringWithFormat:@",%@",self.targetId] lengthOfBytesUsingEncoding:NSASCIIStringEncoding]] retain];
</code>```

Now I want to get the plain text from the NSData object.

If I'm doing that :

```<code>NSString* dataStr = [NSString stringWithFormat:@"%@",data];
</code>```

- I'm getting just an hex expression (i.e <9c3f473e 02000000 0b0000>) and not the plain string I want !

I've tried also using initWithData -

```<code>    NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
</code>```

But it always shows gibrish, no matter which encoding I give it.

Can you please help here ?? :)

答:
Do following change it will work.

```<code>NSData *data = [[NSString stringWithFormat:@",%@",self.targetId] dataUsingEncoding:NSASCIIStringEncoding] ;
</code>```

You did NData of data.

Body:
I have a simple NSString and I'm converting it to NSData :

NSData *data = [[NSData dataWithBytes:[[NSString stringWithFormat:@",%@",self.targetId] dataUsingEncoding:NSASCIIStringEncoding]
                              length:[[NSString stringWithFormat:@",%@",self.targetId] lengthOfBytesUsingEncoding:NSASCIIStringEncoding]] retain];

Now I want to get the plain text from the NSData object.

If I'm doing that :

NSString* dataStr = [NSString stringWithFormat:@"%@",data];

- I'm getting just an hex expression (i.e <9c3f473e 02000000 0b0000>) and not the plain string I want !

I've tried also using initWithData -

    NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

But it always shows gibrish, no matter which encoding I give it.

Can you please help here ?? :)

Body:
Do following change it will work.

NSData *data = [[NSString stringWithFormat:@",%@",self.targetId] dataUsingEncoding:NSASCIIStringEncoding] ;

You did NData of data.


问:
Delete a file inside a folder in Google cloud storage
My wish is very simple and basic. However, I can't find any working/clear answer for it :D

I want to know how to delete a file inside a folder in Google Cloud storage.

If let's say I have a bucket name of xxxx.appspot.com and I have a folder inside called images and I have an image inside this folder (E.g. 123.jpg) which I want to delete.

This is the code I wrote, however it didn't delete it:

```<code>String bucketName = "xxxx.appspot.com";
GcsService gcsService = GcsServiceFactory.createGcsService();
gcsService.delete(new GcsFilename(bucketName,"images/123.jpg"));
</code>```

Did I miss anything?

Thanks in Advance!

答:
You can find some code samples in the documentation. In short, what you want to achieve can be done in Java using a couple of lines of code, given that you have the right permissions:</p>
```<code>BlobId b = BlobId.of(bucketName, blobName);
boolean deleted = storage.delete(b);
</code>```

Body:
My wish is very simple and basic. However, I can't find any working/clear answer for it :D

I want to know how to delete a file inside a folder in Google Cloud storage.

If let's say I have a bucket name of xxxx.appspot.com and I have a folder inside called images and I have an image inside this folder (E.g. 123.jpg) which I want to delete.

This is the code I wrote, however it didn't delete it:

String bucketName = "xxxx.appspot.com";
GcsService gcsService = GcsServiceFactory.createGcsService();
gcsService.delete(new GcsFilename(bucketName,"images/123.jpg"));

Did I miss anything?

Thanks in Advance!

Body:
You can find some code samples in the documentation. In short, what you want to achieve can be done in Java using a couple of lines of code, given that you have the right permissions:

BlobId b = BlobId.of(bucketName, blobName);
boolean deleted = storage.delete(b);


问:
Scrollview with React Native isn't scrolling
I am currently working on a react native project which requires me to make a profile page.  Im trying to use scrollview to render an image with words underneath it.  Here is my code:

```<code>// @flow

import React, { Component } from 'react';
import { Dimensions } from 'react-native';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  ScrollView,
  TouchableWithoutFeedback,
  FlatList,
} from 'react-native';

//import PictureScroller from './PictureScroller';
//import TaggButton from './TaggButton';
import styles from './styles';

//import PropTypes from 'prop-types';

type Props = {
  images: Object,
  name: String,
}

const Profile = (props: Props) => {

    return (
      <ScrollView style={styles.scrollView} contentContainerStyle={{flex:1}}>
        <Image source={props.images}/>
        <Text style={styles.name}>props.name</Text>
      </ScrollView>
      );
    }

export default Profile;
</code>```

Please let me know if I should include additional code.

答:
or else try this </p>

```<code><View style={{flex:1}}>
 <ScrollView>
    <Image source={props.images}/>
    <Text style={styles.name}>props.name</Text>
 </ScrollView>
</View>
</code>```

Body:
I am currently working on a react native project which requires me to make a profile page.  Im trying to use scrollview to render an image with words underneath it.  Here is my code:

// @flow

import React, { Component } from 'react';
import { Dimensions } from 'react-native';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  ScrollView,
  TouchableWithoutFeedback,
  FlatList,
} from 'react-native';

//import PictureScroller from './PictureScroller';
//import TaggButton from './TaggButton';
import styles from './styles';

//import PropTypes from 'prop-types';

type Props = {
  images: Object,
  name: String,
}

const Profile = (props: Props) => {

    return (
      <ScrollView style={styles.scrollView} contentContainerStyle={{flex:1}}>
        <Image source={props.images}/>
        <Text style={styles.name}>props.name</Text>
      </ScrollView>
      );
    }

export default Profile;

Please let me know if I should include additional code.

Body:
or else try this

<View style={{flex:1}}>
 <ScrollView>
    <Image source={props.images}/>
    <Text style={styles.name}>props.name</Text>
 </ScrollView>
</View>


问:
Manipulate CSS of class that is to be added after DOM load
I have a news scroller which is created by appending lis from an array to a ul element. I am making it scroll via the following function:

```<code>$newsItem = $('.news-item');

function newsScroll() {
  $newsItem.eq(currentNewsItem).fadeIn(1000);
  setTimeout(function() {
    $newsItem.eq(currentNewsItem).addClass('move-left');
  }, 2000);
}
</code>```

It adds .move-left class to li where .move-left has CSS rules:

```<code>.move-left {
  -webkit-transition: 5s;
  -moz-transition: 5s;
  -ms-transition: 5s;
  -o-transition: 5s;
  transition: 5s;
  left: -400px;
}
</code>```

The problem is that all the news items are not the same length; some of them exceed the 400px. Thus moving them 400px left, doesn't scroll them out of the display of the scroller.

So I have used the following code to determine the width of the longest of these elements, but I am unsure how to affix this to the class .move-left, or how to alter a class that is not a part of the DOM.

```<code>var moveLeftAmt = Math.max.apply(null, $('ul#newsScroller li').map(function() {
  return $(this).outerWidth(true);
}).get());
</code>```

Any suggestions?

答:
probably you can do like this:

```<code>var moveLeftAmt = Math.max.apply(null, $('ul#newsScroller li').map(function() {
return $(this).outerWidth(true);
}).get());
</code>```

So with above code you will get the highest width in moveLeftAmtand then apply it to the element as an inline css using the following code:

```<code>$newsItem.eq(currentNewsItem).css('left',moveLeftAmt);
</code>```

OR

```<code>$newsItem.eq(currentNewsItem).attribute('style',"left:"+moveLeftAmt+"px;");  // Appended `px` after the variable.
</code>```

Body:
I have a news scroller which is created by appending lis from an array to a ul element. I am making it scroll via the following function:

$newsItem = $('.news-item');

function newsScroll() {
  $newsItem.eq(currentNewsItem).fadeIn(1000);
  setTimeout(function() {
    $newsItem.eq(currentNewsItem).addClass('move-left');
  }, 2000);
}

It adds .move-left class to li where .move-left has CSS rules:

.move-left {
  -webkit-transition: 5s;
  -moz-transition: 5s;
  -ms-transition: 5s;
  -o-transition: 5s;
  transition: 5s;
  left: -400px;
}

The problem is that all the news items are not the same length; some of them exceed the 400px. Thus moving them 400px left, doesn't scroll them out of the display of the scroller.

So I have used the following code to determine the width of the longest of these elements, but I am unsure how to affix this to the class .move-left, or how to alter a class that is not a part of the DOM.

var moveLeftAmt = Math.max.apply(null, $('ul#newsScroller li').map(function() {
  return $(this).outerWidth(true);
}).get());

Any suggestions?

Body:
probably you can do like this:

var moveLeftAmt = Math.max.apply(null, $('ul#newsScroller li').map(function() {
return $(this).outerWidth(true);
}).get());

So with above code you will get the highest width in moveLeftAmtand then apply it to the element as an inline css using the following code:

$newsItem.eq(currentNewsItem).css('left',moveLeftAmt);

OR

$newsItem.eq(currentNewsItem).attribute('style',"left:"+moveLeftAmt+"px;");  // Appended `px` after the variable.


问:
Create reference to object in unique_ptr with typecast

I find I still do an embarrassingly large number of things in c style, so I am now trying to embrace the new millennium by reducing my usage of raw pointers. I have a vector of unique_ptr<BaseClass>, that each points to an object of a derived class. I am trying to get a nice way to refer to one of the objects of the derived class. At the moment, I do this by using the .get() function and casting this to the derived class.

However, as I understand it, .get() is mostly there to interface with legacy code that insists on raw pointers, and its use should be avoided. Having another pointer to an object within a unique_ptr doesn't seem like great style if it can be avoided. Is there a way to get a reference to the derived class object, without using get? Or some other convenient way of handling the object?

Here is a simplified code example:

#include <iostream>
#include <vector>

class Fruit {
public:
    double size = 0;
    virtual ~Fruit() = default;
};

class Apple : public Fruit {
public:
    bool hasLeaf = false;
};

void doAppleStuff(std::vector<std::unique_ptr<Fruit> > &apples) {

    // assume we know that element [0] exists and it is definitely of type Apple
    auto apple = static_cast<Apple *> (apples[0].get());  // is there a better option?

    if (apple->hasLeaf) {
        std::cout << "We can leaf now" << std::endl;
    } else {
        std::cout << "We are pitiably leafless" << std::endl;
    }
}

int main() {
    std::vector<std::unique_ptr<Fruit> > fruitVec;
    auto apple = new Apple;
    apple->hasLeaf = true;
    std::unique_ptr<Fruit> applePt(apple);
    fruitVec.push_back(std::move(applePt));
    doAppleStuff(fruitVec);
    return 0;
}
```

<p>(I think that it's probably possible to shorten the main function with <code>make_unique</code> from c++14).</p>

<p>Would it be good coding style to do something like this?</p>

<pre class="lang-cpp prettyprint-override"><code>auto &apple = *static_cast<Apple *> (apples[0].get());
</code>```

The answer at "Downcasting" unique_ptr<Base> to unique_ptr<Derived> outlines a method to "cast" the unique_ptr by releasing it and recreating a new unique_ptr to the derived class, but that doesn't seem applicable here, as I don't really want to mess with the vector of unique pointers (unless I am missing something).

答:
A safer alternative is to define a helper function

```<code>template <typename T> //
std::vector<T *> of_type(const std::vector<std::unique_ptr<Fruit>> & fruits) {
    std::vector<T *> result;
    for (auto & ptr : fruits) {
        if (T * item = dynamic_cast<T *>(ptr.get())) {
            result.push_back(item);
        }
    }
    return result;
}
</code>```

and then change doAppleStuff to

```<code>void doAppleStuff(std::vector<Apple *> & apples);
</code>```

called as

```<code>doAppleStuff(as_type<Apple>(fruitVec));
</code>```

Body:
I find I still do an embarrassingly large number of things in c style, so I am now trying to embrace the new millennium by reducing my usage of raw pointers. I have a vector of unique_ptr<BaseClass>, that each points to an object of a derived class. I am trying to get a nice way to refer to one of the objects of the derived class. At the moment, I do this by using the .get() function and casting this to the derived class.

However, as I understand it, .get() is mostly there to interface with legacy code that insists on raw pointers, and its use should be avoided. Having another pointer to an object within a unique_ptr doesn't seem like great style if it can be avoided. Is there a way to get a reference to the derived class object, without using get? Or some other convenient way of handling the object?

Here is a simplified code example:

#include <iostream>
#include <vector>

class Fruit {
public:
    double size = 0;
    virtual ~Fruit() = default;
};

class Apple : public Fruit {
public:
    bool hasLeaf = false;
};

void doAppleStuff(std::vector<std::unique_ptr<Fruit> > &apples) {

    // assume we know that element [0] exists and it is definitely of type Apple
    auto apple = static_cast<Apple *> (apples[0].get());  // is there a better option?

    if (apple->hasLeaf) {
        std::cout << "We can leaf now" << std::endl;
    } else {
        std::cout << "We are pitiably leafless" << std::endl;
    }
}

int main() {
    std::vector<std::unique_ptr<Fruit> > fruitVec;
    auto apple = new Apple;
    apple->hasLeaf = true;
    std::unique_ptr<Fruit> applePt(apple);
    fruitVec.push_back(std::move(applePt));
    doAppleStuff(fruitVec);
    return 0;
}

(I think that it's probably possible to shorten the main function with make_unique from c++14).

Would it be good coding style to do something like this?

auto &apple = *static_cast<Apple *> (apples[0].get());

The answer at "Downcasting" unique_ptr<Base> to unique_ptr<Derived> outlines a method to "cast" the unique_ptr by releasing it and recreating a new unique_ptr to the derived class, but that doesn't seem applicable here, as I don't really want to mess with the vector of unique pointers (unless I am missing something).

Body:
A safer alternative is to define a helper function

template <typename T> //
std::vector<T *> of_type(const std::vector<std::unique_ptr<Fruit>> & fruits) {
    std::vector<T *> result;
    for (auto & ptr : fruits) {
        if (T * item = dynamic_cast<T *>(ptr.get())) {
            result.push_back(item);
        }
    }
    return result;
}

and then change doAppleStuff to

void doAppleStuff(std::vector<Apple *> & apples);

called as

doAppleStuff(as_type<Apple>(fruitVec));