问:
How to Go to home screen when pressed on navbar button
I want to add a rightbar button on navigation bar as home button..

When ever i tap on that button i want to go to firstcontroller,that is my home screen

Please help me in this

Thanks in advance

答:
If your application is navigation based app then use following line of code in your button's IBAction.</p>

```<code>[self.navigationController popToRootViewControllerAnimated:YES];
</code>```

Body:
If your application is navigation based app then use following line of code in your button's IBAction.

[self.navigationController popToRootViewControllerAnimated:YES];


来源: stackexchange

问:
Git hooks: where do I put them after I push to remote repo
I've read the git hooks documentation and I'ms still trying to figure out where I put scripts for git hooks for certain events, and how I manage them:

Preconditions:

Create bare git repository foo on some machine A

Jenkins running on machine A

I clone my repository foo to machine B

I make some changes to foo on machine B

Commit changes to foo on B

Push changes to foo to A

Assume master branch

Desired Behavior:
After pushing to machine A, I want Jenkins to kick off a build on machine A

One machine A, there is a hooks directory with various hook scripts samples.
One machine B, there is a .git/hooks directory with various hook script samples.

Questions:

Where do I put the script to cause Jenkins to rebuild my app? On machine A or on machine B?

What would the name be? post-push?

If I put them on machine B, don't the scripts get wiped out if I delete my clone of foo and re-clone the repository?

Would I have to re-create them if I re-clone?

Are git hooks themselves version under git version control or do you just manage them free of source control?

Thanks

答:
Where do I put the script to cause Jenkins to rebuild my app?

On the machine that runs Jenkins (so on Machine A).

What would the name be? post-push?

You want a post-receive hook (assuming A is your remote), which:

[...] is run on the remote when pushing after the all refs have been
  updated. It does not take parameters, but receives info through stdin
  in the form of "  ". Because it is
  called after the updates, it cannot abort the process.

-

If I put them on machine B, don't the scripts get wiped out if I delete my clone of foo and re-clone the repository?

Would I have to re-create them if I re-clone?

Yes. Because:

Are git hooks themselves version under git version control or do you just manage them free of source control?

They are not because active hooks live in .git/hooks which is not under version control. See that answer for more details.

That said, this may be an XY problem. You probably don't want to do this specifically to trigger builds, but use Jenkins' polling to scan for changes, which would probably be simpler to manage.

ContentLicense: CC BY-SA 3.0


问:
Push notifications in php
How to implement push notifications in PHP based webapp.
What I actually want to implement is to get a notification as soon as some user joins a chat.

suppose two users are participants in a chat, if a third user joins that chat, then other two user be notified.

答:
You can set up push notifications without developing your own app using notify.pm. It takes around 2 lines of code, the API is here:
https://github.com/notifypm/notifypm-php-api</p>

```<code><?php

require_once("notifypm.class.php");

$n = new Notifypm('email', 'password', '.pmNumber');
$n->push('Message!', 'Link (optional)!');

$n->disconnect();
</code>```

Title: Push notifications in php

Body:
You can set up push notifications without developing your own app using notify.pm. It takes around 2 lines of code, the API is here:
https://github.com/notifypm/notifypm-php-api

<?php

require_once("notifypm.class.php");

$n = new Notifypm('email', 'password', '.pmNumber');
$n->push('Message!', 'Link (optional)!');

$n->disconnect();


问:
"go build" became very slow after installing a new version of Go
After upgrading from Go 1.2.1 to 1.3 (Windows 7 64 bit) "go build" execution time has increased from around 4 to over 45 seconds. There were no other changes except the go version update. Switching off the virus scanner seems to have no effect. Any clues?</p>

答:
After Go 1.10, you'd just need to type go build. You'd not need to type: go build -i.

From the draft Go 1.10 document, here.

Build & Install

The go build command now detects out-of-date packages purely based on the content of source files, specified build flags, and metadata stored in the compiled packages. Modification times are no longer consulted or relevant. The old advice to add -a to force a rebuild in cases where the modification times were misleading for one reason or another (for example, changes in build flags) is no longer necessary: builds now always detect when packages must be rebuilt. (If you observe otherwise, please file a bug.)

...

The go build command now maintains a cache of recently built packages, separate from the installed packages in $GOROOT/pkg or $GOPATH/pkg. The effect of the cache should be to speed builds that do not explicitly install packages or when switching between different copies of source code (for example, when changing back and forth between different branches in a version control system). The old advice to add the -i flag for speed, as in go build -i or go test -i, is no longer necessary: builds run just as fast without -i. For more details, see go help cache.


问:
Error on javascript queryselector
I'm trying to input an URL Parameter into a form input. When I'm trying to do it via the inspect console, everything seems fine. But when I load the page I got an error: Uncaught TypeError: Cannot set property 'value' of null.

Here the main javascript

```<code>function getParameterByName(name)
 {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null)
     return "";
  else
 return decodeURIComponent(results[1].replace(/\+/g, " "));
 }
</code>```

my input looks like this... There is a part of the ID that randomly changes on reload, only satisfaction_case_number stay the same.

```<code><input id="satisfaction_case_number-da4e00e8-dcf6-4efa-9f92-d9564432f979_2621" class="hs-input" type="text" name="satisfaction_case_number" value="" placeholder="" data-reactid=".hbspt-forms-0.0:$0.$satisfaction_case_number.0">
</code>```

I tried 2 functions call.

```<code>document.getElementByName("satisfaction_case_number").value = getParameterByName("case")
</code>```

and

```<code>document.querySelector('[id^="satisfaction_case_number"]').value = getParameterByName("case")
</code>```

I have to say I'm kinda blind here. Any flag would be appreciated.

Here is the URL of my page : http://info.techo-bloc.com/customer-service-0?case=CAS-00745-Z0G5F8.

I'm trying to get : CAS-00745-Z0G5F8 into the input.
Thanks

答:
Wait till the window has loaded then execute it;

```<code>window.onload = function () {
    document.getElementsByName("satisfaction_case_number")[0].value = getParameterByName('case');
}
</code>```

The form is being dynamically generated after the rest of your content has loaded, It's unreliable to rely on timing as connection speeds can vary, using
 window.onload will ensure the page is fully loaded before executing.

I tested this by throttling my browser connection to "Slow 3G" and it still worked, Your original piece of code that selected the element by name wasn't selecting the first entry in the NodeList, to do this you need to add [0] before the .value

Title: Error on javascript queryselector

Body:
I'm trying to input an URL Parameter into a form input. When I'm trying to do it via the inspect console, everything seems fine. But when I load the page I got an error: Uncaught TypeError: Cannot set property 'value' of null.

Here the main javascript

function getParameterByName(name)
 {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null)
     return "";
  else
 return decodeURIComponent(results[1].replace(/\+/g, " "));
 }

my input looks like this... There is a part of the ID that randomly changes on reload, only satisfaction_case_number stay the same.

<input id="satisfaction_case_number-da4e00e8-dcf6-4efa-9f92-d9564432f979_2621" class="hs-input" type="text" name="satisfaction_case_number" value="" placeholder="" data-reactid=".hbspt-forms-0.0:$0.$satisfaction_case_number.0">

I tried 2 functions call.

document.getElementByName("satisfaction_case_number").value = getParameterByName("case")

and

document.querySelector('[id^="satisfaction_case_number"]').value = getParameterByName("case")

I have to say I'm kinda blind here. Any flag would be appreciated.

Here is the URL of my page : http://info.techo-bloc.com/customer-service-0?case=CAS-00745-Z0G5F8.

I'm trying to get : CAS-00745-Z0G5F8 into the input.
Thanks

Body:
Wait till the window has loaded then execute it;

window.onload = function () {
    document.getElementsByName("satisfaction_case_number")[0].value = getParameterByName('case');
}

The form is being dynamically generated after the rest of your content has loaded, It's unreliable to rely on timing as connection speeds can vary, using
 window.onload will ensure the page is fully loaded before executing.

I tested this by throttling my browser connection to "Slow 3G" and it still worked, Your original piece of code that selected the element by name wasn't selecting the first entry in the NodeList, to do this you need to add [0] before the .value


问:
Making every other row into a new column
So, I have an output that looks like this:

```<code>samples pops    condition 1     condition 2 condition 3

A10051  15  1   3   4
A10051  15  2   4   4
A10052  15  2   1   4
A10052  15  2   1   4
</code>```

However, for the next analysis I need the input to look like this

```<code>samples pops    condition 1     condition 1     condition 2     condition 2 condition 3 condition 3

A10051  15  1   2   3   4   4   4
A10052  15  2   2   1   1   4   4
</code>```

So, it is not just making it so that every other row is a new column, every other row in a given column would be in a new column assigned to that same condition, in a way that each sample has two columns for the same condition and not two rows for the same sample. For the example I put 2 samples and 3 conditions, however IRL I have over 100 samples and over 1000 conditions...
any thoughts? I am confident it can be done with awk, but I just can not figure it out.

答:
3 condition columns

Taking the assertion 'the data is perfect' at face value and disregarding years of experience which indicates that data is seldom if ever perfect, then:

```<code>awk 'NR == 1 { printf "%s  %s  %s  %s  %s  %s  %s  %s\n",
                      $1, $2, $3, $3, $4, $4, $5, $5; next }
     NR == 2 { next }
     NR % 2 == 1 { c[1] = $3; c[2] = $4; c[3] = $5 }
     NR % 2 == 0 { printf "%s  %d  %d  %d  %d  %d  %d  %d\n",
                          $1, $2, c[1], $3, c[2], $4, c[3], $5 }' "$@"
</code>```

Given the input file:

```<code>samples pops    condition_1     condition_2 condition_3

A10051  15  1   3   4
A10051  15  2   4   4
A10052  15  2   1   4
A10052  15  2   1   4
</code>```

the script produces the output:

```<code>samples  pops  condition_1  condition_1  condition_2  condition_2  condition_3  condition_3
A10051  15  1  2  3  4  4  4
A10052  15  2  2  1  1  4  4
</code>```

This code is more mechanical than interesting.  If you have 10 columns in each line, you'd approach it differently.  You'd probably use loops to save and print the data.  If you want a blank line between the headings and the data, you can easily add one (NR == 2 { print; next } or use \n\n in place of \n in the first printf function).  You can arrange for the output fields to be separated by tabs if you wish (they're separated by double spaces in this code).

The code does not depend on tabs separating the data fields; it only depends on there being no white space within a field.

Many condition columns

When there are many condition columns, you need to use arrays and loops to capture and print the data, like this:

```<code>awk 'NR == 1 { printf "%s  %s", $1, $2
               for (i = 3; i <= NF; i++) printf "  %s  %s", $i, $i
               print ""
               next
             }
     NR == 2 { next }
     NR % 2 == 1 { for (i = 3; i <= NF; i++) c[i] = $i }
     NR % 2 == 0 { printf "%s  %d", $1, $2;
                   for (i = 3; i <= NF; i++) printf "  %d  %d", c[i], $i
                   print ""
                 }' "$@"
</code>```

When run on the same data as before, it produces the same output as before, but the loops would allow it to read 1000 conditions per input line and generate 2000 conditions per output line.  The only possible issue is whether your version of Awk handles such long input lines in the first place.  If need be, upgrade to GNU Awk.

Body:
So, I have an output that looks like this:

samples pops    condition 1     condition 2 condition 3

A10051  15  1   3   4
A10051  15  2   4   4
A10052  15  2   1   4
A10052  15  2   1   4

However, for the next analysis I need the input to look like this

samples pops    condition 1     condition 1     condition 2     condition 2 condition 3 condition 3

A10051  15  1   2   3   4   4   4
A10052  15  2   2   1   1   4   4

So, it is not just making it so that every other row is a new column, every other row in a given column would be in a new column assigned to that same condition, in a way that each sample has two columns for the same condition and not two rows for the same sample. For the example I put 2 samples and 3 conditions, however IRL I have over 100 samples and over 1000 conditions...
any thoughts? I am confident it can be done with awk, but I just can not figure it out.

Body:
3 condition columns

Taking the assertion 'the data is perfect' at face value and disregarding years of experience which indicates that data is seldom if ever perfect, then:

awk 'NR == 1 { printf "%s  %s  %s  %s  %s  %s  %s  %s\n",
                      $1, $2, $3, $3, $4, $4, $5, $5; next }
     NR == 2 { next }
     NR % 2 == 1 { c[1] = $3; c[2] = $4; c[3] = $5 }
     NR % 2 == 0 { printf "%s  %d  %d  %d  %d  %d  %d  %d\n",
                          $1, $2, c[1], $3, c[2], $4, c[3], $5 }' "$@"

Given the input file:

samples pops    condition_1     condition_2 condition_3

A10051  15  1   3   4
A10051  15  2   4   4
A10052  15  2   1   4
A10052  15  2   1   4

the script produces the output:

samples  pops  condition_1  condition_1  condition_2  condition_2  condition_3  condition_3
A10051  15  1  2  3  4  4  4
A10052  15  2  2  1  1  4  4

This code is more mechanical than interesting.  If you have 10 columns in each line, you'd approach it differently.  You'd probably use loops to save and print the data.  If you want a blank line between the headings and the data, you can easily add one (NR == 2 { print; next } or use \n\n in place of \n in the first printf function).  You can arrange for the output fields to be separated by tabs if you wish (they're separated by double spaces in this code).

The code does not depend on tabs separating the data fields; it only depends on there being no white space within a field.

Many condition columns

When there are many condition columns, you need to use arrays and loops to capture and print the data, like this:

awk 'NR == 1 { printf "%s  %s", $1, $2
               for (i = 3; i <= NF; i++) printf "  %s  %s", $i, $i
               print ""
               next
             }
     NR == 2 { next }
     NR % 2 == 1 { for (i = 3; i <= NF; i++) c[i] = $i }
     NR % 2 == 0 { printf "%s  %d", $1, $2;
                   for (i = 3; i <= NF; i++) printf "  %d  %d", c[i], $i
                   print ""
                 }' "$@"

When run on the same data as before, it produces the same output as before, but the loops would allow it to read 1000 conditions per input line and generate 2000 conditions per output line.  The only possible issue is whether your version of Awk handles such long input lines in the first place.  If need be, upgrade to GNU Awk.


问:
How can I invert the result of this code in clojure?
```<code>(defn exp
  [n]
  (if (= n 0)
      1
      (* 11 (exp (dec n)))))

(defn Pascals
  [n]
  (loop [x  n]
        (when (< 0 x)
              (println (exp (- x 1)))
              (recur (- x 1)))))
</code>```

I need something like the Pascal's triangle from hackerrank

答:
Your function is printing as it's processed so the only way to flip the results is to flip the process.

What I mean is that if your function were to produce a collection of vectors like

```<code>(map triangle-row (range 1 4)) => ([1 2 1] [1 1] [1])
</code>```

then you could just reverse the results of that

Here is your function with the process reversed:

```<code>(defn Pascals
  [n]
  (loop [x  0]
    (when (>= n x)
      (println (exp x))
      (recur (inc x)))))
</code>```

instead of starting at n and going to 0, it starts as 0 and goes up.

But this doesn't fix the issue that it doesn't produce the proper output for pascal's triangle after the 8th row

Body:
(defn exp
  [n]
  (if (= n 0)
      1
      (* 11 (exp (dec n)))))

(defn Pascals
  [n]
  (loop [x  n]
        (when (< 0 x)
              (println (exp (- x 1)))
              (recur (- x 1)))))

I need something like the Pascal's triangle from hackerrank

Body:
Your function is printing as it's processed so the only way to flip the results is to flip the process.

What I mean is that if your function were to produce a collection of vectors like

(map triangle-row (range 1 4)) => ([1 2 1] [1 1] [1])

then you could just reverse the results of that

Here is your function with the process reversed:

(defn Pascals
  [n]
  (loop [x  0]
    (when (>= n x)
      (println (exp x))
      (recur (inc x)))))

instead of starting at n and going to 0, it starts as 0 and goes up.

But this doesn't fix the issue that it doesn't produce the proper output for pascal's triangle after the 8th row


问:
Creating virtual directory under a specific website with NANT
I am able to create a virtual directory with 'mkiisdir', but it creates under default website only.

With using IISServer attribute it works fine in my test environment but not in Production env.

Scenario 1 (Test env)

IIS with 2 websites, 1 hosted on 80
& other on 88.

Use attribute IIServer='localhost' &
port ='88', it creates the virtual
directory under the right website

Scenario 2 (Production env)

IIS with 2 websites, 1 hosted on 80
& other as well on 80 but with a different hostheader.

What value should i use for IISServer & port so that virtual directory gets created under the website with the host header.

答:
Specify iisserver parameter and identify your site be hostname:port combination</p>

```<code><mkiisdir iisserver="host:port" dirpath="c:\siteroot\test" vdirname="Test" />
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Specify iisserver parameter and identify your site be hostname:port combination

<mkiisdir iisserver="host:port" dirpath="c:\siteroot\test" vdirname="Test" />


答:
A simple solution (no output headers) with GNU datamash (which is a nice tool for "command-line statistical operations" on textual files):

```<code>$ grep -v ^$ file | datamash -W -g1 --header-in first 2 collapse 3-5 | tr ',' ' ' | column -t
A10051  15  1  2  3  4  4  4
A10052  15  2  2  1  1  4  4
</code>```

First, skip all blank lines with grep, then with datamash group lines according to the first field (-g1), using whitespace(s) as field separators (-W), collapsing multiple rows in a group for fields 3, 4 and 5. Collapsed values are comma separated, that's why we have to break them with tr.

For a different number of columns, just adapt the range for collapse operation (e.g. collapse 3-1000). And due to grouping operation, any number of samples per group is already supported.

Title: Making every other row into a new column

Body:
A simple solution (no output headers) with GNU datamash (which is a nice tool for "command-line statistical operations" on textual files):

$ grep -v ^$ file | datamash -W -g1 --header-in first 2 collapse 3-5 | tr ',' ' ' | column -t
A10051  15  1  2  3  4  4  4
A10052  15  2  2  1  1  4  4

First, skip all blank lines with grep, then with datamash group lines according to the first field (-g1), using whitespace(s) as field separators (-W), collapsing multiple rows in a group for fields 3, 4 and 5. Collapsed values are comma separated, that's why we have to break them with tr.

For a different number of columns, just adapt the range for collapse operation (e.g. collapse 3-1000). And due to grouping operation, any number of samples per group is already supported.


问:
How many Docker service replicas do I need?
What is the scale of a docker service replica? Is it 1:1 where I need a replica for each user on the site, or is it on request? I am putting together a small site that won't see a ton of traffic. How many replicas do I need?</p>

答:
Its hard to guess the best number of replicas needed if you don't have any quantitative measure to assess performance and the load on your service.

Creating a replica per user or per request is too much, unless you are doing some extreme computation per request that will need a huge amount of time and resources to complete.

My advice is start with only one replica and monitor the load on your service and adjust accordingly. If you don't have much load and your site is lightweight you won't need to replicate your service, one will be enough.


问:
MYSQL Join and create Distinct json
I have the following select

```<code>if ($result = $mysqli->query("SELECT
a.quoteID, a.quoteTitle , a.notes,  c.web_path
FROM quotes a
INNER JOIN users_files b on b.user_id = a.quoteID
INNER JOIN files c on c.id = b.file_id ORDER BY quoteID ASC"))

{

    $tempArray = array();
    while($row = $result->fetch_object()) {
            $tempArray = $row;
            array_push($myArray, $tempArray);
        }
    echo json_encode($myArray);
}
</code>```

which gets me information I need.

```<code>[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/23.pdf"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/22.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/21.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/20.jpeg"},{"quoteID":"2","quoteTitle":"Kaitlin","notes":"Smith","web_path":"\/surplusAdmin3\/upload\/24.jpg"},{"quoteID":"8","quoteTitle":"Bryar2","notes":"Long","web_path":"\/surplusAdmin3\/upload\/17.png"},{"quoteID":"11","quoteTitle":"Avram","notes":"Allison","web_path":"\/surplusAdmin3\/upload\/4.jpg"}]
</code>```

I now need to get my result as:

```<code>[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path1":"\/surplusAdmin3\/upload\/23.pdf","web_path2":"\/surplusAdmin3\/upload\/22.jpeg","web_path3":"\/surplusAdmin3\/upload\/21.jpeg","web_path4":"\/surplusAdmin3\/upload\/20.jpeg"}]
</code>```

I am not looking to re-do the MYSQL statement I just need to create a new array in the format I need.

I have the following code:

```<code>var currentQuoteID =0;
var dataChanged = [];
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
    console.log(' current quote '+ currentQuoteID + ' = '+ e["quoteID"] + 'file count = '+  fileCount);
    if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e); arrayRow = arrayRow + 1; fileCount = 1}
  else
    {
        console.log('just add the filename array Row = ' +arrayRow );
        // need to insert to the array arrayRow
        // dataChanged.push('web_path'+fileCount,e["web_path"]);
        toPush = 'web_path'+fileCount+'"'+':'+'"'+ e["web_path"];

        var field = 'web_path'+fileCount;
        var data = e["web_path"];
        var tempArray = [field,data];
        dataChanged.push(toPush);
        dataChanged.field = data;
        //dataChanged = dataChanged.concat(tempArray);
        fileCount = fileCount +1;
    }
    currentQuoteID = e["quoteID"];
   console.log('stuff '+ JSON.stringify(dataChanged));
});
</code>```

The result I am getting is :

```<code>dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image"},"web_path1","/surplusAdmin3/upload/22.jpeg"]
</code>```

What I need is

```<code>dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image","web_path1","/surplusAdmin3/upload/22.jpeg"}]
</code>```

But I cannot workout what I need to do here.

答:
Got it working as follows:</p>

```<code>// loop through and add field 'Type' can all be done in one loop.
    dataReturned.forEach(function(e){
    if (typeof e === "object" ){
    e["Type"] = "other";

   // console.log('stuff '+e['Type'][i] )
}

});

//loop through and workout the file type
    dataReturned.forEach(function(e){
    if (typeof e === "object" ){
    var ext = e['web_path'].substr(e['web_path'].lastIndexOf('.') + 1);
    if ( (ext === 'jpeg' ) || ( ext === 'jpg' )|| ( ext === 'png' )|| ( ext === 'gif' ) || ( ext === 'pdf' ))

    { e["Type"] = "image"; }
    //console.log(e['web_path']);
   // console.log('stuff '+ JSON.stringify(e))
  }

});
// create a new array formated as needed
var currentQuoteID =0;
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
e["quoteID"] + 'file count = '+  fileCount);
    if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e);     arrayRow = arrayRow + 1; fileCount = 1}
  else
    {
        //console.log('just add the filename array Row = ' +arrayRow );
        // need to insert to the array arrayRow
        // dataChanged.push('web_path'+fileCount,e["web_path"]);
        var field = 'web_path'+fileCount;
        var data = webPath+e["web_path"];
        var tempArray = [field,data];
        dataChanged[arrayRow]['web_path'+fileCount] = data
        fileCount = fileCount +1;
    }
    currentQuoteID = e["quoteID"];
   console.log('stuff '+ JSON.stringify(dataChanged));
});
</code>```

Title: MYSQL Join and create Distinct json

Body:
I have the following select

if ($result = $mysqli->query("SELECT
a.quoteID, a.quoteTitle , a.notes,  c.web_path
FROM quotes a
INNER JOIN users_files b on b.user_id = a.quoteID
INNER JOIN files c on c.id = b.file_id ORDER BY quoteID ASC"))

{

    $tempArray = array();
    while($row = $result->fetch_object()) {
            $tempArray = $row;
            array_push($myArray, $tempArray);
        }
    echo json_encode($myArray);
}

which gets me information I need.

[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/23.pdf"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/22.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/21.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/20.jpeg"},{"quoteID":"2","quoteTitle":"Kaitlin","notes":"Smith","web_path":"\/surplusAdmin3\/upload\/24.jpg"},{"quoteID":"8","quoteTitle":"Bryar2","notes":"Long","web_path":"\/surplusAdmin3\/upload\/17.png"},{"quoteID":"11","quoteTitle":"Avram","notes":"Allison","web_path":"\/surplusAdmin3\/upload\/4.jpg"}]

I now need to get my result as:

[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path1":"\/surplusAdmin3\/upload\/23.pdf","web_path2":"\/surplusAdmin3\/upload\/22.jpeg","web_path3":"\/surplusAdmin3\/upload\/21.jpeg","web_path4":"\/surplusAdmin3\/upload\/20.jpeg"}]

I am not looking to re-do the MYSQL statement I just need to create a new array in the format I need.

I have the following code:

var currentQuoteID =0;
var dataChanged = [];
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
    console.log(' current quote '+ currentQuoteID + ' = '+ e["quoteID"] + 'file count = '+  fileCount);
    if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e); arrayRow = arrayRow + 1; fileCount = 1}
  else
    {
        console.log('just add the filename array Row = ' +arrayRow );
        // need to insert to the array arrayRow
        // dataChanged.push('web_path'+fileCount,e["web_path"]);
        toPush = 'web_path'+fileCount+'"'+':'+'"'+ e["web_path"];

        var field = 'web_path'+fileCount;
        var data = e["web_path"];
        var tempArray = [field,data];
        dataChanged.push(toPush);
        dataChanged.field = data;
        //dataChanged = dataChanged.concat(tempArray);
        fileCount = fileCount +1;
    }
    currentQuoteID = e["quoteID"];
   console.log('stuff '+ JSON.stringify(dataChanged));
});

The result I am getting is :

dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image"},"web_path1","/surplusAdmin3/upload/22.jpeg"]

What I need is

dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image","web_path1","/surplusAdmin3/upload/22.jpeg"}]

But I cannot workout what I need to do here.

Body:
Got it working as follows:

// loop through and add field 'Type' can all be done in one loop.
    dataReturned.forEach(function(e){
    if (typeof e === "object" ){
    e["Type"] = "other";

   // console.log('stuff '+e['Type'][i] )
}

});

//loop through and workout the file type
    dataReturned.forEach(function(e){
    if (typeof e === "object" ){
    var ext = e['web_path'].substr(e['web_path'].lastIndexOf('.') + 1);
    if ( (ext === 'jpeg' ) || ( ext === 'jpg' )|| ( ext === 'png' )|| ( ext === 'gif' ) || ( ext === 'pdf' ))

    { e["Type"] = "image"; }
    //console.log(e['web_path']);
   // console.log('stuff '+ JSON.stringify(e))
  }

});
// create a new array formated as needed
var currentQuoteID =0;
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
e["quoteID"] + 'file count = '+  fileCount);
    if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e);     arrayRow = arrayRow + 1; fileCount = 1}
  else
    {
        //console.log('just add the filename array Row = ' +arrayRow );
        // need to insert to the array arrayRow
        // dataChanged.push('web_path'+fileCount,e["web_path"]);
        var field = 'web_path'+fileCount;
        var data = webPath+e["web_path"];
        var tempArray = [field,data];
        dataChanged[arrayRow]['web_path'+fileCount] = data
        fileCount = fileCount +1;
    }
    currentQuoteID = e["quoteID"];
   console.log('stuff '+ JSON.stringify(dataChanged));
});


问:
Searchbox in R Shiny
It is possible to add a general search box for the user to find a string in an output widget in Shiny? In the example below, I would like the user to type a string in the textInput widget and have Shiny highlight the matching text in the verbatimTextOutput (or something similar):

```<code>library(shiny)

text <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce nec quam ut tortor interdum pulvinar id vitae magna. Curabitur commodo consequat arcu et lacinia. Proin at diam vitae lectus dignissim auctor nec dictum lectus. Fusce venenatis eros congue velit feugiat, ac aliquam ipsum gravida. Cras bibendum malesuada est in tempus. Suspendisse tincidunt, nisi non finibus consequat, ex nisl condimentum orci, et dignissim neque est vitae nulla."

ui <- fluidPage(
    sidebarPanel(
      textInput("search", "", placeholder = "Search term")
      ),
      verbatimTextOutput("text")
  )
)

server <- function(input, output) {

  output$text <- renderText(paste(text))
}

shinyApp(ui = ui, server = server)
</code>```

So far, I have been working around this problem by splitting the text in fixed-length rows and using grep to display the location of the string in the text. (For example, alerting the user that the string lorem is in the first line).

Can it somehow be done more intuitively?

Edit

@Aurèle's answer is spot on. DT::dataTableOutput also provides a searchbox feature for finding strings in data.tables, without the higlighting.

答:
Here is my naive attempt (does it satisfy the requirement of it being more intuitive?):

```<code>library(shiny)
library(stringr)
library(purrr)

text <- paste(
  "Lorem ipsum dolor sit amet,",
  "consectetur adipiscing elit. Fusce nec quam ut tortor",
  "interdum pulvinar id vitae magna.",
  "Curabitur commodo consequat arcu et lacinia.",
  "Proin at diam vitae lectus dignissim auctor nec dictum lectus.",
  "Fusce venenatis eros congue velit feugiat,",
  "ac aliquam ipsum gravida. Cras bibendum malesuada est in tempus.",
  "Suspendisse tincidunt, nisi non finibus consequat, ex nisl",
  "condimentum orci, et dignissim neque est vitae nulla."
)
insert_mark_tag <- function(s, loc_index, all_locs) {
  str_sub(s, all_locs[loc_index, 2] + 1, all_locs[loc_index, 2]) <- "</mark>"
  str_sub(s, all_locs[loc_index, 1], all_locs[loc_index, 1] - 1) <- "<mark>"
  s
}
ui <- fluidPage(
  sidebarPanel(
    textInput("search", "", placeholder = "Search term")
  ),
  htmlOutput("text")
)
server <- function(input, output) {
  output$text <- renderText({
    m <- if (nchar(input$search))
      str_locate_all(text, fixed(input$search))[[1]] else
        matrix(ncol = 2)[FALSE, ]
    HTML(reduce_right(seq_len(nrow(m)), insert_mark_tag, all_locs = m, .init = text))
  })
}
shinyApp(ui = ui, server = server)
</code>```

The keys are str_locate_all() and str_sub<-.

(you might want to use coll() instead of fixed(), and maybe replace stringr with stringi, I have no idea if the performance impact would be measurable).

I used @bartektartanus' (co-author of stringi) answer here, btw I asked in a comment whether there is a cleaner way than this naive reduce().

Edit

Actually, I have no idea why I made it so complicated. This is (much) simpler (though it behaves a little differently wrt regexes):

```<code>ui <- fluidPage(
  sidebarPanel(
    textInput("search", "", placeholder = "Search term")
  ),
  htmlOutput("text")
)
server <- function(input, output) {
  output$text <- renderText(HTML(
    if (nchar(input$search))
      str_replace_all(text, sprintf("(%s)", input$search), "<mark>\\1</mark>") else
        text
  ))
}
shinyApp(ui = ui, server = server)
</code>```

Title: Searchbox in R Shiny

Body:
It is possible to add a general search box for the user to find a string in an output widget in Shiny? In the example below, I would like the user to type a string in the textInput widget and have Shiny highlight the matching text in the verbatimTextOutput (or something similar):

library(shiny)

text <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce nec quam ut tortor interdum pulvinar id vitae magna. Curabitur commodo consequat arcu et lacinia. Proin at diam vitae lectus dignissim auctor nec dictum lectus. Fusce venenatis eros congue velit feugiat, ac aliquam ipsum gravida. Cras bibendum malesuada est in tempus. Suspendisse tincidunt, nisi non finibus consequat, ex nisl condimentum orci, et dignissim neque est vitae nulla."

ui <- fluidPage(
    sidebarPanel(
      textInput("search", "", placeholder = "Search term")
      ),
      verbatimTextOutput("text")
  )
)

server <- function(input, output) {

  output$text <- renderText(paste(text))
}

shinyApp(ui = ui, server = server)

So far, I have been working around this problem by splitting the text in fixed-length rows and using grep to display the location of the string in the text. (For example, alerting the user that the string lorem is in the first line).

Can it somehow be done more intuitively?

Edit

@Aurèle's answer is spot on. DT::dataTableOutput also provides a searchbox feature for finding strings in data.tables, without the higlighting.

Body:
Here is my naive attempt (does it satisfy the requirement of it being more intuitive?):

library(shiny)
library(stringr)
library(purrr)

text <- paste(
  "Lorem ipsum dolor sit amet,",
  "consectetur adipiscing elit. Fusce nec quam ut tortor",
  "interdum pulvinar id vitae magna.",
  "Curabitur commodo consequat arcu et lacinia.",
  "Proin at diam vitae lectus dignissim auctor nec dictum lectus.",
  "Fusce venenatis eros congue velit feugiat,",
  "ac aliquam ipsum gravida. Cras bibendum malesuada est in tempus.",
  "Suspendisse tincidunt, nisi non finibus consequat, ex nisl",
  "condimentum orci, et dignissim neque est vitae nulla."
)
insert_mark_tag <- function(s, loc_index, all_locs) {
  str_sub(s, all_locs[loc_index, 2] + 1, all_locs[loc_index, 2]) <- "</mark>"
  str_sub(s, all_locs[loc_index, 1], all_locs[loc_index, 1] - 1) <- "<mark>"
  s
}
ui <- fluidPage(
  sidebarPanel(
    textInput("search", "", placeholder = "Search term")
  ),
  htmlOutput("text")
)
server <- function(input, output) {
  output$text <- renderText({
    m <- if (nchar(input$search))
      str_locate_all(text, fixed(input$search))[[1]] else
        matrix(ncol = 2)[FALSE, ]
    HTML(reduce_right(seq_len(nrow(m)), insert_mark_tag, all_locs = m, .init = text))
  })
}
shinyApp(ui = ui, server = server)

The keys are str_locate_all() and str_sub<-.

(you might want to use coll() instead of fixed(), and maybe replace stringr with stringi, I have no idea if the performance impact would be measurable).

I used @bartektartanus' (co-author of stringi) answer here, btw I asked in a comment whether there is a cleaner way than this naive reduce().

Edit

Actually, I have no idea why I made it so complicated. This is (much) simpler (though it behaves a little differently wrt regexes):

ui <- fluidPage(
  sidebarPanel(
    textInput("search", "", placeholder = "Search term")
  ),
  htmlOutput("text")
)
server <- function(input, output) {
  output$text <- renderText(HTML(
    if (nchar(input$search))
      str_replace_all(text, sprintf("(%s)", input$search), "<mark>\\1</mark>") else
        text
  ))
}
shinyApp(ui = ui, server = server)


问:
Python Loop: Index out of range ERROR
I am extremely new to Python, this is, in fact, my first ever made program. It's a simple web crawler that is making its way through a website's sitemap and collection data on the way. This loop will run a lot of times without any problems, every file will run this loop over 3000 times. After around 100 files I get an index out of range error and I have no idea why. Here is the loop that is giving problems:

```<code>for item in soup.find_all('loc'):
    newsItem = {
        'Category': '',
        'Title':    '',
        'Url':      ''
    }

    newsItem['Category'] = list(filter(None, item.text.replace(
        'http://www.nu.nl', '').replace('.html', '').split('/')))[0].title()
    newsItem['Title'] = list(filter(None, item.text.replace(
        'http://www.nu.nl', '').replace('.html', '').split('/')))[2].replace('-', ' ').title()
    newsItem['Url'] = item.text
    newsItems.append(newsItem)
    print_progress(counter, len(soup.find_all('loc')), 'Progress:')
    counter += 1
</code>```

Error:

```<code>Traceback (most recent call last):
  File "theVerge.py", line 52, in <module>
    'http://www.nu.nl', '').replace('.html', '').split('/')))[2].replace('-', ' ').title()
IndexError: list index out of range
</code>```

答:
Without a traceback, my best guess would be this line:

```<code>newsItem['Title'] = list(filter(None, item.text.replace('http://www.nu.nl', '').replace('.html', '').split('/')))[2].replace('-', ' ').title()
</code>```

I'm guessing whatever is the result of

```<code>newsItem['Title'] = list(filter(None, item.text.replace('http://www.nu.nl', '').replace('.html', '').split('/')))
</code>```

Doesn't have 3 items inside, so the [2] index is out of range.

Oh, and by the way...that is some really gnarly string replace lines you have. For the sake of readability, you may want to break these up or find a better way do to this. Reading this code, I have no idea what

```<code>list(filter(None, item.text.replace('http://www.nu.nl', '').replace('.html', '').split('/')))[2].replace('-', ' ').title()
</code>```

would do even if I had an example of input :P

Title: Python Loop: Index out of range ERROR

Body:
I am extremely new to Python, this is, in fact, my first ever made program. It's a simple web crawler that is making its way through a website's sitemap and collection data on the way. This loop will run a lot of times without any problems, every file will run this loop over 3000 times. After around 100 files I get an index out of range error and I have no idea why. Here is the loop that is giving problems:

for item in soup.find_all('loc'):
    newsItem = {
        'Category': '',
        'Title':    '',
        'Url':      ''
    }

    newsItem['Category'] = list(filter(None, item.text.replace(
        'http://www.nu.nl', '').replace('.html', '').split('/')))[0].title()
    newsItem['Title'] = list(filter(None, item.text.replace(
        'http://www.nu.nl', '').replace('.html', '').split('/')))[2].replace('-', ' ').title()
    newsItem['Url'] = item.text
    newsItems.append(newsItem)
    print_progress(counter, len(soup.find_all('loc')), 'Progress:')
    counter += 1

Error:

Traceback (most recent call last):
  File "theVerge.py", line 52, in <module>
    'http://www.nu.nl', '').replace('.html', '').split('/')))[2].replace('-', ' ').title()
IndexError: list index out of range

Body:
Without a traceback, my best guess would be this line:

newsItem['Title'] = list(filter(None, item.text.replace('http://www.nu.nl', '').replace('.html', '').split('/')))[2].replace('-', ' ').title()

I'm guessing whatever is the result of

newsItem['Title'] = list(filter(None, item.text.replace('http://www.nu.nl', '').replace('.html', '').split('/')))

Doesn't have 3 items inside, so the [2] index is out of range.

Oh, and by the way...that is some really gnarly string replace lines you have. For the sake of readability, you may want to break these up or find a better way do to this. Reading this code, I have no idea what

list(filter(None, item.text.replace('http://www.nu.nl', '').replace('.html', '').split('/')))[2].replace('-', ' ').title()

would do even if I had an example of input :P


问:
Removing element from vector by member element
Trying to implement a file system I have 3 classes:

BaseFile - Abstract class. Each with a name.

File - Inherits from BaseFile. Each file has a size.

Directory - Inherits from BaseFile. Holds a:

```<code>vector<Base File*> children;
</code>```

I am trying to build a function that deletes a specific file from a directory using a name as a comparable:

```<code>for (decltype(children.size()) i = 0; i < children.size(); ++i) {
    if(children[i]->getName() == name) {
        cout << "Same name" << endl;
    }
    else {
        cout << "not found" << endl;
    }
}
</code>```

I have found the elements are similar but how do i delete the one in the vector?

答:
You can use the erase-remove_if idiom:

```<code>children.erase(
    std::remove_if(
        std::begin(children),
        std::end(children),
        [&name](const BaseFile* x){ return x->getName() == name; }
    ),
    std::end(children)
);
</code>```

Body:
Trying to implement a file system I have 3 classes:

BaseFile - Abstract class. Each with a name.

File - Inherits from BaseFile. Each file has a size.

Directory - Inherits from BaseFile. Holds a:

vector<Base File*> children;

I am trying to build a function that deletes a specific file from a directory using a name as a comparable:

for (decltype(children.size()) i = 0; i < children.size(); ++i) {
    if(children[i]->getName() == name) {
        cout << "Same name" << endl;
    }
    else {
        cout << "not found" << endl;
    }
}

I have found the elements are similar but how do i delete the one in the vector?

Body:
You can use the erase-remove_if idiom:

children.erase(
    std::remove_if(
        std::begin(children),
        std::end(children),
        [&name](const BaseFile* x){ return x->getName() == name; }
    ),
    std::end(children)
);


问:
CouchDB how to exclude documents from View
I have a CouchDB View to return all documents meeting a certain criteria. I have also run "all_docs" against this same DB.  In this particular case, my View returns 845 docs while all_docs returns 1127 docs.

Is there a way to code a View to effectively do the inverse, and return all documents NOT meeting my specified criteria?  since my DB contains 1127 total docs and my View contains 845 docs, how do I identify the 282 difference?

答:
You can either have two views or one single view.

Single view(persons)

```<code>function(doc){
  var matchMyCriteria = doc.type ==="person";
  emit(matchMyCriteria);
}
</code>```

If I want every document document that are of type "person", I query:

_design/docname/_view/by_person?key="true"

If I want the every other documents

_design/docname/_view/by_person?key="false"

Two view(persons)

persons

```<code>function(doc){
  if(doc.type == "person")
     emit(doc.id);
}
</code>```

not_person

```<code>function(doc){
  if(doc.type != "person")
     emit(doc._id);
}
</code>```

Body:
You can either have two views or one single view.

Single view(persons)

function(doc){
  var matchMyCriteria = doc.type ==="person";
  emit(matchMyCriteria);
}

If I want every document document that are of type "person", I query:

_design/docname/_view/by_person?key="true"

If I want the every other documents

_design/docname/_view/by_person?key="false"

Two view(persons)

persons

function(doc){
  if(doc.type == "person")
     emit(doc.id);
}

not_person

function(doc){
  if(doc.type != "person")
     emit(doc._id);
}


问:
How to Transfer All Greasemonkey userscripts to Tampermonkey on Firefox 57+
After read that Greasemonkey recommends users to install Tampermonkey or Violentmonkey.

I've installed Tampermonkey and now I'm trying to transfer all my Greasemonkey 3.x scripts to be opened on Tampermonkey, but I can't find it's location or even how to do it.

I've read this question that says where and how it's located on Chrome, but where is it on Firefox 57+?
How can I transfer it?

PS: I'm expecting I won't need to update every userscript I have.

答:
Based on derjanb comment I'm answering the question showing the steps I took to achieve the transfer of the userscripts.

Enter about:support on firefox address, then find and click open folder

Now find and open gm_scripts folder, click to search inside it and type .user.js, when the search finishes select all userscripts you want to transfer.

Now right click the selected files and choose Send To - Compressed (zipped) folder.

Once your zip file is created find it on Desktop or where it was created and open the Tampermonkey Dashboard

Go to utilities tab and on Zip select import, find your zip file and once you click open button, it should load

Finally a list with all scripts inside the zip should open, asking which one you desire to import. If you want all, just click import.

That should do it. Check it out on Installed userscripts tab.


答:
awk to the rescue!

```<code>awk     '{k=$1 FS $2}
   NR==1 {p0=$0; pk=k}
   pk==k {split(p0,a); for(i=3;i<=NF;i++) $i=a[i] FS $i; print}
   pk!=k {p0=$0; pk=$1 FS $2}' file

samples pops condition_1 condition_1 condition_2 condition_2 condition_3 condition_3
A10051 15 1 2 3 4 4 4
A10052 15 2 2 1 1 4 4
</code>```

will work for unspecified number of columns and records, as long as they are all well-formed (same number of columns) and grouped (same keys are in sequence).

Body:
awk to the rescue!

awk     '{k=$1 FS $2}
   NR==1 {p0=$0; pk=k}
   pk==k {split(p0,a); for(i=3;i<=NF;i++) $i=a[i] FS $i; print}
   pk!=k {p0=$0; pk=$1 FS $2}' file

samples pops condition_1 condition_1 condition_2 condition_2 condition_3 condition_3
A10051 15 1 2 3 4 4 4
A10052 15 2 2 1 1 4 4

will work for unspecified number of columns and records, as long as they are all well-formed (same number of columns) and grouped (same keys are in sequence).


问:
Rails subtract datepicker dates
I switched from date_select to jQuery UI Datepicker and when I am trying to subtract the dates to get the number of days between those days I am getting the following error.

The date format for date_select is year/month/day however the format for the jQuery Datepicker is month/day/year. How can I combat this issue and still use Datepicker?

答:
You can rewrite it like this:

```<code>Date.strptime(@pdform.date_finish, "%m/%d/%Y") - Date.strptime(@pdform.date_start, "%m/%d/%Y")
</code>```

For my tests on console, this should work. Hope this helps, good luck!

Edit:
That works for the different date format, but the error shown is about nil classes, so maybe there's something wrong with your values... should check that first!

Title: Rails subtract datepicker dates

Body:
You can rewrite it like this:

Date.strptime(@pdform.date_finish, "%m/%d/%Y") - Date.strptime(@pdform.date_start, "%m/%d/%Y")

For my tests on console, this should work. Hope this helps, good luck!

Edit:
That works for the different date format, but the error shown is about nil classes, so maybe there's something wrong with your values... should check that first!


问:
In Google Sheets, How to use '=IMAGE' to reference an image in filesystem:https://docs.google.com/persistent
I have a Google DOC. The DOC has embedded Google Diagrams. I'm writing a Google Script to transfer the content of the Document to a Sheet. The script goes through the document "body's children" identifying if it is a Paragraph or Table, and if it is a paragraph, extract the Text, In line drawing, or In line image.

Now, in DOCS a Diagram is represented as an image of the Diagram, not the diagram per se. Google Docs executes a request (e.g. https://docs.google.com/a/mydomain.com/drawings/d/sDanx1eRvHChcrvgj1IIdCQ/image?w=719&h=573&rev=1346&ac=1) that generates an image (terrible resolution by the way, but that a different topic). Such image is stored "somewhere" as a persistent file, and incorporated into the document via another request (e.g. filesystem:https://docs.google.com/persistent/docs/documents/1DlxAjdWZAVOkGvq1CZvsbEpxBNs8bDCPW1972UKfbxU/drawing/sDanx1eRvHChcrvgj1IIdCQ?zx=xxuxts66tny4).
Neither are regular straight-forward URLs to an image.

The '=IMAGE' function and other Google "dialog screens" (like Insert image from URL in Docs) will NOT resolve them. The preference to use '=IMAGE' is that the image remains with the cell.

Furthermore, the INLINE IMAGE type appears not to provide a method to even acquire these URLs, or the Diagram's document ID.
Even if I could get the URLs, using the URLs directly or 'fetching' them to create a Blob from them, I only see they would be useful with the InsertImage method, which would leave the image detached from a cell.

Apparently, even using the URL that generates the Image with the insertImage(blob), fails saying there was a server error.

Any ideas?

答:
If your embedded images have links you could use getLinkUrl(). Google Apps Script hasn't a method to get directly the URL of an embedded drawing.

I didn't tested this yet, put I think that it should work.

As the Google Sheet function IMAGE requires an URL of a publicly accessible image, when you be preparing your Google drawings that will be used on a spreadsheet,

publish the drawing to the web

grab the URL of the published image

add the Google drawing to the document

add the URL of the published image as a link to the embedded image

Then when you be transferring the content from the Google document to a Google spreadsheet you could use getLinkUrl() to get the URL and add it as parameter of IMAGE


答: You can try document.querySelector('input[id *= satisfaction_case_number]').value = 'example'

Title: Error on javascript queryselector

Body:
I'm trying to input an URL Parameter into a form input. When I'm trying to do it via the inspect console, everything seems fine. But when I load the page I got an error: Uncaught TypeError: Cannot set property 'value' of null.

Here the main javascript

function getParameterByName(name)
 {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null)
     return "";
  else
 return decodeURIComponent(results[1].replace(/\+/g, " "));
 }

my input looks like this... There is a part of the ID that randomly changes on reload, only satisfaction_case_number stay the same.

<input id="satisfaction_case_number-da4e00e8-dcf6-4efa-9f92-d9564432f979_2621" class="hs-input" type="text" name="satisfaction_case_number" value="" placeholder="" data-reactid=".hbspt-forms-0.0:$0.$satisfaction_case_number.0">

I tried 2 functions call.

document.getElementByName("satisfaction_case_number").value = getParameterByName("case")

and

document.querySelector('[id^="satisfaction_case_number"]').value = getParameterByName("case")

I have to say I'm kinda blind here. Any flag would be appreciated.

Here is the URL of my page : http://info.techo-bloc.com/customer-service-0?case=CAS-00745-Z0G5F8.

I'm trying to get : CAS-00745-Z0G5F8 into the input.
Thanks


问:
navbar dropdown not working in bootstrap4.0
My navbar dropdown menu isn't working, I have included the following stylesheets and js files

```<code><link href='{%static "/css/bootstrap.min.css"%}' rel="stylesheet">
<link href='{%static "/css/narrow-jumbotron.css"%}' rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="/static/javascript/bootstrap.min.js"></script>
</code>```

Even after including these the navbar dropdown isn't working

```<code><nav>
   <ul class="nav nav-pills float-right">
     {% url 'home' as home %}
     {% url 'about' as about %}
     {% url 'about' as contact %}
     <li {% if request.path == home %} class="nav-item active" {% endif %}>
       <a class="nav-link" href="{% url 'home' %}">Home<span class="sr-only">(current)</span></a>
     </li>
     <li {% if request.path == about %}class="nav-item" {% endif %}>
       <a class="nav-link" href="{% url 'about' %}">About</a>
     </li>
     <li {% if request.path == contact %}class="nav-item" {% endif %}>
       <a class="nav-link" href="{% url 'contact' %}">Contact</a>
     </li>
     <li class="nav-item dropdown">
       <a class="nav-link dropdown-toggle" href="" id="dropdown01" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Account</a>
       <div class="dropdown-menu" aria-labelledby="dropdown01">
        {% if not request.user.is_authenticated %}
         <a class="dropdown-item" href="{% url 'account_login' %}">Login</a>
         <a class="dropdown-item" href="{% url 'account_signup' %}">SignUp</a>
         <a class="dropdown-item" href="{% url 'account_logout' %}">LogOut</a>
        {% endif %}
       </div>

     </li>

   </ul>
 </nav>
</code>```

答:
Try adding scripts in the following order.

```<code><script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
</code>```

Without adding popper.js, I was not able the dropdown.
I am still trying to know more about this.
As it was never the case in regular Bootstrap.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

      Home(current)

      About

      Contact

      Account

        Login
        SignUp
        LogOut

```

Body:
My navbar dropdown menu isn't working, I have included the following stylesheets and js files

<link href='{%static "/css/bootstrap.min.css"%}' rel="stylesheet">
<link href='{%static "/css/narrow-jumbotron.css"%}' rel="stylesheet">

Even after including these the navbar dropdown isn't working

     {% url 'home' as home %}
     {% url 'about' as about %}
     {% url 'about' as contact %}

       Home(current)

       About

       Contact

       Account

        {% if not request.user.is_authenticated %}
         Login
         SignUp
         LogOut
        {% endif %}

Body:
Try adding scripts in the following order.

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>

Without adding popper.js, I was not able the dropdown.
I am still trying to know more about this.
As it was never the case in regular Bootstrap.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>

<nav>
  <ul class="nav nav-pills float-right">
    <li {% if request.path==h ome %} class="nav-item active" {% endif %}>
      <a class="nav-link" href="{% url 'home' %}">Home<span class="sr-only">(current)</span></a>
    </li>
    <li {% if request.path==a bout %}class="nav-item" {% endif %}>
      <a class="nav-link" href="{% url 'about' %}">About</a>
    </li>
    <li {% if request.path==c ontact %}class="nav-item" {% endif %}>
      <a class="nav-link" href="{% url 'contact' %}">Contact</a>
    </li>
    <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" href="" id="dropdown01" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Account</a>
      <div class="dropdown-menu" aria-labelledby="dropdown01">
        <a class="dropdown-item" href="{% url 'account_login' %}">Login</a>
        <a class="dropdown-item" href="{% url 'account_signup' %}">SignUp</a>
        <a class="dropdown-item" href="{% url 'account_logout' %}">LogOut</a>
      </div>

    </li>

  </ul>
</nav>


问:
Using scroll view programmatically
I am trying to develop an app with the UI created only programmatically.
I want to create a simple view which is a UIScrollView (to be able to scroll the view when the keyboard is appearing) with a containerView (UIView) where we can find a button.

I am using PureLayout to make easier the set up of constraints, swift 4, Xcode 9.2 beta

Below the class of this view

```<code>class SimpleView: UIScrollView {

var containerView: UIView!
var signInButton: UIButton!
var signInLabel: UILabel!

var screenSize: CGSize = CGSize.zero

var shouldSetupConstraints = true

override init(frame: CGRect) {
    super.init(frame: frame)

    self.screenSize = frame.size

    self.containerView = UIView(frame: CGRect.zero)
    self.signInButton = UIButton(frame: CGRect.zero)
    self.signInLabel = UILabel(frame: CGRect.zero)

    self.addSubview(self.containerView)

    self.containerView.addSubview(self.signInButton)

    self.signInButton.addSubview(self.signInLabel)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func updateConstraints() {
    if(shouldSetupConstraints) {

        self.layoutSignInButton()
        self.layoutSignInLabel()

        shouldSetupConstraints = false
    }
    super.updateConstraints()

}

private func layoutContainerView() {
    self.containerView.autoPinEdgesToSuperviewEdges()
    self.containerView.backgroundColor = UIColor.yellow
}

private func layoutSignInButton() {
    self.signInButton.autoPinEdge(toSuperviewEdge: .right)
    self.signInButton.autoPinEdge(toSuperviewEdge: .left)
    self.signInButton.autoPinEdge(toSuperviewEdge: .top)
    self.signInButton.autoSetDimension(.height, toSize: 55.0)

    self.signInButton.backgroundColor = UIColor(hex: "#FD9FA2")
}

private func layoutSignInLabel() {
    self.signInLabel.autoPinEdgesToSuperviewEdges()

    self.signInLabel.shadowColor = UIColor(hex: "#9A615E")
    self.signInLabel.shadowOffset = CGSize(width: 0.0, height: 2)
    self.signInLabel.text = NSLocalizedString("SIGN IN", comment: "")
    self.signInLabel.textAlignment = .center
    self.signInLabel.textColor = UIColor.white
    self.signInLabel.font = UIFont.boldSystemFont(ofSize: 15.0)
    self.signInLabel.backgroundColor = UIColor.clear
}

}
</code>```

Below the code of the UIViewController subclass embedding the previous view

```<code>class SignInViewController: UIViewController {

var simpleView: SimpleView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.simpleView = SimpleView(frame: self.view.bounds) // with SimpleView(frame: self.view.frame) has the same behaviour
    self.view.addSubview(self.simpleView)

    self.simpleView.autoPinEdgesToSuperviewEdges()
    self.navigationController?.navigationBar.isHidden = true

}
}
</code>```

Unfortunatly the result is not the one expected : see below

What am I missing ?
Different points are missing:
 - The position of the button is weird (space between the button and the top / left side of the button partly hidden outside of the screen)
 - the container view is invisible (backgroundColor = UIColor.yellow has no effect)

Thank you by advance !

//////////////////////////// EDIT ////////////////////////////////

Below a screenshot of the exact same code using a UIView instead of UIScrollView

```<code>Class SimpleView: UIView {
</code>```

enter image description here

答:
The content of a UIScrollView must also define the .contentSize` of the scroll view.

I don't use PureLayout, so I don't know what the syntax is, but in your layoutContainerView() func, you need to also do:

```<code>self.containerView ... set width dimension to SuperviewWdith
</code>```

That will set the content of containerView to the width of the scroll view, and that should fix the width part.

I assume you will be adding elements to containerView and set their constraints to control the height of it.

Title: Using scroll view programmatically

Body:
I am trying to develop an app with the UI created only programmatically.
I want to create a simple view which is a UIScrollView (to be able to scroll the view when the keyboard is appearing) with a containerView (UIView) where we can find a button.

I am using PureLayout to make easier the set up of constraints, swift 4, Xcode 9.2 beta

Below the class of this view

class SimpleView: UIScrollView {

var containerView: UIView!
var signInButton: UIButton!
var signInLabel: UILabel!

var screenSize: CGSize = CGSize.zero

var shouldSetupConstraints = true

override init(frame: CGRect) {
    super.init(frame: frame)

    self.screenSize = frame.size

    self.containerView = UIView(frame: CGRect.zero)
    self.signInButton = UIButton(frame: CGRect.zero)
    self.signInLabel = UILabel(frame: CGRect.zero)

    self.addSubview(self.containerView)

    self.containerView.addSubview(self.signInButton)

    self.signInButton.addSubview(self.signInLabel)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func updateConstraints() {
    if(shouldSetupConstraints) {

        self.layoutSignInButton()
        self.layoutSignInLabel()

        shouldSetupConstraints = false
    }
    super.updateConstraints()

}

private func layoutContainerView() {
    self.containerView.autoPinEdgesToSuperviewEdges()
    self.containerView.backgroundColor = UIColor.yellow
}

private func layoutSignInButton() {
    self.signInButton.autoPinEdge(toSuperviewEdge: .right)
    self.signInButton.autoPinEdge(toSuperviewEdge: .left)
    self.signInButton.autoPinEdge(toSuperviewEdge: .top)
    self.signInButton.autoSetDimension(.height, toSize: 55.0)

    self.signInButton.backgroundColor = UIColor(hex: "#FD9FA2")
}

private func layoutSignInLabel() {
    self.signInLabel.autoPinEdgesToSuperviewEdges()

    self.signInLabel.shadowColor = UIColor(hex: "#9A615E")
    self.signInLabel.shadowOffset = CGSize(width: 0.0, height: 2)
    self.signInLabel.text = NSLocalizedString("SIGN IN", comment: "")
    self.signInLabel.textAlignment = .center
    self.signInLabel.textColor = UIColor.white
    self.signInLabel.font = UIFont.boldSystemFont(ofSize: 15.0)
    self.signInLabel.backgroundColor = UIColor.clear
}

}

Below the code of the UIViewController subclass embedding the previous view

class SignInViewController: UIViewController {

var simpleView: SimpleView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.simpleView = SimpleView(frame: self.view.bounds) // with SimpleView(frame: self.view.frame) has the same behaviour
    self.view.addSubview(self.simpleView)

    self.simpleView.autoPinEdgesToSuperviewEdges()
    self.navigationController?.navigationBar.isHidden = true

}
}

Unfortunatly the result is not the one expected : see below

What am I missing ?
Different points are missing:
 - The position of the button is weird (space between the button and the top / left side of the button partly hidden outside of the screen)
 - the container view is invisible (backgroundColor = UIColor.yellow has no effect)

Thank you by advance !

//////////////////////////// EDIT ////////////////////////////////

Below a screenshot of the exact same code using a UIView instead of UIScrollView

Class SimpleView: UIView {

enter image description here

Body:
The content of a UIScrollView must also define the .contentSize` of the scroll view.

I don't use PureLayout, so I don't know what the syntax is, but in your layoutContainerView() func, you need to also do:

self.containerView ... set width dimension to SuperviewWdith

That will set the content of containerView to the width of the scroll view, and that should fix the width part.

I assume you will be adding elements to containerView and set their constraints to control the height of it.


问:
Counting records in a SQL subquery
I'm having difficult with a subquery. In plain English I'm trying to pick a random userID from the QCUsers table that has less than 20 records from the QCTier1_Assignments table.  The problem is that my query below is only picking users where it meets the criteria of the inner query when I need it to pick any user from QCUsers table even if the user does not have any records at all in the QCTier1_Assignments table. I need something like this

AND (Sub.QCCount < 20 OR Sub.QCCount = 0 )

```<code>DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
E1.UserID
,Sub.QCCount --Drawn from the subquery
FROM QCUsers E1
JOIN (SELECT
  QCA.UserID,
  COUNT(*) AS QCCount
  FROM QCTier1_Assignments QCA
  WHERE QCA.ReviewPeriodMonth = @ReviewPeriodMonth
  AND QCA.ReviewPeriodYear = @ReviewPeriodYear
  GROUP BY QCA.UserID
  ) Sub
 ON E1.UserID = Sub.UserID
 WHERE Active = 1
  AND Grade = 12
  AND Sub.QCCount < 20
 ORDER BY NEWID()
</code>```

I also tried it this way with no luck

```<code>DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
E1.UserID
,Sub.QCCount --Drawn from the subquery
FROM QCUsers E1
RIGHT JOIN (SELECT
  QCA.UserID,
  ReviewPeriodMonth,
  ReviewPeriodYear,
  COUNT(*) AS QCCount
  FROM QCTier1_Assignments QCA
  GROUP BY
    QCA.UserID,
    ReviewPeriodMonth,
    ReviewPeriodYear
  ) Sub
ON E1.UserID = Sub.UserID
WHERE Active = 1
  AND Grade = 12
  AND Sub.QCCount < 20
  AND Sub.ReviewPeriodMonth = @ReviewPeriodMonth
  AND Sub.ReviewPeriodYear = @ReviewPeriodYear
ORDER BY NEWID()
</code>```

答:
Try using your second query but change the WHERE clause to use   COALESCE(Sub.QCCount, 0) instead of justSub.QCCount`

If the subquery returns no rows then with your RIGHT JOIN you'll at least still get the row, but the QCCount will be NULL which when compared to anything will result in a "false" effectively.

Also, you should look into the HAVING clause. It might allow you to do this without a subquery at all.

Here's an example with the HAVING clause. If it doesn't give the correct results please let me know as I'm not able to test this.

```<code>DECLARE
    @ReviewPeriodMonth VARCHAR(10) = '10'
    @ReviewPeriodYear  VARCHAR(10) = '2015'

SELECT TOP 1
    E1.UserID,
    COUNT(QCA.UserID) AS QCCount
FROM
    QCUsers E1
LEFT OUTER JOIN QCTier1_Assignments QCA ON
    QCA.UserID = E1.UserID AND
    QCA.ReviewPeriodMonth = @ReviewPeriodMonth AND
    QCA.ReviewPeriodYear = @ReviewPeriodYear
WHERE
    E1.Active = 1 AND
    Grade = 12 AND
HAVING
    COUNT(*) < 20
ORDER BY
    NEWID()
</code>```

Title: Counting records in a SQL subquery

Body:
I'm having difficult with a subquery. In plain English I'm trying to pick a random userID from the QCUsers table that has less than 20 records from the QCTier1_Assignments table.  The problem is that my query below is only picking users where it meets the criteria of the inner query when I need it to pick any user from QCUsers table even if the user does not have any records at all in the QCTier1_Assignments table. I need something like this

AND (Sub.QCCount < 20 OR Sub.QCCount = 0 )

DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
E1.UserID
,Sub.QCCount --Drawn from the subquery
FROM QCUsers E1
JOIN (SELECT
  QCA.UserID,
  COUNT(*) AS QCCount
  FROM QCTier1_Assignments QCA
  WHERE QCA.ReviewPeriodMonth = @ReviewPeriodMonth
  AND QCA.ReviewPeriodYear = @ReviewPeriodYear
  GROUP BY QCA.UserID
  ) Sub
 ON E1.UserID = Sub.UserID
 WHERE Active = 1
  AND Grade = 12
  AND Sub.QCCount < 20
 ORDER BY NEWID()

I also tried it this way with no luck

DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
E1.UserID
,Sub.QCCount --Drawn from the subquery
FROM QCUsers E1
RIGHT JOIN (SELECT
  QCA.UserID,
  ReviewPeriodMonth,
  ReviewPeriodYear,
  COUNT(*) AS QCCount
  FROM QCTier1_Assignments QCA
  GROUP BY
    QCA.UserID,
    ReviewPeriodMonth,
    ReviewPeriodYear
  ) Sub
ON E1.UserID = Sub.UserID
WHERE Active = 1
  AND Grade = 12
  AND Sub.QCCount < 20
  AND Sub.ReviewPeriodMonth = @ReviewPeriodMonth
  AND Sub.ReviewPeriodYear = @ReviewPeriodYear
ORDER BY NEWID()

Body:
Try using your second query but change the WHERE clause to use   COALESCE(Sub.QCCount, 0) instead of justSub.QCCount`

If the subquery returns no rows then with your RIGHT JOIN you'll at least still get the row, but the QCCount will be NULL which when compared to anything will result in a "false" effectively.

Also, you should look into the HAVING clause. It might allow you to do this without a subquery at all.

Here's an example with the HAVING clause. If it doesn't give the correct results please let me know as I'm not able to test this.

DECLARE
    @ReviewPeriodMonth VARCHAR(10) = '10'
    @ReviewPeriodYear  VARCHAR(10) = '2015'

SELECT TOP 1
    E1.UserID,
    COUNT(QCA.UserID) AS QCCount
FROM
    QCUsers E1
LEFT OUTER JOIN QCTier1_Assignments QCA ON
    QCA.UserID = E1.UserID AND
    QCA.ReviewPeriodMonth = @ReviewPeriodMonth AND
    QCA.ReviewPeriodYear = @ReviewPeriodYear
WHERE
    E1.Active = 1 AND
    Grade = 12 AND
HAVING
    COUNT(*) < 20
ORDER BY
    NEWID()


答:
Try doing a null check before the subract operation. something like

if @pdform.date_finish.present && @pdform.done_start.present && //your opertaion

It clearly states you have a nil error

Title: Rails subtract datepicker dates

Body:
I switched from date_select to jQuery UI Datepicker and when I am trying to subtract the dates to get the number of days between those days I am getting the following error.

The date format for date_select is year/month/day however the format for the jQuery Datepicker is month/day/year. How can I combat this issue and still use Datepicker?


问:
dyld: Library not loaded: @rpath/libswiftCore.dylib
I am getting this issue in my existing project and i tried to create new project then i run in device getting same issue

```<code>    dyld: Library not loaded: @rpath/libswiftCore.dylib
      Referenced from: /var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Pro
Reason: no suitable image found.  Did find:
    /private/var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Frameworks/libswiftCore.dylib: mmap() errno=1 validating first page of '/private/var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Frameworks/libswiftCore.dylib'
</code>```

some of the answer i tired but still getting same issue

dyld: Library not loaded: @rpath/libswiftCore.dylib

答:
For me Following steps helped me:

1.Delete your app from device

2.From  "TARGET">"Build Settings">"Runpath Search Paths" ^ then check for values "$(inherited)" & "@executable_path/Frameworks", Feel free to add incase they dont exist

Build your app and run it on device

Body:
I am getting this issue in my existing project and i tried to create new project then i run in device getting same issue

    dyld: Library not loaded: @rpath/libswiftCore.dylib
      Referenced from: /var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Pro
Reason: no suitable image found.  Did find:
    /private/var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Frameworks/libswiftCore.dylib: mmap() errno=1 validating first page of '/private/var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Frameworks/libswiftCore.dylib'

some of the answer i tired but still getting same issue

dyld: Library not loaded: @rpath/libswiftCore.dylib


问:
How do I rerequest Facebook permissions in Meteor?
According to this:

https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.2#re-asking-declined-permissions

I add auth_type: 'rerequest' to the login call, but there is no option for that under Accounts.loginWith<ExternalService>. Is there a way to do it with accounts-facebook or any other package?

答: Accounts.loginWithFacebook({ auth_type: 'rerequest' })


问:
CSS style effect involving z-index and transparency
I'm trying to achieve a design close to the snippet here. My problem is that I can't find a way to replace the blue background of .title by a simple transparency (so that the container's background stays visible). If I simply remove the blue background, the border becomes visible where .title is.

Also the "title" is generated by JS so I can't reliably predict the length of div as it may slightly vary depending on the situation.

.container {
  width: 350px;
  height: 250px;
  display: flex;
 justify-content: center;
 align-items: center;
  position: relative;
  background: url('https://i.pinimg.com/736x/94/90/19/9490199f30fc9db039de091205e73be6--backgrounds-wallpapers-phone-backgrounds.jpg');
}

.zone {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  margin: 0 0 20px 0;
  text-align: center;
}

.title {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  position: absolute;
 top: 0;
 left: 0;
 right: 0;
 z-index: 10;
}

.title span {
  display: inline-flex;
 align-items: center;
 justify-content: center;
 padding: 0 10px;
 height: 20px;
 color: hsla(200, 70%, 20%, 1);
 cursor: default;
 background: hsla(200, 70%, 55%, 1);
}

.content {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  padding: 30px 30px 20px 30px;
 width: 200px;
 border: 0.1rem solid hsla(200, 70%, 20%, 1);
 border-radius: 0rem;
 margin-top: 10px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="zone">
    <div class="title">
      <span>Text Title</span>
    </div>
    <div class="content"></div>
  </div>
</div></code>```

Does anyone have an idea how to achieve what I'm trying to do ? Please let me know if my explanation is too brief or unclear.

Thank you !

答:
You can get the desired effect by adding more elements

.container {
  width: 350px;
  height: 250px;
  display: flex;
 justify-content: center;
 align-items: center;
  position: relative;
  background: url('https://i.pinimg.com/736x/94/90/19/9490199f30fc9db039de091205e73be6--backgrounds-wallpapers-phone-backgrounds.jpg');
}

.zone {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  margin: 0 0 20px 0;
  text-align: center;
}

.title {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  position: absolute;
 top: 0;
 left: 0;
 right: 0;
 z-index: 10;
}

.title__text {
  flex: 0 0 auto;
 padding: 0 10px;
 height: 20px;
 color: hsla(200, 70%, 20%, 1);
 cursor: default;
/*  background: hsla(200, 70%, 55%, 1); */
}

.title__border {
  flex: 1;
  border-top: 0.1rem solid hsla(200, 70%, 20%, 1);
}

.content {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  padding: 30px 30px 20px 30px;
 width: 200px;
 border: 0.1rem solid hsla(200, 70%, 20%, 1);
  border-top: 0.1rem solid transparent;
 border-radius: 0rem;
 margin-top: 10px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="zone">
    <div class="title">
      <span class='title__border'></span>
      <span class='title__text'>Text Title</span>
      <span class='title__border'></span>
    </div>
    <div class="content"></div>
  </div>
</div></code>```

And don't use selectors like .title span. They do not target specific element and styles used by them cannot be reused somewhere else, which means excessive code duplication. Element selectors (like .title span) are also likely to cause problems (you are selecting all spans in .title element) whenever you change your code (adding another span with different styles is hard), which means even more duplicated code! Duplicated code = more complex code = code that is harder to maintain!

You should get BEM or SMACSS or any other methodology (you may even create your own).

Body:
I'm trying to achieve a design close to the snippet here. My problem is that I can't find a way to replace the blue background of .title by a simple transparency (so that the container's background stays visible). If I simply remove the blue background, the border becomes visible where .title is.

Also the "title" is generated by JS so I can't reliably predict the length of div as it may slightly vary depending on the situation.

.container {
  width: 350px;
  height: 250px;
  display: flex;
 justify-content: center;
 align-items: center;
  position: relative;
  background: url('https://i.pinimg.com/736x/94/90/19/9490199f30fc9db039de091205e73be6--backgrounds-wallpapers-phone-backgrounds.jpg');
}

.zone {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  margin: 0 0 20px 0;
  text-align: center;
}

.title {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  position: absolute;
 top: 0;
 left: 0;
 right: 0;
 z-index: 10;
}

.title span {
  display: inline-flex;
 align-items: center;
 justify-content: center;
 padding: 0 10px;
 height: 20px;
 color: hsla(200, 70%, 20%, 1);
 cursor: default;
 background: hsla(200, 70%, 55%, 1);
}

.content {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  padding: 30px 30px 20px 30px;
 width: 200px;
 border: 0.1rem solid hsla(200, 70%, 20%, 1);
 border-radius: 0rem;
 margin-top: 10px;
 }

      Text Title

Does anyone have an idea how to achieve what I'm trying to do ? Please let me know if my explanation is too brief or unclear.

Thank you !

Body:
You can get the desired effect by adding more elements

.container {
  width: 350px;
  height: 250px;
  display: flex;
 justify-content: center;
 align-items: center;
  position: relative;
  background: url('https://i.pinimg.com/736x/94/90/19/9490199f30fc9db039de091205e73be6--backgrounds-wallpapers-phone-backgrounds.jpg');
}

.zone {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  margin: 0 0 20px 0;
  text-align: center;
}

.title {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  position: absolute;
 top: 0;
 left: 0;
 right: 0;
 z-index: 10;
}

.title__text {
  flex: 0 0 auto;
 padding: 0 10px;
 height: 20px;
 color: hsla(200, 70%, 20%, 1);
 cursor: default;
/*  background: hsla(200, 70%, 55%, 1); */
}

.title__border {
  flex: 1;
  border-top: 0.1rem solid hsla(200, 70%, 20%, 1);
}

.content {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  padding: 30px 30px 20px 30px;
 width: 200px;
 border: 0.1rem solid hsla(200, 70%, 20%, 1);
  border-top: 0.1rem solid transparent;
 border-radius: 0rem;
 margin-top: 10px;
 }

<div class="container">
  <div class="zone">
    <div class="title">
      <span class='title__border'></span>
      <span class='title__text'>Text Title</span>
      <span class='title__border'></span>
    </div>
    <div class="content"></div>
  </div>
</div>

And don't use selectors like .title span. They do not target specific element and styles used by them cannot be reused somewhere else, which means excessive code duplication. Element selectors (like .title span) are also likely to cause problems (you are selecting all spans in .title element) whenever you change your code (adding another span with different styles is hard), which means even more duplicated code! Duplicated code = more complex code = code that is harder to maintain!

You should get BEM or SMACSS or any other methodology (you may even create your own).


问:
3D figures from Matplotlib visibility of pane edge
I am not able to get the left pane edge visible.

%pylab inline
from mpl_toolkits.mplot3d import axes3d
rcdefaults()

x, y = meshgrid(linspace(-10, 10, 100), linspace(-10, 10, 100))
z = x**2+y**2

fig = figure(figsize=[16, 9])
ax3D = fig.add_subplot(111, projection='3d')
ax3D.plot_surface(x, y, z, rstride=8, cstride=8, alpha=0.3, cmap='hot')
ax3D.contour(x, y, z, zdir='x', offset=ax3D.get_xlim()[0])
ax3D.contour(x, y, z, zdir='y', offset=ax3D.get_ylim()[1])
ax3D.contour(x, y, z, zdir='z', offset=ax3D.get_zlim()[0])
ax3D.xaxis.pane.set_edgecolor('#000000')
ax3D.yaxis.pane.set_edgecolor('#000000')
ax3D.zaxis.pane.set_edgecolor('#000000')
ax3D.xaxis.pane.set_alpha(1)
ax3D.yaxis.pane.set_alpha(1)
ax3D.zaxis.pane.set_alpha(1)
ax3D.xaxis.pane.fill = False
ax3D.yaxis.pane.fill = False
ax3D.zaxis.pane.fill = False
fig.savefig('test')
```

<p><img src="https://i.stack.imgur.com/4gX6D.png" alt="enter image description here"></p>

<p>An unsatisfactory workaround is to put a labeled ax on this particular pane edge by inverting the x and y axis:</p>

<pre class="lang-py prettyprint-override"><code>ax3D.invert_yaxis()
ax3D.invert_xaxis()
</code>```

A better workaround using a Poly3DCollection line patch almost does it. Except that the retrieved limits don't seem quite right.

from mpl_toolkits.mplot3d import art3d

i = array([ax3D.get_xlim3d()[0], ax3D.get_ylim3d()[0], ax3D.get_zlim3d()[0]])
f = array([ax3D.get_xlim3d()[0], ax3D.get_ylim3d()[0], ax3D.get_zlim3d()[1]])
p = art3d.Poly3DCollection(array([[i, f]]))
p.set_color('black')
ax3D.add_collection3d(p)
```

答:
So here is my somewhat hacky answer or better said workaround for this problem:

%pylab inline
%matplotlib notebook
%matplotlib notebook
from mpl_toolkits.mplot3d import axes3d, art3d
rcdefaults()

x, y = meshgrid(linspace(-10, 10, 100), linspace(-10, 10, 100))
z = x**2+y**2

fig = figure()
ax3D = fig.add_subplot(111, projection='3d')
ax3D.plot_surface(x, y, z, rstride=8, cstride=8, alpha=0.3, cmap='hot')

def lims(mplotlims):
    scale = 1.021
    offset = (mplotlims[1] - mplotlims[0])*scale
    return mplotlims[1] - offset, mplotlims[0] + offset
xlims, ylims, zlims = lims(ax3D.get_xlim()), lims(ax3D.get_ylim()), lims(ax3D.get_zlim())
ax3D.contour(x, y, z, zdir='x', offset=xlims[0])
ax3D.contour(x, y, z, zdir='y', offset=ylims[1])
ax3D.contour(x, y, z, zdir='z', offset=zlims[0])
i = array([xlims[0], ylims[0], zlims[0]])
f = array([xlims[0], ylims[0], zlims[1]])
p = art3d.Poly3DCollection(array([[i, f]]))
p.set_color('black')
ax3D.add_collection3d(p)

ax3D.xaxis.pane.set_edgecolor('#000000')
ax3D.yaxis.pane.set_edgecolor('#000000')
ax3D.zaxis.pane.set_edgecolor('#000000')
ax3D.xaxis.pane.set_alpha(1)
ax3D.yaxis.pane.set_alpha(1)
ax3D.zaxis.pane.set_alpha(1)
ax3D.xaxis.pane.fill = False
ax3D.yaxis.pane.fill = False
ax3D.zaxis.pane.fill = False
fig.tight_layout()
show()
```

Body:
I am not able to get the left pane edge visible.

%pylab inline
from mpl_toolkits.mplot3d import axes3d
rcdefaults()

x, y = meshgrid(linspace(-10, 10, 100), linspace(-10, 10, 100))
z = x**2+y**2

fig = figure(figsize=[16, 9])
ax3D = fig.add_subplot(111, projection='3d')
ax3D.plot_surface(x, y, z, rstride=8, cstride=8, alpha=0.3, cmap='hot')
ax3D.contour(x, y, z, zdir='x', offset=ax3D.get_xlim()[0])
ax3D.contour(x, y, z, zdir='y', offset=ax3D.get_ylim()[1])
ax3D.contour(x, y, z, zdir='z', offset=ax3D.get_zlim()[0])
ax3D.xaxis.pane.set_edgecolor('#000000')
ax3D.yaxis.pane.set_edgecolor('#000000')
ax3D.zaxis.pane.set_edgecolor('#000000')
ax3D.xaxis.pane.set_alpha(1)
ax3D.yaxis.pane.set_alpha(1)
ax3D.zaxis.pane.set_alpha(1)
ax3D.xaxis.pane.fill = False
ax3D.yaxis.pane.fill = False
ax3D.zaxis.pane.fill = False
fig.savefig('test')

An unsatisfactory workaround is to put a labeled ax on this particular pane edge by inverting the x and y axis:

ax3D.invert_yaxis()
ax3D.invert_xaxis()

A better workaround using a Poly3DCollection line patch almost does it. Except that the retrieved limits don't seem quite right.

from mpl_toolkits.mplot3d import art3d

i = array([ax3D.get_xlim3d()[0], ax3D.get_ylim3d()[0], ax3D.get_zlim3d()[0]])
f = array([ax3D.get_xlim3d()[0], ax3D.get_ylim3d()[0], ax3D.get_zlim3d()[1]])
p = art3d.Poly3DCollection(array([[i, f]]))
p.set_color('black')
ax3D.add_collection3d(p)


问:
Issues with Sending Web Push Notifications
I am having some issues figuring out how to send the actual notification.  I have been through several step by step tutorials and am able to get those to work within the browser I am working on, however, none explain how to install the web push library for PHP or how to send the actual notification to a specific endpoint.  Does anyone have a tutorial explaining how to install the web push library for PHP or how to send the notification once the user is subscribed?

I have gone through Google's codelab for adding Push Notifications to a Web App and was able to get it to work, however, it doesn't explain how it works on the back end.

I also went through Mozilla's Web Push demos, however, still very vague when it comes to sending the notification to specific users.

答:
You can set up push notifications without developing your own app using notify.pm. It takes around 2 lines of code, the API is here:
https://github.com/notifypm/notifypm-php-api</p>

```<code><?php

require_once("notifypm.class.php");

$n = new Notifypm('email', 'password', '.pmNumber');
$n->push('Message!', 'Link (optional)!');

$n->disconnect();
</code>```

Body:
You can set up push notifications without developing your own app using notify.pm. It takes around 2 lines of code, the API is here:
https://github.com/notifypm/notifypm-php-api

<?php

require_once("notifypm.class.php");

$n = new Notifypm('email', 'password', '.pmNumber');
$n->push('Message!', 'Link (optional)!');

$n->disconnect();


问:
Can I ReadLock a file while I create/modify it using System.IO.File.WriteAllText() method?
I need to create a process that creates/modifies some text files in a folder. I am using below code to do that:

```<code>file = new System.IO.FileInfo(filePath);
file.Directory.Create();
System.IO.File.WriteAllText(file.FullName, "Some text...");
</code>```

I have a Biztalk queue that looks into the text files in the folder every 2 minutes and picks up the files to process them. I want to lock the files when I am creating/modifying so that Biztalk wont try to process those files. How can I achieve this?

I read about Transactional NTFS in windows which will let me create Transaction context but windows documentation says this feature will deprecated and recommends not to use it.

答:
If the file is on a local NTFS volume of CIFS share, the File Adapter will not attempt to read an open file.  However,

A better pattern would be to do your file work in a temporary folder, then copy the completed files to the BizTalk folder only when they are done.  That way, you don't have to worry about locking at all.

Body:
I need to create a process that creates/modifies some text files in a folder. I am using below code to do that:

file = new System.IO.FileInfo(filePath);
file.Directory.Create();
System.IO.File.WriteAllText(file.FullName, "Some text...");

I have a Biztalk queue that looks into the text files in the folder every 2 minutes and picks up the files to process them. I want to lock the files when I am creating/modifying so that Biztalk wont try to process those files. How can I achieve this?

I read about Transactional NTFS in windows which will let me create Transaction context but windows documentation says this feature will deprecated and recommends not to use it.


问:
When does this self-modifying program for an accumulator architecture terminate?
I have this machine code for an accumulator architecture.
The architecture is eight-bit; the instruction encoding looks like
the real machine code is for instruction one for example is : 001 1 0001, 001 means LOAD, 1 tells us that is a value, and 001 is the decimal 1 so its LOAD #1

```<code>0---LOAD #1
1---STORE 15
2---LOAD #0
3---EQUAL #4
4---JUMP #6
5---HALT
6---LOAD 3
7---SUB #1
8---STORE 3
9---LOAD 15
10--ADD 15
11--STORE 15
12--JUMP #2
13-- 000 0 0000
14-- 000 0 0000
15-- 000 0 0000
</code>```

I have to find what will be in memory cell 15 when the program stops.

But if you jump to instruction 2, this means that accumulator would have the value 0 which will never be equal to 4 and the program will just run as endless loop, right?

And what does the STORE 3 do, if memory cell 3 is empty? Does it mean that when a memory cell is empty its value is number 0?

I cannot proceed more without answering these two questions

答:
I'm assuming that this is for a n accumulator architecture, and I'm having to make a number of assumptions about that architecture.  You really need to describe more of how your CPU works to make this an answerable question.

Yes, at #3, the accumulator will always be 0.
And yes, if instruction #3 never changes, then 0 will never equal 4 and the program will loop for ever.

However, when you store to memory cell 3, I wthink that you end up replacing the instruction at cell 3 with what is in the accumulator now.
So, the interesting question is what happens when you subtract 1 from the instruction representation of equal #4.
That depends on yoru specific architecture, but my strong guess is that you get equal #3 and store that in cell 3.

That should be enough for you to walk through and figure out when your loop terminates and what is in cell 15.

Body:
I have this machine code for an accumulator architecture.
The architecture is eight-bit; the instruction encoding looks like
the real machine code is for instruction one for example is : 001 1 0001, 001 means LOAD, 1 tells us that is a value, and 001 is the decimal 1 so its LOAD #1

0---LOAD #1
1---STORE 15
2---LOAD #0
3---EQUAL #4
4---JUMP #6
5---HALT
6---LOAD 3
7---SUB #1
8---STORE 3
9---LOAD 15
10--ADD 15
11--STORE 15
12--JUMP #2
13-- 000 0 0000
14-- 000 0 0000
15-- 000 0 0000

I have to find what will be in memory cell 15 when the program stops.

But if you jump to instruction 2, this means that accumulator would have the value 0 which will never be equal to 4 and the program will just run as endless loop, right?

And what does the STORE 3 do, if memory cell 3 is empty? Does it mean that when a memory cell is empty its value is number 0?

I cannot proceed more without answering these two questions


问:
generic type interface cast to a specific interface
How can you cast an interface with a generic type to a common interface?

Lets say we have the following interfaces/objects:

```<code>public interface IAction : IAction<object> { }
public interface IAction<T>
{
    T PerformAction();
}
public class SomeAction : IAction<string>
{
    public string PerformAction()
    {
        return "some action result value";
    }
}
public class OtherAction : IAction<int>
{
    public int PerformAction()
    {
        return 100;
    }
}
</code>```

Then if we try to code it in a console application:

```<code>List<IAction> actions = new List<IAction>();
actions.Add(new SomeAction());
actions.Add(new OtherAction());
actions.ForEach(e => Console.WriteLine(e.PerformAction()));
</code>```

How can we work around the error "cannot convert from 'SomeAction' to 'IAction'"?

答:
Your inheritance hierarchy does not make sense, you should have IAction<T> extend IAction and not the other way around.

You also need to add any common methods you want to call to IAction and, if the methods have the same name and parameters, implement them using an explicit interface implementation. It is on the common interface implementation you will be calling the method.

```<code>public interface IAction
{
    object PerformAction();
}
public interface IAction<T> : IAction
{
    new T PerformAction();
}
public class SomeAction : IAction<string>
{
    object IAction.PerformAction()
    {
        return PerformAction();
    }

    public string PerformAction()
    {
        return "some action result value";
    }
}
public class OtherAction : IAction<int>
{
    object IAction.PerformAction()
    {
        return PerformAction();
    }
    public int PerformAction()
    {
        return 100;
    }
}
</code>```

Calling code

```<code>List<IAction> actions = new List<IAction>();
actions.Add(new SomeAction());
actions.Add(new OtherAction());
actions.ForEach(e => Console.WriteLine(e.PerformAction()));
</code>```

Body:
How can you cast an interface with a generic type to a common interface?

Lets say we have the following interfaces/objects:

public interface IAction : IAction<object> { }
public interface IAction<T>
{
    T PerformAction();
}
public class SomeAction : IAction<string>
{
    public string PerformAction()
    {
        return "some action result value";
    }
}
public class OtherAction : IAction<int>
{
    public int PerformAction()
    {
        return 100;
    }
}

Then if we try to code it in a console application:

List<IAction> actions = new List<IAction>();
actions.Add(new SomeAction());
actions.Add(new OtherAction());
actions.ForEach(e => Console.WriteLine(e.PerformAction()));

How can we work around the error "cannot convert from 'SomeAction' to 'IAction'"?

Body:
Your inheritance hierarchy does not make sense, you should have IAction<T> extend IAction and not the other way around.

You also need to add any common methods you want to call to IAction and, if the methods have the same name and parameters, implement them using an explicit interface implementation. It is on the common interface implementation you will be calling the method.

public interface IAction
{
    object PerformAction();
}
public interface IAction<T> : IAction
{
    new T PerformAction();
}
public class SomeAction : IAction<string>
{
    object IAction.PerformAction()
    {
        return PerformAction();
    }

    public string PerformAction()
    {
        return "some action result value";
    }
}
public class OtherAction : IAction<int>
{
    object IAction.PerformAction()
    {
        return PerformAction();
    }
    public int PerformAction()
    {
        return 100;
    }
}

Calling code

List<IAction> actions = new List<IAction>();
actions.Add(new SomeAction());
actions.Add(new OtherAction());
actions.ForEach(e => Console.WriteLine(e.PerformAction()));


问:
Python / Pandas - get_group that has partial string
I have a dataframe like this:

```<code>name   . profession
Alex   . Data Analyst
Markus . Sales Manager
Carlos . Credit Analyst
Otavio . HR Manager
...
</code>```

I need to know how many people in this dataframe has the string "Analyst" in its profession. The answer should be 2.

I'm trying to use groupby and get_group, however I'm not finding the right way to put that into the get_group syntax.

Right now I'm here:

```<code>df.groupby('profession').get_group(???).agg('count')
</code>```

Can someone advise what would be the right syntax or suggest another way to do it?

答:
If you want the scalar answer, you can use this command:

```<code>df.profession.str.contains('Analyst').sum()
</code>```

Output:

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

Or as a dataframe with groupby:

```<code>df.assign(is_analyst = df.profession.str.contains('Analyst'))\
  .groupby('is_analyst')['name']\
  .size()
</code>```

Output:

```<code>is_analyst
False    2
True     2
Name: name, dtype: int64
</code>```

Body:
I have a dataframe like this:

name   . profession
Alex   . Data Analyst
Markus . Sales Manager
Carlos . Credit Analyst
Otavio . HR Manager
...

I need to know how many people in this dataframe has the string "Analyst" in its profession. The answer should be 2.

I'm trying to use groupby and get_group, however I'm not finding the right way to put that into the get_group syntax.

Right now I'm here:

df.groupby('profession').get_group(???).agg('count')

Can someone advise what would be the right syntax or suggest another way to do it?

Body:
If you want the scalar answer, you can use this command:

df.profession.str.contains('Analyst').sum()

Output:

2

Or as a dataframe with groupby:

df.assign(is_analyst = df.profession.str.contains('Analyst'))\
  .groupby('is_analyst')['name']\
  .size()

Output:

is_analyst
False    2
True     2
Name: name, dtype: int64