问:
Binary XML file line #0: Error inflating class TextureView

I have been working on a subclass of TextureView based on the answer to this question. Here's my codes:

```<code>package com.example.edward.openglproject;

public class GLTextureView extends TextureView implements TextureView.SurfaceTextureListener {

    public GLTextureView(Context context) {
        super(context);
        // Do stuff
    }

    public GLTextureView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // Do stuff
    }

    public GLTextureView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // Do stuff
    }

    public GLTextureView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        // Do stuff
    }

// Do other stuff

}
</code>```

My activity_camera.xml file:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0099cc"
    tools:context="com.example.edward.openglproject.CameraActivity">

    <com.example.edward.openglproject.Rendering.GLTextureView
        android:id="@+id/textureView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <!-- Unrelated stuff -->
</FrameLayout>
</code>```

Whenever I run the program, it crashes where the activity calls

```<code>setContentView(R.layout.activity_camera);
</code>```

and returns this error:

```<code>12-07 16:49:01.249 5595-5595/com.example.edward.openglproject E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.edward.openglproject, PID: 5595
                                                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.edward.openglproject/com.example.edward.openglproject.CameraActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.example.edward.openglproject                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                              Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.example.edward.openglproject.Rendering.GLTextureView
                                                                              Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class com.example.edward.openglproject.TextureView
                                                                              Caused by: java.lang.reflect.InvocationTargetException
                                                                                at java.lang.reflect.Constructor.newInstance0(Native Method)
                                                                                at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
                                                                                at android.view.LayoutInflater.createView(LayoutInflater.java:647)
                                                                                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
                                                                                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
                                                                                at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
                                                                                at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                                                                                at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                                                                                at com.example.edward.openglproject.CameraActivity.onCreate(CameraActivity.java:296)
                                                                                at android.app.Activity.performCreate(Activity.java:6975)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

I have looked around on this site, and most of the solutions involves making the constructors public, which I have done.

Can anyone tell me what's needed to be done?

答:
Should correct package name of GLTextureView in code or xml.

In code: com.example.edward.openglproject.GLTextureView

In xml: com.example.edward.openglproject.rendering.GLTextureView

In log: com.example.edward.openglproject.Rendering.GLTextureView

I also think it's odd to have original TextureView (not of Android one).

In log: com.example.edward.openglproject.TextureView

Body:
I have been working on a subclass of TextureView based on the answer to this question. Here's my codes:

package com.example.edward.openglproject;

public class GLTextureView extends TextureView implements TextureView.SurfaceTextureListener {

    public GLTextureView(Context context) {
        super(context);
        // Do stuff
    }

    public GLTextureView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // Do stuff
    }

    public GLTextureView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // Do stuff
    }

    public GLTextureView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        // Do stuff
    }

// Do other stuff

}

My activity_camera.xml file:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0099cc"
    tools:context="com.example.edward.openglproject.CameraActivity">

    <com.example.edward.openglproject.Rendering.GLTextureView
        android:id="@+id/textureView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</FrameLayout>

Whenever I run the program, it crashes where the activity calls

setContentView(R.layout.activity_camera);

and returns this error:

12-07 16:49:01.249 5595-5595/com.example.edward.openglproject E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.edward.openglproject, PID: 5595
                                                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.edward.openglproject/com.example.edward.openglproject.CameraActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.example.edward.openglproject                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                              Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.example.edward.openglproject.Rendering.GLTextureView
                                                                              Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class com.example.edward.openglproject.TextureView
                                                                              Caused by: java.lang.reflect.InvocationTargetException
                                                                                at java.lang.reflect.Constructor.newInstance0(Native Method)
                                                                                at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
                                                                                at android.view.LayoutInflater.createView(LayoutInflater.java:647)
                                                                                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
                                                                                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
                                                                                at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
                                                                                at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                                                                                at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                                                                                at com.example.edward.openglproject.CameraActivity.onCreate(CameraActivity.java:296)
                                                                                at android.app.Activity.performCreate(Activity.java:6975)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

I have looked around on this site, and most of the solutions involves making the constructors public, which I have done.

Can anyone tell me what's needed to be done?


来源: stackexchange

问:
php xtea implementation (cfb)
I came accross a weird behaviour that i could not comprehend.

I am using mcrypt xtea (cfb mode) to encrypt some data.
Since php 7.2 is getting rid of mcrypt and since openssl does nor support Xtea, i had to implement the algorithm myself.

The problem is, no matter the algorithm used :

I tested the one provided here: pear implementation which is an ECB mode only (no init vector)

And the one provided on the wikipedia page taken from this stackoverflow topic

And the one i developed here (for the CFB mode) basing myself on the two following articles from wikipedia here  and here and mcrypt source code that can be found here    :

```<code>/*
* $v is the data, $k is the 128bits key and $iv is 64bits init vector (size = 8)
* Code is not optimized
*/
function encryptCfb($v, $k, $iv) {

    $v = array_values(unpack('N*', $v));
    $iv = array_values(unpack('N*', $iv));
    $k = array_values(unpack('N*', $k));

    $cipher = [];

    //IV ciphering using the 128bits key
    list ($v0, $v1) = cipher($iv[0], $iv[1], $k);
    //Xoring the cipherd block with the first 64bits of data (32bits in V0 and 32 others in V1)
    $cipher[0] =  $v0 ^ $v[0];
    $cipher[1] =  $v1 ^ $v[1];

    for ($i=2; $i < count($v); $i+=2) {
        //Now ciphering the latest "cipherd" data using the 128bits key
        list ($y, $z) = cipher($cipher[$i-2], $cipher[$i-1], $k);

        //Xoring the cipherd block with the second 64bits of data (32bits in V0 and 32 others in V1)
         $cipher[$i] =  $y ^ $v[$i];
         $cipher[$i+1] =  $z ^ $v[$i+1];
    }

    $output = "";
    foreach ($cipher as $i) {
        $output .= pack('N', $i);
    }

    return $output;
}

function cipher($v0, $v1, $k) {

    $delta=0x9e3779b9;
    $sum = 0;
    $limit = $delta * 32;

    for ($i=0; $i < 32; $i++) {
        $v0 += ((($v1<<4) ^ ($v1>>5)) + $v1) ^ ($sum + $k[$sum & 3]);
        $sum += $delta;
        $v1 += ((($v0 << 4) ^ ($v0 >> 5)) + $v0) ^ ($sum + $k[($sum>>11) & 3]);
    }

    return [$v0, $v1];
}
</code>```

i get a different result and furthmore, none of them gives the exact same result mcrypt gives using :

```<code>$cryptModule = mcrypt_module_open('xtea', '', 'ncfb', '');
mcrypt_generic_init($cryptModule, $key, $iv);
mcrypt_generic($cryptModule, $data);
</code>```

You can check and test the different tests i made here using same data/key/IV :

My implementation VS mcrypt in CFB mode. Note that :

The number of rounds changes nothing (32 or 64)

Packing/Unpacking using N mode (big endian) or V mode (little endian) changes nothings

PEAR ECB mode vs mycrypt ECB mode!

The wiki code in CBC mode code vs mcrypt in cbc mode!

Does anyone know why i get different result?

答:
It should work with modulus on $v0 and $v1:

```<code>function cipher($v0, $v1, $k) {
    $delta = 0x9e3779b9;
    $sum = 0;
    $limit = $delta * 32;

    for ($i=0; $i < 32; $i++) {
        $v0 += ((($v1<<4) ^ ($v1>>5)) + $v1) ^ ($sum + $k[$sum & 3]);
        $v0 = $v0 % pow(2, 32);
        $sum += $delta;
        $v1 += ((($v0 << 4) ^ ($v0 >> 5)) + $v0) ^ ($sum + $k[($sum>>11) & 3]);
        $v1 = $v1 % pow(2, 32);
    }

    return [$v0, $v1];
}
</code>```

You will also need to resize the input value $v to make sure it has a correct length, for example with the _resize(&$data, $size, $nonull = false) function of the PEAR module Crypt_Xtea you mention.

ContentLicense: CC BY-SA 3.0

Title: php xtea implementation (cfb)

Body:
I came accross a weird behaviour that i could not comprehend.

I am using mcrypt xtea (cfb mode) to encrypt some data.
Since php 7.2 is getting rid of mcrypt and since openssl does nor support Xtea, i had to implement the algorithm myself.

The problem is, no matter the algorithm used :

I tested the one provided here: pear implementation which is an ECB mode only (no init vector)

And the one provided on the wikipedia page taken from this stackoverflow topic

And the one i developed here (for the CFB mode) basing myself on the two following articles from wikipedia here  and here and mcrypt source code that can be found here    :

/*
* $v is the data, $k is the 128bits key and $iv is 64bits init vector (size = 8)
* Code is not optimized
*/
function encryptCfb($v, $k, $iv) {

    $v = array_values(unpack('N*', $v));
    $iv = array_values(unpack('N*', $iv));
    $k = array_values(unpack('N*', $k));

    $cipher = [];

    //IV ciphering using the 128bits key
    list ($v0, $v1) = cipher($iv[0], $iv[1], $k);
    //Xoring the cipherd block with the first 64bits of data (32bits in V0 and 32 others in V1)
    $cipher[0] =  $v0 ^ $v[0];
    $cipher[1] =  $v1 ^ $v[1];

    for ($i=2; $i < count($v); $i+=2) {
        //Now ciphering the latest "cipherd" data using the 128bits key
        list ($y, $z) = cipher($cipher[$i-2], $cipher[$i-1], $k);

        //Xoring the cipherd block with the second 64bits of data (32bits in V0 and 32 others in V1)
         $cipher[$i] =  $y ^ $v[$i];
         $cipher[$i+1] =  $z ^ $v[$i+1];
    }

    $output = "";
    foreach ($cipher as $i) {
        $output .= pack('N', $i);
    }

    return $output;
}

function cipher($v0, $v1, $k) {

    $delta=0x9e3779b9;
    $sum = 0;
    $limit = $delta * 32;

    for ($i=0; $i < 32; $i++) {
        $v0 += ((($v1<<4) ^ ($v1>>5)) + $v1) ^ ($sum + $k[$sum & 3]);
        $sum += $delta;
        $v1 += ((($v0 << 4) ^ ($v0 >> 5)) + $v0) ^ ($sum + $k[($sum>>11) & 3]);
    }

    return [$v0, $v1];
}

i get a different result and furthmore, none of them gives the exact same result mcrypt gives using :

$cryptModule = mcrypt_module_open('xtea', '', 'ncfb', '');
mcrypt_generic_init($cryptModule, $key, $iv);
mcrypt_generic($cryptModule, $data);

You can check and test the different tests i made here using same data/key/IV :

My implementation VS mcrypt in CFB mode. Note that :

The number of rounds changes nothing (32 or 64)

Packing/Unpacking using N mode (big endian) or V mode (little endian) changes nothings

PEAR ECB mode vs mycrypt ECB mode!

The wiki code in CBC mode code vs mcrypt in cbc mode!

Does anyone know why i get different result?

Body:
It should work with modulus on $v0 and $v1:

function cipher($v0, $v1, $k) {
    $delta = 0x9e3779b9;
    $sum = 0;
    $limit = $delta * 32;

    for ($i=0; $i < 32; $i++) {
        $v0 += ((($v1<<4) ^ ($v1>>5)) + $v1) ^ ($sum + $k[$sum & 3]);
        $v0 = $v0 % pow(2, 32);
        $sum += $delta;
        $v1 += ((($v0 << 4) ^ ($v0 >> 5)) + $v0) ^ ($sum + $k[($sum>>11) & 3]);
        $v1 = $v1 % pow(2, 32);
    }

    return [$v0, $v1];
}

You will also need to resize the input value $v to make sure it has a correct length, for example with the _resize(&$data, $size, $nonull = false) function of the PEAR module Crypt_Xtea you mention.


问:
Shiny slider restrict reaction to releasing left mouse button
I am using a Shiny application in which it may take some time to set a slider to the right value.

So while trying to set the slider to the right value (and not releasing my left mouse button!) the (i.e. my local) server observed several new values and reacts accordingly.

As the response of my server on any new value may take a few seconds I would be pleased if I could either:

postpone signalling the server till the release of the left mouse button, or

at the server side, abort any earlier responses if it receive a new value

答:
Alright, after some digging, I think I've found the solution. It appears the cleanest way to do this, without needing to mess with Java script, would be to use the shinyCustom package, which has a useShinyCustom and customSliderInput function. With these, you can set the reactivity to "debounce" and also mess with the delay time. If you were to use these options together, you should be able to find the sweet spot for only updating the output once the slider stops moving. It won't be a perfect "on release of mouse button;" but it should be pretty darn close!

For example, you may try something like:

```<code># Slider delay type is actually "debounce" by default
useShinyCustom(slider_delay = "500"), # Doubles the default delay time in ms
customSliderInput("bins", #Use customSliderInput instead of sliderInput
              "Number of bins:",
              min = 1,
              max = 50,
              value = 30)
</code>```

Body:
Alright, after some digging, I think I've found the solution. It appears the cleanest way to do this, without needing to mess with Java script, would be to use the shinyCustom package, which has a useShinyCustom and customSliderInput function. With these, you can set the reactivity to "debounce" and also mess with the delay time. If you were to use these options together, you should be able to find the sweet spot for only updating the output once the slider stops moving. It won't be a perfect "on release of mouse button;" but it should be pretty darn close!

For example, you may try something like:

# Slider delay type is actually "debounce" by default
useShinyCustom(slider_delay = "500"), # Doubles the default delay time in ms
customSliderInput("bins", #Use customSliderInput instead of sliderInput
              "Number of bins:",
              min = 1,
              max = 50,
              value = 30)


问:
How is it possible to do UI operations outside the UI thread?
I tried to set a text inside a normal thread outside of the UI thread and it worked fine.

```<code>    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.my_text);
        Log.d("**** ONCREATE****", Thread.currentThread().getId()+"");
        new BackgroundTestThread().start();
    }

    class BackgroundTestThread extends Thread{
    @Override
    public void run() {
         Log.d("**** THREAD****", Thread.currentThread().getId()+"");
         mTextView.setText("Text was set successfully", TextView.BufferType.EDITABLE);
         }
    }
</code>```

I was pretty much surprised to see this happen. I thought a worker thread can never update main thread because only main thread can render the UI elements (TextView, EditText etc.) and if we try to update, for sure we are going to get an exception.

Why did this happen?

答: Android doesnt check every where whether its UI thread or Not so in some cases it might work .but its never thread safe.The preferred way is to display in UIThread.</p>

Body:
I tried to set a text inside a normal thread outside of the UI thread and it worked fine.

    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.my_text);
        Log.d("**** ONCREATE****", Thread.currentThread().getId()+"");
        new BackgroundTestThread().start();
    }

    class BackgroundTestThread extends Thread{
    @Override
    public void run() {
         Log.d("**** THREAD****", Thread.currentThread().getId()+"");
         mTextView.setText("Text was set successfully", TextView.BufferType.EDITABLE);
         }
    }

I was pretty much surprised to see this happen. I thought a worker thread can never update main thread because only main thread can render the UI elements (TextView, EditText etc.) and if we try to update, for sure we are going to get an exception.

Why did this happen?


问:
How to write console output on text file
I am new to programming and I've searched the webpage for the answer to this question and have tried many possibilities without success. I have currently managed to connect a potentiometer to my raspberry and get values on the console, but I don't know how to save these values onto a text file. This is my code:

```<code> #!/usr/bin/python
import spidev
import time

#Define Variables
delay = 0.5
ldr_channel = 0

#Create SPI
spi = spidev.SpiDev()
spi.open(0, 0)

def readadc(adcnum):
  # read SPI data from the MCP3008, 8 channels in total
  if adcnum > 7 or adcnum < 0:
    return -1
  r = spi.xfer2([1, 8 + adcnum << 4, 0])
  data = ((r[1] & 3) << 8) + r[2]
  return data

while True:
  ldr_value = readadc(ldr_channel)
  print ('---------------------------------------')
  print("LDR Value: %d" % ldr_value)
  time.sleep(delay)
  file = open('data.txt','w')
  file.write("LDR Value: %d" % ldr_value)
  file.close()`
</code>```

As you can see from the code, I can get the last value onto data.txt, but not all the values in time. Thank you very much in advance and I am sorry for my "noobness"

答:
When you execute a file in the terminal, you can redirect the outputs of this script to a file like this:

```<code>$ python script.py > /the/path/to/your/file
</code>```

In Python you just have to set the sys.stdout to a file and  then, all the prints will be redirected to /the/path/to/your/file.

```<code>import sys
sys.stdout = open('/the/path/to/your/file', 'w')
</code>```

and do not forget to close the file at the end of your script ;)

```<code>sys.stdout.close()
</code>```

Body:
I am new to programming and I've searched the webpage for the answer to this question and have tried many possibilities without success. I have currently managed to connect a potentiometer to my raspberry and get values on the console, but I don't know how to save these values onto a text file. This is my code:

 #!/usr/bin/python
import spidev
import time

#Define Variables
delay = 0.5
ldr_channel = 0

#Create SPI
spi = spidev.SpiDev()
spi.open(0, 0)

def readadc(adcnum):
  # read SPI data from the MCP3008, 8 channels in total
  if adcnum > 7 or adcnum < 0:
    return -1
  r = spi.xfer2([1, 8 + adcnum << 4, 0])
  data = ((r[1] & 3) << 8) + r[2]
  return data

while True:
  ldr_value = readadc(ldr_channel)
  print ('---------------------------------------')
  print("LDR Value: %d" % ldr_value)
  time.sleep(delay)
  file = open('data.txt','w')
  file.write("LDR Value: %d" % ldr_value)
  file.close()`

As you can see from the code, I can get the last value onto data.txt, but not all the values in time. Thank you very much in advance and I am sorry for my "noobness"

Body:
When you execute a file in the terminal, you can redirect the outputs of this script to a file like this:

$ python script.py > /the/path/to/your/file

In Python you just have to set the sys.stdout to a file and  then, all the prints will be redirected to /the/path/to/your/file.

import sys
sys.stdout = open('/the/path/to/your/file', 'w')

and do not forget to close the file at the end of your script ;)

sys.stdout.close()

ContentLicense: CC BY-SA 4.0


问:
wrong python html parsing
My code:

```<code>from bs4 import BeautifulSoup
import urllib.request

url = "http://yaz.tek.firat.edu.tr/tr/duyurular"
url_oku = urllib.request.urlopen(url)
soup = BeautifulSoup(url_oku, 'html.parser')
icerik = soup.find_all('div',attrs={'class':'views-row views-row-1 views-row-odd views-row-first'})
print(kardiz)
</code>```

my output :

```<code>[<div class="views-row views-row-1 views-row-odd views-row-first">
<span class="views-field views-field-title"> <span class="field-content"><a href="/tr/node/479">Grup-1, Grup-2, Grup-3, Grup-4 ve Grup-6 Öğrencileri İçin Staj Sunum Tarihleri</a></span> </span>
<span class="views-field views-field-created"> <span class="field-content"><i class="fa fa-calendar"></i> Salı, Aralık 5, 2017 - 09:58 </span> </span> </div>]
</code>```

But I want to get just " Grup-1, Grup-2, Grup-3, Grup-4 ve Grup-6 Öğrencileri İçin Staj Sunum Tarihleri ". How can I achieve that?

答:
You can call .text on a result from BeautifulSoup. It takes the textual content of the elements found, skipping the tags of the elements.

e.g.

```<code>from bs4 import BeautifulSoup
import urllib.request

url = "http://yaz.tek.firat.edu.tr/tr/duyurular"
url_oku = urllib.request.urlopen(url)
soup = BeautifulSoup(url_oku, 'html.parser')
icerik = soup.find_all('div',attrs={'class':'views-row views-row-1 views-row-odd views-row-first'})
for result in icerik:
  print(result.text)
</code>```

Title: wrong python html parsing

Body:
My code:

from bs4 import BeautifulSoup
import urllib.request

url = "http://yaz.tek.firat.edu.tr/tr/duyurular"
url_oku = urllib.request.urlopen(url)
soup = BeautifulSoup(url_oku, 'html.parser')
icerik = soup.find_all('div',attrs={'class':'views-row views-row-1 views-row-odd views-row-first'})
print(kardiz)

my output :

[

 Grup-1, Grup-2, Grup-3, Grup-4 ve Grup-6 Öğrencileri İçin Staj Sunum Tarihleri
  Salı, Aralık 5, 2017 - 09:58
]

But I want to get just " Grup-1, Grup-2, Grup-3, Grup-4 ve Grup-6 Öğrencileri İçin Staj Sunum Tarihleri ". How can I achieve that?

Body:
You can call .text on a result from BeautifulSoup. It takes the textual content of the elements found, skipping the tags of the elements.

e.g.

from bs4 import BeautifulSoup
import urllib.request

url = "http://yaz.tek.firat.edu.tr/tr/duyurular"
url_oku = urllib.request.urlopen(url)
soup = BeautifulSoup(url_oku, 'html.parser')
icerik = soup.find_all('div',attrs={'class':'views-row views-row-1 views-row-odd views-row-first'})
for result in icerik:
  print(result.text)


问:
MongoDB check connection of replica member before connecting with Java driver
I am implementing a feature in Java to check the status of the replica set. To do that, I have to connect to one member of the replica set. I extracted the information of each replica set from mongos and stored them in an array, from that array I can get the uri of all replica members.  The problem is that I don't know how to detect if that uri works or not before connecting to it. Currently, I am doing this:

```<code>MongoClient shard = new MongoClient(Arrays.asList(
                new ServerAddress(replicaUriTemp[0]),
                new ServerAddress(replicaUriTemp[1]),
                new ServerAddress(replicaUriTemp[2])));
</code>```

When I stop two replica members [0] and [1], the program cannot connect to [2] and perform the replSetGetStatus command. It always throws this exception:

```<code>MongoTimeoutException: A server error occurred: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=REPLICA_SET, servers=[{address=dockerbox:21100, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=dockerbox:21200, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=dockerbox:21300, type=REPLICA_SET_SECONDARY, roundTripTime=1.0 ms, state=CONNECTED}]
</code>```

However, it works fine when I try to connect to replica member [2] directly:

```<code>MongoClient shard = new MongoClient(new ServerAddress(replicaUriTemp[2]));
</code>```

Is there a way to resolve this matter by connecting to each replica member dynamically, or ping the member before attempting to connect to it ?  I want to blindly test status of replica set without knowing in advance which one is primary/secondary member.

Edit: Seems like the error appears in the my next line of code:

```<code>Document replStatus = shard.getDatabase("admin").runCommand(replStatCmd);
</code>```

Since I turn off two replica members, the left one will become a secondary and that's why I cannot perform runCommand on this member.

答: Ok, after I set the option runCommand to ReadPreference.secondaryPreferred(), the program works fine now.</p>

Body:
I am implementing a feature in Java to check the status of the replica set. To do that, I have to connect to one member of the replica set. I extracted the information of each replica set from mongos and stored them in an array, from that array I can get the uri of all replica members.  The problem is that I don't know how to detect if that uri works or not before connecting to it. Currently, I am doing this:

MongoClient shard = new MongoClient(Arrays.asList(
                new ServerAddress(replicaUriTemp[0]),
                new ServerAddress(replicaUriTemp[1]),
                new ServerAddress(replicaUriTemp[2])));

When I stop two replica members [0] and [1], the program cannot connect to [2] and perform the replSetGetStatus command. It always throws this exception:

MongoTimeoutException: A server error occurred: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=REPLICA_SET, servers=[{address=dockerbox:21100, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=dockerbox:21200, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=dockerbox:21300, type=REPLICA_SET_SECONDARY, roundTripTime=1.0 ms, state=CONNECTED}]

However, it works fine when I try to connect to replica member [2] directly:

MongoClient shard = new MongoClient(new ServerAddress(replicaUriTemp[2]));

Is there a way to resolve this matter by connecting to each replica member dynamically, or ping the member before attempting to connect to it ?  I want to blindly test status of replica set without knowing in advance which one is primary/secondary member.

Edit: Seems like the error appears in the my next line of code:

Document replStatus = shard.getDatabase("admin").runCommand(replStatCmd);

Since I turn off two replica members, the left one will become a secondary and that's why I cannot perform runCommand on this member.


问:
Upgrading from Just-ice.jar to Icefaces 3.3.0 GA
Currently the web logic portal application was using Icefaces 1.8.2. Now i am trying to upgrade it to 3.3, but the application code was using com.icesoft.faces.context.BridgeExternalContext getOriginalRequest method to get the HttpServletRequest by using just-ice.jar provided by Icefaces1.8.2. Can any one guide whats the alternate class and Jar that i have to use in Icefaces 3.3.

Below is the code that I am using.

```<code>BridgeExternalContext bec = (BridgeExternalContext)ec;

Object originalReq = bec.getOriginalRequest();

if( originalReq instanceof HttpServletRequest){

 return (HttpServletRequest)originalReq;
}
</code>```

答:
ICEfaces 2.x and later all use the standard JSF Bridge, so BridgeExternalContext no longer is necessary.

HttpServletRequest requestObj = (HttpServletRequest)

FacesContext.getCurrentInstance().getExternalContext().getRequest();

String value =  (String) requestObj.getAttribute("property");

Would be how I would retrieve an object from the HttpServletRequest.

Body:
Currently the web logic portal application was using Icefaces 1.8.2. Now i am trying to upgrade it to 3.3, but the application code was using com.icesoft.faces.context.BridgeExternalContext getOriginalRequest method to get the HttpServletRequest by using just-ice.jar provided by Icefaces1.8.2. Can any one guide whats the alternate class and Jar that i have to use in Icefaces 3.3.

Below is the code that I am using.

BridgeExternalContext bec = (BridgeExternalContext)ec;

Object originalReq = bec.getOriginalRequest();

if( originalReq instanceof HttpServletRequest){

 return (HttpServletRequest)originalReq;
}


问:
CallKit no sound when answer second call and put first call on hold
I am facing issue with multiple calls when start using CallKit in my VOIP application.

When there is one to one VOIP call, sound is working fine. But once one party gets another VOIP call, and choose to Hold and Accept option; First call is put on hold successfully and second call is answered; But sound gets closed now. Even swapping between calls also does not work. and Dropping one call also does not work.
I am using RTP for voice.

I tried to put breakpoints and check if the AVAudioSession's category and mode are correct.

In the console I can check at my end that the device which has more than one calls, stop sending sound packets.

I am enabling VOIP just before reportNewIncomingCallWithUUID and CXStartCallAction of Provider.

Same case with GSM call. If there is one to one VOIP call with sound is ok and GSM call is received at one side and user choose to Hold and Accept option, sound in GSM call is working fine. But if user makes VOIP call as active and put GSM call on hold by swapping calls, there is no sound in VOIP call. Swapping calls and making GSM call active, sound again works fine. But no sound for VOIP call.

In this case, we are getting AVAudioSessionInterruptionTypeBegan but AVAudioSessionInterruptionTypeEnded is never called. Even after the GSM call is ended.

Has anyone run into similar issues?

答:
Had the same issue. If I have 1 active call, then new calls is incoming, I tap hold&accept. New call works, but after using Swap in CallKit audio stopped working.

After long debug found the spot where actually audio is deactivating/activating for Swap calls via CallKit native interface - that is provider:performSetHeldCallAction: method from CXProviderDelegate protocol.

In my case I used the [audioController deactivateAudioSession] method for the call was putting in OnHold.

But I found that the same method provider:performSetHeldCallAction: was fired for other call that is being put active (from OnHold state), when tap Swap button via CallKit.

So in my case I first toggle hold for call (it put call either on hold or put it active out of hold).
Then I check what is call condition (whether hold or not) and then deactivate or activate audio respectively.

In common way it looks this way:

```<code>- (void)provider:(CXProvider *)provider performSetHeldCallAction:(CXSetHeldCallAction *)action {
    SomeCallClass *call = [self.callManager callWithUUID:action.callUUID];
    if (!call) {
        [action fail];
        return;
    }

    NSError *holdError;
    [call toggleHold:&holdError];

    if (holdError) {
        [action fail];
    } else {

        if (call.onHold)
            [self.audioController deactivateAudioSession];
        else
            [self.audioController activateAudioSession];
        [action fulfill];
    }
}
</code>```

This code should be in the class that works as a CallKit provider delegate.

Body:
Had the same issue. If I have 1 active call, then new calls is incoming, I tap hold&accept. New call works, but after using Swap in CallKit audio stopped working.

After long debug found the spot where actually audio is deactivating/activating for Swap calls via CallKit native interface - that is provider:performSetHeldCallAction: method from CXProviderDelegate protocol.

In my case I used the [audioController deactivateAudioSession] method for the call was putting in OnHold.

But I found that the same method provider:performSetHeldCallAction: was fired for other call that is being put active (from OnHold state), when tap Swap button via CallKit.

So in my case I first toggle hold for call (it put call either on hold or put it active out of hold).
Then I check what is call condition (whether hold or not) and then deactivate or activate audio respectively.

In common way it looks this way:

- (void)provider:(CXProvider *)provider performSetHeldCallAction:(CXSetHeldCallAction *)action {
    SomeCallClass *call = [self.callManager callWithUUID:action.callUUID];
    if (!call) {
        [action fail];
        return;
    }

    NSError *holdError;
    [call toggleHold:&holdError];

    if (holdError) {
        [action fail];
    } else {

        if (call.onHold)
            [self.audioController deactivateAudioSession];
        else
            [self.audioController activateAudioSession];
        [action fulfill];
    }
}

This code should be in the class that works as a CallKit provider delegate.


问:
How to curve a function generated by a function closure directly?
I am trying to curve a power function like

```<code>pow <- function(n) {
    function(x){ x^n }
}
</code>```

When I curve it use the code below, everything fine

```<code>f <- pow(2)
curve(f,-2,2)
</code>```

But when I curve it with

```<code>curve(pow(2),-2,2)
</code>```

I get the error message "'expr' must be a function, or a call or an expression containing 'x'", and I want to know how to curve it without a temporary variable?

答:
Use

```<code>curve(pow(2)(x),-2,2)
</code>```

In the documentation for curve(), it expects

The name of a function, or a call or an expression written as a function of x which will evaluate to an object of the same length as x.

So f is the name of a function so that's why that works. You could have also called curve(f(x),-2,2). But pow(2) is not the name of a function, it is a function call that returns a function. But when curve sees a function call, it expects to see that call written as a function of x. So by adding the (x) part, we turn it into a function call which curve() understands.

Body:
I am trying to curve a power function like

pow <- function(n) {
    function(x){ x^n }
}

When I curve it use the code below, everything fine

f <- pow(2)
curve(f,-2,2)

But when I curve it with

curve(pow(2),-2,2)

I get the error message "'expr' must be a function, or a call or an expression containing 'x'", and I want to know how to curve it without a temporary variable?

Body:
Use

curve(pow(2)(x),-2,2)

In the documentation for curve(), it expects

The name of a function, or a call or an expression written as a function of x which will evaluate to an object of the same length as x.

So f is the name of a function so that's why that works. You could have also called curve(f(x),-2,2). But pow(2) is not the name of a function, it is a function call that returns a function. But when curve sees a function call, it expects to see that call written as a function of x. So by adding the (x) part, we turn it into a function call which curve() understands.


问:
When to use constructor and super in Polymer 2.0?
The following pattern is used a lot when building Polymer 2.0 ES6 web components.

```<code>constructor() {
  super();
}
</code>```

Here the documentation describes calling the super(); function when defining an element.

However here in the Shop App the pattern is only followed 3 times, in the following elements: shop-app.html, shop-ripple-container.html, shop-tabs-overlay.html.

When do we need to call super()? When does this call need to be inside the constructor() function? And what are the consequences of not calling super() as appears in the case of the Shop app?

Edit:
A user (@4castle) suggested this question might be a duplicate of this question. I respectfully disagree. This question deals with Polymer, whereas the other deals with React. The other question asks about arguments passed to the super() function. This question wants to know what happens when super() is not called and where the best place to call is (i.e., inside constructor() or not).

答:
In fact it's also good practice to invoke the following to get the full benefit of your super (parent):

```<code>ready() {
  super.ready();
}
</code>```

That will invoke the ready function in Element when your component is ready.

Body:
The following pattern is used a lot when building Polymer 2.0 ES6 web components.

constructor() {
  super();
}

Here the documentation describes calling the super(); function when defining an element.

However here in the Shop App the pattern is only followed 3 times, in the following elements: shop-app.html, shop-ripple-container.html, shop-tabs-overlay.html.

When do we need to call super()? When does this call need to be inside the constructor() function? And what are the consequences of not calling super() as appears in the case of the Shop app?

Edit:
A user (@4castle) suggested this question might be a duplicate of this question. I respectfully disagree. This question deals with Polymer, whereas the other deals with React. The other question asks about arguments passed to the super() function. This question wants to know what happens when super() is not called and where the best place to call is (i.e., inside constructor() or not).

Body:
In fact it's also good practice to invoke the following to get the full benefit of your super (parent):

ready() {
  super.ready();
}

That will invoke the ready function in Element when your component is ready.


问:
What is the Rubiest way to check strictly for false value (and exclude nil)?
What is the Rubiest way check that a value is false and not nil (which is a falsy value)?

example using a fictional method false?:

```<code>a = false
a.false? # should return true
a = nil
a.false? # should return false
</code>```

答:
So far we have four different approaches:</p>

```<code>a == false                 # credits to @Ilya

a.is_a?(FalseClass)
FalseClass === a

a.instance_of?(FalseClass) # credits to @Ilya

a.nil? ^ !a
</code>```

Body:
What is the Rubiest way check that a value is false and not nil (which is a falsy value)?

example using a fictional method false?:

a = false
a.false? # should return true
a = nil
a.false? # should return false

Body:
So far we have four different approaches:

a == false                 # credits to @Ilya

a.is_a?(FalseClass)
FalseClass === a

a.instance_of?(FalseClass) # credits to @Ilya

a.nil? ^ !a


问:
How to remove the 'unexpected Token export' error from serverless project?
I am creating a project using the serverless framework with es7 support. But i am getting an unexpected Token export error when i try to run my function locally using the following command

```<code>serverless invoke local --f hello
</code>```

I think i have included the required babel dependencies -

package.json

```<code>{
  "name": "olep-app-api",
  "version": "1.1.0",
  "description": "A starter project for the Serverless Framework with ES7 support",
  "main": "handler.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/AnomalyInnovations/serverless-es7.git"
  },
  "devDependencies": {
    "aws-sdk": "^2.94.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-3": "^6.24.1",
    "js-yaml": "^3.8.2",
    "serverless-webpack": "^2.0.0",
    "webpack": "^3.0.0",
    "webpack-node-externals": "^1.6.0"
  },
  "dependencies": {
    "babel-runtime": "^6.23.0",
    "source-map-support": "^0.4.14"
  }
}
</code>```

.babelrc

```<code>{
  "plugins": ["transform-runtime"],
  "presets": ["es2015", "stage-3"]
}
</code>```

serverless.yml

```<code>service: olep-17-api

plugins:
  - serverless-webpack

custom:
  webpackIncludeModules: true

provider:
  name: aws
  runtime: nodejs6.10
  stage: prod
  region: ap-south-1

  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:DescribeTable
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:ap-southeast-1:*:*"

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get
</code>```

webpack.config.js

```<code>var yaml = require('js-yaml');
var fs = require('fs');
var path = require('path');
var nodeExternals = require('webpack-node-externals');

var handlerRegex = /\.[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/;
var include = './_webpack/include.js';
var entries = {};

var doc = yaml.safeLoad(fs.readFileSync('serverless.yml', 'utf8'));

// Find all the handler files in serverless.yml
// and build the entry array with them
for (var key in doc.functions) {
  var handler = doc.functions[key].handler;
  var entryKey = handler.replace(handlerRegex, '');

  // Add error handling and source map support
  entries[entryKey] = [include, './' + entryKey + '.js'];
}

module.exports = {
  entry: entries,
  target: 'node',
  // Generate sourcemaps for proper error messages
  devtool: 'source-map',
  // Since 'aws-sdk' is not compatible with webpack,
  // we exclude all node dependencies
  externals: [nodeExternals()],
  // Run babel on all .js files and skip those in node_modules
  module: {
    rules: [{
      test: /\.js$/,
      loader: 'babel-loader',
      include: __dirname,
      exclude: /node_modules/,
    }]
  },
  output: {
    libraryTarget: 'commonjs',
    path: path.join(__dirname, '.webpack'),
    filename: '[name].js'
  }
};
</code>```

handler.js

```<code>export const hello = async (event, context, callback) => {
  const response = {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
      "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
    },
    body: JSON.stringify({
      message: `Go Serverless v1.0! ${(await message({ time: 1, copy: 'Your function executed successfully!'}))}`,
      input: event,
    }),
  };

  callback(null, response);
};

const message = ({ time, ...rest }) => new Promise((resolve, reject) =>
  setTimeout(() => {
    resolve(`${rest.copy} (with a delay)`);
  }, time * 1000)
);
</code>```

What can I do to get rid of this error?

答:
I have seen this error and it is non-descriptive.  I believe it means an exception is being thrown that is not being caught.  It also appears when there is a runtime syntax error, like using an undefined variable.  Here is my workflow which is different than yours but allows me to set a breakpoint and step through the code.  From this I can identify the bad line.

Install serverless-offline so you can run your project locally.  Install Visual Studio Code so you have an IDE to debug in.  I have posted my launch.json to Breakpoints not being hit when debugging Serverless in vscode  Set a breakpoint then hit your enpoing with a browser or curl.

Body:
I am creating a project using the serverless framework with es7 support. But i am getting an unexpected Token export error when i try to run my function locally using the following command

serverless invoke local --f hello

I think i have included the required babel dependencies -

package.json

{
  "name": "olep-app-api",
  "version": "1.1.0",
  "description": "A starter project for the Serverless Framework with ES7 support",
  "main": "handler.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/AnomalyInnovations/serverless-es7.git"
  },
  "devDependencies": {
    "aws-sdk": "^2.94.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-3": "^6.24.1",
    "js-yaml": "^3.8.2",
    "serverless-webpack": "^2.0.0",
    "webpack": "^3.0.0",
    "webpack-node-externals": "^1.6.0"
  },
  "dependencies": {
    "babel-runtime": "^6.23.0",
    "source-map-support": "^0.4.14"
  }
}

.babelrc

{
  "plugins": ["transform-runtime"],
  "presets": ["es2015", "stage-3"]
}

serverless.yml

service: olep-17-api

plugins:
  - serverless-webpack

custom:
  webpackIncludeModules: true

provider:
  name: aws
  runtime: nodejs6.10
  stage: prod
  region: ap-south-1

  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:DescribeTable
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:ap-southeast-1:*:*"

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get

webpack.config.js

var yaml = require('js-yaml');
var fs = require('fs');
var path = require('path');
var nodeExternals = require('webpack-node-externals');

var handlerRegex = /\.[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/;
var include = './_webpack/include.js';
var entries = {};

var doc = yaml.safeLoad(fs.readFileSync('serverless.yml', 'utf8'));

// Find all the handler files in serverless.yml
// and build the entry array with them
for (var key in doc.functions) {
  var handler = doc.functions[key].handler;
  var entryKey = handler.replace(handlerRegex, '');

  // Add error handling and source map support
  entries[entryKey] = [include, './' + entryKey + '.js'];
}

module.exports = {
  entry: entries,
  target: 'node',
  // Generate sourcemaps for proper error messages
  devtool: 'source-map',
  // Since 'aws-sdk' is not compatible with webpack,
  // we exclude all node dependencies
  externals: [nodeExternals()],
  // Run babel on all .js files and skip those in node_modules
  module: {
    rules: [{
      test: /\.js$/,
      loader: 'babel-loader',
      include: __dirname,
      exclude: /node_modules/,
    }]
  },
  output: {
    libraryTarget: 'commonjs',
    path: path.join(__dirname, '.webpack'),
    filename: '[name].js'
  }
};

handler.js

export const hello = async (event, context, callback) => {
  const response = {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
      "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
    },
    body: JSON.stringify({
      message: `Go Serverless v1.0! ${(await message({ time: 1, copy: 'Your function executed successfully!'}))}`,
      input: event,
    }),
  };

  callback(null, response);
};

const message = ({ time, ...rest }) => new Promise((resolve, reject) =>
  setTimeout(() => {
    resolve(`${rest.copy} (with a delay)`);
  }, time * 1000)
);

What can I do to get rid of this error?


问:
IEnumerable serialize as [JsonObject] in Json.NET, without using the attribute
I want to serialize an IEnumerable as a JsonObject, like the way it gets serialized by applying the [JsonObject] attribute, but I cannot change the DTO classes by introducing this attribute.

Is there a way to tell the (de)serializer to force JsonObject (de)serialization?

答:
Yes, you can use a custom IContractResolver to do this.  All you need to do is create a resolver class deriving from Json.Net's DefaultContractResolver and override the CreateContract(Type) method as shown below, where FooList is replaced with the type of your enumerable.

```<code>class CustomResolver : DefaultContractResolver
{
    protected override JsonContract CreateContract(Type type)
    {
        if (type == typeof(FooList))
            return CreateObjectContract(typeof(FooList));

        return base.CreateContract(type);
    }
}
</code>```

Add the resolver to the serializer settings and use those settings when you serialize:

```<code>var settings = new JsonSerializerSettings
{
    ContractResolver = new CustomResolver(),
    Formatting = Formatting.Indented
};

string json = JsonConvert.SerializeObject(yourObject, settings);
</code>```

Here is a demo: https://dotnetfiddle.net/ocyjU4

Body:
Yes, you can use a custom IContractResolver to do this.  All you need to do is create a resolver class deriving from Json.Net's DefaultContractResolver and override the CreateContract(Type) method as shown below, where FooList is replaced with the type of your enumerable.

class CustomResolver : DefaultContractResolver
{
    protected override JsonContract CreateContract(Type type)
    {
        if (type == typeof(FooList))
            return CreateObjectContract(typeof(FooList));

        return base.CreateContract(type);
    }
}

Add the resolver to the serializer settings and use those settings when you serialize:

var settings = new JsonSerializerSettings
{
    ContractResolver = new CustomResolver(),
    Formatting = Formatting.Indented
};

string json = JsonConvert.SerializeObject(yourObject, settings);

Here is a demo: https://dotnetfiddle.net/ocyjU4


问:
How do I generate a Poisson Process?

Original Question:

I want to generate a Poisson process. If the number of arrivals by time t is N(t) and I have a Poisson distribution with parameter λ how do I generate N(t)? How would I do this in C++?

Clarification:

I originally wanted to generate the process using a Poisson distribution. But, I was confused about what parameter from the process I needed; I thought I could use N(t) but that tells me how many arrivals have occurred on the interval (0,t] which wasn't what I wanted. So, then I thought I could use N(t2)-N(t1) to get the number of arrivals on the interval [t1,t2]. Since N(t)~Poisson(t x λ) I could use Poisson(t2 x λ)-Poisson(t1 x λ) but I don't want the number of arrivals in an interval.

Rather, I want to generate the explicit times that arrivals occur at.

I could do this by making the interval [t2,t1] sufficiently small so that each interval has only one arrival (which occurs as |t2-t1| -> 0).

答:
Generating arrival times via Poisson Process does not mean using a Poisson distribution. It is done by creating an exponential distribution based on the Poisson arrival rate lamda.

In short, you need to generate an exponential distribution with an average = 1/lamda,  see the following example:

```<code>#include <iostream>
#include <iterator>
#include <random>

int
main ()
{
 // seed the RNG
 std::random_device rd; // uniformly-distributed integer random number generator
 std::mt19937 rng (rd ()); // mt19937: Pseudo-random number generation

 double averageArrival = 15;
 double lamda = 1 / averageArrival;
 std::exponential_distribution<double> exp (lamda);

double sumArrivalTimes=0;
double newArrivalTime;

 for (int i = 0; i < 10; ++i)
  {
   newArrivalTime=  exp.operator() (rng); // generates the next random number in the distribution
   sumArrivalTimes  = sumArrivalTimes + newArrivalTime;
   std::cout << "newArrivalTime:  " << newArrivalTime  << "    ,sumArrivalTimes:  " << sumArrivalTimes << std::endl;
  }

}
</code>```

The result of running this code:

```<code>newArrivalTime:  21.6419    ,sumArrivalTimes:  21.6419
newArrivalTime:  1.64205    ,sumArrivalTimes:  23.2839
newArrivalTime:  8.35292    ,sumArrivalTimes:  31.6368
newArrivalTime:  1.82962    ,sumArrivalTimes:  33.4665
newArrivalTime:  34.7628    ,sumArrivalTimes:  68.2292
newArrivalTime:  26.0752    ,sumArrivalTimes:  94.3045
newArrivalTime:  63.4728    ,sumArrivalTimes:  157.777
newArrivalTime:  3.22149    ,sumArrivalTimes:  160.999
newArrivalTime:  1.64637    ,sumArrivalTimes:  162.645
newArrivalTime:  13.8235    ,sumArrivalTimes:  176.469
</code>```

so, based on your experiment you can either use: newArrivalTime or  sumArrivalTimes.

ref:  http://www.math.wsu.edu/faculty/genz/416/lect/l05-45.pdf

Title: How do I generate a Poisson Process?

Body:
Generating arrival times via Poisson Process does not mean using a Poisson distribution. It is done by creating an exponential distribution based on the Poisson arrival rate lamda.

In short, you need to generate an exponential distribution with an average = 1/lamda,  see the following example:

#include <iostream>
#include <iterator>
#include <random>

int
main ()
{
 // seed the RNG
 std::random_device rd; // uniformly-distributed integer random number generator
 std::mt19937 rng (rd ()); // mt19937: Pseudo-random number generation

 double averageArrival = 15;
 double lamda = 1 / averageArrival;
 std::exponential_distribution<double> exp (lamda);

double sumArrivalTimes=0;
double newArrivalTime;

 for (int i = 0; i < 10; ++i)
  {
   newArrivalTime=  exp.operator() (rng); // generates the next random number in the distribution
   sumArrivalTimes  = sumArrivalTimes + newArrivalTime;
   std::cout << "newArrivalTime:  " << newArrivalTime  << "    ,sumArrivalTimes:  " << sumArrivalTimes << std::endl;
  }

}

The result of running this code:

newArrivalTime:  21.6419    ,sumArrivalTimes:  21.6419
newArrivalTime:  1.64205    ,sumArrivalTimes:  23.2839
newArrivalTime:  8.35292    ,sumArrivalTimes:  31.6368
newArrivalTime:  1.82962    ,sumArrivalTimes:  33.4665
newArrivalTime:  34.7628    ,sumArrivalTimes:  68.2292
newArrivalTime:  26.0752    ,sumArrivalTimes:  94.3045
newArrivalTime:  63.4728    ,sumArrivalTimes:  157.777
newArrivalTime:  3.22149    ,sumArrivalTimes:  160.999
newArrivalTime:  1.64637    ,sumArrivalTimes:  162.645
newArrivalTime:  13.8235    ,sumArrivalTimes:  176.469

so, based on your experiment you can either use: newArrivalTime or  sumArrivalTimes.

ref:  http://www.math.wsu.edu/faculty/genz/416/lect/l05-45.pdf


问:
Apply a list of n functions to each row of a dataframe?
I have a list of functions

```<code>funs <- list(fn1 = function(x) x^2,
             fn2 = function(x) x^3,
             fn3 = function(x) sin(x),
             fn4 = function(x) x+1)
#in reality these are all f = splinefun()
</code>```

And I have a dataframe:

```<code>mydata <- data.frame(x1 = c(1, 2, 3, 2),
                     x2 = c(3, 2, 1, 0),
                     x3 = c(1, 2, 2, 3),
                     x4 = c(1, 2, 1, 2))
#actually a 500x15 dataframe of 500 samples from 15 parameters
</code>```

For each of i rows, I would like to evaluate function j on each of the j columns and sum the results:

```<code>unlist(funs)
attach(mydata)
a <- rep(NA,4)
for (i in 1:4) {
     a[i] <- sum(fn1(x1[i]), fn2(x2[i]), fn3(x3[i]), fn4(x4[i]))
}
</code>```

How can I do this efficiently? Is this an appropriate occasion to implement plyr functions? If so, how?

bonus question: why is a[4] NA?

Is this an appropriate time to use functions from plyr, if so, how can I do so?

答:
I tried using plyr::each:

```<code>library(plyr)
sapply(mydata, each(min, max))
    x1 x2 x3 x4
min  1  0  1  1
max  3  3  3  2
</code>```

and it works fine, but when I pass custom functions I get:

```<code>sapply(mydata, each(fn1, fn2))
Error in proto[[i]] <- fs[[i]](x, ...) :
  more elements supplied than there are to replace
</code>```

each has very brief documentation, I don't quite get what's the problem.

ContentLicense: CC BY-SA 2.5

Body:
I have a list of functions

funs <- list(fn1 = function(x) x^2,
             fn2 = function(x) x^3,
             fn3 = function(x) sin(x),
             fn4 = function(x) x+1)
#in reality these are all f = splinefun()

And I have a dataframe:

mydata <- data.frame(x1 = c(1, 2, 3, 2),
                     x2 = c(3, 2, 1, 0),
                     x3 = c(1, 2, 2, 3),
                     x4 = c(1, 2, 1, 2))
#actually a 500x15 dataframe of 500 samples from 15 parameters

For each of i rows, I would like to evaluate function j on each of the j columns and sum the results:

unlist(funs)
attach(mydata)
a <- rep(NA,4)
for (i in 1:4) {
     a[i] <- sum(fn1(x1[i]), fn2(x2[i]), fn3(x3[i]), fn4(x4[i]))
}

How can I do this efficiently? Is this an appropriate occasion to implement plyr functions? If so, how?

bonus question: why is a[4] NA?

Is this an appropriate time to use functions from plyr, if so, how can I do so?

Body:
I tried using plyr::each:

library(plyr)
sapply(mydata, each(min, max))
    x1 x2 x3 x4
min  1  0  1  1
max  3  3  3  2

and it works fine, but when I pass custom functions I get:

sapply(mydata, each(fn1, fn2))
Error in proto[[i]] <- fs[[i]](x, ...) :
  more elements supplied than there are to replace

each has very brief documentation, I don't quite get what's the problem.


问:
Match multiple characters one or more times
Consider the following problem:
We have a string of random chars flowing from /dev/urandom and we want to process it in such way that we will get strings of a constant length which meet certain conditions .
For example if we run the following command 5 times we get :

```<code>cat /dev/urandom |tr -dc A-Z5|head -c${1:-30}
DLZEZDATSTDN55BNVDSNRFSLRKHDGR
AVCRIE5OAFBUWZZYQYQWCTAZSNMQAA
HSTFN5AQNWILXMSZCBIGREPNCFGPDM
AZJNEUQRCDYSKXMQDUHVTOFEOAYPHF
ANFDWHHZHLAGXCPKWLQESSZLEZYNDC
</code>```

Now, these strings meet the conditions I need but only partially.
For ex. I need that the digit 5 to appear at least 2 times but no more than 7 times in a string and any of the letters should not appear more than 10 times.
How should I customize the command above to get this result ?

答:
With GNU awk processing:

```<code>awk -v FS="" '{
                  err=0;
                  for(i=1; i<=NF; i++) {
                      a[$i]++;
                      if ($i~/[A-Z]/ && a[$i]>10) { err=1; break }
                  }
                  if (!err && (2>a[5] || a[5]>7)) err=1
              }
              END{ if (!err) print }' <(cat /dev/urandom | tr -dc A-Z5 | head -c30)
</code>```

FS="" - in this case, each individual character in the record becomes a separate field

The above will make a random string to be printed only if all conditions are satisfied.

Body:
Consider the following problem:
We have a string of random chars flowing from /dev/urandom and we want to process it in such way that we will get strings of a constant length which meet certain conditions .
For example if we run the following command 5 times we get :

cat /dev/urandom |tr -dc A-Z5|head -c${1:-30}
DLZEZDATSTDN55BNVDSNRFSLRKHDGR
AVCRIE5OAFBUWZZYQYQWCTAZSNMQAA
HSTFN5AQNWILXMSZCBIGREPNCFGPDM
AZJNEUQRCDYSKXMQDUHVTOFEOAYPHF
ANFDWHHZHLAGXCPKWLQESSZLEZYNDC

Now, these strings meet the conditions I need but only partially.
For ex. I need that the digit 5 to appear at least 2 times but no more than 7 times in a string and any of the letters should not appear more than 10 times.
How should I customize the command above to get this result ?

Body:
With GNU awk processing:

awk -v FS="" '{
                  err=0;
                  for(i=1; i<=NF; i++) {
                      a[$i]++;
                      if ($i~/[A-Z]/ && a[$i]>10) { err=1; break }
                  }
                  if (!err && (2>a[5] || a[5]>7)) err=1
              }
              END{ if (!err) print }' <(cat /dev/urandom | tr -dc A-Z5 | head -c30)

FS="" - in this case, each individual character in the record becomes a separate field

The above will make a random string to be printed only if all conditions are satisfied.


问:
Checkmarx Integration in Gitlab Continuous Integration
Is it possible to integrate Checkmarx Static Application Security Testing (SAST) tool into Gitlab Continuous Integration (CI) Pipeline for static security scanning?</p>

答:
I have been using Checkmarx with TeamCity and Jenkins pipeline with their Plugin. However, for GitLab pipeline, we need to use REST APIs/ CLI. I would prefer using CLI over REST APIs as CLI provides more functionality that can be used for pipeline decisions.

You can check their Wiki-
https://checkmarx.atlassian.net/wiki/spaces/KC/pages/5767170/CxSAST+API+Guide
https://checkmarx.atlassian.net/wiki/spaces/KC/pages/52560015/CxConsole+CxSAST+CLI

You can always raise a support ticket for getting the recommended approach by Checkmarx.


问:
How can I compare object properties, but not the values, in karma/jasmine?

I'm new to Unit Testing with karma/jasmine, and I am trying to test two objects of the same type, but with different values. Which means, same properties but with different values on each object, like this:

```<code>let myFirstObject: myType = {
    id: 1,
    name: "name1",
    //... some other properties,
}

let mySecondObject: myType = {
    id: 2,
    name: "name2",
    //... some other properties,
}

it('should be a true comparison', () => {
    expect(myFirstObject).toEqual(mySecondObject);
});
</code>```

    I want it to be true, because the type and the properties are equal (the structure is the same), although the values stored are different. But using jasmine .toEqual() only passes when both items are entirely equal (properties and values).

How can I do this comparison of structure/type but not considering the values, in karma/jasmine?

(note: my project is in ionic/angularIO, if that matters)

Any ideas?

答:
Object.Keys(myFirstObject) will return an array of the keys as strings. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Why not just loop the array and check that the mySecondObject.hasOwnProperty(key)?

```<code>Object.keys(myFirstObject).map(key => {
   expect(mySecondObject.hasOwnProperty(key)).toBe(true)
})
</code>```

EDIT: If you are using typescript, you could use an interface to check the objects against. Interface type check with Typescript

Body:
I'm new to Unit Testing with karma/jasmine, and I am trying to test two objects of the same type, but with different values. Which means, same properties but with different values on each object, like this:

let myFirstObject: myType = {
    id: 1,
    name: "name1",
    //... some other properties,
}

let mySecondObject: myType = {
    id: 2,
    name: "name2",
    //... some other properties,
}

it('should be a true comparison', () => {
    expect(myFirstObject).toEqual(mySecondObject);
});

    I want it to be true, because the type and the properties are equal (the structure is the same), although the values stored are different. But using jasmine .toEqual() only passes when both items are entirely equal (properties and values).

How can I do this comparison of structure/type but not considering the values, in karma/jasmine?

(note: my project is in ionic/angularIO, if that matters)

Any ideas?

Body:
Object.Keys(myFirstObject) will return an array of the keys as strings. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Why not just loop the array and check that the mySecondObject.hasOwnProperty(key)?

Object.keys(myFirstObject).map(key => {
   expect(mySecondObject.hasOwnProperty(key)).toBe(true)
})

EDIT: If you are using typescript, you could use an interface to check the objects against. Interface type check with Typescript


问:
Google Distance Matrix Api React Js Cant Set Distance To The State
I have it working it will log the response to the console but then I can't set the distance to the state I will put all the code below.

```<code>getDist(dest){
var self = this;
var origin = this.state.location,
    destination = this.state.dest,
    service = new window.google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: window.google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false,
        unitSystem: window.google.maps.UnitSystem.IMPERIAL
      },
      this.callback
    );
}

callback(response, status) {
    const self = this;
    if(status === "OK") {
        console.log(response);
        var dest = response.destinationAddresses[0];
        var dist = response.rows[0].elements[0].distance.text;
        return response;
    } else {
        alert("Error: " + status);
    }
  }
</code>```

ive tried to set the state in the callback function and it says that setState({}) is not a function. ive tried to set the state by doing this this.setState({ distFromLoc: self.callback }) but that just sets the call back function code to the state which is not what I want I have reached the end of my knowledge and the other web developer I work with makes no sense with our logic.

I just need to be able to set state for 2 seconds as im looping through a list of about 36 jobs and after every search it is going to check whether that job is close enough to the person searching or not.

Thanks in advance -Andy

Edit 1: I have edited my code it doesnt error any more but it still wont let me return the data would you be able to maybe show me what im doing wrong?

going to add the class that calls it, because it is saying that i cant use .then on a function to turn the function into a promise function.

```<code>updateSearchResults(data) {
this.setState({
  searching: true,
});
var self = this;
var output = [];
console.log('Here we will search the db using user data for suitable jobs');
console.log('do some math to work out how many pagination we need for the amount of returned jobs and update the state accordingly');
data.forEach(item => {
  console.log('before');
  this.getDist(item.postcode).then(function (res){
    console.log('after');
    console.log(this.state.distFromLoc);
    if (this.state.location === '') {
      if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('1');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('2');
          output.push(item);
        }
      } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('3');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('4');
          output.push(item);
        }
      } else if (item.option === 'both' && this.state.weekend && this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('5');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('6');
          output.push(item);
        }
      } else if (!this.state.weekend && !this.state.partTime) {
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('7');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('8');
          output.push(item);
        }
      }
    } else if (this.state.distFromLoc <= this.state.distance) {
      console.log(this.state.distFromLoc);
      console.log(this.state.distance);
      if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('9');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('10');
          output.push(item);
        }
      } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('11');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('12');
          output.push(item);
        }
      } else if (item.option === 'both' && this.state.weekend && this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('13');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('14');
          output.push(item);
        }
      } else if (!this.state.weekend && !this.state.partTime) {
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('15');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('16');
          output.push(item);
        }
      }
    }
  })
  .catch(function (err){
    console.log(err);
  });
});
window.setTimeout(function() {
self.setState({
  dataToShow: output,
  searching: false,
  current: 1,
});
const dataLength = self.state.dataToShow.length
self.setState({
  amountOfJobs: dataLength
})}, 10000)
}

getDist(dest){
var self = this;
const wrappedCallback = (...args) => this.callback(...args);
var origin = this.state.location,
    destination = dest,
    service = new window.google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: window.google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false,
        unitSystem: window.google.maps.UnitSystem.IMPERIAL
      }, wrappedCallback
    );
}

callback(response, status) {
    const self = this;
    if(status === "OK") {
        console.log(response);
        var dest = response.destinationAddresses[0];
        if (response.rows[0].elements[0].status === "ZERO_RESULTS"){

        } else if (response.rows[0].elements[0].status === "OK"){
          var dist = response.rows[0].elements[0].distance.text;
          this.setState({
            distFromLoc: dist
          })
        }
    } else {
        alert("Error: " + status);
    }
  }
</code>```

i know im doing something wrong i just cant work out what it is exactly.

current error im getting is this TypeError: Cannot read property 'then' of undefined why cant i put a promise on the function.

答:
There might be an alternative solution, but it uses a global variable:  </p>

```<code>window.callback = function( ) {};

window.callback = (code, name) => {
    me.setState({stateVariable: code});
};
</code>```

<p>You might change this code accordingly and use the callback in any place of your code (because it was declared globally with an arrow function that preserves context, it is a closure)  </p>

Body:
I have it working it will log the response to the console but then I can't set the distance to the state I will put all the code below.

getDist(dest){
var self = this;
var origin = this.state.location,
    destination = this.state.dest,
    service = new window.google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: window.google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false,
        unitSystem: window.google.maps.UnitSystem.IMPERIAL
      },
      this.callback
    );
}

callback(response, status) {
    const self = this;
    if(status === "OK") {
        console.log(response);
        var dest = response.destinationAddresses[0];
        var dist = response.rows[0].elements[0].distance.text;
        return response;
    } else {
        alert("Error: " + status);
    }
  }

ive tried to set the state in the callback function and it says that setState({}) is not a function. ive tried to set the state by doing this this.setState({ distFromLoc: self.callback }) but that just sets the call back function code to the state which is not what I want I have reached the end of my knowledge and the other web developer I work with makes no sense with our logic.

I just need to be able to set state for 2 seconds as im looping through a list of about 36 jobs and after every search it is going to check whether that job is close enough to the person searching or not.

Thanks in advance -Andy

Edit 1: I have edited my code it doesnt error any more but it still wont let me return the data would you be able to maybe show me what im doing wrong?

going to add the class that calls it, because it is saying that i cant use .then on a function to turn the function into a promise function.

updateSearchResults(data) {
this.setState({
  searching: true,
});
var self = this;
var output = [];
console.log('Here we will search the db using user data for suitable jobs');
console.log('do some math to work out how many pagination we need for the amount of returned jobs and update the state accordingly');
data.forEach(item => {
  console.log('before');
  this.getDist(item.postcode).then(function (res){
    console.log('after');
    console.log(this.state.distFromLoc);
    if (this.state.location === '') {
      if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('1');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('2');
          output.push(item);
        }
      } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('3');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('4');
          output.push(item);
        }
      } else if (item.option === 'both' && this.state.weekend && this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('5');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('6');
          output.push(item);
        }
      } else if (!this.state.weekend && !this.state.partTime) {
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('7');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('8');
          output.push(item);
        }
      }
    } else if (this.state.distFromLoc <= this.state.distance) {
      console.log(this.state.distFromLoc);
      console.log(this.state.distance);
      if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('9');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('10');
          output.push(item);
        }
      } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('11');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('12');
          output.push(item);
        }
      } else if (item.option === 'both' && this.state.weekend && this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('13');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('14');
          output.push(item);
        }
      } else if (!this.state.weekend && !this.state.partTime) {
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('15');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('16');
          output.push(item);
        }
      }
    }
  })
  .catch(function (err){
    console.log(err);
  });
});
window.setTimeout(function() {
self.setState({
  dataToShow: output,
  searching: false,
  current: 1,
});
const dataLength = self.state.dataToShow.length
self.setState({
  amountOfJobs: dataLength
})}, 10000)
}

getDist(dest){
var self = this;
const wrappedCallback = (...args) => this.callback(...args);
var origin = this.state.location,
    destination = dest,
    service = new window.google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: window.google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false,
        unitSystem: window.google.maps.UnitSystem.IMPERIAL
      }, wrappedCallback
    );
}

callback(response, status) {
    const self = this;
    if(status === "OK") {
        console.log(response);
        var dest = response.destinationAddresses[0];
        if (response.rows[0].elements[0].status === "ZERO_RESULTS"){

        } else if (response.rows[0].elements[0].status === "OK"){
          var dist = response.rows[0].elements[0].distance.text;
          this.setState({
            distFromLoc: dist
          })
        }
    } else {
        alert("Error: " + status);
    }
  }

i know im doing something wrong i just cant work out what it is exactly.

current error im getting is this TypeError: Cannot read property 'then' of undefined why cant i put a promise on the function.

Body:
There might be an alternative solution, but it uses a global variable:

window.callback = function( ) {};

window.callback = (code, name) => {
    me.setState({stateVariable: code});
};

You might change this code accordingly and use the callback in any place of your code (because it was declared globally with an arrow function that preserves context, it is a closure)