问:
.htaccess - DirectoryIndex appears to have no effect
I'm trying to adapt the .htaccess file in the root of my CodeIgniter installation so I don't have to include index.php in all the URLs leading to my controllers.

This is the content of my .htaccess file:

```<code><IfModule authz_core_module>
    Require all granted
</IfModule>
<IfModule !authz_core_module>
    Deny from all
</IfModule>

DirectoryIndex login.php

RewriteEngine On
RewriteCond $1 !^(index\.php)
RewriteCond $(REQUEST_FILENAME) !-f
RewriteCond $(REQUEST_FILENAME) !-d
RewriteRule ^(.*)$ ./index.php/$1
</code>```

As you can see, it's the default .htaccess file with some rewrite rules for mod_rewrite and a DirectoryIndex directive appended to it. Mod_rewrite is enabled (I've checked this using apachectl -M).

Now, I'm running Apache 2.4.18 on Ubuntu 16.04 LTS and I am using CodeIgniter 3.1.6. The problem is that when I type in no URL I get redirected to CodeIgniters index.php instead of my wanted login.php. I'd rather get the DirectoryIndex directive working instead of transferring the contents of login.php into index.php for obvious reasons. My mod_rewrite rules are meant to route URLs to existing files "through" index.php without having to include index.php in their URL. This way, my URLs are cleaner but I can still use CodeIgniter's facilities.

My master Apache configuration obviously allows me to use .htaccess files (since CodeIgniter needs this too) and the URL rewrite directives work just fine. Why does the DirectoryIndex not seem to do anything no matter where I place it inside the file?

答:
Check out if you have AllowOverride instruction set to All -- it controls if .htaccess file has any power.

There are the answers on how to set it: How to Set AllowOverride all

Body:
I'm trying to adapt the .htaccess file in the root of my CodeIgniter installation so I don't have to include index.php in all the URLs leading to my controllers.

This is the content of my .htaccess file:

<IfModule authz_core_module>
    Require all granted
</IfModule>
<IfModule !authz_core_module>
    Deny from all
</IfModule>

DirectoryIndex login.php

RewriteEngine On
RewriteCond $1 !^(index\.php)
RewriteCond $(REQUEST_FILENAME) !-f
RewriteCond $(REQUEST_FILENAME) !-d
RewriteRule ^(.*)$ ./index.php/$1

As you can see, it's the default .htaccess file with some rewrite rules for mod_rewrite and a DirectoryIndex directive appended to it. Mod_rewrite is enabled (I've checked this using apachectl -M).

Now, I'm running Apache 2.4.18 on Ubuntu 16.04 LTS and I am using CodeIgniter 3.1.6. The problem is that when I type in no URL I get redirected to CodeIgniters index.php instead of my wanted login.php. I'd rather get the DirectoryIndex directive working instead of transferring the contents of login.php into index.php for obvious reasons. My mod_rewrite rules are meant to route URLs to existing files "through" index.php without having to include index.php in their URL. This way, my URLs are cleaner but I can still use CodeIgniter's facilities.

My master Apache configuration obviously allows me to use .htaccess files (since CodeIgniter needs this too) and the URL rewrite directives work just fine. Why does the DirectoryIndex not seem to do anything no matter where I place it inside the file?


来源: stackexchange

问:
Forked Children Initialization Sempahore Blocking
My goal is to synchronize forked processes by a common int value.

I need to fork a number of children but also semaphore block them until all the children have been forked.

This variable (init_num) must first become equal to the number of processes I have and then the processes can continue with their functions.

My code :

    pid_t pid;
    key_t key;
    sem_t *sem;
    sem_t *sem2;
    int shmid;

    int main(int argc , char* argv[])
    {
        if (argc < 2){
            printf("Incorrect number of arguments given!\n");
            exit(-1);
        }

        int num_strings = argc - 2;
        int reps = atoi (argv[1]);

        //  SHARED MEMORY  //

        key = 9876;

        shmid = shmget( key , sizeof(int) , 0644 | IPC_CREAT);
        if ( shmid < 0 ){
            perror("shmget\n");
            exit(-1);
        }

        // SHARED MEMORY INITIATED //

        int *init_num;
        init_num = shmat ( shmid , NULL , 0);
        *init_num = 0;

        // SEMAPHORES TIME //

        sem = sem_open("TheSem", O_CREAT | O_EXCL , 0644 , 1);

        sem2 = sem_open("TheSem2", O_CREAT | O_EXCL , 0644 , 0);

        // SEMAPHORE DONE //

        int i;
        // FORKS //
        for (i=0; i<num_strings; i++){
            pid = fork();

            if (pid < 0) {
                        printf ("Fork error.\n");

                sem_unlink("TheSem");
                sem_close(sem);

                sem_unlink("TheSem2");
                sem_close(sem2);
                }
                else if ( pid == 0)
                        break;
            }

        // FATHER //
        if ( pid !=0 && pid!=-1 ){
            int status;
                    while(pid = waitpid (-1,NULL,0)){
                            if(errno == ECHILD)
                                    break;
                    }
            shmdt (init_num);
            shmctl (shmid, IPC_RMID, 0);

            sem_unlink("TheSem");
            sem_close(sem);

            sem_unlink("TheSem2");
            sem_close(sem);
            }

        int n;
        //CHILDREN //
        if( pid == 0){
            sem_wait(sem);
                init();
                *init_num++;
            sem_post(sem);

            if (*init_num < num_strings ){
                sem_wait(sem2);
            }else{
                for(n=0 ; n <=num_strings-1; n++){
                    sem_post(sem2);
                }
            }

            // DISPLAY //
            for(n=0; n < reps; n++){
                sem_wait(sem);
                    display(argv[2+i]);
                sem_post(sem);
            }

        }
    return(0);
    }
```

<p>And <code>*init_num</code> is in shared memory space.</p>

<p>The problem is after all of the processes have done <code>init()</code> and <code>*init_num</code> should be equal to <code>processes</code> my program deadlocks and stops right there.</p>

<p>Output :</p>

```STARTING: pid 1268, tid 1157203712
STARTING: pid 1270, tid 1157203712
STARTING: pid 1269, tid 1157203712
STARTING: pid 1271, tid 1157203712
STARTING: pid 1272, tid 1157203712
STARTING: pid 1273, tid 1157203712
STARTING: pid 1274, tid 1157203712
STARTING: pid 1275, tid 1157203712  // these are init()
```

答:
Enable warnings, and you will see

```<code>warning: expression result unused [-Wunused-value]
        *init_num++;
        ^~~~~~~~~~~
</code>```

which immediately shows your problem. The children do not increment the value: they increment the pointer. Technically it is UB, but realistically they all read 0. Change it to

```<code>        (*init_num)++;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My goal is to synchronize forked processes by a common int value.

I need to fork a number of children but also semaphore block them until all the children have been forked.

This variable (init_num) must first become equal to the number of processes I have and then the processes can continue with their functions.

My code :

    pid_t pid;
    key_t key;
    sem_t *sem;
    sem_t *sem2;
    int shmid;

    int main(int argc , char* argv[])
    {
        if (argc < 2){
            printf("Incorrect number of arguments given!\n");
            exit(-1);
        }

        int num_strings = argc - 2;
        int reps = atoi (argv[1]);

        //  SHARED MEMORY  //

        key = 9876;

        shmid = shmget( key , sizeof(int) , 0644 | IPC_CREAT);
        if ( shmid < 0 ){
            perror("shmget\n");
            exit(-1);
        }

        // SHARED MEMORY INITIATED //

        int *init_num;
        init_num = shmat ( shmid , NULL , 0);
        *init_num = 0;

        // SEMAPHORES TIME //

        sem = sem_open("TheSem", O_CREAT | O_EXCL , 0644 , 1);

        sem2 = sem_open("TheSem2", O_CREAT | O_EXCL , 0644 , 0);

        // SEMAPHORE DONE //

        int i;
        // FORKS //
        for (i=0; i<num_strings; i++){
            pid = fork();

            if (pid < 0) {
                        printf ("Fork error.\n");

                sem_unlink("TheSem");
                sem_close(sem);

                sem_unlink("TheSem2");
                sem_close(sem2);
                }
                else if ( pid == 0)
                        break;
            }

        // FATHER //
        if ( pid !=0 && pid!=-1 ){
            int status;
                    while(pid = waitpid (-1,NULL,0)){
                            if(errno == ECHILD)
                                    break;
                    }
            shmdt (init_num);
            shmctl (shmid, IPC_RMID, 0);

            sem_unlink("TheSem");
            sem_close(sem);

            sem_unlink("TheSem2");
            sem_close(sem);
            }

        int n;
        //CHILDREN //
        if( pid == 0){
            sem_wait(sem);
                init();
                *init_num++;
            sem_post(sem);

            if (*init_num < num_strings ){
                sem_wait(sem2);
            }else{
                for(n=0 ; n <=num_strings-1; n++){
                    sem_post(sem2);
                }
            }

            // DISPLAY //
            for(n=0; n < reps; n++){
                sem_wait(sem);
                    display(argv[2+i]);
                sem_post(sem);
            }

        }
    return(0);
    }

And *init_num is in shared memory space.

The problem is after all of the processes have done init() and *init_num should be equal to processes my program deadlocks and stops right there.

Output :

STARTING: pid 1268, tid 1157203712
STARTING: pid 1270, tid 1157203712
STARTING: pid 1269, tid 1157203712
STARTING: pid 1271, tid 1157203712
STARTING: pid 1272, tid 1157203712
STARTING: pid 1273, tid 1157203712
STARTING: pid 1274, tid 1157203712
STARTING: pid 1275, tid 1157203712  // these are init()

Body:
Enable warnings, and you will see

warning: expression result unused [-Wunused-value]
        *init_num++;
        ^~~~~~~~~~~

which immediately shows your problem. The children do not increment the value: they increment the pointer. Technically it is UB, but realistically they all read 0. Change it to

        (*init_num)++;

ContentLicense: CC BY-SA 3.0


问:
Using Google Cloud Platform for scheduled recurring API data pull that then loads the data to BigQuery
I need to setup a scheduled daily job that pulls data using a REST API call and then inserts that data into BigQuery.

I traditionally have done these types of tasks using Node.js running on Heroku. My current boss wants me to achieve this using the Google Cloud Platform.

What are some ways to achieve this using Google Cloud Platform?

答:
A few options on GCP:

Spin up a GCE instance and use a cron (a little old school, but will work).

Use Google App Engine and schedule your job(s) that way.

Unfortunately, Google Cloud Functions don't yet support schedulers. Otherwise, that would be perfect.


问:
Inheriting a T4 template from a custom base class, providing Visual Studio 2010 SDK is not installed
I have a system of T4 templates — executed at run-time, not at compile-time — which generate the skeletons of many classes in my app. All these templates reside in a generator tool which is used from time to time to pre-generate new classes into the destination app. The tool contains a configuration class whose properties parameterize the output of all T4 templates.

Originally the configuration class was a static class. However, as the class generator tool grows, it's better to make it non-static and rather make a new instance for each use. The problem is how to pass this instance to the instances of T4 templates. The natural way seems to be inheriting them from a common base which would be provisioned with the configuration class instance.

The problem is that the TextTransformation class, which would have been inherited by my custom T4 base class, is located in an assembly which (according to sources like this SO question) doesn't ship with Visual Studio 2010. Instead it's provided within the Visual Studio 2010 SDK.

The base class generated by VS2010, although itself having no ancestor, isn't partial so there's no way to 'inject' the custom ancestor via another partial declaration.

Thus the question is: Is there a way to inherit a run-time-executed T4 template from a custom base class without the need to install Visual Studio 2010 SDK?

Disclaimer: I'm not very familiar with T4, so I might be completely wrong about how to approach the problem. Hence any other architectural advice is welcome, although my aim isn't to create a super-architected generator — it's just a helper tool, which shall be simple and understandable to the occasional reader.

答:
The assembly containing the base class does actually ship with Visual Studio, but it is installed in the GAC with no reference assembly.
The Visual Studio SDK just contains the referencable version of the DLL.

Consequently if you're creating a new base class in code, you need the VS SDK to build that base class, but not to use it. At rutime, the version in the GAC will be picked up.

ContentLicense: CC BY-SA 2.5


问:
Can't align container to the top of page and center it horizontally
This is my code:

```<code><template>
  <main>
    <v-container grid-list-xs class="text-xs-center">
      <v-layout row>
        <v-flex xs2 v-for="n in 6" :key="n">
          <v-card tile class="pa-1" dark color="error">
            <v-card-text>
              Some mildly interesting thing #{{ n }}
            </v-card-text>
          </v-card>
        </v-flex>
      </v-layout>
      <v-layout row>
        <v-flex xs12 >
          <v-card tile class="pa-2" dark color="secondary">
            <v-card-text>
              Well, that's interesting too!
            </v-card-text>
          </v-card>
        </v-flex>
      </v-layout>
        <v-layout row>
          <v-flex xs2 v-for="n in 6" :key="n">
            <v-card tile class="pa-1" color="warning">
              <v-card-text>
                And something more here #{{ n }}.
              </v-card-text>
              </v-card>
            </v-flex>
          </v-layout>
        </v-layout>
      </v-container>
    </main>
</template>
</code>```

When  is in use, I get the view with all flex items vertically aligned to the top, which is my goal, but they're not aligned to the center horizontally, there's a gap on the right-hand side (where the question mark shows in the 1st picture).

When I remove  from the code and the <v-container> becomes the parent element, the items go to the center, horizontally and vertically (2nd picture).

Again, I need them v-aligned to the top and centered horizontally. How to achieve this?

<img src="https://i.stack.imgur.com/fVk3d.png" alt="Layout with  engaged.">
<img src="https://i.stack.imgur.com/NYB5S.png" alt="Layout without  section">

答: replace your main tag with a v-content tag. I had this same issue. If you are using Router wrap router-view in a v-content tag rather than a main tag. You can find examples in Vuetifys' docs Vuetify</p>

Body:
This is my code:

<template>

    <v-container grid-list-xs class="text-xs-center">
      <v-layout row>
        <v-flex xs2 v-for="n in 6" :key="n">
          <v-card tile class="pa-1" dark color="error">
            <v-card-text>
              Some mildly interesting thing #{{ n }}
            </v-card-text>
          </v-card>
        </v-flex>
      </v-layout>
      <v-layout row>
        <v-flex xs12 >
          <v-card tile class="pa-2" dark color="secondary">
            <v-card-text>
              Well, that's interesting too!
            </v-card-text>
          </v-card>
        </v-flex>
      </v-layout>
        <v-layout row>
          <v-flex xs2 v-for="n in 6" :key="n">
            <v-card tile class="pa-1" color="warning">
              <v-card-text>
                And something more here #{{ n }}.
              </v-card-text>
              </v-card>
            </v-flex>
          </v-layout>
        </v-layout>
      </v-container>

</template>

When  is in use, I get the view with all flex items vertically aligned to the top, which is my goal, but they're not aligned to the center horizontally, there's a gap on the right-hand side (where the question mark shows in the 1st picture).

When I remove  from the code and the <v-container> becomes the parent element, the items go to the center, horizontally and vertically (2nd picture).

Again, I need them v-aligned to the top and centered horizontally. How to achieve this?

<img src="https://i.stack.imgur.com/fVk3d.png" alt="Layout with  engaged.">
<img src="https://i.stack.imgur.com/NYB5S.png" alt="Layout without  section">


问:
Unable to call Object.keys in angularjs
I'm using a UI.Bootstrap accordion and I've defined my heading like so:

<accordion-group ng=repeat="(cname, stations) in byClient">
    <accordion-heading>
        {{ cname }}  {{ Object.keys(stations).length }} Stations
    </accordion-heading>
```

<p>When that displays the <code>Object.keys(stations).length</code> resolves to nothing.  If I put that same length call in my controller I get back the expected count.  Is there something preventing the method call from working in AngularJS?</p>

<p>The rest of the accordion that uses <code>stations</code> acts as expected, so I know that it's being populated properly.  The <code>byClient</code> data structure basically looks like so:</p>

<pre class="lang-js prettyprint-override"><code>{
    "Client Name" : {
        "Station Name": [
            {...},
            {...}
        ]
    }
 }
</code>```

答:
I think filters are the most AngularJS way of handling structures in template code:

```<code>angular.module('app.filters').filter('objectKeysLength', [function() {
    return function(items) {
        return Object.keys(items).length;
    };
}]);

angular.module('app.filters').filter('objectKeys', [function() {
    return function(item) {
        if (!item) return null;
        var keys = Object.keys(item);
        keys.sort();
        return keys;
    };
}]);
</code>```

Title: Unable to call Object.keys in angularjs

Body:
I'm using a UI.Bootstrap accordion and I've defined my heading like so:

<accordion-group ng=repeat="(cname, stations) in byClient">
    <accordion-heading>
        {{ cname }}  {{ Object.keys(stations).length }} Stations
    </accordion-heading>

When that displays the Object.keys(stations).length resolves to nothing.  If I put that same length call in my controller I get back the expected count.  Is there something preventing the method call from working in AngularJS?

The rest of the accordion that uses stations acts as expected, so I know that it's being populated properly.  The byClient data structure basically looks like so:

{
    "Client Name" : {
        "Station Name": [
            {...},
            {...}
        ]
    }
 }

Body:
I think filters are the most AngularJS way of handling structures in template code:

angular.module('app.filters').filter('objectKeysLength', [function() {
    return function(items) {
        return Object.keys(items).length;
    };
}]);

angular.module('app.filters').filter('objectKeys', [function() {
    return function(item) {
        if (!item) return null;
        var keys = Object.keys(item);
        keys.sort();
        return keys;
    };
}]);


问:
SQL Server linked server and Availability Group
I have a database within a SQL server 2008 server (Server A, with database A) that requires to communicate (both ways) to another database in a separate SQL server 2014 server (Server B, with database B).

Easy enough, but Server B is part of an AG group, with one secondary replica (Server C).  My question is:

Do I have to create a SQL script (sp_addlinkedserver) on ALL Servers (A, B and C), and the AG listener; or just some of them?  I assume I have to at least create "add linked server" scripts for A & B.

答:
You will need to create a linked server on all three servers otherwise, you will not have the linked server present when the AlwaysOn High Availabilty Group fails over.

On A to the listener for the AG
On B to A
On C to A


问:
Advanced DateDiff using MSExcel
I have an Excel spreadsheet listing job shifts... four columns that are important for our purposes:

Start Date

Start Time

End Date

End Time

Given this data, I need to abstract the number of hours for each shift that fall between 7am and 7pm.

A few things to keep in mind...
There is no theoretical limit to the length of a shift.  It could run anywhere from 1 hour to 3 days.

I'm open to solutions in C#, VB, PHP, or even an advanced Excel function... anything to get to the solution.

答:
VBA <s>, not taking much account of minutes. I do not know if you need minutes.</s>

```<code>Dim i As Integer
Dim ShiftRange As Range
Dim dteStart As Date
Dim dteEnd As Date
Dim HourCount As Long
Dim MinCount As Long

Set ShiftRange = Sheet1.UsedRange

For i = 2 To ShiftRange.Rows.Count
    HourCount = 0
    dteStart = CDate(Cells(i, 1) + Cells(i, 2))
    dteEnd = CDate(Cells(i, 3) + Cells(i, 4))

    Do While dteStart <= dteEnd
        If Hour(dteStart) >= 7 And Format(dteStart, "hh:mm") <= #7:00:00 PM# Then
            HourCount = HourCount + 1
        End If

        dteStart = DateAdd("h", 1, dteStart)
    Loop

    MinCount = HourCount * 60

    ''Minutes
    If CDate(Cells(i, 2)) >= #7:00:00 AM# And CDate(Cells(i, 2)) <= #7:00:00 PM# Then
         MinCount = MinCount - Minute(CDate(Cells(i, 2)))
    End If

    If CDate(Cells(i, 4)) >= #7:00:00 AM# And CDate(Cells(i, 4)) <= #7:00:00 PM# Then
        MinCount = MinCount + Minute(CDate(Cells(i, 4)))
    End If

    Cells(i, 6) = MinCount
Next
</code>```

This assumes that A, B, C and D are the columns that contain dates and times and that colum F is empty.

Title: Advanced DateDiff using MSExcel

Body:
VBA <s>, not taking much account of minutes. I do not know if you need minutes.</s>

Dim i As Integer
Dim ShiftRange As Range
Dim dteStart As Date
Dim dteEnd As Date
Dim HourCount As Long
Dim MinCount As Long

Set ShiftRange = Sheet1.UsedRange

For i = 2 To ShiftRange.Rows.Count
    HourCount = 0
    dteStart = CDate(Cells(i, 1) + Cells(i, 2))
    dteEnd = CDate(Cells(i, 3) + Cells(i, 4))

    Do While dteStart <= dteEnd
        If Hour(dteStart) >= 7 And Format(dteStart, "hh:mm") <= #7:00:00 PM# Then
            HourCount = HourCount + 1
        End If

        dteStart = DateAdd("h", 1, dteStart)
    Loop

    MinCount = HourCount * 60

    ''Minutes
    If CDate(Cells(i, 2)) >= #7:00:00 AM# And CDate(Cells(i, 2)) <= #7:00:00 PM# Then
         MinCount = MinCount - Minute(CDate(Cells(i, 2)))
    End If

    If CDate(Cells(i, 4)) >= #7:00:00 AM# And CDate(Cells(i, 4)) <= #7:00:00 PM# Then
        MinCount = MinCount + Minute(CDate(Cells(i, 4)))
    End If

    Cells(i, 6) = MinCount
Next

This assumes that A, B, C and D are the columns that contain dates and times and that colum F is empty.


问:
SQL statement inside an SQL statement
I want this statement to return the systems where there are more than two stations, I got this far but I don't know what to do next. All this does it return every system with a regionID less than 1100001. Am I onto the right idea at least? </p>

```<code>SELECT DISTINCT mapSolarSystems.regionID,solarSystemID,solarSystemName,x,z,security
FROM mapSolarSystems
WHERE mapSolarSystems.regionID <11000001
AND
2 < (SELECT COUNT(*) FROM stations,mapSolarSystems
 WHERE mapSolarSystems.solarSystemID=stations.systemid)
</code>```

答:
See if this work:

```<code>SELECT DISTINCT mapSolarSystems.regionID,solarSystemID,solarSystemName,x,z,security
FROM mapSolarSystems m
join stations s on m.solarSystemID = s.systemid
WHERE mapSolarSystems.regionID <11000001
AND select COUNT(*) FROM stations >2
</code>```

OR like that:

```<code>SELECT DISTINCT
mapSolarSystems.regionID,solarSystemID,solarSystemName,x,z,security
FROM mapSolarSystems m
join (select sistemId ,count(systemid) from station group by sistemId having
      count(sistemId) > 2) X on m.solarSystemID = X.systemid
WHERE mapSolarSystems.regionID <11000001
</code>```

Title: SQL statement inside an SQL statement

Body:
I want this statement to return the systems where there are more than two stations, I got this far but I don't know what to do next. All this does it return every system with a regionID less than 1100001. Am I onto the right idea at least?

SELECT DISTINCT mapSolarSystems.regionID,solarSystemID,solarSystemName,x,z,security
FROM mapSolarSystems
WHERE mapSolarSystems.regionID <11000001
AND
2 < (SELECT COUNT(*) FROM stations,mapSolarSystems
 WHERE mapSolarSystems.solarSystemID=stations.systemid)

Body:
See if this work:

SELECT DISTINCT mapSolarSystems.regionID,solarSystemID,solarSystemName,x,z,security
FROM mapSolarSystems m
join stations s on m.solarSystemID = s.systemid
WHERE mapSolarSystems.regionID <11000001
AND select COUNT(*) FROM stations >2

OR like that:

SELECT DISTINCT
mapSolarSystems.regionID,solarSystemID,solarSystemName,x,z,security
FROM mapSolarSystems m
join (select sistemId ,count(systemid) from station group by sistemId having
      count(sistemId) > 2) X on m.solarSystemID = X.systemid
WHERE mapSolarSystems.regionID <11000001


问:
I want to create an operator to divide problem1:("+6x","2"), get("+3x"); problem2:("12","2"), get ("6").
I am trying to add x after the answer, I have tried the way, but one method can only have one return.

the first if is to remove the x from string, after the divide, I want to add it back.

```<code>public String apply(Vector args)
{
    //define two string variables
    String expString1 = (String)args.get(0);
    String expString2 = (String)args.get(1);
    String s = "";
    //move the x if the last char is x.
     if (expString1.charAt(expString1.length()-1) == 'x'){s = expString1.substring(1, expString1.length()-1);
     }else if (expString1.charAt(expString1.length()-1) != 'x') {s = expString1;}
     //convert string to int, and do the divide operator.
     int n2 = Integer.parseInt(expString2);
     int n1 = Integer.parseInt(s);
     int result = n1 / n2;
    //get result, but not the one I want, especially for x string.
    return String.valueOf(result);
}
</code>```

this is what I want get.

```<code>public void testApplyVector() {
    Vector arg = new Vector();
    arg.add("+6x");
    arg.add("2");
    Divide add = new Divide();
    assertEquals("+3x", add.apply(arg));

    Vector arg2 = new Vector();
    arg2.add("12");
    arg2.add("2");
    assertEquals("6", add.apply(arg2));
}
</code>```

but this is the JUnit get, the first condition can't get the answer. I don't how to add a "x" after the answer.

```<code>    public void testApplyVector() {
    Vector arg = new Vector();
    arg.add("+6x");
    arg.add("2");
    Divide add = new Divide();
    assertEquals("3", add.apply(arg));

    Vector arg2 = new Vector();
    arg2.add("12");
    arg2.add("2");
    assertEquals("6", add.apply(arg2));
}
</code>```

答:
I solved the problem by adding another if statement for the result. Code is attached like this.</p>

```<code>public String apply(Vector args)
{
    //define two string variables
    String expString1 = (String)args.get(0);
    String expString2 = (String)args.get(1);
    String s = "";

    //move the x if the last char is x.
     if (expString1.charAt(expString1.length()-1) == 'x'){
         s = expString1.substring(0, expString1.length()-1);
     }else if (expString1.charAt(expString1.length()-1) != 'x') {
         s = expString1;}
     //convert string to int, and do the divide operator.
     int n2 = Integer.parseInt(expString2);
     int n1 = Integer.parseInt(s);
     int div = n1 / n2;
     //this is what i add, to check is the expString1 has a x.
     String result = String.valueOf(div);
     if (expString1.contains("x")) { return result = result + "x"; }
     else  return result;

}
</code>```

Body:
I am trying to add x after the answer, I have tried the way, but one method can only have one return.

the first if is to remove the x from string, after the divide, I want to add it back.

public String apply(Vector args)
{
    //define two string variables
    String expString1 = (String)args.get(0);
    String expString2 = (String)args.get(1);
    String s = "";
    //move the x if the last char is x.
     if (expString1.charAt(expString1.length()-1) == 'x'){s = expString1.substring(1, expString1.length()-1);
     }else if (expString1.charAt(expString1.length()-1) != 'x') {s = expString1;}
     //convert string to int, and do the divide operator.
     int n2 = Integer.parseInt(expString2);
     int n1 = Integer.parseInt(s);
     int result = n1 / n2;
    //get result, but not the one I want, especially for x string.
    return String.valueOf(result);
}

this is what I want get.

public void testApplyVector() {
    Vector arg = new Vector();
    arg.add("+6x");
    arg.add("2");
    Divide add = new Divide();
    assertEquals("+3x", add.apply(arg));

    Vector arg2 = new Vector();
    arg2.add("12");
    arg2.add("2");
    assertEquals("6", add.apply(arg2));
}

but this is the JUnit get, the first condition can't get the answer. I don't how to add a "x" after the answer.

    public void testApplyVector() {
    Vector arg = new Vector();
    arg.add("+6x");
    arg.add("2");
    Divide add = new Divide();
    assertEquals("3", add.apply(arg));

    Vector arg2 = new Vector();
    arg2.add("12");
    arg2.add("2");
    assertEquals("6", add.apply(arg2));
}

Body:
I solved the problem by adding another if statement for the result. Code is attached like this.

public String apply(Vector args)
{
    //define two string variables
    String expString1 = (String)args.get(0);
    String expString2 = (String)args.get(1);
    String s = "";

    //move the x if the last char is x.
     if (expString1.charAt(expString1.length()-1) == 'x'){
         s = expString1.substring(0, expString1.length()-1);
     }else if (expString1.charAt(expString1.length()-1) != 'x') {
         s = expString1;}
     //convert string to int, and do the divide operator.
     int n2 = Integer.parseInt(expString2);
     int n1 = Integer.parseInt(s);
     int div = n1 / n2;
     //this is what i add, to check is the expString1 has a x.
     String result = String.valueOf(div);
     if (expString1.contains("x")) { return result = result + "x"; }
     else  return result;

}


问:
git: creating a patch that contains blobs
I'm trying to create a patch (that I'll send to someone to apply).
However, I added a couple of image files to the commit.
How do I create a patch that will contain not only the code changes, but also the image file blobs?</p>

答:
To output a diff with binary files, include the --binary flag to your git diff call:

```<code>git diff --binary
</code>```

Description:

```<code>--binary
  In addition to --full-index, output a binary diff that can be applied
    with git-apply.
</code>```

Body:
To output a diff with binary files, include the --binary flag to your git diff call:

git diff --binary

Description:

--binary
  In addition to --full-index, output a binary diff that can be applied
    with git-apply.


问:
Why does the nm tool output for the extern-only and defined-only options overlap?
I'll start by giving my understanding of the options:

extern-only: Show me only those symbols which are referenced by the binary but whose definitions (the code or variable) will be provided by another binary

defined-only: Show me only those symbols whose definitions are contained in the binary.

Here are my commands and their output:

```<code>$nm -defined-only GenerationOfNow | grep FIRAZeroingWeakContainer
000000010002c128 t -[FIRAZeroingWeakContainer .cxx_destruct]
000000010002c0fb t -[FIRAZeroingWeakContainer object]
000000010002c114 t -[FIRAZeroingWeakContainer setObject:]
000000010021a218 S _OBJC_CLASS_$_FIRAZeroingWeakContainer
00000001002177f8 s _OBJC_IVAR_$_FIRAZeroingWeakContainer._object
000000010021a1f0 S _OBJC_METACLASS_$_FIRAZeroingWeakContainer

$nm -extern-only GenerationOfNow | grep FIRAZeroingWeakContainer
000000010021a218 S _OBJC_CLASS_$_FIRAZeroingWeakContainer
000000010021a1f0 S _OBJC_METACLASS_$_FIRAZeroingWeakContainer
</code>```

As you can see, the -extern-only output is a subset of the -defined-only output. Why? Perhaps my question should be: What is the meaning of those items which have a S in the second column?

答:
You're confusing -extern-only with -undefined-only.

There are two concepts that are being mixed here:

extern vs. local (in C extern vs. static, "local" is sometimes also called "private")

defined vs. undefined

The former describes the availability of a symbol while the latter describes its origin. And yes, even the notion of a private undefined symbol exists, as per man nm:

Each symbol name is preceded by its value (blanks if undefined). [...] A lower case u in a dynamic shared library indicates a undefined reference to a private external in another module in the same library.

Now, when using -undefined-only you actually do get the complement of -undefined-only

bash$ nm test.dylib
0000000000000f60 T _derp
0000000000000f70 t _herp
                 U _printf
                 U dyld_stub_binder
```

<pre class="lang-none prettyprint-override"><code>bash$ nm -defined-only test.dylib
0000000000000f60 T _derp
0000000000000f70 t _herp
</code>```

bash$ nm -undefined-only test.dylib
_printf
dyld_stub_binder
```

<pre class="lang-none prettyprint-override"><code>bash$ nm -extern-only test.dylib
0000000000000f60 T _derp
                 U _printf
                 U dyld_stub_binder
</code>```

-extern-only does not seem to have a complementary flag however.

Body:
I'll start by giving my understanding of the options:

extern-only: Show me only those symbols which are referenced by the binary but whose definitions (the code or variable) will be provided by another binary

defined-only: Show me only those symbols whose definitions are contained in the binary.

Here are my commands and their output:

$nm -defined-only GenerationOfNow | grep FIRAZeroingWeakContainer
000000010002c128 t -[FIRAZeroingWeakContainer .cxx_destruct]
000000010002c0fb t -[FIRAZeroingWeakContainer object]
000000010002c114 t -[FIRAZeroingWeakContainer setObject:]
000000010021a218 S _OBJC_CLASS_$_FIRAZeroingWeakContainer
00000001002177f8 s _OBJC_IVAR_$_FIRAZeroingWeakContainer._object
000000010021a1f0 S _OBJC_METACLASS_$_FIRAZeroingWeakContainer

$nm -extern-only GenerationOfNow | grep FIRAZeroingWeakContainer
000000010021a218 S _OBJC_CLASS_$_FIRAZeroingWeakContainer
000000010021a1f0 S _OBJC_METACLASS_$_FIRAZeroingWeakContainer

As you can see, the -extern-only output is a subset of the -defined-only output. Why? Perhaps my question should be: What is the meaning of those items which have a S in the second column?

Body:
You're confusing -extern-only with -undefined-only.

There are two concepts that are being mixed here:

extern vs. local (in C extern vs. static, "local" is sometimes also called "private")

defined vs. undefined

The former describes the availability of a symbol while the latter describes its origin. And yes, even the notion of a private undefined symbol exists, as per man nm:

Each symbol name is preceded by its value (blanks if undefined). [...] A lower case u in a dynamic shared library indicates a undefined reference to a private external in another module in the same library.

Now, when using -undefined-only you actually do get the complement of -undefined-only

bash$ nm test.dylib
0000000000000f60 T _derp
0000000000000f70 t _herp
                 U _printf
                 U dyld_stub_binder

bash$ nm -defined-only test.dylib
0000000000000f60 T _derp
0000000000000f70 t _herp

bash$ nm -undefined-only test.dylib
_printf
dyld_stub_binder

bash$ nm -extern-only test.dylib
0000000000000f60 T _derp
                 U _printf
                 U dyld_stub_binder

-extern-only does not seem to have a complementary flag however.


问:
My multiplication in python not working
I'm trying to get a multiplication inside a for loop working on the code below:

```<code>#products list and it's values per unity
tomato = 2
potato = 3
carrot = 1
pricePaid = int()

print("Welcome to my grocery shop!\n")

productList = ["Potato", "Tomato", "Carrot"]

print("What will you want today?\n""We have:")
print(*productList, sep=', ')
product = input("What will it be? ")

quantity = int(input("And how many do you want? "))

for productChoice in product:
    if productChoice == "Potato":
        pricePaid = quantity * potato
    elif productChoice == "Tomato":
        pricePaid = quantity * tomato
    elif productChoice == "Carrot":
        pricePaid = quantity * carrot

print("Here's your bag with {0} {1}s. The total is ${2:.2f}.".format(quantity, product, pricePaid))
</code>```

but I'm getting a $0.00 as my results where it should be the quantity * productPrice:

```<code>"Here's your bag with 1 Tomatos. The total is $0.00."
</code>```

Why is it failing? What am I missing here?

I'm using Python 3.x

Thanks in advance!

答:
You're iterating through the characters in the input, and setting the price paid each time. There's no need to iterate, as product doesn't change. Removing that for loop does the trick. You also need to remove the references to productChoice, since it (literally) has no purpose.

```<code>#products list and it's values per unity
tomato = 2
potato = 3
carrot = 1
pricePaid = int()

print("Welcome to my grocery shop!\n")

productList = ["Potato", "Tomato", "Carrot"]

print("What will you want today?\n""We have:")
print(*productList, sep=', ')
product = input("What will it be? ")

quantity = int(input("And how many do you want? "))

if product == "Potato":
    pricePaid = quantity * potato
elif product == "Tomato":
    pricePaid = quantity * tomato
elif product == "Carrot":
    pricePaid = quantity * carrot

print("Here's your bag with {0} {1}s. The total is ${2:.2f}.".format(quantity, product, pricePaid))
</code>```

Title: My multiplication in python not working

Body:
I'm trying to get a multiplication inside a for loop working on the code below:

#products list and it's values per unity
tomato = 2
potato = 3
carrot = 1
pricePaid = int()

print("Welcome to my grocery shop!\n")

productList = ["Potato", "Tomato", "Carrot"]

print("What will you want today?\n""We have:")
print(*productList, sep=', ')
product = input("What will it be? ")

quantity = int(input("And how many do you want? "))

for productChoice in product:
    if productChoice == "Potato":
        pricePaid = quantity * potato
    elif productChoice == "Tomato":
        pricePaid = quantity * tomato
    elif productChoice == "Carrot":
        pricePaid = quantity * carrot

print("Here's your bag with {0} {1}s. The total is ${2:.2f}.".format(quantity, product, pricePaid))

but I'm getting a $0.00 as my results where it should be the quantity * productPrice:

"Here's your bag with 1 Tomatos. The total is $0.00."

Why is it failing? What am I missing here?

I'm using Python 3.x

Thanks in advance!

Body:
You're iterating through the characters in the input, and setting the price paid each time. There's no need to iterate, as product doesn't change. Removing that for loop does the trick. You also need to remove the references to productChoice, since it (literally) has no purpose.

#products list and it's values per unity
tomato = 2
potato = 3
carrot = 1
pricePaid = int()

print("Welcome to my grocery shop!\n")

productList = ["Potato", "Tomato", "Carrot"]

print("What will you want today?\n""We have:")
print(*productList, sep=', ')
product = input("What will it be? ")

quantity = int(input("And how many do you want? "))

if product == "Potato":
    pricePaid = quantity * potato
elif product == "Tomato":
    pricePaid = quantity * tomato
elif product == "Carrot":
    pricePaid = quantity * carrot

print("Here's your bag with {0} {1}s. The total is ${2:.2f}.".format(quantity, product, pricePaid))


问:
Eclipse auto-copy via SSH from one server to another upon save, PHP
I'm writing a PHP app, and our team has our servers set up so that I have to copy code onto a second server every time I edit a file.  Naturally this is against the DRY concept, and simply a monotonous chore.

When I make a change to the file, and go to refresh the webpage to see the changes, both of these servers have to be updated, or else there is a chance that I will be seeing the old version on the server that hasn't been updated yet.  So I'm copying/pasting/saving hundreds of times a day while I develop this app!

I'm using Eclipse Luna 4.4.1.  In the Remote Systems Explorer, the system type is "SSH Only."  This is the same for server 2.

I would like there to be some kind of functionality where each time I save sample.php on server 1, the same file sample.php will be automatically updated and saved with the same code on server 2.  I don't want to have to do anything else other than just save the file on server 1; after doing that I'd like for the file on server 2 to be automatically updated.

Both servers are running on nginx OS.

I've been reading a lot about this here on SE, but many of the question/answers are 5+ years old, and I wonder if there is an optimal way to do this today.  I don't have much experience with Java, but I'm happy to do this any way that will work.  Any plugin or other way would be great.

答:
Take a look at running  rsync over ssh, and put it on a cron to run the update on a periodic interval as you desire.

Here is an example of an rsync process I run to copy database backups (type / contents of the file are mostly irrelevant here):

```<code> rsync -ar -e "ssh -l <username>" <local_path_of_files_to_watch> hostname:<target_path_where_files_land>
</code>```

This is what my command looks like to rsync databases from a remote system that monitors radio traffic and records decoded messages to a daily log file:

```<code>rsync -av --remove-source-files --progress --stats -e "ssh -l stratdb" 192.168.0.23:/var/log/stratux.sqlite.*.gz /Users/stratdb/sqlite-dbs/.
</code>```

If you want this process to run without having to define a password, you'll want to setup .ssh with shared keys to allow passwordless login from server 1 -> server 2 for this process (Ideally this is done from a user that has limited capabilities on both servers).

There are some continues deployment processes you could use that would do builds and copies and the like (e.g. Jenkins) if you need really robust and highly configurable solution...  but if you just need to brute-force copy files from one server to another with a single easy command (ad-hoc) or automagically..  I'll investigate  rsync

Body:
Take a look at running  rsync over ssh, and put it on a cron to run the update on a periodic interval as you desire.

Here is an example of an rsync process I run to copy database backups (type / contents of the file are mostly irrelevant here):

 rsync -ar -e "ssh -l <username>" <local_path_of_files_to_watch> hostname:<target_path_where_files_land>

This is what my command looks like to rsync databases from a remote system that monitors radio traffic and records decoded messages to a daily log file:

rsync -av --remove-source-files --progress --stats -e "ssh -l stratdb" 192.168.0.23:/var/log/stratux.sqlite.*.gz /Users/stratdb/sqlite-dbs/.

If you want this process to run without having to define a password, you'll want to setup .ssh with shared keys to allow passwordless login from server 1 -> server 2 for this process (Ideally this is done from a user that has limited capabilities on both servers).

There are some continues deployment processes you could use that would do builds and copies and the like (e.g. Jenkins) if you need really robust and highly configurable solution...  but if you just need to brute-force copy files from one server to another with a single easy command (ad-hoc) or automagically..  I'll investigate  rsync


问:
Variadic arguments with TypeScript - enforce last argument
Say we have a function that accepts a variable number of arguments, I believe it's called variadic function.

Something like this:

```<code>function foo(){
 let args = Array.from(arguments).map(v => whatever);
  // do something with args
}
</code>```

A TypeScript interface for this function might look like:

```<code>interface IVariadicFn {
   (...args: string[]): void,
}
</code>```

but let's say we expect a variable number of strings, but the final parameter, we expect to be a callback function.

So we'd have something like this:

```<code>function variadic(){
 let args = Array.from(arguments)
 let fn = args.pop();
 let $args = args.map(v => whatever);
  // do something with args
 process.nextTick(function(){
   fn(null, $args); // fire the callback, asynchronously
 });
}
</code>```

is there a way to declare a TypeScript definition for this function?

The best I can do right now is this:

```<code>type IVariadicArgs = string | Function;

export interface IBeforeFn {
  (...args: IVariadicArgs[]): void;
}
</code>```

答:
While you can't do this in general, you can define multiple overloads which should cover most use cases:

```<code>function variadic(fn: () => void)
function variadic(a: string, fn: () => void)
function variadic(a: string, b: string, fn: () => void)
function variadic(a: string, b: string, c: string, fn: () => void)
function variadic(a: string, b: string, c: string, d: string, fn: () => void)
function variadic(...args: (string | (() => void))[]) {
    // ...
}

variadic(() => 3, "foo") // error
variadic("foo", () => 3) // ok
variadic("foo", "bar", () => 3) // ok
</code>```

playground

Body:
Say we have a function that accepts a variable number of arguments, I believe it's called variadic function.

Something like this:

function foo(){
 let args = Array.from(arguments).map(v => whatever);
  // do something with args
}

A TypeScript interface for this function might look like:

interface IVariadicFn {
   (...args: string[]): void,
}

but let's say we expect a variable number of strings, but the final parameter, we expect to be a callback function.

So we'd have something like this:

function variadic(){
 let args = Array.from(arguments)
 let fn = args.pop();
 let $args = args.map(v => whatever);
  // do something with args
 process.nextTick(function(){
   fn(null, $args); // fire the callback, asynchronously
 });
}

is there a way to declare a TypeScript definition for this function?

The best I can do right now is this:

type IVariadicArgs = string | Function;

export interface IBeforeFn {
  (...args: IVariadicArgs[]): void;
}

Body:
While you can't do this in general, you can define multiple overloads which should cover most use cases:

function variadic(fn: () => void)
function variadic(a: string, fn: () => void)
function variadic(a: string, b: string, fn: () => void)
function variadic(a: string, b: string, c: string, fn: () => void)
function variadic(a: string, b: string, c: string, d: string, fn: () => void)
function variadic(...args: (string | (() => void))[]) {
    // ...
}

variadic(() => 3, "foo") // error
variadic("foo", () => 3) // ok
variadic("foo", "bar", () => 3) // ok

<a href="https://www.typescriptlang.org/play/#src=function%20variadic(fn%3A%20()%20%3D%3E%20void)%0D%0Afunction%20variadic(a%3A%20string%2C%20fn%3A%20()%20%3D%3E%20void)%0D%0Afunction%20variadic(a%3A%20string%2C%20b%3A%20string%2C%20fn%3A%20()%20%3D%3E%20void)%0D%0Afunction%20variadic(a%3A%20string%2C%20b%3A%20string%2C%20c%3A%20string%2C%20fn%3A%20()%20%3D%3E%20void)%0D%0Afunction%20variadic(a%3A%20string%2C%20b%3A%20string%2C%20c%3A%20string%2C%20d%3A%20string%2C%20fn%3A%20()%20%3D%3E%20void)%0D%0Afunction%20variadic(...args%3A%20(string%20%7C%20(()%20%3D%3E%20void))%5B%5D)%20%7B%0D%0A%20%20%20%20%2F%2F%20...%0D%0A%7D%0D%0A%0D%0Avariadic(()%20%3D%3E%203%2C%20%22foo%22)%20%2F%2F%20error%0D%0Avariadic(%22foo%22%2C%20()%20%3D%3E%203)%20%2F%2F%20ok%20%0D%0Avariadic(%22foo%22%2C%20%22bar%22%2C%20()%20%3D%3E%203)%20%2F%2F%20ok" rel="nofollow noreferrer">playground


问:
Bash find fails to return all matching files when called from a script
Running the same command from the command line and from a bash script produces different results on Ubuntu 16.04.

I have a folder with the following contents:

```<code>├── audio
│   └── delete_me.mp3
├── words
│   └── audio
│       └── delete_me.mp3
│   └── images
│       └── delete_me.jpg
└── keep_me.txt
</code>```

I have a bash script named findKeepers.sh:

```<code>#!/usr/bin/env bash

findKeepers () {
  local dir=$1
  echo "$(find $dir -type f ! -name delete_me*)"
}

findKeepers /path/to/directory
</code>```

I expect it to output the path to the keep_me.txt file. Instead, I get a blank line.

```<code>
</code>```

If I run what seems to me to be identical commands from the command line, I get what I expect:

```<code>dir=/path/to/directory; echo "$(find $dir -type f ! -name delete_me*)"
/path/to/directory/keep_me.txt
</code>```

If search instead for all files not called keep_me, the bash script ignores the audio folder. Here's another bash script called findUnwanted.sh:

```<code>#!/usr/bin/env bash

findUnwanted () {
  local dir=$1
  echo "$(find $dir -type f ! -name keep_me*)"
}

findUnwanted /path/to/directory
</code>```

Here's the result:

```<code>$ ./findUnwanted.sh
/path/to/directory/words/audio/delete_me.mp3
/path/to/directory/words/images/delete_me.jpg
</code>```

If I run the same thing from the command line, I get all three delete_me files:

```<code>$ dir=/path/to/directory; echo "$(find $dir -type f ! -name keep_me*)"
/path/to/directory/words/audio/delete_me.mp3
/path/to/directory/words/images/delete_me.jpg
/path/to/directory/audio/delete_me.mp3
</code>```

It seems to me that the bash script starts by going deep into the words folder, and then does not come out again to search adjacent folders or files. Is there something special about the #!/usr/bin/env bash environment that makes it do this? Or is there some other difference that I'm not seeing?

CODA: I'm guessing it was pilot error, because after more modifications it started working for me again. For anyone who is interested, the final version of my function is shown below.

```<code>#!/usr/bin/env bash

# Returns 1 if the given directory contains only placeholder files, or
# 0 if the directory contains something worth keeping
checkForDeletion () {
  local _dir=$1
  local _temp=$(find "$_dir" -type f ! -regex '.*\(unused.txt\|delete_me.*\)')

  if [ -z "$_temp" ]
  then
   return 1
  fi
}
</code>```

I use it like this:

```<code>parent=/path/to/parent/
for dir in $parent*/
do
  checkForDeletion $dir
  if [ $? = 1 ]
  then
    echo "DELETE? $dir" # rm -rf $dir
  fi
done
</code>```

答:
I am guessing that your '!' is breaking the whole pipe. Try using '-not' instead, so your first code snippet would look like this:

```<code>  echo "$(find $dir -type f -not -name delete_me*)"
</code>```

I am not that good at explaining where you should escape special characters and where not, but the fact that things work differently when using that outside function suggests that escaping may be the issue.

Body:
Running the same command from the command line and from a bash script produces different results on Ubuntu 16.04.

I have a folder with the following contents:

├── audio
│   └── delete_me.mp3
├── words
│   └── audio
│       └── delete_me.mp3
│   └── images
│       └── delete_me.jpg
└── keep_me.txt

I have a bash script named findKeepers.sh:

#!/usr/bin/env bash

findKeepers () {
  local dir=$1
  echo "$(find $dir -type f ! -name delete_me*)"
}

findKeepers /path/to/directory

I expect it to output the path to the keep_me.txt file. Instead, I get a blank line.

If I run what seems to me to be identical commands from the command line, I get what I expect:

dir=/path/to/directory; echo "$(find $dir -type f ! -name delete_me*)"
/path/to/directory/keep_me.txt

If search instead for all files not called keep_me, the bash script ignores the audio folder. Here's another bash script called findUnwanted.sh:

#!/usr/bin/env bash

findUnwanted () {
  local dir=$1
  echo "$(find $dir -type f ! -name keep_me*)"
}

findUnwanted /path/to/directory

Here's the result:

$ ./findUnwanted.sh
/path/to/directory/words/audio/delete_me.mp3
/path/to/directory/words/images/delete_me.jpg

If I run the same thing from the command line, I get all three delete_me files:

$ dir=/path/to/directory; echo "$(find $dir -type f ! -name keep_me*)"
/path/to/directory/words/audio/delete_me.mp3
/path/to/directory/words/images/delete_me.jpg
/path/to/directory/audio/delete_me.mp3

It seems to me that the bash script starts by going deep into the words folder, and then does not come out again to search adjacent folders or files. Is there something special about the #!/usr/bin/env bash environment that makes it do this? Or is there some other difference that I'm not seeing?

CODA: I'm guessing it was pilot error, because after more modifications it started working for me again. For anyone who is interested, the final version of my function is shown below.

#!/usr/bin/env bash

# Returns 1 if the given directory contains only placeholder files, or
# 0 if the directory contains something worth keeping
checkForDeletion () {
  local _dir=$1
  local _temp=$(find "$_dir" -type f ! -regex '.*\(unused.txt\|delete_me.*\)')

  if [ -z "$_temp" ]
  then
   return 1
  fi
}

I use it like this:

parent=/path/to/parent/
for dir in $parent*/
do
  checkForDeletion $dir
  if [ $? = 1 ]
  then
    echo "DELETE? $dir" # rm -rf $dir
  fi
done

Body:
I am guessing that your '!' is breaking the whole pipe. Try using '-not' instead, so your first code snippet would look like this:

  echo "$(find $dir -type f -not -name delete_me*)"

I am not that good at explaining where you should escape special characters and where not, but the fact that things work differently when using that outside function suggests that escaping may be the issue.


问:
How to reach specific child node using XPATH?
I have a XML file that I'm trying to parse to get tags named Result.

With the xpath name(//results/*) and count(//results/*), I can see that results has 10 child nodes and that each is named Result. But there is no match if I use any of the following xpaths:

//Result

/query/results/Result[1]

/query/results/Result

Nothing I am doing is returning any Result tag. But I know that there are 10. I can obtain results via /query/results, so I know I'm connecting to this file. How do I generate a xpath to reach each Result?

The XML Structure (shortened):

```<code><?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
    yahoo:count="10" yahoo:created="2013-07-17T15:15:52Z" yahoo:lang="en-US">
    <diagnostics>
    </diagnostics>
    <results>
        <Result id="11762112" xmlns="urn:yahoo:lcl">
            <Title>California Rollin' Sushi Bar</Title>
            <Address>274 Goodman St N</Address>
            <City>Rochester</City>
            <State>NY</State>
            <Phone>(585) 271-8990</Phone>
            <Latitude>43.158685</Latitude>
            <Longitude>-77.585197</Longitude>
            <Rating>
                <AverageRating>3</AverageRating>
                <TotalRatings>10</TotalRatings>
                <TotalReviews>10</TotalReviews>
                <LastReviewDate>1341259499</LastReviewDate>
                <LastReviewIntro> I went with my two girls last week and was told it would be around 1-1/2 wait so we had our name put on list hoping we would get seated sooner. It was busy because the groupons were expiring (which they knew ahead of time, so one would think they would be prepared). Well needless to say after 1-1/2 we still were not seated and there were several tables available. I asked how much longer and the hostess said another hour. I told her we have already been waiting for 1 hour she smirked and said sorry. People were coming in after us and being seated which made one of my girls ask the question why do they get a table before us. I went back in and said since my kids are tired is there anyway I could order take out and use my groupon since I am here and of course the hostess replied no its for dine in only. Ugh we left and ate elsewhere. I did call to speak with the manager who really was more concerned about telling me how proud she was of her staff and really didnt seem to care about our awful experience. Too bad because they lost several customers that night. What ever happend to customer service?</LastReviewIntro>
            </Rating>
            <Distance>1.57</Distance>
            <Url>http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester</Url>
            <ClickUrl>http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester</ClickUrl>
            <MapUrl>http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester?viewtype=map</MapUrl>
            <BusinessUrl>http://californiarollin.com/</BusinessUrl>
            <BusinessClickUrl>http://californiarollin.com/</BusinessClickUrl>
            <Categories>
                <Category id="96926236">Restaurants</Category>
                <Category id="96926205">Sushi Restaurants</Category>
            </Categories>
        </Result>
    </results>
</query>
</code>```

答:
I've tried your xml and had to close the results tag, which I assume was part of you copying and pasting just a bit of the xml. Apart from that, everything worked fine. I've added more Result tags to test it and got what was expected. Check it out:

```<code>import java.io.FileInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class TestXpath {
    public static void main(String[] args) throws IOException, SAXException, IOException, ParserConfigurationException, XPathExpressionException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document parse = builder.parse(new FileInputStream("test.xml"));

        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("/query/results/Result[2]");

        NodeList nl = (NodeList)  expr.evaluate(parse, XPathConstants.NODESET);
        for (int i = 0; i < nl.getLength(); i++) {
            Node item = nl.item(i);
            System.out.println(item.getNodeName());
            System.out.println(item.getTextContent());
        }
    }
}
</code>```

Output:

```<code>Result

            California  2 Rollin' Sushi Bar
            274 Goodman St N
            Rochester
            NY
            (585) 271-8990
            43.158685
            -77.585197

                3
                10
                10
                1341259499
                 I went with my two girls last week and was told it would be around 1-1/2 wait so we had our name put on list hoping we would get seated sooner. It was busy because the groupons were expiring (which they knew ahead of time, so one would think they would be prepared). Well needless to say after 1-1/2 we still were not seated and there were several tables available. I asked how much longer and the hostess said another hour. I told her we have already been waiting for 1 hour she smirked and said sorry. People were coming in after us and being seated which made one of my girls ask the question why do they get a table before us. I went back in and said since my kids are tired is there anyway I could order take out and use my groupon since I am here and of course the hostess replied no its for dine in only. Ugh we left and ate elsewhere. I did call to speak with the manager who really was more concerned about telling me how proud she was of her staff and really didnt seem to care about our awful experience. Too bad because they lost several customers that night. What ever happend to customer service?

            1.57
            http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester
            http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester
            http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester?viewtype=map
            http://californiarollin.com/
            http://californiarollin.com/

                Restaurants
                Sushi Restaurants
</code>```

Notice the California 2 to indicate that it was the second Result entry.

I've also tried //Result and /query/results/Result.

Is there anything wrong with the xml that you have in hand? Could you try it with the code I posted? Cheers!

Body:
I have a XML file that I'm trying to parse to get tags named Result.

With the xpath name(//results/*) and count(//results/*), I can see that results has 10 child nodes and that each is named Result. But there is no match if I use any of the following xpaths:

//Result

/query/results/Result[1]

/query/results/Result

Nothing I am doing is returning any Result tag. But I know that there are 10. I can obtain results via /query/results, so I know I'm connecting to this file. How do I generate a xpath to reach each Result?

The XML Structure (shortened):

<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
    yahoo:count="10" yahoo:created="2013-07-17T15:15:52Z" yahoo:lang="en-US">
    <diagnostics>
    </diagnostics>
    <results>
        <Result id="11762112" xmlns="urn:yahoo:lcl">
            <Title>California Rollin' Sushi Bar</Title>
            <Address>274 Goodman St N</Address>
            <City>Rochester</City>
            <State>NY</State>
            <Phone>(585) 271-8990</Phone>
            <Latitude>43.158685</Latitude>
            <Longitude>-77.585197</Longitude>
            <Rating>
                <AverageRating>3</AverageRating>
                <TotalRatings>10</TotalRatings>
                <TotalReviews>10</TotalReviews>
                <LastReviewDate>1341259499</LastReviewDate>
                <LastReviewIntro> I went with my two girls last week and was told it would be around 1-1/2 wait so we had our name put on list hoping we would get seated sooner. It was busy because the groupons were expiring (which they knew ahead of time, so one would think they would be prepared). Well needless to say after 1-1/2 we still were not seated and there were several tables available. I asked how much longer and the hostess said another hour. I told her we have already been waiting for 1 hour she smirked and said sorry. People were coming in after us and being seated which made one of my girls ask the question why do they get a table before us. I went back in and said since my kids are tired is there anyway I could order take out and use my groupon since I am here and of course the hostess replied no its for dine in only. Ugh we left and ate elsewhere. I did call to speak with the manager who really was more concerned about telling me how proud she was of her staff and really didnt seem to care about our awful experience. Too bad because they lost several customers that night. What ever happend to customer service?</LastReviewIntro>
            </Rating>
            <Distance>1.57</Distance>
            <Url>http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester</Url>
            <ClickUrl>http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester</ClickUrl>
            <MapUrl>http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester?viewtype=map</MapUrl>
            <BusinessUrl>http://californiarollin.com/</BusinessUrl>
            <BusinessClickUrl>http://californiarollin.com/</BusinessClickUrl>
            <Categories>
                <Category id="96926236">Restaurants</Category>
                <Category id="96926205">Sushi Restaurants</Category>
            </Categories>
        </Result>
    </results>
</query>

Body:
I've tried your xml and had to close the results tag, which I assume was part of you copying and pasting just a bit of the xml. Apart from that, everything worked fine. I've added more Result tags to test it and got what was expected. Check it out:

import java.io.FileInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class TestXpath {
    public static void main(String[] args) throws IOException, SAXException, IOException, ParserConfigurationException, XPathExpressionException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document parse = builder.parse(new FileInputStream("test.xml"));

        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("/query/results/Result[2]");

        NodeList nl = (NodeList)  expr.evaluate(parse, XPathConstants.NODESET);
        for (int i = 0; i < nl.getLength(); i++) {
            Node item = nl.item(i);
            System.out.println(item.getNodeName());
            System.out.println(item.getTextContent());
        }
    }
}

Output:

Result

            California  2 Rollin' Sushi Bar
            274 Goodman St N
            Rochester
            NY
            (585) 271-8990
            43.158685
            -77.585197

                3
                10
                10
                1341259499
                 I went with my two girls last week and was told it would be around 1-1/2 wait so we had our name put on list hoping we would get seated sooner. It was busy because the groupons were expiring (which they knew ahead of time, so one would think they would be prepared). Well needless to say after 1-1/2 we still were not seated and there were several tables available. I asked how much longer and the hostess said another hour. I told her we have already been waiting for 1 hour she smirked and said sorry. People were coming in after us and being seated which made one of my girls ask the question why do they get a table before us. I went back in and said since my kids are tired is there anyway I could order take out and use my groupon since I am here and of course the hostess replied no its for dine in only. Ugh we left and ate elsewhere. I did call to speak with the manager who really was more concerned about telling me how proud she was of her staff and really didnt seem to care about our awful experience. Too bad because they lost several customers that night. What ever happend to customer service?

            1.57
            http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester
            http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester
            http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester?viewtype=map
            http://californiarollin.com/
            http://californiarollin.com/

                Restaurants
                Sushi Restaurants

Notice the California 2 to indicate that it was the second Result entry.

I've also tried //Result and /query/results/Result.

Is there anything wrong with the xml that you have in hand? Could you try it with the code I posted? Cheers!


问:
What do you model and when? (Enterprise, Application and Database Design Modeling)
Imagine that you are designing a web application that could possibly grow to the scale of Amazon or Google. In the beginning you start with only one small aspect of the project knowing that, in the name of agile development, you have to start somewhere. For example, you might choose to create a simple directory of books hoping that your project takes off and some day you'll be not just a directory but a one-stop site for buying and selling books as well as all kinds of other merchandise. (This is all purely hypothetical.)

What are the different types of modeling you would employ? What are the different "entities" that you would model in the beginning? How important do you think modeling is and what information should you use to determine when and what to model?

In an answer on a previously asked question on SO there is reference made to the "data centric world view" versus the "process centric world view". Do you model the flow of information across an application or website(s) before you start to perform logical data modeling and physical data modeling? Or do these phrases refer to something different?

What tools might you use for modeling the different types of information?

答:
My modeling is usually done on a piece of paper or sometimes a whiteboard. I came a long way from writing exhaustive technical designs, but I found out that it is no use at all to think ahead to features you'd like to have in a few years or even a few months. Your requirement will change continuously, so you should program for the 'now'.

That is, when it comes to modeling.

Of course you should think of what what happen if your company grows, but not in features, only in performance. Would your app still run if you got 10 times the visitors, 10 times the products, 10 times the orders... Those things you need to worry about, not about what you are intending to build in 2 years. There's no way you can foresee everything, and all attempts to write 'smart' and 'extendable' code, will result in a more complex system that is even harder to customize in two years than it would have been if you didn't think about it at all.

Just build what you need now, and build it lean and clean so it can be extended, refactored or replaced in the future.


问:
I have an Uncaught Reference Error that says a function is not defined, even though it seems to be defined
I am trying to perform some javascript code when an input field's input changes. I started by specifying an oninput event handler function name.

```<code><input type="text" name="venue_name" value="<?php echo $event->venue_name(); ?>"
    class="form-control w2bw2c-name w2bw2c-venue-name" placeholder="Search..."
    oninput="inputChange()">
</code>```

I had the inputChange function defined outside my document-ready function, and this worked for a while, but now it is not working. Now I have this code:

```<code><input type="text" name="venue_name" value="<?php echo $event->venue_name(); ?>"
    class="form-control w2bw2c-name w2bw2c-venue-name" placeholder="Search...">
</code>```

Within my document.ready function I have:

```<code>$('select.w2bw2c-name').input(function() {
    inputChange(this);
});
</code>```

Outside my document.ready function, I have the function:

```<code>function inputChange(x) {
    ... some code ...
};
</code>```

Now when I enter some text into the input field I get the message that inputChange is not defined. Perhaps it is complicating that I must use a class as a selector, but the input field may appear multiple times within a form, and I got it to work initially.

答:
.input() isn't the valid way to attach the input event, you should use .on() instead, like :

```<code>$('select.w2bw2c-name').on('input', function() {
    inputChange(this);
});
</code>```

NOTE : Your selector refer to a select tag when you've an input, it may be :

```<code>$('input.w2bw2c-name')..
</code>```

Instead of :

```<code>$('select.w2bw2c-name')..
</code>```

Body:
I am trying to perform some javascript code when an input field's input changes. I started by specifying an oninput event handler function name.

<input type="text" name="venue_name" value="<?php echo $event->venue_name(); ?>"
    class="form-control w2bw2c-name w2bw2c-venue-name" placeholder="Search..."
    oninput="inputChange()">

I had the inputChange function defined outside my document-ready function, and this worked for a while, but now it is not working. Now I have this code:

<input type="text" name="venue_name" value="<?php echo $event->venue_name(); ?>"
    class="form-control w2bw2c-name w2bw2c-venue-name" placeholder="Search...">

Within my document.ready function I have:

$('select.w2bw2c-name').input(function() {
    inputChange(this);
});

Outside my document.ready function, I have the function:

function inputChange(x) {
    ... some code ...
};

Now when I enter some text into the input field I get the message that inputChange is not defined. Perhaps it is complicating that I must use a class as a selector, but the input field may appear multiple times within a form, and I got it to work initially.

Body:
.input() isn't the valid way to attach the input event, you should use .on() instead, like :

$('select.w2bw2c-name').on('input', function() {
    inputChange(this);
});

NOTE : Your selector refer to a select tag when you've an input, it may be :

$('input.w2bw2c-name')..

Instead of :

$('select.w2bw2c-name')..


问:
ModifiedNodeDoesNotExistException ODL while writing statistic to operational datastore
Scenario is application is writing data directly to device and after 4 seconds they are writing to config datastore. Now in the time gap there is statistic collection triggered which will collect the data written and will write it to operational datastore. </p>

<p>My question is whether the data should be present in config datastore before statistic is collected or before the same data is being written to operational datastore.  </p>

答: You are not saying which ODL release you are using, nor (more importantly) which application features you have installed are using, but when you write "statistic collection triggered" that sounds like openflowplugin project related?  I wonder if https://git.opendaylight.org/gerrit/#/c/66207/ which was proposed just today (not yet reviewed and merged) has anything to do with your problem, and may fix it... If not, you would need to provide more details about you are writing to - as far as I understand, the ModifiedNodeDoesNotExistException basically just means something like that what you want to write to meanwhile was concurrently already removed.

Body:
Scenario is application is writing data directly to device and after 4 seconds they are writing to config datastore. Now in the time gap there is statistic collection triggered which will collect the data written and will write it to operational datastore.

My question is whether the data should be present in config datastore before statistic is collected or before the same data is being written to operational datastore.


问:
Update React Component after render
I am using react-native-sortable-listview to change order of list-item by drag and drop. Only drag item is again rendered so its position is updated but other have their previous position. When This component is re-rendered by other cause like some increment button, all position are being correct.
 So my question is when my react-native-sortable-list is rendered how can I re-render this again.
 Both ways to render by forceUpdate() and this.setState() , I could not follow as I can not update state in render function.
 What can be a possible way for doing this.

答:
I do not know that list but there should be some property like onDrop or something like that. You can pass a function to this event handler that might start sorting the list, you are passing in.

is it this list?

https://www.npmjs.com/package/react-native-sortable-list

i would try what the onReleaseRow event handler does. Maybe something like:

```<code><SortableList onReleaseRow{() => this.sortList() data={this.state.data}}/>

sortList() {
let sortedData = //sort data somehow
this.setState({
    data: sortedData})
}
</code>```

Title: Update React Component after render

Body:
I do not know that list but there should be some property like onDrop or something like that. You can pass a function to this event handler that might start sorting the list, you are passing in.

is it this list?

https://www.npmjs.com/package/react-native-sortable-list

i would try what the onReleaseRow event handler does. Maybe something like:

<SortableList onReleaseRow{() => this.sortList() data={this.state.data}}/>

sortList() {
let sortedData = //sort data somehow
this.setState({
    data: sortedData})
}


问:
Is it possible to create an anonymous class associated with a specific class/package name?
If I'm running in Class X, then all anonymous classes are associated with X$#, in some way.

Is there a way when creating/declaring an anonymous class to have it associated explicitly with a specific package+class?

答: Move your anonymous class definition code to nested (static) classes inside the class. If you are capturing local variables, then pass them in a constructor.</p>


问:
CURL won't get the data from this website
I'm trying to retrieve data from www.dotabuff.com for a list of steam ID, but I only get in return "We couldn't find what you are looking for!".

The goal is to go to the website, search a player with his steam ID and extract his win rate.

(This is intended for very small lists, which will not bother dotabuff).

Here is my code (example with a static steam ID):

```<code>//create array of data to be posted
$post_data['utf8'] = '✓';
$post_data['q'] = '76561198055615656';
$post_data['commit'] = 'Search';

//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}

//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);

//create cURL connection
$curl_connection =
curl_init('https://www.dotabuff.com//');

//set options
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

//set data to be posted
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);

//perform our request
$result = curl_exec($curl_connection);
echo $result;

//close the connection
curl_close($curl_connection);
</code>```

答: You are using POST with curl to do the search, but looking at the Dotabuff website the search form is using GET, so I suspect the website is looking for GET vars instead of POST vars. I haven't tested this but I would suggest doing a curl request to https://www.dotabuff.com/search?q=76561198055615656 (without the POSTFIELDS) and see what that gives you.</p>

Body:
I'm trying to retrieve data from www.dotabuff.com for a list of steam ID, but I only get in return "We couldn't find what you are looking for!".

The goal is to go to the website, search a player with his steam ID and extract his win rate.

(This is intended for very small lists, which will not bother dotabuff).

Here is my code (example with a static steam ID):

//create array of data to be posted
$post_data['utf8'] = '✓';
$post_data['q'] = '76561198055615656';
$post_data['commit'] = 'Search';

//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}

//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);

//create cURL connection
$curl_connection =
curl_init('https://www.dotabuff.com//');

//set options
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

//set data to be posted
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);

//perform our request
$result = curl_exec($curl_connection);
echo $result;

//close the connection
curl_close($curl_connection);


问:
Object Normalization
In the same line as Database Normalization - is there an approach to object normalization, not design pattern, but the same mathematical like approach to normalizing object creation.  For example: first normal form: no repeating fields....
here's some links to DB Normalization:

http://en.wikipedia.org/wiki/Database_normalization
  http://databases.about.com/od/specificproducts/a/normalization.htm

Would this make object creation and self-documentation better?

Here's a link to a book about class normalization (guess we're really talking about classes)
http://www.agiledata.org/essays/classNormalization.html

答:
Perhaps you're taking this from a relational point-of-view, but I would posit that the principles of interfaces and inheritance correspond to normalization in the world of OOP.

For example, a Person abstract class containing FirstName, LastName, Gender and BirthDate can be used by classes such as Employee, User, Member etc. as a valid base class, without a need to repeat the definitions of those attributes in such subclasses.

The principle of DRY, (a core principle of Andy Hunt and Dave Thomas's book The Pragmatic Programmer), and the constant emphasis of object-oriented programming on re-use, also correspond to the efficiencies offered by Normalization in relational databases.

OwnerDisplayName: meade

Title: Object Normalization

LastEditorDisplayName: meade

OwnerDisplayName: Jon Limjap


问:
wordpress -override number of posts in loop
See: http://jasondaydesign.com/portfolio

Also, for this custom loop, how would I override the number of posts as set by WP Settings > Reading > show 10 posts.

thanks!

```<code><?php
/*
Template Name: Portfolio
*/
?>

<?php get_header(); ?>

<ul id="portfolio-filter">
  <li><a href="#all">All</a></li>
  <li><a href="#web-design">Web</a></li>
  <li><a href="#logo-and-branding-design">Logo</a></li>
  <li><a href="#print-and-graphic-design">Print</a></li>
  <li><a href="#sculpture">Sculpture </a></li>
  <li><a href="#for-sale">For Sale </a></li>
 </ul>

        <ul id="portfolio-list">
        <?php query_posts('cat=5&showposts='); ?>
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<!-- ** store the category slugs for each post in a variable $catSlug ** -->
  <li class="<?php foreach((get_the_category()) as $category ) { echo $category->category_nicename . ' '; } ?>all">

 <!-- ** This is my own plugin to get the thumbnail from the post - you may use some custom field you have to get the image. ** -->
                    <a href='<?php the_permalink() ?>' title='<?php the_title(); ?>'><img src='<?php woo_image('width='.$woo_options['woo_thumb_w'].'&height='.$woo_options['woo_thumb_h'].'&class=thumbnail '.$woo_options['woo_thumb_align']); ?>' alt='<?php the_title(); ?>' /></a>

                    <p><?php the_title(); ?></p>
     <p><?php the_excerpt(); ?></p>

                </li>
            <? endwhile; ?>
        <? endif; ?>
  <?php wp_reset_query(); ?>
        </ul>

<?php get_footer(); ?>
</code>```

答:
Change the line that says

```<code><?php query_posts('cat=5&showposts='); ?>
</code>```

to say

```<code><?php query_posts('cat=5&showposts=&posts_per_page=10'); ?>
</code>```

Body:
See: http://jasondaydesign.com/portfolio

Also, for this custom loop, how would I override the number of posts as set by WP Settings > Reading > show 10 posts.

thanks!

<?php
/*
Template Name: Portfolio
*/
?>

<?php get_header(); ?>

All

Web

Logo

Print

Sculpture

For Sale

        <?php query_posts('cat=5&showposts='); ?>
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

  <li class="<?php foreach((get_the_category()) as $category ) { echo $category->category_nicename . ' '; } ?>all">

                    <a href='<?php the_permalink() ?>' title='<?php the_title(); ?>'><img src='<?php woo_image('width='.$woo_options['woo_thumb_w'].'&height='.$woo_options['woo_thumb_h'].'&class=thumbnail '.$woo_options['woo_thumb_align']); ?>' alt='<?php the_title(); ?>' />

<?php the_title(); ?>

<?php the_excerpt(); ?>

            <? endwhile; ?>
        <? endif; ?>
  <?php wp_reset_query(); ?>

<?php get_footer(); ?>

Body:
Change the line that says

<?php query_posts('cat=5&showposts='); ?>

to say

<?php query_posts('cat=5&showposts=&posts_per_page=10'); ?>


问:
How can I change value from property in jQuery
I am trying to select property "top" and the value minus (-200px) from inline css.

```<code><article class="stack" style="position: absolute; left: 741px; top: 1000px;">
</article>
</code>```

What I want is to count the top: 1000px - 200px

It should decrease the move of the article from 1000px to 800px.

Thanks in advance for any help and sorry if the question is badly asked.

答:
You can simply do this :

let a = $('article.stack').css('top'); // get the Top value
console.log(a);

$('article.stack').css('top',parseInt(a)-200); //updated the Top value

a = $('article.stack').css('top');
console.log(a);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article class="stack" style="position: absolute; left: 741px; top: 1000px;">
</article></code>```

Body:
I am trying to select property "top" and the value minus (-200px) from inline css.

What I want is to count the top: 1000px - 200px

It should decrease the move of the article from 1000px to 800px.

Thanks in advance for any help and sorry if the question is badly asked.

Body:
You can simply do this :

let a = $('article.stack').css('top'); // get the Top value
console.log(a);

$('article.stack').css('top',parseInt(a)-200); //updated the Top value

a = $('article.stack').css('top');
console.log(a);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article class="stack" style="position: absolute; left: 741px; top: 1000px;">
</article>


答:
Element Result belongs to the default namespace "urn:yahoo:lcl". See answer to the question:

Getting elements with default namespace (no namespace prefix) using XPath

Title: How to reach specific child node using XPATH?


问:
Correlate two floats using c#
I know im an idiot and I am sure this is simple math. But I cannot seem to wrap my head around it here is my situation

When X = 3, I need Y = 0, and when X = 0 I need y = 1;.
I am trying to fill a progress bar based upon how low X is.

The value to fill the progress bar (Y) must be between 0 and 1.

Math?

答:
As I know best from my high school:

y = a*x + b
You must solve equations:
0 = a*3 + b and
1 = a*0 + b

a = -b/3; b =1

So your equation is: y=-1/3*x+1

```<code>private float GetProgressValue(float x)
{
    return x/-3f + 1f;
}
</code>```

Title: Correlate two floats using c#

Body:
As I know best from my high school:

y = a*x + b
You must solve equations:
0 = a*3 + b and
1 = a*0 + b

a = -b/3; b =1

So your equation is: y=-1/3*x+1

private float GetProgressValue(float x)
{
    return x/-3f + 1f;
}


问:
Hamburger toggle menu for one page site
I am developing a super simple site using jQuery and bootstrap libraries but I would like the menu items to jump to the section (already done with anchors). But when I navigate back to the top the menu dropdown is still open. How would I setup up a toggle so it closes on clicking a menu item?

This is my initial code:

```<code>$( document ).ready(function() {
  $( ".cross" ).hide();
  $( ".menu" ).hide();
  $( ".hamburger" ).click(function() {
    $( ".menu" ).slideToggle( "slow", function() {
      $( ".hamburger" ).hide();
      $( ".cross" ).show();
    });
  });
  $( ".cross" ).click(function() {
    $( ".menu" ).slideToggle( "slow", function() {
      $( ".cross" ).hide();
      $( ".hamburger" ).show();
    });
  });
});

<button class="hamburger">☰</button>
<button class="cross">˟</button>

<div class="menu">
<ul>
<a href="#"><li>Home</li></a>
<a href="#about"><li>Jeff Anderson</li></a>
<a href="#"><li>Hand Built Frames</li></a>
<a href="#"><li>Bike Repairs and Maintenance</li></a>
<a href="#"><li>Frames and Accessories</li></a>
  <a href="#"><li>Contact</li></a>
</ul>
</div>
</div>
</code>```

Any help greatly appreciated. Thanks.

答:
Anything that gets to the document will hide the dropdown

```<code>$(document).click(function(){
  $("#dropdown").hide();
});
</code>```

Clicks within the dropdown won't make it past the dropdown itself

```<code>$("#dropdown").click(function(e){
  e.stopPropagation();
});
</code>```

I believe adding these code will solve your problem.

Title: Hamburger toggle menu for one page site

Body:
I am developing a super simple site using jQuery and bootstrap libraries but I would like the menu items to jump to the section (already done with anchors). But when I navigate back to the top the menu dropdown is still open. How would I setup up a toggle so it closes on clicking a menu item?

This is my initial code:

$( document ).ready(function() {
  $( ".cross" ).hide();
  $( ".menu" ).hide();
  $( ".hamburger" ).click(function() {
    $( ".menu" ).slideToggle( "slow", function() {
      $( ".hamburger" ).hide();
      $( ".cross" ).show();
    });
  });
  $( ".cross" ).click(function() {
    $( ".menu" ).slideToggle( "slow", function() {
      $( ".cross" ).hide();
      $( ".hamburger" ).show();
    });
  });
});

<button class="hamburger">☰</button>
<button class="cross">˟</button>

Home

Jeff Anderson

Hand Built Frames

Bike Repairs and Maintenance

Frames and Accessories

Contact

Any help greatly appreciated. Thanks.

Body:
Anything that gets to the document will hide the dropdown

$(document).click(function(){
  $("#dropdown").hide();
});

Clicks within the dropdown won't make it past the dropdown itself

$("#dropdown").click(function(e){
  e.stopPropagation();
});

I believe adding these code will solve your problem.


问:
google chart candlestick colors
I am trying to customize candlecharts from google charts.

I have found how to change the color of the candle themselves, but not the one of the line indicating the highest and lowest value:

Those are the options I provided:

```<code>    let options = {
      legend: 'none',
      candlestick: {
        risingColor: {stroke: '#4CAF50', fill: 'white'},
        fallingColor: {stroke: '#F44336'}
      }
    }
</code>```

You can try it on this jsFiddle: https://jsfiddle.net/El_Matella/h5p36t3w/2/

I can't find in the documentation how to change it, does someone have an idea? (https://developers.google.com/chart/interactive/docs/gallery/candlestickchart)

答:
if you want all the lines to be the same color,

you can use the colors option...

see following working snippet...

google.charts.load('current', {'packages':['corechart']});

google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Mon', 20, 28, 38, 45],
    ['Tue', 31, 38, 55, 66],
    ['Wed', 50, 55, 77, 80],
    ['Thu', 77, 77, 66, 50],
    ['Fri', 68, 66, 22, 15]
    // Treat first row as data as well.
  ], true);

  var options = {
    legend:'none',
    candlestick: {
      risingColor: {stroke: '#4CAF50', fill: 'white'},
      fallingColor: {stroke: '#F44336'}
    },
    colors: ['magenta']
  };

  var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));

  chart.draw(data, options);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div></code>```

Title: google chart candlestick colors

Body:
I am trying to customize candlecharts from google charts.

I have found how to change the color of the candle themselves, but not the one of the line indicating the highest and lowest value:

Those are the options I provided:

    let options = {
      legend: 'none',
      candlestick: {
        risingColor: {stroke: '#4CAF50', fill: 'white'},
        fallingColor: {stroke: '#F44336'}
      }
    }

You can try it on this jsFiddle: https://jsfiddle.net/El_Matella/h5p36t3w/2/

I can't find in the documentation how to change it, does someone have an idea? (https://developers.google.com/chart/interactive/docs/gallery/candlestickchart)

Body:
if you want all the lines to be the same color,

you can use the colors option...

see following working snippet...

google.charts.load('current', {'packages':['corechart']});

google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Mon', 20, 28, 38, 45],
    ['Tue', 31, 38, 55, 66],
    ['Wed', 50, 55, 77, 80],
    ['Thu', 77, 77, 66, 50],
    ['Fri', 68, 66, 22, 15]
    // Treat first row as data as well.
  ], true);

  var options = {
    legend:'none',
    candlestick: {
      risingColor: {stroke: '#4CAF50', fill: 'white'},
      fallingColor: {stroke: '#F44336'}
    },
    colors: ['magenta']
  };

  var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));

  chart.draw(data, options);
}

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>


问:
How do I mock a class using Rspec and Rails?
I'm using Rails 5 with Rspec 3.  How do I mock a class in my Rspec method?  I have the following class

```<code>require 'rails_helper'

describe CryptoCurrencyService do

  describe ".sell" do

    it "basic_sell" do
      last_buy_price = 3000
      last_transaction = MoneyMakerTransaction.new({
        :transaction_type => "buy",
        :amount_in_usd => "100",
        :btc_price_in_usd => "#{last_buy_price}"
      })
      @client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
      sell_price = 4000
      assert sell_price > last_buy_price * (1 + MoneyMakerThreshhold.find_buy.pct_change)

      allow(@client).to receive(:sell_price).and_return({"base"=>"BTC", "currency"=>"USD", "amount"=>"#{sell_price}"})

      svc = CryptoCurrencyService.new
      svc.sell(last_transaction)
      last_transaction = MoneyMakerTransaction.find_latest_record
      assert last_transaction.transaction_type, "sell"
    end

  end

end
</code>```

Instead of actually instantiating the class "Coinbase::Wallet" in the line

```<code>@client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
</code>```

I'd like to create  mock taht I could then insert into my service class, which I'm testing.  As it stands right now, when I run things, the actual underlying class is getting instantiated, resulting the run time error ...

```<code>  1) CryptoCurrencyService.sell basic_sell
     Failure/Error: payment_method = client.payment_methods()[0]

     Coinbase::Wallet::AuthenticationError:
       invalid api key
</code>```

答:
rspec mocks and stubs can be used on any class.
For example:

```<code>coinbase_mock = double(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
expect(Coinbase::Wallet::Client).to_receive(:new).and_return(coinbase_mock)
</code>```

then you can add whatever you like to the coinbase_mock so that it quacks like the class you need... :)

Body:
I'm using Rails 5 with Rspec 3.  How do I mock a class in my Rspec method?  I have the following class

require 'rails_helper'

describe CryptoCurrencyService do

  describe ".sell" do

    it "basic_sell" do
      last_buy_price = 3000
      last_transaction = MoneyMakerTransaction.new({
        :transaction_type => "buy",
        :amount_in_usd => "100",
        :btc_price_in_usd => "#{last_buy_price}"
      })
      @client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
      sell_price = 4000
      assert sell_price > last_buy_price * (1 + MoneyMakerThreshhold.find_buy.pct_change)

      allow(@client).to receive(:sell_price).and_return({"base"=>"BTC", "currency"=>"USD", "amount"=>"#{sell_price}"})

      svc = CryptoCurrencyService.new
      svc.sell(last_transaction)
      last_transaction = MoneyMakerTransaction.find_latest_record
      assert last_transaction.transaction_type, "sell"
    end

  end

end

Instead of actually instantiating the class "Coinbase::Wallet" in the line

@client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])

I'd like to create  mock taht I could then insert into my service class, which I'm testing.  As it stands right now, when I run things, the actual underlying class is getting instantiated, resulting the run time error ...

  1) CryptoCurrencyService.sell basic_sell
     Failure/Error: payment_method = client.payment_methods()[0]

     Coinbase::Wallet::AuthenticationError:
       invalid api key

Body:
rspec mocks and stubs can be used on any class.
For example:

coinbase_mock = double(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
expect(Coinbase::Wallet::Client).to_receive(:new).and_return(coinbase_mock)

then you can add whatever you like to the coinbase_mock so that it quacks like the class you need... :)


问:
do I need to use full text search for domain names and Ip address?
I do have domain names and ip address of it. this is almost 200k so when I redesign a table do I need to enable FULL TEXT SEARCH functionality of MySQL??

I want search table with domain names and IP address as well. means I search by domain then it should show IP address and if I search with IP then it should show domain names.

答: No, you don't need to use full text search and you don't need to enable FULL TEXT SEARCH.</p>