问:
ES6 Dyanmic Promise Chaining from array
Scenario

I have an array of URLs that I need to download, however each must also be supplied with a unique transaction ID that must be requested from the server and only increments when a request is successful.

Problem

As I loop through the array I need to wait for both the request for the transaction ID and the request for the file to complete before starting the next iteration of the loop but the number of files is not fixed so need to dynamically build a chain of promises.

Pseudocode

Below is some pseudocode, getFiles() is the problem because all the requests get the same transaction Id as they don't wait for the previous request to finish.

```<code>function getTransationId(){
    return new Promise((resolve,reject)=> {
        let id = getNextTransactionId();
        if(id!=error){
            resolve(id);
        }else{
            reject(error);
        }
    })
}

function getFile(url, transactionId){
    return new Promise((resolve,reject)=>{
        http.request(url+transactionId, function(err,response){
            if(err){
                reject(err);
            }else{
                resolve(response);
            }
        });
    });
}

function getFilesFromArray(urlArray){
    for(let url of urlArray){
        getTransactionId().then(resolve=>getFile(url,resolve),reject=>console.error(reject));
    }
}
</code>```

Question

How do I chain chain promises together dynamically?

Answer

Here's a JSFiddle of Ovidiu's answer

答:
A functional approach is to use reduce to iterate and return a final promise chained up from each sub-promise. It also helps building the results e.g. in an array:

```<code>function getFilesFromArray(urlArray){
    const filesPromise = urlArray.reduce((curPromise, url) => {
        return curPromise
           .then(curFiles => {
                return getTransactionId()
                    .then(id => getFile(url, id))
                    .then(newFile => [...curFiles, newFile]);
           });
    }, Promise.resolve([]));

    filesPromise.then(files => {
         console.log(files);
    }
}
</code>```

This effectively builds a promise chain that:

starts with a static Promise with a value [] representing the initial set of files: Promise.resolve([])

on each iteration, returns a promise that waits for the curPromise in the chain and then

performs getTransactionId and uses the id to getFile

once the file will be retrieved it will return an array containing the curFiles set in the the curPromise (previous values) and concatenates the newFile into it

the end result will be a single promise with all files collected

Title: ES6 Dyanmic Promise Chaining from array

Body:
Scenario

I have an array of URLs that I need to download, however each must also be supplied with a unique transaction ID that must be requested from the server and only increments when a request is successful.

Problem

As I loop through the array I need to wait for both the request for the transaction ID and the request for the file to complete before starting the next iteration of the loop but the number of files is not fixed so need to dynamically build a chain of promises.

Pseudocode

Below is some pseudocode, getFiles() is the problem because all the requests get the same transaction Id as they don't wait for the previous request to finish.

function getTransationId(){
    return new Promise((resolve,reject)=> {
        let id = getNextTransactionId();
        if(id!=error){
            resolve(id);
        }else{
            reject(error);
        }
    })
}

function getFile(url, transactionId){
    return new Promise((resolve,reject)=>{
        http.request(url+transactionId, function(err,response){
            if(err){
                reject(err);
            }else{
                resolve(response);
            }
        });
    });
}

function getFilesFromArray(urlArray){
    for(let url of urlArray){
        getTransactionId().then(resolve=>getFile(url,resolve),reject=>console.error(reject));
    }
}

Question

How do I chain chain promises together dynamically?

Answer

Here's a JSFiddle of Ovidiu's answer

Body:
A functional approach is to use reduce to iterate and return a final promise chained up from each sub-promise. It also helps building the results e.g. in an array:

function getFilesFromArray(urlArray){
    const filesPromise = urlArray.reduce((curPromise, url) => {
        return curPromise
           .then(curFiles => {
                return getTransactionId()
                    .then(id => getFile(url, id))
                    .then(newFile => [...curFiles, newFile]);
           });
    }, Promise.resolve([]));

    filesPromise.then(files => {
         console.log(files);
    }
}

This effectively builds a promise chain that:

starts with a static Promise with a value [] representing the initial set of files: Promise.resolve([])

on each iteration, returns a promise that waits for the curPromise in the chain and then

performs getTransactionId and uses the id to getFile

once the file will be retrieved it will return an array containing the curFiles set in the the curPromise (previous values) and concatenates the newFile into it

the end result will be a single promise with all files collected


来源: stackexchange

问:
String concatenation without strcat in C
I am having trouble concatenating strings in C, without strcat library function. Here is my code

```<code>#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
  char *a1=(char*)malloc(100);
  strcpy(a1,"Vivek");
  char *b1=(char*)malloc(100);
  strcpy(b1,"Ratnavel");
  int i;
  int len=strlen(a1);

  for(i=0;i<strlen(b1);i++)
  {
     a1[i+len]=b1[i];
  }

  a1[i+len]='\0';
  printf("\n\n A: %s",a1);

  return 0;
}
</code>```

I made corrections to the code. This is working. Now can I do it without strcpy?

答:
```<code> char a1[] = "Vivek";
</code>```

Will create a char array a1 of size 6. You are trying to stuff it with more characters than it can hold.

If you want to be able to accommodate concatenation "Vivek" and "Ratnavel" you need to have a char array of size atleast 14 (5 + 8 + 1).

In your modified  program you are doing:

```<code>char *a1=(char*)malloc(100);  // 1
a1 = "Vivek";                 // 2
</code>```

1: Will allocate a memory chunk of size 100 bytes, makes a1 point to it.

2: Will make a1 point to the string literal "Vivek". This string literal cannot be modified.

To fix this use strcpy to copy the string into the allocated memory:

```<code>char *a1=(char*)malloc(100);
strcpy(a1,"Vivek");
</code>```

Also the for loop condition i<strlen(b1)-1 will not copy last character from the string, change it to i<strlen(b1)

And

```<code>a1[i]='\0';
</code>```

should be

```<code>a1[i + len]='\0';
</code>```

as the new length of a1 is i+len and you need to have the NUL character at that index.

And don't forget to free your dynamically allocated memory once you are done using it.

ContentLicense: CC BY-SA 3.0

Body:
I am having trouble concatenating strings in C, without strcat library function. Here is my code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
  char *a1=(char*)malloc(100);
  strcpy(a1,"Vivek");
  char *b1=(char*)malloc(100);
  strcpy(b1,"Ratnavel");
  int i;
  int len=strlen(a1);

  for(i=0;i<strlen(b1);i++)
  {
     a1[i+len]=b1[i];
  }

  a1[i+len]='\0';
  printf("\n\n A: %s",a1);

  return 0;
}

I made corrections to the code. This is working. Now can I do it without strcpy?

Body:
 char a1[] = "Vivek";

Will create a char array a1 of size 6. You are trying to stuff it with more characters than it can hold.

If you want to be able to accommodate concatenation "Vivek" and "Ratnavel" you need to have a char array of size atleast 14 (5 + 8 + 1).

In your modified  program you are doing:

char *a1=(char*)malloc(100);  // 1
a1 = "Vivek";                 // 2

1: Will allocate a memory chunk of size 100 bytes, makes a1 point to it.

2: Will make a1 point to the string literal "Vivek". This string literal cannot be modified.

To fix this use strcpy to copy the string into the allocated memory:

char *a1=(char*)malloc(100);
strcpy(a1,"Vivek");

Also the for loop condition i<strlen(b1)-1 will not copy last character from the string, change it to i<strlen(b1)

And

a1[i]='\0';

should be

a1[i + len]='\0';

as the new length of a1 is i+len and you need to have the NUL character at that index.

And don't forget to free your dynamically allocated memory once you are done using it.

ContentLicense: CC BY-SA 2.5


问:
Get postgresql array into struct with StructScan
Test data:

```<code>CREATE TABLE test (id int, data text[])
INSERT INTO test(id, data) VALUES(1, '{a,b,c}')
</code>```

Go Code. First - one that is working just fine:

```<code>func main() {
  db, _ := sqlx.Open("postgres", "user=postgres dbname=test sslmode=disable")
  var id int
  var asSlice []string
  err := db.QueryRowx(`SELECT id, data FROM test WHERE data @> ARRAY['b']`).Scan(&id, pq.Array(&asSlice))
  if err != nil {
    log.Fatal(err)
  }
  fmt.Println(id, asSlice)
}
</code>```

I get 1 [a b c] as expected.
But here I manually assign results to the variables

Now, to the part that is not working - using StructScan

```<code>type MyStruct struct {
    Id   int
    Data []string
}

func main() {
    db, _ := sqlx.Open("postgres", "user=postgres dbname=test sslmode=disable")
    var testStruct MyStruct
    err := db.QueryRowx(`SELECT id, data FROM test WHERE data @> ARRAY['b']`).StructScan(&testStruct)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(testStruct)
}

sql: Scan error on column index 1: unsupported Scan, storing driver.Value type []uint8 into type *[]string
</code>```

I guess that means that sqlx does not know about PostgreSQL arrays and does not use pq.Array internally.

What should I do about it? Maybe I am doing something wrong? Or maybe I should apply pq.Array manually? If so - how?

答:
Try using pq.StringArray type for []string

```<code>type MyStruct struct {
    Id   int
    Data pq.StringArray
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Test data:

CREATE TABLE test (id int, data text[])
INSERT INTO test(id, data) VALUES(1, '{a,b,c}')

Go Code. First - one that is working just fine:

func main() {
  db, _ := sqlx.Open("postgres", "user=postgres dbname=test sslmode=disable")
  var id int
  var asSlice []string
  err := db.QueryRowx(`SELECT id, data FROM test WHERE data @> ARRAY['b']`).Scan(&id, pq.Array(&asSlice))
  if err != nil {
    log.Fatal(err)
  }
  fmt.Println(id, asSlice)
}

I get 1 [a b c] as expected.
But here I manually assign results to the variables

Now, to the part that is not working - using StructScan

type MyStruct struct {
    Id   int
    Data []string
}

func main() {
    db, _ := sqlx.Open("postgres", "user=postgres dbname=test sslmode=disable")
    var testStruct MyStruct
    err := db.QueryRowx(`SELECT id, data FROM test WHERE data @> ARRAY['b']`).StructScan(&testStruct)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(testStruct)
}

sql: Scan error on column index 1: unsupported Scan, storing driver.Value type []uint8 into type *[]string

I guess that means that sqlx does not know about PostgreSQL arrays and does not use pq.Array internally.

What should I do about it? Maybe I am doing something wrong? Or maybe I should apply pq.Array manually? If so - how?

Body:
Try using pq.StringArray type for []string

type MyStruct struct {
    Id   int
    Data pq.StringArray
}


问:
how to push sub array object into an a array in javascript
hi all i am using javascript i am trying to push object values into one array here i attached my code

```<code>var data = [{
            BuildingID: "56", FloorId: "65", volume: [{

                one: 12,
                two: 15,
                three: 12
            }]
        }]

var MainInfo=[];
            for (i = 0; i < data.length; i++) {

                var obj = {}
                obj.BuildingID = data[i].BuildingID;
                obj.FloorId = data[i].FloorId;
                obj.volume = data[i].volume[0];
                MainInfo.push(obj);

            }
</code>```

it's working but not fully applicable here i mentioned the excepted output what should i need

Current output

Expected output

Note:in data volume is dynamic help how to do this

答:
You could use Object.assign for assigning all properties to another object.

var data = [{ BuildingID: "56", FloorId: "65", volume: [{ one: 12, two: 15, three: 12 }] }],
    mainInfo = [],
    i, obj;

for (i = 0; i < data.length; i++) {
  obj = {}
  obj.BuildingID = data[i].BuildingID;
  obj.FloorId = data[i].FloorId;
  mainInfo.push(Object.assign(obj, data[i].volume[0]));
}

console.log(mainInfo);```

Body:
hi all i am using javascript i am trying to push object values into one array here i attached my code

var data = [{
            BuildingID: "56", FloorId: "65", volume: [{

                one: 12,
                two: 15,
                three: 12
            }]
        }]

var MainInfo=[];
            for (i = 0; i < data.length; i++) {

                var obj = {}
                obj.BuildingID = data[i].BuildingID;
                obj.FloorId = data[i].FloorId;
                obj.volume = data[i].volume[0];
                MainInfo.push(obj);

            }

it's working but not fully applicable here i mentioned the excepted output what should i need

Current output

Expected output

Note:in data volume is dynamic help how to do this


问:
try block with empty finally block
When we have a try block without any code is finally block, the compiler compiles it fine. However, there is no purpose of try here - because we are neither catching a exception nor cleaning up code in finally block.

```<code>public int updateTable(InputVo sfVo){
    //SqlSession session = ConnFactory.getSqlSession();
    //InputMapper spMapper = session.getMapper(InputMapper .class);
    int updRecs=0;
    try {

        mapper.updateData(sfVo);

        updRecs=sfVo.getRecsUpdated();
        return updRecs;

    } finally {
        //session.close();
    }
}
</code>```

If thats the case, why does JAVA has not considered a compile time check on this ?

Wouldn't be better if compiler throws error at compile time itself - like "Cannot have a empty finally block"

答:
Since you surrounded your exception-throwing code in a try-catch or try-finally statement, the compiler knows you processed the potential error. What you do with it is up to you, it is authorized to ignore it.

You could argue: "How is that different than no try at all?". The difference is that if you don't put it in a try clause, the compiler can't know if you did it on purpose or you forgot it.

Basically, catching an exception is mandatory, but processing it isn't.

Title: try block with empty finally block

Body:
When we have a try block without any code is finally block, the compiler compiles it fine. However, there is no purpose of try here - because we are neither catching a exception nor cleaning up code in finally block.

public int updateTable(InputVo sfVo){
    //SqlSession session = ConnFactory.getSqlSession();
    //InputMapper spMapper = session.getMapper(InputMapper .class);
    int updRecs=0;
    try {

        mapper.updateData(sfVo);

        updRecs=sfVo.getRecsUpdated();
        return updRecs;

    } finally {
        //session.close();
    }
}

If thats the case, why does JAVA has not considered a compile time check on this ?

Wouldn't be better if compiler throws error at compile time itself - like "Cannot have a empty finally block"


问:
Webview does not display anything in JFrame pane
In my JFrame pane I wanna dislay a webview, the decare of class is :

```<code>public class MainTabbedForm extends javax.swing.JFrame {
</code>```

I have added a Button named Display Weband here is the code of this :

```<code>        private void siteSurveyActionPerformed(java.awt.event.ActionEvent evt) {
JFrame myFrame = new JFrame();
JFXPanel myFXPanel = new JFXPanel();
myFrame.add(myFXPanel);
  Platform.runLater(() -> {
      BorderPane borderPane = new BorderPane();
      WebView webComponent = new WebView();

      webComponent.getEngine().load("http://google.com/");

      borderPane.setCenter(webComponent);
      Scene scene = new Scene(borderPane,450,450);
      myFXPanel.setScene(scene);
});

    }
</code>```

But when I run the program and press the Display Web Button it does nothing!
And nothing in Netbeans output displaye, No error or anything.
Where I am doing wrong?

答:
You are missing</p>

```<code>myFrame.setVisible(true);
</code>```

Body:
In my JFrame pane I wanna dislay a webview, the decare of class is :

public class MainTabbedForm extends javax.swing.JFrame {

I have added a Button named Display Weband here is the code of this :

        private void siteSurveyActionPerformed(java.awt.event.ActionEvent evt) {
JFrame myFrame = new JFrame();
JFXPanel myFXPanel = new JFXPanel();
myFrame.add(myFXPanel);
  Platform.runLater(() -> {
      BorderPane borderPane = new BorderPane();
      WebView webComponent = new WebView();

      webComponent.getEngine().load("http://google.com/");

      borderPane.setCenter(webComponent);
      Scene scene = new Scene(borderPane,450,450);
      myFXPanel.setScene(scene);
});

    }

But when I run the program and press the Display Web Button it does nothing!
And nothing in Netbeans output displaye, No error or anything.
Where I am doing wrong?

Body:
You are missing

myFrame.setVisible(true);


问:
How might I obtain a Snapshot or Thumbnail of a web page using PHP?
I need to create Snapshots / Thumbshots / Site preview a-site.com.

There are some site as thumbshot.org that meets with I need. But I do not want to use an external service, not to depend on others for my project (What would happen if they close the site?)

For this reason, I am looking for some project to let me do this.

Any idea?

答:
There's not much PHP would do for you in this situation. You'd need a complete (X)HTML rendering engine with CSS-support, possibly also with JavaScript support.

That, or use some kind of kinky script that would launch a real browser, and take a screenshot out of that. Either way, PHP is probably not the right tool for the operational part.

OwnerDisplayName: diego

OwnerDisplayName: wolfie


问:
How to Iterate through directory, ordered based on the file time
Go provides a directory iteration functionality out of the box,  with filepath.Walk in the path/filepath package.

However, filepath.Walk walks the file tree in lexical order. How can I walks the file tree in the order of last-modified date? Thx

PS (after accepting the answer) I think the Go filepath.Walk function should provide a way for people to provide the sorting themselves, like the following answer, in which accepting type ByModTime is all it take for people to sort the files themselves themselves.

答:
I think, you should implement it by yourself, because filepath.Walk doesn't allow you to set order.

Look at Walk method. It calls walk, which is relying on file names from readDirNames. So basically, you should make your own Walk method with another readDirNames logic.

Here's how you get files in the order of last-modified date (note, that I'm ignoring errors):

```<code>package main

import (
    "fmt"
    "os"
    "sort"
)

type ByModTime []os.FileInfo

func (fis ByModTime) Len() int {
    return len(fis)
}

func (fis ByModTime) Swap(i, j int) {
    fis[i], fis[j] = fis[j], fis[i]
}

func (fis ByModTime) Less(i, j int) bool {
    return fis[i].ModTime().Before(fis[j].ModTime())
}

func main() {
    f, _ := os.Open("/")
    fis, _ := f.Readdir(-1)
    f.Close()
    sort.Sort(ByModTime(fis))

    for _, fi := range fis {
        fmt.Println(fi.Name())
    }
}
</code>```

Body:
I think, you should implement it by yourself, because filepath.Walk doesn't allow you to set order.

Look at Walk method. It calls walk, which is relying on file names from readDirNames. So basically, you should make your own Walk method with another readDirNames logic.

Here's how you get files in the order of last-modified date (note, that I'm ignoring errors):

package main

import (
    "fmt"
    "os"
    "sort"
)

type ByModTime []os.FileInfo

func (fis ByModTime) Len() int {
    return len(fis)
}

func (fis ByModTime) Swap(i, j int) {
    fis[i], fis[j] = fis[j], fis[i]
}

func (fis ByModTime) Less(i, j int) bool {
    return fis[i].ModTime().Before(fis[j].ModTime())
}

func main() {
    f, _ := os.Open("/")
    fis, _ := f.Readdir(-1)
    f.Close()
    sort.Sort(ByModTime(fis))

    for _, fi := range fis {
        fmt.Println(fi.Name())
    }
}


问:
New row by enter button in input (ASP.NET MVC)
I have text input in my View

Here is code

```<code> @Html.TextAreaFor(model => model.Detail, new { @class = "greeting2", data_bind = "textInput: Detail", id = "Detail", placeholder = "Описание" })
</code>```

And  where i show text via KnockoutJS

Here is code of span

```<code><p style="font-size: 20px; margin-top: 40px; padding-left: 30px; padding-right: 40px; text-align: center;"><span data-bind="text: Detail"/>
                </p>
</code>```

Here is knockoutJS code

```<code> <script type="text/javascript">
    function ViewModel() {
        this.Greeting = ko.observable('');
        this.Detail = ko.observable('');
    };

    var vm = new ViewModel();
    ko.applyBindings(vm);

</script>
</code>```

When I write text all okay and spaces are checking. But when I click enter text will go on new row. But it in one row, like on screenshot.

Screen

How I can make new row by enter?

答:
This is actually just a styling issue, adding white-space: pre-wrap to styling for the span element should fix the issue:

```<code><p style="font-size: 20px; margin-top: 40px; padding-left: 30px; padding-right: 40px; text-align: center;"><span data-bind="text: Detail" style="white-space: pre-wrap" /></p>
</code>```

Body:
I have text input in my View

Here is code

 @Html.TextAreaFor(model => model.Detail, new { @class = "greeting2", data_bind = "textInput: Detail", id = "Detail", placeholder = "Описание" })

And  where i show text via KnockoutJS

Here is code of span

Here is knockoutJS code

When I write text all okay and spaces are checking. But when I click enter text will go on new row. But it in one row, like on screenshot.

Screen

How I can make new row by enter?

Body:
This is actually just a styling issue, adding white-space: pre-wrap to styling for the span element should fix the issue:

<p style="font-size: 20px; margin-top: 40px; padding-left: 30px; padding-right: 40px; text-align: center;"><span data-bind="text: Detail" style="white-space: pre-wrap" /></p>


问:
How to add table functionality to Extended RichTextBox control?
So, I need a WPF RichTextBox control with support for table creation (beside usual formatting stuff, hyperlinks and support for html format). Just to clarify I need the user to be able to insert table rows & columns.

The Xceed RichTextBox control from "Extended WPF Toolkit" is actually great (beside being free and open-source) except that it doesn't have the tables functionality out of the box.

I am just wondering what is the best approach to add table functionality to the control? Has anyone done this before?

Probably the answer is you just add the logic and the UI :) - similar to TinyMCE. I just wanted to know if somebody already done this and made it open-source.

答:
Try to bind the Text property of the RichTextBox to a RTF string that defines the table structure:

Using Tables in RTF

...and set the TextFormatter property to a RtfFormatter:

```<code><toolkit:RichTextBox x:Name="_richTextBox" Margin="10" BorderBrush="Gray" Padding="10"
                     Text="{Binding YourRtfSourceProperty}" ScrollViewer.VerticalScrollBarVisibility="Auto">
    <toolkit:RichTextBox.TextFormatter>
        <toolkit:RtfFormatter />
    </toolkit:RichTextBox.TextFormatter>
</toolkit:RichTextBox>
</code>```

Body:
Try to bind the Text property of the RichTextBox to a RTF string that defines the table structure:

Using Tables in RTF

...and set the TextFormatter property to a RtfFormatter:

<toolkit:RichTextBox x:Name="_richTextBox" Margin="10" BorderBrush="Gray" Padding="10"
                     Text="{Binding YourRtfSourceProperty}" ScrollViewer.VerticalScrollBarVisibility="Auto">
    <toolkit:RichTextBox.TextFormatter>
        <toolkit:RtfFormatter />
    </toolkit:RichTextBox.TextFormatter>
</toolkit:RichTextBox>


问:
Doing operations with only Nth element of a list
I want to multiply only every second number on a list(0-100) but I just can't get it to work.</p>

Body:
I want to change to list so: 1,2,3,4,5,6,7,8 becomes 1,4,3,8,5,16 etc.

Though I don't understand how you multiply 6 to end up with 16, I assume this is what you need:

new_list = []

for x in range(1,100):
  if x % 2 == 0: new_list.append(x*2)
  else: new_list.append(x)

print(new_list)

If the number is divisible by 2, you multiply it with 2 and append it to a new list. If not, you just append it without multiplying.

Running this program, you get the following output:

[1, 4, 3, 8, 5, 12, 7, 16, 9, 20, 11, 24, 13, 28, 15, 32, 17, 36, 19, 40, 21, 44, 23, 48, 25, 52, 27, 56, 29, 60, 31, 64, 33, 68, 35, 72, 37, 76, 39, 80, 41, 84, 43, 88, 45, 92, 47, 96, 49, 100, 51, 104, 53, 108, 55, 112, 57, 116, 59, 120, 61, 124, 63, 128, 65, 132, 67, 136, 69, 140, 71, 144, 73, 148, 75, 152, 77, 156, 79, 160, 81, 164, 83, 168, 85, 172, 87, 176, 89, 180, 91, 184, 93, 188, 95, 192, 97, 196, 99]


问:
How to push to next view controller from xib select button
I would like to push to ParcelPickUpViewController after I clicked a button in LocationDetailsTableViewCell xib. But I've written the code below and it able to run. But the result won't happen at all. Need help on this issue. Thanks.

In LocationDetailsTableViewCell.h

```<code>@property (nonatomic, strong) UINavigationController *viewController;
</code>```

In LocationDetailsTableViewCell.m

```<code>- (IBAction)selectBtn:(id)sender {

    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ParcelPickUpViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier: @ "pickUpVC"];
    [self.viewController pushViewController:vc animated: YES];
    [self.viewController setNavigationBarHidden:YES animated:YES];
}
</code>```

答:
(1) Make sure you have set the isInitialViewController(the first controller you want to display when app launch) in storyboard.

(2) If you did not add UINavigationController in storyboard, create it programeticaly and set it as rootViewController w.r.t your InitialViewController in app delegate didFinishLaunchingWithOptions.

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    UIStoryboard *storyboard = storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:Nil];

    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"Your_First_View_Controller_Identifier"];

    UINavigationController *rootNavigationController = [[UINavigationController alloc] initWithRootViewController:viewController];

    self.window.rootViewController = rootNavigationController;

    return YES;
}
</code>```

(3) While navigating to your ParcelPickUpViewController just simply add below code:

```<code>- (IBAction)selectBtn:(id)sender {

    ParcelPickUpViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier: @ "pickUpVC"];
    [self.navigationController pushViewController:vc animated: YES];
}
</code>```

Body:
I would like to push to ParcelPickUpViewController after I clicked a button in LocationDetailsTableViewCell xib. But I've written the code below and it able to run. But the result won't happen at all. Need help on this issue. Thanks.

In LocationDetailsTableViewCell.h

@property (nonatomic, strong) UINavigationController *viewController;

In LocationDetailsTableViewCell.m

- (IBAction)selectBtn:(id)sender {

    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ParcelPickUpViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier: @ "pickUpVC"];
    [self.viewController pushViewController:vc animated: YES];
    [self.viewController setNavigationBarHidden:YES animated:YES];
}

Body:
(1) Make sure you have set the isInitialViewController(the first controller you want to display when app launch) in storyboard.

(2) If you did not add UINavigationController in storyboard, create it programeticaly and set it as rootViewController w.r.t your InitialViewController in app delegate didFinishLaunchingWithOptions.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    UIStoryboard *storyboard = storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:Nil];

    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"Your_First_View_Controller_Identifier"];

    UINavigationController *rootNavigationController = [[UINavigationController alloc] initWithRootViewController:viewController];

    self.window.rootViewController = rootNavigationController;

    return YES;
}

(3) While navigating to your ParcelPickUpViewController just simply add below code:

- (IBAction)selectBtn:(id)sender {

    ParcelPickUpViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier: @ "pickUpVC"];
    [self.navigationController pushViewController:vc animated: YES];
}


问:
Graph to show departure and arrival times between stations
I have the start and end times of trips made by a bus, with the times in an Excel sheet. I want to make the graph as below :

I tried with Matlab nodes and graphs but did not got the exact figure, below is the Matlab code which I tried as an example:

```<code>A = [1 4]
B = [2 3]
weights = [5 5];
G = digraph(A,B,weights,4)
plot(G)
</code>```

And the figure it generates:

I have got many more than 4 points in the Excel sheet, and I want them to all be displayed as in the first image.

答:
Overview

You don't need any sort of complicated graph package for this, just use normal line plots! Here are methods in Excel and Matlab.

Excel

Give each bus stop a number, and list the bus stop number by the time it arrives/leaves there. I'll use stops number 0 and 1 for this example.

```<code>0   04:41
1   05:35
1   05:40
0   06:34
0   06:51
1   07:45
1   15:21
0   16:15
</code>```

Then simply highlight the data and insert a "scatter with straight lines"

The rest is formatting. You can format the y-axis and tick "values in reverse order" to get the time increasing as in your desired plot. You can change the x-axis tick marks to just show integer stop numbers, get rid of the legend etc.

Final output:

Matlab

Here is the Matlab documentation for converting Excel formatted dates into Matlab datetime arrays: Convert Excel Date Number to Datetime.

Once you have the datetime objects, you can do this easily with the standard plot function.

% Set times up as a datetime array, could do this any number of ways
times = datetime(strcat({'1/1/2000 '}, {'04:41', '05:35', '05:40', '06:34', '06:51', '07:45', '15:21', '16:15'}, ':00'), 'format', 'dd/MM/yyyy HH:mm:ss');
% Set up the location of the bus at each of the above times
station = [0,1,1,0,0,1,1,0];
% Plot
plot(station, times)              % Create plot
set(gca, 'xtick', [0,1])          % Limit to just ticks at the 2 stops
set(gca, 'ydir', 'reverse')       % Reverse y axis to have earlier at top
set(gca,'XTickLabel',{'R', 'L'})  % Name the stops
```

Output:

Body:
I have the start and end times of trips made by a bus, with the times in an Excel sheet. I want to make the graph as below :

I tried with Matlab nodes and graphs but did not got the exact figure, below is the Matlab code which I tried as an example:

A = [1 4]
B = [2 3]
weights = [5 5];
G = digraph(A,B,weights,4)
plot(G)

And the figure it generates:

I have got many more than 4 points in the Excel sheet, and I want them to all be displayed as in the first image.

Body:
Overview

You don't need any sort of complicated graph package for this, just use normal line plots! Here are methods in Excel and Matlab.

Excel

Give each bus stop a number, and list the bus stop number by the time it arrives/leaves there. I'll use stops number 0 and 1 for this example.

0   04:41
1   05:35
1   05:40
0   06:34
0   06:51
1   07:45
1   15:21
0   16:15

Then simply highlight the data and insert a "scatter with straight lines"

The rest is formatting. You can format the y-axis and tick "values in reverse order" to get the time increasing as in your desired plot. You can change the x-axis tick marks to just show integer stop numbers, get rid of the legend etc.

Final output:

Matlab

Here is the Matlab documentation for converting Excel formatted dates into Matlab datetime arrays: Convert Excel Date Number to Datetime.

Once you have the datetime objects, you can do this easily with the standard plot function.

% Set times up as a datetime array, could do this any number of ways
times = datetime(strcat({'1/1/2000 '}, {'04:41', '05:35', '05:40', '06:34', '06:51', '07:45', '15:21', '16:15'}, ':00'), 'format', 'dd/MM/yyyy HH:mm:ss');
% Set up the location of the bus at each of the above times
station = [0,1,1,0,0,1,1,0];
% Plot
plot(station, times)              % Create plot
set(gca, 'xtick', [0,1])          % Limit to just ticks at the 2 stops
set(gca, 'ydir', 'reverse')       % Reverse y axis to have earlier at top
set(gca,'XTickLabel',{'R', 'L'})  % Name the stops

Output:


答:
If you want this expected output just replace the 2nd part by</p>

```<code>var MainInfo=[];
        for (i = 0; i < data.length; i++) {

            var obj = {}
            obj.BuildingID = data[i].BuildingID;
            obj.FloorId = data[i].FloorId;
            obj.one = data[i].volume[0].one;
            obj.three = data[i].volume[0].three;
            obj.two = data[i].volume[0].two;

            MainInfo.push(obj);

        }
</code>```

Title: how to push sub array object into an a array in javascript

Body:
If you want this expected output just replace the 2nd part by

var MainInfo=[];
        for (i = 0; i < data.length; i++) {

            var obj = {}
            obj.BuildingID = data[i].BuildingID;
            obj.FloorId = data[i].FloorId;
            obj.one = data[i].volume[0].one;
            obj.three = data[i].volume[0].three;
            obj.two = data[i].volume[0].two;

            MainInfo.push(obj);

        }


问:
How to get FLAT relief Entry widget in python ttk?
I am writing a GUI FTP client app in python ttk. I can't seem to get the text Entries the way I wanted them to.

The text Entries have the "SUNKEN" effect. I want to adjust the height and get the text entries to have a "FLAT" look, more like this program:

I got the buttons to look flat from here, I am struggling to get the Entries to look flat.

How do I get the Entries to look flat?

I don't want a tk solution, I know how to set relief FLAT in tk.

答:
Trivia:

Appereance of ttk widgets heavily depends on theme in use and/or platform. On windows I can reproduce this depressive gray style with a classic theme, so let's assume that this theme in use. List of themes you can find here (note the 'clam' theme, wich is most similar to your wishes), just if you wonder.

Next stop, our layout or, in other words, a structure of widget's theme.
You can easily print this structure to see available options. Enough words, let's try a structure of an ttk.Entry widget.

```<code>>>> print(s.layout('TEntry'))

#   formatted result, actual result is one-line string
[('Entry.highlight', {
    'sticky': 'nswe',
    'children': [(
        'Entry.field', {
            'sticky': 'nswe',
            'children': [(
                'Entry.padding', {
                    'sticky': 'nswe',
                    'children': [(
                        'Entry.textarea', {
                            'sticky': 'nswe'})]
                })],
            'border': '1'})]
})]
</code>```

As you can see, noone of structure elements has a relief option, hence relief='flat' has no effect on our entry!

```<code>>>> print(s.element_options('Entry.field'))
('-bordercolor', '-lightcolor', '-darkcolor', '-fieldbackground')
</code>```

Workaround:

However, we can edit the layout of desired widget, and replace one element with another, wich able to recognize a relief option (note a removed Entry.field, replaced with an Entry.border).

So try out this little snippet:

```<code>try:
    import tkinter as tk
    import tkinter.ttk as ttk
except ImportError:
    import Tkinter as tk
    import ttk

#   root
root = tk.Tk()

#   declare style variable
s = ttk.Style()
#   assume that classic theme in use
s.theme_use('classic')

#   configure relief
s.configure('SOExample.TEntry', relief='flat')

#   lets try to change this structure
s.layout('SOExample.TEntry', [
    ('Entry.highlight', {
        'sticky': 'nswe',
        'children':
            [('Entry.border', {
                'border': '1',
                'sticky': 'nswe',
                'children':
                    [('Entry.padding', {
                        'sticky': 'nswe',
                        'children':
                            [('Entry.textarea',
                              {'sticky': 'nswe'})]
                    })]
            })]
    })])

#   let's find some differences between this two
print(s.layout('SOExample.TEntry'))
print(s.layout('TEntry'))

#    packing
frame1 = tk.Frame(root)
label1 = tk.Label(frame1, text='Flat Entry')
entry1 = ttk.Entry(frame1, style='SOExample.TEntry')
label1.pack()
entry1.pack()
frame1.pack(side='left')

frame2 = tk.Frame(root)
label2 = tk.Label(frame2, text='Default Entry')
entry2 = ttk.Entry(frame2)
label2.pack()
entry2.pack()
frame2.pack(side='right')

#   mainloop
root.mainloop()
</code>```

...and final appereance is:

Also, on my machine default theme is vista and there I can't even recognize an entry:

And also a structure of an Entry depends on theme, so with vista it's:

```<code>#   formatted result, actual result is one-line string
[('Entry.field', {
    'sticky': 'nswe',
    'children': [(
        'Entry.background', {
            'sticky': 'nswe',
            'children': [(
                'Entry.padding', {
                    'sticky': 'nswe',
                    'children': [(
                        'Entry.textarea', {
                            'sticky': 'nswe'})]
                })]
        })]
})]
</code>```

...and if we replace a field with border element in this structure, the appearence is very close to your demands (also try groove relief in this case):

Conclusion:

Unfortunately, this widget will lack options of field and border color, so another option is create own element for this purpose, but that is another question.

So, basicly I tryied to answer not "how to workaround this", but "why a relief has no effect on Entry", anyway as you can see, a flat relief for an Entry is achievable.

Body:
Trivia:

Appereance of ttk widgets heavily depends on theme in use and/or platform. On windows I can reproduce this depressive gray style with a classic theme, so let's assume that this theme in use. List of themes you can find here (note the 'clam' theme, wich is most similar to your wishes), just if you wonder.

Next stop, our layout or, in other words, a structure of widget's theme.
You can easily print this structure to see available options. Enough words, let's try a structure of an ttk.Entry widget.

>>> print(s.layout('TEntry'))

#   formatted result, actual result is one-line string
[('Entry.highlight', {
    'sticky': 'nswe',
    'children': [(
        'Entry.field', {
            'sticky': 'nswe',
            'children': [(
                'Entry.padding', {
                    'sticky': 'nswe',
                    'children': [(
                        'Entry.textarea', {
                            'sticky': 'nswe'})]
                })],
            'border': '1'})]
})]

As you can see, noone of structure elements has a relief option, hence relief='flat' has no effect on our entry!

>>> print(s.element_options('Entry.field'))
('-bordercolor', '-lightcolor', '-darkcolor', '-fieldbackground')

Workaround:

However, we can edit the layout of desired widget, and replace one element with another, wich able to recognize a relief option (note a removed Entry.field, replaced with an Entry.border).

So try out this little snippet:

try:
    import tkinter as tk
    import tkinter.ttk as ttk
except ImportError:
    import Tkinter as tk
    import ttk

#   root
root = tk.Tk()

#   declare style variable
s = ttk.Style()
#   assume that classic theme in use
s.theme_use('classic')

#   configure relief
s.configure('SOExample.TEntry', relief='flat')

#   lets try to change this structure
s.layout('SOExample.TEntry', [
    ('Entry.highlight', {
        'sticky': 'nswe',
        'children':
            [('Entry.border', {
                'border': '1',
                'sticky': 'nswe',
                'children':
                    [('Entry.padding', {
                        'sticky': 'nswe',
                        'children':
                            [('Entry.textarea',
                              {'sticky': 'nswe'})]
                    })]
            })]
    })])

#   let's find some differences between this two
print(s.layout('SOExample.TEntry'))
print(s.layout('TEntry'))

#    packing
frame1 = tk.Frame(root)
label1 = tk.Label(frame1, text='Flat Entry')
entry1 = ttk.Entry(frame1, style='SOExample.TEntry')
label1.pack()
entry1.pack()
frame1.pack(side='left')

frame2 = tk.Frame(root)
label2 = tk.Label(frame2, text='Default Entry')
entry2 = ttk.Entry(frame2)
label2.pack()
entry2.pack()
frame2.pack(side='right')

#   mainloop
root.mainloop()

...and final appereance is:

Also, on my machine default theme is vista and there I can't even recognize an entry:

And also a structure of an Entry depends on theme, so with vista it's:

#   formatted result, actual result is one-line string
[('Entry.field', {
    'sticky': 'nswe',
    'children': [(
        'Entry.background', {
            'sticky': 'nswe',
            'children': [(
                'Entry.padding', {
                    'sticky': 'nswe',
                    'children': [(
                        'Entry.textarea', {
                            'sticky': 'nswe'})]
                })]
        })]
})]

...and if we replace a field with border element in this structure, the appearence is very close to your demands (also try groove relief in this case):

Conclusion:

Unfortunately, this widget will lack options of field and border color, so another option is create own element for this purpose, but that is another question.

So, basicly I tryied to answer not "how to workaround this", but "why a relief has no effect on Entry", anyway as you can see, a flat relief for an Entry is achievable.


问:
Use reflection to fill array of derived class with array of base class
Consider following problem:
I want to fill an array of type T with values at runtime. I am able to get all the GameObjects (talking about Unity3D here) which hold one of these instances. These GameObjects are in the results array. The GetComponent method allows to extract the instances of T from the gameObject, but autmatically casts it to Ts base class Component. blueprint contains information about the binding target, like the FieldInfo of the array.

The current code looks like this:

```<code>var arrayOfBaseClass =
    (
        from instance
        in results
        select instance.GetComponent(blueprint.Field.FieldType.GetElementType()))
    .ToArray();
// Missing Step here
blueprint.Field.SetValue(o, arrayOfBaseClass);
</code>```

SetValue throws right now ArgumentException: Object type UnityEngine.Component[] cannot be converted to target type: VEL.Input.ActionSignalReceiver[]

Additional info arrayOfBaseClass is actually an array of instaces of T, just cast to the base type by GetComponent. If I knew T beforehand a manual cast to T would work and solve this problem. Sadly T is not know beforehand and may vary between different types (yet all derive from Component)

The question now is if there is a way to use the information of FieldInfo to cast the array back to its most derived type.

答:
Figured it out with some trial and error, will post relevant code below explanation.
As we are working within reflection we need a way to pass into the type of the target we want to use. In this case we can do it by constructing a generic method at runtime.

So first we declare a generic function, which takes a target object, a fieldInfo (beforehand it is checked that this is an array field) and an array of objects. These objects are cast to the target type T and then assigned to the field:

```<code>public void BindToTypedArray<T> (object bindingTarget, FieldInfo field, object[] values)
    {
        var typedArray = from v in values select (T)v;
        field.SetValue(bindingTarget, typedArray.ToArray());
    }
</code>```

To call this function we need to know the type T, but reflection offers a method to created a typed generic method at runtime via MakeGenericMethod. So what we do in the example above is that we create a custom typed instance of the function above and feed in the object array we generated:

```<code>    var arrayOfBaseClass =
        (
            from instance
            in results
            select instance.GetComponent(blueprint.Field.FieldType.GetElementType()))
        .ToArray();

    // NEWCODE --------------------------------------------------------
    MethodInfo bindArray= typeof(DataGlueController).GetMethod("BindToTypedArray");
    MethodInfo bindArrayTyped=bindArray.MakeGenericMethod(blueprint.Field.FieldType.GetElementType());
    bindArrayTyped.Invoke(this, new object[] { o, blueprint.Field, arrayOfBaseClass });
    // END NEWCODE ----------------------------------------------------

    // blueprint.Field.SetValue(o, arrayOfBaseClass); <- this is done in the BindToTypedArray function
</code>```

Body:
Consider following problem:
I want to fill an array of type T with values at runtime. I am able to get all the GameObjects (talking about Unity3D here) which hold one of these instances. These GameObjects are in the results array. The GetComponent method allows to extract the instances of T from the gameObject, but autmatically casts it to Ts base class Component. blueprint contains information about the binding target, like the FieldInfo of the array.

The current code looks like this:

var arrayOfBaseClass =
    (
        from instance
        in results
        select instance.GetComponent(blueprint.Field.FieldType.GetElementType()))
    .ToArray();
// Missing Step here
blueprint.Field.SetValue(o, arrayOfBaseClass);

SetValue throws right now ArgumentException: Object type UnityEngine.Component[] cannot be converted to target type: VEL.Input.ActionSignalReceiver[]

Additional info arrayOfBaseClass is actually an array of instaces of T, just cast to the base type by GetComponent. If I knew T beforehand a manual cast to T would work and solve this problem. Sadly T is not know beforehand and may vary between different types (yet all derive from Component)

The question now is if there is a way to use the information of FieldInfo to cast the array back to its most derived type.

Body:
Figured it out with some trial and error, will post relevant code below explanation.
As we are working within reflection we need a way to pass into the type of the target we want to use. In this case we can do it by constructing a generic method at runtime.

So first we declare a generic function, which takes a target object, a fieldInfo (beforehand it is checked that this is an array field) and an array of objects. These objects are cast to the target type T and then assigned to the field:

public void BindToTypedArray<T> (object bindingTarget, FieldInfo field, object[] values)
    {
        var typedArray = from v in values select (T)v;
        field.SetValue(bindingTarget, typedArray.ToArray());
    }

To call this function we need to know the type T, but reflection offers a method to created a typed generic method at runtime via MakeGenericMethod. So what we do in the example above is that we create a custom typed instance of the function above and feed in the object array we generated:

    var arrayOfBaseClass =
        (
            from instance
            in results
            select instance.GetComponent(blueprint.Field.FieldType.GetElementType()))
        .ToArray();

    // NEWCODE --------------------------------------------------------
    MethodInfo bindArray= typeof(DataGlueController).GetMethod("BindToTypedArray");
    MethodInfo bindArrayTyped=bindArray.MakeGenericMethod(blueprint.Field.FieldType.GetElementType());
    bindArrayTyped.Invoke(this, new object[] { o, blueprint.Field, arrayOfBaseClass });
    // END NEWCODE ----------------------------------------------------

    // blueprint.Field.SetValue(o, arrayOfBaseClass); <- this is done in the BindToTypedArray function


问:
An exception of type 'System.ArgumentException' occurred in Google.Apis.dll but was not handled in user code
I am trying to connect Google Drive Service client but I am getting this exception and I am not getting any solution. Here is my code.

```<code>public static DriveService GetDriveClient()
    {
        var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets { ClientId = clientID, ClientSecret = clientSecret }
                , scopes
                , Environment.UserName
                , CancellationToken.None
                , new FileDataStore(credPath, true)
            ).Result;

        // Create Drive API service.
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = appName,
        });

        return service;
    }
</code>```

I am getting following error in yellow screen:

Invalid Application name
Parameter name: ApplicationName

答:
The appName value you are using to set ApplicationName is invalid.

ApplicationName is used directly in the HTTP User-Agent header, so must conform to the token specification in on RFC2616 page 17.

As of release v1.27.0 this uses the System.Net.Http.Headers.ProductInfoHeaderValue.TryParse() method to check validity. See BaseClientService.cs line 120

Body:
I am trying to connect Google Drive Service client but I am getting this exception and I am not getting any solution. Here is my code.

public static DriveService GetDriveClient()
    {
        var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets { ClientId = clientID, ClientSecret = clientSecret }
                , scopes
                , Environment.UserName
                , CancellationToken.None
                , new FileDataStore(credPath, true)
            ).Result;

        // Create Drive API service.
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = appName,
        });

        return service;
    }

I am getting following error in yellow screen:

Invalid Application name
Parameter name: ApplicationName


问:
angular 2 websql typings
I am writing an app in electron using angular 4. I need a database and want to use websql but I cannot find a way to import websql typings.

I added @types/websql. In my IDE, there is no compil error when i do :

```<code>const db: Database = window.openDatabase('foo', '1.0', 'foo', 2 * 1024 * 1024);
</code>```

but ng serve gives me :

```<code>Property 'openDatabase' does not exist on type 'Window'
</code>```

I do not have any import specific to @types/websql. As it is not a module, I don't know how to import it.

Does anyone have any idea on how I can import this ?

答:
Ok, I found the solution.

ng-cli generate a tsconfig.app.json with a property types set to [].
If I understand tsc doc correctly, it prevents the compiler to use the typeRoots property.

By simply removing this property, my code compile.

Title: angular 2 websql typings

Body:
I am writing an app in electron using angular 4. I need a database and want to use websql but I cannot find a way to import websql typings.

I added @types/websql. In my IDE, there is no compil error when i do :

const db: Database = window.openDatabase('foo', '1.0', 'foo', 2 * 1024 * 1024);

but ng serve gives me :

Property 'openDatabase' does not exist on type 'Window'

I do not have any import specific to @types/websql. As it is not a module, I don't know how to import it.

Does anyone have any idea on how I can import this ?


问:
iOS 11 Core NFC - any sample code?
I just installed the first iOS 11 beta to an iPhone 7 and am interested in trying the NFC. There's nothing about it in settings.  I am wondering if there's any sample code out there showing how to read a tag. Can anyone show how to use the Core NFC SDK, in a code snippet?</p>

答:
To fix this issue you can add com.apple.developer.nfc.readersession.formats key into your entitlements file. The key should be associated with the array of enabled NFS types.
For instance, you can try the following:

<key>com.apple.developer.nfc.readersession.formats</key>
<array>
    <string>NDEF</string>
</array>
```

It worked for me.

Title: iOS 11 Core NFC - any sample code?

Body:
To fix this issue you can add com.apple.developer.nfc.readersession.formats key into your entitlements file. The key should be associated with the array of enabled NFS types.
For instance, you can try the following:

<key>com.apple.developer.nfc.readersession.formats</key>
<array>
    <string>NDEF</string>
</array>

It worked for me.


问:
Equivalent to GOTO in conditions, Python
Since there is no goto operator in Python, what technique can be used instead?

Condition
If it is true, go to thread 1, if is false, go to thread 2
In thread we do something small and after that we go to thread 2 where all other actions take place.

答:
Python is designed to support good coding practices and GOTO is not one of them. It may lead to unreadable program logic, if not used properly.

I suggest to learn code your program in a Python way, do not stick with (sometimes bad) habits from other programming languages. See Python documentation, real mature Python programs and learn.


问:
Intellisense missing for ajax with jQuery in Visual Studio 2010

I'm new in ASP.NET, I'm making a website and I need ajax to do something. But when I try to call ajax in jQuery, it doesn't appear after $. sign. I have downloaded latest version jQuery. I'm using Visual Studio 2010.

I took a picture for my problem. I tried some soluntion above but ajax still not work.The picture for my problem

答: Thank you everyone for helping me. I found the solution for my problem. I search on google for jquery older version (1.8.0) and i copy all code in that jquery then paste it in my jquery file. After do that i can call ajax.My picture</p>


问:
The distance of two point which SDO_CLOSEST_POINTS returns is not the same as dist itself returns
When i query distance between two Geometries like this:

```<code>DECLARE
  dist  NUMBER;
  geoma SDO_GEOMETRY;
  geomb SDO_GEOMETRY;

BEGIN
  SDO_GEOM.SDO_CLOSEST_POINTS(sdo_geometry('POINT(10 10)', 4326),
                              sdo_geometry('POLYGON((0 0, 2 0, 2 2, 0 2, 0 0))',
                                           4326),
                              0.005,
                              NULL,
                              dist,
                              geoma,
                              geomb);
  insert into test (info, geom1, geom2) values (dist, geoma, geomb);

END;
</code>```

It returns like this:

info:1254057.74485897

geom1: 10,10

geom2: 2,2

But when i query the distance between the two points:

```<code>SELECT sdo_geom.sdo_distance(sdo_geom.sdo_geometry('POINT(10 10)', 4326),
                             sdo_geom.sdo_geometry('POINT(2 2)',
                                                   4326),
                             0.0001,
                             'unit=M') distance_in_m
  from DUAL;
</code>```

It returns :1251344.03770147

Why the distances are not the same?How it happen?
Thanks for anyone who will give me some idea.

答:
Following the SDO_GEOMETRY documentation gives a different way of specifying shapes. Using this, the values are the same:

```<code>DECLARE
  d1 NUMBER;
  d2 NUMBER;
  d3 NUMBER;
  g1 SDO_GEOMETRY := SDO_GEOMETRY(
                      2003,                              -- 2 dimensional polygon,
                      NULL,                              -- No SRID / Co-ordinate System
                      NULL,                              -- SDO_POINT,
                      SDO_ELEM_INFO_ARRAY( 1, 1003, 3 ), -- Rectangle exterior
                      SDO_ORDINATE_ARRAY( 0,0, 2,2 )     -- Corners
                     );
  g2 SDO_GEOMETRY := SDO_GEOMETRY(
                      2001,                              -- 2 dimensional point,
                      NULL,                              -- No SRID / Co-ordinate System
                      SDO_POINT_TYPE(10,10,NULL),        -- SDO_POINT,
                      NULL,                              -- Not an array
                      NULL                               -- Not an array
                     );
  g3 SDO_GEOMETRY := SDO_GEOMETRY(
                      2001,                              -- 2 dimensional point,
                      NULL,                              -- No SRID / Co-ordinate System
                      SDO_POINT_TYPE(2,2,NULL),        -- SDO_POINT,
                      NULL,                              -- Not an array
                      NULL                               -- Not an array
                     );
  ga SDO_GEOMETRY;
  gb SDO_GEOMETRY
BEGIN
  SDO_GEOM.SDO_CLOSEST_POINTS(
    geom1     => g1,
    geom2     => g2,
    tolerance => 0.005,
    unit      => NULL,
    dist      => d1,
    geoma     => ga,
    geomb     => gb
  );

  d2 := SDO_GEOM.SDO_DISTANCE( g2, g3, 0.0001, NULL );

  d3 := SDO_GEOM.SDO_DISTANCE( g1, g3, 0.0001, NULL );

  DBMS_OUTPUT.PUT_LINE( d1 || ', ' || d2 || ', ' || d3 );
END;
/
</code>```

Outputs:

```<code>11.3137084989848, 11.3137084989848, 11.3137084989848
</code>```

As an added bonus, the distance is now SQRT(8*8 + 8*8) which is the Cartesian distance from (2,2) to (10,10) and you can also use SDO_DISTANCE with either the polygon or the point for the same answer.

Body:
When i query distance between two Geometries like this:

DECLARE
  dist  NUMBER;
  geoma SDO_GEOMETRY;
  geomb SDO_GEOMETRY;

BEGIN
  SDO_GEOM.SDO_CLOSEST_POINTS(sdo_geometry('POINT(10 10)', 4326),
                              sdo_geometry('POLYGON((0 0, 2 0, 2 2, 0 2, 0 0))',
                                           4326),
                              0.005,
                              NULL,
                              dist,
                              geoma,
                              geomb);
  insert into test (info, geom1, geom2) values (dist, geoma, geomb);

END;

It returns like this:

info:1254057.74485897

geom1: 10,10

geom2: 2,2

But when i query the distance between the two points:

SELECT sdo_geom.sdo_distance(sdo_geom.sdo_geometry('POINT(10 10)', 4326),
                             sdo_geom.sdo_geometry('POINT(2 2)',
                                                   4326),
                             0.0001,
                             'unit=M') distance_in_m
  from DUAL;

It returns :1251344.03770147

Why the distances are not the same?How it happen?
Thanks for anyone who will give me some idea.

Body:
Following the SDO_GEOMETRY documentation gives a different way of specifying shapes. Using this, the values are the same:

DECLARE
  d1 NUMBER;
  d2 NUMBER;
  d3 NUMBER;
  g1 SDO_GEOMETRY := SDO_GEOMETRY(
                      2003,                              -- 2 dimensional polygon,
                      NULL,                              -- No SRID / Co-ordinate System
                      NULL,                              -- SDO_POINT,
                      SDO_ELEM_INFO_ARRAY( 1, 1003, 3 ), -- Rectangle exterior
                      SDO_ORDINATE_ARRAY( 0,0, 2,2 )     -- Corners
                     );
  g2 SDO_GEOMETRY := SDO_GEOMETRY(
                      2001,                              -- 2 dimensional point,
                      NULL,                              -- No SRID / Co-ordinate System
                      SDO_POINT_TYPE(10,10,NULL),        -- SDO_POINT,
                      NULL,                              -- Not an array
                      NULL                               -- Not an array
                     );
  g3 SDO_GEOMETRY := SDO_GEOMETRY(
                      2001,                              -- 2 dimensional point,
                      NULL,                              -- No SRID / Co-ordinate System
                      SDO_POINT_TYPE(2,2,NULL),        -- SDO_POINT,
                      NULL,                              -- Not an array
                      NULL                               -- Not an array
                     );
  ga SDO_GEOMETRY;
  gb SDO_GEOMETRY
BEGIN
  SDO_GEOM.SDO_CLOSEST_POINTS(
    geom1     => g1,
    geom2     => g2,
    tolerance => 0.005,
    unit      => NULL,
    dist      => d1,
    geoma     => ga,
    geomb     => gb
  );

  d2 := SDO_GEOM.SDO_DISTANCE( g2, g3, 0.0001, NULL );

  d3 := SDO_GEOM.SDO_DISTANCE( g1, g3, 0.0001, NULL );

  DBMS_OUTPUT.PUT_LINE( d1 || ', ' || d2 || ', ' || d3 );
END;
/

Outputs:

11.3137084989848, 11.3137084989848, 11.3137084989848

As an added bonus, the distance is now SQRT(8*8 + 8*8) which is the Cartesian distance from (2,2) to (10,10) and you can also use SDO_DISTANCE with either the polygon or the point for the same answer.


问:
How to group multiple views in a ConstraintLayout
I have added 3 buttons in a ConstraintLayout. I have added a button to disable or enable these buttons.

If I was using normal LinearLayout. I could have put all the buttons in a Linear Layout and enable or disable that particular layout.

But I am using ConstraintLayout. So I need to disable or enable all of these buttons, I believe that there must be a way in ConstraintLayout to group different views.

Kindly guide me how to group views in ConstriantLayout

```<code>  <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="16dp"
        android:layout_marginStart="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="16dp" />

    <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="16dp"
        android:layout_marginStart="8dp"
        app:layout_constraintLeft_toRightOf="@+id/button"
        android:layout_marginLeft="8dp"
        app:layout_constraintTop_toTopOf="@+id/button" />

    <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button3"
        app:layout_constraintTop_toTopOf="@+id/button2"
        android:layout_marginEnd="16dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginRight="16dp"
        android:layout_marginStart="8dp"
        app:layout_constraintLeft_toRightOf="@+id/button2"
        android:layout_marginLeft="8dp" />
</code>```

答:
Yes, as I know you can handle visibility using linear layout but not Enable/Disable views I think, correct me if I am wrong. So now in ConstraintLayout also we can handle visibility of particular group of views using the Group

<android.support.constraint.Group/>

This is new feature introduced in ConstraintLayout which is currently
in Beta version.

How to add beta ConstraintLayout to project follow steps below

add maven support in project gradle file as below

```<code>allprojects {
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
}
</code>```

then in app gardle dependencies add ConstarintLayout library dependency

```<code>compile 'com.android.support.constraint:constraint-layout:1.1.0-beta3'
</code>```

now you have to add group in your ConstraintLayout as follow

```<code><android.support.constraint.Group
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:constraint_referenced_ids="button7,button3,button2"
        android:id="@+id/group" />
</code>```

where in Group reference id

```<code>app:constraint_referenced_ids="button7,button3,button2"
</code>```

contains the comma separated view id's you want to handle run time, so in activity you just bind Group as below and handle visibility

```<code>import android.support.constraint.Group; //import statement in activity

Group group=(Group)findViewById(R.id.group);//bind view from xml
group.setVisibility(View.VISIBLE);//this will visible all views
group.setVisibility(View.GONE);//this will set Gone to all views
group.setVisibility(View.INVISIBLE);//this will set INVISIBLE to all view
</code>```

Edit: ConstraintLayout 1.1.0 stable version released on 12 April 2018
https://androidstudio.googleblog.com/2018/04/constraintlayout-110.html

```<code>implementation 'com.android.support.constraint:constraint-layout:1.1.0'
</code>```

Edit: Android X
If anyone using android x package you can find package info here

https://developer.android.com/jetpack/androidx/migrate

and use:

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

Body:
I have added 3 buttons in a ConstraintLayout. I have added a button to disable or enable these buttons.

If I was using normal LinearLayout. I could have put all the buttons in a Linear Layout and enable or disable that particular layout.

But I am using ConstraintLayout. So I need to disable or enable all of these buttons, I believe that there must be a way in ConstraintLayout to group different views.

Kindly guide me how to group views in ConstriantLayout

  <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="16dp"
        android:layout_marginStart="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="16dp" />

    <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="16dp"
        android:layout_marginStart="8dp"
        app:layout_constraintLeft_toRightOf="@+id/button"
        android:layout_marginLeft="8dp"
        app:layout_constraintTop_toTopOf="@+id/button" />

    <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button3"
        app:layout_constraintTop_toTopOf="@+id/button2"
        android:layout_marginEnd="16dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginRight="16dp"
        android:layout_marginStart="8dp"
        app:layout_constraintLeft_toRightOf="@+id/button2"
        android:layout_marginLeft="8dp" />

Body:
Yes, as I know you can handle visibility using linear layout but not Enable/Disable views I think, correct me if I am wrong. So now in ConstraintLayout also we can handle visibility of particular group of views using the Group

<android.support.constraint.Group/>

This is new feature introduced in ConstraintLayout which is currently
in Beta version.

How to add beta ConstraintLayout to project follow steps below

add maven support in project gradle file as below

allprojects {
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
}

then in app gardle dependencies add ConstarintLayout library dependency

compile 'com.android.support.constraint:constraint-layout:1.1.0-beta3'

now you have to add group in your ConstraintLayout as follow

<android.support.constraint.Group
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:constraint_referenced_ids="button7,button3,button2"
        android:id="@+id/group" />

where in Group reference id

app:constraint_referenced_ids="button7,button3,button2"

contains the comma separated view id's you want to handle run time, so in activity you just bind Group as below and handle visibility

import android.support.constraint.Group; //import statement in activity

Group group=(Group)findViewById(R.id.group);//bind view from xml
group.setVisibility(View.VISIBLE);//this will visible all views
group.setVisibility(View.GONE);//this will set Gone to all views
group.setVisibility(View.INVISIBLE);//this will set INVISIBLE to all view

Edit: ConstraintLayout 1.1.0 stable version released on 12 April 2018
https://androidstudio.googleblog.com/2018/04/constraintlayout-110.html

implementation 'com.android.support.constraint:constraint-layout:1.1.0'

Edit: Android X
If anyone using android x package you can find package info here

https://developer.android.com/jetpack/androidx/migrate

and use:

<androidx.constraintlayout.widget.Group />


问:
Easiest way to check ip address against a range of values using c#
We are writing a feature that allows an administrator to block/allow ranges of ip addresses.

Is this easy enough to do with c#?

I was thinking of looking at each number [here].[here].[here].[here] and then mathing it with the ranges and just seeing if each number was between the two?

Will that work for standard ip v4 addresses?

答:
```<code>public static bool CheckIfIpValid(string allowedStartIp, string allowedEndIp, string ip)
        {
            // if both start and end ip's are null, every user with these credential can log in, no ip restriction needed.

        if (string.IsNullOrEmpty(allowedStartIp) && string.IsNullOrEmpty(allowedEndIp))
            return true;
        bool isStartNull = string.IsNullOrEmpty(allowedStartIp),
            isEndNull = string.IsNullOrEmpty(allowedEndIp);
        string[] startIpBlocks, endIpBlocks, userIp = ip.Split('.');
        if (!string.IsNullOrEmpty(allowedStartIp))
            startIpBlocks = allowedStartIp.Split('.');
        else
            startIpBlocks = "0.0.0.0".Split('.');
        if (!string.IsNullOrEmpty(allowedEndIp))
            endIpBlocks = allowedEndIp.Split('.');
        else
            endIpBlocks = "999.999.999.999".Split('.');

        for (int i = 0; i < userIp.Length; i++)
        {
            // if current block is smaller than allowed minimum, ip is not valid.
            if (Convert.ToInt32(userIp[i]) < Convert.ToInt32(startIpBlocks[i]))
                return false;
            // if current block is greater than allowed maximum, ip is not valid.
            else if (Convert.ToInt32(userIp[i]) > Convert.ToInt32(endIpBlocks[i]))
                return false;
            // if current block is greater than allowed minimum, ip is valid.
            else if ((Convert.ToInt32(userIp[i]) > Convert.ToInt32(startIpBlocks[i])) && !isStartNull)
                return true;

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


问:
Laravel mix: how to execute a PHP Lint?
Prologue: I'm playing for the first time with Laravel.

I'd like to use the 'laravel-mix' to run a php lint on my php files when file changes.

Is this doable?

I looked at official doc about Laravel-mix but I found no examples about PHP files

答:
At the end I understand that It's not possible.

Laravel right tool is Envoy. I created Enojy tasks/stories and all now can run well

Title: Laravel mix: how to execute a PHP Lint?


问:
Angular Form Template One-Way Data Binding
I am attempting to one-way bind to a default value in my HTML form.

My component has a Connection string that is being initialized from local storage:

export class AuthAdminComponent implements OnInit {

  public authenticated = false;
  public connection: String
  public username: string;
  public password: string;
  public token: string;

  constructor(private authService: AuthService, private router: Router) {

   }

  ngOnInit() {
    if(localStorage.getItem('adminUser')) {
      let data = JSON.parse(localStorage.getItem('adminUser'));
      this.connection = data.connection;
      this.username = data.username;
      this.password = data.password;    }
  }
}
```

<p>Then in my form I am attempting to one-way bind to these properties such as connection.  However, it returns [object Object].  I can't seem to figure out how to get the actual value:</p>

<pre class="lang-html prettyprint-override"><code><label for="connection">Connection</label>
            <input
            class="input__username"
            type="text"
            name="connection"
            required
            [ngModel]="connection"
            #connection="ngModel" />
            <span *ngIf="!connection.valid && connection.touched">Please enter a valid connection string.</span>
</code>```

I'm sure it's something simple that I'm misunderstanding.  If someone could explain to me what I'm missing, I'd greatly appreciate it.  Thanks!

答:
Here's your problem:

You're trying to bind ngModel to connection which is a variable defined in your class.

On the other hand you defined #connection as a reference variable on the input element.

As a result ngModel will bind to this variable and not to the one defined in your class.

One possible solution would be to rename #connection to #connect (or you can rename connection in your class and bind ngModel to the renamed variable in your template).

This should fix the problem.

Body:
I am attempting to one-way bind to a default value in my HTML form.

My component has a Connection string that is being initialized from local storage:

export class AuthAdminComponent implements OnInit {

  public authenticated = false;
  public connection: String
  public username: string;
  public password: string;
  public token: string;

  constructor(private authService: AuthService, private router: Router) {

   }

  ngOnInit() {
    if(localStorage.getItem('adminUser')) {
      let data = JSON.parse(localStorage.getItem('adminUser'));
      this.connection = data.connection;
      this.username = data.username;
      this.password = data.password;    }
  }
}

Then in my form I am attempting to one-way bind to these properties such as connection.  However, it returns [object Object].  I can't seem to figure out how to get the actual value:

Connection
            <input
            class="input__username"
            type="text"
            name="connection"
            required
            [ngModel]="connection"
            #connection="ngModel" />
            Please enter a valid connection string.

I'm sure it's something simple that I'm misunderstanding.  If someone could explain to me what I'm missing, I'd greatly appreciate it.  Thanks!


问:
how to push sub array object into an a array in javascript
hi all i am using javascript i am trying to push object values into one array here i attached my code

```<code>var data = [{
            BuildingID: "56", FloorId: "65", volume: [{

                one: 12,
                two: 15,
                three: 12
            }]
        }]

var MainInfo=[];
            for (i = 0; i < data.length; i++) {

                var obj = {}
                obj.BuildingID = data[i].BuildingID;
                obj.FloorId = data[i].FloorId;
                obj.volume = data[i].volume[0];
                MainInfo.push(obj);

            }
</code>```

it's working but not fully applicable here i mentioned the excepted output what should i need

Current output

Expected output

Note:in data volume is dynamic help how to do this

答: If you are using jQuery, you can use $.extend(obj, volume[0])

Body:
hi all i am using javascript i am trying to push object values into one array here i attached my code

var data = [{
            BuildingID: "56", FloorId: "65", volume: [{

                one: 12,
                two: 15,
                three: 12
            }]
        }]

var MainInfo=[];
            for (i = 0; i < data.length; i++) {

                var obj = {}
                obj.BuildingID = data[i].BuildingID;
                obj.FloorId = data[i].FloorId;
                obj.volume = data[i].volume[0];
                MainInfo.push(obj);

            }

it's working but not fully applicable here i mentioned the excepted output what should i need

Current output

Expected output

Note:in data volume is dynamic help how to do this


问:
onclick inline script can't reference id in the shadow-dom (Polymer v2.0)
Consider this Plunker minimal example code.

```<code><dom-module id="my-element">
  ...
  <button onclick="dialog.open()">What is Confucianism ?</button>

  <paper-dialog id="dialog" modal>
    <h2>Confucianism</h2>
    <p>...</p>
  </paper-dialog>
  ...
</dom-module>
</code>```

won't work.

I am using Polymer v2.0. When I click on the button dialog.open() fails and says dialog is undefined.

In previous version of Polymer, this code worked but now that I have upgraded my code, I have to clear this issue everywhere I'm using paper-dialog elements. My current solution is to add a on-click attribute on all the buttons in my code and manually write a tied function and execute this.$.<dialogID>.open(); but I don't understand why I have to do that, and it appears to be like an issue to me because I write more tedious code, and this afterward compatibility seems more like a disadvantage to the new version.

Am I really doing something wrong ?

答:
this approach is really bad. You should always call a function that will open dialog. Plus, you should use polymer event handlers. on-tap for example.

And why is your code no longer works? well it depends on if you are using shadow dom. Because in shadow DOM, there are shadowRoots which are, let's say closed, so window object no longer have elements with IDs saved as properties.

Normally, it works because whenever you define element with some ID, this element is saved inside window object and that's why you can do <someID>.<someFunction>.

You should definitely rewrite your app so it's using polymer event handler functions.

EDIT:

Consider this Feature Request #4647 for a future reliable solution.

Body:
Consider this Plunker minimal example code.

<dom-module id="my-element">
  ...
  <button onclick="dialog.open()">What is Confucianism ?</button>

  <paper-dialog id="dialog" modal>

Confucianism

...

  </paper-dialog>
  ...
</dom-module>

won't work.

I am using Polymer v2.0. When I click on the button dialog.open() fails and says dialog is undefined.

In previous version of Polymer, this code worked but now that I have upgraded my code, I have to clear this issue everywhere I'm using paper-dialog elements. My current solution is to add a on-click attribute on all the buttons in my code and manually write a tied function and execute this.$.<dialogID>.open(); but I don't understand why I have to do that, and it appears to be like an issue to me because I write more tedious code, and this afterward compatibility seems more like a disadvantage to the new version.

Am I really doing something wrong ?


问:
Drawing on an Android Canvas, angle is not correct
I have a custom view that I have created for Android where I am drawing a Circle and dividing it into sections.

Here is the code for onDraw:

```<code>int w = Width;
int h = Height;

int pl = PaddingLeft;
int pr = PaddingRight;
int pt = PaddingTop;
int pb = PaddingBottom;

int usableWidth = w - (pl + pr);
int usableHeight = h - (pt + pb);

int radius = Math.Min(usableWidth, usableHeight) / 2;
int cx = pl + (usableWidth / 2);
int cy = pt + (usableHeight / 2);

int lineLenght = radius - (pl * 2) - (pr * 2);

paint.Color = Color.Black;
paint.SetStyle(Paint.Style.Stroke);
canvas.DrawCircle(cx, cy, radius, paint);

//Move to top of the circle
float pointAngle = 360 / noOfJoints;
for (float angle = 0; angle < 361; angle = angle + pointAngle)
{   //move round the circle to each point
    float x = cx + ((float)Math.Cos(radians(angle)) * radius); //convert angle to radians for x and y coordinates
    float y = cy + ((float)Math.Sin(radians(angle)) * radius);
    canvas.DrawLine(cx, cy, x, y, paint); //draw a line from center point back to the point
}
</code>```

But when I run this, it provides a view like the following:

Which is close to what I want, but the start of sections should be from the middle. How can I get it to start from 0 angle (first divider should be from Top to bottom straight line).

The preferred circle is as follows:

答:
Try this:

```<code>for (float angle = 0; angle < 361; angle = angle + pointAngle)
{   //move round the circle to each point
    float displacedAngle = angle - 90;
    float x = cx + ((float)Math.Cos(radians(displacedAngle)) * radius); //convert angle to radians for x and y coordinates
    float y = cy + ((float)Math.Sin(radians(displacedAngle)) * radius);
    canvas.DrawLine(cx, cy, x, y, paint); //draw a line from center point back to the point
}
</code>```

Angle 0 is the rightest point of the circle, subtracting 90 will it move to top point.

Also, a recommendation, avoid variable creation and object instantiation as much as possible in the onDraw method. It's a real performance killer.

Body:
I have a custom view that I have created for Android where I am drawing a Circle and dividing it into sections.

Here is the code for onDraw:

int w = Width;
int h = Height;

int pl = PaddingLeft;
int pr = PaddingRight;
int pt = PaddingTop;
int pb = PaddingBottom;

int usableWidth = w - (pl + pr);
int usableHeight = h - (pt + pb);

int radius = Math.Min(usableWidth, usableHeight) / 2;
int cx = pl + (usableWidth / 2);
int cy = pt + (usableHeight / 2);

int lineLenght = radius - (pl * 2) - (pr * 2);

paint.Color = Color.Black;
paint.SetStyle(Paint.Style.Stroke);
canvas.DrawCircle(cx, cy, radius, paint);

//Move to top of the circle
float pointAngle = 360 / noOfJoints;
for (float angle = 0; angle < 361; angle = angle + pointAngle)
{   //move round the circle to each point
    float x = cx + ((float)Math.Cos(radians(angle)) * radius); //convert angle to radians for x and y coordinates
    float y = cy + ((float)Math.Sin(radians(angle)) * radius);
    canvas.DrawLine(cx, cy, x, y, paint); //draw a line from center point back to the point
}

But when I run this, it provides a view like the following:

Which is close to what I want, but the start of sections should be from the middle. How can I get it to start from 0 angle (first divider should be from Top to bottom straight line).

The preferred circle is as follows:

Body:
Try this:

for (float angle = 0; angle < 361; angle = angle + pointAngle)
{   //move round the circle to each point
    float displacedAngle = angle - 90;
    float x = cx + ((float)Math.Cos(radians(displacedAngle)) * radius); //convert angle to radians for x and y coordinates
    float y = cy + ((float)Math.Sin(radians(displacedAngle)) * radius);
    canvas.DrawLine(cx, cy, x, y, paint); //draw a line from center point back to the point
}

Angle 0 is the rightest point of the circle, subtracting 90 will it move to top point.

Also, a recommendation, avoid variable creation and object instantiation as much as possible in the onDraw method. It's a real performance killer.


问:
Android App with a database crashes
I've built an android application with a database (sqlite 3) targeted for Android 2.2 with API level 8. It works by copying the database from the assets directory to the /data/data/com.myapp.db/databases folder. It works just fine on the emulator. However, when I try to install the application on HTC mobile device with version 2.2 and 2.1-update1, it crashes. The error says "Failed to Copy the Database". Could this be as a result of the database path that I used on the emulator and the actual device mismatching? I'm eagerly looking for your answers.

Thanks

答: I think it's a matter of permissions. The application has limited access to the system folder, unless you have your device rooted. The database you create from your application is saved under application directory. Maybe i didn't properly understand your issue, but... you are not creating a new database, but just moving a database you have in your assets to a final directory?. Where does this database in assets come from?. Why don't you create your tables in the Android application?</p>

Title: Android App with a database crashes


问:
How to pass a jquery variable as an argument in C# function
in the below code I am trying to pass a the cell value of jqgrid as a parameter in c# function but it is showing an error...

答:
we can't directly pass the jquery variable in server side c# function , but we can do it using an alternative method ,that is by calling another jquery method and the second method calls server side method using jquery ,ajax call and the ajax method return the desired output string after success.</p>

```<code>{
     name: 'Id', index: 'Id',
     formatter: function (cellvalue, options, rowObject) {
         var URLdata = "";
         debugger;
         BindTemperProofURL('@Url.Action("AddEventAttendee", "CampaignSchedule")', '', "Id=" + rowObject["Id"], function (data) { URLdata = data; })
         return '<a href="' + URLdata + '" style="width:75px; "class="jqgridlink">' + rowObject["Id"] + '</a>';

     }
},
</code>```

```<code>function BindTemperProofURL(url, nonTamperProofParams, tamperProofParams, callback) {
    var SecureURL = "";
    debugger;
    $.ajax({
        type: 'POST',
        url: '@Url.Action("SecureURL", "Base", new { area = string.Empty }, null)', // we are calling json method
    dataType: 'json',
    data: { url: url, nonTamperProofParams: nonTamperProofParams, tamperProofParams: tamperProofParams },
    success: function (data) {
        callback(data);
    },
    async: false,
    error: function (ex) {
    }
});
</code>```

Body:
we can't directly pass the jquery variable in server side c# function , but we can do it using an alternative method ,that is by calling another jquery method and the second method calls server side method using jquery ,ajax call and the ajax method return the desired output string after success.

{
     name: 'Id', index: 'Id',
     formatter: function (cellvalue, options, rowObject) {
         var URLdata = "";
         debugger;
         BindTemperProofURL('@Url.Action("AddEventAttendee", "CampaignSchedule")', '', "Id=" + rowObject["Id"], function (data) { URLdata = data; })
         return '<a href="' + URLdata + '" style="width:75px; "class="jqgridlink">' + rowObject["Id"] + '</a>';

     }
},

function BindTemperProofURL(url, nonTamperProofParams, tamperProofParams, callback) {
    var SecureURL = "";
    debugger;
    $.ajax({
        type: 'POST',
        url: '@Url.Action("SecureURL", "Base", new { area = string.Empty }, null)', // we are calling json method
    dataType: 'json',
    data: { url: url, nonTamperProofParams: nonTamperProofParams, tamperProofParams: tamperProofParams },
    success: function (data) {
        callback(data);
    },
    async: false,
    error: function (ex) {
    }
});


问:
Codepush React Native Android staging- Task installReleaseStagingDebug not found in root project
I'm trying to configure my RN android project according to this section of the react-native-code-push docs

My build.gradle file has this configuration:

```<code>buildTypes {
        debug {
        }
        releaseStaging {
            buildConfigField "String", "CODEPUSH_KEY", CODEPUSH_KEY_STAGING
        }
        release {
            buildConfigField "String", "CODEPUSH_KEY", CODEPUSH_KEY_PRODUCTION
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
</code>```

but when i run: react-native run-android --variant releaseStaging

I get the error: Task 'installReleaseStagingDebug' not found in root project 'MyAppName'.

Also tried running react-native run-android --configuration releaseStaging

Which gave me a slightly better error:

```<code>Task 'installReleaseStaging' not found in root project 'MyAppName'. Some candidates are: 'uninstallReleaseStaging'.
</code>```

Any idea what i'm missing?

Thanks!

Uri

答:
The Android Gradle plugin allows you to define custom config settings for each "build type" (e.g. debug, release)

To set this up,
Modify android/app/build.gradle in standard React Native projects

```<code>android {
...
buildTypes {
    debug {
        ...
        // Note: CodePush updates should not be tested in Debug mode as they are overriden by the RN packager. However, because CodePush checks for updates in all modes, we must supply a key.
        buildConfigField "String", "CODEPUSH_KEY", '""'
        ...
    }

    releaseStaging {
        ...
        buildConfigField "String", "CODEPUSH_KEY", '"<INSERT_STAGING_KEY>"'
        signingConfig signingConfigs.release
        ...
    }

    release {
        ...
        buildConfigField "String", "CODEPUSH_KEY", '"<INSERT_PRODUCTION_KEY>"'
        signingConfig signingConfigs.release
        ...
    }
}
...
</code>```

}

Note: CodePush updates should not be tested in Debug mode as they are overriden by the RN packager. However, because CodePush checks for updates in all modes, we must supply a key.

buildConfigField "String", "CODEPUSH_KEY", '""'

For latest react-native; you can build with

```<code>`react-native run-android --variant releaseStaging`
</code>```

Body:
I'm trying to configure my RN android project according to this section of the react-native-code-push docs

My build.gradle file has this configuration:

buildTypes {
        debug {
        }
        releaseStaging {
            buildConfigField "String", "CODEPUSH_KEY", CODEPUSH_KEY_STAGING
        }
        release {
            buildConfigField "String", "CODEPUSH_KEY", CODEPUSH_KEY_PRODUCTION
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }

but when i run: react-native run-android --variant releaseStaging

I get the error: Task 'installReleaseStagingDebug' not found in root project 'MyAppName'.

Also tried running react-native run-android --configuration releaseStaging

Which gave me a slightly better error:

Task 'installReleaseStaging' not found in root project 'MyAppName'. Some candidates are: 'uninstallReleaseStaging'.

Any idea what i'm missing?

Thanks!

Uri

Body:
The Android Gradle plugin allows you to define custom config settings for each "build type" (e.g. debug, release)

To set this up,
Modify android/app/build.gradle in standard React Native projects

android {
...
buildTypes {
    debug {
        ...
        // Note: CodePush updates should not be tested in Debug mode as they are overriden by the RN packager. However, because CodePush checks for updates in all modes, we must supply a key.
        buildConfigField "String", "CODEPUSH_KEY", '""'
        ...
    }

    releaseStaging {
        ...
        buildConfigField "String", "CODEPUSH_KEY", '"<INSERT_STAGING_KEY>"'
        signingConfig signingConfigs.release
        ...
    }

    release {
        ...
        buildConfigField "String", "CODEPUSH_KEY", '"<INSERT_PRODUCTION_KEY>"'
        signingConfig signingConfigs.release
        ...
    }
}
...

}

Note: CodePush updates should not be tested in Debug mode as they are overriden by the RN packager. However, because CodePush checks for updates in all modes, we must supply a key.

buildConfigField "String", "CODEPUSH_KEY", '""'

For latest react-native; you can build with

`react-native run-android --variant releaseStaging`


问:
PDO could not find driver
I'm using PHP Version 5.6.25 that was installed via WAMPP. I'm having issues connecting to my database on mySQL DB:

```<code>$server = 'jdbc:sqlserver://DB-1\POWERPIVOT;databaseName=SBV_Foldio';
$user = 'sa';
$pass = 'host';
</code>```

I had check PDO extension and already install

```<code>if (!defined('PDO::ATTR_DRIVER_NAME')) {
echo 'PDO is unavailable<br/>';
}
elseif (defined('PDO::ATTR_DRIVER_NAME')) {
    echo 'PDO is available<br/>';
}
</code>```

PDO is available

but when i run connection

```<code>try {
$dbh = new PDO($server, $user, $pass);

$dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
}
</code>```

it failed

Error!: could not find driver

答:
The problem is that you do not have the PDO_ODBC module installed right now. PDO seems to be properly configured & installed. See http://php.net/manual/en/ref.pdo-odbc.php for more info.

You are obviously running windows, so:

On Windows, php_pdo_odbc.dll has to be enabled as extension in php.ini. It is linked against the Windows ODBC Driver Manager so that PHP can connect to any database cataloged as a System DSN, and is the recommended driver for connecting to Microsoft SQL Server databases.

Title: PDO could not find driver

Body:
I'm using PHP Version 5.6.25 that was installed via WAMPP. I'm having issues connecting to my database on mySQL DB:

$server = 'jdbc:sqlserver://DB-1\POWERPIVOT;databaseName=SBV_Foldio';
$user = 'sa';
$pass = 'host';

I had check PDO extension and already install

if (!defined('PDO::ATTR_DRIVER_NAME')) {
echo 'PDO is unavailable
';
}
elseif (defined('PDO::ATTR_DRIVER_NAME')) {
    echo 'PDO is available
';
}

PDO is available

but when i run connection

try {
$dbh = new PDO($server, $user, $pass);

$dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "
";
}

it failed

Error!: could not find driver


问:
Find Textbox control
In my application i have 50 textboxes i want find all the textbox control using the code and i want to perform a color change in the textbox after doing certain validations. How can i acheive that? i used the following code but it doesnt work properly

```<code>foreach (Control cntrl in Page.Controls)
    {
        if (cntrl is TextBox)
        {
            //Do the operation
        }
    }
</code>```

<%@ Page Language="C#" MasterPageFile="~/HomePageMaster.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="Default" Title="Sample Page" %>

答:
This one goes recursively, so it will run on all controls in the page.
Note that if you want it to go over the textboxes in the databound controls too, you should probably call it in the OnPreRender.</p>

```<code>protected void Page_Load(object sender, EventArgs e)
{
    ColorChange(this);
}

protected static void ColorChange(Control parent)
{
    foreach (Control child in parent.Controls)
    {
        if (child is TextBox)
            (child as TextBox).ForeColor = Color.Red;

        ColorChange(child);
    }
}
</code>```

Title: Find Textbox control

Body:
In my application i have 50 textboxes i want find all the textbox control using the code and i want to perform a color change in the textbox after doing certain validations. How can i acheive that? i used the following code but it doesnt work properly

foreach (Control cntrl in Page.Controls)
    {
        if (cntrl is TextBox)
        {
            //Do the operation
        }
    }

<%@ Page Language="C#" MasterPageFile="~/HomePageMaster.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="Default" Title="Sample Page" %>

Body:
This one goes recursively, so it will run on all controls in the page.
Note that if you want it to go over the textboxes in the databound controls too, you should probably call it in the OnPreRender.

protected void Page_Load(object sender, EventArgs e)
{
    ColorChange(this);
}

protected static void ColorChange(Control parent)
{
    foreach (Control child in parent.Controls)
    {
        if (child is TextBox)
            (child as TextBox).ForeColor = Color.Red;

        ColorChange(child);
    }
}


问:
Trigger event when select from dropdown
I need when a user selects an option from the dropdown menu, it will trigger the event and lock down certain range of cells. I got the codes for lockdown cell but I can't lock it down when I select the dropdown menu. The value of the string data in the dropdown menu is ZFB50

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address = "$K$2" Then

    With Application
     .EnableEvents = False
     .ScreenUpdating = False
     .Calculation = xlCalculationManual
    End With

If Target.Address = "ZFB50" Then

    ActiveSheet.Unprotect

    Range("E8:E100").Select
    Selection.Locked = True

    Range("C8:C100").Select
    Selection.Locked = True

    Range("D8:D100").Select
    Selection.Locked = True

    Range("F8:F100").Select
    Selection.Locked = True

    Next cell

    ActiveSheet.Protect

    With Application
     .EnableEvents = True
     .ScreenUpdating = True
     .Calculation = xlCalculationAutomatic
    End With

End If

End Sub
</code>```

It still doesn't work, is there any problem with this code?

答:
an example can be found here with named ranges:

http://www.sebastianviereck.de/en/VBA-dropdown-change-event-to-perform-action/

Title: Trigger event when select from dropdown

Body:
I need when a user selects an option from the dropdown menu, it will trigger the event and lock down certain range of cells. I got the codes for lockdown cell but I can't lock it down when I select the dropdown menu. The value of the string data in the dropdown menu is ZFB50

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address = "$K$2" Then

    With Application
     .EnableEvents = False
     .ScreenUpdating = False
     .Calculation = xlCalculationManual
    End With

If Target.Address = "ZFB50" Then

    ActiveSheet.Unprotect

    Range("E8:E100").Select
    Selection.Locked = True

    Range("C8:C100").Select
    Selection.Locked = True

    Range("D8:D100").Select
    Selection.Locked = True

    Range("F8:F100").Select
    Selection.Locked = True

    Next cell

    ActiveSheet.Protect

    With Application
     .EnableEvents = True
     .ScreenUpdating = True
     .Calculation = xlCalculationAutomatic
    End With

End If

End Sub

It still doesn't work, is there any problem with this code?