问:
MediaRouteButton not showing with RemoteDisplay Application ID
I am developping a chromecast application for android, implementing  RemoteDisplay using the sdk v2.

My MediaRouteButton nevers shows on my menu for discovery using an application ID I created for RemoteDisplay applications on the cast developer console but the button appears if I use CastMediaControlIntent.DEFAULT_MEDIA_RECEIVER_APPLICATION_ID as ID.

Here is my Activity:

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

public final static String ID = "99FB28D7";

MediaRouter mediaRouter;
MediaRouteSelector  mediaRouteSelector;
private CastDevice selectedDevice;

private MyMediaRouterCallback routerCallback = new MyMediaRouterCallback();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.mediaRouter = MediaRouter.getInstance(getApplicationContext());
    this.mediaRouteSelector = new MediaRouteSelector.Builder()
            .addControlCategory(CastMediaControlIntent.categoryForCast(ID)).build();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.main, menu);
    MenuItem mediaRouteMenuItem = menu.findItem(R.id.media_route_menu_item);
    MediaRouteActionProvider mediaRouteActionProvider =
            (MediaRouteActionProvider) MenuItemCompat.getActionProvider(mediaRouteMenuItem);
    mediaRouteActionProvider.setRouteSelector(this.mediaRouteSelector);
    return true;
}

@Override
protected void onStart() {
    super.onStart();
    this.mediaRouter.addCallback(this.mediaRouteSelector, routerCallback, MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY);
}

@Override
protected void onStop() {
    this.mediaRouter.removeCallback(this.routerCallback);
    super.onStop();
}

private class MyMediaRouterCallback extends MediaRouter.Callback {

    @Override
    public void onRouteSelected(MediaRouter router, MediaRouter.RouteInfo info) {
        selectedDevice = CastDevice.getFromBundle(info.getExtras());
    }

    @Override
    public void onRouteUnselected(MediaRouter router, MediaRouter.RouteInfo info) {
        selectedDevice = null;
    }
}
}
</code>```

My main.xml menu:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/media_route_menu_item"
    android:title="@string/media_route_menu_title"
    app:actionProviderClass="android.support.v7.
    app.MediaRouteActionProvider"
    app:showAsAction="always"/>
</menu>
</code>```

I am testing on Android Marshmallow running GooglePlayServices 11.7. I also tried downgrading GooglePlayServices to  10.2, but it is still not working.

Thanks !

答:
After few weeks, I tried my code again and everything was working fine. I don't know what happened but I found this issue someone opened:

https://issuetracker.google.com/issues/69470206 .

It might be related.

Body:
I am developping a chromecast application for android, implementing  RemoteDisplay using the sdk v2.

My MediaRouteButton nevers shows on my menu for discovery using an application ID I created for RemoteDisplay applications on the cast developer console but the button appears if I use CastMediaControlIntent.DEFAULT_MEDIA_RECEIVER_APPLICATION_ID as ID.

Here is my Activity:

public class MainActivity extends AppCompatActivity {

public final static String ID = "99FB28D7";

MediaRouter mediaRouter;
MediaRouteSelector  mediaRouteSelector;
private CastDevice selectedDevice;

private MyMediaRouterCallback routerCallback = new MyMediaRouterCallback();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.mediaRouter = MediaRouter.getInstance(getApplicationContext());
    this.mediaRouteSelector = new MediaRouteSelector.Builder()
            .addControlCategory(CastMediaControlIntent.categoryForCast(ID)).build();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.main, menu);
    MenuItem mediaRouteMenuItem = menu.findItem(R.id.media_route_menu_item);
    MediaRouteActionProvider mediaRouteActionProvider =
            (MediaRouteActionProvider) MenuItemCompat.getActionProvider(mediaRouteMenuItem);
    mediaRouteActionProvider.setRouteSelector(this.mediaRouteSelector);
    return true;
}

@Override
protected void onStart() {
    super.onStart();
    this.mediaRouter.addCallback(this.mediaRouteSelector, routerCallback, MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY);
}

@Override
protected void onStop() {
    this.mediaRouter.removeCallback(this.routerCallback);
    super.onStop();
}

private class MyMediaRouterCallback extends MediaRouter.Callback {

    @Override
    public void onRouteSelected(MediaRouter router, MediaRouter.RouteInfo info) {
        selectedDevice = CastDevice.getFromBundle(info.getExtras());
    }

    @Override
    public void onRouteUnselected(MediaRouter router, MediaRouter.RouteInfo info) {
        selectedDevice = null;
    }
}
}

My main.xml menu:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/media_route_menu_item"
    android:title="@string/media_route_menu_title"
    app:actionProviderClass="android.support.v7.
    app.MediaRouteActionProvider"
    app:showAsAction="always"/>
</menu>

I am testing on Android Marshmallow running GooglePlayServices 11.7. I also tried downgrading GooglePlayServices to  10.2, but it is still not working.

Thanks !


来源: stackexchange

问:
Scrape multiple pages with Beautiful soup
I am trying to scrape multiple pages of a url.

But am able to scrape only the first page is there is a way to get all the pages.

Here is my code.

```<code>from bs4 import BeautifulSoup as Soup
import urllib, requests, re, pandas as pd

pd.set_option('max_colwidth',500)    # to remove column limit (Otherwise, we'll lose some info)
df = pd.DataFrame()

Comp_urls = ['https://www.indeed.com/jobs?q=Dell&rbc=DELL&jcid=0918a251e6902f97', 'https://www.indeed.com/jobs?q=Harman&rbc=Harman&jcid=4faf342d2307e9ed','https://www.indeed.com/jobs?q=johnson+%26+johnson&rbc=Johnson+%26+Johnson+Family+of+Companies&jcid=08849387e791ebc6','https://www.indeed.com/jobs?q=nova&rbc=Nova+Biomedical&jcid=051380d3bdd5b915']

for url in Comp_urls:
    target = Soup(urllib.request.urlopen(url), "lxml")
    targetElements = target.findAll('div', class_ =' row result')

    for elem in targetElements:
        comp_name = elem.find('span', attrs={'class':'company'}).getText().strip()
        job_title = elem.find('a', attrs={'class':'turnstileLink'}).attrs['title']
        home_url = "http://www.indeed.com"
        job_link = "%s%s" % (home_url,elem.find('a').get('href'))
        job_addr = elem.find('span', attrs={'class':'location'}).getText()
        date_posted = elem.find('span', attrs={'class': 'date'}).getText()
        description = elem.find('span', attrs={'class': 'summary'}).getText().strip()

        comp_link_overall = elem.find('span', attrs={'class':'company'}).find('a')
        if comp_link_overall != None:
        comp_link_overall = "%s%s" % (home_url, comp_link_overall.attrs['href'])
        else: comp_link_overall = None

        df = df.append({'comp_name': comp_name, 'job_title': job_title,
                'job_link': job_link, 'date_posted': date_posted,
                'overall_link': comp_link_overall, 'job_location': job_addr, 'description': description
                }, ignore_index=True)

df

df.to_csv('path\\web_scrape_Indeed.csv', sep=',', encoding='utf-8')
</code>```

Please suggest if there is anyway.

答:
Case 1: The code presented here is exactly what you have

```<code>Comp_urls = ['https://www.indeed.com/jobs?q=Dell&rbc=DELL&jcid=0918a251e6902f97', 'https://www.indeed.com/jobs?q=Harman&rbc=Harman&jcid=4faf342d2307e9ed','https://www.indeed.com/jobs?q=johnson+%26+johnson&rbc=Johnson+%26+Johnson+Family+of+Companies&jcid=08849387e791ebc6','https://www.indeed.com/jobs?q=nova&rbc=Nova+Biomedical&jcid=051380d3bdd5b915']

for url in Comp_urls:
    target = Soup(urllib.request.urlopen(url), "lxml")
    targetElements = target.findAll('div', class_ =' row result')

for elem in targetElements:
</code>```

The problem here is targetElements changes with every iteration in the first for loop.

To avoid this, indent the second for loop inside the first like so:

```<code>for url in Comp_urls:
    target = Soup(urllib.request.urlopen(url), "lxml")
    targetElements = target.findAll('div', class_ =' row result')

    for elem in targetElements:
</code>```

Case 2: Your the bug is not a result of improper indentation (i.e. not like what is in your original post)
If it is the case that your code is properly idented , then it may be the case that targetElements is an empty list. This means target.findAll('div', class_ =' row result') does not return anything. In that case, visit the sites, check out the dom, then modify your scraping program.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to scrape multiple pages of a url.

But am able to scrape only the first page is there is a way to get all the pages.

Here is my code.

from bs4 import BeautifulSoup as Soup
import urllib, requests, re, pandas as pd

pd.set_option('max_colwidth',500)    # to remove column limit (Otherwise, we'll lose some info)
df = pd.DataFrame()

Comp_urls = ['https://www.indeed.com/jobs?q=Dell&rbc=DELL&jcid=0918a251e6902f97', 'https://www.indeed.com/jobs?q=Harman&rbc=Harman&jcid=4faf342d2307e9ed','https://www.indeed.com/jobs?q=johnson+%26+johnson&rbc=Johnson+%26+Johnson+Family+of+Companies&jcid=08849387e791ebc6','https://www.indeed.com/jobs?q=nova&rbc=Nova+Biomedical&jcid=051380d3bdd5b915']

for url in Comp_urls:
    target = Soup(urllib.request.urlopen(url), "lxml")
    targetElements = target.findAll('div', class_ =' row result')

    for elem in targetElements:
        comp_name = elem.find('span', attrs={'class':'company'}).getText().strip()
        job_title = elem.find('a', attrs={'class':'turnstileLink'}).attrs['title']
        home_url = "http://www.indeed.com"
        job_link = "%s%s" % (home_url,elem.find('a').get('href'))
        job_addr = elem.find('span', attrs={'class':'location'}).getText()
        date_posted = elem.find('span', attrs={'class': 'date'}).getText()
        description = elem.find('span', attrs={'class': 'summary'}).getText().strip()

        comp_link_overall = elem.find('span', attrs={'class':'company'}).find('a')
        if comp_link_overall != None:
        comp_link_overall = "%s%s" % (home_url, comp_link_overall.attrs['href'])
        else: comp_link_overall = None

        df = df.append({'comp_name': comp_name, 'job_title': job_title,
                'job_link': job_link, 'date_posted': date_posted,
                'overall_link': comp_link_overall, 'job_location': job_addr, 'description': description
                }, ignore_index=True)

df

df.to_csv('path\\web_scrape_Indeed.csv', sep=',', encoding='utf-8')

Please suggest if there is anyway.

Body:
Case 1: The code presented here is exactly what you have

Comp_urls = ['https://www.indeed.com/jobs?q=Dell&rbc=DELL&jcid=0918a251e6902f97', 'https://www.indeed.com/jobs?q=Harman&rbc=Harman&jcid=4faf342d2307e9ed','https://www.indeed.com/jobs?q=johnson+%26+johnson&rbc=Johnson+%26+Johnson+Family+of+Companies&jcid=08849387e791ebc6','https://www.indeed.com/jobs?q=nova&rbc=Nova+Biomedical&jcid=051380d3bdd5b915']

for url in Comp_urls:
    target = Soup(urllib.request.urlopen(url), "lxml")
    targetElements = target.findAll('div', class_ =' row result')

for elem in targetElements:

The problem here is targetElements changes with every iteration in the first for loop.

To avoid this, indent the second for loop inside the first like so:

for url in Comp_urls:
    target = Soup(urllib.request.urlopen(url), "lxml")
    targetElements = target.findAll('div', class_ =' row result')

    for elem in targetElements:

Case 2: Your the bug is not a result of improper indentation (i.e. not like what is in your original post)
If it is the case that your code is properly idented , then it may be the case that targetElements is an empty list. This means target.findAll('div', class_ =' row result') does not return anything. In that case, visit the sites, check out the dom, then modify your scraping program.


问:
java program is not able to read a string
```<code>import java.util.*;

class DataTypes {

    public static void main(String args[]) {
        int i = 4;
        double d= 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = new String();
        s1 = scan.nextLine();
        j = j+i;
        System.out.println(j);
        d1 = d1+d;
        System.out.println(d1);
        System.out.println(s+" "+s1);
        scan.close();
    }
}
</code>```

See the above code it is error free but after I input the double the program does not read the string it directly shows the output. But When I comment the scanning statements of int and double then the programs reads my string. Why is it so?

答:
Changing the line

```<code> s1 = scan.nextLine();
</code>```

to below line

```<code> s1 = scan.next();
</code>```

will work.

Body:
import java.util.*;

class DataTypes {

    public static void main(String args[]) {
        int i = 4;
        double d= 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = new String();
        s1 = scan.nextLine();
        j = j+i;
        System.out.println(j);
        d1 = d1+d;
        System.out.println(d1);
        System.out.println(s+" "+s1);
        scan.close();
    }
}

See the above code it is error free but after I input the double the program does not read the string it directly shows the output. But When I comment the scanning statements of int and double then the programs reads my string. Why is it so?

Body:
Changing the line

 s1 = scan.nextLine();

to below line

 s1 = scan.next();

will work.


问:
python scheduler on bluemix
I am using the schedule package in python, to invoke a function for every 15 seconds, and want to run this code on IBM Bluemix.
Have pushed the application using the -no-route option to Bluemix, though the application is deployed to Bluemix, Bluemix is not able to start the application

Below is the sample code that I tried

```<code>import schedule
import time

def printMyName():
    print("NAME...")

schedule.every(15).seconds.do(printMyName)

while 1:
   schedule.run_pending()
   time.sleep(10)
</code>```

Messages in the Bluemix logs for this application:

```<code>Destroying container
Successfully destroyed container

0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
</code>```

And after a while, I see this message in the logs

```<code>ERR Timed out after 1m0s: health check never passed.
</code>```

Python version: 3.4.4

答:
I have done something similar with schedule a while back and it worked. Having the no-route option set in the manifest did the trick for me.

Today, I would recommend to take a look at IBM Cloud Functions / OpenWhisk and the alarm package. IBM Cloud Functions allows actions to be written in Python. With the alarms you can invoke those Python functions in a cron-like fashion - and likely with less cost.

Title: python scheduler on bluemix

Body:
I am using the schedule package in python, to invoke a function for every 15 seconds, and want to run this code on IBM Bluemix.
Have pushed the application using the -no-route option to Bluemix, though the application is deployed to Bluemix, Bluemix is not able to start the application

Below is the sample code that I tried

import schedule
import time

def printMyName():
    print("NAME...")

schedule.every(15).seconds.do(printMyName)

while 1:
   schedule.run_pending()
   time.sleep(10)

Messages in the Bluemix logs for this application:

Destroying container
Successfully destroyed container

0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting

And after a while, I see this message in the logs

ERR Timed out after 1m0s: health check never passed.

Python version: 3.4.4


问:
How to create a Wufoo-like (form builder) web application with JQuery and Rails?
I'm looking for some guidance on how to implement a Wufoo-like builder in a Rails 3 application with JQuery on the client side. Basically allow a user to build something (a form in the case of Wufoo) in "offline" mode then save all user edits to the server in one batch by clicking a Save button or similar (e.g. could be an auto-save triggered by the browser every 30s or so).

I'm leaning towards using the HTML5 local storage at this point. The "builder" would essentially store user edits locally in the browser local storage in JSON format. A click on the Save button would then HTTP Post the content of the local storage to the Rails app, again in JSON format. Does this sound about right? Any advice, suggestions?

Some additional considerations/questions:

What about older browsers that do not support HTML5? Should there be a fallback plan that uses cookie storage?

Any JQuery plugin that can help with some of this? e.g. abstract HTML5 local storage as primary storage and cookie storage as secondary/fallback storage.

Any Rails-specific considerations to be aware of?

Note: The following question addresses WYSIWYG form builder specifically and doesn't really provide any good solution.
Creating WYSIWYG form builder (á la Wufoo) in Rails

Thanks!

答:
I have been playing around with this a bit at work and I think it could give you a head start on a jquery form builder that knows how to serialize and deserialize itself. I think it serializes the form to a string rather than JSON, but it's a start. http://www.botsko.net/blog/2009/04/07/jquery-form-builder-plugin/

A google search found me sites.google.com/site/daveschindler/jquery-html5-storage-plugin which says that it stores things in HTML 5 storage with a fallback to cookies if the browser does not support it.

Another thought: If the goal in using local storage is for users not to lose work that they don't yet want to publish, another option could be to implement seperate "save" and "publish" buttons so you still save the user's work on the server side but let them retain "drafts" till they're ready to publish, and this way it wouldn't matter which browser or PC they use.

Hope this helps.

ContentLicense: CC BY-SA 2.5


答:
this is because of you enters: , so till get new line it can not go to next line
so for non string use example:

int j = scan.nextInt(); scan.nextLine();

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

class DataTypes {

    public static void main(String args[]) {

        int i = 4;
        double d = 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);

//      System.out.print("Enter j: ");
        int j = scan.nextInt();
        scan.nextLine();
//      System.out.print("Enter dl: ");
        double d1 = scan.nextDouble();
        scan.nextLine();

        String s1 = new String();
//      System.out.print("Enter s1: ");
        s1 = scan.nextLine();
        j = j + i;
        System.out.println(j);
        d1 = d1 + d;
        System.out.println(d1);
        System.out.println(s + " " + s1);
        scan.close();
    }
}
</code>```

Title: java program is not able to read a string

Body:
this is because of you enters: , so till get new line it can not go to next line
so for non string use example:

int j = scan.nextInt(); scan.nextLine();

import java.util.*;

class DataTypes {

    public static void main(String args[]) {

        int i = 4;
        double d = 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);

//      System.out.print("Enter j: ");
        int j = scan.nextInt();
        scan.nextLine();
//      System.out.print("Enter dl: ");
        double d1 = scan.nextDouble();
        scan.nextLine();

        String s1 = new String();
//      System.out.print("Enter s1: ");
        s1 = scan.nextLine();
        j = j + i;
        System.out.println(j);
        d1 = d1 + d;
        System.out.println(d1);
        System.out.println(s + " " + s1);
        scan.close();
    }
}


问:
Change date format dd-MM-yyyy to yyyy-MM-dd in Java
I was trying to convert date string 08-12-2017 to 2017-12-08(LocalDate). Here is what I tried-

```<code>    String startDateString = "08-12-2017";
    LocalDate date = LocalDate.parse(startDateString);
    System.out.println(date);
</code>```

Also tried using formatter, but getting same result, an DateTimeParseException.
How can I get an output like 2017-12-08, without getting an exception?

答:
Try this (see update below)

```<code>try {
    String startDateString = "08-12-2017";
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(sdf2.format(sdf.parse(startDateString)));
} catch (ParseException e) {
    e.printStackTrace();
}
</code>```

Update - Java 8

```<code>    String startDateString = "08-12-2017";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    System.out.println(LocalDate.parse(startDateString, formatter).format(formatter2));
</code>```

Body:
I was trying to convert date string 08-12-2017 to 2017-12-08(LocalDate). Here is what I tried-

    String startDateString = "08-12-2017";
    LocalDate date = LocalDate.parse(startDateString);
    System.out.println(date);

Also tried using formatter, but getting same result, an DateTimeParseException.
How can I get an output like 2017-12-08, without getting an exception?

Body:
Try this (see update below)

try {
    String startDateString = "08-12-2017";
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(sdf2.format(sdf.parse(startDateString)));
} catch (ParseException e) {
    e.printStackTrace();
}

Update - Java 8

    String startDateString = "08-12-2017";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    System.out.println(LocalDate.parse(startDateString, formatter).format(formatter2));


问:
Gunicorn: No module named '/path/to/my/django/project'
I was using gunicorn with nginx on Ubuntu 16.04 system to deploy a django project and want to create a systemd service for gunicorn. In /lib/systemd/system/gunicorn-mywebsite.service, I write following codes:

```<code>ExecStart=/home/myusername/sites/pythonEnv/bin/gunicorn --bind unix:/tmp/mywebsite.socket /path/to/my/django/project.wsgi:application
</code>```

But when I ran service gunicorn-mywebsite start, there was problem No module named '/path/to/my/django/project'.

If I run the same command my django project directory with relative path of my wsgi:application, it will work.

How can I fix this problem?

答: You can't give gunicorn a path to a file, it needs to be a module path, with application entry point name. So just project.wsgi:application. If the directory containing project is not in your path, then use the --pythonpath to gunicorn to tell it where it is.

Body:
I was using gunicorn with nginx on Ubuntu 16.04 system to deploy a django project and want to create a systemd service for gunicorn. In /lib/systemd/system/gunicorn-mywebsite.service, I write following codes:

ExecStart=/home/myusername/sites/pythonEnv/bin/gunicorn --bind unix:/tmp/mywebsite.socket /path/to/my/django/project.wsgi:application

But when I ran service gunicorn-mywebsite start, there was problem No module named '/path/to/my/django/project'.

If I run the same command my django project directory with relative path of my wsgi:application, it will work.

How can I fix this problem?


问:
Pass jwt refresh token on header or body
When access token is expired, it should re-issued refresh token.

At this point, I'm little hesitate which method is better.

For access token, it passed HTTP header per every request.

pass refresh token on HTTP header.

pass refresh token on HTTP POST body(payload).

Which one is recommended?

答:
The jwt specification recommends (but does not require) sending the access tokens in an authorization header of type Bearer. But there is no mention of the refresh tokens.

Refresh tokens are an Oauth2 concept. If you read the Rfc6749 specification, to refresh an access token, the refresh token is sent using a form parameter in a POST request

6.  Refreshing an Access Token
...

```<code> POST /token HTTP/1.1
 Host: server.example.com
 Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
 Content-Type: application/x-www-form-urlencoded

 grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA
</code>```

You can use the example of oauth2 as reference (pass it in the body), although if you do not use oauth2, you have no obligation, so use the method to send that best suits your project.

Body:
The jwt specification recommends (but does not require) sending the access tokens in an authorization header of type Bearer. But there is no mention of the refresh tokens.

Refresh tokens are an Oauth2 concept. If you read the Rfc6749 specification, to refresh an access token, the refresh token is sent using a form parameter in a POST request

6.  Refreshing an Access Token
...

 POST /token HTTP/1.1
 Host: server.example.com
 Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
 Content-Type: application/x-www-form-urlencoded

 grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA

You can use the example of oauth2 as reference (pass it in the body), although if you do not use oauth2, you have no obligation, so use the method to send that best suits your project.


问:
list with matrices times always the same vector
i am working with consumer price index CPI and in order to calculate it i have to multiply the index matrix with the corresponding weights:

```<code>grossCPI77_10 <- grossIND1977 %*% weights1910/100
grossCPI82_10 <- grossIND1982 %*% weights1910/100
</code>```

of course i would rather like to have a code like the one beyond:

```<code>grossIND1982 <- replicate(20, cbind(1:61))
grossIND1993 <- replicate(20, cbind(1:61))
weights1910_sc <- c(1:20)
grossIND_list <- mget(ls(pattern = "grossIND...."))
totalCPI <- mapply("*", grossIND_list, weights1910_sc)
</code>```

the problem is that it gives me a 1200x20 matrix. i expected a normal matrix (61x20) vector (20x1) multiplication which should result in a 20x1 vector? could you explain me what i am doing wrong? thanks

答:
I am not sure if I understood all aspects of your problem (especially concerning what should be colums, what should be rows, and in which order the crossproduct shall be applied), but I will try at least to cover some aspects. See comments in below code for clarifications of what you did and what you might want. I hope it helps, let me know if this is what you need.</p>

```<code>#instead of using mget, I recommend to use a list structure
#otherwise you might capture other variables with similar names
#that you do not want
INDlist <- sapply(c("1990", "1991"), function(x) {

  #this is how to set up a matrix correctly, check `?matrix`
  #I think your combination of cbind and rep did not give you what you wanted
  matrix(rep(1:61, 20), nrow = 61)

}, USE.NAMES = TRUE, simplify = F)

weights <- list(c(1:20))

#the first argument of mapply needs to be a function, in this case of two variables
#the body of the function calculates the cross product
#you feed the arguments (both lists) in the following part of mapply
#I have repeated your weights, but you might assign different weights for each year
res <- mapply(function(x, y) {x %*% y}, INDlist, rep(weights, length(INDlist)))
dim(res)
#[1] 61  2
</code>```

Body:
i am working with consumer price index CPI and in order to calculate it i have to multiply the index matrix with the corresponding weights:

grossCPI77_10 <- grossIND1977 %*% weights1910/100
grossCPI82_10 <- grossIND1982 %*% weights1910/100

of course i would rather like to have a code like the one beyond:

grossIND1982 <- replicate(20, cbind(1:61))
grossIND1993 <- replicate(20, cbind(1:61))
weights1910_sc <- c(1:20)
grossIND_list <- mget(ls(pattern = "grossIND...."))
totalCPI <- mapply("*", grossIND_list, weights1910_sc)

the problem is that it gives me a 1200x20 matrix. i expected a normal matrix (61x20) vector (20x1) multiplication which should result in a 20x1 vector? could you explain me what i am doing wrong? thanks

Body:
I am not sure if I understood all aspects of your problem (especially concerning what should be colums, what should be rows, and in which order the crossproduct shall be applied), but I will try at least to cover some aspects. See comments in below code for clarifications of what you did and what you might want. I hope it helps, let me know if this is what you need.

#instead of using mget, I recommend to use a list structure
#otherwise you might capture other variables with similar names
#that you do not want
INDlist <- sapply(c("1990", "1991"), function(x) {

  #this is how to set up a matrix correctly, check `?matrix`
  #I think your combination of cbind and rep did not give you what you wanted
  matrix(rep(1:61, 20), nrow = 61)

}, USE.NAMES = TRUE, simplify = F)

weights <- list(c(1:20))

#the first argument of mapply needs to be a function, in this case of two variables
#the body of the function calculates the cross product
#you feed the arguments (both lists) in the following part of mapply
#I have repeated your weights, but you might assign different weights for each year
res <- mapply(function(x, y) {x %*% y}, INDlist, rep(weights, length(INDlist)))
dim(res)
#[1] 61  2


问:
DotNet Core 2.0 WebDeploy call to npm build not working on Publish
I have in past used a strategy whereby our backend devs work in VisualStudio and our UI guys work purely in Sublime/VSCode etc. During website publish in VS2017, I used a publish target to first run npm install, then npm build (to bundle our app.js logic), then include that front end content into the backend package for WebDeploy.

I am trying to replicate this in a dotnet core 2.0 project, but the publish target calls to build the front end are never called (ie you never see the echo command content, nor does the npm install / build run)... so no UI resources are included when the publish happens unless i had previously manually run the build process to generate them from VSCode and they already exist on disk. Ie. the COPYING of the UI generated files works great (if they exist)... but VS2017 is never calling the npm commands to BUILD the resources?

While a touch fiddly, this works great in several .NET 4.6+ projects. I have just copied that exact same logic to a Core 2.0 project, and for some reason it isnt working the way I expect? Any ideas?

E.g. my ProjectDeploy.pubxml file contains (at the bottom before the final closing 'Project' tag):

```<code>  <!--
  make sure that we BUILD the UI *before* we copy the files to the package
  See: http://byalexblog.net/using-msbuild-to-deploy-composite-web-application
  See: http://www.codecadwallader.com/2015/03/15/integrating-gulp-into-your-tfs-builds-and-web-deploy/
  -->
  <PropertyGroup>
    <!-- relative path back out of 'current' folder to outside location of the UI files -->
    <FrontEndLocalPath>..\..\src-app</FrontEndLocalPath>
  </PropertyGroup>
  <!--
  Build the mobile web app assets , ensuring that all packages are installed and up to date
  -->
  <Target Name="BuildFrontEnd">
    <Exec Command="echo Got Here also Dale" />
    <!-- requires that NPM be installed in environment variables, which we will assume rather than use the NPM env variable above -->
    <!-- call npm install -->
    <exec command="npm install" WorkingDirectory="$(FrontEndLocalPath)" />
    <!-- Run npm run build to populate the www folder with your latest minified production build. -->
    <exec command="npm run build" WorkingDirectory="$(FrontEndLocalPath)" />
  </Target>
  <!--
  On each package and/or deploy (because they are different), we want to ensure that we bundle up all the Angular dist code and include that as part of the package / deployment.
  See: https://learn.microsoft.com/en-us/aspnet/web-forms/overview/deployment/visual-studio-web-deployment/deploying-extra-files
  -->
  <Target Name="CustomCollectFiles" DependsOnTargets="BuildFrontEnd">
    <Exec Command="echo Got Here Dale" />
    <ItemGroup>
      <_CustomFiles Include="$(FrontEndLocalPath)\www\**\*" />
      <FilesForPackagingFromProject Include="%(_CustomFiles.Identity)">
        <DestinationRelativePath>wwwroot\%(RecursiveDir)%(Filename)%(Extension)</DestinationRelativePath>
      </FilesForPackagingFromProject>
    </ItemGroup>
  </Target>
  <PropertyGroup>
    <CopyAllFilesToSingleFolderForPackageDependsOn>CustomCollectFiles;</CopyAllFilesToSingleFolderForPackageDependsOn>
    <CopyAllFilesToSingleFolderForMsdeployDependsOn>CustomCollectFiles;</CopyAllFilesToSingleFolderForMsdeployDependsOn>
  </PropertyGroup>
</code>```

答:
Okay, so I don't know if this is specific to new dotnetcore 2.0 or not, but I followed these links and got things working perfectly. Working from the inbuilt VS2017 SPA templates, I now no longer follow the approach we used in .NET 4.6 to modify the .pubxml publish profile to attempt a build/copy files.. instead the gulp/webpack build-SPA-and-copy-files-on-build logic is included in the .csproj file. Note that the benefit of this is you can BUILD your solution quickly without building the UI each time, but still bundle up all fresh UI changes on deployment. My working example follows link:

https://stackoverflow.com/a/44429390/4413476

```<code><PropertyGroup>
    <!--
    relative path back out of 'current' folder to outside location of the
    custom single page app UI files (and any other paths we require)
    -->
    <FrontEndLocalPath>..\..\src-app</FrontEndLocalPath>
  </PropertyGroup>

  <Target Name="DebugBuildSPA" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('wwwroot\dist') ">
    <!-- Ensure Node.js is installed -->
    <Exec Command="node --version" ContinueOnError="true">
    <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
    </Exec>
    <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />

    <!--
    In development, the dist files won't exist on the first run or when cloning to
    a different machine, so rebuild them if not already present.
    -->
    <Message Importance="high" Text="Performing first-run Webpack build..." />
    <exec command="npm install" WorkingDirectory="$(FrontEndLocalPath)" />
    <exec command="npm run build" WorkingDirectory="$(FrontEndLocalPath)" />
  </Target>

  <Target Name="PrepublishScript" BeforeTargets="PrepareForPublish" Condition=" '$(IsCrossTargetingBuild)' != 'true' ">
    <!-- Build our single page application content -->
    <exec command="npm install" WorkingDirectory="$(FrontEndLocalPath)" />
    <exec command="npm run build" WorkingDirectory="$(FrontEndLocalPath)" />
    <ItemGroup>
      <Dist Include="$(FrontEndLocalPath)\www\**;" />
    </ItemGroup>
    <Copy SourceFiles="@(Dist)" DestinationFolder="$(PublishDir)\wwwroot\%(RecursiveDir)" SkipUnchangedFiles="true" />
  </Target>
</code>```

Body:
I have in past used a strategy whereby our backend devs work in VisualStudio and our UI guys work purely in Sublime/VSCode etc. During website publish in VS2017, I used a publish target to first run npm install, then npm build (to bundle our app.js logic), then include that front end content into the backend package for WebDeploy.

I am trying to replicate this in a dotnet core 2.0 project, but the publish target calls to build the front end are never called (ie you never see the echo command content, nor does the npm install / build run)... so no UI resources are included when the publish happens unless i had previously manually run the build process to generate them from VSCode and they already exist on disk. Ie. the COPYING of the UI generated files works great (if they exist)... but VS2017 is never calling the npm commands to BUILD the resources?

While a touch fiddly, this works great in several .NET 4.6+ projects. I have just copied that exact same logic to a Core 2.0 project, and for some reason it isnt working the way I expect? Any ideas?

E.g. my ProjectDeploy.pubxml file contains (at the bottom before the final closing 'Project' tag):

  <PropertyGroup>

    <FrontEndLocalPath>..\..\src-app</FrontEndLocalPath>
  </PropertyGroup>

  <Target Name="BuildFrontEnd">
    <Exec Command="echo Got Here also Dale" />

    <exec command="npm install" WorkingDirectory="$(FrontEndLocalPath)" />

    <exec command="npm run build" WorkingDirectory="$(FrontEndLocalPath)" />
  </Target>

  <Target Name="CustomCollectFiles" DependsOnTargets="BuildFrontEnd">
    <Exec Command="echo Got Here Dale" />
    <ItemGroup>
      <_CustomFiles Include="$(FrontEndLocalPath)\www\**\*" />
      <FilesForPackagingFromProject Include="%(_CustomFiles.Identity)">
        <DestinationRelativePath>wwwroot\%(RecursiveDir)%(Filename)%(Extension)</DestinationRelativePath>
      </FilesForPackagingFromProject>
    </ItemGroup>
  </Target>
  <PropertyGroup>
    <CopyAllFilesToSingleFolderForPackageDependsOn>CustomCollectFiles;</CopyAllFilesToSingleFolderForPackageDependsOn>
    <CopyAllFilesToSingleFolderForMsdeployDependsOn>CustomCollectFiles;</CopyAllFilesToSingleFolderForMsdeployDependsOn>
  </PropertyGroup>

Body:
Okay, so I don't know if this is specific to new dotnetcore 2.0 or not, but I followed these links and got things working perfectly. Working from the inbuilt VS2017 SPA templates, I now no longer follow the approach we used in .NET 4.6 to modify the .pubxml publish profile to attempt a build/copy files.. instead the gulp/webpack build-SPA-and-copy-files-on-build logic is included in the .csproj file. Note that the benefit of this is you can BUILD your solution quickly without building the UI each time, but still bundle up all fresh UI changes on deployment. My working example follows link:

https://stackoverflow.com/a/44429390/4413476

<PropertyGroup>
    <!--
    relative path back out of 'current' folder to outside location of the
    custom single page app UI files (and any other paths we require)
    -->
    <FrontEndLocalPath>..\..\src-app</FrontEndLocalPath>
  </PropertyGroup>

  <Target Name="DebugBuildSPA" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('wwwroot\dist') ">
    <!-- Ensure Node.js is installed -->
    <Exec Command="node --version" ContinueOnError="true">
    <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
    </Exec>
    <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />

    <!--
    In development, the dist files won't exist on the first run or when cloning to
    a different machine, so rebuild them if not already present.
    -->
    <Message Importance="high" Text="Performing first-run Webpack build..." />
    <exec command="npm install" WorkingDirectory="$(FrontEndLocalPath)" />
    <exec command="npm run build" WorkingDirectory="$(FrontEndLocalPath)" />
  </Target>

  <Target Name="PrepublishScript" BeforeTargets="PrepareForPublish" Condition=" '$(IsCrossTargetingBuild)' != 'true' ">
    <!-- Build our single page application content -->
    <exec command="npm install" WorkingDirectory="$(FrontEndLocalPath)" />
    <exec command="npm run build" WorkingDirectory="$(FrontEndLocalPath)" />
    <ItemGroup>
      <Dist Include="$(FrontEndLocalPath)\www\**;" />
    </ItemGroup>
    <Copy SourceFiles="@(Dist)" DestinationFolder="$(PublishDir)\wwwroot\%(RecursiveDir)" SkipUnchangedFiles="true" />
  </Target>


问:
Nested transformation using jolt transformer
How can I do nested / recursive transformation using Jolt transformation.
I m trying to the get the desired output before inputting it to the subsequent service.

My Input is

```<code>            {
                  "took": 7,
                  "timed_out": false,
              "_shards": {
                "total": 1,
                "successful": 1,
                "failed": 0
              },
              "hits": {
                "total": 5,
                "max_score": 1.000438,
                "hits": [
                  {
                    "_id": "AV-SJgvFPkCspwtrqHA1",
                    "_source": {
                      "tenant_id": "tenant1",
                      "session_id": "e780ff74-d33e-4024-9bb7-971f067484ea"
                    },
                    "inner_hits": {
                      "network_events": {
                        "hits": {
                          "total": 1,
                          "max_score": 6.0892797,
                          "hits": [
                            {
                              "_source": {
                                "event_id": 16,
                                "response_time": 0,
                                "url": "http://www.google.com/"
                              }
                            },
                            {
                              "_source": {
                                "event_id": 18,
                                "response_time": 1,
                                "url": "http://www.google1.com/"
                              }
                            }
                          ]
                        }
                      }
                    }
                  },
                  {
                    "_id": "BS-SJgvFPkCspwtrqHA1",
                    "_source": {
                      "tenant_id": "tenant2",
                      "session_id": "f4939272-d33e-4024-9bb7-971f067484ea"
                    },
                    "inner_hits": {
                      "network_events": {
                        "hits": {
                          "total": 1,
                          "max_score": 6.0892797,
                          "hits": [
                            {
                              "_source": {
                                "event_id": 18,
                                "response_time": 4,
                                "url": "http://www.google4.com/"
                              }
                            },
                            {
                              "_source": {
                                "event_id": 5,
                                "response_time": 5,
                                "url": "http://www.google5.com/"
                              }
                            }
                          ]
                        }
                      }
                    }
                  }
                ]
              }
            }
</code>```

And the desired output is

```<code>{
   “sessions”: [
      {
            session_id : “S1”,
            tenant_id : “T1”,
            network_events : [
                {
                   “url”: “A”,
                   “response_time” : 22
                },
                {
                   “url”: “B,
                   “response_time” : 1
                }
           ]

      },
      {
            session_id : “S2”,
            tenant_id : “T1”,
            network_events : [
                {
                   “url”: “C”,
                   “response_time” : 22
                }
           ]

      }
]
}
</code>```

Is this possible using Jolt. I tried multiple combination using the sample examples but didn't get much.

I am new to Jolt so any help will be appreciated.

答:
```<code>[
  {
    "operation": "shift",
    "spec": {
      "hits": {
        "hits": {
          "*": {
            "_source": {
              "tenant_id": "sessions[#3].tenant_id",
              "session_id": "sessions[#3].session_id"
            },
            "inner_hits": {
              "network_events": {
                "hits": {
                  "hits": {
                    "*": {
                      "_source": {
                        "@": "sessions[#8].network_events.[]"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  {
    "operation": "remove",
    "spec": {
      "sessions": {
        "*": {
          "network_events": {
            "*": {
              "data_in": "",
              "data_out": "",
              "attributes": "",
              "event_id": "",
              "parent_url": "",
              "resource_type": ""
            }
          }
        }
      }
    }
  }
]
</code>```

Body:
How can I do nested / recursive transformation using Jolt transformation.
I m trying to the get the desired output before inputting it to the subsequent service.

My Input is

            {
                  "took": 7,
                  "timed_out": false,
              "_shards": {
                "total": 1,
                "successful": 1,
                "failed": 0
              },
              "hits": {
                "total": 5,
                "max_score": 1.000438,
                "hits": [
                  {
                    "_id": "AV-SJgvFPkCspwtrqHA1",
                    "_source": {
                      "tenant_id": "tenant1",
                      "session_id": "e780ff74-d33e-4024-9bb7-971f067484ea"
                    },
                    "inner_hits": {
                      "network_events": {
                        "hits": {
                          "total": 1,
                          "max_score": 6.0892797,
                          "hits": [
                            {
                              "_source": {
                                "event_id": 16,
                                "response_time": 0,
                                "url": "http://www.google.com/"
                              }
                            },
                            {
                              "_source": {
                                "event_id": 18,
                                "response_time": 1,
                                "url": "http://www.google1.com/"
                              }
                            }
                          ]
                        }
                      }
                    }
                  },
                  {
                    "_id": "BS-SJgvFPkCspwtrqHA1",
                    "_source": {
                      "tenant_id": "tenant2",
                      "session_id": "f4939272-d33e-4024-9bb7-971f067484ea"
                    },
                    "inner_hits": {
                      "network_events": {
                        "hits": {
                          "total": 1,
                          "max_score": 6.0892797,
                          "hits": [
                            {
                              "_source": {
                                "event_id": 18,
                                "response_time": 4,
                                "url": "http://www.google4.com/"
                              }
                            },
                            {
                              "_source": {
                                "event_id": 5,
                                "response_time": 5,
                                "url": "http://www.google5.com/"
                              }
                            }
                          ]
                        }
                      }
                    }
                  }
                ]
              }
            }

And the desired output is

{
   “sessions”: [
      {
            session_id : “S1”,
            tenant_id : “T1”,
            network_events : [
                {
                   “url”: “A”,
                   “response_time” : 22
                },
                {
                   “url”: “B,
                   “response_time” : 1
                }
           ]

      },
      {
            session_id : “S2”,
            tenant_id : “T1”,
            network_events : [
                {
                   “url”: “C”,
                   “response_time” : 22
                }
           ]

      }
]
}

Is this possible using Jolt. I tried multiple combination using the sample examples but didn't get much.

I am new to Jolt so any help will be appreciated.


问:
Implement UnityAds Mediation with Admob in Android
I follow this link to integrate UnityAds into Admob via Mediation. But it was not working, whenever I start the video ads, nothing shows at all.

If I do not using mediation, and implement UnityAds in normal way, it worked.

I also noticed the UnityAdapter class, but I did not know how to use it. Currently via mediation, I also have InMobi and it is OK.

Note: apply the mediation for the iOS version and everything is fine.

答:
Finally, it worked. Instead of adding its ".AAR" file, I have to place its library zip file in our libs folder.

Made me feel really annoyed was the instruction from Google Admob Mediation, it just outdated and completely unhelpful.

For example,  I have to contact InMobi team to get their latest adapter since the SDK provided on Google Admob Mediation was just outdated.


问:
SQL TABLE to store lists of strings
I have to maintain some lists in DB (SQLServer, Oracle, DB2, Derby), I have 2 options to design underlying simple table:

1st:

NAME   VALUE

dept      HR
 dept      fin
 role      engineer
 role      designer

UNIQUE CONSTRAINT (NAME, VALUE) and some other columns like auto generated ID, etc.

2nd:

NAME   VALUE_JSON_CLOB

dept   {["HR", "fin"]}

role   {["engineer", "designer"}]

UNIQUE CONSTRAINT (NAME) and some other columns like auto generated ID, etc.

There is no DELETE operation, only SELECT and INSERT/UPDATE. In first advantage is only INSERT is required but SELECT (fetch all values for a given NAME) will be slow. In second SELECT will be fast but UPDATE will be slow. By considering there could be 10000s of such lists with 1000s for possible values in the system with frequent SELECTs and less INSERTs, which TABLE design will be good in terms of select/insert/update performance.

答:
The first table is in First Normal Form, which is the foundation of good relational design. Using a CLOB to store data is bad design, because it means you will need to unpack the array every time you need to reference an individual value or update the set of values: you can't use simple SQL statements.  It also means you can't use the values in constraints (foreign keys, unique constraints).

These are not just theoretical objections. Working with CLOBs will burn CPU every time you extract the individual elements.

The problem is you are trying to build a generic solution which works across multiple database flavours. This inevitably means you will end up with a sub-optimal design for some databases because performance features tend to be product specific. For instance, with an Oracle or MSSQL implementation an Index Organized table (aka clustered index) could be very helpful with the first table structure but Derby and DB2 don't have such a thing. Still a compound index on a regular heap table would be almost as good.

So what it comes down to is this: how likely is that you will be handling tens of thousands of lists with thousands of items? Will you always be working with a whole set rather than a sub-set of a list's values? Depending on those considerations you have a trade-off, ease of use (SQL manipulation) against the reduced I/O for a pre-assembled set.

Title: SQL TABLE to store lists of strings


问:
How to check if a string starts with another string in C?
Is there something like startsWith(str_a, str_b) in the standard C library?

It should take pointers to two strings that end with nullbytes, and tell me whether the first one also appears completely at the beginning of the second one.

Examples:

```<code>"abc", "abcdef" -> true
"abcdef", "abc" -> false
"abd", "abdcef" -> true
"abc", "abc"    -> true
</code>```

答:
I'm no expert at writing elegant code, but...</p>

```<code>int prefix(const char *pre, const char *str)
{
    char cp;
    char cs;

    if (!*pre)
        return 1;

    while ((cp = *pre++) && (cs = *str++))
    {
        if (cp != cs)
            return 0;
    }

    if (!cs)
        return 0;

    return 1;
}
</code>```

Body:
Is there something like startsWith(str_a, str_b) in the standard C library?

It should take pointers to two strings that end with nullbytes, and tell me whether the first one also appears completely at the beginning of the second one.

Examples:

"abc", "abcdef" -> true
"abcdef", "abc" -> false
"abd", "abdcef" -> true
"abc", "abc"    -> true

Body:
I'm no expert at writing elegant code, but...

int prefix(const char *pre, const char *str)
{
    char cp;
    char cs;

    if (!*pre)
        return 1;

    while ((cp = *pre++) && (cs = *str++))
    {
        if (cp != cs)
            return 0;
    }

    if (!cs)
        return 0;

    return 1;
}


问:
Codeigniter: how to test library that takes Controller instance in constructor?
I have the following Library called Item_service:

```<code>class Item_Service {
private $items;

function __construct(Items $items)
{
    $this->items = $items;
}
</code>```

Where Items is an instance of controllers/Items.php.
In my test class called Items_test.php i try to load the Item_service library using the following line:

```<code>$items = $this->CI->load->library('items/Item_service');
</code>```

But then I get error saying

```<code>TypeError: Argument 1 passed to Item_Service::__construct() must be an instance of Items, null given
</code>```

My test class is written based on kenjis/ci-phpunit-test.

How should I inject the controller into this library to be able to test the library? Also, can I test the controller itself? There are a lot of helper methods inside the controller.

答:
The answer is to pass it within an array as the second param to the library call. So for example:

library('items/Item_service',array('controller'=>$this->CI));

Then from the construct of your service don't reference Items - it will be an array but then your Items will be available on the 'controller' key.

$this->items = $items['controller'];

Body:
I have the following Library called Item_service:

class Item_Service {
private $items;

function __construct(Items $items)
{
    $this->items = $items;
}

Where Items is an instance of controllers/Items.php.
In my test class called Items_test.php i try to load the Item_service library using the following line:

$items = $this->CI->load->library('items/Item_service');

But then I get error saying

TypeError: Argument 1 passed to Item_Service::__construct() must be an instance of Items, null given

My test class is written based on kenjis/ci-phpunit-test.

How should I inject the controller into this library to be able to test the library? Also, can I test the controller itself? There are a lot of helper methods inside the controller.


问:
Finding the first Adjacent pair
Trying to find the first adjacent pair in my code. Adjacent meaning only two of the same in a row. If found, it is supposed to print out the index of the first pair found. In this case 44 would be the first actual adjacent pair in my code. Therefore it should return the index of 10. Here is my array that I am currently working with. </p>

```<code>  int[] arr = {88, 88, 88, 63, 29, 77, 77, 77, 77, 50, 44, 44, 8, 0, 99, 99};
</code>```

答:
I caved (sort of) - so here is a partial solution.

```<code>boolean pair = false;
        int index = 0;
        for (int i = 1; i < arr.length - 2; i++) {
            if (arr[i] == arr[i + 1] && arr[i + 1] != arr[i + 2] && arr[i] != arr[i - 1]) {
                pair = true;
                index = i;
                break;
            }
    }
</code>```

Basically loop through starting at index 1 (as need to check the previous element), and end at -2 (as we are checking two ahead).

Note:

There are quite a few* edge cases that you will have to code yourself, such as:

If there are only 0, 1 or 2 elements

If the first two are the only pair

If the last two are the only pair

 *There may be more I've missed so feel free to update the answer if you wish

Title: Finding the first Adjacent pair

Body:
Trying to find the first adjacent pair in my code. Adjacent meaning only two of the same in a row. If found, it is supposed to print out the index of the first pair found. In this case 44 would be the first actual adjacent pair in my code. Therefore it should return the index of 10. Here is my array that I am currently working with.

  int[] arr = {88, 88, 88, 63, 29, 77, 77, 77, 77, 50, 44, 44, 8, 0, 99, 99};

Body:
I caved (sort of) - so here is a partial solution.

boolean pair = false;
        int index = 0;
        for (int i = 1; i < arr.length - 2; i++) {
            if (arr[i] == arr[i + 1] && arr[i + 1] != arr[i + 2] && arr[i] != arr[i - 1]) {
                pair = true;
                index = i;
                break;
            }
    }

Basically loop through starting at index 1 (as need to check the previous element), and end at -2 (as we are checking two ahead).

Note:

There are quite a few* edge cases that you will have to code yourself, such as:

If there are only 0, 1 or 2 elements

If the first two are the only pair

If the last two are the only pair

 *There may be more I've missed so feel free to update the answer if you wish


问:
Viewpager with SwipeRefreshLayout when refresh the icon doesn't go away
My question is exactly like this one.

Frozen snapshot of list rendered with SwipeRefreshLayout in ViewPager

But in short, I refresh the list and the spinning thing still keeps going after the list has been refreshed.

I tried the following solution he gave of wrapping the SwipeRefreshLayout with a FrameLayout and i had no success.

Here are screenshots of what I have right now, and the code where I implement this.

In my Fragment Class and parts of my Asynctask,

```<code>private LocationUtil loc;
private static final String ARG_SORT_TYPE = "sortType";
String sortType = null;
private ArrayList<Facility> results;
private SwipeRefreshLayout mPtrListView;
private ListView waitTimesListView;
SummaryAdapter adapter;

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_wait_times_viewpager_fragment,container,false);

    mPtrListView = (SwipeRefreshLayout) view.findViewById(R.id.wait_times_pull_refresh_list);
    waitTimesListView = (ListView) view.findViewById(R.id.wait_times_listview);
    waitTimesListView.setOnItemClickListener(this);
    mPtrListView.setOnRefreshListener(this);

    WaitTimesTask task = new WaitTimesTask(getActivity());
    task.execute(sortType, longitudeLocation, latitudeLocation);
    return view;
}

 @Override
 public void onRefresh() {
    WaitTimesTask task = new WaitTimesTask(getActivity());
    task.execute("name", longitudeLocation, latitudeLocation);
}

public void setLocation(){
    if(loc.useSmartLocation()){
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            Log.v("Check Location frag" + sortType + " " , " " + location.getLongitude() + " "  + location.getLatitude());

            latitudeLocation = Double.toString(location.getLatitude());
            longitudeLocation = Double.toString(location.getLongitude());

        } else {
            Log.v("Check waitTimesActivity" , " is null");
            }
    }
    else {
        loc.determineLocation();
        latitudeLocation = Double.toString(loc.getLatitude());
        longitudeLocation = Double.toString(loc.getLongitude());
    }
}

    @Override
    protected void onPreExecute() {
        dialog = AsyncProgressDialog.show(mContext, "", "");
        setLocation();
    }

    @Override
    protected void onPostExecute(String string) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if(string != null){
            Log.v("result on post & type: " + Sort, string);

            NovantFacilityXmlParser parser = new NovantFacilityXmlParser();
            string = string.replace("&", "&");
            try {
                results = parser.parse(new ByteArrayInputStream(string.getBytes()));

            } catch (IOException | XmlPullParserException ex) {
                Log.e("Parsing error:", ex.getMessage());
            }

            Log.v("SetUp "," of List");

            if(!results.isEmpty()) {
                adapter = new SummaryAdapter(mContext, R.layout.row_wait_time, results.toArray(new Facility[results.size()]));
                waitTimesListView.setAdapter(adapter);
            }
        }
        else{
            Toast.makeText(getActivity(), "No data available", Toast.LENGTH_LONG).show();
        }
}
</code>```

My xml, both fragment and main activity.

Activity xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="@color/aubergine">

<android.support.design.widget.TabLayout
    android:id="@+id/wait_times_tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabIndicatorHeight="3dp"
    app:tabIndicatorColor="#ffffff"
    app:tabSelectedTextColor="#ffffff"
    app:tabMode="fixed"
    android:background="#333333"/>

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/wait_times_ViewPager">
    </android.support.v4.view.ViewPager>
</LinearLayout>
</code>```

Fragment xml

```<code><FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/base_color">
<!--tools:context=".WaitTimesFragment">-->

        <android.support.v4.widget.SwipeRefreshLayout
            android:id="@+id/wait_times_pull_refresh_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >

            <ListView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/wait_times_listview"/>

        </android.support.v4.widget.SwipeRefreshLayout>
    <include layout="@layout/novant_menu_layout" />
</code>```

In my OnpostExecute, I get the string from the doinBackground and parse the xml feed and make an arraylist that i use for my adapter that i custom made.

Any help would greatly be appreciated.
Thanks.

答:
I think its bit late but It may help someone in future

You must call setRefreshing(false) in your overridden onRefresh() method

```<code>@Override
 public void onRefresh() {
    WaitTimesTask task = new WaitTimesTask(getActivity());
    task.execute("name", longitudeLocation, latitudeLocation);
    mPtrListView.setRefreshing(false); //this method call will resolve your problem
}
</code>```

Body:
My question is exactly like this one.

Frozen snapshot of list rendered with SwipeRefreshLayout in ViewPager

But in short, I refresh the list and the spinning thing still keeps going after the list has been refreshed.

I tried the following solution he gave of wrapping the SwipeRefreshLayout with a FrameLayout and i had no success.

Here are screenshots of what I have right now, and the code where I implement this.

In my Fragment Class and parts of my Asynctask,

private LocationUtil loc;
private static final String ARG_SORT_TYPE = "sortType";
String sortType = null;
private ArrayList<Facility> results;
private SwipeRefreshLayout mPtrListView;
private ListView waitTimesListView;
SummaryAdapter adapter;

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_wait_times_viewpager_fragment,container,false);

    mPtrListView = (SwipeRefreshLayout) view.findViewById(R.id.wait_times_pull_refresh_list);
    waitTimesListView = (ListView) view.findViewById(R.id.wait_times_listview);
    waitTimesListView.setOnItemClickListener(this);
    mPtrListView.setOnRefreshListener(this);

    WaitTimesTask task = new WaitTimesTask(getActivity());
    task.execute(sortType, longitudeLocation, latitudeLocation);
    return view;
}

 @Override
 public void onRefresh() {
    WaitTimesTask task = new WaitTimesTask(getActivity());
    task.execute("name", longitudeLocation, latitudeLocation);
}

public void setLocation(){
    if(loc.useSmartLocation()){
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            Log.v("Check Location frag" + sortType + " " , " " + location.getLongitude() + " "  + location.getLatitude());

            latitudeLocation = Double.toString(location.getLatitude());
            longitudeLocation = Double.toString(location.getLongitude());

        } else {
            Log.v("Check waitTimesActivity" , " is null");
            }
    }
    else {
        loc.determineLocation();
        latitudeLocation = Double.toString(loc.getLatitude());
        longitudeLocation = Double.toString(loc.getLongitude());
    }
}

    @Override
    protected void onPreExecute() {
        dialog = AsyncProgressDialog.show(mContext, "", "");
        setLocation();
    }

    @Override
    protected void onPostExecute(String string) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if(string != null){
            Log.v("result on post & type: " + Sort, string);

            NovantFacilityXmlParser parser = new NovantFacilityXmlParser();
            string = string.replace("&", "&");
            try {
                results = parser.parse(new ByteArrayInputStream(string.getBytes()));

            } catch (IOException | XmlPullParserException ex) {
                Log.e("Parsing error:", ex.getMessage());
            }

            Log.v("SetUp "," of List");

            if(!results.isEmpty()) {
                adapter = new SummaryAdapter(mContext, R.layout.row_wait_time, results.toArray(new Facility[results.size()]));
                waitTimesListView.setAdapter(adapter);
            }
        }
        else{
            Toast.makeText(getActivity(), "No data available", Toast.LENGTH_LONG).show();
        }
}

My xml, both fragment and main activity.

Activity xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="@color/aubergine">

<android.support.design.widget.TabLayout
    android:id="@+id/wait_times_tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabIndicatorHeight="3dp"
    app:tabIndicatorColor="#ffffff"
    app:tabSelectedTextColor="#ffffff"
    app:tabMode="fixed"
    android:background="#333333"/>

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/wait_times_ViewPager">
    </android.support.v4.view.ViewPager>
</LinearLayout>

Fragment xml

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/base_color">

        <android.support.v4.widget.SwipeRefreshLayout
            android:id="@+id/wait_times_pull_refresh_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >

            <ListView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/wait_times_listview"/>

        </android.support.v4.widget.SwipeRefreshLayout>
    <include layout="@layout/novant_menu_layout" />

In my OnpostExecute, I get the string from the doinBackground and parse the xml feed and make an arraylist that i use for my adapter that i custom made.

Any help would greatly be appreciated.
Thanks.

Body:
I think its bit late but It may help someone in future

You must call setRefreshing(false) in your overridden onRefresh() method

@Override
 public void onRefresh() {
    WaitTimesTask task = new WaitTimesTask(getActivity());
    task.execute("name", longitudeLocation, latitudeLocation);
    mPtrListView.setRefreshing(false); //this method call will resolve your problem
}


问:
Windows forms application generate another name
```<code>namespace GenerateApp
{
    public partial class Form1 : Form
    {
        string[] name = new string[4];

        public Form1()
        {
            InitializeComponent();
            name[0] = textBox2.Text;
            name[1] = textBox3.Text;
            name[2] = textBox5.Text;
            name[3] = textBox6.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < name.Length; i++)
            {

            }
        }
    }
}
</code>```

Ok first of all I must mention that i'm at the very beginning with programming and i'm trying to do something in my eyes quite simple but doesn't work and I need your help. I want every time that i click on a button, in my current textboxes to be generated another names. Example textbox2.Text to be textbox3.Text, textbox3.Text to be textbox5.Text and so on till it repeats. Can someone tell me a method of how to do it? I would gladly appreciate it

答:
Seem like you just wanna move names between boxes. All you need is a variable to hold the first name.</p>

```<code>    private void button1_Click(object sender, EventArgs e)
    {
        var tmp = textBox1.Text;
        textBox1.Text = textBox2.Text;
        textBox2.Text = textBox3.Text;
        textBox3.Text = textBox4.Text;
        textBox4.Text = tmp;
    }
</code>```

Body:
namespace GenerateApp
{
    public partial class Form1 : Form
    {
        string[] name = new string[4];

        public Form1()
        {
            InitializeComponent();
            name[0] = textBox2.Text;
            name[1] = textBox3.Text;
            name[2] = textBox5.Text;
            name[3] = textBox6.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < name.Length; i++)
            {

            }
        }
    }
}

Ok first of all I must mention that i'm at the very beginning with programming and i'm trying to do something in my eyes quite simple but doesn't work and I need your help. I want every time that i click on a button, in my current textboxes to be generated another names. Example textbox2.Text to be textbox3.Text, textbox3.Text to be textbox5.Text and so on till it repeats. Can someone tell me a method of how to do it? I would gladly appreciate it

Body:
Seem like you just wanna move names between boxes. All you need is a variable to hold the first name.

    private void button1_Click(object sender, EventArgs e)
    {
        var tmp = textBox1.Text;
        textBox1.Text = textBox2.Text;
        textBox2.Text = textBox3.Text;
        textBox3.Text = textBox4.Text;
        textBox4.Text = tmp;
    }


问:
checkbox-inline placing checkbox over text instead of beside
I'm trying to add checkboxes to my form but the bootstrap class "checkbox-inline" does not seem to be working for me.

Here is the code:

```<code><strong>Styles:</strong>
<%= f.collection_check_boxes :style_ids, Style.all, :id, :name do |cb| %>
  <% cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text} %>
<% end %>
<br><br>

<strong>Ingredients:</strong>
<%= f.collection_check_boxes :ingredient_ids, Ingredient.all, :id, :name do |cbi| %>
  <% cbi.label(class: "checkbox-inline input_checkbox") {cbi.check_box(class: "checkbox") + cbi.text} %>
<% end %>
</code>```

And here is the outcome:

Any help on this would be much appriciated, been pulling my hair out over this.

Edit: After going through the bootstrap docs, it appears checkbox-inline and radio-inline have been dropped. I just need to figure out how to get the checkboxes beside each label

Edit 2: Figured it out! in my css I had

```<code>input {
  width: 100%;
}
</code>```

I removed this and my forms broke, but my checkboxes were in the right place! So instead I just did

```<code>.input_checkbox input {
  width: auto !important;
}
</code>```

--and everything is finally fixed.

答:
Try below code </p>

```<code><%= f.collection_check_boxes :style_ids, Style.all, :id, :name do |cb| %>
  <%= cb.label  { "#{cb.check_box} #{cb.text}".html_safe } %>
<% end %>
</code>```

Body:
I'm trying to add checkboxes to my form but the bootstrap class "checkbox-inline" does not seem to be working for me.

Here is the code:

Styles:
<%= f.collection_check_boxes :style_ids, Style.all, :id, :name do |cb| %>
  <% cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text} %>
<% end %>

Ingredients:
<%= f.collection_check_boxes :ingredient_ids, Ingredient.all, :id, :name do |cbi| %>
  <% cbi.label(class: "checkbox-inline input_checkbox") {cbi.check_box(class: "checkbox") + cbi.text} %>
<% end %>

And here is the outcome:

Any help on this would be much appriciated, been pulling my hair out over this.

Edit: After going through the bootstrap docs, it appears checkbox-inline and radio-inline have been dropped. I just need to figure out how to get the checkboxes beside each label

Edit 2: Figured it out! in my css I had

input {
  width: 100%;
}

I removed this and my forms broke, but my checkboxes were in the right place! So instead I just did

.input_checkbox input {
  width: auto !important;
}

--and everything is finally fixed.

Body:
Try below code

<%= f.collection_check_boxes :style_ids, Style.all, :id, :name do |cb| %>
  <%= cb.label  { "#{cb.check_box} #{cb.text}".html_safe } %>
<% end %>


问:
Golang map containing both string and integer
I am trying to create a JSON string from a map using JSON.Marshal() in golang. However, the int values are being displayed as strings surrounded by double quotes.

My code is outputting:

```<code>{ "age":
    {
        "$gt":"22",
        "$lt":"20"
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}
</code>```

instead of

```<code>{ "age":
    {
        "$gt":22,
        "$lt":20
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}
</code>```

I am using:

```<code>var output_map = map[string]map[string]string{}

//Populate map here

output_json, err := json.Marshal(output_map)

if err!= nil {
    fmt.Println("Error encoding JSON")
}

fmt.Println(output_json)
</code>```

My understanding is that JSON.Marshal() will print the integers correctly if they are supplied but my map won't contain integers. I could change my map to map[string]map[string]int{} but then it wouldn't contain the string values for 'name' and 'location'.

The ultimate problem is that I need the map to contain both int and string values. Some sort of map[string]map[string]{}.

How can I achieve this? Thank you in advance.

Harry

答:
Your code works as expected: map[string]map[string]string{} contains only string values, so json.Marshal(interface{}) return json string with marshaled string values.

I think you should use struct instead of map. Just create a struct, something like this:

```<code>type Age struct {
    Gt  int `json:"gt"`
    Lt  int `json:"lt"`
}

type Person struct {
    Age         Age     `json:"age"`
    Location    string  `json:"location"`
    Name        string  `json:"name"`
}
</code>```

And just marshal it with standart json.Marshal(interface{}) method.
(in this code json tags isn't required, but you can use it if you want to change names of fields in serialized json string)

I create test.go file with following code in main():

```<code>person := Person{
    Age{
        22,
        20,
    },
    "London",
    "Fred",
}

serialized, e := json.Marshal(person)
if e != nil {
    fmt.Println(e)
    return
}

fmt.Println(string(serialized))
</code>```

and it returns this:

```<code>{
    "age":
    {
        "gt":22,
        "lt":20
    },
    "location":"London",
    "name":"Fred"
}
</code>```

P.S. I can't recommend you to use map[string]map[string]interface{} because in this case you need to have custom Unmarshaller (to fill up your map back). With structs you can unmarshal it by this way:

```<code>deserialized := Person{}
e = json.Unmarshal(serialized, &deserialized)
if e != nil {
    fmt.Println("can't deserialize:", e)
    return
}
</code>```

Body:
I am trying to create a JSON string from a map using JSON.Marshal() in golang. However, the int values are being displayed as strings surrounded by double quotes.

My code is outputting:

{ "age":
    {
        "$gt":"22",
        "$lt":"20"
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}

instead of

{ "age":
    {
        "$gt":22,
        "$lt":20
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}

I am using:

var output_map = map[string]map[string]string{}

//Populate map here

output_json, err := json.Marshal(output_map)

if err!= nil {
    fmt.Println("Error encoding JSON")
}

fmt.Println(output_json)

My understanding is that JSON.Marshal() will print the integers correctly if they are supplied but my map won't contain integers. I could change my map to map[string]map[string]int{} but then it wouldn't contain the string values for 'name' and 'location'.

The ultimate problem is that I need the map to contain both int and string values. Some sort of map[string]map[string]{}.

How can I achieve this? Thank you in advance.

Harry

Body:
Your code works as expected: map[string]map[string]string{} contains only string values, so json.Marshal(interface{}) return json string with marshaled string values.

I think you should use struct instead of map. Just create a struct, something like this:

type Age struct {
    Gt  int `json:"gt"`
    Lt  int `json:"lt"`
}

type Person struct {
    Age         Age     `json:"age"`
    Location    string  `json:"location"`
    Name        string  `json:"name"`
}

And just marshal it with standart json.Marshal(interface{}) method.
(in this code json tags isn't required, but you can use it if you want to change names of fields in serialized json string)

I create test.go file with following code in main():

person := Person{
    Age{
        22,
        20,
    },
    "London",
    "Fred",
}

serialized, e := json.Marshal(person)
if e != nil {
    fmt.Println(e)
    return
}

fmt.Println(string(serialized))

and it returns this:

{
    "age":
    {
        "gt":22,
        "lt":20
    },
    "location":"London",
    "name":"Fred"
}

P.S. I can't recommend you to use map[string]map[string]interface{} because in this case you need to have custom Unmarshaller (to fill up your map back). With structs you can unmarshal it by this way:

deserialized := Person{}
e = json.Unmarshal(serialized, &deserialized)
if e != nil {
    fmt.Println("can't deserialize:", e)
    return
}


答:
Use strstr() function.  Stra == strstr(stra, strb)

Reference

```<code>The strstr() function finds the first occurrence of string2 in string1. The function ignores the null character (\0) that ends string2 in the matching process.
</code>```

https://www.ibm.com/docs/en/i/7.4?topic=functions-strstr-locate-substring

Title: How to check if a string starts with another string in C?

Body:
Use strstr() function.  Stra == strstr(stra, strb)

Reference

The strstr() function finds the first occurrence of string2 in string1. The function ignores the null character (\0) that ends string2 in the matching process.

https://www.ibm.com/docs/en/i/7.4?topic=functions-strstr-locate-substring

ContentLicense: CC BY-SA 4.0


问:
How to decode SafetyNet JWS response?
I am investigating SafetyNet provided by Google within my Android Application.

To start with I simply called the SafetyNet attest API and Base64 decoded the parts as shown in the Google supplied examples.

```<code>SafetyNet.getClient(this).attest(NONCE, <API KEY>)
        .addOnSuccessListener(this, new OnSuccessListener<SafetyNetApi.AttestationResponse>() {
            @Override
            public void onSuccess(final SafetyNetApi.AttestationResponse attestationResponse) {
                initialDataExtraction(attestationResponse.getJwsResult());
            }
        })
        .addOnFailureListener(this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull final Exception exception) {
                if (exception instanceof ApiException) {
                    final ApiException apiException = (ApiException) exception;
                    Log.e(TAG, "onFailure: " + apiException.getMessage() + " " + apiException.getStatusCode());
                } else {
                    Log.e(TAG, "Error: ", exception);
                }
            }
        });
</code>```

I extract the JWS parts as follows:-

```<code>private byte[] initialDataExtraction(final String jwsResult) {

    final String[] jwsResultParts = jwsResult.split("[.]");
    if (jwsResultParts.length == 3) {
        final byte[] header = Base64.decode(jwsResultParts[0], Base64.NO_WRAP);
        final byte[] data = Base64.decode(jwsResultParts[1], Base64.NO_WRAP);
        final byte[] signature = Base64.decode(jwsResultParts[2], Base64.NO_WRAP);

        Log.d(TAG, "initialDataExtraction: header = " + new String(header, UTF_8));
        Log.d(TAG, "initialDataExtraction: data = " + new String(data, UTF_8));
        Log.d(TAG, "initialDataExtraction: signature = " + new String(signature, UTF_8));

        return data;
    } else {
        Log.e(TAG, "initialDataExtraction: Failure: Illegal JWS signature format. The JWS consists of " + jwsResultParts.length + " parts instead of 3.");
        return null;
    }
}
</code>```

I am using android.util.Base64 to decode the parts and the majority of the time the decoding completes OK.

Occasionally I receive this exception though:-

```<code>java.lang.IllegalArgumentException: bad base-64
 at android.util.Base64.decode(Base64.java:161)
 at android.util.Base64.decode(Base64.java:136)
 at android.util.Base64.decode(Base64.java:118)
</code>```

when decoding the Signature part.

What am I doing wrong when decoding to see this intermittent error?

I then moved onto to using a JWT library to decode the tokens.

first I tried group: 'com.auth0.android', name: 'jwtdecode', version: '1.1.1'

the code I tried is

```<code> final JWT jwt = new JWT(jwsResult);
</code>```

which consistently fails with the following error

```<code>com.auth0.android.jwt.DecodeException: The token's payload had an invalid JSON format.
at com.auth0.android.jwt.JWT.parseJson(JWT.java:235)
at com.auth0.android.jwt.JWT.decode(JWT.java:203)
at com.auth0.android.jwt.JWT.<init>(JWT.java:40)
Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 23 path $.
at com.google.gson.Gson.fromJson(Gson.java:899)
at com.google.gson.Gson.fromJson(Gson.java:852)
at com.google.gson.Gson.fromJson(Gson.java:801)
</code>```

This exception seems to be caused by the Auth0 library being unable to parse headers 4.1.6.  "x5c" (X.509 Certificate Chain) Header format which is odd as the JWS Spec clearly states the value is represented by a JSON aray:-

```<code>The "x5c" (X.509 Certificate Chain) Header Parameter contains the
   X.509 public key certificate or certificate chain [RFC5280]
   corresponding to the key used to digitally sign the JWS.  The
   certificate or certificate chain is represented as a JSON array of
   certificate value strings.
</code>```

However If I copy and paste the same jws result string into a pure java project and use compile 'com.auth0:java-jwt:3.3.0' and use this code:-

```<code>String token = "<JWS TOKEN>";
        try {
            final DecodedJWT jwt = JWT.decode(token);
            System.out.println("Header = " + jwt.getHeader());
            System.out.println("Payload = " + jwt.getPayload());
            System.out.println("Signature = " + jwt.getSignature());
                } catch (JWTDecodeException exception){
           throw new RuntimeException(exception);
        }
</code>```

The Jws Token is decoded successfully.

What am I doing wrong within my Android application that stops the auth0 android jwt library working as desired?

I then tried 'io.jsonwebtoken:jjwt:0.9.0' library within my Android application.

When I execute this code:-

```<code>Jwts.parser().parse(jwsResult).getBody();
</code>```

it fails with:-

```<code>java.lang.IllegalArgumentException: A signing key must be specified if the specified JWT is digitally signed.
 at io.jsonwebtoken.lang.Assert.notNull(Assert.java:85)
 at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:331)
</code>```

What signing key do I need to pass to Jwts? The only key I have is my API key held in the Google API Console, is this the key I should employ?

when I pass it as follows:

```<code>Jwts.parser().setSigningKey<API KEY>.parse(jwsResult).getBody();
</code>```

this fails with:-

```<code>private byte[] initialDataExtraction(final String jwsResult) {

    final String[] jwsResultParts = jwsResult.split("[.]");
    if (jwsResultParts.length == 3) {
        final byte[] header = Base64.decode(jwsResultParts[0], Base64.NO_WRAP);
        final byte[] data = Base64.decode(jwsResultParts[1], Base64.NO_WRAP);
        final byte[] signature = Base64.decode(jwsResultParts[2], Base64.NO_WRAP);

        Log.d(TAG, "initialDataExtraction: header = " + new String(header, UTF_8));
        Log.d(TAG, "initialDataExtraction: data = " + new String(data, UTF_8));
        Log.d(TAG, "initialDataExtraction: signature = " + new String(signature, UTF_8));

        return data;
    } else {
        Log.e(TAG, "initialDataExtraction: Failure: Illegal JWS signature format. The JWS consists of " + jwsResultParts.length + " parts instead of 3.");
        return null;
    }
}
</code>```0

What is the correct approach to decode and consume the Jws result received from SafetyNet attest API call?

I discovered a fix for the java.lang.IllegalArgumentException: bad base-64 issue from this question Base64: java.lang.IllegalArgumentException: Illegal character

simply replace characters in jws token before decoding

```<code>private byte[] initialDataExtraction(final String jwsResult) {

    final String[] jwsResultParts = jwsResult.split("[.]");
    if (jwsResultParts.length == 3) {
        final byte[] header = Base64.decode(jwsResultParts[0], Base64.NO_WRAP);
        final byte[] data = Base64.decode(jwsResultParts[1], Base64.NO_WRAP);
        final byte[] signature = Base64.decode(jwsResultParts[2], Base64.NO_WRAP);

        Log.d(TAG, "initialDataExtraction: header = " + new String(header, UTF_8));
        Log.d(TAG, "initialDataExtraction: data = " + new String(data, UTF_8));
        Log.d(TAG, "initialDataExtraction: signature = " + new String(signature, UTF_8));

        return data;
    } else {
        Log.e(TAG, "initialDataExtraction: Failure: Illegal JWS signature format. The JWS consists of " + jwsResultParts.length + " parts instead of 3.");
        return null;
    }
}
</code>```1

答:
I identified this library not only does it do the job it works fine on Android.

```<code>// https://mvnrepository.com/artifact/com.nimbusds/nimbus-jose-jwt
implementation group: 'com.nimbusds', name: 'nimbus-jose-jwt', version: '5.1'

    try {
        final JWSObject jwsObject = JWSObject.parse(jwsResult);
        System.out.println("header = " + jwsObject.getHeader());
        System.out.println("header = " + jwsObject.getHeader().getX509CertChain());
        System.out.println("payload = " + jwsObject.getPayload().toJSONObject());
        System.out.println("signature = " + jwsObject.getSignature());
        System.out.println("signature = " + jwsObject.getSignature().decodeToString());
    } catch (ParseException e) {
        e.printStackTrace();
    }
</code>```

Some nice examples are provided:-

https://connect2id.com/products/nimbus-jose-jwt/examples

Title: How to decode SafetyNet JWS response?

Body:
I am investigating SafetyNet provided by Google within my Android Application.

To start with I simply called the SafetyNet attest API and Base64 decoded the parts as shown in the Google supplied examples.

SafetyNet.getClient(this).attest(NONCE, <API KEY>)
        .addOnSuccessListener(this, new OnSuccessListener<SafetyNetApi.AttestationResponse>() {
            @Override
            public void onSuccess(final SafetyNetApi.AttestationResponse attestationResponse) {
                initialDataExtraction(attestationResponse.getJwsResult());
            }
        })
        .addOnFailureListener(this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull final Exception exception) {
                if (exception instanceof ApiException) {
                    final ApiException apiException = (ApiException) exception;
                    Log.e(TAG, "onFailure: " + apiException.getMessage() + " " + apiException.getStatusCode());
                } else {
                    Log.e(TAG, "Error: ", exception);
                }
            }
        });

I extract the JWS parts as follows:-

private byte[] initialDataExtraction(final String jwsResult) {

    final String[] jwsResultParts = jwsResult.split("[.]");
    if (jwsResultParts.length == 3) {
        final byte[] header = Base64.decode(jwsResultParts[0], Base64.NO_WRAP);
        final byte[] data = Base64.decode(jwsResultParts[1], Base64.NO_WRAP);
        final byte[] signature = Base64.decode(jwsResultParts[2], Base64.NO_WRAP);

        Log.d(TAG, "initialDataExtraction: header = " + new String(header, UTF_8));
        Log.d(TAG, "initialDataExtraction: data = " + new String(data, UTF_8));
        Log.d(TAG, "initialDataExtraction: signature = " + new String(signature, UTF_8));

        return data;
    } else {
        Log.e(TAG, "initialDataExtraction: Failure: Illegal JWS signature format. The JWS consists of " + jwsResultParts.length + " parts instead of 3.");
        return null;
    }
}

I am using android.util.Base64 to decode the parts and the majority of the time the decoding completes OK.

Occasionally I receive this exception though:-

java.lang.IllegalArgumentException: bad base-64
 at android.util.Base64.decode(Base64.java:161)
 at android.util.Base64.decode(Base64.java:136)
 at android.util.Base64.decode(Base64.java:118)

when decoding the Signature part.

What am I doing wrong when decoding to see this intermittent error?

I then moved onto to using a JWT library to decode the tokens.

first I tried group: 'com.auth0.android', name: 'jwtdecode', version: '1.1.1'

the code I tried is

 final JWT jwt = new JWT(jwsResult);

which consistently fails with the following error

com.auth0.android.jwt.DecodeException: The token's payload had an invalid JSON format.
at com.auth0.android.jwt.JWT.parseJson(JWT.java:235)
at com.auth0.android.jwt.JWT.decode(JWT.java:203)
at com.auth0.android.jwt.JWT.<init>(JWT.java:40)
Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 23 path $.
at com.google.gson.Gson.fromJson(Gson.java:899)
at com.google.gson.Gson.fromJson(Gson.java:852)
at com.google.gson.Gson.fromJson(Gson.java:801)

This exception seems to be caused by the Auth0 library being unable to parse headers 4.1.6.  "x5c" (X.509 Certificate Chain) Header format which is odd as the JWS Spec clearly states the value is represented by a JSON aray:-

The "x5c" (X.509 Certificate Chain) Header Parameter contains the
   X.509 public key certificate or certificate chain [RFC5280]
   corresponding to the key used to digitally sign the JWS.  The
   certificate or certificate chain is represented as a JSON array of
   certificate value strings.

However If I copy and paste the same jws result string into a pure java project and use compile 'com.auth0:java-jwt:3.3.0' and use this code:-

String token = "<JWS TOKEN>";
        try {
            final DecodedJWT jwt = JWT.decode(token);
            System.out.println("Header = " + jwt.getHeader());
            System.out.println("Payload = " + jwt.getPayload());
            System.out.println("Signature = " + jwt.getSignature());
                } catch (JWTDecodeException exception){
           throw new RuntimeException(exception);
        }

The Jws Token is decoded successfully.

What am I doing wrong within my Android application that stops the auth0 android jwt library working as desired?

I then tried 'io.jsonwebtoken:jjwt:0.9.0' library within my Android application.

When I execute this code:-

Jwts.parser().parse(jwsResult).getBody();

it fails with:-

java.lang.IllegalArgumentException: A signing key must be specified if the specified JWT is digitally signed.
 at io.jsonwebtoken.lang.Assert.notNull(Assert.java:85)
 at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:331)

What signing key do I need to pass to Jwts? The only key I have is my API key held in the Google API Console, is this the key I should employ?

when I pass it as follows:

Jwts.parser().setSigningKey<API KEY>.parse(jwsResult).getBody();

this fails with:-

java.lang.IllegalArgumentException: Key bytes can only be specified for HMAC signatures. Please specify a PublicKey or PrivateKey instance.
at io.jsonwebtoken.lang.Assert.isTrue(Assert.java:38)
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:324)

What is the correct approach to decode and consume the Jws result received from SafetyNet attest API call?

I discovered a fix for the java.lang.IllegalArgumentException: bad base-64 issue from this question Base64: java.lang.IllegalArgumentException: Illegal character

simply replace characters in jws token before decoding

token.replace('-', '+').replace('_', '/')

Body:
I identified this library not only does it do the job it works fine on Android.

// https://mvnrepository.com/artifact/com.nimbusds/nimbus-jose-jwt
implementation group: 'com.nimbusds', name: 'nimbus-jose-jwt', version: '5.1'

    try {
        final JWSObject jwsObject = JWSObject.parse(jwsResult);
        System.out.println("header = " + jwsObject.getHeader());
        System.out.println("header = " + jwsObject.getHeader().getX509CertChain());
        System.out.println("payload = " + jwsObject.getPayload().toJSONObject());
        System.out.println("signature = " + jwsObject.getSignature());
        System.out.println("signature = " + jwsObject.getSignature().decodeToString());
    } catch (ParseException e) {
        e.printStackTrace();
    }

Some nice examples are provided:-

https://connect2id.com/products/nimbus-jose-jwt/examples


问:
How to construct a tensor weights whose certain elements are zero?
I want to construct a weight whose certain elements are zero and never change, and other elements are the variables.For example:

```<code>[[0,0,a,0],[0,0,b,0],[0,0,0,c],[0,0,0,d]]
</code>```

This is a tf variable, and all zeros stay unchanged. Only a, b, c, d are tuned using gradient descent.

Are there anyone who knows how to define such a matrix?

答:
You should look into SparseTensor. It is highly optimised for operations where tensor consists of many zeros.

So, in your case, to initialise SparseTensor:

```<code>a,b,c,d = 10,20,30,40
sparse = tf.SparseTensor([[0,2], [1,2], [2,3], [3,3]], [a,b,c,d], [4,4])
</code>```

Body:
I want to construct a weight whose certain elements are zero and never change, and other elements are the variables.For example:

[[0,0,a,0],[0,0,b,0],[0,0,0,c],[0,0,0,d]]

This is a tf variable, and all zeros stay unchanged. Only a, b, c, d are tuned using gradient descent.

Are there anyone who knows how to define such a matrix?

Body:
You should look into SparseTensor. It is highly optimised for operations where tensor consists of many zeros.

So, in your case, to initialise SparseTensor:

a,b,c,d = 10,20,30,40
sparse = tf.SparseTensor([[0,2], [1,2], [2,3], [3,3]], [a,b,c,d], [4,4])


问:
Incorporating microsoft managed recommended rules in GIT TFS 2015
I tried using stylecop, but it is quite strict with lot of rules. I do not want to customize it by disabling certain rules. I want to document that I am using 'Microsoft managed recommended rules', which I used while coding in  VS 2017.

I want to incorporate the same rules in Git build process TFS-2015. Should I do code standard analysis during build definition? If not, how else?

Any help would be greatly appreciated!

答:
It's not able to do the code analysis in branch policies where you set number of reviews and merge strategies.
Unless the reviews manually check the code and fail the review according to Microsoft managed recommended rules.

If you want to apply Microsoft managed recommended rules to your code. Simply add /p:RunCodeAnalaysis=true to the MsBuild commandline additional arguments.

For stylecop there is also a related build task, if you want use this, you could add it in your build pipeline.

Finally just enable the Build validation in your master branch policy. Set a policy requiring changes in a pull request to build successfully with the protected branch before the pull request can be completed.