问:
How can I the image start from a new line when using dita-ot-3.0 pdf plug outputting PDF?
hope someone to help me, thanks!

When I use dita-ot-3.0 to output pdf, I find in many places, the images are displayed in the same line with text.

I try two plugins:

- default pdf2 plugin

- a customization pdf plugin using PDF Plugin Generator at https://github.com/jelovirt/dita-generator (I didnot find any place to set image attribute)

So here is my question, I write xml like this:

source xml file
When I output pdf, I get this:
image is shown in the same line with text

there are many other images showing like that. How can I make the image show starting from a new line? Am I misusing the  element？ Is the difference between inline element or block?

答: You should be able to do this by setting the attribute placement="break" to the <image> element. This is explained in the spec.


来源: stackexchange

问:
font face not working in local not in server
I used font-face, and it is not working. I used the following code in internal CSS:

```<code>@font-face {
font-family: acme;
src: url(https://s3.ap-south-1.amazonaws.com/mailer-reach-on-time/ACMESecretAgentBB_BoldItal.otf);
}
</code>```

My html code is below:

```<code><p style="text-align:center; font-family: acme; font-size:28px; color: #4D4B4B;">TYPICAL MEETING ROOM</p>
</code>```

When I use this in local it works fine, but when upload the fonts to the server and when I get the fonts from the server it won't work. Please anyone give a solution for this.

答:
Retrieving the font from that Amazon S3 URL results in the CORS error below. Note that the null is just there because I'm testing from a stack snippet. In your case, it will most likely be replaced with your domain.

Access to Font at
  'https://s3.ap-south-1.amazonaws.com/mailer-reach-on-time/ACMESecretAgentBB_BoldItal.otf'
  from origin 'null' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'null' is therefore not allowed access.

To be able to retrieve your font, you need to configure cross-origin resource sharing on your S3 bucket, as described here in the Amazon S3 documentation.

The following configuration allows GET requests to all origins (which might be too liberal, depending on the contents of your bucket):

```<code><CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
 </CORSRule>
</CORSConfiguration>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I used font-face, and it is not working. I used the following code in internal CSS:

@font-face {
font-family: acme;
src: url(https://s3.ap-south-1.amazonaws.com/mailer-reach-on-time/ACMESecretAgentBB_BoldItal.otf);
}

My html code is below:

TYPICAL MEETING ROOM

When I use this in local it works fine, but when upload the fonts to the server and when I get the fonts from the server it won't work. Please anyone give a solution for this.

Body:
Retrieving the font from that Amazon S3 URL results in the CORS error below. Note that the null is just there because I'm testing from a stack snippet. In your case, it will most likely be replaced with your domain.

Access to Font at
  'https://s3.ap-south-1.amazonaws.com/mailer-reach-on-time/ACMESecretAgentBB_BoldItal.otf'
  from origin 'null' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'null' is therefore not allowed access.

To be able to retrieve your font, you need to configure cross-origin resource sharing on your S3 bucket, as described here in the Amazon S3 documentation.

The following configuration allows GET requests to all origins (which might be too liberal, depending on the contents of your bucket):

<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
 </CORSRule>
</CORSConfiguration>


问:
Given a number, find the next higher number which has the exact same set of digits as the original number
I just bombed an interview and made pretty much zero progress on my interview question.

Given a number, find the next higher number which has the exact same
set of digits as the original number. For example: given 38276 return
38627

I wanted to begin by finding the index of the first digit (from the right) that was less than the ones digit. Then I would rotate the last digits in the subset such that it was the next biggest number comprised of the same digits, but got stuck.

The interviewer also suggested trying to swap digits one at a time, but I couldn't figure out the algorithm and just stared at a screen for like 20-30 minutes. Needless to say, I think I'm going to have to continue the job hunt.

答:
Very simple implementation using Javascript, next highest number with same digits

```<code>/*
Algorithm applied
I) Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is “534976”, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is “Not Possible”.

II) Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For “534976″, the right side of 4 contains “976”. The smallest digit greater than 4 is 6.

III) Swap the above found two digits, we get 536974 in above example.

IV) Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get “536479” which is the next greater number for input 534976.

*/

function findNext(arr)
{
  let i;
  //breaking down a digit into arrays of string and then converting back that array to number array
  let arr1=arr.toString().split('').map(Number) ;
  //started to loop from the end of array
  for(i=arr1.length;i>0;i--)
  {
    //looking for if the current number is greater than the number next to it
    if(arr1[i]>arr1[i-1])
    {// if yes then we break the loop it so that we can swap and sort
      break;}
  }

  if(i==0)
  {console.log("Not possible");}

   else
  {
   //saving that big number and smaller number to the left of it
   let smlNum =arr1[i-1];
    let bigNum =i;
   /*now looping again and checking if we have any other greater number, if we have one AFTER big number and smaller number to the right.
     A greater number that is of course greater than that smaller number but smaller than the first number we found.
     Why are doing this? Because that is an algorithm to find next higher number with same digits.
   */
    for(let j=i+1;j<arr1.length;j++)
      {//What if there are no digits afters those found numbers then of course loop will not be initiated otherwise...
        if(arr1[j]> smlNum && arr1[j]<arr1[i])
        {// we assign that other found number here and replace it with the one we found before
          bigNum=j;

        }
      } //now we are doing swapping of places the small num and big number , 3rd part of alogorithm
    arr1[i-1]=arr1[bigNum];
          arr1[bigNum]=smlNum;
    //returning array
    //too many functions applied sounds complicated right but no, here is the  trick
    //return arr first then apply each function one by one to see output and then further another func to that output to match your needs
    // so here after swapping , 4th part of alogorithm is to sort the array right after the 1st small num we found
    // to do that first we simple take part of array, we splice it and then we apply sort fucntion, then check output (to check outputs, pls use chrome dev console)
    //and then  simply the rest concat and join to main one digit again.
     return arr1.concat((arr1.splice(i,arr1.length)).sort(function(a, b){return a-b})).join('');

    // Sorry to make it too long but its fun explaining things in much easier ways as much as possible!!
  }

}

findNext(1234);
</code>```

Since there are lot of comments, so it's better you can copy it to your text editor.
Thanks!

ContentLicense: CC BY-SA 4.0

Body:
Very simple implementation using Javascript, next highest number with same digits

/*
Algorithm applied
I) Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is “534976”, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is “Not Possible”.

II) Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For “534976″, the right side of 4 contains “976”. The smallest digit greater than 4 is 6.

III) Swap the above found two digits, we get 536974 in above example.

IV) Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get “536479” which is the next greater number for input 534976.

*/

function findNext(arr)
{
  let i;
  //breaking down a digit into arrays of string and then converting back that array to number array
  let arr1=arr.toString().split('').map(Number) ;
  //started to loop from the end of array
  for(i=arr1.length;i>0;i--)
  {
    //looking for if the current number is greater than the number next to it
    if(arr1[i]>arr1[i-1])
    {// if yes then we break the loop it so that we can swap and sort
      break;}
  }

  if(i==0)
  {console.log("Not possible");}

   else
  {
   //saving that big number and smaller number to the left of it
   let smlNum =arr1[i-1];
    let bigNum =i;
   /*now looping again and checking if we have any other greater number, if we have one AFTER big number and smaller number to the right.
     A greater number that is of course greater than that smaller number but smaller than the first number we found.
     Why are doing this? Because that is an algorithm to find next higher number with same digits.
   */
    for(let j=i+1;j<arr1.length;j++)
      {//What if there are no digits afters those found numbers then of course loop will not be initiated otherwise...
        if(arr1[j]> smlNum && arr1[j]<arr1[i])
        {// we assign that other found number here and replace it with the one we found before
          bigNum=j;

        }
      } //now we are doing swapping of places the small num and big number , 3rd part of alogorithm
    arr1[i-1]=arr1[bigNum];
          arr1[bigNum]=smlNum;
    //returning array
    //too many functions applied sounds complicated right but no, here is the  trick
    //return arr first then apply each function one by one to see output and then further another func to that output to match your needs
    // so here after swapping , 4th part of alogorithm is to sort the array right after the 1st small num we found
    // to do that first we simple take part of array, we splice it and then we apply sort fucntion, then check output (to check outputs, pls use chrome dev console)
    //and then  simply the rest concat and join to main one digit again.
     return arr1.concat((arr1.splice(i,arr1.length)).sort(function(a, b){return a-b})).join('');

    // Sorry to make it too long but its fun explaining things in much easier ways as much as possible!!
  }

}

findNext(1234);

Since there are lot of comments, so it's better you can copy it to your text editor.
Thanks!


问:
react-native-fetch-blob IOS API openDocument not working
I require showing applications in the IOS device capable of opening various file formats.I tried using react native share to achieve the same but options of copying file to other apps did not appear.So i tried using react native fetch blob. RNFetchBlob.fs.exists(fs.dirs.DocumentDir+'/sample.pdf') return true , meaning the file does exist but when i use RNFetchBlob.ios.openDocument(fs.dirs.DocumentDir+'/sample.pdf') nothing happens, not even an error but rather the success callback is called. Appreciate any help.

答: I was able to resolve the issue , but i don't know why it actually happened in the first place. I used an Alert.alert to find if the file existed or not and then called the RNFetchBlob.ios.openDocument function, upon removing the alert just before the function call it started working.Posting this answer incase it does happen to anyone else.


问:
OracleJet- How to know when a view is ready?
Is there anyway to know if the view is ready/finished rendering? Since oraclejet uses Knockout for data-binding, is this on Knockout'part?

My usecase would be:

Load the website. Router point to "A" view and that view uses "A.js" via "ojModule" namepsace
as model

I would like to run some codes after "A" view has been fully rendered.

答:
You may use busycontext for this as shown in the function below. You can refer more in BusyContext

```<code>function refreshBusyContext() {
  self.pageBusyContext = oj.Context.getPageContext().getBusyContext();
  self.pageBusyContext.whenReady().then(function () {
    console.log('page load is done');
  });
}
</code>```

I think you can also use lifecycle methods like handleBindingsApplied() as below

```<code>self.handleBindingsApplied = function(info) {
 // Executes after all the bindings applied and all jet components are ready in view
};
</code>```

Body:
You may use busycontext for this as shown in the function below. You can refer more in BusyContext

function refreshBusyContext() {
  self.pageBusyContext = oj.Context.getPageContext().getBusyContext();
  self.pageBusyContext.whenReady().then(function () {
    console.log('page load is done');
  });
}

I think you can also use lifecycle methods like handleBindingsApplied() as below

self.handleBindingsApplied = function(info) {
 // Executes after all the bindings applied and all jet components are ready in view
};


问:
C++ overload the + operator of a class so you can add a different class to that class and get a third class
So I'm just playing around but I would like to see if I can overload the + operator of a class to allow it to not add two of itself together, but add it to a second class and get a third class as a result.

Example:

```<code>#include <iostream>
#include <string>

using namespace std;

class dog;
class cat;
class catdog;

class dog
{
    public:
    string name;
    int weight;
    string soundMakes;

    dog(string, int, string);

    catdog operator + (const cat&);
};

dog::dog(string inName, int inWeight, string inSound)
{
    name = inName;
    weight = inWeight;
    soundMakes = inSound;
}

catdog dog::operator + (const cat& inCat)
{
    catdog newBorn("Rottens", this -> weight + inCat.weight, "Wooeow");

    return newBorn;
}

class cat
{
public:
    string name;
    int weight;
    string soundMakes;

    cat(string, int, string);
};

cat::cat(string inName, int inWeight, string inSound)
{
    name = inName;
    weight = inWeight;
    soundMakes = inSound;
}

class catdog
{
    string name;
    int weight;
    string soundMakes;

    catdog(string, int, string);
};

catdog::catdog(string inName, int inWeight, string inSound)
{
    name = inName;
    weight = inWeight;
    soundMakes = inSound;
}

int main()
{
    dog rover("Rover", 20, "Woof");
    cat mittens("Mittens", 10, "Meow");

    catdog rottens = rover + mittens;

    cout << "I have a cat dog, his name is " << rottens.name << " and he weighs " << rottens.weight << endl;
}
</code>```

I've been trying this but I keep getting problems with it not knowing what a cat is during the dogs operator + overload (or vice versa depending on the order). The exact error is class is imcomplete.

Is there anyway to accomplish what I'm tyring to do? I realise this example seems pretty stupid but I'm more going for if its possible to do the concept.

答:
You may use non-member operator+ instead. Place it after all 3 classes so that it can see them all as complete type.

```<code>catdog operator + (const dog& inDog, const cat& inCat)
{
    catdog newBorn("Rottens", inDog.weight + inCat.weight, "Wooeow");

    return newBorn;
}
</code>```

Full code and demo:

https://godbolt.org/g/1Yoq9D

http://coliru.stacked-crooked.com/a/a6bc0182103fe414

Body:
So I'm just playing around but I would like to see if I can overload the + operator of a class to allow it to not add two of itself together, but add it to a second class and get a third class as a result.

Example:

#include <iostream>
#include <string>

using namespace std;

class dog;
class cat;
class catdog;

class dog
{
    public:
    string name;
    int weight;
    string soundMakes;

    dog(string, int, string);

    catdog operator + (const cat&);
};

dog::dog(string inName, int inWeight, string inSound)
{
    name = inName;
    weight = inWeight;
    soundMakes = inSound;
}

catdog dog::operator + (const cat& inCat)
{
    catdog newBorn("Rottens", this -> weight + inCat.weight, "Wooeow");

    return newBorn;
}

class cat
{
public:
    string name;
    int weight;
    string soundMakes;

    cat(string, int, string);
};

cat::cat(string inName, int inWeight, string inSound)
{
    name = inName;
    weight = inWeight;
    soundMakes = inSound;
}

class catdog
{
    string name;
    int weight;
    string soundMakes;

    catdog(string, int, string);
};

catdog::catdog(string inName, int inWeight, string inSound)
{
    name = inName;
    weight = inWeight;
    soundMakes = inSound;
}

int main()
{
    dog rover("Rover", 20, "Woof");
    cat mittens("Mittens", 10, "Meow");

    catdog rottens = rover + mittens;

    cout << "I have a cat dog, his name is " << rottens.name << " and he weighs " << rottens.weight << endl;
}

I've been trying this but I keep getting problems with it not knowing what a cat is during the dogs operator + overload (or vice versa depending on the order). The exact error is class is imcomplete.

Is there anyway to accomplish what I'm tyring to do? I realise this example seems pretty stupid but I'm more going for if its possible to do the concept.

Body:
You may use non-member operator+ instead. Place it after all 3 classes so that it can see them all as complete type.

catdog operator + (const dog& inDog, const cat& inCat)
{
    catdog newBorn("Rottens", inDog.weight + inCat.weight, "Wooeow");

    return newBorn;
}

Full code and demo:

https://godbolt.org/g/1Yoq9D

http://coliru.stacked-crooked.com/a/a6bc0182103fe414


问:
Does NodeJS respect Docker virtualization and resource limits?
It is known that some applications aren't aware of Linux kernel isolation and virtualization features such as cgroups. This includes system utils like top, free and ps, but also platforms like Java.

I've recently read an article which suggests that when running JVMs in Kubernetes, you should enforce manual limits on the Java heap size to avoid errors.

I cannot find anywhere whether this is also true for NodeJS. Do I need to implement something like above to set --max_old_space_size=XXX on my NodeJS application in Kubernetes?

答:
A NodeJS process will try an allocate memory regardless of the container limits, just like Java.

Setting a limit on the process will help stop the OS from killing the process, particularly in constrained environments where Node might try allocate past the memory limit even though Node could probably run inside the limit.

If you are running an app that is close to using the memory limit then adding the memory limit settings just changes the failure scenario. NodeJS and the JVM will have a chance to exit with an out of memory error (OOM) rather than be killed by the operating system. The process will likely slow to a crawl as it nears the memory limit and the garbage collector tries the best it can to keep the process below the limit.

Note that the old space is only one of multiple memory spaces in NodeJS. Only the new space (semi spaces) and old space can be limited.

```<code>--max_semi_space_size (max size of a semi-space (in MBytes), the new space consists of two semi-spaces)
    type: int  default: 0
--max_old_space_size (max size of the old space (in Mbytes))
    type: int  default: 0
</code>```

The other heap spaces are generally small and static enough not to worry about.

Modules that run native code can allocate memory outside the heap and can't be limited by an option.

Body:
A NodeJS process will try an allocate memory regardless of the container limits, just like Java.

Setting a limit on the process will help stop the OS from killing the process, particularly in constrained environments where Node might try allocate past the memory limit even though Node could probably run inside the limit.

If you are running an app that is close to using the memory limit then adding the memory limit settings just changes the failure scenario. NodeJS and the JVM will have a chance to exit with an out of memory error (OOM) rather than be killed by the operating system. The process will likely slow to a crawl as it nears the memory limit and the garbage collector tries the best it can to keep the process below the limit.

Note that the old space is only one of multiple memory spaces in NodeJS. Only the new space (semi spaces) and old space can be limited.

--max_semi_space_size (max size of a semi-space (in MBytes), the new space consists of two semi-spaces)
    type: int  default: 0
--max_old_space_size (max size of the old space (in Mbytes))
    type: int  default: 0

The other heap spaces are generally small and static enough not to worry about.

Modules that run native code can allocate memory outside the heap and can't be limited by an option.


问:
Worksheet_Calculate to hide command button
I found the code below for Worksheet_Change. But my H29 is formula =SUM.
How do I change this to Worksheet_Calculate so that the below macro will run?

Basically what I want is if H29 is calculated as being equal to 20, show the button, else hide it.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False

If Target = Range("H29") Then
If Target.Value = "20" Then
Me.CommandButton1.Visible = True

Else

Me.CommandButton1.Visible = False

End If
Application.ScreenUpdating = True
End If
</code>```

答:
Sorry asked too soon. Resolved</p>

```<code>Private Sub Worksheet_Calculate()
'ActiveX button
Application.ScreenUpdating = False
If Range("H29").Value = 20 Then
  Me.CommandButton1.Visible = True
Else
   Me.CommandButton1.Visible = False
End If
Application.ScreenUpdating = True
End Sub
</code>```

Body:
I found the code below for Worksheet_Change. But my H29 is formula =SUM.
How do I change this to Worksheet_Calculate so that the below macro will run?

Basically what I want is if H29 is calculated as being equal to 20, show the button, else hide it.

Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False

If Target = Range("H29") Then
If Target.Value = "20" Then
Me.CommandButton1.Visible = True

Else

Me.CommandButton1.Visible = False

End If
Application.ScreenUpdating = True
End If

Body:
Sorry asked too soon. Resolved

Private Sub Worksheet_Calculate()
'ActiveX button
Application.ScreenUpdating = False
If Range("H29").Value = 20 Then
  Me.CommandButton1.Visible = True
Else
   Me.CommandButton1.Visible = False
End If
Application.ScreenUpdating = True
End Sub


问:
chartist graph color change
I am using a chartist graph and the colours are defined in a framework level, but i need to change it in for a specific graph, so i cannot change in the frame work level, tried to create a .less file but still the changes are not reflecting.

is there any other option on how to change the colour of a bar graph and if i add more bars, the colours should be different.

PS : link for the frame work changes for chartist.
https://github.com/capitalone/Hygieia/tree/master/UI/src/app/chartist

color change need to be done in
https://github.com/capitalone/Hygieia/blob/master/UI/src/components/widgets/build/build.less

wrote a piece of code given in .less file , but it's not reflecting... any inputs please.

```<code> .ct-series-a .ct-bar {
  stroke: white;
  stroke-width: 20px;
}
.ct-series-b .ct-bar {
      stroke: blue;
      stroke-width: 20px;
    }
</code>```

Thanks

答:
I know this answer may be quite late but I found a java script solution from this link, It shows how you can dynamically color different components.</p>

```<code>var chart = new Chartist.Bar('#barChart', data, options, responsiveOptions);
    chart.on('draw', function(context) {

      if(context.type === 'bar') {
         context.element.attr({
          style: 'stroke:  red'
        });
      }else if(context.type === 'point') {
            context.element.attr({
            style: 'stroke:  blue'
        });
      }else if(context.type === 'line') {
          context.element.attr({
            style: 'stroke:  green'
        });
      }
    });
</code>```

Title: chartist graph color change

Body:
I am using a chartist graph and the colours are defined in a framework level, but i need to change it in for a specific graph, so i cannot change in the frame work level, tried to create a .less file but still the changes are not reflecting.

is there any other option on how to change the colour of a bar graph and if i add more bars, the colours should be different.

PS : link for the frame work changes for chartist.
https://github.com/capitalone/Hygieia/tree/master/UI/src/app/chartist

color change need to be done in
https://github.com/capitalone/Hygieia/blob/master/UI/src/components/widgets/build/build.less

wrote a piece of code given in .less file , but it's not reflecting... any inputs please.

 .ct-series-a .ct-bar {
  stroke: white;
  stroke-width: 20px;
}
.ct-series-b .ct-bar {
      stroke: blue;
      stroke-width: 20px;
    }

Thanks

Body:
I know this answer may be quite late but I found a java script solution from this link, It shows how you can dynamically color different components.

var chart = new Chartist.Bar('#barChart', data, options, responsiveOptions);
    chart.on('draw', function(context) {

      if(context.type === 'bar') {
         context.element.attr({
          style: 'stroke:  red'
        });
      }else if(context.type === 'point') {
            context.element.attr({
            style: 'stroke:  blue'
        });
      }else if(context.type === 'line') {
          context.element.attr({
            style: 'stroke:  green'
        });
      }
    });


问:
Unmarshal JSON returns empty struct
Here's my JSON file:

```<code>{
    "database": {
        "dialect": "mysql"
        "host": "localhost",
        "user": "root",
        "pass": "",
        "name": "sws"
    }
}
</code>```

Here's my code:

```<code>package config

import (
    "fmt"
    "encoding/json"
    "io/ioutil"
    "log"
    "os"
)

type ConfigType struct {
    Database DatabaseType `json:"database"`
}

type DatabaseType struct {
    Dialect string `json:"dialect"`
    Host string `json:"host"`
    User string `json:"user"`
    Pass string `json:"pass"`
    Name string `json:"name"`
}

func Config() {
    file, err := os.Open("./config/config.json")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    fileBytes, _ := ioutil.ReadAll(file)

    var Conf ConfigType
    json.Unmarshal(fileBytes, &Conf)

    fmt.Printf("File content:\n%v", string(fileBytes))
    fmt.Printf("Conf: %v\n", Conf)
    fmt.Printf("Content: \n %v \nType: %T", Conf.Database.Host, Conf)
}
</code>```

And here is the output:

```<code>File content:
{
    "database": {
        "dialect": "mysql"
        "host": "localhost",
        "user": "root",
        "pass": "",
        "name": "sws"
    }
}
Conf: {{    }}
Content:

Type: config.ConfigType%
</code>```

The package is imported to main and just the Config function is executed. I've looked at a lot of similar questions and it seems like I almost have the exact same code as in the answers but I can't get my code to work.

答:
Don't neglect the errors. Always keep track of errors if function is returning one. It helps you find out if somethings goes wrong.  </p>

```<code>> In your case json file is invalid you missed "," after "dialect": "mysql" .
> valid json file should be (config.json )

     {
       "database": {
          "dialect": "mysql",
          "host": "localhost",
          "user": "root",
          "pass": "",
          "name": "sws"
       }
     }

>
>
> Modified code

    package main
    import (
       "encoding/json"
       "fmt"
       "io/ioutil"
       "log"
       "os"
    )

    type ConfigType struct {
       Database DatabaseType `json:"database"`
    }

    type DatabaseType struct {
       Dialect string `json:"dialect"`
       Host    string `json:"host"`
       User    string `json:"user"`
       Pass    string `json:"pass"`
       Name    string `json:"name"`
    }

    func main() {
       file, err := os.Open("./config.json")
       if err != nil {
           log.Fatal(err)
       }
       defer file.Close()

       fileBytes, err := ioutil.ReadAll(file)
       if err != nil {
           fmt.Println("error reading file", err)
           return
       }

      var Conf ConfigType
      err = json.Unmarshal(fileBytes, &Conf)

      if err != nil {
          fmt.Println("unmarshalling error ", err)
          return
      }
      fmt.Printf("File content:\n%v\n", string(fileBytes))
      fmt.Printf("Conf: %v\n", Conf)
      fmt.Printf("Content: \n %v \nType: %T", Conf.Database.Host, Conf)
}

> Output

    File content:
    {
      "database": {
      "dialect": "mysql",
      "host": "localhost",
      "user": "root",
      "pass": "",
      "name": "sws"
      }
    }
    Conf: {{mysql localhost root  sws}}
    Content:
    localhost
    Type: main.ConfigType
</code>```

Title: Unmarshal JSON returns empty struct

Body:
Here's my JSON file:

{
    "database": {
        "dialect": "mysql"
        "host": "localhost",
        "user": "root",
        "pass": "",
        "name": "sws"
    }
}

Here's my code:

package config

import (
    "fmt"
    "encoding/json"
    "io/ioutil"
    "log"
    "os"
)

type ConfigType struct {
    Database DatabaseType `json:"database"`
}

type DatabaseType struct {
    Dialect string `json:"dialect"`
    Host string `json:"host"`
    User string `json:"user"`
    Pass string `json:"pass"`
    Name string `json:"name"`
}

func Config() {
    file, err := os.Open("./config/config.json")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    fileBytes, _ := ioutil.ReadAll(file)

    var Conf ConfigType
    json.Unmarshal(fileBytes, &Conf)

    fmt.Printf("File content:\n%v", string(fileBytes))
    fmt.Printf("Conf: %v\n", Conf)
    fmt.Printf("Content: \n %v \nType: %T", Conf.Database.Host, Conf)
}

And here is the output:

File content:
{
    "database": {
        "dialect": "mysql"
        "host": "localhost",
        "user": "root",
        "pass": "",
        "name": "sws"
    }
}
Conf: {{    }}
Content:

Type: config.ConfigType%

The package is imported to main and just the Config function is executed. I've looked at a lot of similar questions and it seems like I almost have the exact same code as in the answers but I can't get my code to work.

Body:
Don't neglect the errors. Always keep track of errors if function is returning one. It helps you find out if somethings goes wrong.

> In your case json file is invalid you missed "," after "dialect": "mysql" .
> valid json file should be (config.json )

     {
       "database": {
          "dialect": "mysql",
          "host": "localhost",
          "user": "root",
          "pass": "",
          "name": "sws"
       }
     }

>
>
> Modified code

    package main
    import (
       "encoding/json"
       "fmt"
       "io/ioutil"
       "log"
       "os"
    )

    type ConfigType struct {
       Database DatabaseType `json:"database"`
    }

    type DatabaseType struct {
       Dialect string `json:"dialect"`
       Host    string `json:"host"`
       User    string `json:"user"`
       Pass    string `json:"pass"`
       Name    string `json:"name"`
    }

    func main() {
       file, err := os.Open("./config.json")
       if err != nil {
           log.Fatal(err)
       }
       defer file.Close()

       fileBytes, err := ioutil.ReadAll(file)
       if err != nil {
           fmt.Println("error reading file", err)
           return
       }

      var Conf ConfigType
      err = json.Unmarshal(fileBytes, &Conf)

      if err != nil {
          fmt.Println("unmarshalling error ", err)
          return
      }
      fmt.Printf("File content:\n%v\n", string(fileBytes))
      fmt.Printf("Conf: %v\n", Conf)
      fmt.Printf("Content: \n %v \nType: %T", Conf.Database.Host, Conf)
}

> Output

    File content:
    {
      "database": {
      "dialect": "mysql",
      "host": "localhost",
      "user": "root",
      "pass": "",
      "name": "sws"
      }
    }
    Conf: {{mysql localhost root  sws}}
    Content:
    localhost
    Type: main.ConfigType


问:
Populating a PDF file - Python
I have a ready-made PDF document containing placeholder values in certain areas.

e.g. {{ first_name }}, {{ postcode }}, ...

I need to substitute these values using python.

Any suggestions?

答:
I use reportlab to dynamically create 100 thousands of PDFs that include headers, footers, charts, tables, bullets, several different paragraph styles. etc.

http://www.reportlab.com/software/opensource/

ContentLicense: CC BY-SA 2.5

Title: Populating a PDF file - Python


问:
Amazon Linux: "apt-get: command not found"
I'm trying to install an Apache server on my AWS instance. However, it seems that it doesn't have the apt package installed.

I googled and all I found was some broken links to this package. I am using PuTTY on a Windows machine if that information helps.

I currently have low to none experience in Linux environments.

I am running the following version of Linux:

```<code>Linux ip-172-31-37-96 3.14.48-33.39.amzn1.x86_64 #1 SMP Tue Jul 14 23:43:07 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
</code>```

How can I fix this problem?

答:
I faced the same issue regarding apt-get: command not found. Here are the steps how I resolved it on Ubuntu 16.04 (Xenial Xerus):

Search the appropriate version of apt from here
(apt_1.6.13_amd64.deb for Ubuntu 16.04)

Download the apt.deb

wget http://security.ubuntu.com/ubuntu/pool/main/a/apt/apt_1.6.13_amd64.deb

Install the apt.deb package

sudo dpkg -i apt_1.6.13_amd64.deb

Now we can easily run

sudo apt-get install htop

Body:
I'm trying to install an Apache server on my AWS instance. However, it seems that it doesn't have the apt package installed.

I googled and all I found was some broken links to this package. I am using PuTTY on a Windows machine if that information helps.

I currently have low to none experience in Linux environments.

I am running the following version of Linux:

Linux ip-172-31-37-96 3.14.48-33.39.amzn1.x86_64 #1 SMP Tue Jul 14 23:43:07 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

How can I fix this problem?


问:
Facebook ShareDialog Limitations
Am facing one problem -> Sharing photos on facebook using Facebook Share Dialog (Facebook SDK) and that thing don't require publish action permission.

And everything works perfect until i share more then 6 photos. Its not working for more photos. So i want to know that is there any limitations from facebook side or from SDK that i can share 6 photos programatically (Bulk)

Here is the code Sample that am following :

```<code>for (int index = 0; index < mArryLstPhotos.size(); index++) {

                String pathofBmp = saveImageToExternalStorage(mArryLstPhotos.get(index), mImagesPath.get(index));
                Bitmap bitmap = null;
                bitmap = BitmapFactory.decodeFile(pathofBmp.contains("file:///") ?
                        pathofBmp.replace("file://", "")
                        : pathofBmp);

                if (bitmap != null && photos.size() < 6)
                    photos.add(new SharePhoto.Builder()
                            .setBitmap(bitmap)
                            .build());
            }
</code>```

And then showing it using  :

```<code>if (shareDialog.canShow(content)) {
 shareDialog.show(content, ShareDialog.Mode.AUTOMATIC);}
</code>```

答:
Yeah so finally found an answer.

-> People can share a combination of photos and videos from your app to Facebook with the Share Dialog. Note the following:

People need the native Facebook for Android app installed, version 71 or higher.
Photos must be less than 12MB in size.
Videos must be less than 12MB in size.
People can share a maximum of 6 photos and videos at a time.

For more detail : https://developers.facebook.com/docs/sharing/android

Title: Facebook ShareDialog Limitations

Body:
Am facing one problem -> Sharing photos on facebook using Facebook Share Dialog (Facebook SDK) and that thing don't require publish action permission.

And everything works perfect until i share more then 6 photos. Its not working for more photos. So i want to know that is there any limitations from facebook side or from SDK that i can share 6 photos programatically (Bulk)

Here is the code Sample that am following :

for (int index = 0; index < mArryLstPhotos.size(); index++) {

                String pathofBmp = saveImageToExternalStorage(mArryLstPhotos.get(index), mImagesPath.get(index));
                Bitmap bitmap = null;
                bitmap = BitmapFactory.decodeFile(pathofBmp.contains("file:///") ?
                        pathofBmp.replace("file://", "")
                        : pathofBmp);

                if (bitmap != null && photos.size() < 6)
                    photos.add(new SharePhoto.Builder()
                            .setBitmap(bitmap)
                            .build());
            }

And then showing it using  :

if (shareDialog.canShow(content)) {
 shareDialog.show(content, ShareDialog.Mode.AUTOMATIC);}


问:
find by id in spring data jpa Base Repository
I'm trying to implement a generic findByIdsIn method in the BaseRepository of my Spring Data JPA class so that the functionality can be used by all the classes that implement that interface.
I'm pretty new to Spring Data JPA so I'm not sure if that is possible and how to implement it.

Here's the code I have so far. The findByIdsIn is the functionality I'd like to implement.

```<code>import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;

@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
    List<T> findAll( );
    Optional<T> findById(ID id);
    List<T> findByIdsIn(List<ID> ids); // This is the functionality I'd like to implement.
}
</code>```

Do you guys have any suggestions?
Many thanks!

答:
I've just found a solution I'm satisfied with:

```<code>@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
    List<T> findAll( );
    Optional<T> findById(ID id);
    @Query("SELECT t FROM #{#entityName} t WHERE t.id IN :ids")
    List<T> findByIdsIn(@Param("ids") List<ID> ids);
}
</code>```

I'm happy for other people to contribute if there are more elegant solutions, though.

Body:
I'm trying to implement a generic findByIdsIn method in the BaseRepository of my Spring Data JPA class so that the functionality can be used by all the classes that implement that interface.
I'm pretty new to Spring Data JPA so I'm not sure if that is possible and how to implement it.

Here's the code I have so far. The findByIdsIn is the functionality I'd like to implement.

import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;

@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
    List<T> findAll( );
    Optional<T> findById(ID id);
    List<T> findByIdsIn(List<ID> ids); // This is the functionality I'd like to implement.
}

Do you guys have any suggestions?
Many thanks!

Body:
I've just found a solution I'm satisfied with:

@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
    List<T> findAll( );
    Optional<T> findById(ID id);
    @Query("SELECT t FROM #{#entityName} t WHERE t.id IN :ids")
    List<T> findByIdsIn(@Param("ids") List<ID> ids);
}

I'm happy for other people to contribute if there are more elegant solutions, though.


问:
stats.chisquare wrongly returns p_value = 0
I have such expected and frequencies in each category as shown below:

They seem to be pretty similar, but chi square test doesn't think so:

```<code>stats.chisquare(city_ans.answered, city_ans.sent)
# Power_divergenceResult(statistic=893005.32003277098, pvalue=0.0)
</code>```

Filtering values less than 10 doesn't change much:

```<code>stats.chisquare(city_ans[city_ans.answered > 10].answered, city_ans[city_ans.answered > 10].sent)

# Power_divergenceResult(statistic=892917.3023088905, pvalue=0.0)
</code>```

What am I doing wrong?
How can I apply F - test here?

PS. Using this test with the same values as obs and exp - return p_val = 1

```<code>stats.chisquare(city_ans.sent, city_ans.sent)
# Power_divergenceResult(statistic=0.0, pvalue=1.0)
</code>```

However such code also should return p_val = 1, but it doesn't:

```<code>stats.chisquare(0.9*city_ans.sent, city_ans.sent)
# Power_divergenceResult(statistic=10591.249999999995, pvalue=0.0)
</code>```

UPD:

```<code>f_obs = weeks_ans.answered / np.sum(weeks_ans.answered)
f_exp = weeks_ans.sent / np.sum(weeks_ans.sent)
stats.chisquare(f_obs, f_exp)

# Power_divergenceResult(statistic=0.064491479990141154, pvalue=1.0)
</code>```

Its seems to pretty nice result but I think something isnt right here.

For example look to that distribution below, same approach:

```<code># Power_divergenceResult(statistic=0.064491479990141154, pvalue=1.0)
</code>```

Is it fair to use such test that the distribution are the same

答:
As pointed out by @Crasy Ivan, the chisquare test needs the same number of observations or counts in observed and expected counts.

In this case, it seems to be that the data comes from two different samples. This is essentially a 2 by K contingency table and the hypothesis that each row has the same distribution will be corrected by the row totals in computing the expected frequency counts.

So using chisquare test directly is the wrong test for the two sample case. scipy.stats has the chisquare test for independence in contingency tables.

A general remark about very large counts which seems to be the case here:

As the sample size grows the null hypothesis will be rejected and the pvalue goes to zero for any small but nonzero deviation from the null hypothesis. With counts, i.e. total number of observations, of more that 50,000 the proper hypthesis test will most likely reject even small differences that are statistically significant but irrelevant in applications.

An alternative would be to use equivalence tests to test the hypothesis that the two distributions do not differ by more than some small margin. The difficulty is that it is difficult to specify what the equivalence thresholds should be in terms of some goodness-of-fit statistics.

Body:
I have such expected and frequencies in each category as shown below:

They seem to be pretty similar, but chi square test doesn't think so:

stats.chisquare(city_ans.answered, city_ans.sent)
# Power_divergenceResult(statistic=893005.32003277098, pvalue=0.0)

Filtering values less than 10 doesn't change much:

stats.chisquare(city_ans[city_ans.answered > 10].answered, city_ans[city_ans.answered > 10].sent)

# Power_divergenceResult(statistic=892917.3023088905, pvalue=0.0)

What am I doing wrong?
How can I apply F - test here?

PS. Using this test with the same values as obs and exp - return p_val = 1

stats.chisquare(city_ans.sent, city_ans.sent)
# Power_divergenceResult(statistic=0.0, pvalue=1.0)

However such code also should return p_val = 1, but it doesn't:

stats.chisquare(0.9*city_ans.sent, city_ans.sent)
# Power_divergenceResult(statistic=10591.249999999995, pvalue=0.0)

UPD:

f_obs = weeks_ans.answered / np.sum(weeks_ans.answered)
f_exp = weeks_ans.sent / np.sum(weeks_ans.sent)
stats.chisquare(f_obs, f_exp)

# Power_divergenceResult(statistic=0.064491479990141154, pvalue=1.0)

Its seems to pretty nice result but I think something isnt right here.

For example look to that distribution below, same approach:

# Power_divergenceResult(statistic=0.064491479990141154, pvalue=1.0)

Is it fair to use such test that the distribution are the same


问:
I m not able to run a postman collection using newman
I m trying to run a postman collection using newman. This collection works fine with postman. However when i run it through newman i see this below error

#  failure        detail

Error          Hostname/IP doesn't match certificate's altnames: "IP:
               10.10.XXX.XXX is not in the cert's list: "
               at request
               inside "Translate Dataa"

I have to use newman for my test beacause the script have file post in the request.

A help would be much appreciated

答:
Figured out had to appended -k and it worked
C:\Users\anaik>newman run C:\ProgramData\anaik\Postman\app-5.4.1\Test.postman_co
llection.json -k</p>


问:
How do I move bar to center in chart in MPAndroidChart?
I'm using the MPAndroidChart.

It's nice library but I couldn't have solved a problem.

This is result be executed.

The axis are well to center align but bar groups are no center align.

I would like to move bar groups to center too.

And, This is entire code.

```<code>        float barWidth = 0.1f;
        float barSpace = 0f;
        float groupSpace = 0.1f;
        int groupCount = 3;

        distinctionGraph = (BarChart) findViewById(R.id.distinction_graph);
        verificationGraph = (BarChart) findViewById(R.id.verification_graph);
        sentenceGraph = (BarChart) findViewById(R.id.sentence_graph);

        ArrayList xVals = new ArrayList();

        xVals.add("3월");
        xVals.add("2월");
        xVals.add("1월");

        ArrayList yVals1 = new ArrayList();
        ArrayList yVals2 = new ArrayList();
        ArrayList yVals3 = new ArrayList();

        yVals1.add(new BarEntry(1, (float) 1));
        yVals2.add(new BarEntry(1, (float) 2));
        yVals3.add(new BarEntry(1, (float) 2));

        yVals1.add(new BarEntry(2, (float) 3));
        yVals2.add(new BarEntry(2, (float) 4));
        yVals3.add(new BarEntry(2, (float) 4));

        yVals1.add(new BarEntry(3, (float) 5));
        yVals2.add(new BarEntry(3, (float) 6));
        yVals3.add(new BarEntry(3, (float) 6));

        BarDataSet set1, set2, set3;
        set1 = new BarDataSet(yVals1, "쉬움");
        set1.setColor(Color.parseColor("#3EBB9B"));
        set2 = new BarDataSet(yVals2, "보통");
        set2.setColor(Color.parseColor("#3698DB"));
        set3 = new BarDataSet(yVals3, "어려움");
        set3.setColor(Color.parseColor("#2C80B9"));

        BarData data = new BarData(set1, set2, set3);
        data.setValueFormatter(new LargeValueFormatter());

        distinctionGraph.setData(data);
        distinctionGraph.getBarData().setBarWidth(barWidth);
        distinctionGraph.getXAxis().setAxisMinimum(0);
        distinctionGraph.getXAxis().setAxisMaximum(0 + distinctionGraph.getBarData().getGroupWidth(groupSpace, barSpace) * groupCount);
        distinctionGraph.groupBars(0, groupSpace, barSpace);
        distinctionGraph.getData().setHighlightEnabled(false);
        distinctionGraph.invalidate();

        distinctionGraph.setDescription(null);
        distinctionGraph.setPinchZoom(false);
        distinctionGraph.setScaleEnabled(false);
        distinctionGraph.setDrawBarShadow(false);
        distinctionGraph.setDrawGridBackground(false);

        Legend l = distinctionGraph.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(true);
        l.setYOffset(20f);
        l.setXOffset(0f);
        l.setYEntrySpace(0f);
        l.setTextSize(8f);

        //X-axis
        XAxis xAxis = distinctionGraph.getXAxis();
        xAxis.setGranularity(1f);
        xAxis.setGranularityEnabled(true);
        xAxis.setCenterAxisLabels(true);
        xAxis.setDrawGridLines(false);
        xAxis.setAxisMaximum(3);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new IndexAxisValueFormatter(xVals));
        //Y-axis
        distinctionGraph.getAxisRight().setEnabled(false);
        YAxis leftAxis = distinctionGraph.getAxisLeft();
        leftAxis.setValueFormatter(new LargeValueFormatter());
        leftAxis.setDrawGridLines(true);
        leftAxis.setSpaceTop(35f);
        leftAxis.setAxisMinimum(0f);
</code>```

I set 3 for groupCount but not working.
Do I miss something?

For example, like this.

Needs help. Thank you :)

答:
I solved it by myself.

First, I changed variable like below.

```<code>    float barWidth = 0.3f;
    float barSpace = 0.0f;
    float groupSpace = 0.06f;
    int groupCount = 3;
</code>```

The point was barWidth.
I Changed it 0.0f to 0.3f.

0.3 * 3 = 0.9.

it's close to 1.

And, I modified groupBars like below.

```<code>distinctionGraph.groupBars(groupSpace, groupSpace, barSpace);
</code>```

First Argument of groupBar is fromX.
Before modification, groupSpace was 0.

This is screenshot after I solved it.

Body:
I'm using the MPAndroidChart.

It's nice library but I couldn't have solved a problem.

This is result be executed.

The axis are well to center align but bar groups are no center align.

I would like to move bar groups to center too.

And, This is entire code.

        float barWidth = 0.1f;
        float barSpace = 0f;
        float groupSpace = 0.1f;
        int groupCount = 3;

        distinctionGraph = (BarChart) findViewById(R.id.distinction_graph);
        verificationGraph = (BarChart) findViewById(R.id.verification_graph);
        sentenceGraph = (BarChart) findViewById(R.id.sentence_graph);

        ArrayList xVals = new ArrayList();

        xVals.add("3월");
        xVals.add("2월");
        xVals.add("1월");

        ArrayList yVals1 = new ArrayList();
        ArrayList yVals2 = new ArrayList();
        ArrayList yVals3 = new ArrayList();

        yVals1.add(new BarEntry(1, (float) 1));
        yVals2.add(new BarEntry(1, (float) 2));
        yVals3.add(new BarEntry(1, (float) 2));

        yVals1.add(new BarEntry(2, (float) 3));
        yVals2.add(new BarEntry(2, (float) 4));
        yVals3.add(new BarEntry(2, (float) 4));

        yVals1.add(new BarEntry(3, (float) 5));
        yVals2.add(new BarEntry(3, (float) 6));
        yVals3.add(new BarEntry(3, (float) 6));

        BarDataSet set1, set2, set3;
        set1 = new BarDataSet(yVals1, "쉬움");
        set1.setColor(Color.parseColor("#3EBB9B"));
        set2 = new BarDataSet(yVals2, "보통");
        set2.setColor(Color.parseColor("#3698DB"));
        set3 = new BarDataSet(yVals3, "어려움");
        set3.setColor(Color.parseColor("#2C80B9"));

        BarData data = new BarData(set1, set2, set3);
        data.setValueFormatter(new LargeValueFormatter());

        distinctionGraph.setData(data);
        distinctionGraph.getBarData().setBarWidth(barWidth);
        distinctionGraph.getXAxis().setAxisMinimum(0);
        distinctionGraph.getXAxis().setAxisMaximum(0 + distinctionGraph.getBarData().getGroupWidth(groupSpace, barSpace) * groupCount);
        distinctionGraph.groupBars(0, groupSpace, barSpace);
        distinctionGraph.getData().setHighlightEnabled(false);
        distinctionGraph.invalidate();

        distinctionGraph.setDescription(null);
        distinctionGraph.setPinchZoom(false);
        distinctionGraph.setScaleEnabled(false);
        distinctionGraph.setDrawBarShadow(false);
        distinctionGraph.setDrawGridBackground(false);

        Legend l = distinctionGraph.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(true);
        l.setYOffset(20f);
        l.setXOffset(0f);
        l.setYEntrySpace(0f);
        l.setTextSize(8f);

        //X-axis
        XAxis xAxis = distinctionGraph.getXAxis();
        xAxis.setGranularity(1f);
        xAxis.setGranularityEnabled(true);
        xAxis.setCenterAxisLabels(true);
        xAxis.setDrawGridLines(false);
        xAxis.setAxisMaximum(3);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new IndexAxisValueFormatter(xVals));
        //Y-axis
        distinctionGraph.getAxisRight().setEnabled(false);
        YAxis leftAxis = distinctionGraph.getAxisLeft();
        leftAxis.setValueFormatter(new LargeValueFormatter());
        leftAxis.setDrawGridLines(true);
        leftAxis.setSpaceTop(35f);
        leftAxis.setAxisMinimum(0f);

I set 3 for groupCount but not working.
Do I miss something?

For example, like this.

Needs help. Thank you :)

Body:
I solved it by myself.

First, I changed variable like below.

    float barWidth = 0.3f;
    float barSpace = 0.0f;
    float groupSpace = 0.06f;
    int groupCount = 3;

The point was barWidth.
I Changed it 0.0f to 0.3f.

0.3 * 3 = 0.9.

it's close to 1.

And, I modified groupBars like below.

distinctionGraph.groupBars(groupSpace, groupSpace, barSpace);

First Argument of groupBar is fromX.
Before modification, groupSpace was 0.

This is screenshot after I solved it.


问:
How to save a web page into a HTML file with PowerShell or C#?
I have the following link , and when I open the link via Chrome and then right-click the page and then choose "save as" to save the page into a HTML file (c:\temp\cu2.html)

After it is saved, I can open this cu2.html file with an HTML editor (say VS2015), and I can see
inside the file, there is  tag as seen below

However, if I open the link with IE11 (instead of Chrome), and then save the same page as HTML file, I cannot find this  tag at all. Actually, the html file saved from IE11 is the same content as what I can extract with PowerShell script below.

```<code>#Requires -version 4.0
$url = 'https://support.microsoft.com/en-us/help/4052574/cumulative-update-2-for-sql-server-2017';

$wr = Invoke-WebRequest $url;
$wr.RawContent.contains('<table') # returns false

$wr.RawContent | out-file -FilePath c:\temp\cu2_ps.html -Force; #same as the file saved from the webpage to html file in IE
</code>```

So my question is:

Why is a web page saved (as html file) in Chrome is different from that in IE?

How can I use PowerShell(or C#) to save such web page into a HTML file (same as the file saved in Chrome)?

答:
You can use Selenium.WebDriver and Selenium.Chrome.WebDriver packages to download and save html content:

```<code>var service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
var options = new ChromeOptions();
options.AddArgument("headless");

using (var driver = new ChromeDriver(service, options))
{
    driver.Url = "https://support.microsoft.com/en-us/help/4052574/cumulative-update-2-for-sql-server-2017";
    File.WriteAllText("cu2_ps.html", driver.PageSource);
}
</code>```

But that means that you need to have chrome installed. You could use IE driver as well, but then probably better to use IE COM automation as was suggested in another answer.

Body:
I have the following link , and when I open the link via Chrome and then right-click the page and then choose "save as" to save the page into a HTML file (c:\temp\cu2.html)

After it is saved, I can open this cu2.html file with an HTML editor (say VS2015), and I can see
inside the file, there is  tag as seen below

However, if I open the link with IE11 (instead of Chrome), and then save the same page as HTML file, I cannot find this  tag at all. Actually, the html file saved from IE11 is the same content as what I can extract with PowerShell script below.

#Requires -version 4.0
$url = 'https://support.microsoft.com/en-us/help/4052574/cumulative-update-2-for-sql-server-2017';

$wr = Invoke-WebRequest $url;
$wr.RawContent.contains('<table') # returns false

$wr.RawContent | out-file -FilePath c:\temp\cu2_ps.html -Force; #same as the file saved from the webpage to html file in IE

So my question is:

Why is a web page saved (as html file) in Chrome is different from that in IE?

How can I use PowerShell(or C#) to save such web page into a HTML file (same as the file saved in Chrome)?

Body:
You can use Selenium.WebDriver and Selenium.Chrome.WebDriver packages to download and save html content:

var service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
var options = new ChromeOptions();
options.AddArgument("headless");

using (var driver = new ChromeDriver(service, options))
{
    driver.Url = "https://support.microsoft.com/en-us/help/4052574/cumulative-update-2-for-sql-server-2017";
    File.WriteAllText("cu2_ps.html", driver.PageSource);
}

But that means that you need to have chrome installed. You could use IE driver as well, but then probably better to use IE COM automation as was suggested in another answer.


问:
assigned objects using spread syntax `...` and equals `=`
Is there a difference if I assign an object using = or ...

```<code>var o1 = {
    a:1,
    b:2
}

var o2 = o1; //say style 1
var o3 = {...o1} //say style 2
</code>```

Does it matter whether I use style 1 or style 2?

答:
Spread operator does a one level deep cloning of your object and hence

```<code>var o1 = {
    a:1,
    b:2
}

var o3 = {...o1}
</code>```

will return create a new object that doesn't reference o1 where as when you write var o3 = o1 you are assigning the reference of o1 to o3, and so if you change the value of say o3.a = 2, it will change for the original object too, whereas it won't for the first case

var o1 = {
        a:1,
        b:2
    }
    var o2 = {
        a:1,
        b:2
    }

var o3 = {...o1}
var o4 = o2;

o3.a = 2;
console.log(o3, o1);

o4.a = 4;
console.log(o2, o4);```

Body:
Is there a difference if I assign an object using = or ...

var o1 = {
    a:1,
    b:2
}

var o2 = o1; //say style 1
var o3 = {...o1} //say style 2

Does it matter whether I use style 1 or style 2?

Body:
Spread operator does a one level deep cloning of your object and hence

var o1 = {
    a:1,
    b:2
}

var o3 = {...o1}

will return create a new object that doesn't reference o1 where as when you write var o3 = o1 you are assigning the reference of o1 to o3, and so if you change the value of say o3.a = 2, it will change for the original object too, whereas it won't for the first case

var o1 = {
        a:1,
        b:2
    }
    var o2 = {
        a:1,
        b:2
    }

var o3 = {...o1}
var o4 = o2;

o3.a = 2;
console.log(o3, o1);

o4.a = 4;
console.log(o2, o4);


问:
Priority/Cascading datetime without full table scan
```<code>SELECT IF(priority_date, priority_date, created_at) as created_at
FROM table
WHERE IF(priority_date , priority_date , created_at)
    BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59';
</code>```

What is the best way to execute this query, performance-wise?

I have a fairly large table that has two datetimes. created_at and priority_date.

priority_date doesn't always exist, but if it does, it should be what is queried upon, else it falls back to created_at. created_at is always generated upon creation of the row. The above query causes a (nearly) full table scan.

The explain plan for initial query:

```<code>+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
| id   | select_type | table           | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
|    1 | SIMPLE      | table           | ALL  | NULL          | NULL | NULL    | NULL | 444877 | Using where |
+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
</code>```

I should also note that priority_date or created_at may not necessarily both be within the time frame in question on a single row. So doing something like:

```<code>WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
</code>```

Could give bad results if priority_date was 2017-10-04 23:10:43 and created_at was 2017-10-10 01:23:45

My current rows for said table: 582739

Count of WHERE priority_date BETWEEN... : 3908

Count of WHERE created_at BETWEEN...: 3437

Example explain of just one of the columns queried in WHERE BETWEEN:

```<code>+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
| id   | select_type | table           | type  | possible_keys                    | key                              | key_len | ref  | rows | Extra                 |
+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
|    1 | SIMPLE      | table           | range | table_created_at_index           | table_created_at_index           | 5       | NULL | 3436 | Using index condition |
+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
</code>```

Clearly the IF is not the most efficient. The columns are indexed and the explains of individual rows are matching to their counts for rows on the explain plan. How can I leverage having a priority/fallback query without the wild performance loss?

EDIT

The best I've been able to figure (But WOW, is that verbose and copy/paste-y feeling)

```<code>SELECT IF(priority_date, priority_date, created_at) as created_at, priority_date
FROM table
WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
    OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
HAVING ((priority_date AND priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59')
    OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59');
</code>```

And its explain plan:

```<code>+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
| id   | select_type | table           | type        | possible_keys                                                         | key                                                                   | key_len | ref  | rows | Extra                                                                                |
+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
|    1 | SIMPLE      | table           | index_merge | table_priority_date_index,table_created_at_index                      | table_priority_date_index,table_created_at_index                      | 6,5     | NULL | 7343 | Using sort_union(table_priority_date_index,table_created_at_index); Using where                      |
+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
</code>```

答:
```<code>SELECT priority_date as created_at
FROM table
WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'

UNION ALL

SELECT created_at
FROM table
WHERE created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
 AND priority_date IS NULL;
</code>```

You'll need an index starting with priority_date for the first half of this query, and an index on (created_at, priority_date) for the second half.

The first half will naturally not match any rows where the priority_date  is NULL.

The second half will do the range-condition on created_at, and then among the subset of matching rows, further test that priority_date is NULL. This may be done by index condition pushdown.

Body:
SELECT IF(priority_date, priority_date, created_at) as created_at
FROM table
WHERE IF(priority_date , priority_date , created_at)
    BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59';

What is the best way to execute this query, performance-wise?

I have a fairly large table that has two datetimes. created_at and priority_date.

priority_date doesn't always exist, but if it does, it should be what is queried upon, else it falls back to created_at. created_at is always generated upon creation of the row. The above query causes a (nearly) full table scan.

The explain plan for initial query:

+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
| id   | select_type | table           | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
|    1 | SIMPLE      | table           | ALL  | NULL          | NULL | NULL    | NULL | 444877 | Using where |
+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+

I should also note that priority_date or created_at may not necessarily both be within the time frame in question on a single row. So doing something like:

WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'

Could give bad results if priority_date was 2017-10-04 23:10:43 and created_at was 2017-10-10 01:23:45

My current rows for said table: 582739

Count of WHERE priority_date BETWEEN... : 3908

Count of WHERE created_at BETWEEN...: 3437

Example explain of just one of the columns queried in WHERE BETWEEN:

+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
| id   | select_type | table           | type  | possible_keys                    | key                              | key_len | ref  | rows | Extra                 |
+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
|    1 | SIMPLE      | table           | range | table_created_at_index           | table_created_at_index           | 5       | NULL | 3436 | Using index condition |
+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+

Clearly the IF is not the most efficient. The columns are indexed and the explains of individual rows are matching to their counts for rows on the explain plan. How can I leverage having a priority/fallback query without the wild performance loss?

EDIT

The best I've been able to figure (But WOW, is that verbose and copy/paste-y feeling)

SELECT IF(priority_date, priority_date, created_at) as created_at, priority_date
FROM table
WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
    OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
HAVING ((priority_date AND priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59')
    OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59');

And its explain plan:

+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
| id   | select_type | table           | type        | possible_keys                                                         | key                                                                   | key_len | ref  | rows | Extra                                                                                |
+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
|    1 | SIMPLE      | table           | index_merge | table_priority_date_index,table_created_at_index                      | table_priority_date_index,table_created_at_index                      | 6,5     | NULL | 7343 | Using sort_union(table_priority_date_index,table_created_at_index); Using where                      |
+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+

Body:
SELECT priority_date as created_at
FROM table
WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'

UNION ALL

SELECT created_at
FROM table
WHERE created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
 AND priority_date IS NULL;

You'll need an index starting with priority_date for the first half of this query, and an index on (created_at, priority_date) for the second half.

The first half will naturally not match any rows where the priority_date  is NULL.

The second half will do the range-condition on created_at, and then among the subset of matching rows, further test that priority_date is NULL. This may be done by index condition pushdown.


问:
How to clear old badge count in android
I set "0" means its showing badge count was "1". how to clear my old badge count.

//Badge count set method

```<code>  public static void setBadge(Context mContext, int count) {
    String launcherClassName = getLauncherClassName(mContext);
    if (launcherClassName == null) {
        return;
    }
    Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
    intent.putExtra("badge_count", count);
    intent.putExtra("badge_count_package_name", mContext.getPackageName());
    intent.putExtra("badge_count_class_name", launcherClassName);
    mContext.sendBroadcast(intent);
}
</code>```

//Find out our app and here return app package name.

```<code> public static String getLauncherClassName(Context mContext) {

    PackageManager pm = mContext.getPackageManager();
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
        if (pkgName.equalsIgnoreCase(mContext.getPackageName())) {
            String className = resolveInfo.activityInfo.name;
            return className;
        }
    }
    return null;
}
</code>```

答:
This can be done if using the https://github.com/leolin310148/ShortcutBadger library by calling the method as follows:</p>

```<code>ShortcutBadger.applyCount(Context context, int badgeCount)

//or

ShortcutBadger.removeCount(Context context)
</code>```

Title: How to clear old badge count in android

Body:
I set "0" means its showing badge count was "1". how to clear my old badge count.

//Badge count set method

  public static void setBadge(Context mContext, int count) {
    String launcherClassName = getLauncherClassName(mContext);
    if (launcherClassName == null) {
        return;
    }
    Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
    intent.putExtra("badge_count", count);
    intent.putExtra("badge_count_package_name", mContext.getPackageName());
    intent.putExtra("badge_count_class_name", launcherClassName);
    mContext.sendBroadcast(intent);
}

//Find out our app and here return app package name.

 public static String getLauncherClassName(Context mContext) {

    PackageManager pm = mContext.getPackageManager();
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
        if (pkgName.equalsIgnoreCase(mContext.getPackageName())) {
            String className = resolveInfo.activityInfo.name;
            return className;
        }
    }
    return null;
}

Body:
This can be done if using the https://github.com/leolin310148/ShortcutBadger library by calling the method as follows:

ShortcutBadger.applyCount(Context context, int badgeCount)

//or

ShortcutBadger.removeCount(Context context)


问:
jenkins build failure shell command permission denied
I am trying to run shell build command on mac but I get permission denied for e.g. ls /Users/... command.

I see whoami is jenkins, which is different for my uesr login?

I read online I need to run chmod for jenkins user, how do I do that?

I changed file permission using chmod 777?

Do I need to change jenkins user?

答:
In linux, e.g. ubuntu, you can add user jenkins to the root group:

```<code>sudo usermod -a -G root jenkins
</code>```

Then restart jenkins:

```<code>sudo service jenkins restart
</code>```

Be aware that, adding jenkins user to root group can make the user too powerful, use with caution

Body:
In linux, e.g. ubuntu, you can add user jenkins to the root group:

sudo usermod -a -G root jenkins

Then restart jenkins:

sudo service jenkins restart

Be aware that, adding jenkins user to root group can make the user too powerful, use with caution


问:
My circles are not matching up with my planets orbits
My planets orbits are not matching up with my circular paths im plotting of the orbits, I have matched in my for loop the distance for every planet with the distance they are from the center.(image is attached)
    from pylab import *
    from matplotlib.animation import *
Here is where I am defining the circes I will plot to show the paths of the orbits at the "def circle..."

```<code>def circle(x0,y0,R,N) :
    ''' create circle, given center x0,y0, input radius R,
        and number of points N, then
        output arrays of x and y coordinates '''

    theta = linspace(0.0,2.0*pi,N)
    x = R * cos(theta) + x0
    y = R * sin(theta) + y0
    return x,y

a= array([.39,.72,1,1.52,5.20,9.54,19.2,30.1]) #astronomical units of #the planets in order of the planets(i.e mercury, venus, earth,mars...)
period = a**(3.0/2.0)
</code>```

I am taking the distane of the planets and inputting them in array, to be able to use a for loop to graph the circles.

```<code>#distance of the planets
d= array([390,790,980, 1520,5200,9540,19200,30100])#same order of the #planets as well

#attributes of the sun
x0 =0
y0 = 0
r_s=70*1.2#actual earth radius is 695e6

#radius of the planets
r_Ear = 63.781#e in m {for all the planets}
r_Merc= 24
r_Ven = 60
r_Mars= 33.9
r_Jup = 700
r_Sat = 582
r_Ura = 253
r_Nep = 246
</code>```

the actual distance of the planets

```<code>#Distance of the planets
d_Ear = 1000#152
d_Merc= 390#70
d_Ven = 790#109
d_Mars= 1520#249
d_Jup = 5200#816
d_Sat = 9540#1514
d_Ura = 19200#3003
d_Nep = 30100#4545

fig = plt.figure()
ax = plt.axes(xlim=(-1e4-5000, 1e4+5000), ylim=(-1e4-5000, 1e4+5000), aspect=True)
</code>```

This is where I am looping over, to plot 8 circles. Theres a link here to see the plot I have generated.

```<code>for i in range(8) :
    x, y = circle(0.0,0.0,d[i],10000) # orbit
    plot(x,y,':k')
[enter image description here][1]
</code>```

The rest are the patches of the planets and the FuncAnimation.

```<code>Sun = plt.Circle((x0, y0), radius=r_s, ec='yellow', fc='yellow', lw=3)
Mercury = plt.Circle((0, 0), radius=r_Merc, ec='brown', fc='brown', lw=3)
Venus = plt.Circle((0, 0), radius=r_Ven, ec='brown', fc='brown', lw=3)
Earth = plt.Circle((0, 0), radius=r_Ear, ec='black', fc='black', lw=3)
Mars = plt.Circle((0, 0), radius=r_Mars, ec='brown', fc='brown', lw=3)
Jupiter = plt.Circle((0, 0), radius=r_Jup, ec='green', fc='green', lw=3)
Saturn = plt.Circle((0, 0), radius=r_Sat, ec='green', fc='green', lw=3)
Uranus = plt.Circle((0, 0), radius=r_Ura, ec='green', fc='green', lw=3)
Neptune = plt.Circle((0, 0), radius=r_Nep, ec='green', fc='green', lw=3)

ax.add_patch(Sun)

def init():

    ax.add_patch(Earth)
    ax.add_patch(Mercury)
    ax.add_patch(Venus)
    ax.add_patch(Mars)
    ax.add_patch(Jupiter)
    ax.add_patch(Saturn)
    ax.add_patch(Uranus)
    ax.add_patch(Neptune)

    return Mercury, Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,
def animate(i):

    theta = radians(i)
    mx = d_Merc*np.cos(theta/period[0]) - d_Merc*np.sin(theta/period[0])
    my = d_Merc*np.sin(theta/period[0]) + d_Merc*np.cos(theta/period[0])

    vx = d_Ven *np.cos(theta/period[1]) - d_Ven*np.sin(theta/period[1])
    vy = d_Ven *np.cos(theta/period[1]) + d_Ven*np.sin(theta/period[1])

    ex = d_Ear*np.cos(theta/period[2]) - d_Ear*np.sin(theta/period[2])
    ey = d_Ear*np.sin(theta/period[2]) + d_Ear*np.cos(theta/period[2])

    Mx = d_Mars*np.cos(theta/period[3]) - d_Mars*np.sin(theta/period[3])
    My = d_Mars*np.sin(theta/period[3]) + d_Mars*np.cos(theta/period[3])

    Jx = d_Jup*np.cos(theta/period[4]) - d_Jup*np.sin(theta/period[4])
    Jy = d_Jup*np.sin(theta/period[4]) + d_Jup*np.cos(theta/period[4])

    Sx = d_Sat*np.cos(theta/period[5]) - d_Sat*np.sin(theta/period[5])
    Sy = d_Sat*np.sin(theta/period[5]) + d_Sat*np.cos(theta/period[5])

    Ux = d_Ura*np.cos(theta/period[6]) - d_Ura*np.sin(theta/period[6])
    Uy = d_Ura*np.sin(theta/period[6]) + d_Ura*np.cos(theta/period[6])

    Nx = d_Nep*np.cos(theta/period[7]) - d_Nep*np.sin(theta/period[7])
    Ny = d_Nep*np.sin(theta/period[7]) + d_Nep*np.cos(theta/period[7])

    Mercury.center = (mx, my)
    Mercury._angle = i
    Venus.center = (vx, vy)
    Venus._angle = i
    Earth.center = (ex, ey)
    Earth._angle = i
    Mars.center  = (Mx, My)
    Mars.angle =i
    Jupiter.center = (Jx, Jy)
    Jupiter._angle = i
    Saturn.center = (Sx, Sy)
    Saturn._angle = i
    Uranus.center = (Ux, Uy)
    Uranus.angle = i
    Neptune.center = (Nx, Ny)
    Neptune._angle = i

    return  Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus,          Neptune,

anim = FuncAnimation(fig, animate, init_func=init, frames=1080,
                               interval=25, blit=True)

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

答:
I'm not following your math on this:

```<code>mx = d_Merc*np.cos(theta/period[0]) - d_Merc*np.sin(theta/period[0])
my = d_Merc*np.sin(theta/period[0]) + d_Merc*np.cos(theta/period[0])
</code>```

You'll be more correct if you change that to this:

```<code>mx = d_Merc*np.cos(theta/period[0])
my = d_Merc*np.sin(theta/period[0])
</code>```

And even more correct if you take the size of the planet into account

```<code>mx = (d_Merc+(r_Merc/2))*np.cos(theta/period[0])
my = (d_Merc+(r_Merc/2))*np.sin(theta/period[0])
</code>```

That will fix your basic issue I think.

Beyond that:

d_Ear differs from Earth's value in the d array. 980 vs. 1000.

vy = d_Ven *np.cos(theta/period[1]) is not correct. That needs
to be vy = d_Ven *np.sin(theta/period[1])

As far as the code goes, you may consider using a few dictionaries to
avoid repetition like with your d array.

Body:
My planets orbits are not matching up with my circular paths im plotting of the orbits, I have matched in my for loop the distance for every planet with the distance they are from the center.(image is attached)
    from pylab import *
    from matplotlib.animation import *
Here is where I am defining the circes I will plot to show the paths of the orbits at the "def circle..."

def circle(x0,y0,R,N) :
    ''' create circle, given center x0,y0, input radius R,
        and number of points N, then
        output arrays of x and y coordinates '''

    theta = linspace(0.0,2.0*pi,N)
    x = R * cos(theta) + x0
    y = R * sin(theta) + y0
    return x,y

a= array([.39,.72,1,1.52,5.20,9.54,19.2,30.1]) #astronomical units of #the planets in order of the planets(i.e mercury, venus, earth,mars...)
period = a**(3.0/2.0)

I am taking the distane of the planets and inputting them in array, to be able to use a for loop to graph the circles.

#distance of the planets
d= array([390,790,980, 1520,5200,9540,19200,30100])#same order of the #planets as well

#attributes of the sun
x0 =0
y0 = 0
r_s=70*1.2#actual earth radius is 695e6

#radius of the planets
r_Ear = 63.781#e in m {for all the planets}
r_Merc= 24
r_Ven = 60
r_Mars= 33.9
r_Jup = 700
r_Sat = 582
r_Ura = 253
r_Nep = 246

the actual distance of the planets

#Distance of the planets
d_Ear = 1000#152
d_Merc= 390#70
d_Ven = 790#109
d_Mars= 1520#249
d_Jup = 5200#816
d_Sat = 9540#1514
d_Ura = 19200#3003
d_Nep = 30100#4545

fig = plt.figure()
ax = plt.axes(xlim=(-1e4-5000, 1e4+5000), ylim=(-1e4-5000, 1e4+5000), aspect=True)

This is where I am looping over, to plot 8 circles. Theres a link here to see the plot I have generated.

for i in range(8) :
    x, y = circle(0.0,0.0,d[i],10000) # orbit
    plot(x,y,':k')
[enter image description here][1]

The rest are the patches of the planets and the FuncAnimation.

Sun = plt.Circle((x0, y0), radius=r_s, ec='yellow', fc='yellow', lw=3)
Mercury = plt.Circle((0, 0), radius=r_Merc, ec='brown', fc='brown', lw=3)
Venus = plt.Circle((0, 0), radius=r_Ven, ec='brown', fc='brown', lw=3)
Earth = plt.Circle((0, 0), radius=r_Ear, ec='black', fc='black', lw=3)
Mars = plt.Circle((0, 0), radius=r_Mars, ec='brown', fc='brown', lw=3)
Jupiter = plt.Circle((0, 0), radius=r_Jup, ec='green', fc='green', lw=3)
Saturn = plt.Circle((0, 0), radius=r_Sat, ec='green', fc='green', lw=3)
Uranus = plt.Circle((0, 0), radius=r_Ura, ec='green', fc='green', lw=3)
Neptune = plt.Circle((0, 0), radius=r_Nep, ec='green', fc='green', lw=3)

ax.add_patch(Sun)

def init():

    ax.add_patch(Earth)
    ax.add_patch(Mercury)
    ax.add_patch(Venus)
    ax.add_patch(Mars)
    ax.add_patch(Jupiter)
    ax.add_patch(Saturn)
    ax.add_patch(Uranus)
    ax.add_patch(Neptune)

    return Mercury, Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,
def animate(i):

    theta = radians(i)
    mx = d_Merc*np.cos(theta/period[0]) - d_Merc*np.sin(theta/period[0])
    my = d_Merc*np.sin(theta/period[0]) + d_Merc*np.cos(theta/period[0])

    vx = d_Ven *np.cos(theta/period[1]) - d_Ven*np.sin(theta/period[1])
    vy = d_Ven *np.cos(theta/period[1]) + d_Ven*np.sin(theta/period[1])

    ex = d_Ear*np.cos(theta/period[2]) - d_Ear*np.sin(theta/period[2])
    ey = d_Ear*np.sin(theta/period[2]) + d_Ear*np.cos(theta/period[2])

    Mx = d_Mars*np.cos(theta/period[3]) - d_Mars*np.sin(theta/period[3])
    My = d_Mars*np.sin(theta/period[3]) + d_Mars*np.cos(theta/period[3])

    Jx = d_Jup*np.cos(theta/period[4]) - d_Jup*np.sin(theta/period[4])
    Jy = d_Jup*np.sin(theta/period[4]) + d_Jup*np.cos(theta/period[4])

    Sx = d_Sat*np.cos(theta/period[5]) - d_Sat*np.sin(theta/period[5])
    Sy = d_Sat*np.sin(theta/period[5]) + d_Sat*np.cos(theta/period[5])

    Ux = d_Ura*np.cos(theta/period[6]) - d_Ura*np.sin(theta/period[6])
    Uy = d_Ura*np.sin(theta/period[6]) + d_Ura*np.cos(theta/period[6])

    Nx = d_Nep*np.cos(theta/period[7]) - d_Nep*np.sin(theta/period[7])
    Ny = d_Nep*np.sin(theta/period[7]) + d_Nep*np.cos(theta/period[7])

    Mercury.center = (mx, my)
    Mercury._angle = i
    Venus.center = (vx, vy)
    Venus._angle = i
    Earth.center = (ex, ey)
    Earth._angle = i
    Mars.center  = (Mx, My)
    Mars.angle =i
    Jupiter.center = (Jx, Jy)
    Jupiter._angle = i
    Saturn.center = (Sx, Sy)
    Saturn._angle = i
    Uranus.center = (Ux, Uy)
    Uranus.angle = i
    Neptune.center = (Nx, Ny)
    Neptune._angle = i

    return  Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus,          Neptune,

anim = FuncAnimation(fig, animate, init_func=init, frames=1080,
                               interval=25, blit=True)

plt.show()

Body:
I'm not following your math on this:

mx = d_Merc*np.cos(theta/period[0]) - d_Merc*np.sin(theta/period[0])
my = d_Merc*np.sin(theta/period[0]) + d_Merc*np.cos(theta/period[0])

You'll be more correct if you change that to this:

mx = d_Merc*np.cos(theta/period[0])
my = d_Merc*np.sin(theta/period[0])

And even more correct if you take the size of the planet into account

mx = (d_Merc+(r_Merc/2))*np.cos(theta/period[0])
my = (d_Merc+(r_Merc/2))*np.sin(theta/period[0])

That will fix your basic issue I think.

Beyond that:

d_Ear differs from Earth's value in the d array. 980 vs. 1000.

vy = d_Ven *np.cos(theta/period[1]) is not correct. That needs
to be vy = d_Ven *np.sin(theta/period[1])

As far as the code goes, you may consider using a few dictionaries to
avoid repetition like with your d array.


问:
Node ORM and Python ORM for same DB?
If I have two backends, one NodeJS and one Python both of them are accessing the same database. Is it possible to use an ORM for both or is that really bad practice? It seems like that would lead to a maintenance nightmare.</p>

答: It is possible, but it may cause conflicts with table names, constraint names, sequence names and other names which are depend on ORM naming strategy. </p>

Title: Node ORM and Python ORM for same DB?


问:
Why won't my while loop if condition work correctly?
My checkWin method returns false until there's a winner in the Connect 4 game by putting 4 "checkers" in a row horizontally, vertically, or diagonally in my board array. Once there's a winner, the checkWin method returns true, the nearest if statement iterates, printing the winner, then terminating the entire loop (if I coded it all correctly). However, when I run the program, the while loop iterates only once, accepts one input for red, states red won, then does the same thing for yellow, then terminates.

What am I missing here?

 Below is the relevant code.

Thank you.

```<code>public static void main(String[] args) {
    char[][] board = new char[6][7];
    boolean loop = true;
    // loop to alternate players until there's a winner
    while (loop) {
        printData(board);
        red(board);
        if (checkWin(board) == true) {
            printData(board);
            System.out.print("Red wins!");
            loop = false;
        }
        printData(board);
        yellow(board);
        if (checkWin(board) == true) {
            printData(board);
            System.out.print("Yellow wins!");
            loop = false;
        }
    }
}

public static void printData(char[][] tbl) {
    for (int r = 0; r < tbl.length; r++) {
        for (int c = 0; c < tbl[r].length; c++) {
            if (tbl[r][c] == 0) {
                System.out.print("| ");
            } else {
                System.out.print("|" + tbl[r][c]);
            }
        } // end for col loop
        System.out.println("|");
    } // end for row loop
    System.out.println("---------------");
} // end printData method

public static void red(char[][] f) {
    System.out.println("Place a red checker at column (0-6)");
    Scanner in = new Scanner(System.in);
    int c = in.nextInt();
    for (int i = 5; i >= 0; i--) {
        if (f[i][c] == 0) {
            f[i][c] = 'R';
            break;
        }
    }
}

public static void yellow(char[][] f) {
    System.out.println("Place a yellow checker at column (0-6)");
    Scanner in = new Scanner(System.in);
    int c = in.nextInt();
    for (int i = 5; i >= 0; i--) {
        if (f[i][c] == 0) {
            f[i][c] = 'Y';
            break;
        }
    }
}

// Method to check for a winner. Receives 2-D array as parameter. Returns
// boolean value.
public static boolean checkWin(char[][] b) {
    // Create four boolean variables, one for each set of rows. Initialize
    // all of them to false.
    boolean foundRow = false;
    boolean foundCol = false;
    boolean foundMjrD = false;
    boolean foundMinD = false;

    // Check to see if four consecutive cells in a row match.
    // check rows
    for (int r = 0; r <= 5; r++) {
        for (int c = 0; c <= 3; c++) {
            if (b[r][c] == b[r][c + 1] && b[r][c] == b[r][c + 2] && b[r][c] == b[r][c + 3] && b[r][c] != ' ') {
                foundRow = true;
                break;
            }
        }
    }

    // Check to see if four columns in the same row match
    // check columns
    for (int r = 0; r <= 2; r++) {
        for (int c = 0; c <= 6; c++) {
            if (b[r][c] == b[r + 1][c] && b[r][c] == b[r + 2][c] && b[r][c] == b[r + 3][c] && b[r][c] != ' ') {
                foundCol = true;
                break;
            }
        }
    }

    // Check to see if four diagonals match (top left to bottom right)
    // check major diagonal
    for (int r = 0; r <= 2; r++) {
        for (int c = 0; c <= 3; c++) {
            if (b[r][c] == b[r + 1][c + 1] && b[r][c] == b[r + 2][c + 2] && b[r][c] == b[r + 3][c + 3]
                    && b[r][c] != ' ') {
                foundMjrD = true;
                break;
            }
        }
    }

    // Check to see if four diagonals in the other direction match (top
    // right to bottom left)
    // check minor diagonal
    for (int r = 0; r <= 2; r++) {
        for (int c = 3; c <= 6; c++) {
            if (b[r][c] == b[r + 1][c - 1] && b[r][c] == b[r + 2][c - 2] && b[r][c] == b[r + 3][c - 3]
                    && b[r][c] != ' ') {
                foundMinD = true;
                break;
            }
        }
    }

    // If ONE of the booleans is true, we have a winner.
    // checks boolean for a true
    if (foundRow || foundCol || foundMjrD || foundMinD)
        return true;
    else
        return false;
} // end checkWin method
</code>```

答:
You should take a closer look at this line:

```<code>if (b[r][c] == b[r][c + 1] && b[r][c] == b[r][c + 2] && b[r][c] == b[r][c + 3] && b[r][c] != ' ') {
</code>```

You check for b[r][c] != ' ', but you never put a space in char[][] board, therefore the default value in board[?][?] is 0.

Body:
My checkWin method returns false until there's a winner in the Connect 4 game by putting 4 "checkers" in a row horizontally, vertically, or diagonally in my board array. Once there's a winner, the checkWin method returns true, the nearest if statement iterates, printing the winner, then terminating the entire loop (if I coded it all correctly). However, when I run the program, the while loop iterates only once, accepts one input for red, states red won, then does the same thing for yellow, then terminates.

What am I missing here?

 Below is the relevant code.

Thank you.

public static void main(String[] args) {
    char[][] board = new char[6][7];
    boolean loop = true;
    // loop to alternate players until there's a winner
    while (loop) {
        printData(board);
        red(board);
        if (checkWin(board) == true) {
            printData(board);
            System.out.print("Red wins!");
            loop = false;
        }
        printData(board);
        yellow(board);
        if (checkWin(board) == true) {
            printData(board);
            System.out.print("Yellow wins!");
            loop = false;
        }
    }
}

public static void printData(char[][] tbl) {
    for (int r = 0; r < tbl.length; r++) {
        for (int c = 0; c < tbl[r].length; c++) {
            if (tbl[r][c] == 0) {
                System.out.print("| ");
            } else {
                System.out.print("|" + tbl[r][c]);
            }
        } // end for col loop
        System.out.println("|");
    } // end for row loop
    System.out.println("---------------");
} // end printData method

public static void red(char[][] f) {
    System.out.println("Place a red checker at column (0-6)");
    Scanner in = new Scanner(System.in);
    int c = in.nextInt();
    for (int i = 5; i >= 0; i--) {
        if (f[i][c] == 0) {
            f[i][c] = 'R';
            break;
        }
    }
}

public static void yellow(char[][] f) {
    System.out.println("Place a yellow checker at column (0-6)");
    Scanner in = new Scanner(System.in);
    int c = in.nextInt();
    for (int i = 5; i >= 0; i--) {
        if (f[i][c] == 0) {
            f[i][c] = 'Y';
            break;
        }
    }
}

// Method to check for a winner. Receives 2-D array as parameter. Returns
// boolean value.
public static boolean checkWin(char[][] b) {
    // Create four boolean variables, one for each set of rows. Initialize
    // all of them to false.
    boolean foundRow = false;
    boolean foundCol = false;
    boolean foundMjrD = false;
    boolean foundMinD = false;

    // Check to see if four consecutive cells in a row match.
    // check rows
    for (int r = 0; r <= 5; r++) {
        for (int c = 0; c <= 3; c++) {
            if (b[r][c] == b[r][c + 1] && b[r][c] == b[r][c + 2] && b[r][c] == b[r][c + 3] && b[r][c] != ' ') {
                foundRow = true;
                break;
            }
        }
    }

    // Check to see if four columns in the same row match
    // check columns
    for (int r = 0; r <= 2; r++) {
        for (int c = 0; c <= 6; c++) {
            if (b[r][c] == b[r + 1][c] && b[r][c] == b[r + 2][c] && b[r][c] == b[r + 3][c] && b[r][c] != ' ') {
                foundCol = true;
                break;
            }
        }
    }

    // Check to see if four diagonals match (top left to bottom right)
    // check major diagonal
    for (int r = 0; r <= 2; r++) {
        for (int c = 0; c <= 3; c++) {
            if (b[r][c] == b[r + 1][c + 1] && b[r][c] == b[r + 2][c + 2] && b[r][c] == b[r + 3][c + 3]
                    && b[r][c] != ' ') {
                foundMjrD = true;
                break;
            }
        }
    }

    // Check to see if four diagonals in the other direction match (top
    // right to bottom left)
    // check minor diagonal
    for (int r = 0; r <= 2; r++) {
        for (int c = 3; c <= 6; c++) {
            if (b[r][c] == b[r + 1][c - 1] && b[r][c] == b[r + 2][c - 2] && b[r][c] == b[r + 3][c - 3]
                    && b[r][c] != ' ') {
                foundMinD = true;
                break;
            }
        }
    }

    // If ONE of the booleans is true, we have a winner.
    // checks boolean for a true
    if (foundRow || foundCol || foundMjrD || foundMinD)
        return true;
    else
        return false;
} // end checkWin method

Body:
You should take a closer look at this line:

if (b[r][c] == b[r][c + 1] && b[r][c] == b[r][c + 2] && b[r][c] == b[r][c + 3] && b[r][c] != ' ') {

You check for b[r][c] != ' ', but you never put a space in char[][] board, therefore the default value in board[?][?] is 0.


问:
Can not find a java.io.InputStream with the name [fileInputStream] in the invocation stack
Can not find a java.io.InputStream with the name [fileInputStream] in the invocation stack. Check the  tag specified for this action.</p>

答:
Your question is not clear , by what I've understood , you are trying to search "FileInputStream" under "InputStream" both classes belong to "java.io" package.

You can search like this :


问:
Manual testing for GPS on ios
I'm a newbie in testing area. I have an application which has the facility to use gps and I don't have garmin tracker. I have done few tests on gps but i don't feel it's sufficient. </p>

<p>How to test gps manually?
What are the ways and methods to test it? please, suggest some testcases for it. </p>

答:
I am sure your done with smoke testing!, In that case start with Interruption testing.

Keep moving in a place, check the your GPS connectivity.

Travel to remote places where you feel the GPS can't be tracked. Check how your application responds.

Try receiving call while using the Application.

Place an alarm, check how your application responds during alarm work.

Check when your device is about to die, how the application responds. Since you'l be using GPS, chances of u'r battery drain is too high.

Check with Notification. how your application behaves.

Switch off your GPS, see if an appropriate alert is provided.

Title: Manual testing for GPS on ios

Body:
I'm a newbie in testing area. I have an application which has the facility to use gps and I don't have garmin tracker. I have done few tests on gps but i don't feel it's sufficient.

How to test gps manually?
What are the ways and methods to test it? please, suggest some testcases for it.


问:
About IB,init,load view and view did load?
this is a quite general question but i want to understand this please -

I usually build my apps without using IB.

what are, the cons and pros of using IB vs. creating interface programmatically?

what oppressions/code fits the init method and what is for the loadView method?

is there any difference between loadView an ViewDidLoad or do i need to use only one of them?

thanks
shani

答:
Some people would say that writing a ViewController in code would be "easier" and would make the app load faster because it doesn't need to load a file on startup. Although that is true depending on the size of the .xib, If you're a developer who knows how to write an app in all code, making an app with .xib's would be a lot easier and faster because you don't have to make an object

```<code>UISomething *smthng = [[UISomething alloc] initWithFrame:CGRectZero];
[smthng doSoemthing:nil];
//ect ect...
</code>```

over, and over again to construct your UI.

As for loadView and viewDidLoad, Apple says that loadView is for loading a view programmatically but you can still use it for .xibs

Body:
Some people would say that writing a ViewController in code would be "easier" and would make the app load faster because it doesn't need to load a file on startup. Although that is true depending on the size of the .xib, If you're a developer who knows how to write an app in all code, making an app with .xib's would be a lot easier and faster because you don't have to make an object

UISomething *smthng = [[UISomething alloc] initWithFrame:CGRectZero];
[smthng doSoemthing:nil];
//ect ect...

over, and over again to construct your UI.

As for loadView and viewDidLoad, Apple says that loadView is for loading a view programmatically but you can still use it for .xibs