问:
Can't find CSS rule that is declaring the width of
I am working on some HTML / CSS stuff and for some reason, I have a stray element that is overflowing my body and causing horizontal scroll bars.  Before you say it, I know this is a pretty n00b sounding mistake.  I typically don't have issues like this but I could really use a second set of eyes.

http://easterndancer.com.s66112.gridserver.com/

Can you find the element that's causing the scrolling overflow (horizontal)?

答:
Looks like it's this:

```<code><ul class="menu" id="menu-primary-navigation-1">
</code>```

In FireBug, it shows that its position is WAAAAaaay over to the right.  It's related to the left: 50%; styling.  While fiddling with the code, disabling this removed the scroll bar.

Title: Can't find CSS rule that is declaring the width of <body>

Body:
Looks like it's this:

<ul class="menu" id="menu-primary-navigation-1">

In FireBug, it shows that its position is WAAAAaaay over to the right.  It's related to the left: 50%; styling.  While fiddling with the code, disabling this removed the scroll bar.


来源: stackexchange

问:
Custom response from Volley
When i'm making a request and it fails, it shows the Toast with a full response error, I just want the "message" from it and not the whole JSON.

I want to make the message only appear and not the whole JSON String.

This is my JSON String:

```<code>{"status":false,"message":"message here"}
</code>```

This is the onResponse function:

```<code>        @Override
        public void onResponse(String response){
            try {
                JSONObject volleyResponse = new JSONObject(response);

                boolean success = volleyResponse.getBoolean("success");
                final String message = volleyResponse.getString("message");

                if(success){
                    messageText.setText("success");
                }
            } catch(JSONException e) {
                Toast.makeText(Authentication.this, response, Toast.LENGTH_LONG).show();
            }
        }
</code>```

答:
By definition, that is not possible.

There are two main failure cases. One is if you have some sort of networking problem, in which case onResponse() is not called, and you do not have any JSON to work with.

The other, shown in your code above, is if you have a JSON parsing error. In that case, you cannot get the message, because the message is in the JSON, and you are unable to parse that JSON. What you are showing in the Toast is not valid JSON (as otherwise, you would not have gotten a JSONException).

In your exception handler, add:

```<code>Log.e("heyoooooo", "Exception parsing JSON", e);
</code>```

Then, look at the Java stack trace to see more details about the particular parsing error.

ContentLicense: CC BY-SA 3.0

Title: Custom response from Volley

Body:
When i'm making a request and it fails, it shows the Toast with a full response error, I just want the "message" from it and not the whole JSON.

I want to make the message only appear and not the whole JSON String.

This is my JSON String:

{"status":false,"message":"message here"}

This is the onResponse function:

        @Override
        public void onResponse(String response){
            try {
                JSONObject volleyResponse = new JSONObject(response);

                boolean success = volleyResponse.getBoolean("success");
                final String message = volleyResponse.getString("message");

                if(success){
                    messageText.setText("success");
                }
            } catch(JSONException e) {
                Toast.makeText(Authentication.this, response, Toast.LENGTH_LONG).show();
            }
        }

Body:
By definition, that is not possible.

There are two main failure cases. One is if you have some sort of networking problem, in which case onResponse() is not called, and you do not have any JSON to work with.

The other, shown in your code above, is if you have a JSON parsing error. In that case, you cannot get the message, because the message is in the JSON, and you are unable to parse that JSON. What you are showing in the Toast is not valid JSON (as otherwise, you would not have gotten a JSONException).

In your exception handler, add:

Log.e("heyoooooo", "Exception parsing JSON", e);

Then, look at the Java stack trace to see more details about the particular parsing error.


问:
$ is not Defined in external .JS file
I have 4 files for my page - html.html, css.css, javascript.js, and jquery.js. In my jquery.js file I am having issues as when I use the starting code it comes up with an error in the console. Here is the code:

```<code>$(function(){console.log("works")});
</code>```

For some reason this comes up in the console log:

```<code>Uncaught ReferenceError: $ is not defined
</code>```

Anyone know why and how to fix it? I think it may be related to the shorthand of the "document" thing and maybe because it is a separate file it doesn't work.

答:
It looks like you came across the solution so I'm going to still post this here for others to see:

It's highly likely you did not link the jQuery file first.

This would give the error you describe:

```<code>    <script type='text/javascript' src='script.js'></script>
    <script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
</code>```

This would be correct:

```<code>    <script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
    <script type='text/javascript' src='script.js'></script>
</code>```

The reason why: your script.js uses jQuery. If you load the script.js first, jQuery specific delimiters, functions, etc will not be recognized in the script because they have not been defined yet.

Title: $ is not Defined in external .JS file

Body:
I have 4 files for my page - html.html, css.css, javascript.js, and jquery.js. In my jquery.js file I am having issues as when I use the starting code it comes up with an error in the console. Here is the code:

$(function(){console.log("works")});

For some reason this comes up in the console log:

Uncaught ReferenceError: $ is not defined

Anyone know why and how to fix it? I think it may be related to the shorthand of the "document" thing and maybe because it is a separate file it doesn't work.

Body:
It looks like you came across the solution so I'm going to still post this here for others to see:

It's highly likely you did not link the jQuery file first.

This would give the error you describe:

    <script type='text/javascript' src='script.js'></script>
    <script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>

This would be correct:

    <script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
    <script type='text/javascript' src='script.js'></script>

The reason why: your script.js uses jQuery. If you load the script.js first, jQuery specific delimiters, functions, etc will not be recognized in the script because they have not been defined yet.


问:
How to check if a pair of values exist on a 2-dimensional array in java
I have a 2d array of that form:

```<code>int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
            {-1, -2}, {-2, 1}, {-2, -1}};
</code>```

and i want to check programmaticaly if a pair of values {j,k}
exist on my 2d array moves.

答:
```<code>    int[][] moves;
    moves = new int[][] { { 1, 2 }, { 1, -2 }, { 2, 1 }, { 2, -1 }, { -1, 2 }, { -1, -2 }, { -2, 1 }, { -2, -1 } };
    int n = 1;
    int m = 2;
    boolean found = false;
    for (int i = 0; i < moves.length; i++) {
        for (int j = 0; j < moves[0].length; j++) {
            if (moves[i][j] == n) {
                if (j < 1 && moves[i][j + 1] == m) {
                    found = true;
                    break;
                }
            }
        }
    }
    if (found) {
        System.out.println(String.format("[%d , %d] found", n, m));
    } else {
        System.out.println(String.format("[%d , %d] not found", n, m));
    }
</code>```

Body:
I have a 2d array of that form:

int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
            {-1, -2}, {-2, 1}, {-2, -1}};

and i want to check programmaticaly if a pair of values {j,k}
exist on my 2d array moves.


问:
How do I create objects with a different number of arguments?
my question is what if I want to create an object that represents a person in a contact list.
The user has to enter a last name, if not, the program won't work.
Besides that the user can enter the first name, the address, phone number and so on, but these aren't necessary.
So how do I tackle these?
I could create a huge amount of constructors with the different parameter combinations, but I don't think that is the right solution.

Can you guys help me out?

答:
Simple way : using a constructor with mandatory fields and provides setters to value the other fields.

More complex way if immutability is required: using a builder to build the Person instance.

Builder should be a static nested class of Person that provides a way to build a Builder object and the Builder class provides method to set values of the Builder object.

Each one of this method returns the current Builder instance but build() that creates and returns the created Person object.

Here is a sample class :

```<code>public class Person {

    private String name;
    private String address;
    private String phone;

    // private constructor
    private Person() {
    }

    public static class Builder {

      private String name;
      private String address;
      private String phone;

      // mandatory fields
      public Builder(String name) {
        this.name = name;
      }

      public Builder address(String address) {
        this.address = address;
        return this;
      }

      public Builder phone(String phone) {
        this.phone = phone;
        return this;
      }

      public Person build() {
        Person p = new Person();
        p.name = name;
        p.address = address;
        p.phone = phone;
        return p;
      }
   }

}
</code>```

You could use then it in this way :

```<code>Person person = new Person.Builder("myName").address("myAddress").build();
</code>```

or

```<code> Person person = new Person.Builder("myName").address("myAddress").phone("my phone").build();
</code>```

Body:
Simple way : using a constructor with mandatory fields and provides setters to value the other fields.

More complex way if immutability is required: using a builder to build the Person instance.

Builder should be a static nested class of Person that provides a way to build a Builder object and the Builder class provides method to set values of the Builder object.

Each one of this method returns the current Builder instance but build() that creates and returns the created Person object.

Here is a sample class :

public class Person {

    private String name;
    private String address;
    private String phone;

    // private constructor
    private Person() {
    }

    public static class Builder {

      private String name;
      private String address;
      private String phone;

      // mandatory fields
      public Builder(String name) {
        this.name = name;
      }

      public Builder address(String address) {
        this.address = address;
        return this;
      }

      public Builder phone(String phone) {
        this.phone = phone;
        return this;
      }

      public Person build() {
        Person p = new Person();
        p.name = name;
        p.address = address;
        p.phone = phone;
        return p;
      }
   }

}

You could use then it in this way :

Person person = new Person.Builder("myName").address("myAddress").build();

or

 Person person = new Person.Builder("myName").address("myAddress").phone("my phone").build();


问:
App closing with clicking on about button
06-04 12:34:07.871 3697-3697/com.example.halls.basicrecipes E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.example.halls.basicrecipes, PID: 3697
                                                                              android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.halls.basicrecipes/com.example.halls.basicrecipes.About}; have you declared this activity in your AndroidManifest.xml?
                                                                                at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
                                                                                at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4224)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4183)
                                                                                at android.app.Activity.startActivity(Activity.java:4507)
                                                                                at android.app.Activity.startActivity(Activity.java:4475)
                                                                                at com.example.halls.basicrecipes.MainMenu.onClick(MainMenu.java:22)
                                                                                at android.view.View.performClick(View.java:5610)
                                                                                at android.view.View$PerformClick.run(View.java:22265)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

```<code>enter code here
</code>```

here is my code

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.halls.basicrecipes">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainMenu">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答:
Each Activity in your project have to be declared in your Manifest.

So, you have to declare the About activity in your AndroidManifest file like this :

```<code><activity
    android:name=".About"
    android:label="@string/app_name" />
</code>```

Body:
06-04 12:34:07.871 3697-3697/com.example.halls.basicrecipes E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.example.halls.basicrecipes, PID: 3697
                                                                              android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.halls.basicrecipes/com.example.halls.basicrecipes.About}; have you declared this activity in your AndroidManifest.xml?
                                                                                at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
                                                                                at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4224)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4183)
                                                                                at android.app.Activity.startActivity(Activity.java:4507)
                                                                                at android.app.Activity.startActivity(Activity.java:4475)
                                                                                at com.example.halls.basicrecipes.MainMenu.onClick(MainMenu.java:22)
                                                                                at android.view.View.performClick(View.java:5610)
                                                                                at android.view.View$PerformClick.run(View.java:22265)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

enter code here

here is my code

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.halls.basicrecipes">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainMenu">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Body:
Each Activity in your project have to be declared in your Manifest.

So, you have to declare the About activity in your AndroidManifest file like this :

<activity
    android:name=".About"
    android:label="@string/app_name" />


问:
Batch PCollection in Beam/Dataflow
I have a PCollection in GCP Dataflow/Apache Beam. Instead of processing it one by one, I need to combine "by N". Something like grouped(N). So, in case of bounded processing, it will group by 10 items in batch and last batch with whatever left.
Is this possible in Apache Beam?

答:
Edit, looks like: Google Dataflow "elementCountExact" aggregation

You should be able to do something similar by assigning elements to global window and using AfterPane.elementCountAtLeast(N). You still need to account for what what if there isn’t enough elements to fire the trigger. You could use this:

```<code> Repeatedly.forever(AfterFirst.of(
  AfterPane.elementCountAtLeast(N),
  AfterProcessingTime.pastFirstElementInPane().plusDelayOf(Duration.standardMinutes(X))))
</code>```

But you should ask yourself why do you need this heuristic in the first place, there probably is more idomatice way to solve your problem. Read about Data-Driven Triggers in Beam’s programming guide

Title: Batch PCollection in Beam/Dataflow

Body:
Edit, looks like: Google Dataflow "elementCountExact" aggregation

You should be able to do something similar by assigning elements to global window and using AfterPane.elementCountAtLeast(N). You still need to account for what what if there isn’t enough elements to fire the trigger. You could use this:

 Repeatedly.forever(AfterFirst.of(
  AfterPane.elementCountAtLeast(N),
  AfterProcessingTime.pastFirstElementInPane().plusDelayOf(Duration.standardMinutes(X))))

But you should ask yourself why do you need this heuristic in the first place, there probably is more idomatice way to solve your problem. Read about Data-Driven Triggers in Beam’s programming guide


问:
(Ionic - Firebase) Why only the last data is diplayed?
Issue

I'm using Ionic & Firebase for develop the application.

I don't know why but only the last data added to the database is displayed.

I've tried to use "value" instead of "child_added" but I got a list with only the raw values {"data":"Hello"}

I'd like to get a list with only the values !

Thanks for your help

news.html

```<code><ion-view title="News">
 <ion-nav-buttons side="right">
  <button ng-click="messageCreator()" class="button button-icon ion-ios-chatboxes-outline"></button>
 </ion-nav-buttons>

 <ion-content class="has-header">
  <ion-list ng-controller="displayMessages">
   <ion-item ng-click="goCalendar()" ng-repeat="val in value"  class="item item-icon-right">
    {{val}}
     <a class="icon icon-accessory ion-chevron-right"></a>
   </ion-item>
  </ion-list>
 </ion-content>
</ion-view>
</code>```

Method for create a new data

```<code>$scope.messageCreator = function () {
  $ionicPopup.prompt({
    title: 'New message',
  }).then(function(res) {
      firebase.database().ref('ParentName').push().set({
        data: res
      }).then(function() {
         alert("Data submitted");
      }).catch(function(error) {
        alert(error.message);
     });
  });
}
</code>```

Method for display data

```<code>$scope.displayMessages = function ($timeout) {
  var testRef = firebase.database().ref('ParentName');

  testRef.on('child_added', function (snapshot) {
    $timeout(function () {
      update(snapshot);
    });
  });

  function update (snapshot) {
    $scope.value = snapshot.val();
  }
}
</code>```

Display only the last data added to the database

答:
I don't think there is any reason for this:

```<code>testRef.on('child_added', function (snapshot) {
  $timeout(function () {
    update(snapshot);
  });
});
</code>```

The problem is the type of the data. You should declare your data as an Observable, so that the refresh is instant without the need of extra code. The declaration is like this:

```<code>data: FirebaseListObservable<any[]>;
</code>```

This type can be included by:

```<code>import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
</code>```

You can check a ready tutorial here, which also provides a live example to test it.

Body:
Issue

I'm using Ionic & Firebase for develop the application.

I don't know why but only the last data added to the database is displayed.

I've tried to use "value" instead of "child_added" but I got a list with only the raw values {"data":"Hello"}

I'd like to get a list with only the values !

Thanks for your help

news.html

<ion-view title="News">
 <ion-nav-buttons side="right">
  <button ng-click="messageCreator()" class="button button-icon ion-ios-chatboxes-outline"></button>
 </ion-nav-buttons>

 <ion-content class="has-header">
  <ion-list ng-controller="displayMessages">
   <ion-item ng-click="goCalendar()" ng-repeat="val in value"  class="item item-icon-right">
    {{val}}

   </ion-item>
  </ion-list>
 </ion-content>
</ion-view>

Method for create a new data

$scope.messageCreator = function () {
  $ionicPopup.prompt({
    title: 'New message',
  }).then(function(res) {
      firebase.database().ref('ParentName').push().set({
        data: res
      }).then(function() {
         alert("Data submitted");
      }).catch(function(error) {
        alert(error.message);
     });
  });
}

Method for display data

$scope.displayMessages = function ($timeout) {
  var testRef = firebase.database().ref('ParentName');

  testRef.on('child_added', function (snapshot) {
    $timeout(function () {
      update(snapshot);
    });
  });

  function update (snapshot) {
    $scope.value = snapshot.val();
  }
}

Display only the last data added to the database

Body:
I don't think there is any reason for this:

testRef.on('child_added', function (snapshot) {
  $timeout(function () {
    update(snapshot);
  });
});

The problem is the type of the data. You should declare your data as an Observable, so that the refresh is instant without the need of extra code. The declaration is like this:

data: FirebaseListObservable<any[]>;

This type can be included by:

import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';

You can check a ready tutorial here, which also provides a live example to test it.


问:
How to match a character to find if it is a special character in javascript
I am trying to find whether my string contains any special character. I am very new to javascript and would really appreciate your help.

Here is a simplified code :

```<code>function checkMe(text){
    var reg = '/[a-zA-Z0-9-]/gi';
    var character = text.charAt(0);
    if((character.match(reg)) == false){
        alert("special character found!!  ");
     }
}
</code>```

This is not giving desired output. Please help!!

答:
I think you mean special characters mean !@# etc.
Here is how you can check by calling test on regular expression.
See the code below, one with special chars and one with normal chars.

function checkMe(text) {
  var reg = /[a-zA-Z0-9-]/gi;
  var character = text.charAt(0);
  if (!reg.test(character)) {
    alert("special character found!!  ");
  } else {
    alert("NO special character found!!  ");
  }
}

checkMe('!@#$');
checkMe('normal');```

Body:
I am trying to find whether my string contains any special character. I am very new to javascript and would really appreciate your help.

Here is a simplified code :

function checkMe(text){
    var reg = '/[a-zA-Z0-9-]/gi';
    var character = text.charAt(0);
    if((character.match(reg)) == false){
        alert("special character found!!  ");
     }
}

This is not giving desired output. Please help!!


问:
What is a simpler way to go about reading specific lines of a text file, with varying lengths?
I am currently working on reading a long text file of varying length, with information broken down into blocks - specifically, I attempted to store into variables from my ifstream infile, three characters placed at various parts of the file, with their locations written into the file itself.

The text file I am currently reading has this structure, which I've heavily simplified:

xxx <--- This line indicates how many lines until the NEXT line I want to read. In this case, there are 3 of the "xxx xx x" lines.

a b c <--- This is the line(s) I want to read.

xxx xx x

xxx xx x

xxx xx x

xxx

a b c <--- This is the line(s) I want to read.

x xxx xx

x xxx xx

...and so on. The file goes on for about 20 more lines with varying block lengths. As you can see the line(s) with three of the characters represented here with x's is what I'd like. The way I currently have tried to do this is with the format I was used to, that is:

```<code>int count = 0;
infile.get(List[count].first_item, 4);
while(infile)
{
    int temp = List[count].first_item;
    count++;
    infile.ignore(81, '\n');
    infile>> List[count].wanted_value_1;
    infile>> List[count].wanted_value_2;
    infile>> List[count].wanted_value_3;
    count++;
    infile.ignore(81, '\n');
    for (int i = 0; i < temp; i++)
    {
        infile.ignore(81, '\n');
        count++;
    }
    infile.get(List[count].first_item, 4);
}
</code>```

The file read works fine for the first block, and even the second. My output when I print all this to screen looks like this:

a b c

a b c

a ~and then a bunch of gibberish indicating that it points to nothing.

With my For loop, I was trying to skip the "xxx xx x" lines by however much was indicated. But I'm kind of baffled. Am I on the right track? Or is my mindset just wrong? Thanks in advance!

答: Nvm, I managed to figure it out! I needed to skip another line after my For loop. It works like a charm now.</p>

Body:
I am currently working on reading a long text file of varying length, with information broken down into blocks - specifically, I attempted to store into variables from my ifstream infile, three characters placed at various parts of the file, with their locations written into the file itself.

The text file I am currently reading has this structure, which I've heavily simplified:

xxx <--- This line indicates how many lines until the NEXT line I want to read. In this case, there are 3 of the "xxx xx x" lines.

a b c <--- This is the line(s) I want to read.

xxx xx x

xxx xx x

xxx xx x

xxx

a b c <--- This is the line(s) I want to read.

x xxx xx

x xxx xx

...and so on. The file goes on for about 20 more lines with varying block lengths. As you can see the line(s) with three of the characters represented here with x's is what I'd like. The way I currently have tried to do this is with the format I was used to, that is:

int count = 0;
infile.get(List[count].first_item, 4);
while(infile)
{
    int temp = List[count].first_item;
    count++;
    infile.ignore(81, '\n');
    infile>> List[count].wanted_value_1;
    infile>> List[count].wanted_value_2;
    infile>> List[count].wanted_value_3;
    count++;
    infile.ignore(81, '\n');
    for (int i = 0; i < temp; i++)
    {
        infile.ignore(81, '\n');
        count++;
    }
    infile.get(List[count].first_item, 4);
}

The file read works fine for the first block, and even the second. My output when I print all this to screen looks like this:

a b c

a b c

a ~and then a bunch of gibberish indicating that it points to nothing.

With my For loop, I was trying to skip the "xxx xx x" lines by however much was indicated. But I'm kind of baffled. Am I on the right track? Or is my mindset just wrong? Thanks in advance!


问:
Google App Engine - Datastore - Get an entity, not by it's key
I'm building an Android app, and I'm using Google App Engine to store user's data. I want users to be able to connect from other devices to their account, but I could not figure how.

The users table (kind) has 4 properties: id, email, nickname and level:

I have read this:
https://cloud.google.com/appengine/docs/standard/java/datastore/creating-entities

It's written their that I can only get entities by their key, and it's a problem for me, because in a new device, I can only get the user's email, not the key and Id. I need to get the key and id by their email.

Is this possible?
If it's not, is their any other solution?

答:
What is stored at the id property? Does it have some meaningful value or just random unique number to be used as a unique identifier?

It seems like you can design your database differently so the email address would be your unique identifier. In that case, you will have a User table contains the following properties:

email (your unique identifier), nickname and level.

That way you will be able to use the following code snippet:

```<code>Key userEmail; //Get user's email
Entity user = datastore.get(userEmail);
</code>```

Regardless of that, you are still able to access your entity without the need for the entity's key, by using a query. That way you won't be using the entity's key in order to get its instance but you would rather get the desired entity by using the given property value and finding the matching entity with that property value.

The query would look something like that:

```<code>String userEmail; //Get user's email
Filter propertyFilter =
    new FilterPredicate("email", FilterOperator.EQUAL, userEmail);
Query q = new Query("User").setFilter(propertyFilter);
PreparedQuery pq = datastore.prepare(q);
try {
    Entity user = pq.asSingleEntity()
    //Same as Entity user = datastore.get(userEmail) mentioned above

} catch (TooManyResultsException e) {
    // If more than one result is returned from the Query.
    // Add code for dealing the exception here
}
</code>```

Body:
What is stored at the id property? Does it have some meaningful value or just random unique number to be used as a unique identifier?

It seems like you can design your database differently so the email address would be your unique identifier. In that case, you will have a User table contains the following properties:

email (your unique identifier), nickname and level.

That way you will be able to use the following code snippet:

Key userEmail; //Get user's email
Entity user = datastore.get(userEmail);

Regardless of that, you are still able to access your entity without the need for the entity's key, by using a query. That way you won't be using the entity's key in order to get its instance but you would rather get the desired entity by using the given property value and finding the matching entity with that property value.

The query would look something like that:

String userEmail; //Get user's email
Filter propertyFilter =
    new FilterPredicate("email", FilterOperator.EQUAL, userEmail);
Query q = new Query("User").setFilter(propertyFilter);
PreparedQuery pq = datastore.prepare(q);
try {
    Entity user = pq.asSingleEntity()
    //Same as Entity user = datastore.get(userEmail) mentioned above

} catch (TooManyResultsException e) {
    // If more than one result is returned from the Query.
    // Add code for dealing the exception here
}


问:
c++ 2D array row sort based on average row value
Helo,

I'm wondering if there's any working method for this?
I'm trying make this work, but no luck.

```<code>int mat[3][3];

    mat[0][0] = 4;mat[0][1] = 5;mat[0][2] = 3;

    mat[1][0] = 3;mat[1][1] = 2;mat[1][2] = 1;

    mat[2][0] = 1;mat[2][1] = 8;mat[2][2] = 9;
</code>```

Any idea? :)

答: A more idiomatically C++ way of doing this (vs. your original approach of array-of-arrays) would be to have a vector of vectors, ie. std::vector<std::vector<int> > and then invoke std::sort on the top-level vector. You can pass sort a custom predicate that compares two rows based on their average.

ContentLicense: CC BY-SA 2.5

Body:
Helo,

I'm wondering if there's any working method for this?
I'm trying make this work, but no luck.

int mat[3][3];

    mat[0][0] = 4;mat[0][1] = 5;mat[0][2] = 3;

    mat[1][0] = 3;mat[1][1] = 2;mat[1][2] = 1;

    mat[2][0] = 1;mat[2][1] = 8;mat[2][2] = 9;

Any idea? :)


问:
How to post an UTF-8 encoded request to a PHP server with TIdHTTP?
When I send a string to a PHP page it works fine.

The problem is when I use Arabic language like "محمد", I get a result like "؟؟؟؟". Here is my Delphi code:

```<code>var
  s: string;
  server: TIdHttp;
begin
  s := 'محمد';
  server := TIdHttp.Create;
  server.Post('http://mywebsite.com/insert_studint.php?name1=' + s);
  server.Free;
end;
</code>```

My PHP code:

<?php
    $name1=$_post['name1'];
    echo $name1;
?>
```

How can I encode my request to UTF-8 to get a proper result on my PHP server?

答:
That's not how URL string query parameters are handled by the TIdHTTP class. The first parameter of the Post method is just the target URL. The URL string query parameters need to be passed as the second parameter of this method as a stream or a string list collection. You need to specify the request encoding in your code as well and the rest will handle the class internally. Try this instead:

```<code>var
  Server: TIdHTTP;
  Params: TStrings;
begin
  Server := TIdHTTP.Create;
  try
    { setup the request charset }
    Server.Request.Charset := 'utf-8';
    { create the name=value parameter collection }
    Params := TStringList.Create;
    try
      { add the name1 parameter (concatenated with its value) }
      Params.Add('name1=محمد');
      { do the request }
      Server.Post('http://mywebsite.com/insert_studint.php', Params);
    finally
      Params.Free;
    end;
  finally
    Server.Free;
  end;
end;
</code>```

Body:
When I send a string to a PHP page it works fine.

The problem is when I use Arabic language like "محمد", I get a result like "؟؟؟؟". Here is my Delphi code:

var
  s: string;
  server: TIdHttp;
begin
  s := 'محمد';
  server := TIdHttp.Create;
  server.Post('http://mywebsite.com/insert_studint.php?name1=' + s);
  server.Free;
end;

My PHP code:

<?php
    $name1=$_post['name1'];
    echo $name1;
?>

How can I encode my request to UTF-8 to get a proper result on my PHP server?

Body:
That's not how URL string query parameters are handled by the TIdHTTP class. The first parameter of the Post method is just the target URL. The URL string query parameters need to be passed as the second parameter of this method as a stream or a string list collection. You need to specify the request encoding in your code as well and the rest will handle the class internally. Try this instead:

var
  Server: TIdHTTP;
  Params: TStrings;
begin
  Server := TIdHTTP.Create;
  try
    { setup the request charset }
    Server.Request.Charset := 'utf-8';
    { create the name=value parameter collection }
    Params := TStringList.Create;
    try
      { add the name1 parameter (concatenated with its value) }
      Params.Add('name1=محمد');
      { do the request }
      Server.Post('http://mywebsite.com/insert_studint.php', Params);
    finally
      Params.Free;
    end;
  finally
    Server.Free;
  end;
end;


问:
Taking values from an 'answer key' dataframe based on matching 2 variables in 1 dataframe to the 'key' in the 'answer key' dataframe
I can't think of a way to concisely or effectively phrase this, but this is what I want to do...

I have the following :

Dataframe of interest with columns (amongst others):

$first_name: "DONALD", "BARACK", "GEORGE", "BILL", ...

$last_name:  "TRUMP", "OBAMA", "BUSH", "CLINTON", ...

and

An "answer key" dataframe:

$name: "Donald John, TRUMP", "Barack Hussein, OBAMA", "Bill Jefferson, CLINTON", "George Walker, BUSH", ...

$value: 0, 2, 4, 6, ...

I want:

$first_name: "DONALD", "BARACK", "GEORGE", "BILL", ...

$last_name: "TRUMP", "OBAMA", "BUSH", "CLINTON", ...

$value: 0, 2, 4, 6, ...

It's important to note that:

There is no way of knowing the metaphorical middle names from the "answer key" dataframe (without visually inspecting thousands of columns).

The names are not lined up the same (in contrast to how I have displayed it).

The $first_name and $last_names's are repeated within the dataframe of interest.

So far

I've managed to get the $first_name's to be in the same format as they are in $name (that is, I now have "Bill" and "CLINTON", but I can't figure out how to connect them to "Bill Jefferson, CLINTON" <- 6 ). I originally planned on using grep() somehow to match them, but I don't think that is possible because it doesn't seem that you can use a vector for "pattern =".

These two seem relevant, at least in concept, but I'm just drawing a blank.

Create New Data Frame with Column Names from Unique Values in another Data Frame and Corresponding Values Assigned to Column

Define the value of a column in a dataframe based on 2 keys from a different dataframe

Thank you in advance.

答:
We extract the substring from the second dataset, do a match and use that to get the 'value'

```<code>df1$value <- df2$value[match(do.call(paste, df1), toupper(sub("\\s+\\w+,", "", df2$name)))]
df1
#    first_name last_name value
#1     DONALD     TRUMP     0
#2     BARACK     OBAMA     2
#3     GEORGE      BUSH     6
#4       BILL   CLINTON     4
</code>```

data

```<code> df1 <- data.frame(first_name = c("DONALD", "BARACK", "GEORGE", "BILL"),
  last_name = c("TRUMP", "OBAMA", "BUSH", "CLINTON"), stringsAsFactors=FALSE)
 df2 <- data.frame(name = c("Donald John, TRUMP", "Barack Hussein, OBAMA",
  "Bill Jefferson, CLINTON",
     "George Walker, BUSH"), value = c(0, 2, 4, 6) , stringsAsFactors=FALSE)
</code>```

Body:
We extract the substring from the second dataset, do a match and use that to get the 'value'

df1$value <- df2$value[match(do.call(paste, df1), toupper(sub("\\s+\\w+,", "", df2$name)))]
df1
#    first_name last_name value
#1     DONALD     TRUMP     0
#2     BARACK     OBAMA     2
#3     GEORGE      BUSH     6
#4       BILL   CLINTON     4

data

 df1 <- data.frame(first_name = c("DONALD", "BARACK", "GEORGE", "BILL"),
  last_name = c("TRUMP", "OBAMA", "BUSH", "CLINTON"), stringsAsFactors=FALSE)
 df2 <- data.frame(name = c("Donald John, TRUMP", "Barack Hussein, OBAMA",
  "Bill Jefferson, CLINTON",
     "George Walker, BUSH"), value = c(0, 2, 4, 6) , stringsAsFactors=FALSE)


问:
Repeated code for validating request in each controller
I have bunch of Rest controllers. for example:

```<code>@RequestMapping(path="/{groupId}",method=RequestMethod.PUT)
public void update(@RequestBody GroupDto groupDto, @PathVariable long groupId, Principal principal, BindingResult result) throws IOException {
    updateGroupDtoValidator.validate(groupDto, result);
    if (result.hasErrors()) {
        throw new ValidationException();
    }
    groupService.update(groupId, groupDto, principal.getName());
}
</code>```

In each method controller I have to repeat making a call to validate and checking the result for errors. IS there any better way ? Is it possible to configure @Validated somehow to validate the input data from the client ?

Update1 I have several validators. For example, I have UpdateGroupDtoValidator which validates a GroupDto object when it's passed to the Update Rest endpoint. I have another validator CreateGroupDtoValidator which validates GroupDto when dto is passed to the Create Rest endpoint.

答: You can define a Spring MVC Interceptor which will as its name suggests intercepts your calls before they reach the controller, you can perform your validation at that point.</p>

Body:
I have bunch of Rest controllers. for example:

@RequestMapping(path="/{groupId}",method=RequestMethod.PUT)
public void update(@RequestBody GroupDto groupDto, @PathVariable long groupId, Principal principal, BindingResult result) throws IOException {
    updateGroupDtoValidator.validate(groupDto, result);
    if (result.hasErrors()) {
        throw new ValidationException();
    }
    groupService.update(groupId, groupDto, principal.getName());
}

In each method controller I have to repeat making a call to validate and checking the result for errors. IS there any better way ? Is it possible to configure @Validated somehow to validate the input data from the client ?

Update1 I have several validators. For example, I have UpdateGroupDtoValidator which validates a GroupDto object when it's passed to the Update Rest endpoint. I have another validator CreateGroupDtoValidator which validates GroupDto when dto is passed to the Create Rest endpoint.


问:
Vapor with Postgres - table is not getting prepared
I have 3 Model objects in my project.

```<code>drop.preparations.append(Club.self)
drop.preparations.append(ClubPlayers.self)
drop.preparations.append(Player.self)
</code>```

for some reason, Club table is not created. this is my prepare method:

```<code>static func prepare(_ database: Database) throws {
        try database.create(Club.tableName, closure: { club in
            club.id()
            club.string(Club.nameColumn)
            club.string(Club.urlColumn)
        })

}
</code>```

it's built exactly as my other models, but it's the only one that is not being created. I don't receive any warning or error.
I'm using Swift 3.1.1, vapor 1.5 and vapor-toolbox 2

答:
My solution was: remove the 'Club' row from the 'fluent' table. then running vapor run prepare did work.
There are also other options:

use migration. https://vapor.github.io/documentation/fluent/model.html#preparations-as-migrations

use psql ADD COLUMN command. http://www.postgresqltutorial.com/postgresql-add-column/

I didn't try tanner0101 suggestion, but it sounds interesting

Body:
I have 3 Model objects in my project.

drop.preparations.append(Club.self)
drop.preparations.append(ClubPlayers.self)
drop.preparations.append(Player.self)

for some reason, Club table is not created. this is my prepare method:

static func prepare(_ database: Database) throws {
        try database.create(Club.tableName, closure: { club in
            club.id()
            club.string(Club.nameColumn)
            club.string(Club.urlColumn)
        })

}

it's built exactly as my other models, but it's the only one that is not being created. I don't receive any warning or error.
I'm using Swift 3.1.1, vapor 1.5 and vapor-toolbox 2


问:
fedora, tizen studio: "failed to start sdb", cannot connect tizen device
It is just sharing of knowledge. I hope I saved someone's time.

Problem description

If you have Fedora Linux (I use f25 now) but want to use Tizen Studio (officially it works only with Ubuntu Linux) you can face with these issues after installation and launch Studio:

Error message "failed to start sdb" during every Studio start

You can view Tizen devices from your network, but cannot connect

The problem is not started sdb tool (~/tizen-studio/tools/sdb)

For checking suspects you can try to launch sdb, it must failed with error: sdb: error while loading shared libraries: libcrypto.so.1.0.0: cannot open shared object file: No such file or directory.

Then, if you will check sdb with ldd command, you will see that libcrypto.so.1.0.0 is not found:

```<code>user@host$ ldd ~/tizen-studio/tools/sdb
linux-vdso.so.1 (0x00007ffc9dbf9000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fd8fc5be000)
libcrypto.so.1.0.0 => not found
libc.so.6 => /lib64/libc.so.6 (0x00007fd8fc1f8000)
/lib64/ld-linux-x86-64.so.2 (0x0000560aab3af000)
</code>```

The solution

Unfortunately, this problem cannot be solved with simple symlink to libcrypto.so and libssl.so and  on Fedora 25 (and, I suppose, on Fedora 23 and 24 also). So, the simplest way is to get this libs from Ubuntu repo. We need package libssl1.0.0_1.0.2g-1ubuntu9_amd64.deb (link for mirror.yandex repo), but do not forget to choose your architecture. Extract this deb package and copy (as root user) files libcrypto.so.1.0.0 and libssl.so.1.0.0 to /usr/lib64 (or /usr/lib for i686 arch). Then launch command ldconfig as root.

After these actions you can launch sdb command:

```<code>user@host$ ~/tizen-studio/tools/sdb version
Smart Development Bridge version 2.2.91
</code>```

After re-launching Tizen Studio you will can connect to Tizen Devices.

答:
It is much better to let your root partition untouched. You can write a script which preloads needed liraries and starts the sdb binary like this:

```<code>$ cd ~/tizen-studio/tools/
$ mv ./sdb sdb.bin
$ mkdir ./lib
$ mv libcrypto.so.1.0.0 ./lib/
</code>```

then create a script named "sdb":

```<code># sdb
LD_LIBRARY_PATH=./lib/ ./sdb.bin "$@"
</code>```

$ chmod +x ./sdb and you are all set!

Body:
It is just sharing of knowledge. I hope I saved someone's time.

Problem description

If you have Fedora Linux (I use f25 now) but want to use Tizen Studio (officially it works only with Ubuntu Linux) you can face with these issues after installation and launch Studio:

Error message "failed to start sdb" during every Studio start

You can view Tizen devices from your network, but cannot connect

The problem is not started sdb tool (~/tizen-studio/tools/sdb)

For checking suspects you can try to launch sdb, it must failed with error: sdb: error while loading shared libraries: libcrypto.so.1.0.0: cannot open shared object file: No such file or directory.

Then, if you will check sdb with ldd command, you will see that libcrypto.so.1.0.0 is not found:

user@host$ ldd ~/tizen-studio/tools/sdb
linux-vdso.so.1 (0x00007ffc9dbf9000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fd8fc5be000)
libcrypto.so.1.0.0 => not found
libc.so.6 => /lib64/libc.so.6 (0x00007fd8fc1f8000)
/lib64/ld-linux-x86-64.so.2 (0x0000560aab3af000)

The solution

Unfortunately, this problem cannot be solved with simple symlink to libcrypto.so and libssl.so and  on Fedora 25 (and, I suppose, on Fedora 23 and 24 also). So, the simplest way is to get this libs from Ubuntu repo. We need package libssl1.0.0_1.0.2g-1ubuntu9_amd64.deb (link for mirror.yandex repo), but do not forget to choose your architecture. Extract this deb package and copy (as root user) files libcrypto.so.1.0.0 and libssl.so.1.0.0 to /usr/lib64 (or /usr/lib for i686 arch). Then launch command ldconfig as root.

After these actions you can launch sdb command:

user@host$ ~/tizen-studio/tools/sdb version
Smart Development Bridge version 2.2.91

After re-launching Tizen Studio you will can connect to Tizen Devices.

Body:
It is much better to let your root partition untouched. You can write a script which preloads needed liraries and starts the sdb binary like this:

$ cd ~/tizen-studio/tools/
$ mv ./sdb sdb.bin
$ mkdir ./lib
$ mv libcrypto.so.1.0.0 ./lib/

then create a script named "sdb":

# sdb
LD_LIBRARY_PATH=./lib/ ./sdb.bin "$@"

$ chmod +x ./sdb and you are all set!


问:
Javascript timer help needed
I have the following ajax page. The form should be submitted and the timer should be restart counting down when the timer expires or button is clicked.

For some reason the timer is not reset and goes minus. Can someone tell me how to fix this?

(The code is standalone, you can copy/paste ans test it, then run it on server)

test.htm:

```<code>
<html>
<head>
<script type="text/javascript" src="http://mootools.net/download/get/mootools-core-1.3-full-compat.js"></script>
</head>
<body>
<div id="container">
<form id="form" name="form" action="test.htm" method="post">
Remaining time: <input type="text" name="clock" size="4">seconds
<input type="submit" value="submit" ID="questionSubmit">
</form>
<script type="text/javascript">
var timeLeft = 10;
function startClock() {
    timeLeft--;
    document.form.clock.value = timeLeft;
    if(timeLeft == 0) {
        sendForm();
    }
    else {
        setTimeout("startClock()", 1000);
    }
}

setTimeout("startClock()", 1000);
</script>

<script type="text/javascript">
function handleSubmit(e) {
    e = new Event(e).stop();
    sendForm();
}

function sendForm() {
    $('form').set('send', {onComplete: function(response) {
        $('container').set('html', response);
        $('questionSubmit').addEventListener('click', handleSubmit, false);
        setTimeout("startClock()", 1000);
    }});
    //Send the form.
    $('form').send();
}

$('questionSubmit').addEventListener('click', handleSubmit, false);
</script>
</div>
</body>
</html>
</code>```

答:
As I mentioned in my comment, you should use <=0. As you replied, sendForm() is then called every second. This doesn't make sense, so I suspect there's something else going on

My second observation is that you're never resetting timeLeft. A good place for this would be following the call to sendForm

Title: Javascript timer help needed

Body:
I have the following ajax page. The form should be submitted and the timer should be restart counting down when the timer expires or button is clicked.

For some reason the timer is not reset and goes minus. Can someone tell me how to fix this?

(The code is standalone, you can copy/paste ans test it, then run it on server)

test.htm:

<form id="form" name="form" action="test.htm" method="post">
Remaining time: <input type="text" name="clock" size="4">seconds
<input type="submit" value="submit" ID="questionSubmit">
</form>


问:
how do you separate each part of an array into another array?
so I have a string that is split at any period. It is then stored into the array "sentences". Now I want to split all parts of the array "sentences" by spacing. How do I do that?

my code so far:

```<code>string input = TextEditor.Text;
string[] sentences = input.Split('.');
string[] words = sentences[0].Split(' ');
</code>```

this does not work though, obviously.

the output I want is if the string is: hello world I feel great. How about you.

output:

```<code>wordarray[0] = {"hello", "world", "I", "feel", "great"};
wordarray[1] = {"How", "about", "you"};
</code>```

答:
You might want to loop through and get the inner arrays filled like</p>

```<code>    string input = TextEditor.Text;
    string[] sentences = input.Split('.');

    for(int i=0; i< sentences.Length; i++)
    {
      string[] words = sentences[i].Split(' ');
       //do some processing on this
    }
</code>```

Body:
so I have a string that is split at any period. It is then stored into the array "sentences". Now I want to split all parts of the array "sentences" by spacing. How do I do that?

my code so far:

string input = TextEditor.Text;
string[] sentences = input.Split('.');
string[] words = sentences[0].Split(' ');

this does not work though, obviously.

the output I want is if the string is: hello world I feel great. How about you.

output:

wordarray[0] = {"hello", "world", "I", "feel", "great"};
wordarray[1] = {"How", "about", "you"};

Body:
You might want to loop through and get the inner arrays filled like

    string input = TextEditor.Text;
    string[] sentences = input.Split('.');

    for(int i=0; i< sentences.Length; i++)
    {
      string[] words = sentences[i].Split(' ');
       //do some processing on this
    }


问:
Excel: ISEVEN and text
First I'll explain what I want as result:

If there is an odd number in the column "HOME_TEAM_ID", I would like to see "Premier League 1" in the column "COMPETITIE", otherwise I want to have "Super League 1"

Now the problem:

I can't find the formula to do this. I tried "=ISEVEN" but that is more like a boolean and will only show me "TRUE" or "FALSE".

I am working on Excel online, don't know if this could affect something.

Thanks for helping.

答:
Yes ISEVEN will return TRUE/FALSE.

So we use IF() to tell the cell what to display based on the outcome of ISEVEN.

```<code>=IF(ISEVEN(B2),"Super League 1","Premier League 1")
</code>```

Title: Excel: ISEVEN and text

Body:
Yes ISEVEN will return TRUE/FALSE.

So we use IF() to tell the cell what to display based on the outcome of ISEVEN.

=IF(ISEVEN(B2),"Super League 1","Premier League 1")


问:
PHP Classes function inside function?
I'm self-studying the PHP language. And I'm focused on the latest PHP OOP language.

I search for some "ready-to-install" PHP software and as I scan for some references to search and know, I saw lines of code with a structure like this (can't remember so I'll create my own):

```<code>$myapp->settings->getValue('openforum');
$myapp->settings->setValue('closeformaintenance', '1');
</code>```

So my question is, how can I reproduce the code above? I don't know what term to use that line of code (objects, I guess?).

Something like this:

```<code>$newLogin->search($uid)->setLogin($dateToday);
</code>```

Like that. I really need to do that way so I can organize my coding structure. Thanks by the way.

And also for the final question, IS THAT POSSIBLE?

答:
Here's a fairly straight forward way of looking at it, using dependency injection.

Try it out: https://3v4l.org/iSJgL

Note, the below requires PHP 7 due to the string type hint. Remove that and I believe it should work in 5.6 just fine.

```<code><?php

$myapp = new MyApp(new SettingsBag([
    'works' => false,
    'random' => rand(),
]));

var_dump($myapp->settings()->get('random'));

var_dump($myapp->settings()->get('works'));

// Let's change it up...
$myapp->settings()->set('works', true);

// Now it should be true.
var_dump($myapp->settings()->get('works'));
</code>```

These would normally have namespaces like \App and/or \App\Configuration, but I ignore that here so it's easier to follow:

```<code>class MyApp {

    private $settings_bag = null;

    function __construct(SettingsBag $settings_bag)
    {
        $this->settings_bag = $settings_bag;
    }

    public function settings()
    {
        return $this->settings_bag;
    }

}

class SettingsBag {

    private $settings = null;

    function __construct(array $settings = [])
    {
        $this->settings = $settings;
    }

    public function set(string $key, $value)
    {
        return $this->settings[$key] = $value;
    }

    public function get(string $key)
    {
        return $this->settings[$key];
    }

}
</code>```

Title: PHP Classes function inside function?

Body:
I'm self-studying the PHP language. And I'm focused on the latest PHP OOP language.

I search for some "ready-to-install" PHP software and as I scan for some references to search and know, I saw lines of code with a structure like this (can't remember so I'll create my own):

$myapp->settings->getValue('openforum');
$myapp->settings->setValue('closeformaintenance', '1');

So my question is, how can I reproduce the code above? I don't know what term to use that line of code (objects, I guess?).

Something like this:

$newLogin->search($uid)->setLogin($dateToday);

Like that. I really need to do that way so I can organize my coding structure. Thanks by the way.

And also for the final question, IS THAT POSSIBLE?

Body:
Here's a fairly straight forward way of looking at it, using dependency injection.

Try it out: https://3v4l.org/iSJgL

Note, the below requires PHP 7 due to the string type hint. Remove that and I believe it should work in 5.6 just fine.

<?php

$myapp = new MyApp(new SettingsBag([
    'works' => false,
    'random' => rand(),
]));

var_dump($myapp->settings()->get('random'));

var_dump($myapp->settings()->get('works'));

// Let's change it up...
$myapp->settings()->set('works', true);

// Now it should be true.
var_dump($myapp->settings()->get('works'));

These would normally have namespaces like \App and/or \App\Configuration, but I ignore that here so it's easier to follow:

class MyApp {

    private $settings_bag = null;

    function __construct(SettingsBag $settings_bag)
    {
        $this->settings_bag = $settings_bag;
    }

    public function settings()
    {
        return $this->settings_bag;
    }

}

class SettingsBag {

    private $settings = null;

    function __construct(array $settings = [])
    {
        $this->settings = $settings;
    }

    public function set(string $key, $value)
    {
        return $this->settings[$key] = $value;
    }

    public function get(string $key)
    {
        return $this->settings[$key];
    }

}


问:
Create dynamic switchery
I want to create dynamic switchery and create and button object with jquery and some dynamic variable for this then I want the Html object to append to Html I can't do it below link is my code
Visit jsfiddle.net/eu3a0k3m/2/

my js codes:

```<code>var count = 3;
$("#btn").click(function(){
    CreateInlineChildWithSwitchery(++count);
});
function CreateInlineChildWithSwitchery (countOfChilds){

      var Integer_LastSwitcheryId = count;

      var btn = $('<input type="checkbox" id="js-switch' + Integer_LastSwitcheryId + '" class="js-switch' + Integer_LastSwitcheryId + ' js-check-change' + Integer_LastSwitcheryId + ' col-lg-3" data-switchery="true">');
console.log(btn)
$('#all-encyclopedia').append(
        $("#tpl ").html()
                                  .replace(/{switchery}/g,btn)
      );

      eval("elem" + Integer_LastSwitcheryId.toString() + "=document.querySelector('#js-switch"+Integer_LastSwitcheryId.toString()+"')");

      eval("switchery" + Integer_LastSwitcheryId.toString() +"={elem" + Integer_LastSwitcheryId.toString() + ",  color: '#1AB394',secondaryColor: '#688ab0'}");

      eval("changeCheckbox" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change"+Integer_LastSwitcheryId.toString()+"')");

      eval("changeField" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change-field"+Integer_LastSwitcheryId.toString()+"')");

  }

  for(i=1;i<4;i++)
      CreateInlineChildWithSwitchery(count++);
</code>```

my Html codes:

```<code><script type="text/tpl" id="tpl">
{switchery}
</script>
<button id="btn">insert Switchery</button>
<div id="all-encyclopedia"></div>
</code>```

答:
with change blow section of code

```<code>eval("switchery" + Integer_LastSwitcheryId.toString() + "={elem" + Integer_LastSwitcheryId.toString() + ",  color: '#1AB394',secondaryColor: '#688ab0'}");
</code>```

To:

```<code>var swicheryy = new Switchery(window[ "elem" + Integer_LastSwitcheryId.toString() ],{
  color: '#1AB394',
  secondaryColor: '#688ab0'
});
</code>```

my problem is solved

Visit: jsfiddle.net/eu3a0k3m/5/

Title: Create dynamic switchery

Body:
I want to create dynamic switchery and create and button object with jquery and some dynamic variable for this then I want the Html object to append to Html I can't do it below link is my code
Visit jsfiddle.net/eu3a0k3m/2/

my js codes:

var count = 3;
$("#btn").click(function(){
    CreateInlineChildWithSwitchery(++count);
});
function CreateInlineChildWithSwitchery (countOfChilds){

      var Integer_LastSwitcheryId = count;

      var btn = $('<input type="checkbox" id="js-switch' + Integer_LastSwitcheryId + '" class="js-switch' + Integer_LastSwitcheryId + ' js-check-change' + Integer_LastSwitcheryId + ' col-lg-3" data-switchery="true">');
console.log(btn)
$('#all-encyclopedia').append(
        $("#tpl ").html()
                                  .replace(/{switchery}/g,btn)
      );

      eval("elem" + Integer_LastSwitcheryId.toString() + "=document.querySelector('#js-switch"+Integer_LastSwitcheryId.toString()+"')");

      eval("switchery" + Integer_LastSwitcheryId.toString() +"={elem" + Integer_LastSwitcheryId.toString() + ",  color: '#1AB394',secondaryColor: '#688ab0'}");

      eval("changeCheckbox" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change"+Integer_LastSwitcheryId.toString()+"')");

      eval("changeField" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change-field"+Integer_LastSwitcheryId.toString()+"')");

  }

  for(i=1;i<4;i++)
      CreateInlineChildWithSwitchery(count++);

my Html codes:

<button id="btn">insert Switchery</button>

Body:
with change blow section of code

eval("switchery" + Integer_LastSwitcheryId.toString() + "={elem" + Integer_LastSwitcheryId.toString() + ",  color: '#1AB394',secondaryColor: '#688ab0'}");

To:

var swicheryy = new Switchery(window[ "elem" + Integer_LastSwitcheryId.toString() ],{
  color: '#1AB394',
  secondaryColor: '#688ab0'
});

my problem is solved

Visit: jsfiddle.net/eu3a0k3m/5/


问:
Why does my loop iterate only twice?
I have defined two structs and when I loop to set their values, it only loop twice as printf return. Any ideas?

```<code>typedef struct {
  int x;
  int y;
  unsigned char status;
} Cell;

typedef struct {
  int sizeX;
  int sizeY;
  Cell cell[];
} World;

int main() {
  int i, x, y;
  i = 0;
  World grid;
  grid.sizeX = 10;
  grid.sizeY = 10;

  for (x = 0; x < grid.sizeX; x++) {
    for (y = 0; y < grid.sizeY; y++) {
      Cell cell;
      cell.x = x;
      cell.y = y;

      printf("%d,%d: ", cell.x, cell.y);

      grid.cell[i] = cell;
      i++;
    }
  }

    return 0;
}
</code>```

EDIT :

Correct answer given below, thanks for comments and your patience for a C noob !

答:
Your World struct has a flexible array member as the last element.  There is actually no space set aside for that member.  As a result, you write off the end of the struct when you write to the array, resulting in undefined behavior.

You need to declare a World *  and use malloc to allocate space for the struct plus the array.

```<code>World *world = malloc(sizeof(World) + 10 * 10 * sizeof(Cell));
</code>```

Title: Why does my loop iterate only twice?

Body:
I have defined two structs and when I loop to set their values, it only loop twice as printf return. Any ideas?

typedef struct {
  int x;
  int y;
  unsigned char status;
} Cell;

typedef struct {
  int sizeX;
  int sizeY;
  Cell cell[];
} World;

int main() {
  int i, x, y;
  i = 0;
  World grid;
  grid.sizeX = 10;
  grid.sizeY = 10;

  for (x = 0; x < grid.sizeX; x++) {
    for (y = 0; y < grid.sizeY; y++) {
      Cell cell;
      cell.x = x;
      cell.y = y;

      printf("%d,%d: ", cell.x, cell.y);

      grid.cell[i] = cell;
      i++;
    }
  }

    return 0;
}

EDIT :

Correct answer given below, thanks for comments and your patience for a C noob !

Body:
Your World struct has a flexible array member as the last element.  There is actually no space set aside for that member.  As a result, you write off the end of the struct when you write to the array, resulting in undefined behavior.

You need to declare a World *  and use malloc to allocate space for the struct plus the array.

World *world = malloc(sizeof(World) + 10 * 10 * sizeof(Cell));


问:
OpenGL ES : getting a fixed size for an object
I have an open GL ES (1.1) scene with many 3d objects and a "player" model. I'd like the player to have the same pixel size, regardless of the screen orientation on an Android phone or Iphone.
I'm not using glOrtho or billboards. That's a perspective 3d scene, but I just want the objects to have the same size in both screen orientation. Currently, if I rotate the phone, I keep the same aspect ratio but the scene "zooms out" in landscape mode.
I suspect that I have to play with parameters to glFrustrum to get this; but can't figure out yet how to do it.
So any ideas are welcome!

Thanks

答:
You will need to change the aspect ratio when the device is turned to go from a the otherwise the size of the objects are going to change. THink of yourself looking out through a window, the objects on the other side of the window are only going to be the same size if you don't change your distance from the window (i.e. zooom in and out), when you "turn" the window sidewayse, the aspect ratio of the window changes (the metaphor is starting to not work).

If you draw a square in the view with the side length being the short side of the screen, then you should still have a square when you turn the phone sideways, still covering the same area on the screen.

Things will probably be easier to calculate if you use the code from gluPerspective. You set the aspect ratio to the actual aspect ratio, fix the fovy for the first aspect ratio. You can then use what would be fovx for this aspect ratio as the fovy for your rotated view.


问:
Setting filter brightness of parent without affecting child element
Is there a way to achieve the effect of setting CSS filter: brightness() on an element without it also affecting specific / all (does not matter) child elements?

Consider the following example:

function setBrightness (bright) {
  $('.icon').css('filter', `brightness(${bright})`);
  // None of these work:
  // $('.indicator').css('filter', '');
  // $('.indicator').css('filter', 'brightness(1.0)');
  // $('.indicator').css('filter', `brightness(${1.0/bright})`);
}

window.setInterval(function () {
  let ms = new Date().getTime();
  let bright = Math.cos(2.0 * 3.14 * ms / 3000.0) + 1.0;
  setBrightness(bright);
}, 50);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#bar {
  background: #222;
  font-size: 0;
}

.icon {
  background-image: url(https://cdn.sstatic.net/img/share-sprite-new.svg?v=78be252218f3);
  width: 36px;
  height: 34px;
  display: table-cell;
  text-align: center;
  /* normally middle but set to top to not obscure background for this example: */
  vertical-align: top;
}

.icon1 {
  background-position: -141px -54px;
}

.icon2 {
  background-position: -220px -54px;
}

.indicator {
  border-radius: 2px;
  color: white;
  display: inline-block;
  font-family: sans-serif;
  font-size: 8pt;
  width: 50%;
}

.icon1 .indicator {
  background: #a00;
}

.icon2 .indicator {
  background: #0f0;
}</code>```

    3

      10

```
</div>
</div>
</p>

<p>Here, I've got a <code>span</code> inside a <code>div</code> (class <code>icon</code>) and I'm setting the filter brightness on the <code>div</code>'s like so:</p>

```$('.icon').css('filter', `brightness(${bright})`);
```

<p>However, I'd like it to <em>only</em> affect that background, and not affect the little "indicator" <code>span</code>. That is, in the above snippet, the icon should be pulsing but the foreground indicators and their red/green backgrounds should remain unchanged. The only things I thought of to try failed:</p>

```function setBrightness (bright) {
  $('.icon').css('filter', `brightness(${bright})`);
  // None of these work:
  // $('.indicator').css('filter', '');
  // $('.indicator').css('filter', 'brightness(1.0)');
  // $('.indicator').css('filter', `brightness(${1.0/bright})`);
}
```

Also, it's important that I not make changes to the following:

Cannot change background-* CSS properties.

Cannot change structure of HTML, the span must remain a child of the div.

I don't actually need a solution that omits all child elements, by the way. I only need a single given child (those spans) unaffected, as the structure I'm working with does not have multiple children under each div; the example is representative. Not sure if that matters.

Is there a way to do this?

答:
Changing the opacity of a parent element will always change the opacity of the child element. Sadly there is no way around that. However you can change the HTML structure and absolute position the elements on top of one another, and then only target the elements you want to fade.

$(document).ready(function(){
  function setBrightness (bright) {
  $('.icon').css('filter', `brightness(${bright})`);
}

window.setInterval(function () {
  let ms = new Date().getTime();
  let bright = Math.cos(2.0 * 3.14 * ms / 3000.0) + 1.0;
    setBrightness(bright);
  }, 50);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#bar {
  background: #222;
  font-size: 0;
 }

 .icon {
  background-image: url(https://cdn.sstatic.net/img/share-sprite-new.svg?v=78be252218f3);
  width: 36px;
  height: 34px;
  display: inline-block;
  position: absolute;
  top:0;
  left: 0;
 }

 .icon-wrap {
  width: 36px;
  height: 34px;
  text-align: center;
  position: relative;
  display: table-cell;
  /* normally middle but set to top to not obscure background for this example: */
 }

 .icon1 .icon {
  background-position: -141px -54px;
 }

 .icon2 .icon {
  background-position: -220px -54px;
 }

 .indicator {
  border-radius: 2px;
  color: white;
  font-family: sans-serif;
  font-size: 8pt;
  width: 18px;
  height: 14px;
  position: absolute;
  top:0;
  left:50%;
  margin-left: -9px;
 }

 .icon1 .indicator {
  background: #a00;
 }

 .icon2 .indicator {
  background: #0f0;
 }</code>```

    3

    10

```
</div>
</div>
</p>

<p>It is also possible to do with CSS3 keyframes:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#bar {
  background: #222;
  font-size: 0;
}

.icon {
  background-image: url(https://cdn.sstatic.net/img/share-sprite-new.svg?v=78be252218f3);
  width: 36px;
  height: 34px;
  display: inline-block;
  position: absolute;
  top:0;
  left: 0;
  -webkit-filter: grayscale(200%); /* Safari 6.0 - 9.0 */
  filter: grayscale(200%);
}

.icon-wrap {
  width: 36px;
  height: 34px;
  text-align: center;
  position: relative;
  display: table-cell;
  /* normally middle but set to top to not obscure background for this example: */
}

.icon1 .icon {
  background-position: -141px -54px;
}

.icon2 .icon {
  background-position: -220px -54px;
}

.indicator {
  border-radius: 2px;
  color: white;
  font-family: sans-serif;
  font-size: 8pt;
  width: 18px;
  height: 14px;
  position: absolute;
  top:0;
  left:50%;
  margin-left: -9px;
}

.icon1 .indicator {
  background: #a00;
}

.icon2 .indicator {
  background: #0f0;
}

@keyframes fader {
  0%   {
    -webkit-filter: grayscale(200%); /* Safari 6.0 - 9.0 */
    filter: grayscale(200%);
  }
  50%  {
    -webkit-filter: grayscale(0%); /* Safari 6.0 - 9.0 */
    filter: grayscale(0%);
  }
  100% { opacity:1;
    -webkit-filter: grayscale(200%); /* Safari 6.0 - 9.0 */
    filter: grayscale(200%);
  }
}
@-o-keyframes fader {
  0%   {
   -webkit-filter: brightness(200%); /* Safari 6.0 - 9.0 */
   filter: brightness(200%);
 }
 50%  {
   -webkit-filter: brightness(0%); /* Safari 6.0 - 9.0 */
   filter: brightness(0%);
 }
 100% { opacity:1;
   -webkit-filter: brightness(200%); /* Safari 6.0 - 9.0 */
   filter: brightness(200%);
 }
}
@-moz-keyframes fader {
  0%   {
   -webkit-filter: brightness(200%); /* Safari 6.0 - 9.0 */
   filter: brightness(200%);
 }
 50%  {
   -webkit-filter: brightness(0%); /* Safari 6.0 - 9.0 */
   filter: brightness(0%);
 }
 100% { opacity:1;
   -webkit-filter: brightness(200%); /* Safari 6.0 - 9.0 */
   filter: brightness(200%);
 }
}
@-webkit-keyframes fader {
  0%   {
   -webkit-filter: brightness(200%); /* Safari 6.0 - 9.0 */
   filter: brightness(200%);
 }
 50%  {
   -webkit-filter: brightness(0%); /* Safari 6.0 - 9.0 */
   filter: brightness(0%);
 }
 100% { opacity:1;
   -webkit-filter: brightness(200%); /* Safari 6.0 - 9.0 */
   filter: brightness(200%);
 }
}
.icon {
   -webkit-animation: fader 3s infinite ease-in;
   -moz-animation: fader 3s infinite ease-in;
   -o-animation: fader 3s infinite ease-in;
   animation: fader 3s infinite ease-in;
}</code>```

    3

    10

```

Body:
Is there a way to achieve the effect of setting CSS filter: brightness() on an element without it also affecting specific / all (does not matter) child elements?

Consider the following example:

function setBrightness (bright) {
  $('.icon').css('filter', `brightness(${bright})`);
  // None of these work:
  // $('.indicator').css('filter', '');
  // $('.indicator').css('filter', 'brightness(1.0)');
  // $('.indicator').css('filter', `brightness(${1.0/bright})`);
}

window.setInterval(function () {
  let ms = new Date().getTime();
  let bright = Math.cos(2.0 * 3.14 * ms / 3000.0) + 1.0;
  setBrightness(bright);
}, 50);

#bar {
  background: #222;
  font-size: 0;
}

.icon {
  background-image: url(https://cdn.sstatic.net/img/share-sprite-new.svg?v=78be252218f3);
  width: 36px;
  height: 34px;
  display: table-cell;
  text-align: center;
  /* normally middle but set to top to not obscure background for this example: */
  vertical-align: top;
}

.icon1 {
  background-position: -141px -54px;
}

.icon2 {
  background-position: -220px -54px;
}

.indicator {
  border-radius: 2px;
  color: white;
  display: inline-block;
  font-family: sans-serif;
  font-size: 8pt;
  width: 50%;
}

.icon1 .indicator {
  background: #a00;
}

.icon2 .indicator {
  background: #0f0;
}

    3

      10

Here, I've got a span inside a div (class icon) and I'm setting the filter brightness on the div's like so:

$('.icon').css('filter', `brightness(${bright})`);

However, I'd like it to only affect that background, and not affect the little "indicator" span. That is, in the above snippet, the icon should be pulsing but the foreground indicators and their red/green backgrounds should remain unchanged. The only things I thought of to try failed:

function setBrightness (bright) {
  $('.icon').css('filter', `brightness(${bright})`);
  // None of these work:
  // $('.indicator').css('filter', '');
  // $('.indicator').css('filter', 'brightness(1.0)');
  // $('.indicator').css('filter', `brightness(${1.0/bright})`);
}

Also, it's important that I not make changes to the following:

Cannot change background-* CSS properties.

Cannot change structure of HTML, the span must remain a child of the div.

I don't actually need a solution that omits all child elements, by the way. I only need a single given child (those spans) unaffected, as the structure I'm working with does not have multiple children under each div; the example is representative. Not sure if that matters.

Is there a way to do this?

Body:
Changing the opacity of a parent element will always change the opacity of the child element. Sadly there is no way around that. However you can change the HTML structure and absolute position the elements on top of one another, and then only target the elements you want to fade.

$(document).ready(function(){
  function setBrightness (bright) {
  $('.icon').css('filter', `brightness(${bright})`);
}

window.setInterval(function () {
  let ms = new Date().getTime();
  let bright = Math.cos(2.0 * 3.14 * ms / 3000.0) + 1.0;
    setBrightness(bright);
  }, 50);
});

#bar {
  background: #222;
  font-size: 0;
 }

 .icon {
  background-image: url(https://cdn.sstatic.net/img/share-sprite-new.svg?v=78be252218f3);
  width: 36px;
  height: 34px;
  display: inline-block;
  position: absolute;
  top:0;
  left: 0;
 }

 .icon-wrap {
  width: 36px;
  height: 34px;
  text-align: center;
  position: relative;
  display: table-cell;
  /* normally middle but set to top to not obscure background for this example: */
 }

 .icon1 .icon {
  background-position: -141px -54px;
 }

 .icon2 .icon {
  background-position: -220px -54px;
 }

 .indicator {
  border-radius: 2px;
  color: white;
  font-family: sans-serif;
  font-size: 8pt;
  width: 18px;
  height: 14px;
  position: absolute;
  top:0;
  left:50%;
  margin-left: -9px;
 }

 .icon1 .indicator {
  background: #a00;
 }

 .icon2 .indicator {
  background: #0f0;
 }

<div id="bar">
  <div class="icon1 icon-wrap">
    <span class="icon"></span>
    <span class="indicator">3</span>
  </div>
  <div class="icon2 icon-wrap">
    <span class="icon"></span>
    <span class="indicator">10</span>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

It is also possible to do with CSS3 keyframes:

#bar {
  background: #222;
  font-size: 0;
}

.icon {
  background-image: url(https://cdn.sstatic.net/img/share-sprite-new.svg?v=78be252218f3);
  width: 36px;
  height: 34px;
  display: inline-block;
  position: absolute;
  top:0;
  left: 0;
  -webkit-filter: grayscale(200%); /* Safari 6.0 - 9.0 */
  filter: grayscale(200%);
}

.icon-wrap {
  width: 36px;
  height: 34px;
  text-align: center;
  position: relative;
  display: table-cell;
  /* normally middle but set to top to not obscure background for this example: */
}

.icon1 .icon {
  background-position: -141px -54px;
}

.icon2 .icon {
  background-position: -220px -54px;
}

.indicator {
  border-radius: 2px;
  color: white;
  font-family: sans-serif;
  font-size: 8pt;
  width: 18px;
  height: 14px;
  position: absolute;
  top:0;
  left:50%;
  margin-left: -9px;
}

.icon1 .indicator {
  background: #a00;
}

.icon2 .indicator {
  background: #0f0;
}

@keyframes fader {
  0%   {
    -webkit-filter: grayscale(200%); /* Safari 6.0 - 9.0 */
    filter: grayscale(200%);
  }
  50%  {
    -webkit-filter: grayscale(0%); /* Safari 6.0 - 9.0 */
    filter: grayscale(0%);
  }
  100% { opacity:1;
    -webkit-filter: grayscale(200%); /* Safari 6.0 - 9.0 */
    filter: grayscale(200%);
  }
}
@-o-keyframes fader {
  0%   {
   -webkit-filter: brightness(200%); /* Safari 6.0 - 9.0 */
   filter: brightness(200%);
 }
 50%  {
   -webkit-filter: brightness(0%); /* Safari 6.0 - 9.0 */
   filter: brightness(0%);
 }
 100% { opacity:1;
   -webkit-filter: brightness(200%); /* Safari 6.0 - 9.0 */
   filter: brightness(200%);
 }
}
@-moz-keyframes fader {
  0%   {
   -webkit-filter: brightness(200%); /* Safari 6.0 - 9.0 */
   filter: brightness(200%);
 }
 50%  {
   -webkit-filter: brightness(0%); /* Safari 6.0 - 9.0 */
   filter: brightness(0%);
 }
 100% { opacity:1;
   -webkit-filter: brightness(200%); /* Safari 6.0 - 9.0 */
   filter: brightness(200%);
 }
}
@-webkit-keyframes fader {
  0%   {
   -webkit-filter: brightness(200%); /* Safari 6.0 - 9.0 */
   filter: brightness(200%);
 }
 50%  {
   -webkit-filter: brightness(0%); /* Safari 6.0 - 9.0 */
   filter: brightness(0%);
 }
 100% { opacity:1;
   -webkit-filter: brightness(200%); /* Safari 6.0 - 9.0 */
   filter: brightness(200%);
 }
}
.icon {
   -webkit-animation: fader 3s infinite ease-in;
   -moz-animation: fader 3s infinite ease-in;
   -o-animation: fader 3s infinite ease-in;
   animation: fader 3s infinite ease-in;
}

<div id="bar">
  <div class="icon1 icon-wrap">
    <span class="icon"></span>
    <span class="indicator">3</span>
  </div>
  <div class="icon2 icon-wrap">
    <span class="icon"></span>
    <span class="indicator">10</span>
  </div>
</div>


问:
C# - Call stored procedure with type
I want to call a stored procedure from my database, but it also needs a List of attributes as a type and I placed a cursor on that type. But everytime I execute the command I get an exception back that the cursor is not open.

What I have now already

```<code>        using (Connection = new SqlConnection(ConnectionString))
        {
            Connection.Open();

            using (Command = new SqlCommand())
            {
                Command.Connection = Connection;
                Command.CommandText = "CreateCharacter";
                Command.CommandType = CommandType.StoredProcedure;
                Command.Parameters.AddWithValue("@Skills", skills);
                Command.Parameters.AddWithValue("@AccountId", accountId);
                Command.Parameters.AddWithValue("@ClassId", masteryId);
                Command.Parameters.AddWithValue("@RaceId", raceId);
                Command.Parameters.AddWithValue("@Name", name);

                try
                {
                    return character = LoadCharacter(Convert.ToInt32(Command.ExecuteScalar()));
                }

                catch (Exception)
                {
                    return null;
                }
            }
        }
</code>```

Type

```<code>CREATE TYPE dbo.AttributeList AS TABLE
(
    AttributeId integer,
    [Level] integer
);
GO
</code>```

Stored Procedure

```<code>CREATE PROCEDURE dbo.CreateCharacter (@Attributes AS dbo.AttributeList
READONLY, @AccountId integer, @ClassId integer, @RaceId integer, @Name
varchar(12))
AS
BEGIN
DECLARE AttributeCursor CURSOR FOR
SELECT
    AttributeId,
    [Level]
FROM @Attributes

INSERT INTO Character
    VALUES (@ClassId, @RaceId, NULL, @Name, 1, 0, 0)
DECLARE @Id integer
DECLARE @AttributeId integer
DECLARE @AttributeLevel integer
SET @Id = IDENT_CURRENT('Character');

UPDATE Account
SET CharacterId = @Id
WHERE Id = @AccountId

WHILE (@@FETCH_STATUS = 0)
BEGIN
    INSERT INTO Attribute_Character
        VALUES (@AttributeId, @Id, @AttributeLevel)
    FETCH NEXT FROM AttributeCursor INTO @AttributeId, @AttributeLevel
END
RETURN @Id;
END
</code>```

答:
In order to send a Table param you just have to build a DataTable on the C# side:

```<code>var table = new DataTable();
table.Columns.Add("AttributeID", typeof(int));
table.Columns.Add("Level", typeof(int));

//Add data
table.Rows.Add(new []{1, 2});

//More code
Command.Parameters.AddWithValue("@Attributes", table);
</code>```

And I think you don't need a cursor in the Procedure. Just insert the data:

```<code>INSERT INTO Attribute_Character(AttributeId, AttributeLevel)
SELECT AttributeId, AttributeLevel
FROM @Attributes
</code>```

Title: C# - Call stored procedure with type

Body:
I want to call a stored procedure from my database, but it also needs a List of attributes as a type and I placed a cursor on that type. But everytime I execute the command I get an exception back that the cursor is not open.

What I have now already

        using (Connection = new SqlConnection(ConnectionString))
        {
            Connection.Open();

            using (Command = new SqlCommand())
            {
                Command.Connection = Connection;
                Command.CommandText = "CreateCharacter";
                Command.CommandType = CommandType.StoredProcedure;
                Command.Parameters.AddWithValue("@Skills", skills);
                Command.Parameters.AddWithValue("@AccountId", accountId);
                Command.Parameters.AddWithValue("@ClassId", masteryId);
                Command.Parameters.AddWithValue("@RaceId", raceId);
                Command.Parameters.AddWithValue("@Name", name);

                try
                {
                    return character = LoadCharacter(Convert.ToInt32(Command.ExecuteScalar()));
                }

                catch (Exception)
                {
                    return null;
                }
            }
        }

Type

CREATE TYPE dbo.AttributeList AS TABLE
(
    AttributeId integer,
    [Level] integer
);
GO

Stored Procedure

CREATE PROCEDURE dbo.CreateCharacter (@Attributes AS dbo.AttributeList
READONLY, @AccountId integer, @ClassId integer, @RaceId integer, @Name
varchar(12))
AS
BEGIN
DECLARE AttributeCursor CURSOR FOR
SELECT
    AttributeId,
    [Level]
FROM @Attributes

INSERT INTO Character
    VALUES (@ClassId, @RaceId, NULL, @Name, 1, 0, 0)
DECLARE @Id integer
DECLARE @AttributeId integer
DECLARE @AttributeLevel integer
SET @Id = IDENT_CURRENT('Character');

UPDATE Account
SET CharacterId = @Id
WHERE Id = @AccountId

WHILE (@@FETCH_STATUS = 0)
BEGIN
    INSERT INTO Attribute_Character
        VALUES (@AttributeId, @Id, @AttributeLevel)
    FETCH NEXT FROM AttributeCursor INTO @AttributeId, @AttributeLevel
END
RETURN @Id;
END

Body:
In order to send a Table param you just have to build a DataTable on the C# side:

var table = new DataTable();
table.Columns.Add("AttributeID", typeof(int));
table.Columns.Add("Level", typeof(int));

//Add data
table.Rows.Add(new []{1, 2});

//More code
Command.Parameters.AddWithValue("@Attributes", table);

And I think you don't need a cursor in the Procedure. Just insert the data:

INSERT INTO Attribute_Character(AttributeId, AttributeLevel)
SELECT AttributeId, AttributeLevel
FROM @Attributes


问:
How to match a character to find if it is a special character in javascript
I am trying to find whether my string contains any special character. I am very new to javascript and would really appreciate your help.

Here is a simplified code :

```<code>function checkMe(text){
    var reg = '/[a-zA-Z0-9-]/gi';
    var character = text.charAt(0);
    if((character.match(reg)) == false){
        alert("special character found!!  ");
     }
}
</code>```

This is not giving desired output. Please help!!

答:
First of all, you need a regular expression and not a string with a regular expression inside.

Then you need just to check, because, you get for a single valid character an array with the matched character. If no match occurs, then String#match returns null.

function checkMe(text) {
    var reg = /[a-z0-9-]/gi;   // regular expr, A-Z is not necessary, because of flag i
    if (!text[0].match(reg)) { // test for falsyness
        console.log("special character found!");
    }
}

checkMe('Übermut');```

Body:
I am trying to find whether my string contains any special character. I am very new to javascript and would really appreciate your help.

Here is a simplified code :

function checkMe(text){
    var reg = '/[a-zA-Z0-9-]/gi';
    var character = text.charAt(0);
    if((character.match(reg)) == false){
        alert("special character found!!  ");
     }
}

This is not giving desired output. Please help!!


问:
how to set the template url in angular 2
I created a new angular app using @angular/cli. in that app template already have app component. inside that app component I want to use another component called user. so inside @Component there is a property called templateUrl and also some says to use only the template. so which one should I use and which is the best. currently I'm trying to use templateUrl with this.

think this is my app.component.ts

```<code>@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
</code>```

and this is my user.component.ts

```<code>@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
</code>```

so how can I use my user component with app component. I tried by giving relative paths but it didn't work and gave absolute path didn't work that too. I'm confused. hope your help with this.

答:
nothing to do with template url, just use the selector inside my app component like below.

inside my app.component.html we should use the user component selector name like below.

```<code><div class="row">
    <app-user></app-user>
</div>
</code>```

this will show the user component content inside the app component

Body:
I created a new angular app using @angular/cli. in that app template already have app component. inside that app component I want to use another component called user. so inside @Component there is a property called templateUrl and also some says to use only the template. so which one should I use and which is the best. currently I'm trying to use templateUrl with this.

think this is my app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

and this is my user.component.ts

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})

so how can I use my user component with app component. I tried by giving relative paths but it didn't work and gave absolute path didn't work that too. I'm confused. hope your help with this.

Body:
nothing to do with template url, just use the selector inside my app component like below.

inside my app.component.html we should use the user component selector name like below.

<div class="row">
    <app-user></app-user>
</div>

this will show the user component content inside the app component