问:
custom dots slick.js slickGoTo not working
I tried making a carousel with slick js and make custom dots. (I make this custom dots since I need the dots to be outside of carousel div, so it's no use telling me to use "dots: true" parameter). here is the fiddle

http://jsfiddle.net/sjkdpcjo/49/

```<code><div class="paging-group">
  <ul>
    <li data-page="1">
      <button>1</button>
    </li>
    <li data-page="2">
      <button>2</button>
    </li>
    <li data-page="3">
      <button>3</button>
    </li>
  </ul>
</div>

<section class="main-carousel">
  <div class="carousel">
    <div class="carousel-item">1</div>
    <div class="carousel-item">2</div>
    <div class="carousel-item">3</div>
    <div class="carousel-item">4</div>
    <div class="carousel-item">5</div>
    <div class="carousel-item">6</div>
    <div class="carousel-item">7</div>
    <div class="carousel-item">8</div>
    <div class="carousel-item">9</div>
    <div class="carousel-item">10</div>
    <div class="carousel-item">11</div>
    <div class="carousel-item">12</div>
    <div class="carousel-item">13</div>
    <div class="carousel-item">14</div>
    <div class="carousel-item">15</div>
    <div class="carousel-item">16</div>
  </div>
</section>
</code>```

the javascript code

```<code>carousel.slick({
  dots: true,
  slidesToShow: 4,
  slidesToScroll: 4,
  arrows: false,
  infinite: false,
  dots: false,
});

$( '.paging-group ul li' ).click( function() {
    var page = $( this ).data( 'page' );
    console.log( page );
    carousel.slick('slickGoTo', page);
});
</code>```

it's weird, since it won't go to other page except first page (try to slide / swipe to any page except the first one, and click the dots).

答:
The slickToGo function asks for the item number as parameter, not the page number. The reason why it always goes to the first page is because all items (1, 2, and 3) are all on the first page. You can change the code as follows, assuming there is always exactly 4 items per page:

```<code>carousel.slick('slickGoTo', (page - 1) * 4 + 1);
</code>```

In this case, if the user clicks 2 (for page 2), it will call slickGoTo on item number 5, which is the beginning of page 2.

Body:
I tried making a carousel with slick js and make custom dots. (I make this custom dots since I need the dots to be outside of carousel div, so it's no use telling me to use "dots: true" parameter). here is the fiddle

http://jsfiddle.net/sjkdpcjo/49/

      <button>1</button>

      <button>2</button>

      <button>3</button>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

the javascript code

carousel.slick({
  dots: true,
  slidesToShow: 4,
  slidesToScroll: 4,
  arrows: false,
  infinite: false,
  dots: false,
});

$( '.paging-group ul li' ).click( function() {
    var page = $( this ).data( 'page' );
    console.log( page );
    carousel.slick('slickGoTo', page);
});

it's weird, since it won't go to other page except first page (try to slide / swipe to any page except the first one, and click the dots).

Body:
The slickToGo function asks for the item number as parameter, not the page number. The reason why it always goes to the first page is because all items (1, 2, and 3) are all on the first page. You can change the code as follows, assuming there is always exactly 4 items per page:

carousel.slick('slickGoTo', (page - 1) * 4 + 1);

In this case, if the user clicks 2 (for page 2), it will call slickGoTo on item number 5, which is the beginning of page 2.


来源: stackexchange

问:
Python script could not access network drive in scheduled task but could run manually
I have a simple Python script to scan a network drive and copy file out. The script could copy file in IDE. However, if I add the script into task scheduler, it will show the network drive not accessible.
Code snippet

```<code>os.system("net use z: /d /Y")
os.system("net use z: \\server\folder password /user:user_name /p:yes")
network_drive=r"\\server\folder"
if not os.path.exists(network_drive):
    print("Drive  "+ network_drive+" is not available")
else:
    #copy files
</code>```

Manually run the code, it could copy. Ran in task scheduler, it will print info.
I add network mapping lines from this link. Seems not working for me.
How could I access network drive in my python code? In task scheduler, I already selected "Run whether user is logged on or not" and "Run with highest privileges".

EDIT:
The real issue is net use doesn't mount the folder correctly.
I check the output of os.system and get below error

System error 1219  has occurred Multiple connections to a server or
  shared resource by the same user, using more  than one user name, are
  not allowed. Disconnect all previous connections to the  server or
  shared resource and try again.

Combine the solution from here , delete all mounts and restart the sever resolve issue for me.
Please let me know if there is solution without restart server.

答:
There was a major overhaul of Scheduled Tasks security in Vista and later to prevent hackers from installing a scheduled task that could access network resources.

When a user is not logged on, task scheduler uses “Service-for-User” (S4U) authentication which denies the user access to any network functionality. This applies to both mapped drives and using UNC file specs.

"Run with Highest privileges" does not grant higher privileges to the specified user but runs under a completely separate security token for the system Administrator account that is created when Windows is installed.

https://technet.microsoft.com/en-us/library/cc722152(v=ws.11).aspx

https://technet.microsoft.com/en-us/library/cc732613(v=ws.10).aspx

https://technet.microsoft.com/en-us/library/ee844140(v=ws.10).aspx

The only way I got access to networked drives using either a mapped drive or a UNC spec was to leave the machine on and the user logged in.

ContentLicense: CC BY-SA 3.0

Body:
I have a simple Python script to scan a network drive and copy file out. The script could copy file in IDE. However, if I add the script into task scheduler, it will show the network drive not accessible.
Code snippet

os.system("net use z: /d /Y")
os.system("net use z: \\server\folder password /user:user_name /p:yes")
network_drive=r"\\server\folder"
if not os.path.exists(network_drive):
    print("Drive  "+ network_drive+" is not available")
else:
    #copy files

Manually run the code, it could copy. Ran in task scheduler, it will print info.
I add network mapping lines from this link. Seems not working for me.
How could I access network drive in my python code? In task scheduler, I already selected "Run whether user is logged on or not" and "Run with highest privileges".

EDIT:
The real issue is net use doesn't mount the folder correctly.
I check the output of os.system and get below error

System error 1219  has occurred Multiple connections to a server or
  shared resource by the same user, using more  than one user name, are
  not allowed. Disconnect all previous connections to the  server or
  shared resource and try again.

Combine the solution from here , delete all mounts and restart the sever resolve issue for me.
Please let me know if there is solution without restart server.


问:
Help with a MySQL query
I have the following query:

```<code>SELECT u.uid, pf.title, pv.value FROM users AS u INNER JOIN
profile_values AS pv ON pv.uid = u.uid
INNER JOIN
profile_fields AS pf ON pf.fid = pv.fid
ORDER BY u.uid
</code>```

Which results in:

```<code>uid     title   value
1   First name  Jared
1   Last name   Boo
1   Organization    Acme
1   Website http://acme.com
1   Country Canada
6   First name  Nathan
6   Last name   Foo
</code>```

I am attempting to use this result to create another result set which looks like this:

```<code>uid  First name  Last name  Organization  Website  Country
1    Jared       Boo        Acme          http...  Canada
6    Nathan      Foo
</code>```

Am I going about this correctly?

Thanks in advance

EDIT

Tables:

```<code>CREATE TABLE `users` (
  `uid` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(60) NOT NULL default '',
  `pass` varchar(32) NOT NULL default '',
  `mail` varchar(64) default '',
  `created` int(11) NOT NULL default '0',
  `access` int(11) NOT NULL default '0',
  PRIMARY KEY  (`uid`),
  UNIQUE KEY `name` (`name`),
  KEY `access` (`access`),
  KEY `created` (`created`),
  KEY `mail` (`mail`)
);

CREATE TABLE `profile_fields` (
  `fid` int(11) NOT NULL auto_increment,
  `title` varchar(255) default NULL,
  `name` varchar(128) NOT NULL default '',
  `explanation` text,
  `category` varchar(255) default NULL,
  PRIMARY KEY  (`fid`),
  UNIQUE KEY `name` (`name`),
  KEY `category` (`category`)
);

CREATE TABLE `profile_values` (
  `fid` int(10) unsigned NOT NULL default '0',
  `uid` int(10) unsigned NOT NULL default '0',
  `value` text,
  PRIMARY KEY  (`uid`,`fid`),
  KEY `fid` (`fid`)
);
</code>```

答: This is all correct. It is not clear where organization, Website, Country fields should come from (as we don't know your database structure), but, for example, if country was a column of profile_fields, you would simply add SELECT ..., pf.country ...  to get the desired data.

ContentLicense: CC BY-SA 2.5

Title: Help with a MySQL query

Body:
I have the following query:

SELECT u.uid, pf.title, pv.value FROM users AS u INNER JOIN
profile_values AS pv ON pv.uid = u.uid
INNER JOIN
profile_fields AS pf ON pf.fid = pv.fid
ORDER BY u.uid

Which results in:

uid     title   value
1   First name  Jared
1   Last name   Boo
1   Organization    Acme
1   Website http://acme.com
1   Country Canada
6   First name  Nathan
6   Last name   Foo

I am attempting to use this result to create another result set which looks like this:

uid  First name  Last name  Organization  Website  Country
1    Jared       Boo        Acme          http...  Canada
6    Nathan      Foo

Am I going about this correctly?

Thanks in advance

EDIT

Tables:

CREATE TABLE `users` (
  `uid` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(60) NOT NULL default '',
  `pass` varchar(32) NOT NULL default '',
  `mail` varchar(64) default '',
  `created` int(11) NOT NULL default '0',
  `access` int(11) NOT NULL default '0',
  PRIMARY KEY  (`uid`),
  UNIQUE KEY `name` (`name`),
  KEY `access` (`access`),
  KEY `created` (`created`),
  KEY `mail` (`mail`)
);

CREATE TABLE `profile_fields` (
  `fid` int(11) NOT NULL auto_increment,
  `title` varchar(255) default NULL,
  `name` varchar(128) NOT NULL default '',
  `explanation` text,
  `category` varchar(255) default NULL,
  PRIMARY KEY  (`fid`),
  UNIQUE KEY `name` (`name`),
  KEY `category` (`category`)
);

CREATE TABLE `profile_values` (
  `fid` int(10) unsigned NOT NULL default '0',
  `uid` int(10) unsigned NOT NULL default '0',
  `value` text,
  PRIMARY KEY  (`uid`,`fid`),
  KEY `fid` (`fid`)
);


问:
Firebase Authenticate using a Phone Number: use of unresolved identifier AuthAPNSTokenTypeProd and UIBackgroundFetchResultNoData error
I am integrating Authenticate with Firebase on iOS using a Phone Number and I am having errors in the initial implementation of the procedure as mentioned in their document in this link.

I followed the procedure mentioned their, installed the pods and imported the firebase SDK.
The error comes in the following two methods:

```<code>func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  // Pass device token to auth
  Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenTypeProd)

  // Further handling of the device token if needed by the app
  // ...
}
</code>```

and

```<code>func application(_ application: UIApplication,
didReceiveRemoteNotification notification: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if Auth.auth().canHandleNotification(notification) {
    completionHandler(UIBackgroundFetchResultNoData)
    return
  }
  // This notification is not auth related, developer should handle it.
}
</code>```

It says "use of unresolved identifier 'AuthAPNSTokenTypeProd'" and "use of unresolved identifier 'UIBackgroundFetchResultNoData'".

I am not sure about the procedure I am missing in the implementation. I have gone through the implementation procedure many times, I can't find the mistake.

答:
Please try following code

```<code>Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.prod)
</code>```

and this

```<code>func application(_ application: UIApplication,
                 didReceiveRemoteNotification notification: [AnyHashable : Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if Auth.auth().canHandleNotification(notification) {
        completionHandler(UIBackgroundFetchResult.noData)
        return
    }
    // This notification is not auth related, developer should handle it.
}
</code>```

Body:
I am integrating Authenticate with Firebase on iOS using a Phone Number and I am having errors in the initial implementation of the procedure as mentioned in their document in this link.

I followed the procedure mentioned their, installed the pods and imported the firebase SDK.
The error comes in the following two methods:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  // Pass device token to auth
  Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenTypeProd)

  // Further handling of the device token if needed by the app
  // ...
}

and

func application(_ application: UIApplication,
didReceiveRemoteNotification notification: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if Auth.auth().canHandleNotification(notification) {
    completionHandler(UIBackgroundFetchResultNoData)
    return
  }
  // This notification is not auth related, developer should handle it.
}

It says "use of unresolved identifier 'AuthAPNSTokenTypeProd'" and "use of unresolved identifier 'UIBackgroundFetchResultNoData'".

I am not sure about the procedure I am missing in the implementation. I have gone through the implementation procedure many times, I can't find the mistake.

Body:
Please try following code

Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.prod)

and this

func application(_ application: UIApplication,
                 didReceiveRemoteNotification notification: [AnyHashable : Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if Auth.auth().canHandleNotification(notification) {
        completionHandler(UIBackgroundFetchResult.noData)
        return
    }
    // This notification is not auth related, developer should handle it.
}


问:
ElasticSearch 5.4.0 query (PHP)
To connect to ElastickSearch, I use basemkhirat/elasticsearch. The following problem was formed: Using this method with this query("google.com") to search links in index

```<code>ES::type("links")->search("google.com")->get();
</code>```

I'm found 56 links (for example), but if I used query "google"

```<code>ES::type("links")->search("google")->get();
</code>```

I'm found nothing(0). What is my problem?

JSON Query, witch created through the search:

```<code>{
    "index":"links",
    "type":"link",
    "body": {
        "query": {
            "bool": {
                "must": [
                    {
                        "query_string": {
                            "query":"google.com"
                        }
                    }
                ]
            }
        }
    },
    "from":0,
    "size":10000
}
</code>```

P.S: In Kibana I'm watching the same things.

答:
I haven't looked into the library you're using but it looks like doing a wild card query will work for you. It won't perform great if you have a lot of data, or if you overuse the wildcard.

Something like this might work for you - let me know how it goes.

```<code>ES::type("links")->search("google*")->get();
</code>```

PS, if I were in your position, I would have looked into the library and tried to find out if they support Prefix queries. I'm assuming they must be - might want to spend couple of hours looking there.

Title: ElasticSearch 5.4.0 query (PHP)

Body:
To connect to ElastickSearch, I use basemkhirat/elasticsearch. The following problem was formed: Using this method with this query("google.com") to search links in index

ES::type("links")->search("google.com")->get();

I'm found 56 links (for example), but if I used query "google"

ES::type("links")->search("google")->get();

I'm found nothing(0). What is my problem?

JSON Query, witch created through the search:

{
    "index":"links",
    "type":"link",
    "body": {
        "query": {
            "bool": {
                "must": [
                    {
                        "query_string": {
                            "query":"google.com"
                        }
                    }
                ]
            }
        }
    },
    "from":0,
    "size":10000
}

P.S: In Kibana I'm watching the same things.

Body:
I haven't looked into the library you're using but it looks like doing a wild card query will work for you. It won't perform great if you have a lot of data, or if you overuse the wildcard.

Something like this might work for you - let me know how it goes.

ES::type("links")->search("google*")->get();

PS, if I were in your position, I would have looked into the library and tried to find out if they support Prefix queries. I'm assuming they must be - might want to spend couple of hours looking there.


问:
Most efficient way to get genre of song android
I am trying to grab the genre of each song while I'm loading the songs. Currently I am using this solution:

```<code>MediaMetadataRetriever mr = new MediaMetadataRetriever();
Uri trackUri = ContentUris.withAppendedId(
                  android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                  cursor.getLong(id));
mr.setDataSource(c, trackUri);
String genre = mr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE);
</code>```

It does work, but takes an insanely long time. On my test phone with only ~20 songs it works fast, but on my main phone with 1700+ songs it takes a really long time. If I remove that code and load just the songs it's almost instant so I know it has to be this. Is there a better/more efficient way to get the genre of a song with the song id?

Thanks in advance for any help!

Full code snippet

```<code>    try {
        if (cursor.moveToFirst()) {
            int id = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
            int title = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            int album = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
            int artist = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
            int duration = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
            int albumId = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
            int data = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);

            do {

                MediaMetadataRetriever mr = new MediaMetadataRetriever();
                Uri trackUri = ContentUris.withAppendedId(
                        android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        cursor.getLong(id));
                mr.setDataSource(c, trackUri);
                String genre = mr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE);

                if (genre == null){
                    genre = "Not Specified";
                }

                 genres.add(genre);

                Song item = new Song(cursor.getLong(id), cursor.getString(title),
                        cursor.getString(artist), cursor.getString(album),
                        cursor.getLong(duration),
                        ContentUris.withAppendedId(albumArtUri, cursor.getLong(albumId)),
                        Uri.parse(cursor.getString(data)), "");

                items.add(item);
            } while (cursor.moveToNext());
        }
    } finally {
        cursor.close();
    }
</code>```

答:
Your do-while loop is likely the cause of the bottleneck. Instead of iterating through sequentially like you are, you could try implementing code to execute the iterations of the loop in parallel.

I'm not sure what sort of data structure the cursor is iterating through, but assuming it's a data structure called allCursors, the code would look something like this:

```<code>allCursors.parallelStream().forEach(cursor -> {
    // inside of loop
});
</code>```

Body:
I am trying to grab the genre of each song while I'm loading the songs. Currently I am using this solution:

MediaMetadataRetriever mr = new MediaMetadataRetriever();
Uri trackUri = ContentUris.withAppendedId(
                  android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                  cursor.getLong(id));
mr.setDataSource(c, trackUri);
String genre = mr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE);

It does work, but takes an insanely long time. On my test phone with only ~20 songs it works fast, but on my main phone with 1700+ songs it takes a really long time. If I remove that code and load just the songs it's almost instant so I know it has to be this. Is there a better/more efficient way to get the genre of a song with the song id?

Thanks in advance for any help!

Full code snippet

    try {
        if (cursor.moveToFirst()) {
            int id = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
            int title = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            int album = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
            int artist = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
            int duration = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
            int albumId = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
            int data = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);

            do {

                MediaMetadataRetriever mr = new MediaMetadataRetriever();
                Uri trackUri = ContentUris.withAppendedId(
                        android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        cursor.getLong(id));
                mr.setDataSource(c, trackUri);
                String genre = mr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE);

                if (genre == null){
                    genre = "Not Specified";
                }

                 genres.add(genre);

                Song item = new Song(cursor.getLong(id), cursor.getString(title),
                        cursor.getString(artist), cursor.getString(album),
                        cursor.getLong(duration),
                        ContentUris.withAppendedId(albumArtUri, cursor.getLong(albumId)),
                        Uri.parse(cursor.getString(data)), "");

                items.add(item);
            } while (cursor.moveToNext());
        }
    } finally {
        cursor.close();
    }

Body:
Your do-while loop is likely the cause of the bottleneck. Instead of iterating through sequentially like you are, you could try implementing code to execute the iterations of the loop in parallel.

I'm not sure what sort of data structure the cursor is iterating through, but assuming it's a data structure called allCursors, the code would look something like this:

allCursors.parallelStream().forEach(cursor -> {
    // inside of loop
});


问:
What is the `g` in angular selectors for?
Some ngx-charts components have a g in the selector like this:

```<code>selector: 'g[ngx-charts-line]'
</code>```

What is the g for?

答:
I'm guessing it is the HTML <g> tag:

https://developer.mozilla.org/en/docs/Web/SVG/Element/g

Body:
Some ngx-charts components have a g in the selector like this:

selector: 'g[ngx-charts-line]'

What is the g for?


问:
PL/SQL Package invalidated
I have a script that makes use of a package (PKG_MY_PACKAGE). I will change some of the fields in a query in that package and then recompile it (I don't change or compile any other packages). I run the script and I get an error that looks like

```
    ORA-04068: existing state of packages has been discarded
    ORA-04061: existing state of package body "USER3.PKG_MY_PACKAGE" has been invalidated
    ORA-04065: not executed, altered or dropped package body "USER3.PKG_MY_PACKAGE"
    ORA-06508: PL/SQL: could not find program unit being called: "USER3.PKG_MY_PACKAGE"
    ORA-06512: at line 34
```

I run the script again (without changing anything else in the system) and the script executes successfully.

I thought that when I compiled before I executed the script that would fix any invalid references. This is 100% reproducible, and the more I use this script the more annoying it gets. What could cause this, and what would fix it?

(oracle 10g, using PL/SQL Developer 7)

答:
The above error : ORA-06508: PL/SQL: could not find program unit being called.

is caused when an attempt was made to call a stored program that could not be found. The program may have been dropped or incompatibly modified, or have compiled with errors.

Check that all referenced programs, including their package bodies,    exist and are compatible.

You can run this query to find invalid objects, which may cause the ORA-06508 error:

select
   comp_id,
   comp_name,
   version,
   status,
   namespace,
   schema
from
   dba_registry;

Title: PL/SQL Package invalidated

Body:
I have a script that makes use of a package (PKG_MY_PACKAGE). I will change some of the fields in a query in that package and then recompile it (I don't change or compile any other packages). I run the script and I get an error that looks like

    ORA-04068: existing state of packages has been discarded
    ORA-04061: existing state of package body "USER3.PKG_MY_PACKAGE" has been invalidated
    ORA-04065: not executed, altered or dropped package body "USER3.PKG_MY_PACKAGE"
    ORA-06508: PL/SQL: could not find program unit being called: "USER3.PKG_MY_PACKAGE"
    ORA-06512: at line 34

I run the script again (without changing anything else in the system) and the script executes successfully.

I thought that when I compiled before I executed the script that would fix any invalid references. This is 100% reproducible, and the more I use this script the more annoying it gets. What could cause this, and what would fix it?

(oracle 10g, using PL/SQL Developer 7)


问:
visual studio - "tag" some code with a test
I'm making sure all my code has test coverage by just associating some code (a method, or maybe an if/else branch) with a unique id, and then associating some tests with that same unique id, but its all just commented out guid strings. Is there a better way at specifically managing tests and the code snippets they relate to? </p>

答:
I added this as an enhancement request for NYC, seems like its been endorsed, hopefully it will be implemented

https://github.com/istanbuljs/nyc/issues/597


问:
Hash_hmac equivalent in Node.js
I have code that is working in my PHP app.  In the PHP I sign the url with the following code:

```<code>private static function __getHash($string)
{
    return hash_hmac('sha1', $string, self::$__secretKey, true);
}
</code>```

I am attempting to sign the URL in the same way in a Node.js application.  This is what I'm trying:

```<code>S3.prototype.getHash = function(string){
    var key = this.secret_key;
    var hmac = crypto.createHash('sha1', key);
    hmac.update(string);
    return hmac.digest('binary');
};
</code>```

However, I am getting the following error:

The request signature we calculated does not match the signature you provided. Check your key and signing method.

Do these pieces of code do the same thing? Am I missing something?

答:
This answer from Chris is good if you are porting hash_hmac with the last parameter being true. In this case, binary is produced, as is the case with Chris's javascript.

To add to that, this example:

```<code> $sign = hash_hmac('sha512', $post_data, $secret);
</code>```

Would be ported with a function like so in nodejs:

```<code>const crypto = require("crypto");

function signHmacSha512(key, str) {
  let hmac = crypto.createHmac("sha512", key);
  let signed = hmac.update(Buffer.from(str, 'utf-8')).digest("hex");
  return signed
}
</code>```

The difference here being that when you leave off the last argument to hash_hmac (or set it to something not true), it behaves as defined in the PHP docs:

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

In order to do this with node.js we use digest('hex') as you can see in the snippet.

Title: Hash_hmac equivalent in Node.js

Body:
I have code that is working in my PHP app.  In the PHP I sign the url with the following code:

private static function __getHash($string)
{
    return hash_hmac('sha1', $string, self::$__secretKey, true);
}

I am attempting to sign the URL in the same way in a Node.js application.  This is what I'm trying:

S3.prototype.getHash = function(string){
    var key = this.secret_key;
    var hmac = crypto.createHash('sha1', key);
    hmac.update(string);
    return hmac.digest('binary');
};

However, I am getting the following error:

The request signature we calculated does not match the signature you provided. Check your key and signing method.

Do these pieces of code do the same thing? Am I missing something?

Body:
This answer from Chris is good if you are porting hash_hmac with the last parameter being true. In this case, binary is produced, as is the case with Chris's javascript.

To add to that, this example:

 $sign = hash_hmac('sha512', $post_data, $secret);

Would be ported with a function like so in nodejs:

const crypto = require("crypto");

function signHmacSha512(key, str) {
  let hmac = crypto.createHmac("sha512", key);
  let signed = hmac.update(Buffer.from(str, 'utf-8')).digest("hex");
  return signed
}

The difference here being that when you leave off the last argument to hash_hmac (or set it to something not true), it behaves as defined in the PHP docs:

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

In order to do this with node.js we use digest('hex') as you can see in the snippet.

ContentLicense: CC BY-SA 4.0


问:
PID error on mysql.server start?
I've just tried installing MySQL using homebrew (on Mac OS X 10.6), but I've run across an issue at the first hurdle. When trying to manually start the server (mysql.server start), I get the following error:

```<code>. ERROR! Manager of pid-file quit without updating file.
</code>```

Unfortunately I'm not sure of which error logs or configuration files to check, as I've never installed MySQL in this way before.

答:
You probably need to ensure that you're running mysql as the root user -- otherwise it won't have permission to write the PID file (thus the error you're receiving).

Try this:

```<code>sudo mysql.server start
</code>```

You'll be prompted for your password.  (this assumes that your user account has permissions to "sudo" -- which it should, unless it's setup as a restricted user account in OS X).

This may not be the only issue -- but it should get you to the next step anyway.

Title: PID error on mysql.server start?

Body:
I've just tried installing MySQL using homebrew (on Mac OS X 10.6), but I've run across an issue at the first hurdle. When trying to manually start the server (mysql.server start), I get the following error:

. ERROR! Manager of pid-file quit without updating file.

Unfortunately I'm not sure of which error logs or configuration files to check, as I've never installed MySQL in this way before.

Body:
You probably need to ensure that you're running mysql as the root user -- otherwise it won't have permission to write the PID file (thus the error you're receiving).

Try this:

sudo mysql.server start

You'll be prompted for your password.  (this assumes that your user account has permissions to "sudo" -- which it should, unless it's setup as a restricted user account in OS X).

This may not be the only issue -- but it should get you to the next step anyway.


问:
Emulator not working in Android Studio 2.0
I am using Android Studio 2.0 Stable version. Whenever I click on the play button on the device to run it shows starting AVD progress in android studio and after completing it's progress nothing happened.The app window remains as it shown in screenshot and the emulator doesn't start. I can't find a solution for this issue. I have already tried many solutions which I found on the internet, changing HAXM version android SDK update, changed target API's. But nothing works.

答: I had the same problem. I just created the AVD with 768 MB RAM and it did run fine!</p>


问:
Recursive Compounding Interest
I have to rewrite this as a recursive function, and I don't understand what I'm doing wrong. I've googled and googled and seen many different ways, which just makes it even more confusing.

```<code>float Total(float ir=0, int time=0)//Savings Procedure
{
    float bal = Balance;
    for (short i = 0; i < time; i++)
    {
        bal += (Balance*((1.0+ir)/time))/100;
    }
    return bal;
};
</code>```

My attempt:

```<code>float compoundit(float balance, float ir, int time)
{
    if (time < 0)
    {
        return balance;
    }
    balance = balance * ((1.0 + ir)/time);
    return compoundit(balance, ir, --time);
}
float TotalRecursive(float ir=0, int time=0)
{
    return compoundit(Balance, ir, time);
};
</code>```

Am I even close? Sometimes I just get 'inf' as a result. Any help would be appreciated.

答:
Consider this part of your code:

```<code>if (time < 0)
{
    return balance;
}
</code>```

Okay, at this point we know that time >= 0. Next:

```<code>balance = balance * ((1.0 + ir)/time);
</code>```

So time could be zero in the above expression. And what happens when you divide by zero in IEEE floating point? You get infinity.

Aside from that, you have another bug. You divide by time, but you're decrementing time on each recursive call. In the original function, you don't decrement time. So in your recursive version, you need to pass both time and the number of recursive calls you've made, as separate arguments.

Note also that the original non-recursive Total is also broken in at least two ways, so it does not give calculate compound interest correctly either.

Title: Recursive Compounding Interest

Body:
I have to rewrite this as a recursive function, and I don't understand what I'm doing wrong. I've googled and googled and seen many different ways, which just makes it even more confusing.

float Total(float ir=0, int time=0)//Savings Procedure
{
    float bal = Balance;
    for (short i = 0; i < time; i++)
    {
        bal += (Balance*((1.0+ir)/time))/100;
    }
    return bal;
};

My attempt:

float compoundit(float balance, float ir, int time)
{
    if (time < 0)
    {
        return balance;
    }
    balance = balance * ((1.0 + ir)/time);
    return compoundit(balance, ir, --time);
}
float TotalRecursive(float ir=0, int time=0)
{
    return compoundit(Balance, ir, time);
};

Am I even close? Sometimes I just get 'inf' as a result. Any help would be appreciated.

Body:
Consider this part of your code:

if (time < 0)
{
    return balance;
}

Okay, at this point we know that time >= 0. Next:

balance = balance * ((1.0 + ir)/time);

So time could be zero in the above expression. And what happens when you divide by zero in IEEE floating point? You get infinity.

Aside from that, you have another bug. You divide by time, but you're decrementing time on each recursive call. In the original function, you don't decrement time. So in your recursive version, you need to pass both time and the number of recursive calls you've made, as separate arguments.

Note also that the original non-recursive Total is also broken in at least two ways, so it does not give calculate compound interest correctly either.


问:
Upload a Pandas DataFrame as Excel file directly to Google Drive using PyDrive
I'm trying to write a pandas.DataFrame directly to Google Drive, without first writing the file out locally. I can't find a solution and not sure if it is even possible. I've tried the code below, but I get an AttributeError.

```<code>import pandas as pd
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LoadCredentialsFile(mycreds)
drive = GoogleDrive(gauth)

df = pd.DataFrame({'a':[1,2],'b':[2,3]})

f = drive.CreateFile({'id': '0B_6_uVX9biFuX0FJWFkt'}) #test.xlsx file
f.SetContentString(df)
f.Upload()
</code>```

AttributeError: 'DataFrame' object has no attribute 'encode'

答:
It is possible to get pandas to write an Excel file directly to a string like:

Code:

```<code>wb = Workbook()
writer = pd.ExcelWriter('', engine='openpyxl')
writer.book = wb
df.to_excel(writer)
file_as_string = save_virtual_workbook(wb)
</code>```

Full Code:

Here is the above code combined with your example.  Please note that this part is untested.

```<code>import pandas as pd
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LoadCredentialsFile(mycreds)
drive = GoogleDrive(gauth)

df = pd.DataFrame({'a': [1, 2], 'b': [2, 3]})

from openpyxl.workbook import Workbook
from openpyxl.writer.excel import save_virtual_workbook

wb = Workbook()
writer = pd.ExcelWriter('', engine='openpyxl')
writer.book = wb
df.to_excel(writer)

f = drive.CreateFile({'id': '0B_6_uVX9biFuX0FJWFkt'}) #test.xlsx file
f.SetContentString(save_virtual_workbook(wb))
f.Upload()
</code>```

Body:
I'm trying to write a pandas.DataFrame directly to Google Drive, without first writing the file out locally. I can't find a solution and not sure if it is even possible. I've tried the code below, but I get an AttributeError.

import pandas as pd
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LoadCredentialsFile(mycreds)
drive = GoogleDrive(gauth)

df = pd.DataFrame({'a':[1,2],'b':[2,3]})

f = drive.CreateFile({'id': '0B_6_uVX9biFuX0FJWFkt'}) #test.xlsx file
f.SetContentString(df)
f.Upload()

AttributeError: 'DataFrame' object has no attribute 'encode'

Body:
It is possible to get pandas to write an Excel file directly to a string like:

Code:

wb = Workbook()
writer = pd.ExcelWriter('', engine='openpyxl')
writer.book = wb
df.to_excel(writer)
file_as_string = save_virtual_workbook(wb)

Full Code:

Here is the above code combined with your example.  Please note that this part is untested.

import pandas as pd
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LoadCredentialsFile(mycreds)
drive = GoogleDrive(gauth)

df = pd.DataFrame({'a': [1, 2], 'b': [2, 3]})

from openpyxl.workbook import Workbook
from openpyxl.writer.excel import save_virtual_workbook

wb = Workbook()
writer = pd.ExcelWriter('', engine='openpyxl')
writer.book = wb
df.to_excel(writer)

f = drive.CreateFile({'id': '0B_6_uVX9biFuX0FJWFkt'}) #test.xlsx file
f.SetContentString(save_virtual_workbook(wb))
f.Upload()


问:
Is it iCloud or is it my code?
I am using a slightly updated code of this question: Method for downloading iCloud files? Very confusing?

Here is an excerpt of the code:

```<code>private func downloadUbiquitiousItem(atURL url: URL) -> Void {
        do {
            try FileManager.default.startDownloadingUbiquitousItem(at: url)
            do {
                let attributes = try url.resourceValues(forKeys: [URLResourceKey.ubiquitousItemDownloadingStatusKey])
                if let status: URLUbiquitousItemDownloadingStatus = attributes.allValues[URLResourceKey.ubiquitousItemDownloadingStatusKey] as? URLUbiquitousItemDownloadingStatus {
                    if status == URLUbiquitousItemDownloadingStatus.current {
                        self.processDocument(withURL: url)
                        return
                    } else if status == URLUbiquitousItemDownloadingStatus.downloaded {
                        self.processDocument(withURL: url)
                        return
                    } else if status == URLUbiquitousItemDownloadingStatus.notDownloaded {
                        do {
                            //will go just fine, if it is unnecessary to download again
                            try FileManager.default.startDownloadingUbiquitousItem(at: url)
                        } catch {
                            return
                        }
                    }
                }
            } catch {

            }

            //only happens if the try does not fail
            self.documentsQuery = NSMetadataQuery()
            self.documentsQuery.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
            self.documentsQuery.valueListAttributes = [NSMetadataUbiquitousItemPercentDownloadedKey,NSMetadataUbiquitousItemDownloadingStatusKey]
            self.documentsQuery.predicate = NSPredicate(format: "%K like 'backup.json'", argumentArray: [NSMetadataItemFSNameKey])

            NotificationCenter.default.addObserver(self, selector: #selector(self.queryUpdate(notification:)), name: NSNotification.Name.NSMetadataQueryDidUpdate, object: self.documentsQuery)

            DispatchQueue.main.async {
                if self.documentsQuery.start() {
                    if self.restoreHUD != nil {
                        self.restoreHUD.show(animated: true)
                        //timeout for restoring
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(30), execute: {
                            if self.restoreHUD != nil {
                                self.restoreHUD.hide(animated: true)
                            }
                        })
                    }
                }
            }
        } catch {
            //file does not exist in icloud most likely
        }
    }
</code>```

So this works sometimes, but it is really unstable, for example we tested the following cases:

Backup to iCloud

Check that we have a valid document in Settings -> iCloud -> Storage -> Manage Storage -> MyApp -> backup.json

Force a first launch, so that the app restores backup.json (aka executes the code above)

This sometimes works and sometimes doesn't. Sometimes the query won't update.

We also tested the following scenario:

Remove backup from iCloud manually via settings

Uninstall the app and reinstall it to provide a first launch

the startDownloadingUbiquitousItem function does not seem to throw, even though nothing is in iCloud because I think that iCloud still hasn't synced the local file or deleted the local data, but it also does not download properly... yet the status is notDownloaded.

Maybe users are not supposed to wipe the stuff via Settings? I'd like to know if my code is missing a case that could happen, or if this API is just really unhandy for developers...

Thanks!

答:
Probably, we call to adding notification in "main thread".</p>

```<code>NotificationCenter.default.addObserver(self, selector: #selector(self.queryUpdate(notification:)), name: NSNotification.Name.NSMetadataQueryDidUpdate, object: self.documentsQuery)
</code>```

Title: Is it iCloud or is it my code?

Body:
I am using a slightly updated code of this question: Method for downloading iCloud files? Very confusing?

Here is an excerpt of the code:

private func downloadUbiquitiousItem(atURL url: URL) -> Void {
        do {
            try FileManager.default.startDownloadingUbiquitousItem(at: url)
            do {
                let attributes = try url.resourceValues(forKeys: [URLResourceKey.ubiquitousItemDownloadingStatusKey])
                if let status: URLUbiquitousItemDownloadingStatus = attributes.allValues[URLResourceKey.ubiquitousItemDownloadingStatusKey] as? URLUbiquitousItemDownloadingStatus {
                    if status == URLUbiquitousItemDownloadingStatus.current {
                        self.processDocument(withURL: url)
                        return
                    } else if status == URLUbiquitousItemDownloadingStatus.downloaded {
                        self.processDocument(withURL: url)
                        return
                    } else if status == URLUbiquitousItemDownloadingStatus.notDownloaded {
                        do {
                            //will go just fine, if it is unnecessary to download again
                            try FileManager.default.startDownloadingUbiquitousItem(at: url)
                        } catch {
                            return
                        }
                    }
                }
            } catch {

            }

            //only happens if the try does not fail
            self.documentsQuery = NSMetadataQuery()
            self.documentsQuery.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
            self.documentsQuery.valueListAttributes = [NSMetadataUbiquitousItemPercentDownloadedKey,NSMetadataUbiquitousItemDownloadingStatusKey]
            self.documentsQuery.predicate = NSPredicate(format: "%K like 'backup.json'", argumentArray: [NSMetadataItemFSNameKey])

            NotificationCenter.default.addObserver(self, selector: #selector(self.queryUpdate(notification:)), name: NSNotification.Name.NSMetadataQueryDidUpdate, object: self.documentsQuery)

            DispatchQueue.main.async {
                if self.documentsQuery.start() {
                    if self.restoreHUD != nil {
                        self.restoreHUD.show(animated: true)
                        //timeout for restoring
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(30), execute: {
                            if self.restoreHUD != nil {
                                self.restoreHUD.hide(animated: true)
                            }
                        })
                    }
                }
            }
        } catch {
            //file does not exist in icloud most likely
        }
    }

So this works sometimes, but it is really unstable, for example we tested the following cases:

Backup to iCloud

Check that we have a valid document in Settings -> iCloud -> Storage -> Manage Storage -> MyApp -> backup.json

Force a first launch, so that the app restores backup.json (aka executes the code above)

This sometimes works and sometimes doesn't. Sometimes the query won't update.

We also tested the following scenario:

Remove backup from iCloud manually via settings

Uninstall the app and reinstall it to provide a first launch

the startDownloadingUbiquitousItem function does not seem to throw, even though nothing is in iCloud because I think that iCloud still hasn't synced the local file or deleted the local data, but it also does not download properly... yet the status is notDownloaded.

Maybe users are not supposed to wipe the stuff via Settings? I'd like to know if my code is missing a case that could happen, or if this API is just really unhandy for developers...

Thanks!

Body:
Probably, we call to adding notification in "main thread".

NotificationCenter.default.addObserver(self, selector: #selector(self.queryUpdate(notification:)), name: NSNotification.Name.NSMetadataQueryDidUpdate, object: self.documentsQuery)


问:
how to use execute in nightwatchjs
I wish to populate a field in my application using execute when running nightwatchjs tests

I have tried the following:

```<code>.execute("document.getElementByClassName('.price').setAttribute('value', '19.99')")
</code>```

This does not work, field is not populated however I do not get an error. Can someone explain what I may be doing wrong?

Thanks!

p.s - I know I can populate the field by using .setValue('.price', '9
.99') but I wish to learn how to do it via execute.

答:
You can try the following code. There is only small changes.</p>

```<code>.execute("document.getElementsByClassName('price')[0].setAttribute('value', '19.99')")
</code>```

Title: how to use execute in nightwatchjs

Body:
I wish to populate a field in my application using execute when running nightwatchjs tests

I have tried the following:

.execute("document.getElementByClassName('.price').setAttribute('value', '19.99')")

This does not work, field is not populated however I do not get an error. Can someone explain what I may be doing wrong?

Thanks!

p.s - I know I can populate the field by using .setValue('.price', '9
.99') but I wish to learn how to do it via execute.

Body:
You can try the following code. There is only small changes.

.execute("document.getElementsByClassName('price')[0].setAttribute('value', '19.99')")


问:
Signing a java applet with an spc file from GoDaddy
I'm trying to sign a java applet using an spc file from godaddy.  Here's the command I'm using:

keytool -import -keystore codesignstore -storepass [pass] -alias [alias] -file [filename]

Unfortunately, running this command returns

keytool error: java.lang.Exception: Input not an X.509 certificate

I talked to GoDaddy and they assure me that it is indeed a valid X.509 certificate and otherwise provided 0 help.  Anyone know how to make this work?  I've read a few comments that suggest that the problem might be the alias, but we've tried the alias we specified when creating the CSR as well as the one specified in GoDaddy.  In addition, some note that the problem may be related to this java bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4874076.  However, I don't see any odd URLs in the spc of the type they note in that bug report.  Thanks in advance for your help.

答: While I don't know what was causing the error, I was able to get through the signing process by properly following GoDaddy's instructions.  We originally generated our own CSR and then jumped into GoDaddy's instructions part of the way through.  For others with this problem that have problems reading/following instructions, save yourself the headache and start over again following the steps that GoDaddy outlines.</p>


问:
How do I list the hot links of a subreddit via PowerShell?
What's a good way to retrieve subreddit links via API in PowerShell?</p>

答:
Here's an approach which doesn't depend on any third party libraries. I.e. it's in terms of pure PowerShell.

Let's assume you're keeping your reddit credentials, reddit app client ID and reddit app client secret in files:

```<code>$username          = Get-Content $env:APPDATA\reddit-username
$password          = Get-Content $env:APPDATA\reddit-password

$app_client_id     = Get-Content $env:APPDATA\reddit-app-client-id
$app_client_secret = Get-Content $env:APPDATA\reddit-app-client-secret
</code>```

(See this page for information about getting a reddit client ID.)

Retrieve an access token:

```<code>$result_access_token = Invoke-RestMethod -Uri 'https://www.reddit.com/api/v1/access_token' `
    -Method Post `
    -Headers @{
        Authorization = ('Basic {0}' -f (
            [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(
                "${app_client_id}:${app_client_secret}"))))
    } `
    -Body @{
        grant_type = 'password'
        username   = $username
        password   = $password
    }
</code>```

Let's extract the token from the result and assign it to a variable:

```<code>$token = $result_access_token.access_token
</code>```

Now let's get the current hot links on /r/programming:

```<code>$result_listing = Invoke-RestMethod -Uri 'https://oauth.reddit.com/r/programming/hot' -Headers @{ Authorization = "bearer $token" }
</code>```

Show the links:

```<code>$result_listing.data.children | ForEach-Object data | Select-Object score, subreddit, title, url
</code>```

Example output:

Body:
Here's an approach which doesn't depend on any third party libraries. I.e. it's in terms of pure PowerShell.

Let's assume you're keeping your reddit credentials, reddit app client ID and reddit app client secret in files:

$username          = Get-Content $env:APPDATA\reddit-username
$password          = Get-Content $env:APPDATA\reddit-password

$app_client_id     = Get-Content $env:APPDATA\reddit-app-client-id
$app_client_secret = Get-Content $env:APPDATA\reddit-app-client-secret

(See this page for information about getting a reddit client ID.)

Retrieve an access token:

$result_access_token = Invoke-RestMethod -Uri 'https://www.reddit.com/api/v1/access_token' `
    -Method Post `
    -Headers @{
        Authorization = ('Basic {0}' -f (
            [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(
                "${app_client_id}:${app_client_secret}"))))
    } `
    -Body @{
        grant_type = 'password'
        username   = $username
        password   = $password
    }

Let's extract the token from the result and assign it to a variable:

$token = $result_access_token.access_token

Now let's get the current hot links on /r/programming:

$result_listing = Invoke-RestMethod -Uri 'https://oauth.reddit.com/r/programming/hot' -Headers @{ Authorization = "bearer $token" }

Show the links:

$result_listing.data.children | ForEach-Object data | Select-Object score, subreddit, title, url

Example output:


问:
Simple HTML Dom Can't access 3rd level DIV element
I am trying to display the value 2.11 by using the attribute of data-gamename="1x2" from the third DIV, The code below are from original source.

```<code><div class="games">==$0
  <div class="wrap">
<div class="outcome" onclick="addBet(this)" id="outcome-225162629" data-gameid="61158022" data-outcomeid="225162629" data-gamename="1X2" data-eventname="Benevento Calcio - Carpi FC" data-eventcodeid="137" data-gamename="1X2">2.11</div>
</code>```

From the above code if i want retrieve values of  it will work good and if i want to retrieve values from  it will work good too and make to make a record this second div is inside the first div of  there it come another one inside the second div of  it is called  My problem start here if i want to retrieve data from lets say  it will work like charm but if i change the attribute lets say  like in example above it will not work, it just display nothing i tried to solve with no lucky , As the code look above can any one help me where am wrong?

This is the code for retrieve the value

```<code><?php
include('simple_html_dom.php');
$html = file_get_html('yoururl');
foreach($html->find('div=[data-gamename="1X2"]') as $a){
echo $a->plaintext;
echo nl2br('\n');
}
?>
</code>```

Any idea where am wrong?

答:
I see 3 problems, first the css is wrong, there's an extra = in there. Second, simple_html_dom is old and doesn't fully support css. For a library that does better I suggest this one. Third, why do you call your div $a? That's confusing.

```<code>include('advanced_html_dom.php');
$html = file_get_html('https://sport.premierbet.com/tz/sport/1/#');
foreach($html->find('div[data-gamename="1X2"]') as $div){
  echo $div->plaintext;
  echo nl2br('\n');
}
</code>```

Body:
I am trying to display the value 2.11 by using the attribute of data-gamename="1x2" from the third DIV, The code below are from original source.

==$0

2.11

From the above code if i want retrieve values of  it will work good and if i want to retrieve values from  it will work good too and make to make a record this second div is inside the first div of  there it come another one inside the second div of  it is called  My problem start here if i want to retrieve data from lets say  it will work like charm but if i change the attribute lets say  like in example above it will not work, it just display nothing i tried to solve with no lucky , As the code look above can any one help me where am wrong?

This is the code for retrieve the value

<?php
include('simple_html_dom.php');
$html = file_get_html('yoururl');
foreach($html->find('div=[data-gamename="1X2"]') as $a){
echo $a->plaintext;
echo nl2br('\n');
}
?>

Any idea where am wrong?

Body:
I see 3 problems, first the css is wrong, there's an extra = in there. Second, simple_html_dom is old and doesn't fully support css. For a library that does better I suggest this one. Third, why do you call your div $a? That's confusing.

include('advanced_html_dom.php');
$html = file_get_html('https://sport.premierbet.com/tz/sport/1/#');
foreach($html->find('div[data-gamename="1X2"]') as $div){
  echo $div->plaintext;
  echo nl2br('\n');
}


问:
Adding and retrieving custom properties to MQ
I am bit new to the whole MQ world so I am not sure about the specific technicalities.
I am struggling to send a message on a Websphere Mq with additional data; the additional data will then be used by another system for processing.

I am using the following code to do add additional properties to the mq; is this the correct way to do it?
Code in C#

```<code>IMessage sendMsg;

IMessageProducer producer;

// Create a message ---someMessage will be a xml file
sendMsg = new IMessage(someMessage);

int fileSize= size("document.pdf");

//add addtional message properties
sendMsg.SetStringProperty("MessageSize",fileSize);

// Send the message
producer.Send(sendMsg);
</code>```

Also, how do i query the mq so that I get all these properties along with the actual message?

Can anyone please help; this has got me going round in circles....

答: Yes using SetStringProperty,SetBooleanProperty, etc,you should be able to set the properties. For getting back the property values you should use msg.GetStringProperty,msg.GetBooleanProperty etc after the message is received.In your case it has to be something like msg.GetStringProperty(MessageSize).</p>

Body:
I am bit new to the whole MQ world so I am not sure about the specific technicalities.
I am struggling to send a message on a Websphere Mq with additional data; the additional data will then be used by another system for processing.

I am using the following code to do add additional properties to the mq; is this the correct way to do it?
Code in C#

IMessage sendMsg;

IMessageProducer producer;

// Create a message ---someMessage will be a xml file
sendMsg = new IMessage(someMessage);

int fileSize= size("document.pdf");

//add addtional message properties
sendMsg.SetStringProperty("MessageSize",fileSize);

// Send the message
producer.Send(sendMsg);

Also, how do i query the mq so that I get all these properties along with the actual message?

Can anyone please help; this has got me going round in circles....


问:
How to pass variable to stride by argument
I'm trying to pass an Int constant to my for loop's stride by argument. It takes type T.stride.

```<code>let notchStep:Int = 5

    for degrees:Double in stride(from: 0, to: 359, by: notchStep) {
</code>```

I get this error:

Cannot invoke 'stride' with an argument list of type '(from: Int, to: Int, by: Int)'. What type of value can I pass to by or how can I cast my Int to an appropriate type?

答:
Try removing the :Double in your code, so it reads:

```<code>let notchStep: Int = 5

for degrees in stride(from: 0, to: 359, by: notchStep) {
    // do something
}
</code>```

Looking at the method signature, I think mixing Ints and Doubles is generating the issue.

Body:
I'm trying to pass an Int constant to my for loop's stride by argument. It takes type T.stride.

let notchStep:Int = 5

    for degrees:Double in stride(from: 0, to: 359, by: notchStep) {

I get this error:

Cannot invoke 'stride' with an argument list of type '(from: Int, to: Int, by: Int)'. What type of value can I pass to by or how can I cast my Int to an appropriate type?

Body:
Try removing the :Double in your code, so it reads:

let notchStep: Int = 5

for degrees in stride(from: 0, to: 359, by: notchStep) {
    // do something
}

Looking at the method signature, I think mixing Ints and Doubles is generating the issue.


问:
Why does official prefer concantane than hstack/vstack in Numpy?
I find that the latest documentation about hstack/vstack note that "you should prefer np.concatenate or np.stack".

But I think their readability is better than concatenate(a, 0) or concatenate(a, 1)

答:
All 3 'stack' functions use concatenate (as does np.append and column_stack).  It's instructive to look at their code.  np.source(np.hstack) for example.

What they all do is massage the dimensions of the input arrays, making sure they are are 1d or 2d etc, and then call concatenate with the appropriate axis.  So in the long run it's a good idea to know how to use concatenate without the 'crutch' of the others.

But people will continue to use hstack and vstack where convenient.  dstack and column_stack are less common.  np.append is frequently misused and should be banished.

I think this 'preferred' note was added when np.stack was added.  np.stack also uses concatenate, but in a somewhat more sophisticated way.  It inserts a new axis (with expand_dims).  I view it as a generalization of np.array.  When given a list of matching arrays, np.array joins them on a new initial axis.  np.stack does the same thing as a default, but lets us specify a different 'new' axis for concatenation.

I should qualify my answer.  It is not official.  Rather I'm making an educated guess based on knowledge of the code.


问:
How to config ftps user for wordpress on linux centos 6.9 port 22 ftps(ssl)
my wordpress directory /var/www/html/web/wordpress

I can not install plugin&theme wordpress.

答:
```<code>define( 'FS_METHOD', 'direct' );
</code>```

<p>add this in your wp-config.php file and check </p>

Body:
define( 'FS_METHOD', 'direct' );

add this in your wp-config.php file and check


问:
Contravariant Interfaces referring to their own types
I have the following pathfinding code:

```<code>public interface INode
{
    List<INode> GetNeighbours();
    float GetMovementCost(INode other);
}

public static class Pathfinder
{
    public static List<INode> FindPath(INode origin, INode target)
    {
        var path = new List<INode>();
        var cameFrom = new Dictionary<INode, INode>();
        var costToNode = new Dictionary<INode, float>();
        var frontier = new PriorityQueue<INode>();
        Dictionary<INode, float> costSoFar = new Dictionary<INode, float>();

        frontier.Enqueue(origin, 0);
        costSoFar[frontier[0].Element] = 0;

        while (frontier.Count > 0)
        {
            INode current = frontier.Dequeue();
            foreach (var neighbour in current.GetNeighbours())
            {
                float newCost = costSoFar[current] +
                                current.GetMovementCost(neighbour);
                if (!costSoFar.ContainsKey(neighbour) || newCost < costSoFar[neighbour])
                {
                    costSoFar[neighbour] = newCost;
                    frontier.Enqueue(neighbour, newCost);
                    cameFrom[neighbour] = current;
                }
            }
            if (current == target)
            {
                break;
            }
        }
        //build path
        INode nn = target;
        while (nn != origin)
        {
            path.Add(nn);
            nn = cameFrom[nn];
        }
        path.Reverse();
        return path;

    }

    public struct PriorityElement<T>
    {
        public T Element;
        public float Priority;

        public PriorityElement(T element, float priority)
        {
            if (priority < 0) throw new Exception("Priorities must be non-negative");
            Element = element;
            Priority = priority;
        }
    }

    public class PriorityQueue<T> : List<PriorityElement<T>>
    {
        public void Enqueue(T element, float priority)
        {
            if (this.Count == 0)
            {
                this.Insert(0, new PriorityElement<T>(element, priority));
                return;
            }
            if (priority > this.Last().Priority)
            {
                this.Add(new PriorityElement<T>(element, priority));
                return;
            }
            var firstLowerThan = this.First(p => priority <= p.Priority);
            this.Insert(IndexOf(firstLowerThan), new PriorityElement<T>(element, priority));
        }

        public T Dequeue()
        {
            if (this.Count == 0)
            {
                throw new Exception("Cannot dequeue, queue is empty");
            }
            var ret = this.First();
            this.Remove(ret);
            return ret.Element;
        }
    }
}
</code>```

This works fine, but the really annoying thing is it returns a INode and not something that impliments INode, so I have to cast it back up and its not very type safe.

I am trying to implement the generic version of this code, something along the lines of:

```<code>public static List<Node> FindPath<Node>(Node origin, Node target) where Node : INode<Node>
</code>```

However this obviously doesn't work as List<INode> GetNeighbours(); cannot return a more derived type without using covariance and contravariance. Implementing contravariance is tricky here.

Can someone please help me redefine my INode interface such that the above signature will work? The main issue is that GetNeighbours() needs to return a list of a move derived type of INode.

Something along the lines of:

```<code>public interface INode
{
    List<T> GetNeighbours<T>() where T : INode;
    float GetMovementCost(INode other);
}
</code>```

答:
Your FindPath should take arguments of type T where T : class, INode, rather than explicitly taking INode arguments. Then, inside the method, you should refer to T rather than INode. For example, you could write:

```<code>public static List<T> FindPath<T>(T origin, T target) where T : class, INode
{
    var path = new List<T>();
    var cameFrom = new Dictionary<T, T>();
    var costToNode = new Dictionary<T, float>();
    var frontier = new PriorityQueue<T>();
    Dictionary<T, float> costSoFar = new Dictionary<T, float>();

    frontier.Enqueue(origin, 0);
    costSoFar[frontier[0].Element] = 0;

    while (frontier.Count > 0)
    {
        T current = frontier.Dequeue();
        foreach (var neighbour in current.GetNeighbours<T>())
        {
            float newCost = costSoFar[current] +
                            current.GetMovementCost(neighbour);
            if (!costSoFar.ContainsKey(neighbour) || newCost < costSoFar[neighbour])
            {
                costSoFar[neighbour] = newCost;
                frontier.Enqueue(neighbour, newCost);
                cameFrom[neighbour] = current;
            }
        }
        if (current == target)
        {
            break;
        }
    }
    //build path
    T nn = target;
    while (nn != origin)
    {
        path.Add(nn);
        nn = cameFrom[nn];
    }
    path.Reverse();
    return path;
}
</code>```

And then simply change your interface to:

```<code>public interface INode
{
    List<T> GetNeighbours<T>() where T : INode;
    float GetMovementCost(INode other);
}
</code>```

Body:
I have the following pathfinding code:

public interface INode
{
    List<INode> GetNeighbours();
    float GetMovementCost(INode other);
}

public static class Pathfinder
{
    public static List<INode> FindPath(INode origin, INode target)
    {
        var path = new List<INode>();
        var cameFrom = new Dictionary<INode, INode>();
        var costToNode = new Dictionary<INode, float>();
        var frontier = new PriorityQueue<INode>();
        Dictionary<INode, float> costSoFar = new Dictionary<INode, float>();

        frontier.Enqueue(origin, 0);
        costSoFar[frontier[0].Element] = 0;

        while (frontier.Count > 0)
        {
            INode current = frontier.Dequeue();
            foreach (var neighbour in current.GetNeighbours())
            {
                float newCost = costSoFar[current] +
                                current.GetMovementCost(neighbour);
                if (!costSoFar.ContainsKey(neighbour) || newCost < costSoFar[neighbour])
                {
                    costSoFar[neighbour] = newCost;
                    frontier.Enqueue(neighbour, newCost);
                    cameFrom[neighbour] = current;
                }
            }
            if (current == target)
            {
                break;
            }
        }
        //build path
        INode nn = target;
        while (nn != origin)
        {
            path.Add(nn);
            nn = cameFrom[nn];
        }
        path.Reverse();
        return path;

    }

    public struct PriorityElement<T>
    {
        public T Element;
        public float Priority;

        public PriorityElement(T element, float priority)
        {
            if (priority < 0) throw new Exception("Priorities must be non-negative");
            Element = element;
            Priority = priority;
        }
    }

    public class PriorityQueue<T> : List<PriorityElement<T>>
    {
        public void Enqueue(T element, float priority)
        {
            if (this.Count == 0)
            {
                this.Insert(0, new PriorityElement<T>(element, priority));
                return;
            }
            if (priority > this.Last().Priority)
            {
                this.Add(new PriorityElement<T>(element, priority));
                return;
            }
            var firstLowerThan = this.First(p => priority <= p.Priority);
            this.Insert(IndexOf(firstLowerThan), new PriorityElement<T>(element, priority));
        }

        public T Dequeue()
        {
            if (this.Count == 0)
            {
                throw new Exception("Cannot dequeue, queue is empty");
            }
            var ret = this.First();
            this.Remove(ret);
            return ret.Element;
        }
    }
}

This works fine, but the really annoying thing is it returns a INode and not something that impliments INode, so I have to cast it back up and its not very type safe.

I am trying to implement the generic version of this code, something along the lines of:

public static List<Node> FindPath<Node>(Node origin, Node target) where Node : INode<Node>

However this obviously doesn't work as List<INode> GetNeighbours(); cannot return a more derived type without using covariance and contravariance. Implementing contravariance is tricky here.

Can someone please help me redefine my INode interface such that the above signature will work? The main issue is that GetNeighbours() needs to return a list of a move derived type of INode.

Something along the lines of:

public interface INode
{
    List<T> GetNeighbours<T>() where T : INode;
    float GetMovementCost(INode other);
}

Body:
Your FindPath should take arguments of type T where T : class, INode, rather than explicitly taking INode arguments. Then, inside the method, you should refer to T rather than INode. For example, you could write:

public static List<T> FindPath<T>(T origin, T target) where T : class, INode
{
    var path = new List<T>();
    var cameFrom = new Dictionary<T, T>();
    var costToNode = new Dictionary<T, float>();
    var frontier = new PriorityQueue<T>();
    Dictionary<T, float> costSoFar = new Dictionary<T, float>();

    frontier.Enqueue(origin, 0);
    costSoFar[frontier[0].Element] = 0;

    while (frontier.Count > 0)
    {
        T current = frontier.Dequeue();
        foreach (var neighbour in current.GetNeighbours<T>())
        {
            float newCost = costSoFar[current] +
                            current.GetMovementCost(neighbour);
            if (!costSoFar.ContainsKey(neighbour) || newCost < costSoFar[neighbour])
            {
                costSoFar[neighbour] = newCost;
                frontier.Enqueue(neighbour, newCost);
                cameFrom[neighbour] = current;
            }
        }
        if (current == target)
        {
            break;
        }
    }
    //build path
    T nn = target;
    while (nn != origin)
    {
        path.Add(nn);
        nn = cameFrom[nn];
    }
    path.Reverse();
    return path;
}

And then simply change your interface to:

public interface INode
{
    List<T> GetNeighbours<T>() where T : INode;
    float GetMovementCost(INode other);
}


问:
how do i unhide spaces between words in a hangman game?
I am making a hangman game, but there's something i can't figure out.

I am able to hide the letters using

```<code>guessed = "_"*len(guess)
</code>```

but it also hides the spaces. for example if my word is 'the avengers' it will hide 12 characters instead of 11. how do unhide/leave the spaces alone? this is what i have so far:

```<code>def getHiddenWord():
    guess = getRandomWord().lower()
    guessed = "_"*len(guess)
    if "_" in guessed is " ":
        print(guessed.replace("_", " "))
    else:
        print("The Word is:", guessed)
    return guessed
</code>```

答:
Use re.sub

```<code>guessed = re.sub(r'\S', '_', guess)
</code>```

\S would match any non-space character. So the above re.sub function would replace any non-space character from the input string with _.

Example:

```<code>>>> import re
>>> s = 'the avengers'
>>> re.sub(r'\S', '_', s)
'___ ________'
>>>
</code>```

or

```<code>>>> ''.join(['_' if not i.isspace() else i for i in s])
'___ ________'
>>>
</code>```

Body:
I am making a hangman game, but there's something i can't figure out.

I am able to hide the letters using

guessed = "_"*len(guess)

but it also hides the spaces. for example if my word is 'the avengers' it will hide 12 characters instead of 11. how do unhide/leave the spaces alone? this is what i have so far:

def getHiddenWord():
    guess = getRandomWord().lower()
    guessed = "_"*len(guess)
    if "_" in guessed is " ":
        print(guessed.replace("_", " "))
    else:
        print("The Word is:", guessed)
    return guessed

Body:
Use re.sub

guessed = re.sub(r'\S', '_', guess)

\S would match any non-space character. So the above re.sub function would replace any non-space character from the input string with _.

Example:

>>> import re
>>> s = 'the avengers'
>>> re.sub(r'\S', '_', s)
'___ ________'
>>>

or

>>> ''.join(['_' if not i.isspace() else i for i in s])
'___ ________'
>>>


问:
Why is that __init__ function of python doesn't have a return statement even though its a function
This may be a silly question but i am curious to know the answer.
As per official documentation, __init__ doesn't need return statement. Any particular reason why is it that way.

```<code>>>> class Complex:
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...
>>> x = Complex(3.0, -4.5)

>>> x.r, x.i
(3.0, -4.5)
</code>```

答:
__init__ is called when you create a new instance of a class.

It's main use is initializing the instance variables, and it can be called only with an instance - so you can't call it before you create an instance anyways (what triggers it automatically).

For these reasons, __init__s have no reason to be able to return any value - it's simply not their use case.

Body:
This may be a silly question but i am curious to know the answer.
As per official documentation, __init__ doesn't need return statement. Any particular reason why is it that way.

>>> class Complex:
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...
>>> x = Complex(3.0, -4.5)

>>> x.r, x.i
(3.0, -4.5)


答:
__init__() is not a normal function. It is a special method Python uses to customize an instance of a class. It is part of Python's data model:

Called after the instance has been created (by __new__()), but before it is returned to the caller[...].

As you can see from above, when you create a new instance of a class, Python first calls __new_() - which is also a special method - to create a new instance of the class. Then __init__() is called to customize the new instance.

It wouldn't make sense to return anything from __init__(), since the class instance is already created. In fact, Python goes as far as raising an error to prevent this:

```<code>>>> class A:
...     def __init__(self):
...         return 'foo'
...
>>> A()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() should return None, not 'str'
>>>
</code>```

If you want to know what exactly is going on behind the scenes, @eryksun provides a nice explanation:

To completely explain this story, you have to step back to the metaclass __call__ method. In particular the default type.__call__ in CPython calls __new__ and __init__ via their C slot functions, and it's slot_tp_init (defined in Objects/typeobject.c) that enforces the return value to be None. If you use a custom metaclass that overrides type.__call__, it can manually call the __new__ and __init__ methods of the class with no restriction on what __init__ can return -- as silly as that would be.

Title: Why is that __init__ function of python doesn't have a return statement even though its a function

Body:
__init__() is not a normal function. It is a special method Python uses to customize an instance of a class. It is part of Python's data model:

Called after the instance has been created (by __new__()), but before it is returned to the caller[...].

As you can see from above, when you create a new instance of a class, Python first calls __new_() - which is also a special method - to create a new instance of the class. Then __init__() is called to customize the new instance.

It wouldn't make sense to return anything from __init__(), since the class instance is already created. In fact, Python goes as far as raising an error to prevent this:

>>> class A:
...     def __init__(self):
...         return 'foo'
...
>>> A()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() should return None, not 'str'
>>>

If you want to know what exactly is going on behind the scenes, @eryksun provides a nice explanation:

To completely explain this story, you have to step back to the metaclass __call__ method. In particular the default type.__call__ in CPython calls __new__ and __init__ via their C slot functions, and it's slot_tp_init (defined in Objects/typeobject.c) that enforces the return value to be None. If you use a custom metaclass that overrides type.__call__, it can manually call the __new__ and __init__ methods of the class with no restriction on what __init__ can return -- as silly as that would be.


问:
chrome extension - Fill the web form from the data from Excel
Is it possible to fill the web form by bringing the data from excel in chrome extension?

i have an url with some numbers, example http://www.desipearl.com/tracker/544258/371/ASD-Collection-736151299754834/57/smp/

the number 544258 will keep an increased by one number, according the number change the article get changed

The above mentioned url is available in excel database,

i want to post the first url number 544258 then after some interval i want to post 544259 , this keeps on going on constant interval

Can we achieve the above mentioned function by chrome extension

答:
It might be easier to do this via python. I'd use the openpyxl module from python which is documented here. Then I'd go through each number in the spreadsheet and use the requests module to get the page using a GET request as documented here.

With a chrome extension you could do this. The general steps would be to load the excel file. Then process it to get a list of numbers and then make a GET request using those numbers from chrome.


问:
How to manage URLs of a website with different articles?
I have made a sample website with some articles. The way I want the URLs to be is like:

www.example.com/news/first-article

however, for now, I have just placed the required first-article.html file in the directory by first creating the directory: home/news/.

Thing to be noted is that I do have all the contents of the article (such as heading, body, date, etc.) saved in a Database, so I feel like there might be a better way such as URI matcher present in Android, instead of just creating file in each directory.

The motive here is to identify the category of the article (here 'news') and the name of the article (here 'first-article') and then to retrieve details from DB and generate the required page dynamically. Is this possible in PHP?

[A sample code snippet could would help]

答:
I would recommend using a single PHP page to read from the database, and display the content based on a $_GET parameter:

```<code>include('database_connection.php'); // Saved as $mysqli

if (isset($_GET['id'])) {
    $news_id = $_GET['id'];

    // Grab the news information given the ID (in MySQLi)
    $stmt = $mysqli->prepare("SELECT id, news, date FROM news WHERE id = ?");
    $stmt->bind_param('i', $news_id);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($id, $news, $date);
    $stmt->fetch();

    // Output results
    echo "<h1>" . $date . "</h1>";
    echo "<p"> . $news . "</p>";

    $stmt->close();
}
</code>```

This will only require one PHP page (news.php), which loads various articles with news.php?id=1, news.php?id=2, etc.

Then you could use .htaccess to 'morph' the news pages into 'pretty' pages with something like this following:

```<code>Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) news.php?id=$1&$2
</code>```

When you link using something like:

```<code>$article_title = 'First Article';
echo '<a href="' . str_replace(" ", "-", $article_title).'">Read More</a>';
</code>```

Which will 'prettify' your page URLs, based on the script filenames.

Hope this helps! :)

Body:
I would recommend using a single PHP page to read from the database, and display the content based on a $_GET parameter:

include('database_connection.php'); // Saved as $mysqli

if (isset($_GET['id'])) {
    $news_id = $_GET['id'];

    // Grab the news information given the ID (in MySQLi)
    $stmt = $mysqli->prepare("SELECT id, news, date FROM news WHERE id = ?");
    $stmt->bind_param('i', $news_id);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($id, $news, $date);
    $stmt->fetch();

    // Output results
    echo "<h1>" . $date . "</h1>";
    echo "<p"> . $news . "</p>";

    $stmt->close();
}

This will only require one PHP page (news.php), which loads various articles with news.php?id=1, news.php?id=2, etc.

Then you could use .htaccess to 'morph' the news pages into 'pretty' pages with something like this following:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) news.php?id=$1&$2

When you link using something like:

$article_title = 'First Article';
echo '<a href="' . str_replace(" ", "-", $article_title).'">Read More</a>';

Which will 'prettify' your page URLs, based on the script filenames.

Hope this helps! :)


问:
laravel 5.4 change authentication users table name
I'm currently using the laarvel5.4 authentication in my application; and I want to change the users table name while keeping its role as it is in the authentication logic, all I need is just to change the name.

It seems that Laravel changer the Auth file and code structure in the latest version, so auth.php doesn't really look as in the previous versions of laravel.

I have done the following so far, but it's still not working gy giving me an error saying that the table users doesn't exist:

1- I have changed the migration's up() and down() functions to create and drop staff table instead of users and run the migration successfully.

2- I have changed the validator() function in RegisterController.

3- I have changed all the 'users' to 'staff' in config/auth.php, as shown in the code:

```<code> return [

'defaults' => [
    'guard' => 'web',
    'passwords' => 'staff',
],

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'staff',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'staff',
    ],
],

'providers' => [
    'staff' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    // 'staff' => [
    //     'driver' => 'database',
    //     'table' => 'staff',
    // ],
],
'passwords' => [
    'staff' => [
        'provider' => 'staff',
        'table' => 'password_resets',
        'expire' => 60,
    ],
],
</code>```

];

However, in app/User.php I don't know what to change since in the previous versions there used to be a table variable which u need to change its value from users to the new table name but in my class I don't have such thing

```<code><?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use Notifiable;
    protected $fillable = [
        'name', 'email', 'password',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];
}
</code>```

答:
You can change the table name in the migration file and then change the table name variable in the User.php model.

Example:

```<code>class Flight extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'my_flights';
}
</code>```

https://laravel.com/docs/5.4/eloquent#eloquent-model-conventions

Body:
I'm currently using the laarvel5.4 authentication in my application; and I want to change the users table name while keeping its role as it is in the authentication logic, all I need is just to change the name.

It seems that Laravel changer the Auth file and code structure in the latest version, so auth.php doesn't really look as in the previous versions of laravel.

I have done the following so far, but it's still not working gy giving me an error saying that the table users doesn't exist:

1- I have changed the migration's up() and down() functions to create and drop staff table instead of users and run the migration successfully.

2- I have changed the validator() function in RegisterController.

3- I have changed all the 'users' to 'staff' in config/auth.php, as shown in the code:

 return [

'defaults' => [
    'guard' => 'web',
    'passwords' => 'staff',
],

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'staff',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'staff',
    ],
],

'providers' => [
    'staff' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    // 'staff' => [
    //     'driver' => 'database',
    //     'table' => 'staff',
    // ],
],
'passwords' => [
    'staff' => [
        'provider' => 'staff',
        'table' => 'password_resets',
        'expire' => 60,
    ],
],

];

However, in app/User.php I don't know what to change since in the previous versions there used to be a table variable which u need to change its value from users to the new table name but in my class I don't have such thing

<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use Notifiable;
    protected $fillable = [
        'name', 'email', 'password',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Body:
You can change the table name in the migration file and then change the table name variable in the User.php model.

Example:

class Flight extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'my_flights';
}

https://laravel.com/docs/5.4/eloquent#eloquent-model-conventions


问:
OracleDataSource vs. Oracle UCP PoolDataSource
I was researching some JDBC Oracle Connection Pooling items and came across a new(er) Oracle Pool implementation called Universal Connection Pool (UCP).  Now this uses a new class, PoolDataSource, for connection pooling rather then the OracleDataSource [with the cache option enabled].  I am debating whether to switch to this new implementation but can't find any good documentation of what (if any) fixes/upgrades this would buy me.  Anyone have an experience with both?  Pluses/Minuses?  Thanks.</p>

答: I did an extensive evaluation of UCP and decided to NOT use UCP - please have a look at this post for details.</p>


问:
dynamically add suggestion chips on Api.ai for Actions on google
I want to add suggestions for the user in my Google Assistant Bot. I am using API.ai for bot development and using fulfilment, I am communicating with my backend for data.

I am not able to send suggestions using suggestions chips to my bot.

 I have followed as answered here Webhook response with "suggestion chips"
as well as the document at https://developers.google.com/actions/assistant/responses#json.
But still, I only see simple text response at my bot on device as well as on simulator.

I also checked at https://discuss.api.ai/t/google-assistant-rich-message-responses/5134/19. But didn't find any way to switch to V1 or V2. The sample format also didn't work!

Here are my 2 JSONs:

at API.ai

```<code>"fulfillment": {
  "speech": "want to proceed further?",
  "messages": [
    {
      "type": 0,
      "speech": "want to proceed further?"
    }
  ],
  "data": {
    "google": {
      "conversationToken": "[\"AS-PER-JSON-FROM-SIMULATOR\"]",
      "expectedInputs": [
        {
          "inputPrompt": {
            "richInitialPrompt": {
              "items": [
                {
                  "simpleResponse": {
                    "textToSpeech": "want to proceed further?",
                    "displayText": "want to proceed further?"
                  }
                }
              ],
              "suggestions": [
                {
                  "title": "Yes"
                },
                {
                  "title": "No"
                }
              ]
            }
          }
        }
      ]
    }
  }
},
</code>```

at action on Google

```<code>"expectUserResponse": true,
    "expectedInputs": [
        {
            "inputPrompt": {
                "richInitialPrompt": {
                    "items": [
                        {
                            "simpleResponse": {
                                "textToSpeech": "want to proceed?"
                            }
                        }
                    ]
                },
                "noMatchPrompts": [],
                "noInputPrompts": []
            },
            "possibleIntents": [
                {
                    "intent": "assistant.intent.action.TEXT"
                }
            ],
            "speechBiasingHints": [
                "$subject",
                "$answer"
            ]
        }
    ]
</code>```

python server

```<code>return = '{"speech":"want to proceed?", "data": {"google":{"expectedInputs":[{"inputPrompt":{"richInitialPrompt":{"items":[{"simpleResponse":{"textToSpeech":"want to proceed?","displayText":"want to proceed?"}}],"suggestions":[{"title":"Yes"},{"title":"No"}]}}}]}}}'
</code>```

答:
Add 'expectUserResponse' into data -> google

```<code>'expectUserResponse': true,
'isSsml': false,
</code>```

Body:
I want to add suggestions for the user in my Google Assistant Bot. I am using API.ai for bot development and using fulfilment, I am communicating with my backend for data.

I am not able to send suggestions using suggestions chips to my bot.

 I have followed as answered here Webhook response with "suggestion chips"
as well as the document at https://developers.google.com/actions/assistant/responses#json.
But still, I only see simple text response at my bot on device as well as on simulator.

I also checked at https://discuss.api.ai/t/google-assistant-rich-message-responses/5134/19. But didn't find any way to switch to V1 or V2. The sample format also didn't work!

Here are my 2 JSONs:

at API.ai

"fulfillment": {
  "speech": "want to proceed further?",
  "messages": [
    {
      "type": 0,
      "speech": "want to proceed further?"
    }
  ],
  "data": {
    "google": {
      "conversationToken": "[\"AS-PER-JSON-FROM-SIMULATOR\"]",
      "expectedInputs": [
        {
          "inputPrompt": {
            "richInitialPrompt": {
              "items": [
                {
                  "simpleResponse": {
                    "textToSpeech": "want to proceed further?",
                    "displayText": "want to proceed further?"
                  }
                }
              ],
              "suggestions": [
                {
                  "title": "Yes"
                },
                {
                  "title": "No"
                }
              ]
            }
          }
        }
      ]
    }
  }
},

at action on Google

"expectUserResponse": true,
    "expectedInputs": [
        {
            "inputPrompt": {
                "richInitialPrompt": {
                    "items": [
                        {
                            "simpleResponse": {
                                "textToSpeech": "want to proceed?"
                            }
                        }
                    ]
                },
                "noMatchPrompts": [],
                "noInputPrompts": []
            },
            "possibleIntents": [
                {
                    "intent": "assistant.intent.action.TEXT"
                }
            ],
            "speechBiasingHints": [
                "$subject",
                "$answer"
            ]
        }
    ]

python server

return = '{"speech":"want to proceed?", "data": {"google":{"expectedInputs":[{"inputPrompt":{"richInitialPrompt":{"items":[{"simpleResponse":{"textToSpeech":"want to proceed?","displayText":"want to proceed?"}}],"suggestions":[{"title":"Yes"},{"title":"No"}]}}}]}}}'

Body:
Add 'expectUserResponse' into data -> google

'expectUserResponse': true,
'isSsml': false,


问:
Child position absolute parent relative doesn't work
I’m trying to implement something like a web page navbar. I have code like this:

nav {
  position: relative;
  display: inline-block;
}

.nav-right {
  display: inline-block;
  position: absolute;
  right: 0px;
  list-style: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <h2>My First Website</h2>
  <ul class="nav-right">
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav></code>```

I have known that an absolute element is positioned to its first positioned (not static) ancestor element. I have set position property of element nav as absolute, but it looks like the
 run out of the  range.  In other word  i'm confused about why nav'height  is  less than  ul's   Thanks a  lot.

答:
try top : 0px; also with that.If the top is auto then it defaults to their  position: static values.Check this for more details:position: absolute without setting top/left/bottom/right?

Also display:block for the nav for the nav to take full sapce

nav {
  position: relative;
  display: block;
}

.nav-right {
  display: inline-block;
  position: absolute;
  top:0px;
  right:0px;
  list-style: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
      <h2>My First Website</h2>
      <ul class="nav-right">
        <li>Home</li>
        <li>About</li>
        <li>Contact</li>
      </ul>
    </nav></code>```

Body:
I’m trying to implement something like a web page navbar. I have code like this:

nav {
  position: relative;
  display: inline-block;
}

.nav-right {
  display: inline-block;
  position: absolute;
  right: 0px;
  list-style: none;
}

My First Website

Home

About

Contact

I have known that an absolute element is positioned to its first positioned (not static) ancestor element. I have set position property of element nav as absolute, but it looks like the
 run out of the  range.  In other word  i'm confused about why nav'height  is  less than  ul's   Thanks a  lot.

Body:
try top : 0px; also with that.If the top is auto then it defaults to their  position: static values.Check this for more details:position: absolute without setting top/left/bottom/right?

Also display:block for the nav for the nav to take full sapce

nav {
  position: relative;
  display: block;
}

.nav-right {
  display: inline-block;
  position: absolute;
  top:0px;
  right:0px;
  list-style: none;
}

<nav>
      <h2>My First Website</h2>
      <ul class="nav-right">
        <li>Home</li>
        <li>About</li>
        <li>Contact</li>
      </ul>
    </nav>


问:
What is the `g` in angular selectors for?
Some ngx-charts components have a g in the selector like this:

```<code>selector: 'g[ngx-charts-line]'
</code>```

What is the g for?

答: ngx-charts uses SVGs (Scalable Vector Graphics) to create it's charts and components. As a result, the g in the selector targets SVG <g> elements which are used to group other SVG elements. This selector specifically targets <g> elements with the ngx-charts-line attribute.

Body:
Some ngx-charts components have a g in the selector like this:

selector: 'g[ngx-charts-line]'

What is the g for?


问:
General ASP.NET Session questions
I have some questions in regards to Session in ASP.NET

As we need to manually create cookie, does Session automatically created by the application when the application starts?

Is it just only one Session object to store all users'information? Or there is new Session object for every user?

There is Timeout attribute for Session, can I use this attribute instead of setting expiry time for cookie?

答:
Question 1
No need to create cookie your own, session id created automatically when you access the url

Question 2
You can create multiple session object to store different data into it and there is new session object for each user because server will auto generate session id for each user access to url

Question 3
Timeout attribute is just to provide an expiry time for the session so the data will not retain in session after a period of time

Title: General ASP.NET Session questions