问:
Reading JSON from HTTP POST using PHP (Typeform)
I'm having trouble reading JSON data (using PHP) that's coming in from a webhook (Typeform.)

I've tried the solution provided Here but I'm still getting a null array. My code is exactly the same as the example shown in the link (although I'm not accessing particular arrays, I just want to read the data.) All my test deliveries are returning 200, so I'm just a bit stuck.

```<code>$data = json_decode(file_get_contents('php://input'));

var_dump($data);
</code>```

答:
TypeForm runs the page, They'll get the var_dump response...

When you run the page, you haven't posted anything so $data is empty, therefore null

Try saving $data to a file, then when TypeForm POSTS to it, You can see what the POST contents were, in that file

```<code>file_put_contents("webhookData.txt",$data, FILE_APPEND);
</code>```

Body:
I'm having trouble reading JSON data (using PHP) that's coming in from a webhook (Typeform.)

I've tried the solution provided Here but I'm still getting a null array. My code is exactly the same as the example shown in the link (although I'm not accessing particular arrays, I just want to read the data.) All my test deliveries are returning 200, so I'm just a bit stuck.

$data = json_decode(file_get_contents('php://input'));

var_dump($data);

Body:
TypeForm runs the page, They'll get the var_dump response...

When you run the page, you haven't posted anything so $data is empty, therefore null

Try saving $data to a file, then when TypeForm POSTS to it, You can see what the POST contents were, in that file

file_put_contents("webhookData.txt",$data, FILE_APPEND);


来源: stackexchange

问:
How can you design a script that is prepared to take varied possible quantity of arguments as argv?
When you give a function a set of needed arguments or assign argv, the code demands that you give the correct number of args or it goes on to give, "expected number of things to unpack from a tuple is wrong", sorts of errors.

But I use scripts everyday that are very dynamic in how specifically the arguments can be given and in which types orders, etc.

I eventually imagine making scripts with a --help switch that list all the possible argv and options you can add, but for now as I am beginning, lets keep it very, somewhat simple:

I want the following to not raise error and to not EXPECT arguments to be given but to take them when they are there:

#!/usr/bin/env python3

from sys import argv

script, verbose_option, user_input = argv

if "verbose" in verbose_option:
    verbose_option = True
else:
    verbose_option = False

x = value
if verbose_option == True:
    print("var x is set to value...")
else:
    pass

if user_input == True: # if true, the var contains any value, correct?
    print(user_input)
else:
    print("user_input not given but, ... no problem!")
    user_input = input("> ") # or maybe it has a default value that can be changed from argv

if verbose_option == True:
    print("Would I really need this conditional on every line I left a verbose explanation on?")
else:
    pass
```

Somehow it has to know that user_input is not intended as verbose just because verbose isn't there, so... maybe a conditional branch that tests the len() of the tuple of arguments and figures, "well, that must be this and not that based on that number. OR.... is that overly complex and there is a better way?

This is a less important: how messy a verbose option must make the code if there isn't a better way than I imagined in the example code, but that's a bonus question. I want to not error and have default values for things or means of getting the data if not given as argv despite being able to be taken as argv.

答:
Sure, there's some arg parsing packages out there, but, if you want to do it from scratch, you could try something like:

```<code>args = sys.argv
if args:
    #Verbose would be a boolean, true if -v in args, false if not
    verbose = '-v' in args
    #Same thing here, making a boolean based on existence
    help = '--help' in args
    #Here we are assuming the arg after '-x' is some variable we want to store
    x = args[args.index('-x') + 1] if '-x' in args else None
</code>```

For your conditionals, if 'verbose' is a boolean, you only need to use:

```<code>if verbose:
   do_something
</code>```

Or you could do something like:

```<code>print('Hello') if verbose else None
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When you give a function a set of needed arguments or assign argv, the code demands that you give the correct number of args or it goes on to give, "expected number of things to unpack from a tuple is wrong", sorts of errors.

But I use scripts everyday that are very dynamic in how specifically the arguments can be given and in which types orders, etc.

I eventually imagine making scripts with a --help switch that list all the possible argv and options you can add, but for now as I am beginning, lets keep it very, somewhat simple:

I want the following to not raise error and to not EXPECT arguments to be given but to take them when they are there:

#!/usr/bin/env python3

from sys import argv

script, verbose_option, user_input = argv

if "verbose" in verbose_option:
    verbose_option = True
else:
    verbose_option = False

x = value
if verbose_option == True:
    print("var x is set to value...")
else:
    pass

if user_input == True: # if true, the var contains any value, correct?
    print(user_input)
else:
    print("user_input not given but, ... no problem!")
    user_input = input("> ") # or maybe it has a default value that can be changed from argv

if verbose_option == True:
    print("Would I really need this conditional on every line I left a verbose explanation on?")
else:
    pass

Somehow it has to know that user_input is not intended as verbose just because verbose isn't there, so... maybe a conditional branch that tests the len() of the tuple of arguments and figures, "well, that must be this and not that based on that number. OR.... is that overly complex and there is a better way?

This is a less important: how messy a verbose option must make the code if there isn't a better way than I imagined in the example code, but that's a bonus question. I want to not error and have default values for things or means of getting the data if not given as argv despite being able to be taken as argv.

Body:
Sure, there's some arg parsing packages out there, but, if you want to do it from scratch, you could try something like:

args = sys.argv
if args:
    #Verbose would be a boolean, true if -v in args, false if not
    verbose = '-v' in args
    #Same thing here, making a boolean based on existence
    help = '--help' in args
    #Here we are assuming the arg after '-x' is some variable we want to store
    x = args[args.index('-x') + 1] if '-x' in args else None

For your conditionals, if 'verbose' is a boolean, you only need to use:

if verbose:
   do_something

Or you could do something like:

print('Hello') if verbose else None


问:
how to make a heat map when I have 2 conditions, each of which are in triplicate?
I am trying to make a heatmap using ggplot. My actual data is huge. But in this example, I can not get ggplot to 1) plot this and 2) plot condition "A" and "B" in parallel with each other (side-by-side on the same graph)

I have tried using dpyr's gather() to define "x" and "y" for the heat map but get this response:

```<code>          key value
1   condition    A1
2   condition    A1
3   condition    A1
4   condition    A2
5   condition    A2
6   condition    A2
...
...
...
32 expression     5
33 expression     6
34 expression     7
35 expression     8
36 expression     9

library(tidyverse)
</code>```

sample data 1

```<code>Matrix1 <- data.matrix(matrix(1:9, nrow = 3,
dimnames = list(c('AC009234.1' , 'ACSL5' , 'ADAMTS15')), byrow = FALSE))
</code>```

sample data 2

```<code>Matrix2 <-data.matrix(matrix(1:9, nrow = 3,
dimnames = list(c('AC009234.1' , 'ACSL5' , 'ADAMTS15')), byrow = FALSE))
</code>```

head sample datasets

```<code>df_1 <- `colnames<-`(Matrix1, c("A1", "A2", "A3"))
df_2 <- `colnames<-`(Matrix2, c("B1", "B2", "B3"))
</code>```

combine datasets and convery to dataframe

```<code>data <- as.data.frame(cbind(df_1, df_2))
</code>```

Trying x and values

```<code>mydata <- gather(data, key = condition, value = expression)
</code>```

sample plot

```<code>p <- (ggplot(mydata, aes(Condition, expression, fill = expression))
      + geom_tile(aes(fill = expression), colour = "white")
      + scale_fill_gradient(low = "blue", high = "red"))
p
</code>```

there should be 2 keys, to my understanding, condition "A" and "B". And I need the conditions to be on the x axis on the heatmap plot. THANK YOU in advance!

答:
Using your data, I think the last missing step is to extract the letter from the condition field which has 6 values based on the data columns (A1, A2, A3, B1, B2, B3).

```<code>mydata %>%
  separate(condition, c("condition", "version"), -1) %>%
  ggplot(aes(condition, expression, fill = expression)) +
  geom_tile(aes(fill = expression), colour = "white") +
  scale_fill_gradient(low = "blue", high = "red")
</code>```

Body:
I am trying to make a heatmap using ggplot. My actual data is huge. But in this example, I can not get ggplot to 1) plot this and 2) plot condition "A" and "B" in parallel with each other (side-by-side on the same graph)

I have tried using dpyr's gather() to define "x" and "y" for the heat map but get this response:

          key value
1   condition    A1
2   condition    A1
3   condition    A1
4   condition    A2
5   condition    A2
6   condition    A2
...
...
...
32 expression     5
33 expression     6
34 expression     7
35 expression     8
36 expression     9

library(tidyverse)

sample data 1

Matrix1 <- data.matrix(matrix(1:9, nrow = 3,
dimnames = list(c('AC009234.1' , 'ACSL5' , 'ADAMTS15')), byrow = FALSE))

sample data 2

Matrix2 <-data.matrix(matrix(1:9, nrow = 3,
dimnames = list(c('AC009234.1' , 'ACSL5' , 'ADAMTS15')), byrow = FALSE))

head sample datasets

df_1 <- `colnames<-`(Matrix1, c("A1", "A2", "A3"))
df_2 <- `colnames<-`(Matrix2, c("B1", "B2", "B3"))

combine datasets and convery to dataframe

data <- as.data.frame(cbind(df_1, df_2))

Trying x and values

mydata <- gather(data, key = condition, value = expression)

sample plot

p <- (ggplot(mydata, aes(Condition, expression, fill = expression))
      + geom_tile(aes(fill = expression), colour = "white")
      + scale_fill_gradient(low = "blue", high = "red"))
p

there should be 2 keys, to my understanding, condition "A" and "B". And I need the conditions to be on the x axis on the heatmap plot. THANK YOU in advance!

Body:
Using your data, I think the last missing step is to extract the letter from the condition field which has 6 values based on the data columns (A1, A2, A3, B1, B2, B3).

mydata %>%
  separate(condition, c("condition", "version"), -1) %>%
  ggplot(aes(condition, expression, fill = expression)) +
  geom_tile(aes(fill = expression), colour = "white") +
  scale_fill_gradient(low = "blue", high = "red")


问:
How to get a Bitmap from a raw image
I am reading a raw image from the network. This image has been read by an image sensor, not from a file.

These are the things I know about the image:

~ Height & Width

~ Total size (in bytes)

~ 8-bit grayscale

~ 1 byte/pixel

I'm trying to convert this image to a bitmap to display in an imageview.

Here's what I tried:

```<code>BitmapFactory.Options opt = new BitmapFactory.Options();
opt.outHeight = shortHeight; //360
opt.outWidth = shortWidth;//248
imageBitmap = BitmapFactory.decodeByteArray(imageArray, 0, imageSize, opt);
</code>```

decodeByteArray returns null, since it cannot decode my image.

I also tried reading it directly from the input stream, without converting it to a Byte Array first:

```<code>imageBitmap = BitmapFactory.decodeStream(imageInputStream, null, opt);
</code>```

This returns null as well.

I've searched on this & other forums, but cannot find a way to achieve this.

Any ideas?

EDIT: I should add that the first thing I did was to check if the stream actually contains the raw image. I did this using other  applications `(iPhone/Windows MFC) & they are able to read it and display the image correctly. I just need to figure out a way to do this in Java/Android.

答:
Android does not support grayscale bitmaps. So first thing, you have to extend every byte to a 32-bit ARGB int. Alpha is 0xff, and R, G and B bytes are copies of the source image's byte pixel value. Then create the bitmap on top of that array.

Also (see comments), it seems that the device thinks that 0 is white, 1 is black - we have to invert the source bits.

So, let's assume that the source image is in the byte array called Src. Here's the code:

```<code>byte [] src; //Comes from somewhere...
byte [] bits = new byte[src.length*4]; //That's where the RGBA array goes.
int i;
for(i=0;i<src.length;i++)
{
    bits[i*4] =
        bits[i*4+1] =
        bits[i*4+2] = ~src[i]; //Invert the source bits
    bits[i*4+3] = 0xff; // the alpha.
}

//Now put these nice RGBA pixels into a Bitmap object

Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bm.copyPixelsFromBuffer(ByteBuffer.wrap(bits));
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get a Bitmap from a raw image

Body:
I am reading a raw image from the network. This image has been read by an image sensor, not from a file.

These are the things I know about the image:

~ Height & Width

~ Total size (in bytes)

~ 8-bit grayscale

~ 1 byte/pixel

I'm trying to convert this image to a bitmap to display in an imageview.

Here's what I tried:

BitmapFactory.Options opt = new BitmapFactory.Options();
opt.outHeight = shortHeight; //360
opt.outWidth = shortWidth;//248
imageBitmap = BitmapFactory.decodeByteArray(imageArray, 0, imageSize, opt);

decodeByteArray returns null, since it cannot decode my image.

I also tried reading it directly from the input stream, without converting it to a Byte Array first:

imageBitmap = BitmapFactory.decodeStream(imageInputStream, null, opt);

This returns null as well.

I've searched on this & other forums, but cannot find a way to achieve this.

Any ideas?

EDIT: I should add that the first thing I did was to check if the stream actually contains the raw image. I did this using other  applications `(iPhone/Windows MFC) & they are able to read it and display the image correctly. I just need to figure out a way to do this in Java/Android.

Body:
Android does not support grayscale bitmaps. So first thing, you have to extend every byte to a 32-bit ARGB int. Alpha is 0xff, and R, G and B bytes are copies of the source image's byte pixel value. Then create the bitmap on top of that array.

Also (see comments), it seems that the device thinks that 0 is white, 1 is black - we have to invert the source bits.

So, let's assume that the source image is in the byte array called Src. Here's the code:

byte [] src; //Comes from somewhere...
byte [] bits = new byte[src.length*4]; //That's where the RGBA array goes.
int i;
for(i=0;i<src.length;i++)
{
    bits[i*4] =
        bits[i*4+1] =
        bits[i*4+2] = ~src[i]; //Invert the source bits
    bits[i*4+3] = 0xff; // the alpha.
}

//Now put these nice RGBA pixels into a Bitmap object

Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bm.copyPixelsFromBuffer(ByteBuffer.wrap(bits));


问:
grails rollback db operation on some error

I have a service where to save a lot of data to db.
Using MYSQL
I have used like this

```<code>Domain1.withTransaction {text->
            def domain1=//Create my domain object to save
             if(!domain1.save()){
               domain1.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain1')
        }
        Domain2.withTransaction {text->
            def domain2=//Create my domain object to save
             if(!domain2.save()){
               domain2.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain2')
        }
</code>```

My problem if there occurred any problem in saving domain2 i need to roll back domain1 save also.

I need to remove domain1 from db.

答:
Instead of using programatic transaction handling, the Service artifact allows for automatic transaction handling. This typically leads to cleaner and more maintainable code.

You can also use the failOnError:true when you save() to force a RuntimeException to be thrown.

Example below:

```<code>class SomeService {

    static transactional = false

    def serviceMethod() {
        def domain1=//Create my domain object to save
        def domain2=//Create my domain object to save
        domain1.save(failOnError:true)
        domain2.save(failOnError:true)
    }
}
</code>```

UPDATE

I'm revisiting this topic, after I read a response to another topic. Grails Integration Test Does NOT Rollback

Please verify that your dialect is setup as InnoDB as MyISAM tables aren't transactional. This is configured in your Config.groovy

```<code>dataSource {
      dialect= org.hibernate.dialect.MySQLInnoDBDialect
      ...
}
</code>```

Body:
I have a service where to save a lot of data to db.
Using MYSQL
I have used like this

Domain1.withTransaction {text->
            def domain1=//Create my domain object to save
             if(!domain1.save()){
               domain1.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain1')
        }
        Domain2.withTransaction {text->
            def domain2=//Create my domain object to save
             if(!domain2.save()){
               domain2.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain2')
        }

My problem if there occurred any problem in saving domain2 i need to roll back domain1 save also.

I need to remove domain1 from db.

Body:
Instead of using programatic transaction handling, the Service artifact allows for automatic transaction handling. This typically leads to cleaner and more maintainable code.

You can also use the failOnError:true when you save() to force a RuntimeException to be thrown.

Example below:

class SomeService {

    static transactional = false

    def serviceMethod() {
        def domain1=//Create my domain object to save
        def domain2=//Create my domain object to save
        domain1.save(failOnError:true)
        domain2.save(failOnError:true)
    }
}

UPDATE

I'm revisiting this topic, after I read a response to another topic. Grails Integration Test Does NOT Rollback

Please verify that your dialect is setup as InnoDB as MyISAM tables aren't transactional. This is configured in your Config.groovy

dataSource {
      dialect= org.hibernate.dialect.MySQLInnoDBDialect
      ...
}


问:
How to find the furthest point from other given points in Java
I have a given S point (red on the graph) and n other points (black on the graph). I want to find a point P, in a distance of 1 from S, which is the furthest from all the black points (in this case - the sum of distances between P and each point should is the highest).

As P is 1 away from S, we can tell that y = √(1 - x^2).

The analitical way I would personally use would be to:

Calculate the sum of the distances

Q - P = √((Qx - Sx - x)^2 + (Qy - Sy - √(1 - x^2))^2) (repeat of all n points and sum up),

Calculate the derivative of the obtained expression,

Calculate roots of the derivative and find maximums (in the domain),

Calculate values at the ends of the intervals in the domain,

Choose the correct X.

What would be the most efficient way to do this in Java and what libraries could be used? I heard about libraries allowing to do this analyticaly, but it sounds complicated and slow so I was searching for any numerical ideas, but couldn't find any.

答:
EDIT: The algorithm below doesn't work as explained in the comments. I'll keep it here as a reference.

This might a bit naive, but how about:

Find the average of all black points. This can be as easy as
sum(x-coord)/n and sum(y-coord)/n. This "average" point will likely
NOT be on the circle. Let's call this point "A"

Draw a line from this
average point towards S = |AS|

Continue this line along the same
angle until you reach the circle at the other side of S. Let's call
this point O (opposite). You now have line |ASO|.

O can be calculated because you know the radius of the circle is 1, and by definition this point is the furthest point on the red circle away from the average point A, and from here it follows no other point on the circle will be
further away from all black points.

Corner-case: if all black points are point-symmetrical around the origin (for example, one point at -2,-2 and one point at 2,2; then the solution above would have no answer because A (the average point) would equal S (origin 0,0). You can do an additional check for A being equal to S and then throw an exception.


问:
PHP: Ensure that an array contains objects from only a certain class
In some of my setters, I pass an array of objects. I would like to ensure that it only contains instances from a given class. Reading the doc, here is what I do : </p>

```<code>class Foo
{
    public function __construct()
    {

    }
}

class ErrorFoo
{
    public function __construct()
    {

    }
}

$arrayObject = Array();

array_push($arrayObject, new Foo());
array_push($arrayObject, new Foo());
array_push($arrayObject, new ErrorFoo());

$error = false;
foreach ($arrayObject as $obj)
{
    if ( $obj instanceof Foo )
    {
        echo "ok" . '<br>';
    }
    else
    {
        echo "error" . '<br>';
        $error = true;
    }
}
</code>```

<p>Do you know a simpler way than iterate through the array like this? </p>

答:
You can use variadics to enforce types:</p>

```<code>function doSomething(MyObject ...$array)
{
     // $array contains only MyObject instances in it
}

doSomething(new MyObject, new MyObject, new MyObject);
</code>```

Body:
In some of my setters, I pass an array of objects. I would like to ensure that it only contains instances from a given class. Reading the doc, here is what I do :

class Foo
{
    public function __construct()
    {

    }
}

class ErrorFoo
{
    public function __construct()
    {

    }
}

$arrayObject = Array();

array_push($arrayObject, new Foo());
array_push($arrayObject, new Foo());
array_push($arrayObject, new ErrorFoo());

$error = false;
foreach ($arrayObject as $obj)
{
    if ( $obj instanceof Foo )
    {
        echo "ok" . '
';
    }
    else
    {
        echo "error" . '
';
        $error = true;
    }
}

Do you know a simpler way than iterate through the array like this?

Body:
You can use variadics to enforce types:

function doSomething(MyObject ...$array)
{
     // $array contains only MyObject instances in it
}

doSomething(new MyObject, new MyObject, new MyObject);


问:
When to use ViewFlipper?
I have an input wizard type activity with 2 views and a ViewFlipper. Each view takes up the entire screen and sets it's own title. I combined them because it was a packaged deal, you will never access view2 without first going through view1 and 99% of the time if you access view1, you will access view2.

Is this a recommended setup? Is there any cons to using it this way?

答: That's just perfect. In fact, if you are 99% sure that you will have 2 views only, it's recommended to use ViewSwitcher. But using ViewFlipper is OK.

Title: When to use ViewFlipper?


问:
Reinforcement Learning in arbitrarily large action/state spaces
I’m interested to use Deep Reinforcement Learning in order to find an - unique - optimal path back home among (too many) possibilities and a few (required) intermediate stopes (for instance, buy a coffee or refuel).

Furthermore, I want to apply this in cases where the agent doesn’t know a “model” of the environment, and the agent can't try all possible combinations of states and actions at all. I.e. needing to use approximation techniques in Q-value function (and/or policy).

I’ve read of methods for facing cases like this - where rewards, if any, are sparse and binary - like Monte Carlo Tree search (which implies some sort of modeling and planning, according to my understandings) or Hindsight Experience Replay (HER), applying ideas of DDPG.

But there are so many different kind of algorithms to consider, I’m a bit confused what’s best to begin with.
I know it’s a difficult problem, and maybe it’s too naive to ask this, but Is there any clear, direct and we’ll-known way to solve the problem I want to face?

Thanks a lot!

Matias

答:
If the final destination is fixed as in this case(home) you can go for dynamic search as a* will not work due to  changeable enviornment.
And if you want to use deep learning algorithm then go for a3c with experience replay due to the large action/state spaces.It capable of handling complex probelm.


问:
Why does this code to stash babylonjs meshes cause an error?
I am loading a .obj file containing meshes of numerals. I want to stash each mesh against its name so that I can create instances later.

The code works fine if I remove the line that is actually stashing the mesh in 'originals'. However when I leave it in it appears that an exception is thrown and caught inside Babylon with the message "BJS - [12:17:50]: Unable to load assets from /threedee/InputMonoNumerics.obj: Error in onSuccess callback".

```<code>originals = {}
BABYLON.SceneLoader.LoadAssetContainer(assetPath, assetName, scene, (container) ->
  container.addAllToScene()
  for i in[0...scene.meshes.length]
    mesh = scene.meshes[i]
    if (mesh.name.startsWith('numeral'))
      character = mesh.name.charAt('numeral_'.length)
      originals["_#{character}"] = mesh
      console.log("This line is never reached.")
      mesh
)
</code>```

This is coffeescript source - but the transpiled code looks exactly as you would expect

答:
Yes - much thanks to caffeinated.tech - obviously (now you come to mention it) try and catch to see the underlying error!

... which was that the debug statements I had put in to help were throwing an error by calling JSON.stringify on Babylon Mesh objects - which are circular - I think because they have a reference to their parent which of course has a reference back to the Mesh.

It is no longer clear what the original problem was - but that's not a problem.

Body:
I am loading a .obj file containing meshes of numerals. I want to stash each mesh against its name so that I can create instances later.

The code works fine if I remove the line that is actually stashing the mesh in 'originals'. However when I leave it in it appears that an exception is thrown and caught inside Babylon with the message "BJS - [12:17:50]: Unable to load assets from /threedee/InputMonoNumerics.obj: Error in onSuccess callback".

originals = {}
BABYLON.SceneLoader.LoadAssetContainer(assetPath, assetName, scene, (container) ->
  container.addAllToScene()
  for i in[0...scene.meshes.length]
    mesh = scene.meshes[i]
    if (mesh.name.startsWith('numeral'))
      character = mesh.name.charAt('numeral_'.length)
      originals["_#{character}"] = mesh
      console.log("This line is never reached.")
      mesh
)

This is coffeescript source - but the transpiled code looks exactly as you would expect


问:
Generate a list with a head based on object property in array
In Vue, i'm trying to generate a list based on a property in an object.
I have an array coming from the vuex store that looks like this:

```<code>const array = [
 {
   name: "British title string"
   nationality: "British"
 },
 {
   name: "Another title"
   nationality: "American"
 },
 {
   name: "Name"
   nationality: "Dutch"
 },
{
   name: "Another american item"
   nationality: "American"
 },
];

</code>```

What i want to have is the output like this using v-for:

```<code><h2>British</h2>
<ul>
   <li>British title string</li>
</ul>

<h2>American</h2>
<ul>
   <li>Another title</li>
   <li>Another american item</li>
</ul>

<h2>Dutch</h2>
<ul>
   <li>Name</li>
</ul>
</code>```

I have already sorted the array by the nationality property using lodash _.sortBy and it's given me an array sorted by nationality but i want to add a H2 element with the value of nationality.

答:
You can do this, considering that the array is ordered:

```<code>    const array = [
      {
        name: "Another title",
        nationality: "American"
      },
      {
        name: "Another american item",
        nationality: "American"
      },
      {
        name: "British title string",
        nationality: "British"
      },
      {
        name: "Name",
        nationality: "Dutch"
      },

    ];
    const arrayAux = [];
    var j = 0;
    for (var i = 0; i < array.length;) {
      console.log(array[i].name);
      arrayAux.push({
        nationality: array[i].nationality,
        names: [array[i].name]
      });
      i++;
      while ( i < array.length && array[i].nationality === array[i - 1].nationality) {
        arrayAux[j].names.push(array[i].name);
        i++;
      }
      j++;

    }
    console.log(arrayAux);
</code>```

In the html:

```<code><div v-for="item in arrayAux">
  <h2>{{ item.nationality }}</h2>
  <ul>
    <li v-for="n in item.names">
      {{ n.name }}
    </li>
  </ul>
</div>
</code>```

Body:
In Vue, i'm trying to generate a list based on a property in an object.
I have an array coming from the vuex store that looks like this:

const array = [
 {
   name: "British title string"
   nationality: "British"
 },
 {
   name: "Another title"
   nationality: "American"
 },
 {
   name: "Name"
   nationality: "Dutch"
 },
{
   name: "Another american item"
   nationality: "American"
 },
];

What i want to have is the output like this using v-for:

British

British title string

American

Another title

Another american item

Dutch

Name

I have already sorted the array by the nationality property using lodash _.sortBy and it's given me an array sorted by nationality but i want to add a H2 element with the value of nationality.

Body:
You can do this, considering that the array is ordered:

    const array = [
      {
        name: "Another title",
        nationality: "American"
      },
      {
        name: "Another american item",
        nationality: "American"
      },
      {
        name: "British title string",
        nationality: "British"
      },
      {
        name: "Name",
        nationality: "Dutch"
      },

    ];
    const arrayAux = [];
    var j = 0;
    for (var i = 0; i < array.length;) {
      console.log(array[i].name);
      arrayAux.push({
        nationality: array[i].nationality,
        names: [array[i].name]
      });
      i++;
      while ( i < array.length && array[i].nationality === array[i - 1].nationality) {
        arrayAux[j].names.push(array[i].name);
        i++;
      }
      j++;

    }
    console.log(arrayAux);

In the html:

<div v-for="item in arrayAux">
  <h2>{{ item.nationality }}</h2>
  <ul>
    <li v-for="n in item.names">
      {{ n.name }}
    </li>
  </ul>
</div>


问:
Partial autocomplete of the suggestions given by vscode?
Is it possible for the autocomplete feature of vscode to accept only part of the suggestions on Tab?

Basically, we can specify the word separators characters in settings but the autocomplete feature seems to ignore these and replace the complete full word either way.

What I want, for example, is that by specifying the word separator "_" the autocomplete won't replace the full suggestion but only until this character which should effectively be considered the end of the word.

For example, having semi_completions_foo() declared and having written only the initial "se".

"se" + Tab -> "semi_"

"semi_" + Tab -> "semi_completions_"

On the other hand by pressing Enter the full suggestion would be accepted.

"se" + Enter -> "semi_completions_foo"

Is this already implemented?

答:
This is currently not supported by default as of VS Code 1.35 but is tracked by this feature request.

However VS Code does support tabbing through suggestion alternatives after you accept a completion with tab. Just press tab again to switch to the next suggestion from the list.


问:
Storing columns from a text file in an array
I am trying to plot a range of data. My data consists of 49 variables and I want to split this into 7. I have my data stored in a text file consisting of two rows of x and y as following:

I want to split both rows by 7 and create an x,y plot so that it gives me seven lines on my graph. I tried doing this:

```<code>lines = f.readlines()
lines1 = lines1[0:6]
lines2 = lines2[7:14]
lines3 = lines3[15:21]
lines4 = lines4[21:28]
lines5 = lines5[28:35]
lines6 = lines6[35:42]
lines7 = lines7[43:49]
</code>```

I would then put all of the above data in an array and the same process for the y values as well. Finally, I would plot the variables. But this is inefficient and requires alot of time. There must be an easier way, but I cannot think of it. Could someone help?

答:
You can use NumPy's loadtxt to read the data and then use a for loop to plot the x and the y coordinates in batches of 7. Below is a sample answer. Just replace sample.txt by your actual file name (including the directory where the file is located).

```<code>import numpy as np
import matplotlib.pyplot as plt

x, y = np.loadtxt('sample.txt', unpack=True)

for i in range(0, 49, 7):
    plt.plot(x[i:i+7], y[i:i+7])

plt.show()
</code>```

EDIT Adding labels

```<code>for lab, i in enumerate(range(0, 49, 7)):
    plt.plot(x[i:i+7], y[i:i+7], label='group %d' %lab)
plt.legend()
plt.show()
</code>```

Body:
I am trying to plot a range of data. My data consists of 49 variables and I want to split this into 7. I have my data stored in a text file consisting of two rows of x and y as following:

I want to split both rows by 7 and create an x,y plot so that it gives me seven lines on my graph. I tried doing this:

lines = f.readlines()
lines1 = lines1[0:6]
lines2 = lines2[7:14]
lines3 = lines3[15:21]
lines4 = lines4[21:28]
lines5 = lines5[28:35]
lines6 = lines6[35:42]
lines7 = lines7[43:49]

I would then put all of the above data in an array and the same process for the y values as well. Finally, I would plot the variables. But this is inefficient and requires alot of time. There must be an easier way, but I cannot think of it. Could someone help?

Body:
You can use NumPy's loadtxt to read the data and then use a for loop to plot the x and the y coordinates in batches of 7. Below is a sample answer. Just replace sample.txt by your actual file name (including the directory where the file is located).

import numpy as np
import matplotlib.pyplot as plt

x, y = np.loadtxt('sample.txt', unpack=True)

for i in range(0, 49, 7):
    plt.plot(x[i:i+7], y[i:i+7])

plt.show()

EDIT Adding labels

for lab, i in enumerate(range(0, 49, 7)):
    plt.plot(x[i:i+7], y[i:i+7], label='group %d' %lab)
plt.legend()
plt.show()


问:
Arduino IDE Ubuntu ports greyed out (no serial port installed)
I want to run Arduino IDE on a Ubuntu machine that has no serial ports. I'm only going to be using it for OTA but the IDE port option is greyed out. I've tried installing tty0tty but that didn't help. I can set up two minicom serial sessions and chat between them on the tnt0 and tnt1.</p>

答:
Are you running Arduino IDE as root? See this SuperUser query for more details about the potential permissions issue.

Also, verify that your user is in the dialout group. This is a requirement for the ports to be accessible in Arduino.

From the Arduino IDE docs:

On Linux, the Uno and Mega 2560 show up as devices of the form /dev/ttyACM0. These are not supported by the standard version of the RXTX library that the Arduino software uses for serial communication. The Arduino software download for Linux includes a version of the RXTX library patched to also search for these /dev/ttyACM* devices. There's also an Ubuntu package (for 11.04) which includes support for these devices. If, however, you're using the RXTX package from your distribution, you may need to symlink from /dev/ttyACM0 to /dev/ttyUSB0 (for example) so that the serial port appears in the Arduino software.
  Run:

```<code>sudo usermod -a -G tty yourUserName
sudo usermod -a -G dialout yourUserName
</code>```

Body:
Are you running Arduino IDE as root? See this SuperUser query for more details about the potential permissions issue.

Also, verify that your user is in the dialout group. This is a requirement for the ports to be accessible in Arduino.

From the Arduino IDE docs:

On Linux, the Uno and Mega 2560 show up as devices of the form /dev/ttyACM0. These are not supported by the standard version of the RXTX library that the Arduino software uses for serial communication. The Arduino software download for Linux includes a version of the RXTX library patched to also search for these /dev/ttyACM* devices. There's also an Ubuntu package (for 11.04) which includes support for these devices. If, however, you're using the RXTX package from your distribution, you may need to symlink from /dev/ttyACM0 to /dev/ttyUSB0 (for example) so that the serial port appears in the Arduino software.
  Run:

sudo usermod -a -G tty yourUserName
sudo usermod -a -G dialout yourUserName


问:
Acumatica Account Details Not Matching Historical Inventory Valuation Report
We are comparing these two reports as I mentioned and noticed that they do not match with the Inventory Account. Is it possible that they could be calculating a different way for each other? For example, you can say that it always seems that the Historical Inventory Balance is always about $120,000.00 less than the other. We have compared multiple reports multiple times and keep coming up with the same result. We have compared inventory items within the two reports and they seem to match, but something is still off. I have checked how the report is designed in the report designer and cannot come up with any solutions. Does anyone else seem to have this problem, idea, or are we completely missing something?</p>

答:
```<code>Is it possible that they could be calculating a different way for each other?
</code>```

You're not missing anything. Because the results are different it is logical to assume this is almost a fact.

The reports could be pulling data from the same source but applying different filtering. If that's the case, the fastest way to debug this issue is to dump and compare the SQL requests executed by the reports.

You can do so by opening the Trace window from the report page:

Then you launch the report and refresh the Trace window, the full SQL request will be available in the trace details. You can then execute it in Microsoft SQL Management Studio and compare the results. I suggest removing filters one by one until you find the ones which yields different results. You can also dump SQL requests of most Acumatica web page by using the Request Profiler screen (SM205070).

Body:
Is it possible that they could be calculating a different way for each other?

You're not missing anything. Because the results are different it is logical to assume this is almost a fact.

The reports could be pulling data from the same source but applying different filtering. If that's the case, the fastest way to debug this issue is to dump and compare the SQL requests executed by the reports.

You can do so by opening the Trace window from the report page:

Then you launch the report and refresh the Trace window, the full SQL request will be available in the trace details. You can then execute it in Microsoft SQL Management Studio and compare the results. I suggest removing filters one by one until you find the ones which yields different results. You can also dump SQL requests of most Acumatica web page by using the Request Profiler screen (SM205070).


问:
How to make a Custom Login Flow reset password on Force Password Change
I have created a custom signin flow using the starter pack (with only changes for my ad tenant). I create a new user in Ad, with a temporary password that the user is forced to change on first signin.

When the user signs in for the first time, an error is displayed that the username/password is invalid, rather than going to a password reset page.

What changes do I need to make to the Custom signin flow so it presents a password reset page?

答:
MS have provided a sample that describes how to enact the force password reset. See Here.

This only works if you create the users programmatically. One point to note is you should make sure you set passwordProfile.ForceChangePasswordNextLogin to false when creating users.


问:
How to set excel value to datagrid in c#?
xmal.c

```<code>  <StackPanel HorizontalAlignment="Left" Height="337" VerticalAlignment="Top" Width="514" Margin="103,39,0,0">
            <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Source=Lecturers}" >
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                    <DataGridTextColumn Header="Surname" Binding="{Binding Surname}"/>
                    <DataGridTextColumn Header="Phone" Binding="{Binding Phone_Number}" />
                </DataGrid.Columns>
            </DataGrid>
        </StackPanel>
</code>```

Excel row and column:

```<code>Name   Surname   Phone_Number

A        C           123

C        C           124
</code>```

Hi.I got the values in Excel. It comes in the same way. But I couldn't do it when I wanted to set datagrid. How do I set datagrid? The same datagrid row counts with Excel.

```<code> **Lecturers.DataSource=cellvalue**
</code>```

this line use set datagrid. But I don't set datagrid.

答:
First create a class which represent your data

```<code>    public class Lecturer
    {
       public string Name { get; set;}

       public string Surname { get; set;}

       public int Phone_Number { get; set;}
    }
</code>```

Then in your ViewModel, declare an ObservableCollection in which you will be able to store Read objects in it.
An ObservableCollection implements the INotifyPropertyChanged interface that will allow your view to be notified of a data change in the ViewModel.

```<code>[...]

public ObservableCollection<Lecturer> Lecturers { get; set; }

public MyViewModel()
{
  Lecturers = new ObservableCollection<Lecturer>();
}

public void ExtractLecturersFromXlFile(string filePath)
{
 Excel.Application xlApp = new Excel.Application();
 Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filePath);
 Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];

 Excel.Range range = sheet.UsedRange;
 Excel.Range excelrange = (Excel.Range)sheet.get_Range("A1:C100",Type.Missing);

 // Iterate through datas, fill Lecturer's object and add it to the Observable
 // Collection

 // Cleanup
 GC.Collect();
 GC.WaitForPendingFinalizers();

 Marshal.ReleaseComObject(xlWorksheet);

 // Close and release
 xlWorkbook.Close();
 Marshal.ReleaseComObject(xlWorkbook);

 // Quit and release
 xlApp.Quit();
 Marshal.ReleaseComObject(xlApp);

}
</code>```

And in the XAML

```<code>     <StackPanel HorizontalAlignment="Left" Height="337" VerticalAlignment="Top"                   Width="514" Margin="103,39,0,0">
        <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Lecturers}" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Surname" Binding="{Binding Surname}"/>
                <DataGridTextColumn Header="Phone" Binding="{Binding Phone_Number}" />
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>
</code>```

Body:
xmal.c

  <StackPanel HorizontalAlignment="Left" Height="337" VerticalAlignment="Top" Width="514" Margin="103,39,0,0">
            <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Source=Lecturers}" >
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                    <DataGridTextColumn Header="Surname" Binding="{Binding Surname}"/>
                    <DataGridTextColumn Header="Phone" Binding="{Binding Phone_Number}" />
                </DataGrid.Columns>
            </DataGrid>
        </StackPanel>

Excel row and column:

Name   Surname   Phone_Number

A        C           123

C        C           124

Hi.I got the values in Excel. It comes in the same way. But I couldn't do it when I wanted to set datagrid. How do I set datagrid? The same datagrid row counts with Excel.

 **Lecturers.DataSource=cellvalue**

this line use set datagrid. But I don't set datagrid.

Body:
First create a class which represent your data

    public class Lecturer
    {
       public string Name { get; set;}

       public string Surname { get; set;}

       public int Phone_Number { get; set;}
    }

Then in your ViewModel, declare an ObservableCollection in which you will be able to store Read objects in it.
An ObservableCollection implements the INotifyPropertyChanged interface that will allow your view to be notified of a data change in the ViewModel.

[...]

public ObservableCollection<Lecturer> Lecturers { get; set; }

public MyViewModel()
{
  Lecturers = new ObservableCollection<Lecturer>();
}

public void ExtractLecturersFromXlFile(string filePath)
{
 Excel.Application xlApp = new Excel.Application();
 Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filePath);
 Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];

 Excel.Range range = sheet.UsedRange;
 Excel.Range excelrange = (Excel.Range)sheet.get_Range("A1:C100",Type.Missing);

 // Iterate through datas, fill Lecturer's object and add it to the Observable
 // Collection

 // Cleanup
 GC.Collect();
 GC.WaitForPendingFinalizers();

 Marshal.ReleaseComObject(xlWorksheet);

 // Close and release
 xlWorkbook.Close();
 Marshal.ReleaseComObject(xlWorkbook);

 // Quit and release
 xlApp.Quit();
 Marshal.ReleaseComObject(xlApp);

}

And in the XAML

     <StackPanel HorizontalAlignment="Left" Height="337" VerticalAlignment="Top"                   Width="514" Margin="103,39,0,0">
        <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Lecturers}" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Surname" Binding="{Binding Surname}"/>
                <DataGridTextColumn Header="Phone" Binding="{Binding Phone_Number}" />
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>


问:
What's an alternative to getChildFragmentManager() in API 28?
I got trouble with reloading fragments in a viewpager.
Due to searches I must use getChildFragmentManager() in case of nested fragments, but as I can see per documentation the method and the android.app.fragment itself are deprecated in API level 28. So are there any alternatives to solve this issue?</p>

答: Only android.app.Fragment and the related classes are deprecated. You can continue to use androidx.fragment.app.Fragment and its getChildFragmentManager() on all API 14+ devices.


问:
Remember previous utterance
I have a capsule where the user needs to provide Bixby an account name, property, and date range, then Bixby returns the result. What if the user wanted to check a different account with the same property and date range and the user's utterance is something like "What about the foo account?" How could I get Bixby to keep the property and date range from the previous utterance, but change the account name to search for?</p>

答:
In the language training, you can define a continuation of the goal.  That will allow you to filter on 'foo' in your action.

For example:
https://bixbydevelopers.com/dev/docs/dev-guide/developers/training.intro-training

Title: Remember previous utterance


问:
How to get client side data from Kendo Grid to controller
I am trying to get Kendo Grid data which is hydrated from client side to a MVC controller method. My view contains several single fields like name, date of birth etc  and tabular field which I hooked with a Kendo Grid. Since its a new operation I have no data in the grid ( and other fields) and user enters them from client side.

I have no idea how to proceed on this. Ideally I would like to get this data to a list in my viewmodal. So that when the user hits save, I  have all other data and the grid data coming into a controller method.

I am able to successfully bind a list with kendo grid and display it. I have very little experience on JavaScript and Kendo and web programming.
If any of you can point me to the right direction, sample code would be greatly appreciated.

```<code>$("#departmet").kendoGrid({
                dataSource: dataSource,
                height: 250,
                scrollable: true,
                sortable: true,
                filterable: true,
                pageable: {
                    input: true,
                    numeric: false
                },
                columns: [
                    "DepartmentName",
                    "SubDivision"
                ]
            });
</code>```

答:
SO won't let me comment yet so have to add another answer.  You will not need to define the data source within the .NET code when dealing with client only data.  Just use this.

```<code>.DataSource(dataSource => dataSource
    .Ajax()
    .ServerOperation(false)
)
</code>```

If you will have data coming from the backend then you need to use the generic-less constructor and pass in the object else keep what you have.

```<code>Html.Kendo().Grid(Model.MyList)
</code>```

However, if you are preprocessing some client data on the screen that you want to initialize then you will need to do this on ready.  Don't worry about the schema part of the data source.  It already knows this when you used the .NET MVC wrapper because you gave it the schema(type) via the generic or the parameter provided.

```<code>var initialDS= new kendo.data.DataSource({
    data: [
        { ActionName: "Some Name", ActionType: "Some Type" }
    ]
});

$(document).ready(function () {
    $('#docworkflow').data('kendoGrid').setDataSource(initialDS);
});
</code>```

As I mentioned in the other answer.  Use the data source functions for adding additional data to the data source.  No need to setDataSource each time you want to add. Just

```<code>//Assuming you have 2 inputs on the screen the user is entering info into
var nameEntry = $('#action-name').val();
var typeEntry = $('#action-type').val();
$('#docworkflow').data('kendoGrid').dataSource.add({ ActionName: nameEntry , ActionType: typeEntry });
</code>```

Body:
I am trying to get Kendo Grid data which is hydrated from client side to a MVC controller method. My view contains several single fields like name, date of birth etc  and tabular field which I hooked with a Kendo Grid. Since its a new operation I have no data in the grid ( and other fields) and user enters them from client side.

I have no idea how to proceed on this. Ideally I would like to get this data to a list in my viewmodal. So that when the user hits save, I  have all other data and the grid data coming into a controller method.

I am able to successfully bind a list with kendo grid and display it. I have very little experience on JavaScript and Kendo and web programming.
If any of you can point me to the right direction, sample code would be greatly appreciated.

$("#departmet").kendoGrid({
                dataSource: dataSource,
                height: 250,
                scrollable: true,
                sortable: true,
                filterable: true,
                pageable: {
                    input: true,
                    numeric: false
                },
                columns: [
                    "DepartmentName",
                    "SubDivision"
                ]
            });

Body:
SO won't let me comment yet so have to add another answer.  You will not need to define the data source within the .NET code when dealing with client only data.  Just use this.

.DataSource(dataSource => dataSource
    .Ajax()
    .ServerOperation(false)
)

If you will have data coming from the backend then you need to use the generic-less constructor and pass in the object else keep what you have.

Html.Kendo().Grid(Model.MyList)

However, if you are preprocessing some client data on the screen that you want to initialize then you will need to do this on ready.  Don't worry about the schema part of the data source.  It already knows this when you used the .NET MVC wrapper because you gave it the schema(type) via the generic or the parameter provided.

var initialDS= new kendo.data.DataSource({
    data: [
        { ActionName: "Some Name", ActionType: "Some Type" }
    ]
});

$(document).ready(function () {
    $('#docworkflow').data('kendoGrid').setDataSource(initialDS);
});

As I mentioned in the other answer.  Use the data source functions for adding additional data to the data source.  No need to setDataSource each time you want to add. Just

//Assuming you have 2 inputs on the screen the user is entering info into
var nameEntry = $('#action-name').val();
var typeEntry = $('#action-type').val();
$('#docworkflow').data('kendoGrid').dataSource.add({ ActionName: nameEntry , ActionType: typeEntry });


问:
Joining multiple dataframes horizontally
I have the following dataframe

```<code>val count :Dataframe = spark.sql("select 1,$database_name,$table_name count(*) from $table_name ")
</code>```

Output  :

1,stock,T076p,4332

```<code>val dist_count :Dataframe = spark.sql("1,select distinct count(*) from $table_name")`
</code>```

Output  :

4112 or 4332(can be same )

```<code>val truecount : Dataframe = spark.sql("select 1,count(*) from $table_name where flag =true")`
</code>```

Output  :

4330

```<code>   val Falsecount : DataFrame = spark.sql("select 1,count(*) from $table_name where flag =false")
</code>```

Output  :

4332

Question : How do I join above dataframe to get the resultant dataframe which give me Output.

as the below.

stock ,T076p, 4332,4332,4330

Here comma is for column separator

P.S - I have added 1 to every dataframe so I can use join dataframes (so 1 is not mandatory here.)

答:
Question :

  How do I join above dataframe to get the resultant dataframe which
  give me o/p as the below.

stock ,T076p, 4332,4332,4330 -Here comma is for column seperator

just check this example. I have mimicked your requirement with dummy dataframes like below.

```<code>package com.examples

import org.apache.log4j.{Level, Logger}
import org.apache.spark.sql.SparkSession

object MultiDFJoin {
  def main(args: Array[String]) {
    import org.apache.spark.sql.functions._
    Logger.getLogger("org").setLevel(Level.OFF)

    val spark = SparkSession.builder.
      master("local")
      .appName(this.getClass.getName)
      .getOrCreate()
    import spark.implicits._
    val columns = Array("column1", "column2", "column3", "column4")
    val df1 = (Seq(
      (1, "stock", "T076p", 4332))
      ).toDF(columns: _*).as("first")
    df1.show()
    val df2 = Seq((1, 4332)).toDF(columns.slice(0, 2): _*).as("second")
    df2.show()
    val df3 = Seq((1, 4330)).toDF(columns.slice(0, 2): _*).as("third")
    df3.show()
    val df4 = Seq((1, 4332)).toDF(columns.slice(0, 2): _*).as("four")
    df4.show()
    val finalcsv = df1.join(df2, col("first.column1") === col("second.column1")).selectExpr("first.*", "second.column2")
      .join(df3, Seq("column1")).selectExpr("first.*", "third.column2")
      .join(df4, Seq("column1"))
      .selectExpr("first.*", "third.column2", "four.column2")
      .drop("column1").collect.mkString(",") // this column used for just joining hence dropping
    print(finalcsv)
  }
}
</code>```

Result :

```
+-------+-------+-------+-------+
|column1|column2|column3|column4|
+-------+-------+-------+-------+
|      1|  stock|  T076p|   4332|
+-------+-------+-------+-------+

+-------+-------+
|column1|column2|
+-------+-------+
|      1|   4332|
+-------+-------+

+-------+-------+
|column1|column2|
+-------+-------+
|      1|   4330|
+-------+-------+

+-------+-------+
|column1|column2|
+-------+-------+
|      1|   4332|
+-------+-------+

[stock,T076p,4332,4330,4332]
```

Body:
I have the following dataframe

val count :Dataframe = spark.sql("select 1,$database_name,$table_name count(*) from $table_name ")

Output  :

1,stock,T076p,4332

val dist_count :Dataframe = spark.sql("1,select distinct count(*) from $table_name")`

Output  :

4112 or 4332(can be same )

val truecount : Dataframe = spark.sql("select 1,count(*) from $table_name where flag =true")`

Output  :

4330

   val Falsecount : DataFrame = spark.sql("select 1,count(*) from $table_name where flag =false")

Output  :

4332

Question : How do I join above dataframe to get the resultant dataframe which give me Output.

as the below.

stock ,T076p, 4332,4332,4330

Here comma is for column separator

P.S - I have added 1 to every dataframe so I can use join dataframes (so 1 is not mandatory here.)

Body:
Question :

  How do I join above dataframe to get the resultant dataframe which
  give me o/p as the below.

stock ,T076p, 4332,4332,4330 -Here comma is for column seperator

just check this example. I have mimicked your requirement with dummy dataframes like below.

package com.examples

import org.apache.log4j.{Level, Logger}
import org.apache.spark.sql.SparkSession

object MultiDFJoin {
  def main(args: Array[String]) {
    import org.apache.spark.sql.functions._
    Logger.getLogger("org").setLevel(Level.OFF)

    val spark = SparkSession.builder.
      master("local")
      .appName(this.getClass.getName)
      .getOrCreate()
    import spark.implicits._
    val columns = Array("column1", "column2", "column3", "column4")
    val df1 = (Seq(
      (1, "stock", "T076p", 4332))
      ).toDF(columns: _*).as("first")
    df1.show()
    val df2 = Seq((1, 4332)).toDF(columns.slice(0, 2): _*).as("second")
    df2.show()
    val df3 = Seq((1, 4330)).toDF(columns.slice(0, 2): _*).as("third")
    df3.show()
    val df4 = Seq((1, 4332)).toDF(columns.slice(0, 2): _*).as("four")
    df4.show()
    val finalcsv = df1.join(df2, col("first.column1") === col("second.column1")).selectExpr("first.*", "second.column2")
      .join(df3, Seq("column1")).selectExpr("first.*", "third.column2")
      .join(df4, Seq("column1"))
      .selectExpr("first.*", "third.column2", "four.column2")
      .drop("column1").collect.mkString(",") // this column used for just joining hence dropping
    print(finalcsv)
  }
}

Result :

+-------+-------+-------+-------+
|column1|column2|column3|column4|
+-------+-------+-------+-------+
|      1|  stock|  T076p|   4332|
+-------+-------+-------+-------+

+-------+-------+
|column1|column2|
+-------+-------+
|      1|   4332|
+-------+-------+

+-------+-------+
|column1|column2|
+-------+-------+
|      1|   4330|
+-------+-------+

+-------+-------+
|column1|column2|
+-------+-------+
|      1|   4332|
+-------+-------+

[stock,T076p,4332,4330,4332]


问:
How to include ' in dynamic query?
I need to generate a query like this

SELECT max(batch_sk) INTO  ln_batch  FROM test_app.table WHERE categ_cd = 'ABC' ;

This 'ABC' is coming as an input parameter in the procedure(in_code).
I have tried different version of the below mentioned query , but not getting the correct query .

SET lv_query ='SELECT max(batch_sk) INTO  ln_batch  FROM test_app.table
WHERE categ_cd = ''''||in_code||'';

How to include those ' in the query?

答:
Several things wrong here.

Mismatched / un-escaped quotes

Concatenation operates on character strings and there is no implicit
    conversion from TIMESTAMP to VARCHAR. You would need to convert with explicit CAST or TO_CHAR, etc. first

SELECT … INTO is not allowed as dynamic SQL. Perhaps parameterized static SQL with a host variable?

SELECT max(batch_sk) INTO ln_batch FROM test_app.table WHERE categ_cd=:in_code;

otherwise you need a dynamic cursor to supply the value as a literal

```<code>DECLARE lv_cur CURSOR for lv_stmt;
SET lv_query ='SELECT max(batch_sk) FROM test_app.table WHERE categ_cd = '''||in_code||'''';
PREPARE lv_stmt FROM lv_query;
OPEN lv_cur;
FETCH  lv_cur INTO ln_batch;
CLOSE lv_cur;
</code>```

Title: How to include ' in dynamic query?

Body:
Several things wrong here.

Mismatched / un-escaped quotes

Concatenation operates on character strings and there is no implicit
    conversion from TIMESTAMP to VARCHAR. You would need to convert with explicit CAST or TO_CHAR, etc. first

SELECT … INTO is not allowed as dynamic SQL. Perhaps parameterized static SQL with a host variable?

SELECT max(batch_sk) INTO ln_batch FROM test_app.table WHERE categ_cd=:in_code;

otherwise you need a dynamic cursor to supply the value as a literal

DECLARE lv_cur CURSOR for lv_stmt;
SET lv_query ='SELECT max(batch_sk) FROM test_app.table WHERE categ_cd = '''||in_code||'''';
PREPARE lv_stmt FROM lv_query;
OPEN lv_cur;
FETCH  lv_cur INTO ln_batch;
CLOSE lv_cur;


问:
How to add an amount of years to all dates stored as String format stored in a mongo collection
For a college project i have imported a household energy consumption dataset on my MongoDB.

dataset:https://archive.ics.uci.edu/ml/datasets/individual+household+electric+power+consumption

For my purposes, I need to split each sub-metering while still maintaining the date and time. But also since this dataset is from 2006 i'd like to add 8 years to the date so i have a date closer to now.

The approach i have been following is to create a view for each sub metering.

Structure of my document :

```<code>{
    "_id" : ObjectId("5ceec64e871bf4fa89a7f4f3"),
    "Date" : "16/12/2006",
    "Time" : "17:24:00",
    "Global_active_power" : 4.216,
    "Global_reactive_power" : 0.418,
    "Voltage" : 234.84,
    "Global_intensity" : 18.4,
    "Sub_metering_1" : 0.0,
    "Sub_metering_2" : 1.0,
    "Sub_metering_3" : 17.0
}
</code>```

And i use the following to create the views :

```<code>db.createView("sub_metering1","sensor",[{$project: {"_id":"$_id","datetime":{ $dateFromString:{ dateString: {$concat:[ "$Date"," ","$Time"]},format:"%d/%m/%Y %H:%M:%S" }},"metering":"$Sub_metering_1"}}])
</code>```

The views work fine, but i simply can't figure out how to add the 8 years to the original date. I tried to do a find and then a forEach to update, but the documents werent updated, it also took too long to execute.

The dataset starts in 2006 and ends in 2010, i wanted the dates to be pushed 8 years so it started in 2014 and ended in 2018.

Any help is welcome, thanks in advance.

答:
I found a solution!

First i retrieved all the dates with 8 added years. And then iterated over it with a for each loop to add a new field to each document.

Used the $add operation on top of the $dateFromString operation to add the years to my date value, the time had to be added in milliseconds though, which gave me: 8*365*24*60*60000 for 8 years.

mongo docs about $add operation: https://docs.mongodb.com/manual/reference/operator/aggregation/add/

Please find my script below:

```<code> var datetime=db.sensor.aggregate([
        {$project:{ "_id":"$_id", "datetime": { $add:[
            { $dateFromString:{ dateString: {$concat:[ "$Date"," ","$Time"]},format:"%d/%m/%Y %H:%M:%S" }}
            ,8*365*24*60*60000
            ]}}}
    ])

    datetime.forEach(function(doc){
            db.sensor.updateMany({_id:doc._id},{$set: {datetime:doc.datetime}})
        })
</code>```

Body:
For a college project i have imported a household energy consumption dataset on my MongoDB.

dataset:https://archive.ics.uci.edu/ml/datasets/individual+household+electric+power+consumption

For my purposes, I need to split each sub-metering while still maintaining the date and time. But also since this dataset is from 2006 i'd like to add 8 years to the date so i have a date closer to now.

The approach i have been following is to create a view for each sub metering.

Structure of my document :

{
    "_id" : ObjectId("5ceec64e871bf4fa89a7f4f3"),
    "Date" : "16/12/2006",
    "Time" : "17:24:00",
    "Global_active_power" : 4.216,
    "Global_reactive_power" : 0.418,
    "Voltage" : 234.84,
    "Global_intensity" : 18.4,
    "Sub_metering_1" : 0.0,
    "Sub_metering_2" : 1.0,
    "Sub_metering_3" : 17.0
}

And i use the following to create the views :

db.createView("sub_metering1","sensor",[{$project: {"_id":"$_id","datetime":{ $dateFromString:{ dateString: {$concat:[ "$Date"," ","$Time"]},format:"%d/%m/%Y %H:%M:%S" }},"metering":"$Sub_metering_1"}}])

The views work fine, but i simply can't figure out how to add the 8 years to the original date. I tried to do a find and then a forEach to update, but the documents werent updated, it also took too long to execute.

The dataset starts in 2006 and ends in 2010, i wanted the dates to be pushed 8 years so it started in 2014 and ended in 2018.

Any help is welcome, thanks in advance.

Body:
I found a solution!

First i retrieved all the dates with 8 added years. And then iterated over it with a for each loop to add a new field to each document.

Used the $add operation on top of the $dateFromString operation to add the years to my date value, the time had to be added in milliseconds though, which gave me: 8*365*24*60*60000 for 8 years.

mongo docs about $add operation: https://docs.mongodb.com/manual/reference/operator/aggregation/add/

Please find my script below:

 var datetime=db.sensor.aggregate([
        {$project:{ "_id":"$_id", "datetime": { $add:[
            { $dateFromString:{ dateString: {$concat:[ "$Date"," ","$Time"]},format:"%d/%m/%Y %H:%M:%S" }}
            ,8*365*24*60*60000
            ]}}}
    ])

    datetime.forEach(function(doc){
            db.sensor.updateMany({_id:doc._id},{$set: {datetime:doc.datetime}})
        })


问:
Use Fragments in Kotlin
How does one use fragments instead of layouts to give them its on Kotlin file. Using the navigation drawer template in Andriod studio.

```<code>override fun onNavigationItemSelected(item: MenuItem): Boolean {
    // Handle navigation view item clicks here.
    when (item.itemId) {
        R.id.nav_home -> {
            // Handle the camera action
        }
        R.id.nav_gallery -> {

        }
        R.id.nav_slideshow -> {

        }
        R.id.nav_tools -> {

        }
        R.id.nav_share -> {

        }
        R.id.nav_send -> {

        }
    }
    val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
    drawerLayout.closeDrawer(GravityCompat.START)
    return true
}
</code>```

Does this constructor automatically switch the view based on their name ie nav_gallery I am new to koltin and java so please excuse my ignorance.

Eg.
For Example if the Gallery layout how do I show a page that is something other than the content_main.xml that is showing each time I click the navigation bar.

答:
This is the way how you can add a Fragment in kotlin.fun

```<code>fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int){
    supportFragmentManager.inTransaction { add(frameId, fragment) }
}
</code>```

Title: Use Fragments in Kotlin

Body:
How does one use fragments instead of layouts to give them its on Kotlin file. Using the navigation drawer template in Andriod studio.

override fun onNavigationItemSelected(item: MenuItem): Boolean {
    // Handle navigation view item clicks here.
    when (item.itemId) {
        R.id.nav_home -> {
            // Handle the camera action
        }
        R.id.nav_gallery -> {

        }
        R.id.nav_slideshow -> {

        }
        R.id.nav_tools -> {

        }
        R.id.nav_share -> {

        }
        R.id.nav_send -> {

        }
    }
    val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
    drawerLayout.closeDrawer(GravityCompat.START)
    return true
}

Does this constructor automatically switch the view based on their name ie nav_gallery I am new to koltin and java so please excuse my ignorance.

Eg.
For Example if the Gallery layout how do I show a page that is something other than the content_main.xml that is showing each time I click the navigation bar.

Body:
This is the way how you can add a Fragment in kotlin.fun

fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int){
    supportFragmentManager.inTransaction { add(frameId, fragment) }
}


问:
Unable to access web server on Heroku
I am following this tutorial/guide. Locally, it works, using localhost as the domain, and 8080 as the port.

Here's the local configuration:

```<code>"dashboard" : {
    "oauthSecret": `${process.env.oauthSecret}`,
    "callbackURL": `http://localhost:8080/callback`,
    "sessionSecret": "fakesessionsecret",
    "domain": "localhost",
    "port": 8080
  },
</code>```

But now, I would like to use the app on Heroku, and access the web dashboard through https://project-name.herokuapp.comor through a custom domain, which I linked already to the DNS provided, in format dashboard.example.com.

localhost and/or the port does not work for Heroku, so I'm not sure what to change it to for it to work. I have already tried to change the domain to xxx.herokudns.com, port to process.env.PORT, domain to the custom one I set in Heroku - but they all result in the app crashing with status 503 when I visit the URL.

From what I see, the configuration domains and ports are used in these codes:

```<code>const express = require("express");
const app = express();
const passport = require("passport");

passport.use(new Strategy({
    clientID: client.appInfo.id,
    clientSecret: config.dashboard.oauthSecret, //from configuration
    callbackURL: config.dashboard.callbackURL, //from configuration
    scope: ["identify", "guilds"]
  }
...
app.locals.domain = config.dashboard.domain;
...
app.listen(client.config.dashboard.port);
</code>```

So how do I access the web application from Heroku?

答:
When you get a 503, are you checking your Heroku logs? They should provide specific info about what's causing the crash.

The domain should be dashboard.example.com and the port should be process.env.PORT. Better still, use dotenv and a .env file to define your environment variables locally, and use Heroku's "Settings" tab to set the environment variables in production (in this instance, just domain – port is already set for you on each app launch).

Title: Unable to access web server on Heroku

Body:
I am following this tutorial/guide. Locally, it works, using localhost as the domain, and 8080 as the port.

Here's the local configuration:

"dashboard" : {
    "oauthSecret": `${process.env.oauthSecret}`,
    "callbackURL": `http://localhost:8080/callback`,
    "sessionSecret": "fakesessionsecret",
    "domain": "localhost",
    "port": 8080
  },

But now, I would like to use the app on Heroku, and access the web dashboard through https://project-name.herokuapp.comor through a custom domain, which I linked already to the DNS provided, in format dashboard.example.com.

localhost and/or the port does not work for Heroku, so I'm not sure what to change it to for it to work. I have already tried to change the domain to xxx.herokudns.com, port to process.env.PORT, domain to the custom one I set in Heroku - but they all result in the app crashing with status 503 when I visit the URL.

From what I see, the configuration domains and ports are used in these codes:

const express = require("express");
const app = express();
const passport = require("passport");

passport.use(new Strategy({
    clientID: client.appInfo.id,
    clientSecret: config.dashboard.oauthSecret, //from configuration
    callbackURL: config.dashboard.callbackURL, //from configuration
    scope: ["identify", "guilds"]
  }
...
app.locals.domain = config.dashboard.domain;
...
app.listen(client.config.dashboard.port);

So how do I access the web application from Heroku?


问:
Handle multiple transformation on an Image
I'm running a project that will do more or less the same as CameraRaw/Photoshop does. The thing is, how do I handle multiple mods on the image matrix?

let me explain, I read the image Using OpenCV function, and I built a simple Ui in QtCreator, with a few sliders for contrast, exposure etc..
so I got my sliders that, on triggered action, call the function contrast(); on where I pass my Image, and the sliders value (sliders can go from -100 to 100).

Here's the problem: if I set the exposure to +50, then my Image will increase it to +50. From that, if I try to decrease it, to +30, then the exposure will be +50 +30, as I wrote on my pixels image.

So, in order to decrease from +50 to +30, I made a copy of my image, that will be modified , and when I recall the exposure(), then the filter will be applied on the original Image.

So far so good, but, what if I'll apply contrast() and exposure() at the same time? As I done for now, calling one of the twos will exclude the firstly called.

Is there anybody that can help with figure out a way for handling that?

答:
What about applying all the transformations on the original image all the time?

You know the positions of your sliders, and you know when something changes. Then, you simply start from scratch. Take the new image and apply the transformations one by one.

In order to do this, you make the functions return a copy of the original image with the transformations applied. So, the algorithm would be something like:

```<code>originalImage = getImage();
brightnessImage = applyBrightness(originalImage);
contrastedImage = applyContrast(brightnessImage);
</code>```

and so on. Everytime something changes.

I think this is reasonable, since you don't seem to deal with very expensive operations.

Body:
What about applying all the transformations on the original image all the time?

You know the positions of your sliders, and you know when something changes. Then, you simply start from scratch. Take the new image and apply the transformations one by one.

In order to do this, you make the functions return a copy of the original image with the transformations applied. So, the algorithm would be something like:

originalImage = getImage();
brightnessImage = applyBrightness(originalImage);
contrastedImage = applyContrast(brightnessImage);

and so on. Everytime something changes.

I think this is reasonable, since you don't seem to deal with very expensive operations.


问:
Looping an array together with a jquery hover function
I'm trying to... God, this is hard to explain.

I got an array called 'triggers' with these variables:

"#1_trigger","#2_trigger","#3_trigger"

And inside a jQuery each(), I create another variable called 'targets' that copies everything from 'triggers' and replaces all _trigger to _target. I then append the 'triggers' to anchor IDs, and 'targets' to hidden div IDs.

What I want to do, is this: When hovering a _trigger, the _target will show up. I've managed to make it work with only one variable, but not with multiple.

As I said, it's kind of hard to explain what I want to do in text, so here's a demo and my progress so far:
http://jsfiddle.net/WJWe3/6/

I've been stuck with this one for too many hours now, please help!

答:
1st, do not name them with a # since you use that in the actual id. (you can add the # in when you need to seek them with jquery)

After that step the code you need is

```<code>$("#experiment a").hover(function(){
   $( '#' + this.id.replace('_trigger', '_target') ).show();

}, function(){
   $( '#' + this.id.replace('_trigger', '_target') ).hide();
});
</code>```

This should be outside of the each loop since it automatically finds the relevant target.

You were also missing a sign = at the point that you assigned the id to the divs.

demo at http://jsfiddle.net/gaby/WJWe3/14/

Body:
1st, do not name them with a # since you use that in the actual id. (you can add the # in when you need to seek them with jquery)

After that step the code you need is

$("#experiment a").hover(function(){
   $( '#' + this.id.replace('_trigger', '_target') ).show();

}, function(){
   $( '#' + this.id.replace('_trigger', '_target') ).hide();
});

This should be outside of the each loop since it automatically finds the relevant target.

You were also missing a sign = at the point that you assigned the id to the divs.

demo at http://jsfiddle.net/gaby/WJWe3/14/


问:
Get the names of all keys in nested documents of a MongoDB collection
I want to get all the keys from subdocuments in mongodb collection.

I tried $ObjectToArray it work for mongo shell but i want to achieve same using pymongo.

Mongodb collection named: collection

```<code>  {
    "_id": 0,
    "9": {
      "aam1": "a",
      "aam2": "b",
      "aam3": "c",
      "aam4": "ddd",
      "aam5": false,
      "aam6": {
        "aam1": "a",
        "aam2": "b",
        "aam3": "c",
        "aam4": "ddd",
        "aam5": false,
        "aam6": false
      },

    },
    "entity": "ask-me",
    "url": "",
    "createdDate": 21
  }
]
</code>```

Mongo shell working code:

```<code>  {
    "$project": {
      "arrayofkeyvalue": {
        "$objectToArray": "$9.aam6"
      }
    }
  },
  {
    "$project": {
      "keys": "$arrayofkeyvalue.k"
    }
  }
])
</code>```

I want to achieve above mongo shell working code using pymongo in python.

答:
I believe you need to use the aggregation framework from pymongo. Assuming c is your pymongo.Collection

```<code>pipeline = [
    {
    "$project": {
      "arrayofkeyvalue": {
        "$objectToArray": "$9.aam6"
      }
    }
  },
  {
    "$project": {
      "keys": "$arrayofkeyvalue.k"
    }
  }
]
print(list(c.aggregate(pipeline)))    # [{u'_id': 0, u'keys': [u'aam5', u'aam4', u'aam6', u'aam1', u'aam3', u'aam2']}]
</code>```

Body:
I want to get all the keys from subdocuments in mongodb collection.

I tried $ObjectToArray it work for mongo shell but i want to achieve same using pymongo.

Mongodb collection named: collection

  {
    "_id": 0,
    "9": {
      "aam1": "a",
      "aam2": "b",
      "aam3": "c",
      "aam4": "ddd",
      "aam5": false,
      "aam6": {
        "aam1": "a",
        "aam2": "b",
        "aam3": "c",
        "aam4": "ddd",
        "aam5": false,
        "aam6": false
      },

    },
    "entity": "ask-me",
    "url": "",
    "createdDate": 21
  }
]

Mongo shell working code:

  {
    "$project": {
      "arrayofkeyvalue": {
        "$objectToArray": "$9.aam6"
      }
    }
  },
  {
    "$project": {
      "keys": "$arrayofkeyvalue.k"
    }
  }
])

I want to achieve above mongo shell working code using pymongo in python.

Body:
I believe you need to use the aggregation framework from pymongo. Assuming c is your pymongo.Collection

pipeline = [
    {
    "$project": {
      "arrayofkeyvalue": {
        "$objectToArray": "$9.aam6"
      }
    }
  },
  {
    "$project": {
      "keys": "$arrayofkeyvalue.k"
    }
  }
]
print(list(c.aggregate(pipeline)))    # [{u'_id': 0, u'keys': [u'aam5', u'aam4', u'aam6', u'aam1', u'aam3', u'aam2']}]


问:
Replace capital letters in an entire string with lowercase letters and hyphens
I'm trying to replace the capital letters in an entire string with their lower case counter parts while adding hyphen after it (unless its the last letter). So that Sunny&Cloudy would be come sunny-&-cloudy

```<code>var name = 'Sunny&Cloudy';
name.replace(/([A-Z])(.*)/, '\L$1');
</code>```

I've tried this this myself but it only reaches the first capital letter adds a hyphen and stops. Leaving me with -S

答:
If you want to convert Sunny&Cloudy into sunny-&-cloudy, then the following code should work:

```<code>var name = 'Sunny&Cloudy';
name.replace(/[A-Z][a-z]*/g, str => '-' + str.toLowerCase() + '-')
  // Convert words to lower case and add hyphens around it (for stuff like "&")
  .replace('--', '-') // remove double hyphens
  .replace(/(^-)|(-$)/g, ''); // remove hyphens at the beginning and the end
</code>```

Basically you just use a function as the second parameter of .replace. (Reference)

It's not only replacing capitalized letter with their lowercase counterpart though, so you might want to revise your question description.

Body:
I'm trying to replace the capital letters in an entire string with their lower case counter parts while adding hyphen after it (unless its the last letter). So that Sunny&Cloudy would be come sunny-&-cloudy

var name = 'Sunny&Cloudy';
name.replace(/([A-Z])(.*)/, '\L$1');

I've tried this this myself but it only reaches the first capital letter adds a hyphen and stops. Leaving me with -S

Body:
If you want to convert Sunny&Cloudy into sunny-&-cloudy, then the following code should work:

var name = 'Sunny&Cloudy';
name.replace(/[A-Z][a-z]*/g, str => '-' + str.toLowerCase() + '-')
  // Convert words to lower case and add hyphens around it (for stuff like "&")
  .replace('--', '-') // remove double hyphens
  .replace(/(^-)|(-$)/g, ''); // remove hyphens at the beginning and the end

Basically you just use a function as the second parameter of .replace. (Reference)

It's not only replacing capitalized letter with their lowercase counterpart though, so you might want to revise your question description.


问:
Why do I get different result?
i'm a newbie of SPARQL and probably I'm doing a logical mistake, but this is the problem i have:

i want to retrieve "Freddie_Mercury" from a list of people, each one having rdf:Type like dbo:MusicalArtist too.

The first query I have done is this:

```<code>select ?x where{?x a dbo:MusicalArtist; dbo:birthName ?realName. FILTER regex(?realName,"Farrokh Bulsara")}
</code>```

This works great. I get a link to Freddie Mercury page and I can go.
But if I run the following python code, Freddie Mercury do not enter in list. Why?

```<code> from SPARQLWrapper import SPARQLWrapper, JSON
#select all people with type MusicalArtist#
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
sparql.setQuery(
"""select ?singer where{?singer a dbo:MusicalArtist} """)
sparql.setReturnFormat(JSON)
resultsSingers = sparql.query().convert()
#creating list of singers (only complete name)#
singerNames = []
iFoundFreddie = False
#for result in "bindings"#
for result in resultsSingers["results"]["bindings"]:
    try:
        #get string in "singer" in "value", after "/resource/"#
        singerN = result["singer"]["value"].split("/resource/")[1]
        #add string to list#
        singerNames.append(singerN)
        if "_Mercury" in singerN:
            iFoundFreddie = True
    except:
        print("",end="")

print(iFoundFreddie)
</code>```

答:
DBpedia has a limit of 10,000 on the resultset size you can get by a single query, and there are 71,014 musical artists in DBpedia. Use limit and offset to simulate pagination and get all results by multiple queries (in fact, 8 queries to get all musical artists here).

You can find how many entities there are for a particular type like this:

```<code>select (count(?x) as ?cnt) {?x a dbo:MusicalArtist }
</code>```

Title: Why do I get different result?

Body:
i'm a newbie of SPARQL and probably I'm doing a logical mistake, but this is the problem i have:

i want to retrieve "Freddie_Mercury" from a list of people, each one having rdf:Type like dbo:MusicalArtist too.

The first query I have done is this:

select ?x where{?x a dbo:MusicalArtist; dbo:birthName ?realName. FILTER regex(?realName,"Farrokh Bulsara")}

This works great. I get a link to Freddie Mercury page and I can go.
But if I run the following python code, Freddie Mercury do not enter in list. Why?

 from SPARQLWrapper import SPARQLWrapper, JSON
#select all people with type MusicalArtist#
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
sparql.setQuery(
"""select ?singer where{?singer a dbo:MusicalArtist} """)
sparql.setReturnFormat(JSON)
resultsSingers = sparql.query().convert()
#creating list of singers (only complete name)#
singerNames = []
iFoundFreddie = False
#for result in "bindings"#
for result in resultsSingers["results"]["bindings"]:
    try:
        #get string in "singer" in "value", after "/resource/"#
        singerN = result["singer"]["value"].split("/resource/")[1]
        #add string to list#
        singerNames.append(singerN)
        if "_Mercury" in singerN:
            iFoundFreddie = True
    except:
        print("",end="")

print(iFoundFreddie)

Body:
DBpedia has a limit of 10,000 on the resultset size you can get by a single query, and there are 71,014 musical artists in DBpedia. Use limit and offset to simulate pagination and get all results by multiple queries (in fact, 8 queries to get all musical artists here).

You can find how many entities there are for a particular type like this:

select (count(?x) as ?cnt) {?x a dbo:MusicalArtist }


问:
Why does android emulator running Oreo crash when FireFox is running on Windows 10?
I created android emulator with the following settings:

```<code>Name: Pixel_API_27_Oreo

CPU/ABI: Google Play Intel Atom (x86)

Path: C:\Users\username\AppData\Local\Android\sdk\.android\avd\Pixel_API_27_Oreo.avd

Target: google_apis_playstore [Google Play] (API level 27)

Skin: pixel_silver

SD Card: 512M

fastboot.chosenSnapshotFile:

runtime.network.speed: full

hw.accelerometer: yes

hw.device.name: pixel

hw.lcd.width: 1080

hw.initialOrientation: Portrait

image.androidVersion.api: 27

tag.id: google_apis_playstore

hw.mainKeys: no

hw.camera.front: emulated

avd.ini.displayname: Pixel API 27 Oreo

hw.gpu.mode: auto

hw.ramSize: 1536

PlayStore.enabled: true

fastboot.forceColdBoot: no

hw.cpu.ncore: 4

hw.keyboard: yes

hw.sensors.proximity: yes

hw.dPad: no

hw.lcd.height: 1920

vm.heapSize: 228

skin.dynamic: yes

hw.device.manufacturer: Google

hw.gps: yes

hw.audioInput: yes

image.sysdir.1: system-images\android-27\google_apis_playstore\x86\

showDeviceFrame: yes

hw.camera.back: virtualscene

AvdId: Pixel_API_27_Oreo

hw.lcd.density: 420

hw.arc: false

hw.device.hash2: MD5:55acbc835978f326788ed66a5cd4c9a7

fastboot.forceChosenSnapshotBoot: no

fastboot.forceFastBoot: yes

hw.trackBall: no

hw.battery: yes

hw.sdCard: yes

tag.display: Google Play

runtime.network.latency: none

disk.dataPartition.size: 2G

hw.sensors.orientation: yes

avd.ini.encoding: UTF-8

hw.gpu.enabled: yes
</code>```

If the emulator is started while FireFox v 67.0 is running then it crashes immediately.

What I've Tried
I can start an emulator image running x86 Nougat or Marshmallow with no problem.

Here are the errors from android studio:

```<code>5:42 PM Emulator: Fatal: createDIB: CreateDIBSection failed (300x300, format: 6) ((null):0, (null))

5:42 PM Emulator: Process finished with exit code -1073740286 (0xC0000602)

5:43 PM Emulator: terminate called without an active exception

5:44 PM Emulator: Warning: QObject::~QObject: Timers cannot be stopped from another thread ((null):0, (null))

5:44 PM Emulator: Process finished with exit code 3
</code>```

If FireFox isn't running then when the emulator starts it gives this error (keep in mind this is from a fresh image, never been started before).

If I do anything on the phone then I get a black screen on the emulator.

If I start the image again then the emulator screen is black/blank and I see the following message in Android Studio

But there is no message on the emulator.

答:
I went back to the AVD (Android Virtual Device manager) and selected the image and dropped the list and wiped the user data (even though this one has never been started before.

Then I restarted the image again after about 1 minute android started and I saw the following:

Body:
I created android emulator with the following settings:

Name: Pixel_API_27_Oreo

CPU/ABI: Google Play Intel Atom (x86)

Path: C:\Users\username\AppData\Local\Android\sdk\.android\avd\Pixel_API_27_Oreo.avd

Target: google_apis_playstore [Google Play] (API level 27)

Skin: pixel_silver

SD Card: 512M

fastboot.chosenSnapshotFile:

runtime.network.speed: full

hw.accelerometer: yes

hw.device.name: pixel

hw.lcd.width: 1080

hw.initialOrientation: Portrait

image.androidVersion.api: 27

tag.id: google_apis_playstore

hw.mainKeys: no

hw.camera.front: emulated

avd.ini.displayname: Pixel API 27 Oreo

hw.gpu.mode: auto

hw.ramSize: 1536

PlayStore.enabled: true

fastboot.forceColdBoot: no

hw.cpu.ncore: 4

hw.keyboard: yes

hw.sensors.proximity: yes

hw.dPad: no

hw.lcd.height: 1920

vm.heapSize: 228

skin.dynamic: yes

hw.device.manufacturer: Google

hw.gps: yes

hw.audioInput: yes

image.sysdir.1: system-images\android-27\google_apis_playstore\x86\

showDeviceFrame: yes

hw.camera.back: virtualscene

AvdId: Pixel_API_27_Oreo

hw.lcd.density: 420

hw.arc: false

hw.device.hash2: MD5:55acbc835978f326788ed66a5cd4c9a7

fastboot.forceChosenSnapshotBoot: no

fastboot.forceFastBoot: yes

hw.trackBall: no

hw.battery: yes

hw.sdCard: yes

tag.display: Google Play

runtime.network.latency: none

disk.dataPartition.size: 2G

hw.sensors.orientation: yes

avd.ini.encoding: UTF-8

hw.gpu.enabled: yes

If the emulator is started while FireFox v 67.0 is running then it crashes immediately.

What I've Tried
I can start an emulator image running x86 Nougat or Marshmallow with no problem.

Here are the errors from android studio:

5:42 PM Emulator: Fatal: createDIB: CreateDIBSection failed (300x300, format: 6) ((null):0, (null))

5:42 PM Emulator: Process finished with exit code -1073740286 (0xC0000602)

5:43 PM Emulator: terminate called without an active exception

5:44 PM Emulator: Warning: QObject::~QObject: Timers cannot be stopped from another thread ((null):0, (null))

5:44 PM Emulator: Process finished with exit code 3

If FireFox isn't running then when the emulator starts it gives this error (keep in mind this is from a fresh image, never been started before).

If I do anything on the phone then I get a black screen on the emulator.

If I start the image again then the emulator screen is black/blank and I see the following message in Android Studio

But there is no message on the emulator.


问:
Need a logic on how to implement this problem
I want to implement this logic in PHP CodeIgniter.

I have a check-in time options that are in intervals of 30 minutes from 00:00 to 23:30. e.g the time can be 00:00 ,00:30, 01:00, 01:30, 02:00, 02:30 ,03:00, 03:30 ..... 23:30.

Because of 2-hour booking window, the system will display a limited number of check-in time options and as such, a customer cannot see all our check-in time options. It will work based on the current time of the system. The customer will see check-in time options from the nearest check-in time option from his current time till the next 2 hours. For example, the current time is 00:50. The nearest check-in time option is 01:00 and 2 hours from 01:00 is 03:00. Hence, the customer will only see the following check-in time options which will be 5 options at any time of the day; 01:00, 01:30 ,02:00,02:30,03:00 etc

I can't seem to be able to translate this to PHP.

答:
So you need to essentially parse the current time in to hours and minutes, then using a DateInterval go to the nearest (next/forward) half-hour or hour. This becomes option 1. From there it is a matter of generating the next 4 options to equal 2 hours from the first available option. We do this with a for loop and adding on 30m each iteration until all the options are complete.

```<code><?php

function check_in_options($time) {

    $dt = new DateTime($time);

    $minutes = $dt->format('i');
    $hour = $dt->format('H');

    $interval = $minutes >= 30 ? 60 - $minutes : 30 - $minutes;
    $dt->add(new DateInterval("PT{$interval}M"));

    $options[] = $dt->format('H:i');

    for ($x = 1; $x <= 4; $x++) {
        $options[] = $dt->add(new DateInterval("PT30M"))->format('H:i');
    }

    return $options;

}

$time = '00:50';

$options = check_in_options($time);

echo '```';
print_r($options);
```

<p>Result:</p>

```Array
(
    [0] => 01:00
    [1] => 01:30
    [2] => 02:00
    [3] => 02:30
    [4] => 03:00
)
```

Body:
So you need to essentially parse the current time in to hours and minutes, then using a DateInterval go to the nearest (next/forward) half-hour or hour. This becomes option 1. From there it is a matter of generating the next 4 options to equal 2 hours from the first available option. We do this with a for loop and adding on 30m each iteration until all the options are complete.

<?php

function check_in_options($time) {

    $dt = new DateTime($time);

    $minutes = $dt->format('i');
    $hour = $dt->format('H');

    $interval = $minutes >= 30 ? 60 - $minutes : 30 - $minutes;
    $dt->add(new DateInterval("PT{$interval}M"));

    $options[] = $dt->format('H:i');

    for ($x = 1; $x <= 4; $x++) {
        $options[] = $dt->add(new DateInterval("PT30M"))->format('H:i');
    }

    return $options;

}

$time = '00:50';

$options = check_in_options($time);

echo '<pre>';
print_r($options);

Result:

Array
(
    [0] => 01:00
    [1] => 01:30
    [2] => 02:00
    [3] => 02:30
    [4] => 03:00
)


问:
How to Mysqli Escape string without access to the db connection?
I am trying to modify some code and I wanted to use mysqli instead of mysql if possible.   Here is what it looks like today.

```<code>$query = sprintf("select * from table where column = '%s';",mysql_escape_string($value));
$result = do_query_mysqli($query, __FILE__, __LINE__);
</code>```

the function do_query_mysqli is in another file and I don't want to modify that file if possible.   That function also includes $link to connect to the DB.

I do not have access to $link in the file I am modifying.

What is the best alternative to the code below if I want to achieve a similar result but I don't have access to $link?

```<code>$value = mysqli_real_escape_string($link, $value);
</code>```

Thanks!

Edit --
None of the answers and comments address my issue which is I am trying to reduce the risk of sql injection without having to change the function that executes the queries.  But I will look into the solutions suggested anyway.  Thanks.

答:
With mysqli to avoid SQL injection I've found it's better to use bind_param and bind_result.

```<code>$select1 = $con->prepare("SELECT jobnumber ,starttime ,endtime, title from JobSheet WHERE starttime BETWEEN ? AND ?;");
$select1->bind_param('ss', $mondayMidnight, $sundayMidnight);
$select1->bind_result($jobnumber, $starttime, $endtime, $title);
$select1->execute();
</code>```

It's also good practice to ONLY select the columns you're interested in to satisfy the query you're using. SELECT * FROM ... is a minefield and a program error waiting to happen (when someone alters the table).

bind_param doesn't allow for SQL injection as the SQL is already prepared.

Body:
I am trying to modify some code and I wanted to use mysqli instead of mysql if possible.   Here is what it looks like today.

$query = sprintf("select * from table where column = '%s';",mysql_escape_string($value));
$result = do_query_mysqli($query, __FILE__, __LINE__);

the function do_query_mysqli is in another file and I don't want to modify that file if possible.   That function also includes $link to connect to the DB.

I do not have access to $link in the file I am modifying.

What is the best alternative to the code below if I want to achieve a similar result but I don't have access to $link?

$value = mysqli_real_escape_string($link, $value);

Thanks!

Edit --
None of the answers and comments address my issue which is I am trying to reduce the risk of sql injection without having to change the function that executes the queries.  But I will look into the solutions suggested anyway.  Thanks.

Body:
With mysqli to avoid SQL injection I've found it's better to use bind_param and bind_result.

$select1 = $con->prepare("SELECT jobnumber ,starttime ,endtime, title from JobSheet WHERE starttime BETWEEN ? AND ?;");
$select1->bind_param('ss', $mondayMidnight, $sundayMidnight);
$select1->bind_result($jobnumber, $starttime, $endtime, $title);
$select1->execute();

It's also good practice to ONLY select the columns you're interested in to satisfy the query you're using. SELECT * FROM ... is a minefield and a program error waiting to happen (when someone alters the table).

bind_param doesn't allow for SQL injection as the SQL is already prepared.