问:
Android error No, minSdk(API 19) > deviceSdk(API 1)
I have just set up android studio and am trying to compile my first project. The project gets compiled but when the 'Choose Device' menu opens the device and state is shown as [OFFLINE] and compatible gives message Android error message Android error
'No, minSdk(API 19) > deviceSdk(API 1)'
 What does this mean? How can I solve it?

my build.grandle file looks like this

```<code>    apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.yaron.myapplication"
        minSdkVersion 19
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
}
</code>```

答:
On your file build.gradle you need to add  the correct API of your deviceSdk.

minSdkVersion 1

minSdk(API 19) > deviceSdk(API 1)

https://i.stack.imgur.com/AkEYY.png

i am using USB and my Connected Device

Body:
I have just set up android studio and am trying to compile my first project. The project gets compiled but when the 'Choose Device' menu opens the device and state is shown as [OFFLINE] and compatible gives message Android error message Android error
'No, minSdk(API 19) > deviceSdk(API 1)'
 What does this mean? How can I solve it?

my build.grandle file looks like this

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.yaron.myapplication"
        minSdkVersion 19
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
}


来源: stackexchange

问:
Fform method returns a blank page
I want my admin user to be able to approve a jobpost
so I defined a method in my jobposts controller like this:

```<code> public function approved(Request $request, JobPost $jobpost)
{
    //save
    $approved = JobPost::where('id', $jobpost->id)->update([
        'approval'=> $request->input('approved')
        ]);

    if($approved)
    {     $user = auth()->user();
        $jobposts = auth()->user()->JobPosts;
        $company = auth()->user()->company;
       return view('/JobPosts/admin/WaitingJobPosts',[
           'jobposts' => $jobposts,
           'company' => $company,
           'user' => $user,
       ]);
    }
</code>```

Then I defined a rout for it in my web.php:

```<code>Route::patch('jobposts.approval/approved', [
    'as'=>'jobposts.approved',
    'uses'=> 'JobPostsController@approved'
]);
</code>```

and in my view I have defined a form like this:

```<code> <form method="post" action="{{route('jobposts.approved', [$jobpost-> id])}}">
                                <input type="hidden" name="_method" value="patch">
                                <input type="hidden" name="approved" value="1">
                            {{--<form method="post" action="{{route('jobposts.approved', [$jobpost])}}">--}}
                                {{csrf_field()}}
                                <div class="form-group">
                                    {{--<input type="hidden" value="1" name="approval"/>--}}
                                    <button type="submit" class="btn btn-block btn-success">تایید</button>
                                </div>
                            </form>
</code>```

It returns a blank page and does not change the approval column value for the job post. The returned url is: http://127.0.0.1:8000/jobposts.approval/approved?
3
I'm a bit new to laravel.

答:
You are not returning a response in your approved action in case approving fails so you need to return a view or some sort of response.

Also, return view('/JobPosts/admin/WaitingJobPosts'... seems incorrect since you have to provide a view in dot notation in Laravel and not the actual path to the view.

You are type-hinting a job post so there is no need to run a find query. You can simply work with the $jobpost variable.

Second, your route seems incorrect. Change it as follows

```<code>Route::patch('jobposts/{job_post}/approved', 'JobPostsController@approved')->name('jobposts.approved');
</code>```

Finally, here is the form.

```<code><form method="post" action="{{ route('jobposts.approved', ['job_post' => $jobpost])}}">
    {{ csrf_field() }}
    {{ method_field('PATCH') }}
    <input type="hidden" name="approved" value="1">
    <div class="form-group">
        <button type="submit" class="btn btn-block btn-success">تایید</button>
    </div>
</form>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Fform method returns a blank page

Body:
I want my admin user to be able to approve a jobpost
so I defined a method in my jobposts controller like this:

 public function approved(Request $request, JobPost $jobpost)
{
    //save
    $approved = JobPost::where('id', $jobpost->id)->update([
        'approval'=> $request->input('approved')
        ]);

    if($approved)
    {     $user = auth()->user();
        $jobposts = auth()->user()->JobPosts;
        $company = auth()->user()->company;
       return view('/JobPosts/admin/WaitingJobPosts',[
           'jobposts' => $jobposts,
           'company' => $company,
           'user' => $user,
       ]);
    }

Then I defined a rout for it in my web.php:

Route::patch('jobposts.approval/approved', [
    'as'=>'jobposts.approved',
    'uses'=> 'JobPostsController@approved'
]);

and in my view I have defined a form like this:

 <form method="post" action="{{route('jobposts.approved', [$jobpost-> id])}}">
                                <input type="hidden" name="_method" value="patch">
                                <input type="hidden" name="approved" value="1">
                            {{--<form method="post" action="{{route('jobposts.approved', [$jobpost])}}">--}}
                                {{csrf_field()}}

                                    {{--<input type="hidden" value="1" name="approval"/>--}}
                                    <button type="submit" class="btn btn-block btn-success">تایید</button>

                            </form>

It returns a blank page and does not change the approval column value for the job post. The returned url is: http://127.0.0.1:8000/jobposts.approval/approved?
3
I'm a bit new to laravel.

Body:
You are not returning a response in your approved action in case approving fails so you need to return a view or some sort of response.

Also, return view('/JobPosts/admin/WaitingJobPosts'... seems incorrect since you have to provide a view in dot notation in Laravel and not the actual path to the view.

You are type-hinting a job post so there is no need to run a find query. You can simply work with the $jobpost variable.

Second, your route seems incorrect. Change it as follows

Route::patch('jobposts/{job_post}/approved', 'JobPostsController@approved')->name('jobposts.approved');

Finally, here is the form.

<form method="post" action="{{ route('jobposts.approved', ['job_post' => $jobpost])}}">
    {{ csrf_field() }}
    {{ method_field('PATCH') }}
    <input type="hidden" name="approved" value="1">
    <div class="form-group">
        <button type="submit" class="btn btn-block btn-success">تایید</button>
    </div>
</form>

ContentLicense: CC BY-SA 3.0


问:
MVC 2 Twitter Application
This is my first time here so I apologize in advance if this question is not relevant here. I have just started to learn C# and MVC 2. Most of my learning so far has been from examples and I wanted to learn from an example which I can learn a lot from.

So my example is I want to create a C# web-app for twitter. Meaning the web application that has a text box and a submit button using MVC 2 and entity framework and When any content is submitted via the text box, the content is posted to a Twitter account. The content and twitter id are logged to a database and the form is shown again with the most recent content on the page.

Much obliged to anyone who can help/guide me on this and truly appreciate the help.

Derek

答:
LinqToTwitter is one library that I used. I used it for a different purpose but it has the APIs that will help you build what you want. There are plenty more libraries which will help you building a twitter client if you wish to explore more.

Other post by Sergio has already pointed you to a right place regarding MVC.

ContentLicense: CC BY-SA 2.5

Title: MVC 2 Twitter Application


问:
Counting occurrences of a character in String (consecutive as one)
I am trying to figure out how to count the occurrences of a certain character in String such that the consecutive occurrence is considered as one. Like in string "PPPPAPAAPP" the occurrence of P as 3 and A as 2.</p>

答:
I think this will help you,</p>

```<code>   import java.util.*;

      public class MyClass {
       public static void main(String args[]) {
             Map<String,Integer> countMap = new HashMap<String,Integer>();
             String s = "PPPPPAAPAP";
             String prev = null;
             for(int i=0;i<s.length();i++){
              String c = String.valueOf(s.charAt(i));
              if(prev==null){
                countMap.put(c,new Integer(1));
              }else{
              if(!c.equals(prev)){

                if(countMap.containsKey(c)){

                      Integer count = countMap.get(c);
                      count = count +1;
                      countMap.put(c,count);

                }
               else{

                     countMap.put(c,new Integer(1));

               }
            }
        }
        prev = c;
      }
      for(String keys :countMap.keySet()){
        System.out.println("Keys:"+keys+"\t"+countMap.get(keys));
      }
     }
    }
</code>```

Body:
I think this will help you,

   import java.util.*;

      public class MyClass {
       public static void main(String args[]) {
             Map<String,Integer> countMap = new HashMap<String,Integer>();
             String s = "PPPPPAAPAP";
             String prev = null;
             for(int i=0;i<s.length();i++){
              String c = String.valueOf(s.charAt(i));
              if(prev==null){
                countMap.put(c,new Integer(1));
              }else{
              if(!c.equals(prev)){

                if(countMap.containsKey(c)){

                      Integer count = countMap.get(c);
                      count = count +1;
                      countMap.put(c,count);

                }
               else{

                     countMap.put(c,new Integer(1));

               }
            }
        }
        prev = c;
      }
      for(String keys :countMap.keySet()){
        System.out.println("Keys:"+keys+"\t"+countMap.get(keys));
      }
     }
    }


问:
how to compare date and display upcoming weeks data?
Requirement-- I want to display data of upcoming week.
Current position-- Below is my html code, i used *ngIf to compare deadline_date(list.deadline_dt) with today's date(this.datt1).I used date format (dd-MM-yy) but it does not compare two dates. so, i use 'timeAgo'.but still its not working.

```<code><ion-card>
<ion-card-header>
  Upcoming Week Tasks to do
</ion-card-header>
<ion-card-content>
  <!-- Add card content here! -->

  <ion-list *ngFor="let list of dataa" >

    <ion-item class="desc" *ngIf="(list.DEADLINE_DT | timeAgo) >= (this.datt1 | timeAgo)">
      <p style="color:#9ea5a9; margin-top:10px" item-start>{{list.TASKDESC}}</p>
      <p style="color:green"> {{list.DEADLINE_DT}} </p>
      <p style="color:#9ea5a9; margin-top:10px" item-end>{{list.ENTUSR }}</p>
      <hr/>

    </ion-item>

  </ion-list>

</ion-card-content>
</code>```

.ts

```<code>public datt=new Date();
 this.datt1=this.datepipe.transform(this.datt,'dd-MMM-yy');
console.log(this.datt1,"sysdat");
</code>```

enter image description here

答:
I'm guessing the timeAgo pipe tells you how far in the past a time is? I don't think we need that. You want to display the upcoming week which is not in the past. Also, you shouldn't need to pipe a Date object through anything in order to compare two dates. You can just compare them directly.

I'm guessing a problem is that you're comparing it to this.datt1. Is that a property of the component/page class? If so, you shouldn't put this, you just reference it with datt1.

Body:
Requirement-- I want to display data of upcoming week.
Current position-- Below is my html code, i used *ngIf to compare deadline_date(list.deadline_dt) with today's date(this.datt1).I used date format (dd-MM-yy) but it does not compare two dates. so, i use 'timeAgo'.but still its not working.

<ion-card>
<ion-card-header>
  Upcoming Week Tasks to do
</ion-card-header>
<ion-card-content>

  <ion-list *ngFor="let list of dataa" >

    <ion-item class="desc" *ngIf="(list.DEADLINE_DT | timeAgo) >= (this.datt1 | timeAgo)">

{{list.TASKDESC}}

 {{list.DEADLINE_DT}}

{{list.ENTUSR }}

    </ion-item>

  </ion-list>

</ion-card-content>

.ts

public datt=new Date();
 this.datt1=this.datepipe.transform(this.datt,'dd-MMM-yy');
console.log(this.datt1,"sysdat");

enter image description here


问:
Google App Engine GoogleCredential getApplicationDefault
I am trying to use GoogleCredential getApplicationDefault() to get access to the app engine default service account which I have already created using app engine dashboard. The code is as shown below.

```<code>    try{
        GoogleCredential credential = GoogleCredential.getApplicationDefault();
        if (credential.createScopedRequired()){
            ArrayList<String> scope = new ArrayList<String>();
            scope.add("https://www.googleapis.com/auth/devstorage.read_write");
            GoogleCredential scopedCredential = credential.createScoped(scope);
            scopedCredential.refreshToken();
            return scopedCredential.getAccessToken();
        }
    }
    catch(Exception ex){
        entityException = new Entity(Constants.ENTITY_EXCEPTION);
        entityException.setProperty("Exception",ex.getMessage());
        datastore.put(entityException);
    }
    return "";
</code>```

When scopedCredential.refreshToken() is called an exception happens with the message accounts.google.com

Also when I call scopedCredential.getServiceAccountId() and scopedCredential.getServiceAccountPrivateKeyId() I am getting the correct values of the default app engine service account.

Can anyone please help me with this.

Guys,

Can someone help me? I tried adding a new service account, created a p12 file instead of json etc. nothing seems to work. I hv no idea where I m going wrong. Please help.

答: Hey all I figured it out myself. I specified runtime as java8 and that was causing all the problems. guess these work only on java7 runtime. thanks.</p>

Body:
I am trying to use GoogleCredential getApplicationDefault() to get access to the app engine default service account which I have already created using app engine dashboard. The code is as shown below.

    try{
        GoogleCredential credential = GoogleCredential.getApplicationDefault();
        if (credential.createScopedRequired()){
            ArrayList<String> scope = new ArrayList<String>();
            scope.add("https://www.googleapis.com/auth/devstorage.read_write");
            GoogleCredential scopedCredential = credential.createScoped(scope);
            scopedCredential.refreshToken();
            return scopedCredential.getAccessToken();
        }
    }
    catch(Exception ex){
        entityException = new Entity(Constants.ENTITY_EXCEPTION);
        entityException.setProperty("Exception",ex.getMessage());
        datastore.put(entityException);
    }
    return "";

When scopedCredential.refreshToken() is called an exception happens with the message accounts.google.com

Also when I call scopedCredential.getServiceAccountId() and scopedCredential.getServiceAccountPrivateKeyId() I am getting the correct values of the default app engine service account.

Can anyone please help me with this.

Guys,

Can someone help me? I tried adding a new service account, created a p12 file instead of json etc. nothing seems to work. I hv no idea where I m going wrong. Please help.


答:
This shows your total correctly:</p>

```<code> public static void main (String Args[]){
Scanner in =new Scanner(System.in);
String s =in.next();
//HashSet hd =new HashSet();
int flag=0;
int count=1;
char a=s.charAt(0);
for(int i=1;i<s.length();i++)
{
    //hd.add(s.charAt(i));
    if(a==s.charAt(i))
    {
        continue;
    }
    else
    {
        a=s.charAt(i);
        count++;
    }
}
System.out.println(count);
        }
</code>```

Title: Counting occurrences of a character in String (consecutive as one)

Body: I am trying to figure out how to count the occurrences of a certain character in String such that the consecutive occurrence is considered as one. Like in string "PPPPAPAAPP" the occurrence of P as 3 and A as 2.

Body:
This shows your total correctly:

 public static void main (String Args[]){
Scanner in =new Scanner(System.in);
String s =in.next();
//HashSet hd =new HashSet();
int flag=0;
int count=1;
char a=s.charAt(0);
for(int i=1;i<s.length();i++)
{
    //hd.add(s.charAt(i));
    if(a==s.charAt(i))
    {
        continue;
    }
    else
    {
        a=s.charAt(i);
        count++;
    }
}
System.out.println(count);
        }


问:
#Stata remove rows before event
I have a unbelanced panel data and have hard time to analyze it

I would like to remove all rows that I have for each person before an event happens because I'm interested in the effect of the event on other variables

One problem are the many missing values, mostly every other year, the second problem are persons where the "event" occurs more than once, in this care I'm only interessted in the last event as you can see for person 3 in my picture

答:
If all you are interested in is identifying the last non-missing event, this should do the trick:

```<code>clear

* Input data
input float id str7 event
1 "1"
1 "missing"
1 "1"
1 "missing"
1 "0"
1 "missing"
2 "missing"
2 "0"
2 "missing"
2 "missing"
2 "1"
2 "missing"
2 "0"
3 "missing"
3 "0"
3 "1"
3 "0"
3 "missing"
3 "1"
3 "0"
end

* Re-structure event variable to byte and preserve sort order
replace event = "." if event == "missing"
destring event, replace
gen sortorder = _n

* Identify last event iff event == 1
bysort id event (sortorder): gen lastevent = _n == _N if event == 1
</code>```

I assume you have a time variable to preserve sort order better, but this should serve in the example. Once you have them identified, you can do with them what you wish. Use keep if lastevent == 1 to drop all necessary observations, or keep them around as missing (for event == missing | 0).

Title: #Stata remove rows before event

Body:
If all you are interested in is identifying the last non-missing event, this should do the trick:

clear

* Input data
input float id str7 event
1 "1"
1 "missing"
1 "1"
1 "missing"
1 "0"
1 "missing"
2 "missing"
2 "0"
2 "missing"
2 "missing"
2 "1"
2 "missing"
2 "0"
3 "missing"
3 "0"
3 "1"
3 "0"
3 "missing"
3 "1"
3 "0"
end

* Re-structure event variable to byte and preserve sort order
replace event = "." if event == "missing"
destring event, replace
gen sortorder = _n

* Identify last event iff event == 1
bysort id event (sortorder): gen lastevent = _n == _N if event == 1

I assume you have a time variable to preserve sort order better, but this should serve in the example. Once you have them identified, you can do with them what you wish. Use keep if lastevent == 1 to drop all necessary observations, or keep them around as missing (for event == missing | 0).


问:
How to cheat and avoid cheating in Flash games?
I'm writing a small online flash game that keeps high scores of players. Obviously I'd like to keep the players from cheating and getting an arbitrarily high score.

What are the most common methods for cheating in flash games and what can I do to make it hard to use them?

答:
To protect the high score as it's being sent to your server, either digitally sign it with a key embedded in your app, or else send an HMAC of the data (again, key embedded in app).

This suggestion assumes that people do not reverse-engineer your flash game. Not that this is hard, but in most cases, there are much easier ways to attack flash games, so this will raise the bar a little higher.

OwnerDisplayName: Shy

LastEditorDisplayName: Spoike

OwnerDisplayName: Chris Jester-Young


问:
Can I extend Androids Contacts database?
I was wondering is it possible to extend the Android Contacts database?

From here - http://d.android.com/reference/android/provider/ContactsContract.html

It says:

ContactsContract defines an extensible
  database of contact-related
  information

Extensible would suggest to me that I can add in more data to the contacts application outside the normal values such as Name, number, email, work number, home number etc..

However the examples of this page - http://d.android.com/reference/android/provider/ContactsContract.RawContacts.html only show how to insert the standard values like name and not how to add a new field to a contact.

Furthermore a search on the web does not turn up much information on extending the contacts data.

So I was wondering is it even possible or does the extensible refer to some other part of the contacts?

For example I would like to add in an additional field for contacts that have special privileges within my app so when a user looks at the contacts he or she knows what users they can use my app with.

Is this possible?

答:
You can store custom data in the contacts database. However "when a user looks at the contacts he or she knows what users they can use my app with," may not be possible if you are thinking users will be able to see the custom data you inserted while using the built-in Android Contacts application. You would have to display the custom data in your own application.

The javadocs for the ContactsContract.Data class should provide an explanation, as well as the Contacts article.

To use this you'll need to get a raw contact id by querying the RawContacts.

Here some example code that might help you get started...

```<code>private void makePowerful(int rawContactId) {
    ContentValues values = new ContentValues();
    values.put(Privilege.RAW_CONTACT_ID, rawContactId);
    values.put(Privilege.MIMETYPE, Privilege.CONTENT_ITEM_TYPE);
    values.put(Privilege.PRIVILEGE_LEVEL, Privilege.TYPE_POWERFUL);
    Uri uri = getContentResolver().insert(Data.CONTENT_URI, values);
}

public static final class Privilege implements ContactsContract.DataColumnsWithJoins, ContactsContract.CommonDataKinds.CommonColumns {
    public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/my_app_privilege";
    public static final int TYPE_POWERFUL = 1;
    public static final int TYPE_WEAK = 2;
    public static final String PRIVILEGE_LEVEL = DATA1;

    private Privilege() { }
}
</code>```

Body:
You can store custom data in the contacts database. However "when a user looks at the contacts he or she knows what users they can use my app with," may not be possible if you are thinking users will be able to see the custom data you inserted while using the built-in Android Contacts application. You would have to display the custom data in your own application.

The javadocs for the ContactsContract.Data class should provide an explanation, as well as the Contacts article.

To use this you'll need to get a raw contact id by querying the RawContacts.

Here some example code that might help you get started...

private void makePowerful(int rawContactId) {
    ContentValues values = new ContentValues();
    values.put(Privilege.RAW_CONTACT_ID, rawContactId);
    values.put(Privilege.MIMETYPE, Privilege.CONTENT_ITEM_TYPE);
    values.put(Privilege.PRIVILEGE_LEVEL, Privilege.TYPE_POWERFUL);
    Uri uri = getContentResolver().insert(Data.CONTENT_URI, values);
}

public static final class Privilege implements ContactsContract.DataColumnsWithJoins, ContactsContract.CommonDataKinds.CommonColumns {
    public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/my_app_privilege";
    public static final int TYPE_POWERFUL = 1;
    public static final int TYPE_WEAK = 2;
    public static final String PRIVILEGE_LEVEL = DATA1;

    private Privilege() { }
}


问:
React.js: Parent state values not passing into child properties + Fetch API data cannot be accessed
I am encountering several issues in a very basic color harmony picker I am developing. I am still a beginner in React and JSX. I initially had it put up on GitHub so the full files are on there, but I moved it over to Codepen instead.

Here is the Codepen

I made a lot of comments so sorry if they're a bit much, but hopefully they help. My problems don't begin until line 41, the displayHarmonies() method of the DataStore class. The values passed to it come from my App (parent) component:

```<code>displayHarmonies(color, harmony) {
    //color and harmony pass in dynamically just fine...this.data will not return anything, not even "undefined"
    console.log(color + " is the color and " + harmony + " is the harmony...and dataStore.displayHarmonies says: " + this.data);

    this.registeredWatchers.map((watcher) => {
        let result = "not green"; //result and resultHex will be determined with an underscore statement that will associate the color & harmony choice (primary + foreign key concept) and will return correct harmony color(s)
        let resultHex = "#HEX";

        appState.harmonyColor = result;
        appState.harmonyHex = resultHex;

        //call to app component's onDataChange() method, where new states will be set using the the appState data we just set in lines 49 and 50
        watcher.onDataChange();
    })
}
</code>```

As you can see from my first comment, the only part that doesn't log to the console is this.data, which is set in the constructor for the DataStore:

```<code>constructor(data) {
    //store that data in the object
    //data is not being received from object instance of dataStore on line 187
    this.data = data;
</code>```

On line 187 I make an instance of the DataStore and pass it a variable named data. Prior to being used, this variable is  initialized and then assigned to parsed JSON data via Fetch API:

```<code>let data = [];

//use polyfill for older browsers to do Ajax request
fetch("data/data.json").then((response) => {
//if we actually got something
    if (response.ok) {
        //then return the text we loaded
        return response.text();
    }
}).then((textResponse) => {
    data = JSON.parse(textResponse);
});
</code>```

If I console out the data in the second fetch .then() method, the JSON comes back just fine. As soon as I try to use the data variable anywhere else in the application, it returns nothing, as shown in the displayHarmonies() method's console.log(). So that's my first issue, but before I wanted to get to that, I wanted to solve the other issue I was having.

After the appState object (initialized prior to the DataStore, under the fetch statement) values get set to the result variables, displayHarmonies() runs watcher.onDataChange() (in the App component/parent) where the harmonyColor and harmonyHex states get assigned to the new appState values:

```<code>onDataChange() {
    console.log("onDataChange() in App called");
    this.setState({
        harmonyColor: appState.harmonyColor,
        harmonyHex: appState.harmonyHex
    })
}
</code>```

If I log these states out to the console, they are the right values, so that's not the problem. I then pass my states to the Display child component to be used as properties:

```<code><Display colorChoice={this.state.currentColor} harmonyChoice={this.state.currentHarmony} harmonyColor={this.state.harmonyColor} harmonyHex={this.state.harmonyHex} />
</code>```

I then set the Display component states in the constructor, assigning them to the props that are being sent to it with each new rendition of the application. I then display the data onto the DOM with the Display component's render method. What's odd is that the application will display the initial states (color: red, harmony: direct, harmonyColor: green, etc.) just fine, but as soon as a change is made, the data on the DOM does not update. The initial data is loaded in the same way though: by passing the parent's states into the child's properties. I have a few console.log()s in place that seem to prove why this should work, however, it does not. So what am I doing wrong?

Thanks, and hope this is not too much for one question!

答:
I tried cloning your repo, but it seems to be nested in another repo. With your current setup, this may work:

In your App component, you can put this lifecycle method to fetch the data, and then set the state with the received data.:

```<code>    componentDidMount(){
      fetch("data/data.json").then((response) => {
    //if we actually got something
    if (response.ok) {
        //then return the text we loaded
        return response.text();
    }
}).then((textResponse) => {
  this.setState({
    data : JSON.parse(textResponse);
  })

});
    }
</code>```

In the return statement, you can render the data store as a child so App can pass the data like this:

```<code>return (
    <div className="App">
      <DataStore data={this.state.data} />
      <h1>Color Harmonies</h1>
        {/* assigns this.colorChosen() & this.harmonyChosen() methods as properties to be called in Picker component */}
        <Picker colorChosen={this.colorChosen.bind(this)} harmonyChosen={this.harmonyChosen.bind(this)}/>
        {/* give Display component props that are dynamically set with states */}
        <Display colorChoice={this.state.currentColor} harmonyChoice={this.state.currentHarmony} harmonyColor={this.state.harmonyColor} harmonyHex={this.state.harmonyHex} />
    </div>
);
</code>```

Then, your data store should receive the data as a prop, so you can use it like this:

```<code>displayHarmonies(color, harmony) {
    //color and harmony pass in dynamically just fine...this.data will not return anything, not even "undefined"
    console.log(color + " is the color and " + harmony + " is the harmony...and dataStore.displayHarmonies says: " + this.props.data); //data is received in the properties so you can use it.
//other code

})
</code>```

Doing this, you should also be able to remove this.data from the constructor of the DataStore component.

Also in Data store, youll want to to allow it to accept props like this:

```<code>constructor(props){
super(props)
}
</code>```

Body:
I am encountering several issues in a very basic color harmony picker I am developing. I am still a beginner in React and JSX. I initially had it put up on GitHub so the full files are on there, but I moved it over to Codepen instead.

Here is the Codepen

I made a lot of comments so sorry if they're a bit much, but hopefully they help. My problems don't begin until line 41, the displayHarmonies() method of the DataStore class. The values passed to it come from my App (parent) component:

displayHarmonies(color, harmony) {
    //color and harmony pass in dynamically just fine...this.data will not return anything, not even "undefined"
    console.log(color + " is the color and " + harmony + " is the harmony...and dataStore.displayHarmonies says: " + this.data);

    this.registeredWatchers.map((watcher) => {
        let result = "not green"; //result and resultHex will be determined with an underscore statement that will associate the color & harmony choice (primary + foreign key concept) and will return correct harmony color(s)
        let resultHex = "#HEX";

        appState.harmonyColor = result;
        appState.harmonyHex = resultHex;

        //call to app component's onDataChange() method, where new states will be set using the the appState data we just set in lines 49 and 50
        watcher.onDataChange();
    })
}

As you can see from my first comment, the only part that doesn't log to the console is this.data, which is set in the constructor for the DataStore:

constructor(data) {
    //store that data in the object
    //data is not being received from object instance of dataStore on line 187
    this.data = data;

On line 187 I make an instance of the DataStore and pass it a variable named data. Prior to being used, this variable is  initialized and then assigned to parsed JSON data via Fetch API:

let data = [];

//use polyfill for older browsers to do Ajax request
fetch("data/data.json").then((response) => {
//if we actually got something
    if (response.ok) {
        //then return the text we loaded
        return response.text();
    }
}).then((textResponse) => {
    data = JSON.parse(textResponse);
});

If I console out the data in the second fetch .then() method, the JSON comes back just fine. As soon as I try to use the data variable anywhere else in the application, it returns nothing, as shown in the displayHarmonies() method's console.log(). So that's my first issue, but before I wanted to get to that, I wanted to solve the other issue I was having.

After the appState object (initialized prior to the DataStore, under the fetch statement) values get set to the result variables, displayHarmonies() runs watcher.onDataChange() (in the App component/parent) where the harmonyColor and harmonyHex states get assigned to the new appState values:

onDataChange() {
    console.log("onDataChange() in App called");
    this.setState({
        harmonyColor: appState.harmonyColor,
        harmonyHex: appState.harmonyHex
    })
}

If I log these states out to the console, they are the right values, so that's not the problem. I then pass my states to the Display child component to be used as properties:

<Display colorChoice={this.state.currentColor} harmonyChoice={this.state.currentHarmony} harmonyColor={this.state.harmonyColor} harmonyHex={this.state.harmonyHex} />

I then set the Display component states in the constructor, assigning them to the props that are being sent to it with each new rendition of the application. I then display the data onto the DOM with the Display component's render method. What's odd is that the application will display the initial states (color: red, harmony: direct, harmonyColor: green, etc.) just fine, but as soon as a change is made, the data on the DOM does not update. The initial data is loaded in the same way though: by passing the parent's states into the child's properties. I have a few console.log()s in place that seem to prove why this should work, however, it does not. So what am I doing wrong?

Thanks, and hope this is not too much for one question!

Body:
I tried cloning your repo, but it seems to be nested in another repo. With your current setup, this may work:

In your App component, you can put this lifecycle method to fetch the data, and then set the state with the received data.:

    componentDidMount(){
      fetch("data/data.json").then((response) => {
    //if we actually got something
    if (response.ok) {
        //then return the text we loaded
        return response.text();
    }
}).then((textResponse) => {
  this.setState({
    data : JSON.parse(textResponse);
  })

});
    }

In the return statement, you can render the data store as a child so App can pass the data like this:

return (
    <div className="App">
      <DataStore data={this.state.data} />
      <h1>Color Harmonies</h1>
        {/* assigns this.colorChosen() & this.harmonyChosen() methods as properties to be called in Picker component */}
        <Picker colorChosen={this.colorChosen.bind(this)} harmonyChosen={this.harmonyChosen.bind(this)}/>
        {/* give Display component props that are dynamically set with states */}
        <Display colorChoice={this.state.currentColor} harmonyChoice={this.state.currentHarmony} harmonyColor={this.state.harmonyColor} harmonyHex={this.state.harmonyHex} />
    </div>
);

Then, your data store should receive the data as a prop, so you can use it like this:

displayHarmonies(color, harmony) {
    //color and harmony pass in dynamically just fine...this.data will not return anything, not even "undefined"
    console.log(color + " is the color and " + harmony + " is the harmony...and dataStore.displayHarmonies says: " + this.props.data); //data is received in the properties so you can use it.
//other code

})

Doing this, you should also be able to remove this.data from the constructor of the DataStore component.

Also in Data store, youll want to to allow it to accept props like this:

constructor(props){
super(props)
}


问:
SQL Server function to return minimum date (January 1, 1753)
I am looking for a SQL Server function to return the minimum value for datetime, namely January 1, 1753. I'd rather not hardcode that date value into my script.

Does anything like that exist? (For comparison, in C#, I could just do DateTime.MinValue)
Or would I have to write this myself?

I am using Microsoft SQL Server 2008 Express.

答:
This is what I use to get the minimum date in SQL Server. Please note that it is globalisation friendly:

```<code>CREATE FUNCTION [dbo].[DateTimeMinValue]()
RETURNS datetime
AS
BEGIN
  RETURN (SELECT
    CAST('17530101' AS datetime))
END
</code>```

Call using:

```<code>SELECT [dbo].[DateTimeMinValue]()
</code>```

Body:
This is what I use to get the minimum date in SQL Server. Please note that it is globalisation friendly:

CREATE FUNCTION [dbo].[DateTimeMinValue]()
RETURNS datetime
AS
BEGIN
  RETURN (SELECT
    CAST('17530101' AS datetime))
END

Call using:

SELECT [dbo].[DateTimeMinValue]()


问:
How to load Table View in Main View Controller before segueing
Working on Swift 3 Xcode 9.1

I have two view controllers (one MainView and one Table View)

Problem: The Table View loads data from an API and displays it, however it take too long. I'm trying to have the load occur on the Main Controller.

I tried creating a custom method How to instantiate and load a view controller before segueing to it using swift

However the Table View has too many functions and I'm not sure how to call it.

Table View Code:

```<code>public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return array.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return cell
}

func loadData(){
 //loads data
 DispatchQueue.main.sync(execute:{
    self.tableView.reloadData()
}
</code>```

Question: Is creating a custom method the best way or is there another way? Please note I'm trying to do all this is the Main View Controller so the data can load once I segue to the Table View.

答: To load tablview in main view before segueing you can use NSNotificationCenter. It is call in ViewDidLoad so it will reload data.</p>

Body:
Working on Swift 3 Xcode 9.1

I have two view controllers (one MainView and one Table View)

Problem: The Table View loads data from an API and displays it, however it take too long. I'm trying to have the load occur on the Main Controller.

I tried creating a custom method How to instantiate and load a view controller before segueing to it using swift

However the Table View has too many functions and I'm not sure how to call it.

Table View Code:

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return array.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return cell
}

func loadData(){
 //loads data
 DispatchQueue.main.sync(execute:{
    self.tableView.reloadData()
}

Question: Is creating a custom method the best way or is there another way? Please note I'm trying to do all this is the Main View Controller so the data can load once I segue to the Table View.


问:
Method to go in which class?
I have 2 classes, player and game and a method called get_player_games($player_id). Which class does this method belong to?

I seem to run into this problem a bit, where I'm not 100% sure which class the method should go in. Is it just a matter of preference?

Thanks

答:
It's a typical cross-reference sort of situation -- to be completely objective, it can go in either class.  It really is a matter of preference, assuming that a player can have multiple games and a game can be associated with multiple players.

That said, I've always approached it philosophically from the way you're inclined to name the method in the first place -- get_player_games() sounds like you're interested in the games for a particular player. The player is the subject of interest (based on the limited English-style grammar of the method name), the games happened to be the detail associated with that.  If you had said get_game_players() or get_games_for_player(), then I would say that the games are the subject of interest, not the player.

Obviously, I'm biased by the noun you chose first (again, from a biased English grammar point of view), but since you can argue that the method belongs in either class, it's the only possible basis to use in such a case.

Again, it's somewhat of an arbitrary decision, but I've always been inclined to follow what the method naming rhetorically suggests to me about in which class it belongs.

Title: Method to go in which class?


问:
Using (OSX) Core MIDI in a c++ project
Here is the (Objective C) documentation for Core Midi: https://developer.apple.com/documentation/coremidi

How can I learn what is expected of me to be able to utilize this in a C++ project?

(I guess a more fundamental question is also: Can I use Core MIDI in a C++ project? - but I've seen other stackoverflow questions where the answer appears to be "yes" [then again, those were from years ago...])

What do I need to do to get this set up- to the point where I can start using the API? The documentation doesn't so much as show what frameworks are used, what header files are required, etc...

So, what are the steps to get started?

Ideally, I'd like to be able to compile from a simple makefile.

答:
The majority of the CoreMIDI API is plain old C. You can easily call it from C++ code without doing anything special.

(The Apple docs have a language toggle between "Swift" and "Objective-C", but don't take "Objective-C" literally. It really means "C family, either C or Objective-C". Toggling it to Swift shows you the same APIs, but in the translated form that's visible to Swift.)

Specifically, see CoreMIDI/MIDIServices.h.

The oldest and simplest piece of CoreMIDI sample code, "Echo.cpp", is in fact C++. It reads MIDI input from all sources and sends that MIDI data to the first available destination (on channel 1). It's very rough, but you have to start somewhere.

To compile:

```<code>clang Echo.cpp -framework CoreMIDI -framework CoreFoundation -o Echo
</code>```

The code:

```<code>/*  Copyright © 2007 Apple Inc. All Rights Reserved.

Disclaimer: IMPORTANT:  This Apple software is supplied to you by
        Apple Inc. ("Apple") in consideration of your agreement to the
        following terms, and your use, installation, modification or
        redistribution of this Apple software constitutes acceptance of these
        terms.  If you do not agree with these terms, please do not use,
        install, modify or redistribute this Apple software.

        In consideration of your agreement to abide by the following terms, and
        subject to these terms, Apple grants you a personal, non-exclusive
        license, under Apple's copyrights in this original Apple software (the
        "Apple Software"), to use, reproduce, modify and redistribute the Apple
        Software, with or without modifications, in source and/or binary forms;
        provided that if you redistribute the Apple Software in its entirety and
        without modifications, you must retain this notice and the following
        text and disclaimers in all such redistributions of the Apple Software.
        Neither the name, trademarks, service marks or logos of Apple Inc.
        may be used to endorse or promote products derived from the Apple
        Software without specific prior written permission from Apple.  Except
        as expressly stated in this notice, no other rights or licenses, express
        or implied, are granted by Apple herein, including but not limited to
        any patent rights that may be infringed by your derivative works or by
        other works in which the Apple Software may be incorporated.

        The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
        MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
        THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
        FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
        OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.

        IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
        OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
        SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
        INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
        MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
        AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
        STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
        POSSIBILITY OF SUCH DAMAGE.
*/
#include <CoreMIDI/MIDIServices.h>
#include <CoreFoundation/CFRunLoop.h>
#include <stdio.h>

// ___________________________________________________________________________________________
// test program to echo MIDI In to Out
// ___________________________________________________________________________________________

MIDIPortRef     gOutPort = NULL;
MIDIEndpointRef gDest = NULL;
int             gChannel = 0;

static void MyReadProc(const MIDIPacketList *pktlist, void *refCon, void *connRefCon)
{
    if (gOutPort != NULL && gDest != NULL) {
        MIDIPacket *packet = (MIDIPacket *)pktlist->packet; // remove const (!)
        for (unsigned int j = 0; j < pktlist->numPackets; ++j) {
            for (int i = 0; i < packet->length; ++i) {
//              printf("%02X ", packet->data[i]);

                // rechannelize status bytes
                if (packet->data[i] >= 0x80 && packet->data[i] < 0xF0)
                    packet->data[i] = (packet->data[i] & 0xF0) | gChannel;
            }

//          printf("\n");
            packet = MIDIPacketNext(packet);
        }

        MIDISend(gOutPort, gDest, pktlist);
    }
}

int     main(int argc, char *argv[])
{
    if (argc >= 2) {
        // first argument, if present, is the MIDI channel number to echo to (1-16)
        sscanf(argv[1], "%d", &gChannel);
        if (gChannel < 1) gChannel = 1;
        else if (gChannel > 16) gChannel = 16;
        --gChannel; // convert to 0-15
    }

    // create client and ports
    MIDIClientRef client = NULL;
    MIDIClientCreate(CFSTR("MIDI Echo"), NULL, NULL, &client);

    MIDIPortRef inPort = NULL;
    MIDIInputPortCreate(client, CFSTR("Input port"), MyReadProc, NULL, &inPort);
    MIDIOutputPortCreate(client, CFSTR("Output port"), &gOutPort);

    // enumerate devices (not really related to purpose of the echo program
    // but shows how to get information about devices)
    int i, n;
    CFStringRef pname, pmanuf, pmodel;
    char name[64], manuf[64], model[64];

    n = MIDIGetNumberOfDevices();
    for (i = 0; i < n; ++i) {
        MIDIDeviceRef dev = MIDIGetDevice(i);

        MIDIObjectGetStringProperty(dev, kMIDIPropertyName, &pname);
        MIDIObjectGetStringProperty(dev, kMIDIPropertyManufacturer, &pmanuf);
        MIDIObjectGetStringProperty(dev, kMIDIPropertyModel, &pmodel);

        CFStringGetCString(pname, name, sizeof(name), 0);
        CFStringGetCString(pmanuf, manuf, sizeof(manuf), 0);
        CFStringGetCString(pmodel, model, sizeof(model), 0);
        CFRelease(pname);
        CFRelease(pmanuf);
        CFRelease(pmodel);

        printf("name=%s, manuf=%s, model=%s\n", name, manuf, model);
    }

    // open connections from all sources
    n = MIDIGetNumberOfSources();
    printf("%d sources\n", n);
    for (i = 0; i < n; ++i) {
        MIDIEndpointRef src = MIDIGetSource(i);
        MIDIPortConnectSource(inPort, src, NULL);
    }

    // find the first destination
    n = MIDIGetNumberOfDestinations();
    if (n > 0)
        gDest = MIDIGetDestination(0);

    if (gDest != NULL) {
        MIDIObjectGetStringProperty(gDest, kMIDIPropertyName, &pname);
        CFStringGetCString(pname, name, sizeof(name), 0);
        CFRelease(pname);
        printf("Echoing to channel %d of %s\n", gChannel + 1, name);
    } else {
        printf("No MIDI destinations present\n");
    }

    CFRunLoopRun();
    // run until aborted with control-C

    return 0;
}
</code>```

Title: Using (OSX) Core MIDI in a c++ project

Body:
The majority of the CoreMIDI API is plain old C. You can easily call it from C++ code without doing anything special.

(The Apple docs have a language toggle between "Swift" and "Objective-C", but don't take "Objective-C" literally. It really means "C family, either C or Objective-C". Toggling it to Swift shows you the same APIs, but in the translated form that's visible to Swift.)

Specifically, see CoreMIDI/MIDIServices.h.

The oldest and simplest piece of CoreMIDI sample code, "Echo.cpp", is in fact C++. It reads MIDI input from all sources and sends that MIDI data to the first available destination (on channel 1). It's very rough, but you have to start somewhere.

To compile:

clang Echo.cpp -framework CoreMIDI -framework CoreFoundation -o Echo

The code:

/*  Copyright © 2007 Apple Inc. All Rights Reserved.

Disclaimer: IMPORTANT:  This Apple software is supplied to you by
        Apple Inc. ("Apple") in consideration of your agreement to the
        following terms, and your use, installation, modification or
        redistribution of this Apple software constitutes acceptance of these
        terms.  If you do not agree with these terms, please do not use,
        install, modify or redistribute this Apple software.

        In consideration of your agreement to abide by the following terms, and
        subject to these terms, Apple grants you a personal, non-exclusive
        license, under Apple's copyrights in this original Apple software (the
        "Apple Software"), to use, reproduce, modify and redistribute the Apple
        Software, with or without modifications, in source and/or binary forms;
        provided that if you redistribute the Apple Software in its entirety and
        without modifications, you must retain this notice and the following
        text and disclaimers in all such redistributions of the Apple Software.
        Neither the name, trademarks, service marks or logos of Apple Inc.
        may be used to endorse or promote products derived from the Apple
        Software without specific prior written permission from Apple.  Except
        as expressly stated in this notice, no other rights or licenses, express
        or implied, are granted by Apple herein, including but not limited to
        any patent rights that may be infringed by your derivative works or by
        other works in which the Apple Software may be incorporated.

        The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
        MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
        THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
        FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
        OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.

        IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
        OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
        SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
        INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
        MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
        AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
        STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
        POSSIBILITY OF SUCH DAMAGE.
*/
#include <CoreMIDI/MIDIServices.h>
#include <CoreFoundation/CFRunLoop.h>
#include <stdio.h>

// ___________________________________________________________________________________________
// test program to echo MIDI In to Out
// ___________________________________________________________________________________________

MIDIPortRef     gOutPort = NULL;
MIDIEndpointRef gDest = NULL;
int             gChannel = 0;

static void MyReadProc(const MIDIPacketList *pktlist, void *refCon, void *connRefCon)
{
    if (gOutPort != NULL && gDest != NULL) {
        MIDIPacket *packet = (MIDIPacket *)pktlist->packet; // remove const (!)
        for (unsigned int j = 0; j < pktlist->numPackets; ++j) {
            for (int i = 0; i < packet->length; ++i) {
//              printf("%02X ", packet->data[i]);

                // rechannelize status bytes
                if (packet->data[i] >= 0x80 && packet->data[i] < 0xF0)
                    packet->data[i] = (packet->data[i] & 0xF0) | gChannel;
            }

//          printf("\n");
            packet = MIDIPacketNext(packet);
        }

        MIDISend(gOutPort, gDest, pktlist);
    }
}

int     main(int argc, char *argv[])
{
    if (argc >= 2) {
        // first argument, if present, is the MIDI channel number to echo to (1-16)
        sscanf(argv[1], "%d", &gChannel);
        if (gChannel < 1) gChannel = 1;
        else if (gChannel > 16) gChannel = 16;
        --gChannel; // convert to 0-15
    }

    // create client and ports
    MIDIClientRef client = NULL;
    MIDIClientCreate(CFSTR("MIDI Echo"), NULL, NULL, &client);

    MIDIPortRef inPort = NULL;
    MIDIInputPortCreate(client, CFSTR("Input port"), MyReadProc, NULL, &inPort);
    MIDIOutputPortCreate(client, CFSTR("Output port"), &gOutPort);

    // enumerate devices (not really related to purpose of the echo program
    // but shows how to get information about devices)
    int i, n;
    CFStringRef pname, pmanuf, pmodel;
    char name[64], manuf[64], model[64];

    n = MIDIGetNumberOfDevices();
    for (i = 0; i < n; ++i) {
        MIDIDeviceRef dev = MIDIGetDevice(i);

        MIDIObjectGetStringProperty(dev, kMIDIPropertyName, &pname);
        MIDIObjectGetStringProperty(dev, kMIDIPropertyManufacturer, &pmanuf);
        MIDIObjectGetStringProperty(dev, kMIDIPropertyModel, &pmodel);

        CFStringGetCString(pname, name, sizeof(name), 0);
        CFStringGetCString(pmanuf, manuf, sizeof(manuf), 0);
        CFStringGetCString(pmodel, model, sizeof(model), 0);
        CFRelease(pname);
        CFRelease(pmanuf);
        CFRelease(pmodel);

        printf("name=%s, manuf=%s, model=%s\n", name, manuf, model);
    }

    // open connections from all sources
    n = MIDIGetNumberOfSources();
    printf("%d sources\n", n);
    for (i = 0; i < n; ++i) {
        MIDIEndpointRef src = MIDIGetSource(i);
        MIDIPortConnectSource(inPort, src, NULL);
    }

    // find the first destination
    n = MIDIGetNumberOfDestinations();
    if (n > 0)
        gDest = MIDIGetDestination(0);

    if (gDest != NULL) {
        MIDIObjectGetStringProperty(gDest, kMIDIPropertyName, &pname);
        CFStringGetCString(pname, name, sizeof(name), 0);
        CFRelease(pname);
        printf("Echoing to channel %d of %s\n", gChannel + 1, name);
    } else {
        printf("No MIDI destinations present\n");
    }

    CFRunLoopRun();
    // run until aborted with control-C

    return 0;
}


问:
overflow:hidden not working with border-radius in Chrome
I'm trying to make a circle-shaped image with an overlay that shows on hover. However, the "hitbox" of hovering (and clicking) is incorrect, as shown in the snippet below.

This issue seems to only occur in Chrome (not sure about Safari). I've found some fixes on the Internet, but none of them worked. JSFiddle for testing

$(document).ready(function() {
 $(".circle").click(function() {
  alert($(this).attr("id"));
 });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
 width: 100%;
 padding-bottom: 75%;
 position: relative;
 overflow: hidden;
 background-color: #eee;
}
.circle {
 position: absolute;
 width: 25%;
 padding-bottom: 25%;
 border-radius: 50%;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 overflow: hidden;
 cursor: pointer;
 /*https://stackoverflow.com/a/32987370/5532169*/
 -webkit-backface-visibility: hidden;
 -moz-backface-visibility: hidden;
 /*https://stackoverflow.com/a/25206004/5532169*/
 z-index: 1;
 /*https://stackoverflow.com/a/10296258/5532169*/
 -webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
 /*https://stackoverflow.com/a/16878347/5532169*/
 -webkit-mask-image: -webkit-radial-gradient(circle, white, black);
}
.mid {
 width: 100%;
 height: 100%;
 position: absolute;
}
.inner {
 width: 100%;
 height: 100%;
 position: relative;
}
.inner>* {
 position: absolute;
 top: 0;
 bottom: 0;
 left: 0;
 right: 0;
 width: 100%;
 height: 100%;
}
.hover {
 background-color: rgba(255, 255, 255, 0.6);
 opacity: 0;
 transition: opacity 0.5s;
}
.hover:hover {
 opacity: 100;
 transition: opacity 0.5s;
}
span {
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 width: 72%;
 text-align: center;
 font-family: monospace;
 font-size: 2em;
 font-weight: bold;
 color: #08f;
}</code>```

    Hello World!

```

Edit: Tested in Firefox 57, works without problem. IE and Edge were tested already, so it's a Chrome-/webkit-specific issue.

答:
The blocks in HTML are square defined by position (x, y) and size (width, height) so the browser can have a simplified idea of what is on the page and interact with. So even with border-radius, mask-image, etc... your .circle div is still a square with coming drawn within.

To avoid that, you can't use a dynamic selector like :hover because it will use the shape of the div and that is a square. You need to use javascript to detect mouse position when hovering your block and with that execute an animation (with sinus and cosinus calculation).

You can get the mouse position with something like this :

```<code><div class="circle" onmouseover="hoverFunction(e)"></div>
<script>
function hoverFunction(e) {
  var x = e.clientX;
  var y = e.clientY;
}
</script>
</code>```

I also found this topic talking about getting elements position on the page.

Body:
I'm trying to make a circle-shaped image with an overlay that shows on hover. However, the "hitbox" of hovering (and clicking) is incorrect, as shown in the snippet below.

This issue seems to only occur in Chrome (not sure about Safari). I've found some fixes on the Internet, but none of them worked. JSFiddle for testing

$(document).ready(function() {
 $(".circle").click(function() {
  alert($(this).attr("id"));
 });
});

#canvas {
 width: 100%;
 padding-bottom: 75%;
 position: relative;
 overflow: hidden;
 background-color: #eee;
}
.circle {
 position: absolute;
 width: 25%;
 padding-bottom: 25%;
 border-radius: 50%;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 overflow: hidden;
 cursor: pointer;
 /*https://stackoverflow.com/a/32987370/5532169*/
 -webkit-backface-visibility: hidden;
 -moz-backface-visibility: hidden;
 /*https://stackoverflow.com/a/25206004/5532169*/
 z-index: 1;
 /*https://stackoverflow.com/a/10296258/5532169*/
 -webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
 /*https://stackoverflow.com/a/16878347/5532169*/
 -webkit-mask-image: -webkit-radial-gradient(circle, white, black);
}
.mid {
 width: 100%;
 height: 100%;
 position: absolute;
}
.inner {
 width: 100%;
 height: 100%;
 position: relative;
}
.inner>* {
 position: absolute;
 top: 0;
 bottom: 0;
 left: 0;
 right: 0;
 width: 100%;
 height: 100%;
}
.hover {
 background-color: rgba(255, 255, 255, 0.6);
 opacity: 0;
 transition: opacity 0.5s;
}
.hover:hover {
 opacity: 100;
 transition: opacity 0.5s;
}
span {
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 width: 72%;
 text-align: center;
 font-family: monospace;
 font-size: 2em;
 font-weight: bold;
 color: #08f;
}

    Hello World!

Edit: Tested in Firefox 57, works without problem. IE and Edge were tested already, so it's a Chrome-/webkit-specific issue.

Body:
The blocks in HTML are square defined by position (x, y) and size (width, height) so the browser can have a simplified idea of what is on the page and interact with. So even with border-radius, mask-image, etc... your .circle div is still a square with coming drawn within.

To avoid that, you can't use a dynamic selector like :hover because it will use the shape of the div and that is a square. You need to use javascript to detect mouse position when hovering your block and with that execute an animation (with sinus and cosinus calculation).

You can get the mouse position with something like this :

<div class="circle" onmouseover="hoverFunction(e)"></div>
<script>
function hoverFunction(e) {
  var x = e.clientX;
  var y = e.clientY;
}
</script>

I also found this topic talking about getting elements position on the page.


问:
How to get all images from specific folder?
In my application,I want to read the all images from specific folder in File explorer and iterate in for loop. How can i do this?</p>

答:
use this one</p>

```<code>    private void showImageList() {
    File file = new
    File(android.os.Environment.getExternalStorageDirectory() + "/SpyCam/");
    if (file.exists()) {
        String[] fileListVideo = file.list();
        Collections.addAll(arrayList, fileListVideo);

    }
</code>```

Body:
use this one

    private void showImageList() {
    File file = new
    File(android.os.Environment.getExternalStorageDirectory() + "/SpyCam/");
    if (file.exists()) {
        String[] fileListVideo = file.list();
        Collections.addAll(arrayList, fileListVideo);

    }


问:
How can I make the following picture as a network in R (qgraph or igraph)?
I would like to make the following picture in R. I draw it but i would like to weight the edge size according to their value, use this two different colors (red and blue), and two different edge types (dashed and not dashed). How do I do this?

network drawing

Here is the code for the dataframe

```<code>data.frame(Node = c("MF", "MF", "SF","SF", "AFS","AFS"), Edge.col= c(rep(c("Blue","Red"),3)), RC = c(215, 79, 38, 22, 659, 43), SER = c(285, 43, 120, 44, 252, 95))
</code>```

答:
I finally managed to make the picture. I couldn't do in R, but I used the software graphviz. Below I show the code:</p>

```<code>digraph g {
layout = "neato"

MF -> SER [color=blue, penwidth=3.24, label = "285"];
MF -> SER [color=red, penwidth=0.49, label = "43"];
MF -> RC [style=dashed, color=blue, penwidth=2.44, label = "215"];
MF -> RC [style=dashed, color=red, penwidth=0.9, label = "79"];
SF -> SER [color=blue, penwidth=1.36, label = "120"];
SF -> SER [color=red, penwidth=0.5, label = "44"];
SF -> RC [style=dashed, color=blue, penwidth=0.43, label = "38"];
SF -> RC [style=dashed, color=red, penwidth=0.25, label = "22"];
AFS -> SER [color=blue, penwidth=2.86, label = "252"];
AFS -> SER [color=red, penwidth=1.08, label = "95"];
AFS -> RC [style=dashed, color=blue, penwidth=7.5, label = "659"];
AFS -> RC [style=dashed, color=red, penwidth=0.49, label = "43"];

MF[pos="0,2!", height = 1, width = 1.5, fontsize = 28, fontname = "Helvetica"]
SF [pos="-2,-2!", height = 1, width = 1.5, fontsize = 28, fontname = "Helvetica"]
AFS [pos="2,-2!", height = 1, width = 1.5, fontsize = 28, fontname = "Helvetica"]
RC [pos="1,0!", label = "BB",shape=Mdiamond, height = 1, width = 1.5, fontsize = 28, fontname = "Helvetica"];
SER [pos="-1,0!", label = "P-S", shape=Msquare, height = 1, width = 1, fontsize = 28, fontname = "Helvetica"];
}
</code>```

Body:
I would like to make the following picture in R. I draw it but i would like to weight the edge size according to their value, use this two different colors (red and blue), and two different edge types (dashed and not dashed). How do I do this?

network drawing

Here is the code for the dataframe

data.frame(Node = c("MF", "MF", "SF","SF", "AFS","AFS"), Edge.col= c(rep(c("Blue","Red"),3)), RC = c(215, 79, 38, 22, 659, 43), SER = c(285, 43, 120, 44, 252, 95))

Body:
I finally managed to make the picture. I couldn't do in R, but I used the software graphviz. Below I show the code:

digraph g {
layout = "neato"

MF -> SER [color=blue, penwidth=3.24, label = "285"];
MF -> SER [color=red, penwidth=0.49, label = "43"];
MF -> RC [style=dashed, color=blue, penwidth=2.44, label = "215"];
MF -> RC [style=dashed, color=red, penwidth=0.9, label = "79"];
SF -> SER [color=blue, penwidth=1.36, label = "120"];
SF -> SER [color=red, penwidth=0.5, label = "44"];
SF -> RC [style=dashed, color=blue, penwidth=0.43, label = "38"];
SF -> RC [style=dashed, color=red, penwidth=0.25, label = "22"];
AFS -> SER [color=blue, penwidth=2.86, label = "252"];
AFS -> SER [color=red, penwidth=1.08, label = "95"];
AFS -> RC [style=dashed, color=blue, penwidth=7.5, label = "659"];
AFS -> RC [style=dashed, color=red, penwidth=0.49, label = "43"];

MF[pos="0,2!", height = 1, width = 1.5, fontsize = 28, fontname = "Helvetica"]
SF [pos="-2,-2!", height = 1, width = 1.5, fontsize = 28, fontname = "Helvetica"]
AFS [pos="2,-2!", height = 1, width = 1.5, fontsize = 28, fontname = "Helvetica"]
RC [pos="1,0!", label = "BB",shape=Mdiamond, height = 1, width = 1.5, fontsize = 28, fontname = "Helvetica"];
SER [pos="-1,0!", label = "P-S", shape=Msquare, height = 1, width = 1, fontsize = 28, fontname = "Helvetica"];
}


问:
Sum and Echo Column Data from MySQL Database
I am attempting to sum the data from a specific column in a MySQL database and then echo it to the page. My code is as follows:

```<code><?php
//Trackingboard Display
$mysqli = new mysqli('localhost', 'root', '', 'disolDemo');
$query = $mysqli->query("SELECT sum(totLocMiles) FROM odoboard WHERE waybill_ID = '3'") or die($msqli->error);
$sumTot = mysql_fetch_array($query);
echo $sumTot[0];
?>
</code>```

What am I doing wrong?

答:
you're mixing mysqli with mysql

try this

```<code>$mysqli = new mysqli('localhost', 'root', '', 'disolDemo');
$query = $mysqli->query("SELECT sum(totLocMiles) as sum FROM odoboard WHERE waybill_ID = '3'") or die($msqli->error);

 while($row = $query->fetch_assoc())
    {
        echo $row['sum'];

    }
</code>```

Body:
I am attempting to sum the data from a specific column in a MySQL database and then echo it to the page. My code is as follows:

<?php
//Trackingboard Display
$mysqli = new mysqli('localhost', 'root', '', 'disolDemo');
$query = $mysqli->query("SELECT sum(totLocMiles) FROM odoboard WHERE waybill_ID = '3'") or die($msqli->error);
$sumTot = mysql_fetch_array($query);
echo $sumTot[0];
?>

What am I doing wrong?

Body:
you're mixing mysqli with mysql

try this

$mysqli = new mysqli('localhost', 'root', '', 'disolDemo');
$query = $mysqli->query("SELECT sum(totLocMiles) as sum FROM odoboard WHERE waybill_ID = '3'") or die($msqli->error);

 while($row = $query->fetch_assoc())
    {
        echo $row['sum'];

    }


问:
Correct usage of spring @Autowired annotation
I'm working on a jax-rs project for an RESTFul API

I choose to use spring in order to automatically inject my dependencies

```<code>import org.springframework.beans.factory.annotation.Autowired;

@Autowired
private UserManager userManager;
</code>```

And here is my spring.xml

```<code><beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:annotation-config/>

    <!-- Manager -->
    <bean id="userManager" class="com.mypackage.manager.UserManagerImpl"/>
    <bean id="cardManager" class="com.mypackage.manager.CardManagerImpl"/>
    <bean id="albumManager" class="com.mypackage.manager.AlbumManagerImpl"/>

    <!-- Dao -->
    <bean id="userDao" class="com.mypackage.dao.UserDaoImpl"/>
    <bean id="cardDao" class="com.mypackage.dao.CardDaoImpl"/>

    <!-- Session factory for hibernate -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="configLocation" value="file:web/WEB-INF/hibernate.cfg.xml"/>
    </bean>

</beans>
</code>```

But I got a NullPointerException here :

```<code>userManager.getUserById(1);
</code>```

And here is the code of the method :

```<code>public UserDto getUserById(Integer userId) throws NotFoundException {
    /*User user = userDao.findById(userId);*/
    User user = new User();
    user.setUsername("creekorful");
    user.setAvatarUrl("myavatar/avatar.image");
    user.setEmail("creekorful@gmail.com");
    user.setUserStatus(UserStatus.ACTIVATED);
    user.setAccountType(AccountType.ADMINISTRATOR);
    return new UserDto(user);
}
</code>```

Is there all I need to make spring automatically instantiate and inject my manager? Because no matter what soluce I try to use, It seems that my userManager is still null. I think i'm missing something about the functionnement of spring...

N.B : I've put my spring.xml into my WEB-INF/class directory in my .war

Thank in advance

答:
In your spring.xml, you'll also need to ensure that you've enabled annotations like so:

```<code><context:annotation-config/>
</code>```

Hope that helps!

Body:
I'm working on a jax-rs project for an RESTFul API

I choose to use spring in order to automatically inject my dependencies

import org.springframework.beans.factory.annotation.Autowired;

@Autowired
private UserManager userManager;

And here is my spring.xml

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:annotation-config/>

    <bean id="userManager" class="com.mypackage.manager.UserManagerImpl"/>
    <bean id="cardManager" class="com.mypackage.manager.CardManagerImpl"/>
    <bean id="albumManager" class="com.mypackage.manager.AlbumManagerImpl"/>

    <bean id="userDao" class="com.mypackage.dao.UserDaoImpl"/>
    <bean id="cardDao" class="com.mypackage.dao.CardDaoImpl"/>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="configLocation" value="file:web/WEB-INF/hibernate.cfg.xml"/>
    </bean>

</beans>

But I got a NullPointerException here :

userManager.getUserById(1);

And here is the code of the method :

public UserDto getUserById(Integer userId) throws NotFoundException {
    /*User user = userDao.findById(userId);*/
    User user = new User();
    user.setUsername("creekorful");
    user.setAvatarUrl("myavatar/avatar.image");
    user.setEmail("creekorful@gmail.com");
    user.setUserStatus(UserStatus.ACTIVATED);
    user.setAccountType(AccountType.ADMINISTRATOR);
    return new UserDto(user);
}

Is there all I need to make spring automatically instantiate and inject my manager? Because no matter what soluce I try to use, It seems that my userManager is still null. I think i'm missing something about the functionnement of spring...

N.B : I've put my spring.xml into my WEB-INF/class directory in my .war

Thank in advance

Body:
In your spring.xml, you'll also need to ensure that you've enabled annotations like so:

<context:annotation-config/>

Hope that helps!


问:
How to avoid creating unnecessary lists?
I keep coming across situations where I pull some information from a file or wherever, then have to massage the data to the final desired form through several steps. For example:

```<code>def insight_pull(file):
    with open(file) as in_f:
        lines = in_f.readlines()

        dirty = [line.split('    ') for line in lines]
        clean = [i[1] for i in dirty]
        cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]
        cleanest = [i[0].split() + i[1].split() for i in cleaner]

        with open("Output_File.txt", "w") as out_f:
            out_f.writelines(' '.join(i) + '\n' for i in cleanest)
</code>```

As per the example above:

```<code>    # Pull raw data from file splitting on '   '.
    dirty = [line.split('    ') for line in lines]

    # Select every 2nd element from each nested list.
    clean = [i[1] for i in dirty]

    # Couple every 2nd element with it's predecessor into a new list.
    cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]

    # Split each entry in cleaner into the final formatted list.
    cleanest = [i[0].split() + i[1].split() for i in cleaner]
</code>```

Seeing as I can't put all of the edits into one line or loop (since each edit depends on the edit before it), is there a better way to structure code like this?

Apologies if the question is a bit vague. Any input is much appreciated.

答:
To achieve the goal, I would recommend pipeline processing. I found an article which expains the technique: generator pipelines.

Here is my try for a direct transformation of your loop into a pipeline. The code is untested (because we've got no data to test) and may contain bugs.

The leading f in func names stands for filter.

```<code>def fromfile(name):
    # see coments
    with open(name) as in_f:
        for line in in_f:
            yield line

def fsplit(pp):
    for line in pp:
        yield line.split('    ')

def fitem1(pp):
    for item in pp:
        yield item[1]

def fpairs(pp):
    # edited
    for x in pp:
        try:
            yield [x, next(pp)]
        except StopIteration:
            break

def fcleanup(pp):
    for i in pp:
        yield i[0].split() + i[1].split()

pipeline = fcleanup(fpairs(fitem1(fsplit(fromfile(NAME)))))

output = list(pipeline)
</code>```

For real-world usage I would aggregate the first 3 filters and also the next 2 ones.

Body:
I keep coming across situations where I pull some information from a file or wherever, then have to massage the data to the final desired form through several steps. For example:

def insight_pull(file):
    with open(file) as in_f:
        lines = in_f.readlines()

        dirty = [line.split('    ') for line in lines]
        clean = [i[1] for i in dirty]
        cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]
        cleanest = [i[0].split() + i[1].split() for i in cleaner]

        with open("Output_File.txt", "w") as out_f:
            out_f.writelines(' '.join(i) + '\n' for i in cleanest)

As per the example above:

    # Pull raw data from file splitting on '   '.
    dirty = [line.split('    ') for line in lines]

    # Select every 2nd element from each nested list.
    clean = [i[1] for i in dirty]

    # Couple every 2nd element with it's predecessor into a new list.
    cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]

    # Split each entry in cleaner into the final formatted list.
    cleanest = [i[0].split() + i[1].split() for i in cleaner]

Seeing as I can't put all of the edits into one line or loop (since each edit depends on the edit before it), is there a better way to structure code like this?

Apologies if the question is a bit vague. Any input is much appreciated.

Body:
To achieve the goal, I would recommend pipeline processing. I found an article which expains the technique: generator pipelines.

Here is my try for a direct transformation of your loop into a pipeline. The code is untested (because we've got no data to test) and may contain bugs.

The leading f in func names stands for filter.

def fromfile(name):
    # see coments
    with open(name) as in_f:
        for line in in_f:
            yield line

def fsplit(pp):
    for line in pp:
        yield line.split('    ')

def fitem1(pp):
    for item in pp:
        yield item[1]

def fpairs(pp):
    # edited
    for x in pp:
        try:
            yield [x, next(pp)]
        except StopIteration:
            break

def fcleanup(pp):
    for i in pp:
        yield i[0].split() + i[1].split()

pipeline = fcleanup(fpairs(fitem1(fsplit(fromfile(NAME)))))

output = list(pipeline)

For real-world usage I would aggregate the first 3 filters and also the next 2 ones.


答:
You can use below code to get all images from specific folder.

1) First you need to define File object to get the storage and appened the name of the folder you want to read.

```<code>File folder = new File(Environment.getExternalStorageDirectory().toString() + "/Folder Name/");
</code>```

2) And now use folder object to get list of files with defined filter. Hope that helps.

```<code>if(folder.exists())
File[] allFiles = folder.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
    return (name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png"));
}
});
</code>```

Title: How to get all images from specific folder?

Body: In my application,I want to read the all images from specific folder in File explorer and iterate in for loop. How can i do this?

Body:
You can use below code to get all images from specific folder.

1) First you need to define File object to get the storage and appened the name of the folder you want to read.

File folder = new File(Environment.getExternalStorageDirectory().toString() + "/Folder Name/");

2) And now use folder object to get list of files with defined filter. Hope that helps.

if(folder.exists())
File[] allFiles = folder.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
    return (name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png"));
}
});


问:
Trouble getting a new activity to pop up on notification click
So I want to make this application that receives SMS texts, and when it does, it displays a notification, and when the user clicks on it, a new activity is popped up with the SMS message. So I have most if it done like the BroadcastReceiver class which works in receiving SMS texts and it displays a notification all fine and dandy.

```<code>public class SMSReceiver extends BroadcastReceiver {

    static final int notificationId = 1;

    @Override
    public void onReceive(Context context, Intent intent) {

        final Bundle bundle = intent.getExtras();

        try {

            if (bundle != null) {

                final Object[] pdusObj = (Object[]) bundle.get("pdus");

                for (int i = 0; i < pdusObj.length; i++) {

                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String message = currentMessage.getDisplayMessageBody();
                    newNotification(context, phoneNumber, message);

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void newNotification(Context context, String title, String text) {

        NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notifyIntent = new Intent(context, NotificationActivity.class);
        notifyIntent.putExtra("SMSText", text);
        notifyIntent.setAction(text);
        notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notifyIntent, 0);

        Notification notification = new NotificationCompat.Builder(context)
                .setContentIntent(contentIntent)
                .setContentText(text)
                .setContentTitle(title)
                .setTicker(text)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(System.currentTimeMillis())
                .build();

        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notifyMgr.notify(notificationId, notification);

    }

}
</code>```

The only problem is when I click on the notification. The first time it works perfectly, the NotificationActivity class pops up displaying the SMS message. But after that, the information never updates. I assume the app realizes that it already has NotificationActivity open, so it doesn't open another one. Even though I properly add the flag FLAG_ACTIVITY_NEW_TASK when I create the new notification. Also here is my NotificationActivity class

```<code>public class NotificationActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);

        String newString;
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if (extras == null) {
                newString = null;
            } else {
                newString = extras.getString("SMSText");
            }
        } else {
            newString = (String) savedInstanceState.getSerializable("SMSText");
        }

        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(newString);

    }
}
</code>```

I also do have a launcher activity, MainActivity, but felt it was unnecessary to show because all it does is register the SMSReceiver. Any help would be greatly appreciated, thanks!

答:
change this line</p>

```<code>    PendingIntent contentIntent = PendingIntent.getActivity(context,
    notificationId ,
    notifyIntent, PendingIntent.FLAG_ONE_SHOT););
</code>```

Body:
So I want to make this application that receives SMS texts, and when it does, it displays a notification, and when the user clicks on it, a new activity is popped up with the SMS message. So I have most if it done like the BroadcastReceiver class which works in receiving SMS texts and it displays a notification all fine and dandy.

public class SMSReceiver extends BroadcastReceiver {

    static final int notificationId = 1;

    @Override
    public void onReceive(Context context, Intent intent) {

        final Bundle bundle = intent.getExtras();

        try {

            if (bundle != null) {

                final Object[] pdusObj = (Object[]) bundle.get("pdus");

                for (int i = 0; i < pdusObj.length; i++) {

                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String message = currentMessage.getDisplayMessageBody();
                    newNotification(context, phoneNumber, message);

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void newNotification(Context context, String title, String text) {

        NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notifyIntent = new Intent(context, NotificationActivity.class);
        notifyIntent.putExtra("SMSText", text);
        notifyIntent.setAction(text);
        notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notifyIntent, 0);

        Notification notification = new NotificationCompat.Builder(context)
                .setContentIntent(contentIntent)
                .setContentText(text)
                .setContentTitle(title)
                .setTicker(text)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(System.currentTimeMillis())
                .build();

        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notifyMgr.notify(notificationId, notification);

    }

}

The only problem is when I click on the notification. The first time it works perfectly, the NotificationActivity class pops up displaying the SMS message. But after that, the information never updates. I assume the app realizes that it already has NotificationActivity open, so it doesn't open another one. Even though I properly add the flag FLAG_ACTIVITY_NEW_TASK when I create the new notification. Also here is my NotificationActivity class

public class NotificationActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);

        String newString;
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if (extras == null) {
                newString = null;
            } else {
                newString = extras.getString("SMSText");
            }
        } else {
            newString = (String) savedInstanceState.getSerializable("SMSText");
        }

        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(newString);

    }
}

I also do have a launcher activity, MainActivity, but felt it was unnecessary to show because all it does is register the SMSReceiver. Any help would be greatly appreciated, thanks!

Body:
change this line

    PendingIntent contentIntent = PendingIntent.getActivity(context,
    notificationId ,
    notifyIntent, PendingIntent.FLAG_ONE_SHOT););


问:
How to loop data from JSON to TH's and TD's in a Datatable?
The th's of the Datatable are the keys/entities from the database and the td's are the values. The th's are not yet written on the html file because the web app will allow the admin to add more. I'm trying to append it but the sort button doesn't work. I use jquery and my database is Firebase

Here is an example of my JSON.

data = {IDNumber: "1", NAME: "Kim", A1: "10", A2: "20", A3: "30", …}
and
data = {IDNumber: "2", NAME: "Joon", A1: "9", A2: "19", A3: "29", …}

The table will look like this

IDNumber | Name | A1 | A2 | A3 | ....

1                 | Kim     | 10  | 20 | 30  | ....

2                 | Joon   | 9    | 19 | 29  | ...

答:
Please check the documentation here https://datatables.net/

also you will have to have separate array of th's and td's to map


问:
Way to toggle debugging code on and off
I was programming a manchester decoding algorithm for arduino, and I often had to print debug stuff when trying to get things working, but printing to serial and string constants add a lot of overhead. I can't just leave it there in the final binary.

I usually just go through the code removing anything debug related lines.
I'm looking for a way to easily turn it on and off.

The only way I know is this

```<code> #if VERBOSE==1
     Serial.println();
     Serial.print(s);
     Serial.print(" ");
     Serial.print(t);
     Serial.print(" preamble");
 #endif

...

 #if VERBOSE==1
     Serial.println(" SYNC!\n");
 #endif
</code>```

and on top of the file I can just have

```<code>#define VERBOSE 0 // 1 to debug
</code>```

I don't like how much clutter it adds to single liners. I was very tempted to do something very nasty like this. But yeah, evil.

Change every debug output to

```<code>verbose("debug message");
</code>```

then use

```<code>#define verbose(x) Serial.print(x) //debug on
</code>```

or

```<code>#define verbose(x) //debug off
</code>```

There's a C++ feature that allows me to just do this instead of preprocessor?

答: You could also use templates utilizing the constexpr if feature in C++17. you don't have to worry about the preprocessor at all but your declaration and definition have to be in the same place when using templates.

Title: Way to toggle debugging code on and off

Body:
I was programming a manchester decoding algorithm for arduino, and I often had to print debug stuff when trying to get things working, but printing to serial and string constants add a lot of overhead. I can't just leave it there in the final binary.

I usually just go through the code removing anything debug related lines.
I'm looking for a way to easily turn it on and off.

The only way I know is this

 #if VERBOSE==1
     Serial.println();
     Serial.print(s);
     Serial.print(" ");
     Serial.print(t);
     Serial.print(" preamble");
 #endif

...

 #if VERBOSE==1
     Serial.println(" SYNC!\n");
 #endif

and on top of the file I can just have

#define VERBOSE 0 // 1 to debug

I don't like how much clutter it adds to single liners. I was very tempted to do something very nasty like this. But yeah, evil.

Change every debug output to

verbose("debug message");

then use

#define verbose(x) Serial.print(x) //debug on

or

#define verbose(x) //debug off

There's a C++ feature that allows me to just do this instead of preprocessor?


问:
SQL Server 2012 - using select * into along with dynamic SQL

Hi I have the the following code:

```<code>use TSQL2012;
go

if OBJECT_ID('Sales.FreightTotals') is not null drop table
Sales.FreightTotals
go

declare @shipperid as nvarchar(max) ='';
declare @dsql as nvarchar(max);
select @shipperid += quotename(shipperid,'')+',' from sales.Orders group by
shipperid;
set @shipperid = LEFT(@shipperid, LEN(@shipperid)-1)

print @shipperid;

set @dsql='
select empid,'+@shipperid+' from
(select empid, shipperid, freight from Sales.Orders )as d
pivot(sum(freight) for shipperid in('+@shipperid+')) as pvt
order by pvt.empid
'
</code>```

print @dsql

--exec sp_executesql @dsql

```<code>select * into Sales.FreightTotals from @dsql;
</code>```

I am trying to use select * into with dynamic pivot as shown above.If I use

```<code>exec sp_executesql @dsql
</code>```

I get the following result the result i am looking for

```<code>empid       1                     2                     3
----------- --------------------- --------------------- --------------------
1           2194.73               3259.99               3381.92
2           2281.09               4350.20               2065.12
3           2491.74               4258.90               4134.10
4           3129.39               4926.73               3290.02
5           1218.27               1991.84               708.60
6           1049.83               1270.42               1460.22
7           1204.60               3155.18               2305.66
8           1889.27               3297.40               2301.21
9           726.41                1734.19               865.66

(9 rows affected)
</code>```

but if I do
    select * into Sales.FreightTotals from @dsql;

i get:

```<code>Msg 1087, Level 16, State 1, Line 26
Must declare the table variable "@dsql".
</code>```

any suggestion as to why this is the case?

答:
try the following:

```<code>exec ('select * into Sales.FreightTotals from ('+@dsql+')t;')
</code>```

Thanks.

Body:
Hi I have the the following code:

use TSQL2012;
go

if OBJECT_ID('Sales.FreightTotals') is not null drop table
Sales.FreightTotals
go

declare @shipperid as nvarchar(max) ='';
declare @dsql as nvarchar(max);
select @shipperid += quotename(shipperid,'')+',' from sales.Orders group by
shipperid;
set @shipperid = LEFT(@shipperid, LEN(@shipperid)-1)

print @shipperid;

set @dsql='
select empid,'+@shipperid+' from
(select empid, shipperid, freight from Sales.Orders )as d
pivot(sum(freight) for shipperid in('+@shipperid+')) as pvt
order by pvt.empid
'

print @dsql

--exec sp_executesql @dsql

select * into Sales.FreightTotals from @dsql;

I am trying to use select * into with dynamic pivot as shown above.If I use

exec sp_executesql @dsql

I get the following result the result i am looking for

empid       1                     2                     3
----------- --------------------- --------------------- --------------------
1           2194.73               3259.99               3381.92
2           2281.09               4350.20               2065.12
3           2491.74               4258.90               4134.10
4           3129.39               4926.73               3290.02
5           1218.27               1991.84               708.60
6           1049.83               1270.42               1460.22
7           1204.60               3155.18               2305.66
8           1889.27               3297.40               2301.21
9           726.41                1734.19               865.66

(9 rows affected)

but if I do
    select * into Sales.FreightTotals from @dsql;

i get:

Msg 1087, Level 16, State 1, Line 26
Must declare the table variable "@dsql".

any suggestion as to why this is the case?

Body:
try the following:

exec ('select * into Sales.FreightTotals from ('+@dsql+')t;')

Thanks.


问:
EPPlus Changing Border Color of cells
I'm trying to change the cell border color on a selected range. Couldn't find any other styles for cell borders other than for the weights of the borders as follows:</p>

```<code>range.Style.Border.Top.Style = ExcelBorderStyle.Thin;
range.Style.Border.Left.Style = ExcelBorderStyle.Thin;
range.Style.Border.Right.Style = ExcelBorderStyle.Thin;
range.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
</code>```

答:
```<code>            using (ExcelRange range = worksheet.Cells["A1:H1"])
            {
                range.Style.Font.Bold = true;
                range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                range.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                range.Style.Fill.PatternType = ExcelFillStyle.Solid;
                range.Style.Fill.BackgroundColor.SetColor(Color.White);

                range.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                range.Style.Border.Top.Color.SetColor(Color.Red);
                range.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                range.Style.Border.Left.Color.SetColor(Color.Green);
                range.Style.Border.Right.Style = ExcelBorderStyle.Thin;
                range.Style.Border.Right.Color.SetColor(Color.Green);
                range.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                range.Style.Border.Bottom.Color.SetColor(Color.Green);
            }
</code>```

Title: EPPlus Changing Border Color of cells

Body:
I'm trying to change the cell border color on a selected range. Couldn't find any other styles for cell borders other than for the weights of the borders as follows:

range.Style.Border.Top.Style = ExcelBorderStyle.Thin;
range.Style.Border.Left.Style = ExcelBorderStyle.Thin;
range.Style.Border.Right.Style = ExcelBorderStyle.Thin;
range.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;


问:
I'm using vue(-router) to develop a hybrid app, how can I save some data in history state, so I can restore them when I back to previous pages?
In Android apps, when you start a new activity, the original activity is still in there, with all its internal data, so when you come back, it is the same as before.

How can I simulate this behaviour in my vue.js hybrid app? Is there some existing solution?

PS. I'm aware of vuex, but I think if I want to all the internal states of the pages in the history stack, then I must implement a stack-like structure by vuex myself. Is there some existing library can do this for me?

Thanks.

答:
Wrapping <router-view> in <keep-alive> would get you expected results.

Or some custom baked solution, similar vuex-router-sync library to keep your page state in sync with the router.


问:
Order of Function arguments in C++
I was reading "Bjarne Stroustrup's C++ Style and Technique" FAQ where he mentioned about this FAQ
What's the value of i++ + i++?

In this he has mentioned "...the order of evaluation of function arguments are undefined." when he is refering to f(v[i],i++); example.

I am aware of that the order of evaluation of function arguments is unspecified not undefined but in this case is it undefined because we are relying on value of i so as to which v[i] to pass or its an error in the FAQ itself?

答:
The order of evaluation of function arguments is unspecified but the behaviour of the expression is undefined. Bjarne has just got it wrong. :-)

Check out this thread to understand the difference between Unspecified Behaviour and Undefined Behaviour.

I once asked Bjarne the difference between unspecified and undefined and this was his reply..

Personally, I don't bother with the distinction between "undefined" and "unspecified"; do you know what it is? That code should be taken out and shot in either case: (carefully avoiding the words "undefined" and "unspecified")

.....

You don't need to know: just avoid both. If someone really want to know they can look up the definitions in the C++ or C standards (my bet would be that the C and C++ standards will disagree on unimportant details).

Title: Order of Function arguments in C++