问:
Renderscript broken with AndroidX?
Since I've migrated to androidx I can't make Renderscript run. I'm getting following exception:

2018-10-12 16:27:58.328 27195-27195/pl.qus.xenoamp2 A/zygote64:
  java_vm_ext.cc:504] JNI DETECTED ERROR IN APPLICATION: JNI
  NewGlobalRef called with pending exception
  java.lang.ClassNotFoundException: Didn't find class
  "android.support.v8.renderscript.RenderScript" on path:
  DexPathList[[zip file
  "/data/app/pl.qus.xenoamp2-xHJAddeg9oM-uGSxlvMp7A==/base.apk"],nativeLibraryDirectories=[/data/app/pl.qus.xenoamp2-xHJAddeg9oM-uGSxlvMp7A==/lib/arm64,
  /data/app/pl.qus.xenoamp2-xHJAddeg9oM-uGSxlvMp7A==/base.apk!/lib/arm64-v8a,
  /system/lib64, /system/vendor/lib64]] 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  java.lang.Class
  dalvik.system.BaseDexClassLoader.findClass(java.lang.String)
  (BaseDexClassLoader.java:93) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String,
  boolean) (ClassLoader.java:379) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String)
  (ClassLoader.java:312) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  java.lang.String java.lang.Runtime.nativeLoad(java.lang.String,
  java.lang.ClassLoader, java.lang.String) (Runtime.java:-2) 2018-10-12
  16:27:58.328 27195-27195/pl.qus.xenoamp2 A/zygote64:
  java_vm_ext.cc:504]   at java.lang.String
  java.lang.Runtime.doLoad(java.lang.String, java.lang.ClassLoader)
  (Runtime.java:1099) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at void
  java.lang.Runtime.loadLibrary0(java.lang.ClassLoader,
  java.lang.String) (Runtime.java:1014) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at void
  java.lang.System.loadLibrary(java.lang.String) (System.java:1657)
  2018-10-12 16:27:58.328 27195-27195/pl.qus.xenoamp2 A/zygote64:
  java_vm_ext.cc:504]   at androidx.renderscript.RenderScript
  androidx.renderscript.RenderScript.internalCreate(android.content.Context,
  int, androidx.renderscript.RenderScript$ContextType, int)
  (RenderScript.java:1408) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  androidx.renderscript.RenderScript
  androidx.renderscript.RenderScript.create(android.content.Context,
  int, androidx.renderscript.RenderScript$ContextType, int)
  (RenderScript.java:1599) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  androidx.renderscript.RenderScript
  androidx.renderscript.RenderScript.create(android.content.Context,
  androidx.renderscript.RenderScript$ContextType, int)
  (RenderScript.java:1549) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  androidx.renderscript.RenderScript
  androidx.renderscript.RenderScript.create(android.content.Context,
  androidx.renderscript.RenderScript$ContextType)
  (RenderScript.java:1525) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  androidx.renderscript.RenderScript
  androidx.renderscript.RenderScript.create(android.content.Context)
  (RenderScript.java:1512)

I have usual entries in gradle:

```<code>    renderscriptTargetApi 18
    renderscriptSupportModeEnabled true
</code>```

Anything else I have to change?

答:
in my gradle module file I had:

```<code>renderscriptTargetApi 19
renderscriptSupportModeEnabled true
</code>```

And, I had the following imports before migrating to AndroidX:

```<code>import android.support.v8.renderscript.Allocation;
import android.support.v8.renderscript.Element;
import android.support.v8.renderscript.Matrix4f;
import android.support.v8.renderscript.RenderScript;
import android.support.v8.renderscript.ScriptIntrinsicBlur;
import android.support.v8.renderscript.ScriptIntrinsicColorMatrix;
import android.support.v8.renderscript.ScriptIntrinsicConvolve3x3;
</code>```

After migrating to AndroidX, just like the documentation says:

I kept the same statements on my gradle module file, but I upgraded to buildToolsVersion 29.0.2 and my compileSdkVersion to 28

I changed the previous imports to the following, and it all works.

```<code>import androidx.renderscript.Matrix4f;
import androidx.renderscript.RenderScript;
import androidx.renderscript.Allocation;
import androidx.renderscript.Element;
import androidx.renderscript.ScriptIntrinsicBlur;
import androidx.renderscript.ScriptIntrinsicColorMatrix;
import androidx.renderscript.ScriptIntrinsicConvolve3x3;
</code>```

Title: Renderscript broken with AndroidX?

Body:
Since I've migrated to androidx I can't make Renderscript run. I'm getting following exception:

2018-10-12 16:27:58.328 27195-27195/pl.qus.xenoamp2 A/zygote64:
  java_vm_ext.cc:504] JNI DETECTED ERROR IN APPLICATION: JNI
  NewGlobalRef called with pending exception
  java.lang.ClassNotFoundException: Didn't find class
  "android.support.v8.renderscript.RenderScript" on path:
  DexPathList[[zip file
  "/data/app/pl.qus.xenoamp2-xHJAddeg9oM-uGSxlvMp7A==/base.apk"],nativeLibraryDirectories=[/data/app/pl.qus.xenoamp2-xHJAddeg9oM-uGSxlvMp7A==/lib/arm64,
  /data/app/pl.qus.xenoamp2-xHJAddeg9oM-uGSxlvMp7A==/base.apk!/lib/arm64-v8a,
  /system/lib64, /system/vendor/lib64]] 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  java.lang.Class
  dalvik.system.BaseDexClassLoader.findClass(java.lang.String)
  (BaseDexClassLoader.java:93) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String,
  boolean) (ClassLoader.java:379) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String)
  (ClassLoader.java:312) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  java.lang.String java.lang.Runtime.nativeLoad(java.lang.String,
  java.lang.ClassLoader, java.lang.String) (Runtime.java:-2) 2018-10-12
  16:27:58.328 27195-27195/pl.qus.xenoamp2 A/zygote64:
  java_vm_ext.cc:504]   at java.lang.String
  java.lang.Runtime.doLoad(java.lang.String, java.lang.ClassLoader)
  (Runtime.java:1099) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at void
  java.lang.Runtime.loadLibrary0(java.lang.ClassLoader,
  java.lang.String) (Runtime.java:1014) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at void
  java.lang.System.loadLibrary(java.lang.String) (System.java:1657)
  2018-10-12 16:27:58.328 27195-27195/pl.qus.xenoamp2 A/zygote64:
  java_vm_ext.cc:504]   at androidx.renderscript.RenderScript
  androidx.renderscript.RenderScript.internalCreate(android.content.Context,
  int, androidx.renderscript.RenderScript$ContextType, int)
  (RenderScript.java:1408) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  androidx.renderscript.RenderScript
  androidx.renderscript.RenderScript.create(android.content.Context,
  int, androidx.renderscript.RenderScript$ContextType, int)
  (RenderScript.java:1599) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  androidx.renderscript.RenderScript
  androidx.renderscript.RenderScript.create(android.content.Context,
  androidx.renderscript.RenderScript$ContextType, int)
  (RenderScript.java:1549) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  androidx.renderscript.RenderScript
  androidx.renderscript.RenderScript.create(android.content.Context,
  androidx.renderscript.RenderScript$ContextType)
  (RenderScript.java:1525) 2018-10-12 16:27:58.328
  27195-27195/pl.qus.xenoamp2 A/zygote64: java_vm_ext.cc:504]   at
  androidx.renderscript.RenderScript
  androidx.renderscript.RenderScript.create(android.content.Context)
  (RenderScript.java:1512)

I have usual entries in gradle:

    renderscriptTargetApi 18
    renderscriptSupportModeEnabled true

Anything else I have to change?

Body:
in my gradle module file I had:

renderscriptTargetApi 19
renderscriptSupportModeEnabled true

And, I had the following imports before migrating to AndroidX:

import android.support.v8.renderscript.Allocation;
import android.support.v8.renderscript.Element;
import android.support.v8.renderscript.Matrix4f;
import android.support.v8.renderscript.RenderScript;
import android.support.v8.renderscript.ScriptIntrinsicBlur;
import android.support.v8.renderscript.ScriptIntrinsicColorMatrix;
import android.support.v8.renderscript.ScriptIntrinsicConvolve3x3;

After migrating to AndroidX, just like the documentation says:

I kept the same statements on my gradle module file, but I upgraded to buildToolsVersion 29.0.2 and my compileSdkVersion to 28

I changed the previous imports to the following, and it all works.

import androidx.renderscript.Matrix4f;
import androidx.renderscript.RenderScript;
import androidx.renderscript.Allocation;
import androidx.renderscript.Element;
import androidx.renderscript.ScriptIntrinsicBlur;
import androidx.renderscript.ScriptIntrinsicColorMatrix;
import androidx.renderscript.ScriptIntrinsicConvolve3x3;


来源: stackexchange

问:
kafka producer - how to know which key will go to what partition?
I am aware of kafka console producer command and it is quite handy. I want to know is there a way to know for sure which key will go to which partition when we have key as well? Assuming we have 10 partitions in kafka topic, how will producer decide to which partition the key will go?

I thought it might use key.toString.hashCode() % (num_of_partitons), but i don't think this is the way kafka console producer employs.

Can we check to which partition producer will send data to?

答:
If the default partioner is used it will not hashcode the keys string value, instead it uses a Murmur2 hashing algorithm as seen in the org.apache.kafka.clients.producer.internals.DefaultPartitioner code:

```<code>Utils.toPositive(Utils.murmur2(keyBytes)) % numPartitions;
</code>```

The implementation of the algorithm can be found here.

ContentLicense: CC BY-SA 4.0

Body:
If the default partioner is used it will not hashcode the keys string value, instead it uses a Murmur2 hashing algorithm as seen in the org.apache.kafka.clients.producer.internals.DefaultPartitioner code:

Utils.toPositive(Utils.murmur2(keyBytes)) % numPartitions;

The implementation of the algorithm can be found here.


问:
Generate a random list of custom data type, where values provided to data constructor are somehow bounded within a range
I have defined a Point data type, with a single value constructor like so:

```<code>data Point = Point {
  x :: Int,
  y :: Int,
  color :: Color
} deriving (Show, Eq)

data Color = None
  | Black
  | Red
  | Green
  | Blue
  deriving (Show, Eq, Enum, Bounded)
</code>```

I have found an example of making a Bounded Enum an instance of the Random class and have made Color an instance of it like so:

```<code>instance Random Color where
  random g = case randomR (1, 4) g of
    (r, g') -> (toEnum r, g')
  randomR (a, b) g = case randomR (fromEnum a, fromEnum b) g of
    (r, g') -> (toEnum r, g')
</code>```

I was then able to find out how to make Point an instance of the Random class also:

```<code>instance Random Point where
  randomR (Point xl yl cl, Point xr yr cr) g =
    let (x, g1) = randomR (xl, xr) g
        (y, g2) = randomR (yl, yr) g1
        (c, g3) = randomR (cl, cr) g2
    in (Point x y c, g3)
  random g =
    let (x, g1) = random g
        (y, g2) = random g1
        (c, g3) = random g2
    in (Point x y c, g3)
</code>```

So, this let's me make random point values. But, what I'd like to do is be able to create a list of random Point values, where the x and the y properties are bounded within some range whilst leaving the color property to be an unbounded random value. Is this possible with the way I am currently modelling the code, or do I need to rethink how I construct Point values? For instance, instead of making Point an instance of the Random class, should I just create a random list of Int in the IO monad and then have a pure function that creates n Points, using values from the random list to construct each Point value?

Edit, I think I have found out how to do it:

Without changing the above code, in the IO monad I can do the following:

```<code>solved :: IO ()
solved = do
  randGen <- getStdGen

  let x = 2
  let randomPoints = take x $ randomRs (Point 0 0 None, Point 200 200 Blue) randGen

  putStrLn $ "Random points: " ++ show randomPoints
</code>```

This seems to work, randomRs appears to let me specify a range...

Presumably because my Point data type derives Eq?

Or

Is it because my x and y properties are Int (guessing here, but may be "bounded" by default) and I have Color derive bounded?

答:
It works because of the properties of the Int and Color types, not because of the properties of Point. If one suppresses the Eq clause of Point, it still works.

Your code is overall quite good, however I would mention a few minor caveats.

In the Random instance for Point, you are chaining the generator states manually; this is a bit error prone, and monadic do notation is supposed to make it unnecessary. The Color instance could be simplified.

You are using IO where it is not really required. IO is just one instance of the MonadRandom class. If g is an instance of RandomGen, any Rand g is an instance of MonadRandom.

The random values you're getting are not reproducible from a program execution to the next one; this is because getStdGen implicitly uses the launch time as a random number generation seed. It may do that because it is IO-hosted. In many situations, this is a problem, as one might want to vary the choice of random sequence and the system parameters independently of each other.

Using monadic style, the basics of your code could be rewritten for example like this:

```<code>import  System.Random
import  System.Random.TF -- Threefish random number generator
import  Control.Monad.Random

data Point = Point {
  x :: Int,
  y :: Int,
  color :: Color
} deriving (Show, Eq)

data Color = None
  | Black
  | Red
  | Green
  | Blue
  deriving (Show, Eq, Enum, Bounded)

instance Random Color where
  randomR (a, b) g = let (r,g') = randomR (fromEnum a, fromEnum b) g
                     in  (toEnum r, g')
  random g = randomR (minBound::Color, maxBound::Color) g

singleRandomPoint ::  -- monadic action for just one random point
  MonadRandom mr => Int -> Int -> Color -> Int -> Int -> Color -> mr Point
singleRandomPoint xmin ymin cmin xmax ymax cmax =
  do
    -- avoid manual chaining of generator states:
    x <- getRandomR (xmin, xmax)
    y <- getRandomR (ymin, ymax)
    c <- getRandomR (cmin, cmax)
    return (Point x y c)

</code>```

And then we can derive an expression returning an unlimited list of random points:

```<code>-- monadic action for an unlimited list of random points:
seqRandomPoints :: MonadRandom mr =>
  Int -> Int -> Color -> Int -> Int -> Color -> mr [Point]
seqRandomPoints xmin ymin cmin xmax ymax cmax =
    sequence (repeat (singleRandomPoint xmin ymin cmin xmax ymax cmax))

-- returns an unlimited list of random points:
randomPoints ::  Int  -> Int -> Int -> Color -> Int -> Int -> Color -> [Point]
randomPoints  seed  xmin ymin cmin xmax ymax cmax =
    let
        -- get random number generator:
        -- using Threefish algorithm (TF) for better statistical properties
        randGen = mkTFGen seed
        action  = seqRandomPoints xmin ymin cmin xmax ymax cmax
    in
        evalRand action randGen
</code>```

Finally we can print the first few random points on stdout:

```<code>
-- Small printing utility:
printListAsLines :: Show t => [t] -> IO()
printListAsLines xs = mapM_ (putStrLn . show) xs

solved01 :: IO ()
solved01 = do
  let
       seed            = 42  -- for random number generator setup
       -- unlimited list of random points:
       allRandomPoints = randomPoints  seed  0 0 None 200 200 Blue
       count           = 5
       someRandomPoints = take count allRandomPoints
       -- IO not used at all so far

  putStrLn $ "Random points: "
  printListAsLines someRandomPoints

main = solved01

</code>```

Program execution (reproducible with constant seed):

```<code>$ randomPoints
Random points:
Point {x = 187, y = 56, color = Green}
Point {x = 131, y = 28, color = Black}
Point {x = 89, y = 135, color = Blue}
Point {x = 183, y = 190, color = Red}
Point {x = 27, y = 161, color = Green}
$

</code>```

Should you prefer to just get a finite number of points and also get back the updated state of your random number generator, you would have to use replicate n instead of repeat, and runRand instead of evalRand.

Bit more details about the monadic approach here.

Body:
I have defined a Point data type, with a single value constructor like so:

data Point = Point {
  x :: Int,
  y :: Int,
  color :: Color
} deriving (Show, Eq)

data Color = None
  | Black
  | Red
  | Green
  | Blue
  deriving (Show, Eq, Enum, Bounded)

I have found an example of making a Bounded Enum an instance of the Random class and have made Color an instance of it like so:

instance Random Color where
  random g = case randomR (1, 4) g of
    (r, g') -> (toEnum r, g')
  randomR (a, b) g = case randomR (fromEnum a, fromEnum b) g of
    (r, g') -> (toEnum r, g')

I was then able to find out how to make Point an instance of the Random class also:

instance Random Point where
  randomR (Point xl yl cl, Point xr yr cr) g =
    let (x, g1) = randomR (xl, xr) g
        (y, g2) = randomR (yl, yr) g1
        (c, g3) = randomR (cl, cr) g2
    in (Point x y c, g3)
  random g =
    let (x, g1) = random g
        (y, g2) = random g1
        (c, g3) = random g2
    in (Point x y c, g3)

So, this let's me make random point values. But, what I'd like to do is be able to create a list of random Point values, where the x and the y properties are bounded within some range whilst leaving the color property to be an unbounded random value. Is this possible with the way I am currently modelling the code, or do I need to rethink how I construct Point values? For instance, instead of making Point an instance of the Random class, should I just create a random list of Int in the IO monad and then have a pure function that creates n Points, using values from the random list to construct each Point value?

Edit, I think I have found out how to do it:

Without changing the above code, in the IO monad I can do the following:

solved :: IO ()
solved = do
  randGen <- getStdGen

  let x = 2
  let randomPoints = take x $ randomRs (Point 0 0 None, Point 200 200 Blue) randGen

  putStrLn $ "Random points: " ++ show randomPoints

This seems to work, randomRs appears to let me specify a range...

Presumably because my Point data type derives Eq?

Or

Is it because my x and y properties are Int (guessing here, but may be "bounded" by default) and I have Color derive bounded?

Body:
It works because of the properties of the Int and Color types, not because of the properties of Point. If one suppresses the Eq clause of Point, it still works.

Your code is overall quite good, however I would mention a few minor caveats.

In the Random instance for Point, you are chaining the generator states manually; this is a bit error prone, and monadic do notation is supposed to make it unnecessary. The Color instance could be simplified.

You are using IO where it is not really required. IO is just one instance of the MonadRandom class. If g is an instance of RandomGen, any Rand g is an instance of MonadRandom.

The random values you're getting are not reproducible from a program execution to the next one; this is because getStdGen implicitly uses the launch time as a random number generation seed. It may do that because it is IO-hosted. In many situations, this is a problem, as one might want to vary the choice of random sequence and the system parameters independently of each other.

Using monadic style, the basics of your code could be rewritten for example like this:

import  System.Random
import  System.Random.TF -- Threefish random number generator
import  Control.Monad.Random

data Point = Point {
  x :: Int,
  y :: Int,
  color :: Color
} deriving (Show, Eq)

data Color = None
  | Black
  | Red
  | Green
  | Blue
  deriving (Show, Eq, Enum, Bounded)

instance Random Color where
  randomR (a, b) g = let (r,g') = randomR (fromEnum a, fromEnum b) g
                     in  (toEnum r, g')
  random g = randomR (minBound::Color, maxBound::Color) g

singleRandomPoint ::  -- monadic action for just one random point
  MonadRandom mr => Int -> Int -> Color -> Int -> Int -> Color -> mr Point
singleRandomPoint xmin ymin cmin xmax ymax cmax =
  do
    -- avoid manual chaining of generator states:
    x <- getRandomR (xmin, xmax)
    y <- getRandomR (ymin, ymax)
    c <- getRandomR (cmin, cmax)
    return (Point x y c)

And then we can derive an expression returning an unlimited list of random points:

-- monadic action for an unlimited list of random points:
seqRandomPoints :: MonadRandom mr =>
  Int -> Int -> Color -> Int -> Int -> Color -> mr [Point]
seqRandomPoints xmin ymin cmin xmax ymax cmax =
    sequence (repeat (singleRandomPoint xmin ymin cmin xmax ymax cmax))

-- returns an unlimited list of random points:
randomPoints ::  Int  -> Int -> Int -> Color -> Int -> Int -> Color -> [Point]
randomPoints  seed  xmin ymin cmin xmax ymax cmax =
    let
        -- get random number generator:
        -- using Threefish algorithm (TF) for better statistical properties
        randGen = mkTFGen seed
        action  = seqRandomPoints xmin ymin cmin xmax ymax cmax
    in
        evalRand action randGen

Finally we can print the first few random points on stdout:

-- Small printing utility:
printListAsLines :: Show t => [t] -> IO()
printListAsLines xs = mapM_ (putStrLn . show) xs

solved01 :: IO ()
solved01 = do
  let
       seed            = 42  -- for random number generator setup
       -- unlimited list of random points:
       allRandomPoints = randomPoints  seed  0 0 None 200 200 Blue
       count           = 5
       someRandomPoints = take count allRandomPoints
       -- IO not used at all so far

  putStrLn $ "Random points: "
  printListAsLines someRandomPoints

main = solved01

Program execution (reproducible with constant seed):

$ randomPoints
Random points:
Point {x = 187, y = 56, color = Green}
Point {x = 131, y = 28, color = Black}
Point {x = 89, y = 135, color = Blue}
Point {x = 183, y = 190, color = Red}
Point {x = 27, y = 161, color = Green}
$

Should you prefer to just get a finite number of points and also get back the updated state of your random number generator, you would have to use replicate n instead of repeat, and runRand instead of evalRand.

Bit more details about the monadic approach here.


问:
JavaScript - get the first day of the week from current date
I need the fastest way to get the first day of the week. For example: today is the 11th of November, and a Thursday; and I want the first day of this week, which is the 8th of November, and a Monday. I need the fastest method for MongoDB map function, any ideas? </p>

答:
First / Last Day of The Week

To get the upcoming first day of the week, you can use something like so:

function getUpcomingSunday() {
  const date = new Date();
  const today = date.getDate();
  const currentDay = date.getDay();
  const newDate = date.setDate(today - currentDay + 7);
  return new Date(newDate);
}

console.log(getUpcomingSunday());```
</div>
</div>
</p>
<p>Or to get the latest first day:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getLastSunday() {
  const date = new Date();
  const today = date.getDate();
  const currentDay = date.getDay();
  const newDate = date.setDate(today - (currentDay || 7));
  return new Date(newDate);
}

console.log(getLastSunday());</code>```

* Depending on your time zone, the beginning of the week doesn't has to start on Sunday, it can start on Friday, Saturday, Monday or any other day your machine is set to. Those methods will account for that.

* You can also format it using toISOString method like so: getLastSunday().toISOString()

Body:
First / Last Day of The Week

To get the upcoming first day of the week, you can use something like so:

function getUpcomingSunday() {
  const date = new Date();
  const today = date.getDate();
  const currentDay = date.getDay();
  const newDate = date.setDate(today - currentDay + 7);
  return new Date(newDate);
}

console.log(getUpcomingSunday());

Or to get the latest first day:

function getLastSunday() {
  const date = new Date();
  const today = date.getDate();
  const currentDay = date.getDay();
  const newDate = date.setDate(today - (currentDay || 7));
  return new Date(newDate);
}

console.log(getLastSunday());

* Depending on your time zone, the beginning of the week doesn't has to start on Sunday, it can start on Friday, Saturday, Monday or any other day your machine is set to. Those methods will account for that.

* You can also format it using toISOString method like so: getLastSunday().toISOString()


问:
Button for main screen
I figure out a code for a bus schedule, but i need help creating a main screen before the actual schedule that links to all this code.

THANK YOU to all the people who posted answers before & helped me ALOT !

```<code>var myDate:Date = new Date();
var countdown:Number

//Shuttle bus to CSI
var busHours:Array = new Array();
busHours[0] = ["2CSI", 7, 05];
busHours[1] = ["2CSI", 7, 35];
busHours[2] = ["2CSI", 8, 05];
busHours[3] = ["2CSI", 8, 35];
busHours[4] = ["2CSI", 9, 05];
busHours[5] = ["2CSI", 9, 35];
busHours[6] = ["2CSI", 10, 05];
busHours[7] = ["2CSI", 10, 35];
busHours[8] = ["2CSI", 11, 05];
busHours[9] = ["2CSI", 11, 35];
busHours[10] = ["2CSI", 12, 05];
busHours[11] = ["2CSI", 12, 35];
busHours[12] = ["2CSI", 13, 05];
busHours[13] = ["2CSI", 13, 35];
busHours[14] = ["2CSI", 14, 05];
busHours[15] = ["2CSI", 14, 35];
busHours[16] = ["2CSI", 15, 05];
busHours[17] = ["2CSI", 15, 35];
busHours[18] = ["2CSI", 16, 05];
busHours[19] = ["2CSI", 16, 35];
busHours[20] = ["2CSI", 17, 05];
busHours[21] = ["2CSI", 17, 35];
busHours[22] = ["2CSI", 18, 05];
busHours[23] = ["2CSI", 18, 35];
busHours[24] = ["2CSI", 19, 05];
busHours[25] = ["2CSI", 19, 35];
busHours[26] = ["2CSI", 20, 05];
busHours[26] = ["2CSI", 20, 35];
busHours[26] = ["2CSI", 21, 05];
busHours[26] = ["2CSI", 21, 35];
busHours[26] = ["2CSI", 22, 05];
busHours[26] = ["2CSI", 22, 35];

for (var i:Number = 0; i < busHours.length; i++) {

if(myDate.hours < busHours[i][1] || myDate.hours == busHours[i][1] && myDate.minutes <= busHours[i][2]){
    trace(busHours[i][1]);
    if(busHours[i][1] == myDate.hours){
        countdown = busHours[i][2] - myDate.minutes;
    } else {
        countdown = 60 - myDate.minutes + busHours[i][2];

    }

    csi.text = "The next Shuttle bus to CSI arrives at " + busHours[i][1] + ":" + busHours[i][2] + " in " + countdown + " minute(s)";
    i += busHours.length;
} else {

    csi.text = "There are no more Shuttle buses arriving at The College of Staten Island at this time.";

}

}

//Shuttle Bus to ferry
var FerrybusHours:Array = new Array();
FerrybusHours[0] = ["2Ferry", 7, 35];
FerrybusHours[1] = ["2Ferry", 8, 05];
FerrybusHours[2] = ["2Ferry", 8, 35];
FerrybusHours[3] = ["2Ferry", 9, 05];
FerrybusHours[4] = ["2Ferry", 9, 35];
FerrybusHours[5] = ["2Ferry", 10, 05];
FerrybusHours[6] = ["2Ferry", 10, 35];
FerrybusHours[7] = ["2Ferry", 11, 05];
FerrybusHours[8] = ["2Ferry", 11, 35];
FerrybusHours[9] = ["2Ferry", 12, 05];
FerrybusHours[10] = ["2Ferry", 12, 35];
FerrybusHours[11] = ["2Ferry", 13, 05];
FerrybusHours[12] = ["2Ferry", 13, 35];
FerrybusHours[13] = ["2Ferry", 14, 05];
FerrybusHours[14] = ["2Ferry", 14, 35];
FerrybusHours[15] = ["2Ferry", 15, 05];
FerrybusHours[16] = ["2Ferry", 15, 35];
FerrybusHours[17] = ["2Ferry", 16, 05];
FerrybusHours[18] = ["2Ferry", 16, 35];
FerrybusHours[19] = ["2Ferry", 17, 05];
FerrybusHours[20] = ["2Ferry", 17, 35];
FerrybusHours[21] = ["2Ferry", 18, 05];
FerrybusHours[22] = ["2Ferry", 18, 35];
FerrybusHours[23] = ["2Ferry", 19, 05];
FerrybusHours[24] = ["2Ferry", 19, 35];
FerrybusHours[25] = ["2Ferry", 20, 05];
FerrybusHours[26] = ["2Ferry", 20, 35];
FerrybusHours[27] = ["2Ferry", 21, 05];
FerrybusHours[28] = ["2Ferry", 21, 35];
FerrybusHours[29] = ["2Ferry", 22, 05];
FerrybusHours[30] = ["2Ferry", 22, 35];
FerrybusHours[31] = ["2Ferry", 23, 05];

for (var f:Number = 0; f < FerrybusHours.length; f++) {

if(myDate.hours < FerrybusHours[f][1] || myDate.hours == FerrybusHours[f][1] && myDate.minutes <= FerrybusHours[f][2]){
    trace(FerrybusHours[f][1]);
    if(FerrybusHours[f][1] == myDate.hours){
        countdown = FerrybusHours[f][2] - myDate.minutes;
    } else {
        countdown = 60 - myDate.minutes + FerrybusHours[f][2];

    }

    ferry.text = "The next Shuttle bus to the Ferry Terminal arrives at " + FerrybusHours[f][1] + ":" + FerrybusHours[f][2] + " in " + countdown + " minute(s)";
    f += FerrybusHours.length;
} else {

    ferry.text = "There are no more Shuttle buses arriving at the ferry terminal at this time.";

}

}
</code>```

答:
From your post it sounds like you're working in the Flash IDE and coding in the timeline. If that isn't the case then you might want to ignore this.

You could just add an event listener to check for when your button/movieclip is clicked and place your bus code and assets on the second frame. On the first frame put your button with the code:

```<code>button.addEventListener(MouseEvent.CLICK,clickButton);
function clickButton(e:MouseEvent){
   gotoAndStop(2);
}
</code>```

Now when you click the button it should move to frame 2 and run your bus code.

ContentLicense: CC BY-SA 3.0

Title: Button for main screen

Body:
I figure out a code for a bus schedule, but i need help creating a main screen before the actual schedule that links to all this code.

THANK YOU to all the people who posted answers before & helped me ALOT !

var myDate:Date = new Date();
var countdown:Number

//Shuttle bus to CSI
var busHours:Array = new Array();
busHours[0] = ["2CSI", 7, 05];
busHours[1] = ["2CSI", 7, 35];
busHours[2] = ["2CSI", 8, 05];
busHours[3] = ["2CSI", 8, 35];
busHours[4] = ["2CSI", 9, 05];
busHours[5] = ["2CSI", 9, 35];
busHours[6] = ["2CSI", 10, 05];
busHours[7] = ["2CSI", 10, 35];
busHours[8] = ["2CSI", 11, 05];
busHours[9] = ["2CSI", 11, 35];
busHours[10] = ["2CSI", 12, 05];
busHours[11] = ["2CSI", 12, 35];
busHours[12] = ["2CSI", 13, 05];
busHours[13] = ["2CSI", 13, 35];
busHours[14] = ["2CSI", 14, 05];
busHours[15] = ["2CSI", 14, 35];
busHours[16] = ["2CSI", 15, 05];
busHours[17] = ["2CSI", 15, 35];
busHours[18] = ["2CSI", 16, 05];
busHours[19] = ["2CSI", 16, 35];
busHours[20] = ["2CSI", 17, 05];
busHours[21] = ["2CSI", 17, 35];
busHours[22] = ["2CSI", 18, 05];
busHours[23] = ["2CSI", 18, 35];
busHours[24] = ["2CSI", 19, 05];
busHours[25] = ["2CSI", 19, 35];
busHours[26] = ["2CSI", 20, 05];
busHours[26] = ["2CSI", 20, 35];
busHours[26] = ["2CSI", 21, 05];
busHours[26] = ["2CSI", 21, 35];
busHours[26] = ["2CSI", 22, 05];
busHours[26] = ["2CSI", 22, 35];

for (var i:Number = 0; i < busHours.length; i++) {

if(myDate.hours < busHours[i][1] || myDate.hours == busHours[i][1] && myDate.minutes <= busHours[i][2]){
    trace(busHours[i][1]);
    if(busHours[i][1] == myDate.hours){
        countdown = busHours[i][2] - myDate.minutes;
    } else {
        countdown = 60 - myDate.minutes + busHours[i][2];

    }

    csi.text = "The next Shuttle bus to CSI arrives at " + busHours[i][1] + ":" + busHours[i][2] + " in " + countdown + " minute(s)";
    i += busHours.length;
} else {

    csi.text = "There are no more Shuttle buses arriving at The College of Staten Island at this time.";

}

}

//Shuttle Bus to ferry
var FerrybusHours:Array = new Array();
FerrybusHours[0] = ["2Ferry", 7, 35];
FerrybusHours[1] = ["2Ferry", 8, 05];
FerrybusHours[2] = ["2Ferry", 8, 35];
FerrybusHours[3] = ["2Ferry", 9, 05];
FerrybusHours[4] = ["2Ferry", 9, 35];
FerrybusHours[5] = ["2Ferry", 10, 05];
FerrybusHours[6] = ["2Ferry", 10, 35];
FerrybusHours[7] = ["2Ferry", 11, 05];
FerrybusHours[8] = ["2Ferry", 11, 35];
FerrybusHours[9] = ["2Ferry", 12, 05];
FerrybusHours[10] = ["2Ferry", 12, 35];
FerrybusHours[11] = ["2Ferry", 13, 05];
FerrybusHours[12] = ["2Ferry", 13, 35];
FerrybusHours[13] = ["2Ferry", 14, 05];
FerrybusHours[14] = ["2Ferry", 14, 35];
FerrybusHours[15] = ["2Ferry", 15, 05];
FerrybusHours[16] = ["2Ferry", 15, 35];
FerrybusHours[17] = ["2Ferry", 16, 05];
FerrybusHours[18] = ["2Ferry", 16, 35];
FerrybusHours[19] = ["2Ferry", 17, 05];
FerrybusHours[20] = ["2Ferry", 17, 35];
FerrybusHours[21] = ["2Ferry", 18, 05];
FerrybusHours[22] = ["2Ferry", 18, 35];
FerrybusHours[23] = ["2Ferry", 19, 05];
FerrybusHours[24] = ["2Ferry", 19, 35];
FerrybusHours[25] = ["2Ferry", 20, 05];
FerrybusHours[26] = ["2Ferry", 20, 35];
FerrybusHours[27] = ["2Ferry", 21, 05];
FerrybusHours[28] = ["2Ferry", 21, 35];
FerrybusHours[29] = ["2Ferry", 22, 05];
FerrybusHours[30] = ["2Ferry", 22, 35];
FerrybusHours[31] = ["2Ferry", 23, 05];

for (var f:Number = 0; f < FerrybusHours.length; f++) {

if(myDate.hours < FerrybusHours[f][1] || myDate.hours == FerrybusHours[f][1] && myDate.minutes <= FerrybusHours[f][2]){
    trace(FerrybusHours[f][1]);
    if(FerrybusHours[f][1] == myDate.hours){
        countdown = FerrybusHours[f][2] - myDate.minutes;
    } else {
        countdown = 60 - myDate.minutes + FerrybusHours[f][2];

    }

    ferry.text = "The next Shuttle bus to the Ferry Terminal arrives at " + FerrybusHours[f][1] + ":" + FerrybusHours[f][2] + " in " + countdown + " minute(s)";
    f += FerrybusHours.length;
} else {

    ferry.text = "There are no more Shuttle buses arriving at the ferry terminal at this time.";

}

}

Body:
From your post it sounds like you're working in the Flash IDE and coding in the timeline. If that isn't the case then you might want to ignore this.

You could just add an event listener to check for when your button/movieclip is clicked and place your bus code and assets on the second frame. On the first frame put your button with the code:

button.addEventListener(MouseEvent.CLICK,clickButton);
function clickButton(e:MouseEvent){
   gotoAndStop(2);
}

Now when you click the button it should move to frame 2 and run your bus code.


问:
What can i use as a device identifier in flutter?
I'm building an app and I need a unique identifier for each device and I don't want it to change even if the user uninstalls the app, what should I use? I don't know what I should look for. I searched a bit and I found something named deviceid is it good enough?
https://pub.dev/packages/device_id

答:
The safest way is to build a registration for the user. So, if the user want to use your app, he needs to register a profile. Each account gets a unique identifier and even when the user reinstall the app you can identifier him.

The package that you linked is possible too, but remember jailbreaked devices could change the device id.

I'm not 100% sure, but in Swift/iOS you can use for this case KeyChain. Check this package, maybe it can help you. You can find more infos about KeyChain here.


问:
TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe' while plotting a seaborn.regplot
I'm trying to plot a regplot using seaborn and i'm not unable to plot it and facing TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe' .

My data has 731 rows and 16 column -

```<code>>>> bike_df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 731 entries, 0 to 730
Data columns (total 16 columns):
 #   Column      Non-Null Count  Dtype
---  ------      --------------  -----
 0   instant     731 non-null    int64
 1   dteday      731 non-null    object
 2   season      731 non-null    int64
 3   yr          731 non-null    int64
 4   mnth        731 non-null    int64
 5   holiday     731 non-null    int64
 6   weekday     731 non-null    int64
 7   workingday  731 non-null    int64
 8   weathersit  731 non-null    int64
 9   temp        731 non-null    float64
 10  atemp       731 non-null    float64
 11  hum         731 non-null    float64
 12  windspeed   731 non-null    float64
 13  casual      731 non-null    int64
 14  registered  731 non-null    int64
 15  cnt         731 non-null    int64
dtypes: float64(4), int64(11), object(1)
memory usage: 88.6+ KB
</code>```

Here is a snippet of the data

And when i'm trying to plot regplot using seaborn -

```<code>>>> sns.regplot(x="casual", y="cnt", data=bike_df);

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-54-68533af96906> in <module>
----> 1 sns.regplot(x="casual", y="cnt", data=bike_df);

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\regression.py in regplot(x, y, data, x_estimator, x_bins, x_ci, scatter, fit_reg, ci, n_boot, units, seed, order, logistic, lowess, robust, logx, x_partial, y_partial, truncate, dropna, x_jitter, y_jitter, label, color, marker, scatter_kws, line_kws, ax)
    816     scatter_kws["marker"] = marker
    817     line_kws = {} if line_kws is None else copy.copy(line_kws)
--> 818     plotter.plot(ax, scatter_kws, line_kws)
    819     return ax
    820

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\regression.py in plot(self, ax, scatter_kws, line_kws)
    363
    364         if self.fit_reg:
--> 365             self.lineplot(ax, line_kws)
    366
    367         # Label the axes

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\regression.py in lineplot(self, ax, kws)
    406         """Draw the model."""
    407         # Fit the regression model
--> 408         grid, yhat, err_bands = self.fit_regression(ax)
    409         edges = grid[0], grid[-1]
    410

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\regression.py in fit_regression(self, ax, x_range, grid)
    214             yhat, yhat_boots = self.fit_logx(grid)
    215         else:
--> 216             yhat, yhat_boots = self.fit_fast(grid)
    217
    218         # Compute the confidence interval at each grid point

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\regression.py in fit_fast(self, grid)
    239                                     n_boot=self.n_boot,
    240                                     units=self.units,
--> 241                                     seed=self.seed).T
    242         yhat_boots = grid.dot(beta_boots).T
    243         return yhat, yhat_boots

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\algorithms.py in bootstrap(*args, **kwargs)
     83     for i in range(int(n_boot)):
     84         resampler = integers(0, n, n)
---> 85         sample = [a.take(resampler, axis=0) for a in args]
     86         boot_dist.append(f(*sample, **func_kwargs))
     87     return np.array(boot_dist)

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\algorithms.py in <listcomp>(.0)
     83     for i in range(int(n_boot)):
     84         resampler = integers(0, n, n)
---> 85         sample = [a.take(resampler, axis=0) for a in args]
     86         boot_dist.append(f(*sample, **func_kwargs))
     87     return np.array(boot_dist)

TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'
</code>```

I tried changing the datatypes using dtypes for all the rows like below -

```<code>>>> bike_df['cnt'] = bike_df['cnt'].astype(np.int32)
</code>```

but this did not help and got the same error again while plotting.

Any suggestions are appreciated.

Thanks in advance.

答:
Update: this bug is solved in Seaborn version 0.10.1 (April 2020).

I encountered the same problem. It is issue 1950 at Seaborn's github. Related to running a 32-bit version of numpy. It will be solved in the next release.

To work around the problem, I changed line 84 of my local version of Seaborn's algorithm.py:

```<code>resampler = integers(0, n, n, dtype=np.int_)
</code>```

This happened with:

numpy version: 1.18.1

seaborn version: 0.10.0

Body:
I'm trying to plot a regplot using seaborn and i'm not unable to plot it and facing TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe' .

My data has 731 rows and 16 column -

>>> bike_df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 731 entries, 0 to 730
Data columns (total 16 columns):
 #   Column      Non-Null Count  Dtype
---  ------      --------------  -----
 0   instant     731 non-null    int64
 1   dteday      731 non-null    object
 2   season      731 non-null    int64
 3   yr          731 non-null    int64
 4   mnth        731 non-null    int64
 5   holiday     731 non-null    int64
 6   weekday     731 non-null    int64
 7   workingday  731 non-null    int64
 8   weathersit  731 non-null    int64
 9   temp        731 non-null    float64
 10  atemp       731 non-null    float64
 11  hum         731 non-null    float64
 12  windspeed   731 non-null    float64
 13  casual      731 non-null    int64
 14  registered  731 non-null    int64
 15  cnt         731 non-null    int64
dtypes: float64(4), int64(11), object(1)
memory usage: 88.6+ KB

Here is a snippet of the data

And when i'm trying to plot regplot using seaborn -

>>> sns.regplot(x="casual", y="cnt", data=bike_df);

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-54-68533af96906> in <module>
----> 1 sns.regplot(x="casual", y="cnt", data=bike_df);

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\regression.py in regplot(x, y, data, x_estimator, x_bins, x_ci, scatter, fit_reg, ci, n_boot, units, seed, order, logistic, lowess, robust, logx, x_partial, y_partial, truncate, dropna, x_jitter, y_jitter, label, color, marker, scatter_kws, line_kws, ax)
    816     scatter_kws["marker"] = marker
    817     line_kws = {} if line_kws is None else copy.copy(line_kws)
--> 818     plotter.plot(ax, scatter_kws, line_kws)
    819     return ax
    820

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\regression.py in plot(self, ax, scatter_kws, line_kws)
    363
    364         if self.fit_reg:
--> 365             self.lineplot(ax, line_kws)
    366
    367         # Label the axes

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\regression.py in lineplot(self, ax, kws)
    406         """Draw the model."""
    407         # Fit the regression model
--> 408         grid, yhat, err_bands = self.fit_regression(ax)
    409         edges = grid[0], grid[-1]
    410

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\regression.py in fit_regression(self, ax, x_range, grid)
    214             yhat, yhat_boots = self.fit_logx(grid)
    215         else:
--> 216             yhat, yhat_boots = self.fit_fast(grid)
    217
    218         # Compute the confidence interval at each grid point

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\regression.py in fit_fast(self, grid)
    239                                     n_boot=self.n_boot,
    240                                     units=self.units,
--> 241                                     seed=self.seed).T
    242         yhat_boots = grid.dot(beta_boots).T
    243         return yhat, yhat_boots

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\algorithms.py in bootstrap(*args, **kwargs)
     83     for i in range(int(n_boot)):
     84         resampler = integers(0, n, n)
---> 85         sample = [a.take(resampler, axis=0) for a in args]
     86         boot_dist.append(f(*sample, **func_kwargs))
     87     return np.array(boot_dist)

~\AppData\Local\Continuum\anaconda3\envs\rstudio\lib\site-packages\seaborn\algorithms.py in <listcomp>(.0)
     83     for i in range(int(n_boot)):
     84         resampler = integers(0, n, n)
---> 85         sample = [a.take(resampler, axis=0) for a in args]
     86         boot_dist.append(f(*sample, **func_kwargs))
     87     return np.array(boot_dist)

TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'

I tried changing the datatypes using dtypes for all the rows like below -

>>> bike_df['cnt'] = bike_df['cnt'].astype(np.int32)

but this did not help and got the same error again while plotting.

Any suggestions are appreciated.

Thanks in advance.

Body:
Update: this bug is solved in Seaborn version 0.10.1 (April 2020).

I encountered the same problem. It is issue 1950 at Seaborn's github. Related to running a 32-bit version of numpy. It will be solved in the next release.

To work around the problem, I changed line 84 of my local version of Seaborn's algorithm.py:

resampler = integers(0, n, n, dtype=np.int_)

This happened with:

numpy version: 1.18.1

seaborn version: 0.10.0


问:
regexp does not work as expected in Octave
I have downloaded the "NYU Depth V2" dataset and toolbox from here. In the toolbox there is a script called get_synched_frames.m. I do not have Matlab, so I have tried running it in Octave. Unfortunately, it does not work as expected.

The line

```<code>% Faster than matlab's Dir function for big directories and slow
% distributed file systems...
files = regexp(ls(sceneDir), '(\s+|\n)', 'split');
</code>```

gives only

```<code>files =
{
  [1,1] = a-1300302776.479149-3987628315.dump
}
</code>```

but ls(sceneDir) shows all files in the directory. Has anyone experienced this?

答:
The difference is probably not in regexp, but in the return value of ls. ls does not behave the same way in Matlab and Octave when you capture its return value. Matlab's ls returns a char row vector (single string as char) with multiple files listed in it as a multi-line string with embedded newlines; Octave's ls returns a 2-D char array with one file per line. (IMHO Octave's format is better; it is very difficult to parse Matlab's ls output in a reliably correct manner. (That regexp code is not adequate.))

You might just want this in Octave:

```<code>files = cellstr(ls(sceneDir));
</code>```

Body:
I have downloaded the "NYU Depth V2" dataset and toolbox from here. In the toolbox there is a script called get_synched_frames.m. I do not have Matlab, so I have tried running it in Octave. Unfortunately, it does not work as expected.

The line

% Faster than matlab's Dir function for big directories and slow
% distributed file systems...
files = regexp(ls(sceneDir), '(\s+|\n)', 'split');

gives only

files =
{
  [1,1] = a-1300302776.479149-3987628315.dump
}

but ls(sceneDir) shows all files in the directory. Has anyone experienced this?

Body:
The difference is probably not in regexp, but in the return value of ls. ls does not behave the same way in Matlab and Octave when you capture its return value. Matlab's ls returns a char row vector (single string as char) with multiple files listed in it as a multi-line string with embedded newlines; Octave's ls returns a 2-D char array with one file per line. (IMHO Octave's format is better; it is very difficult to parse Matlab's ls output in a reliably correct manner. (That regexp code is not adequate.))

You might just want this in Octave:

files = cellstr(ls(sceneDir));


问:
HashiCorp Vault Database Secrets display Connection URL
Following:

https://www.vaultproject.io/docs/secrets/databases/mysql-maria/

I want to display connection_url or database host along with userpass when I query Vault via:

vault read database/creds/my-role

答:
Im afraid that is not possible with the current db plugins.

Other possible solutions are to create a KV with the connection url and retrieve that. To maintain consistency, you can keep the same path as the creds, for example

db creds with vault read database/creds/my-role
and connection string with vault read kv/database/creds/my-role

This means that you have some overhead when you are setting up vault and when you are retrieving the credentials

Another option is to read the database config from the API.

This will yield back something like

```<code>{
  "data": {
    "allowed_roles": ["readonly"],
    "connection_details": {
      "connection_url": "{{username}}:{{password}}@tcp(127.0.0.1:3306)/",
      "username": "root"
    },
    "plugin_name": "mysql-database-plugin"
  }
}
</code>```

where you can get the connection_url and regex it to get the connection string. I think this requires more effort as your client needs to know how to convert the connection string (comparing it with the first solution i mentioned where the KV is generated when you are generating the database engine config)

Body:
Im afraid that is not possible with the current db plugins.

Other possible solutions are to create a KV with the connection url and retrieve that. To maintain consistency, you can keep the same path as the creds, for example

db creds with vault read database/creds/my-role
and connection string with vault read kv/database/creds/my-role

This means that you have some overhead when you are setting up vault and when you are retrieving the credentials

Another option is to read the database config from the API.

This will yield back something like

{
  "data": {
    "allowed_roles": ["readonly"],
    "connection_details": {
      "connection_url": "{{username}}:{{password}}@tcp(127.0.0.1:3306)/",
      "username": "root"
    },
    "plugin_name": "mysql-database-plugin"
  }
}

where you can get the connection_url and regex it to get the connection string. I think this requires more effort as your client needs to know how to convert the connection string (comparing it with the first solution i mentioned where the KV is generated when you are generating the database engine config)


问:
Lift a key’s values to top level whilst preserving rest of object using Ramda
I would like to build it into my compose function so that record’s values go to the top level of the object, whilst the rest of the keys stay in tact:

```<code>{
  record: {
    seasons: [
      1
    ],
    colors: [
      2
    ]
  },
  tag_ids: [
    2091
  ]
}
</code>```

The result I am after:

```<code>{
  seasons: [
    1
  ],
  colors: [
    2
  ],
  tag_ids: [
    2091
  ]
}
</code>```

Any of the keys may or may not exist.

I have always scratched my head with the ramda way to do it in a compose function. Currently I am looking at toPairs and doing some pretty long winded transforms with no luck.

答:
This might help too!

const lift = key => R.converge(R.mergeRight, [
  R.dissoc(key),
  R.prop(key),
]);

const liftRecord = lift('record');

// ====
const data = {
  record: {
    seasons: [
      1
    ],
    colors: [
      2
    ]
  },
  tag_ids: [
    2091
  ]
};

console.log(
  liftRecord(data),
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js" integrity="sha256-buL0byPvI/XRDFscnSc/e0q+sLA65O9y+rbF+0O/4FE=" crossorigin="anonymous"></script></code>```

Body:
I would like to build it into my compose function so that record’s values go to the top level of the object, whilst the rest of the keys stay in tact:

{
  record: {
    seasons: [
      1
    ],
    colors: [
      2
    ]
  },
  tag_ids: [
    2091
  ]
}

The result I am after:

{
  seasons: [
    1
  ],
  colors: [
    2
  ],
  tag_ids: [
    2091
  ]
}

Any of the keys may or may not exist.

I have always scratched my head with the ramda way to do it in a compose function. Currently I am looking at toPairs and doing some pretty long winded transforms with no luck.

Body:
This might help too!

const lift = key => R.converge(R.mergeRight, [
  R.dissoc(key),
  R.prop(key),
]);

const liftRecord = lift('record');

// ====
const data = {
  record: {
    seasons: [
      1
    ],
    colors: [
      2
    ]
  },
  tag_ids: [
    2091
  ]
};

console.log(
  liftRecord(data),
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js" integrity="sha256-buL0byPvI/XRDFscnSc/e0q+sLA65O9y+rbF+0O/4FE=" crossorigin="anonymous"></script>


问:
MySQL: How to enable load data local on both, client and server sides
I tried to upload a .txt file into MySQL Workbench, but I have the following issue:

Error Code: 3948 Loading Local data is disable; this must be enable on both the client and server sides

答:
Workbench uses a MySQL feature called LOAD DATA LOCAL for this .txt file import operation. Because that feature exposes some security problems in the server, the operator of the server needs to enable that feature, by running the MySQL server software (mysqld, it's called) with a specific system variable called local_infile.  Your error message means that flag is not enabled.

You can try enabling it at runtime before you do your upload operation. Try this SQL statement.

```<code>SET @@GLOBAL.local_infile = 1;
</code>```

If that doesn't work you need to ask the person who runs your server to enable it.

Body:
Workbench uses a MySQL feature called LOAD DATA LOCAL for this .txt file import operation. Because that feature exposes some security problems in the server, the operator of the server needs to enable that feature, by running the MySQL server software (mysqld, it's called) with a specific system variable called local_infile.  Your error message means that flag is not enabled.

You can try enabling it at runtime before you do your upload operation. Try this SQL statement.

SET @@GLOBAL.local_infile = 1;

If that doesn't work you need to ask the person who runs your server to enable it.


问:
How to create a function to dynamically create list of tuples within a range?
Is there a way to create a function which creates a list of tuples with arguments for:

number of tuples

elements per tuple

beginning range

ending range

I believe I have most of it:

```<code>import random

def list_rand_num_tuples(num_of_tups, range_beg, range_end):
    list_tuples = [
        (random.randrange(range_beg, range_end),
         random.randrange(range_beg, range_end),
         random.randrange(range_beg, range_end))
        for i in range(num_of_tups)]
    return list_tuples

# test/display it
print(list_rand_num_tuples(3, 0, 51))
</code>```

but how can this portion be more dynamic?

```<code>(random.randrange(range_beg, range_end),
 random.randrange(range_beg, range_end),
 random.randrange(range_beg, range_end))
</code>```

For example, can the length of tuple / elements of tuple argument be provided to loop through this part the appropriate number of times?

答:
Adding the elem_per_tuple variable into the function. Using lambda for readability sake so that your nested list comprehension list_tuples doesn't look like knotted noodles.

import random

def list_rand_num_tuples(num_of_tups, elem_per_tuple, range_beg, range_end):
    rand = lambda: random.randrange(range_beg, range_end)
    return [tuple(rand() for _ in range(elem_per_tuple)) for _ in range(num_of_tups)]

print(list_rand_num_tuples(3, 3, 0, 51))
```

<p>Outputs:</p>

```[(22, 47, 11), (37, 26, 40), (29, 22, 7)]
```

Body:
Is there a way to create a function which creates a list of tuples with arguments for:

number of tuples

elements per tuple

beginning range

ending range

I believe I have most of it:

import random

def list_rand_num_tuples(num_of_tups, range_beg, range_end):
    list_tuples = [
        (random.randrange(range_beg, range_end),
         random.randrange(range_beg, range_end),
         random.randrange(range_beg, range_end))
        for i in range(num_of_tups)]
    return list_tuples

# test/display it
print(list_rand_num_tuples(3, 0, 51))

but how can this portion be more dynamic?

(random.randrange(range_beg, range_end),
 random.randrange(range_beg, range_end),
 random.randrange(range_beg, range_end))

For example, can the length of tuple / elements of tuple argument be provided to loop through this part the appropriate number of times?

Body:
Adding the elem_per_tuple variable into the function. Using lambda for readability sake so that your nested list comprehension list_tuples doesn't look like knotted noodles.

import random

def list_rand_num_tuples(num_of_tups, elem_per_tuple, range_beg, range_end):
    rand = lambda: random.randrange(range_beg, range_end)
    return [tuple(rand() for _ in range(elem_per_tuple)) for _ in range(num_of_tups)]

print(list_rand_num_tuples(3, 3, 0, 51))

Outputs:

[(22, 47, 11), (37, 26, 40), (29, 22, 7)]


问:
Is Byte Really The Minimum Addressable Unit?
Section 3.6 of C11 standard defines "byte" as "addressable unit of data storage ... to hold ... character".

Section 1.7 of C++11 standard defines "byte" as "the fundamental storage unit in the C++ memory model ... to contain ... character".

Both definitions does not say that "byte" is the minimum addressable unit. Is this because standards intentionally want to abstract from a specific machine ? Can you provide a real example of machine where C/C++ compiler were decided to have "byte" longer/shorter than the minimum addressable unit ?

答:
One example of a real machine and its compiler where the minimal addressable unit is smaller than a byte is the 8051 family. One compiler I was used to is Keil C51.

The minimal addressable unit is a bit. You can define a variable of this type, you can read and write it. However, the syntax to define the variable is non-standard. Of course, C51 needs several extensions to support all of this. BTW, pointers to bits are not allowed.

For example:

```<code>unsigned char bdata bitsAdressable;
sbit bitAddressed = bitsAdressable^5;

void f(void) {
    bitAddressed = 1;
}

bit singleBit;

void g(bit value) {
    singleBit = value;
}
</code>```

Body:
One example of a real machine and its compiler where the minimal addressable unit is smaller than a byte is the 8051 family. One compiler I was used to is Keil C51.

The minimal addressable unit is a bit. You can define a variable of this type, you can read and write it. However, the syntax to define the variable is non-standard. Of course, C51 needs several extensions to support all of this. BTW, pointers to bits are not allowed.

For example:

unsigned char bdata bitsAdressable;
sbit bitAddressed = bitsAdressable^5;

void f(void) {
    bitAddressed = 1;
}

bit singleBit;

void g(bit value) {
    singleBit = value;
}


问:
Adding list item is not adding all innerHTML
for part of a learning project I'm making I've run into a weird javascript/html issue. The section in question is a simple to do list, which works perfectly fine except for one thing. The program will successfully grab the text the user enters, add it to a new list item and insert it into the unordered list, but only adds an X (for a remove function I haven't added yet) to the first element.

Additionally, if you check in the browser inspector, both new li's do have the 'a' element with the X inside of it, but on hovering over the a element in both li's (or more li's depending) they all "point" back to the one and only 'a' element on the first li.

Can anyone explain what I did wrong so that I can fix it and avoid this in the future? Why is it not adding the 'a' element individually to each new li?

I've included a jsfiddle link below:

```<code> const li = document.createElement('li');
  // add li class
  li.className = 'list-item';
  // append text node containing user input to li item
  li.appendChild(document.createTextNode(taskList.value));
  // create 'a' element to list and add classes/html
  const link = document.createElement('a');
  link.className = 'delete-item';
  link.innerHTML = '<i class="fa fa-remove"></i>';

  // append 'a' element to li
  li.appendChild(link);
  document.querySelector('.list-items').append(li);
</code>```

https://jsfiddle.net/Iahon/xocpb6n7/11/

答:
Your javascript code works, it's a CSS issue.

Your .delete-item class has a position: absolute property that makes all the links to be stacked at the same position. Change your position: absolute with a float: right and remove the top and right properties:

.container .row2 .to-doList .list-items .list-item .delete-item {
  float: right;
  cursor: pointer;
}
```

This will fix the issue and keep your link at the same position.

Edit: If you do not want to use float: right, see @AdamKniec answer below offering another possibility by modifying the CSS of the parent element.

Body:
for part of a learning project I'm making I've run into a weird javascript/html issue. The section in question is a simple to do list, which works perfectly fine except for one thing. The program will successfully grab the text the user enters, add it to a new list item and insert it into the unordered list, but only adds an X (for a remove function I haven't added yet) to the first element.

Additionally, if you check in the browser inspector, both new li's do have the 'a' element with the X inside of it, but on hovering over the a element in both li's (or more li's depending) they all "point" back to the one and only 'a' element on the first li.

Can anyone explain what I did wrong so that I can fix it and avoid this in the future? Why is it not adding the 'a' element individually to each new li?

I've included a jsfiddle link below:

 const li = document.createElement('li');
  // add li class
  li.className = 'list-item';
  // append text node containing user input to li item
  li.appendChild(document.createTextNode(taskList.value));
  // create 'a' element to list and add classes/html
  const link = document.createElement('a');
  link.className = 'delete-item';
  link.innerHTML = '';

  // append 'a' element to li
  li.appendChild(link);
  document.querySelector('.list-items').append(li);

https://jsfiddle.net/Iahon/xocpb6n7/11/

Body:
Your javascript code works, it's a CSS issue.

Your .delete-item class has a position: absolute property that makes all the links to be stacked at the same position. Change your position: absolute with a float: right and remove the top and right properties:

.container .row2 .to-doList .list-items .list-item .delete-item {
  float: right;
  cursor: pointer;
}

This will fix the issue and keep your link at the same position.

Edit: If you do not want to use float: right, see @AdamKniec answer below offering another possibility by modifying the CSS of the parent element.


问:
Can I add multiple answers for a single question in Azure QnA Maker?
I'd like to have users input a single prompt, like "read me a poem," and have QnA give a different response every time.  Ideally, QnA would rotate through a list of responses I've created.  Is there any way to do this?</p>

答:
yes, you can now: they added the param "top" to the JSON object for the POST:

e.g.

```<code>{
  "question": "Hi",
  "top": 30,
  "isTest": true,
  "RankerType":"QuestionOnly"
}
</code>```

POST to QnAMaker API returns (max.) the top 30 answers.

See also https://learn.microsoft.com/en-us/azure/cognitive-services/qnamaker/how-to/improve-knowledge-base#use-the-top-property-in-the-generateanswer-request-to-get-several-matching-answers

Body:
yes, you can now: they added the param "top" to the JSON object for the POST:

e.g.

{
  "question": "Hi",
  "top": 30,
  "isTest": true,
  "RankerType":"QuestionOnly"
}

POST to QnAMaker API returns (max.) the top 30 answers.

See also https://learn.microsoft.com/en-us/azure/cognitive-services/qnamaker/how-to/improve-knowledge-base#use-the-top-property-in-the-generateanswer-request-to-get-several-matching-answers


问:
How to call methods on Python class descriptor objects?
I created a class String() with __get__(), __set__(), and a method to_db(); however, when I do name = String(), I can't do self.name.to_db() because it's calling to_db() on the value returned by __get__(), not the object "name".

```<code>class String(object):

    def __init__(self, value=None):
        if value:
            self.value = str(value)

    def __get__(self, instance, owner):
        return self.value

    def __set__(self, instance, value):
        self.value = str(value)

    def to_db(self):
        return {'type':'string', 'value': self.value}

class Example(object):

    name = String()
    age = Integer()

    def __init__(self,name,age):
        self.name = name
        self.age = age

    def save():
        data = dict(name=self.name.to_db(), age=self.age.to_db())
        db.save(data)
</code>```

One way to deal with this is to not call self.name.to_db() directly and instead set a flag in instance and create a conditional in __get__() to check for it and call to_db() if it's True, but this seems kludgy. Is there a better way?

Also, I'm new to descriptors -- what are the pros/cons of using instance and/or instance.__dict__ to store state vs storing it in self?

答:
Here's a solution that allows you to bypass any descriptors defined in the class:

```<code>class BypassableDescriptor(object):
    pass

class String(BypassableDescriptor):
    def __init__(self, value=None):
        if value:
            self.value = str(value)

    def __get__(self, instance, owner):
        return self.value

    def __set__(self, instance, value):
        self.value = str(value)

    def to_db(self):
        return {'type': 'string', 'value': self.value}

class Integer(BypassableDescriptor):
    def __init__(self, value=None):
        if value:
            self.value = str(value)

    def __get__(self, instance, owner):
        return self.value

    def __set__(self, instance, value):
        self.value = int(value)

    def to_db(self):
        return {'type': 'integer', 'value': self.value}

class BypassDescriptor(object):
    def __init__(self, descriptor):
        self.descriptor = descriptor

    def __getattr__(self, name):
        return getattr(self.descriptor, name)

class AllowBypassableDescriptors(type):
    def __new__(cls, name, bases, members):
        new_members = {}
        for name, value in members.iteritems():
            if isinstance(value, BypassableDescriptor):
                new_members['real_' + name] = BypassDescriptor(value)
        members.update(new_members)
        return type.__new__(cls, name, bases, members)

class Example(object):
    __metaclass__ = AllowBypassableDescriptors

    name = String()
    age  = Integer()

    def __init__(self,name,age):
        self.name = name
        self.age  = age

    def save(self):
        data = dict(name = self.real_name.to_db(), age = self.real_age.to_db())
</code>```

Note that it's not perfect - you'll always have to call real_fieldname.method() instead of fieldname.method() and you'll have to use the metaclass AllowBypassableDescriptors for all your classes which need to access this field. Then again, it's a pretty compatible solution that avoids monkey-patching the object wrapped by the descriptor.

That said, I'm not sure that descriptors are the best solution for what you're trying to do (writing to a database?).

Body:
I created a class String() with __get__(), __set__(), and a method to_db(); however, when I do name = String(), I can't do self.name.to_db() because it's calling to_db() on the value returned by __get__(), not the object "name".

class String(object):

    def __init__(self, value=None):
        if value:
            self.value = str(value)

    def __get__(self, instance, owner):
        return self.value

    def __set__(self, instance, value):
        self.value = str(value)

    def to_db(self):
        return {'type':'string', 'value': self.value}

class Example(object):

    name = String()
    age = Integer()

    def __init__(self,name,age):
        self.name = name
        self.age = age

    def save():
        data = dict(name=self.name.to_db(), age=self.age.to_db())
        db.save(data)

One way to deal with this is to not call self.name.to_db() directly and instead set a flag in instance and create a conditional in __get__() to check for it and call to_db() if it's True, but this seems kludgy. Is there a better way?

Also, I'm new to descriptors -- what are the pros/cons of using instance and/or instance.__dict__ to store state vs storing it in self?

Body:
Here's a solution that allows you to bypass any descriptors defined in the class:

class BypassableDescriptor(object):
    pass

class String(BypassableDescriptor):
    def __init__(self, value=None):
        if value:
            self.value = str(value)

    def __get__(self, instance, owner):
        return self.value

    def __set__(self, instance, value):
        self.value = str(value)

    def to_db(self):
        return {'type': 'string', 'value': self.value}

class Integer(BypassableDescriptor):
    def __init__(self, value=None):
        if value:
            self.value = str(value)

    def __get__(self, instance, owner):
        return self.value

    def __set__(self, instance, value):
        self.value = int(value)

    def to_db(self):
        return {'type': 'integer', 'value': self.value}

class BypassDescriptor(object):
    def __init__(self, descriptor):
        self.descriptor = descriptor

    def __getattr__(self, name):
        return getattr(self.descriptor, name)

class AllowBypassableDescriptors(type):
    def __new__(cls, name, bases, members):
        new_members = {}
        for name, value in members.iteritems():
            if isinstance(value, BypassableDescriptor):
                new_members['real_' + name] = BypassDescriptor(value)
        members.update(new_members)
        return type.__new__(cls, name, bases, members)

class Example(object):
    __metaclass__ = AllowBypassableDescriptors

    name = String()
    age  = Integer()

    def __init__(self,name,age):
        self.name = name
        self.age  = age

    def save(self):
        data = dict(name = self.real_name.to_db(), age = self.real_age.to_db())

Note that it's not perfect - you'll always have to call real_fieldname.method() instead of fieldname.method() and you'll have to use the metaclass AllowBypassableDescriptors for all your classes which need to access this field. Then again, it's a pretty compatible solution that avoids monkey-patching the object wrapped by the descriptor.

That said, I'm not sure that descriptors are the best solution for what you're trying to do (writing to a database?).


问:
Prevent child from assuming full width of dynamic width parent
I have a container, and the width of this container is determined by either max-width or the width of its widest child.

How do I force each child to assume the width of its content while maintaining a single column of elements?

In the example below, how do I make the abc elements, outlined by the limegreen border, only as wide as their content (i.e. abc)?

#container {
  display: inline-block;
box-sizing: border-box;
border: solid orange 2px;
}

.child {
box-sizing: border-box;
border: solid limegreen 2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div></code>```

答:
Made .child width: fit-content;

#container {
  display: inline-block;
  box-sizing: border-box;
  border: solid orange 2px;
  direction: rtl;
}

.child {
  box-sizing: border-box;
  border: solid limegreen 2px;
  width: fit-content;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div></code>```

Body:
I have a container, and the width of this container is determined by either max-width or the width of its widest child.

How do I force each child to assume the width of its content while maintaining a single column of elements?

In the example below, how do I make the abc elements, outlined by the limegreen border, only as wide as their content (i.e. abc)?

#container {
  display: inline-block;
box-sizing: border-box;
border: solid orange 2px;
}

.child {
box-sizing: border-box;
border: solid limegreen 2px;
}

abcdefghi

abc

abc

Body:
Made .child width: fit-content;

#container {
  display: inline-block;
  box-sizing: border-box;
  border: solid orange 2px;
  direction: rtl;
}

.child {
  box-sizing: border-box;
  border: solid limegreen 2px;
  width: fit-content;
}

<div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div>


问:
dynamic favicon in form result
i changed a pen to add a favicon in the form result.
it's works when the page load but when your add dynamicly not.
here is the pen :https://codepen.io/nathel/pen/eYNZYJN
any help would be appreciated  </p>

```<code>    <div class="panel">
        <input type="text" placeholder="Search Bookmarks" ng-model="search" />
    </div>
    <ul class="bookmarks">
        <li ng-repeat="site in bookmarks | filter: search">
          <a href="{{ site.url }}">
            <img ng-src="{{site.favicon}}">{{site.url}}
          </a>
          <span class="label secondary"> {{site.category}}</span>
          <i class="right icon-trash" ng-click="deleteBookmark($index)"></i>
        </li>
    </ul>
</div>
</code>```

```<code>var myApp = angular.module("myApp", ["favicon"]);
myApp.controller("appCtrl", ["$scope", "faviconFilter", function($scope, faviconFilter) {
  $scope.bookmarks = [
    {
      //title: 'CodePen',
      url: 'https://codepen.io',
      category: 'Web Design',
      likes: 3
    }
  ];
  $scope.increment = function ($index) {
      $scope.likes++;
   };
  $scope.addBookmark = function () {
      $scope.bookmarks.push({
          title: $scope.site_name,
          url: $scope.site_url,
          category: $scope.site_category,
          likes: 0
      });
      $scope.site_name = '';
      $scope.site_url = '';
      $scope.site_category = '';
  };
  $scope.bookmarks.forEach( function(bookmarks) {
    bookmarks.favicon = faviconFilter(bookmarks.url);
  });

  $scope.deleteBookmark = function (id) {
      var bookmark = $scope.bookmarks[id];
      $scope.bookmarks.splice(id, 1);
  };
}]);
</code>```

答:
it's works when the page load but when your add dynamicly not.

Add a favicon property to the pushed object in the addBookmark function:

```<code> $scope.addBookmark = function () {
      $scope.bookmarks.push({
          title: $scope.site_name,
          url: $scope.site_url,
          category: $scope.site_category,
          likes: 0,
          //IMPORTANT
          favicon: faviconFilter($scope.site_url)
      });
      $scope.site_name = '';
      $scope.site_url = '';
      $scope.site_category = '';
  };
</code>```

Title: dynamic favicon in form result

Body:
i changed a pen to add a favicon in the form result.
it's works when the page load but when your add dynamicly not.
here is the pen :https://codepen.io/nathel/pen/eYNZYJN
any help would be appreciated

        <input type="text" placeholder="Search Bookmarks" ng-model="search" />

            {{site.url}}

           {{site.category}}

var myApp = angular.module("myApp", ["favicon"]);
myApp.controller("appCtrl", ["$scope", "faviconFilter", function($scope, faviconFilter) {
  $scope.bookmarks = [
    {
      //title: 'CodePen',
      url: 'https://codepen.io',
      category: 'Web Design',
      likes: 3
    }
  ];
  $scope.increment = function ($index) {
      $scope.likes++;
   };
  $scope.addBookmark = function () {
      $scope.bookmarks.push({
          title: $scope.site_name,
          url: $scope.site_url,
          category: $scope.site_category,
          likes: 0
      });
      $scope.site_name = '';
      $scope.site_url = '';
      $scope.site_category = '';
  };
  $scope.bookmarks.forEach( function(bookmarks) {
    bookmarks.favicon = faviconFilter(bookmarks.url);
  });

  $scope.deleteBookmark = function (id) {
      var bookmark = $scope.bookmarks[id];
      $scope.bookmarks.splice(id, 1);
  };
}]);

Body:
it's works when the page load but when your add dynamicly not.

Add a favicon property to the pushed object in the addBookmark function:

 $scope.addBookmark = function () {
      $scope.bookmarks.push({
          title: $scope.site_name,
          url: $scope.site_url,
          category: $scope.site_category,
          likes: 0,
          //IMPORTANT
          favicon: faviconFilter($scope.site_url)
      });
      $scope.site_name = '';
      $scope.site_url = '';
      $scope.site_category = '';
  };


问:
Why does the design look different than what's shown in emulator in android studio?
I'm trying to make a game app on Android Studio and when I try to run my app on the emulator, it look different than what's shown on the design. How can I fix this ?

this is my layout xml code:

```<code>                            <?xml version="1.0" encoding="utf-8"?>
                 <androidx.constraintlayout.widget.ConstraintLayout
               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"
                tools:context=".MainActivity">

                <Button
                    android:id="@+id/button"
            style="@android:style/Widget.DeviceDefault.Light.Button.Small"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:background="@drawable/custom_button"
                    android:text="player1"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    tools:layout_editor_absoluteX="78dp"
                    tools:layout_editor_absoluteY="271dp" />

                <Button
                    android:id="@+id/button2"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:layout_marginBottom="280dp"
                    android:background="@drawable/custom_button"
                    android:text="player2"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    tools:layout_editor_absoluteX="78dp" />

                <Button
                    android:id="@+id/button3"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:background="@drawable/custom_button"
                    android:text="New"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    tools:layout_editor_absoluteX="78dp"
                    tools:layout_editor_absoluteY="334dp" />

                <TextView
                    android:id="@+id/textView"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:padding="11dp"
                    android:text="TextView"
                    android:textColor="#000000"
                    android:textSize="20sp"
                    android:textStyle="bold"
                    tools:layout_editor_absoluteX="187dp"
                    tools:layout_editor_absoluteY="271dp" />

                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:padding="11dp"
                    android:text="TextView"
                    android:textColor="#000000"
                    android:textSize="20sp"
                    android:textStyle="bold"
                    tools:layout_editor_absoluteX="187dp"
                    tools:layout_editor_absoluteY="334dp" />

                <TextView
                    android:id="@+id/textView3"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:padding="15dp"
                    android:text="TextView"
                    android:textColor="#000000"
                    android:textSize="20sp"
                    android:textStyle="bold"
                    tools:layout_editor_absoluteX="187dp"
                    tools:layout_editor_absoluteY="400dp" />
</code>```

thanks in advance

答:
You are missing constraints on your views so in run time the position of them is not the same as the preview.

In addition, because different devices got different screen sizes you cant use fixed sizes on your views because it will just look different on different devices.

You can use ConstraintLayout with:

```<code>app:layout_constraintHeight_percent="0.1"
app:layout_constraintWidth_percent="0.3"
</code>```

And some Guidelines to achieve responsive layout:

Here is an example:

```<code>  <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        style="@android:style/Widget.DeviceDefault.Light.Button.Small"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="player1"
        android:textAllCaps="false"
        android:textSize="20sp"
        app:layout_constraintEnd_toStartOf="@+id/guideline3"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintTop_toTopOf="@+id/guideline2"
        app:layout_constraintWidth_percent="0.3" />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="player2"
        android:textAllCaps="false"
        android:textSize="20sp"
        app:layout_constraintEnd_toStartOf="@+id/textView"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toStartOf="@+id/button"
        app:layout_constraintTop_toBottomOf="@+id/button3" />

    <Button
        android:id="@+id/button3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="New"
        android:textAllCaps="false"
        android:textSize="20sp"
        app:layout_constraintEnd_toStartOf="@+id/textView"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toStartOf="@+id/button"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"
        android:gravity="center"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toTopOf="@+id/guideline2"
        app:layout_constraintWidth_percent="0.3" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"
        android:gravity="center"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="@+id/textView"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"
        android:gravity="center"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="@+id/textView"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.3" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

This will look like this:

Body:
I'm trying to make a game app on Android Studio and when I try to run my app on the emulator, it look different than what's shown on the design. How can I fix this ?

this is my layout xml code:

                            <?xml version="1.0" encoding="utf-8"?>
                 <androidx.constraintlayout.widget.ConstraintLayout
               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"
                tools:context=".MainActivity">

                <Button
                    android:id="@+id/button"
            style="@android:style/Widget.DeviceDefault.Light.Button.Small"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:background="@drawable/custom_button"
                    android:text="player1"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    tools:layout_editor_absoluteX="78dp"
                    tools:layout_editor_absoluteY="271dp" />

                <Button
                    android:id="@+id/button2"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:layout_marginBottom="280dp"
                    android:background="@drawable/custom_button"
                    android:text="player2"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    tools:layout_editor_absoluteX="78dp" />

                <Button
                    android:id="@+id/button3"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:background="@drawable/custom_button"
                    android:text="New"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    tools:layout_editor_absoluteX="78dp"
                    tools:layout_editor_absoluteY="334dp" />

                <TextView
                    android:id="@+id/textView"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:padding="11dp"
                    android:text="TextView"
                    android:textColor="#000000"
                    android:textSize="20sp"
                    android:textStyle="bold"
                    tools:layout_editor_absoluteX="187dp"
                    tools:layout_editor_absoluteY="271dp" />

                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:padding="11dp"
                    android:text="TextView"
                    android:textColor="#000000"
                    android:textSize="20sp"
                    android:textStyle="bold"
                    tools:layout_editor_absoluteX="187dp"
                    tools:layout_editor_absoluteY="334dp" />

                <TextView
                    android:id="@+id/textView3"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:padding="15dp"
                    android:text="TextView"
                    android:textColor="#000000"
                    android:textSize="20sp"
                    android:textStyle="bold"
                    tools:layout_editor_absoluteX="187dp"
                    tools:layout_editor_absoluteY="400dp" />

thanks in advance

Body:
You are missing constraints on your views so in run time the position of them is not the same as the preview.

In addition, because different devices got different screen sizes you cant use fixed sizes on your views because it will just look different on different devices.

You can use ConstraintLayout with:

app:layout_constraintHeight_percent="0.1"
app:layout_constraintWidth_percent="0.3"

And some Guidelines to achieve responsive layout:

Here is an example:

  <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        style="@android:style/Widget.DeviceDefault.Light.Button.Small"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="player1"
        android:textAllCaps="false"
        android:textSize="20sp"
        app:layout_constraintEnd_toStartOf="@+id/guideline3"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintTop_toTopOf="@+id/guideline2"
        app:layout_constraintWidth_percent="0.3" />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="player2"
        android:textAllCaps="false"
        android:textSize="20sp"
        app:layout_constraintEnd_toStartOf="@+id/textView"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toStartOf="@+id/button"
        app:layout_constraintTop_toBottomOf="@+id/button3" />

    <Button
        android:id="@+id/button3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="New"
        android:textAllCaps="false"
        android:textSize="20sp"
        app:layout_constraintEnd_toStartOf="@+id/textView"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toStartOf="@+id/button"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"
        android:gravity="center"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toTopOf="@+id/guideline2"
        app:layout_constraintWidth_percent="0.3" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"
        android:gravity="center"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="@+id/textView"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"
        android:gravity="center"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="@+id/textView"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.3" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5"/>

</androidx.constraintlayout.widget.ConstraintLayout>

This will look like this:


问:
Are PHP workers the same as child processes?
I know it's a noobish question?

Are they the same?
AFAK workers are for Apache and child processes are for PHP-FPM?

Thanks in advance,

答:
They are both child processes forked from a parent process, yes. The difference between mod_php and something like PHP-FPM is that mod_php embeds itself as a shared object inside of the apache httpd child worker processes and thus those processes serve as both a web serer process as well as a php process. PHP-FPM, on the other hand, operates outside of the web server as its own Fork-Process-Manager and only communicates with the web server over FastCGI. These are both considered prefork-mpms, however. Also, you can still use FastCGI in apache httpd. So that the child workers are not a part of the web server workers. So this isn't exclusive to nginx.

Here's a visual of how the two prefork styles might look:

Using PHP-FPM and Nginx

Using mod_php and Apache httpd