问:
RegEx for a conditional pattern in a string
I need to extract substrings from some strings,for example:
My data is a vector: c("Shigella dysenteriae","PREDICTED: Ceratitis")

```<code>a = "Shigella dysenteriae"

b = "PREDICTED: Ceratitis"
</code>```

I hope that if the string starts with "PREDICTED:", it can be extracted to the subsequent word(maybe "Ceratitis"), and if the string doesn't start with "PREDICTED", it can be extracted to the first word(maybe Shigella);

In this example, the result would be:

```<code>result_of_a = "Shigella"

result_of_b = "Ceratitis"
</code>```

Well,it is a typical conditional regular expression.I tried,but always failed;

I used R which can compatible perl's regular expression.

I know R supports perl's regular expression so I tried to use regexpr and regmatches, two functions to extract the substrings that I want.

The code  is :

```<code>
pattern = "(?<=PREDICTED:)?(?(1)(\\s+\\w+\\b)|(\\w+\\b))"

a = c("Shigella dysenteriae")
m_a = regexpr(pattern,a,perl = TRUE)
result_a = regmatches(a,m_a)

b = c("PREDICTED: Ceratitis")
m_b = regexpr(pattern,a,perl = TRUE)
result_b = regmatches(b,m_b)
</code>```

Finaly,the result is :

```<code># result_a = "Shigella"
# result_b = "PREDICTED"
</code>```

It is not the result I expect,result_a is right,result_b is wrong.

WHY???Its seem that the condition didn't work...

PS:
   I tried to read some details of conditional reg-expresstion. this is the web I tried to read : https://www.regular-expressions.info/conditional.html and I try to imitate "pattern" from this web ,and also tried to use "RegexBuddy" software to find the reason.

答:
EDIT:
To use the function below on a vector, one can do:
Vector: myvec<-c("Shigella dysenteriae","PREDICTED: Ceratitis")

```<code>lapply(myvec,extractor)
[[1]]
[1] "Shigella"

[[2]]
[1] "Ceratitis"
</code>```

Or:

```<code>unlist(lapply(myvec,extractor))
[1] "Shigella"  "Ceratitis"
</code>```

This assumes that the strings are always in the format shown above:

```<code>extractor<- function(string){
if(grepl("^PREDICTED",string)){
  strsplit(string,": ")[[1]][2]
}
  else{
    strsplit(string," ")[[1]][1]
  }

}
 extractor(b)
 #[1] "Ceratitis"
 extractor(a)
 #[1] "Shigella"
</code>```

Body:
I need to extract substrings from some strings,for example:
My data is a vector: c("Shigella dysenteriae","PREDICTED: Ceratitis")

a = "Shigella dysenteriae"

b = "PREDICTED: Ceratitis"

I hope that if the string starts with "PREDICTED:", it can be extracted to the subsequent word(maybe "Ceratitis"), and if the string doesn't start with "PREDICTED", it can be extracted to the first word(maybe Shigella);

In this example, the result would be:

result_of_a = "Shigella"

result_of_b = "Ceratitis"

Well,it is a typical conditional regular expression.I tried,but always failed;

I used R which can compatible perl's regular expression.

I know R supports perl's regular expression so I tried to use regexpr and regmatches, two functions to extract the substrings that I want.

The code  is :

pattern = "(?<=PREDICTED:)?(?(1)(\\s+\\w+\\b)|(\\w+\\b))"

a = c("Shigella dysenteriae")
m_a = regexpr(pattern,a,perl = TRUE)
result_a = regmatches(a,m_a)

b = c("PREDICTED: Ceratitis")
m_b = regexpr(pattern,a,perl = TRUE)
result_b = regmatches(b,m_b)

Finaly,the result is :

# result_a = "Shigella"
# result_b = "PREDICTED"

It is not the result I expect,result_a is right,result_b is wrong.

WHY???Its seem that the condition didn't work...

PS:
   I tried to read some details of conditional reg-expresstion. this is the web I tried to read : https://www.regular-expressions.info/conditional.html and I try to imitate "pattern" from this web ,and also tried to use "RegexBuddy" software to find the reason.

Body:
EDIT:
To use the function below on a vector, one can do:
Vector: myvec<-c("Shigella dysenteriae","PREDICTED: Ceratitis")

lapply(myvec,extractor)
[[1]]
[1] "Shigella"

[[2]]
[1] "Ceratitis"

Or:

unlist(lapply(myvec,extractor))
[1] "Shigella"  "Ceratitis"

This assumes that the strings are always in the format shown above:

extractor<- function(string){
if(grepl("^PREDICTED",string)){
  strsplit(string,": ")[[1]][2]
}
  else{
    strsplit(string," ")[[1]][1]
  }

}
 extractor(b)
 #[1] "Ceratitis"
 extractor(a)
 #[1] "Shigella"


来源: stackexchange

问:
Volume Mounting in local OSX gitlab-runner for exec docker
I'm trying to test my gitlab-ci.yml file by running the jobs through gitlab-runner on my laptop (OSX).  The yml looks like

```<code>image: ruby:2.2
start:
  script:
  - echo "made it"
</code>```

The executor is docker. I've tried:

```<code>gitlab-runner --debug exec docker start
gitlab-runner --debug exec docker --docker-volumes /users/Shared/Sites/Werk/werk-mailer:/users/Shared/Sites/Werk/werk-mailer
</code>```

And a many other paths and flags, but no luck.  I keep getting this message:

```<code>ERROR: Job failed (system failure): Error response from daemon: Mounts denied:
The path /users/Shared/Sites/Werk/werk-mailer
is not shared from OS X and is not known to Docker.
You can configure shared paths from Docker -> Preferences... -> File Sharing.
See https://docs.docker.com/docker-for-mac/osxfs/#namespaces for more info.
</code>```

答: An alternative fix for a related problem, although it doesn't seem to be apparent from the initial question: I found that Docker tried to locate a folder all in lower case. Docker runs linux, which is case sensitive, whereas MacOS's file system is not case sensitive :/ I simply created a new self-owned directory /development (sudo mkdir /development && sudo chown {username}:staff /development) and symlinked my project's folder there (cd /development && ln -s {path to project}) and added /development to the list of folders Docker for macOS has access to. Running the gitlab runner from that point worked for me.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to test my gitlab-ci.yml file by running the jobs through gitlab-runner on my laptop (OSX).  The yml looks like

image: ruby:2.2
start:
  script:
  - echo "made it"

The executor is docker. I've tried:

gitlab-runner --debug exec docker start
gitlab-runner --debug exec docker --docker-volumes /users/Shared/Sites/Werk/werk-mailer:/users/Shared/Sites/Werk/werk-mailer

And a many other paths and flags, but no luck.  I keep getting this message:

ERROR: Job failed (system failure): Error response from daemon: Mounts denied:
The path /users/Shared/Sites/Werk/werk-mailer
is not shared from OS X and is not known to Docker.
You can configure shared paths from Docker -> Preferences... -> File Sharing.
See https://docs.docker.com/docker-for-mac/osxfs/#namespaces for more info.

ContentLicense: CC BY-SA 4.0


问:
How do you add two Class Member Functions together with another function inside the same class?

I have two functions in my class, we'll say:

```<code>double MyClass::FunctionOne() {
    double Number = 1.5;
    return Number;
}
</code>```

and

```<code>double MyClass::FunctionTwo(double x, double y, double z, double w) {
    total = x+y+z+w;
    return total;
}
</code>```

assume that "total" is a double declared in the class header

How exactly do I add the returned values of both of these functions after my object has been instantiated in main?

In main, we'll assume it looks like this:

```<code>MyClass Object();
std::cout << "Function One: " << Object.FunctionOne()
          << "Function Two: " << Object.FunctionTwo(1.1, 2.2, 3.3, 4.4);
</code>```

Is there a way to sum these two functions in a separate function inside the class? And then call it using an accessor or something? Or must I do it like this:

```<code>double CombineFunctions(double x, double y) {
    double total2 = (x + y);
    return total2;
}

std::cout << "Sum of both functions: "
<< CombineFunctions(Object.FunctionOne(), Object.FunctionTwo(1.1, 2.2, 3.3, 4.4));
</code>```

I'm fairly new at C++, so I don't actually know how to do this. I tried researching for a few hours but couldn't really find anything or wrap my head around it.

What I've tried: The closest I've got was declaring two variables in the class, then using them inside the class functions, and attempting to return them as:

```<code>double MyClass::SumOfReturns() {
    return total1 + total2;
}
</code>```

but the number I received was what I think was a memory location? 163423e19 or something.

答:
In the header of your class you can add sunch a function:</p>

```<code>inline double MyClass::SumOfReturns() {
    return function1() + total;
}
</code>```

Body:
I have two functions in my class, we'll say:

double MyClass::FunctionOne() {
    double Number = 1.5;
    return Number;
}

and

double MyClass::FunctionTwo(double x, double y, double z, double w) {
    total = x+y+z+w;
    return total;
}

assume that "total" is a double declared in the class header

How exactly do I add the returned values of both of these functions after my object has been instantiated in main?

In main, we'll assume it looks like this:

MyClass Object();
std::cout << "Function One: " << Object.FunctionOne()
          << "Function Two: " << Object.FunctionTwo(1.1, 2.2, 3.3, 4.4);

Is there a way to sum these two functions in a separate function inside the class? And then call it using an accessor or something? Or must I do it like this:

double CombineFunctions(double x, double y) {
    double total2 = (x + y);
    return total2;
}

std::cout << "Sum of both functions: "
<< CombineFunctions(Object.FunctionOne(), Object.FunctionTwo(1.1, 2.2, 3.3, 4.4));

I'm fairly new at C++, so I don't actually know how to do this. I tried researching for a few hours but couldn't really find anything or wrap my head around it.

What I've tried: The closest I've got was declaring two variables in the class, then using them inside the class functions, and attempting to return them as:

double MyClass::SumOfReturns() {
    return total1 + total2;
}

but the number I received was what I think was a memory location? 163423e19 or something.

Body:
In the header of your class you can add sunch a function:

inline double MyClass::SumOfReturns() {
    return function1() + total;
}


问:
array filter in python?
For example, I have two lists

```<code> A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements
</code>```

Is there a built-in function in python to do this?

答:
set(A)-set(subset_of_A) gives your the intended result set, but it won't retain the original order. The following is order preserving:

```<code>[a for a in A if not a in subset_of_A]
</code>```

Title: array filter in python?

Body:
For example, I have two lists

 A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements

Is there a built-in function in python to do this?

Body:
set(A)-set(subset_of_A) gives your the intended result set, but it won't retain the original order. The following is order preserving:

[a for a in A if not a in subset_of_A]


问:
JS error: why can't the system find my js file
I am making my final project for university and I need to build a game for 2 players. whenever I load in the script with  the page can't seem to find the js. I've tried to put the script in other folders and it just seems to cannot find the script.

I placed the script in other folders, including the same folder where the current php file is. (head.php) and this did not work. If I paste the whole script file in the php file suddenly the js code does work.

This is the code from the main file welcome.php:

```<code><script src="../scripts/validate_form.js" type="text/javascript"></script>
</code>```

For debugging I put the file also in the tpl folder but that did not work either.

It cannot find any scripts what so ever.

答:
The problem is ../ is getting it back to the root.

use:

```<code><script src="/webpro/scripts/validate_form.js"></script>
</code>```

This should fix the problem

Body:
I am making my final project for university and I need to build a game for 2 players. whenever I load in the script with  the page can't seem to find the js. I've tried to put the script in other folders and it just seems to cannot find the script.

I placed the script in other folders, including the same folder where the current php file is. (head.php) and this did not work. If I paste the whole script file in the php file suddenly the js code does work.

This is the code from the main file welcome.php:

For debugging I put the file also in the tpl folder but that did not work either.

It cannot find any scripts what so ever.

Body:
The problem is ../ is getting it back to the root.

use:

<script src="/webpro/scripts/validate_form.js"></script>

This should fix the problem


答:
neither!

The best practice is to create three separate tables which one holds user data, one holds your worlds and the last one, holds relation between these two tables.

So table 1:
world
columns:
id
name
region
owner
.
.
.

table2 :
user
 columns:
id
username
.
.
.

table3:
world_user
 columns:
world_id
user_id
.
.
.

Title: more columns or one array, what is better performance?

Body:
I want to make a game(minecraft) region database and player's permissions.

and these are my table ideas.

example1)

Column ---------------- Datatype

worldname ------------ 1 ----- (INT(10)) ----- PK , NN

regionname ----------- 1 ----- (INT(10)) ----- PK , NN

owner ------------------- 2 ----- (INT(10))

member ---------------- 5, 13, 54, 246, 38295, 564, 2535, 5364, 411, 9 ----- (VARCHAR(128))

this one and I receive 'member' and split by ', ' to array.

example2)

Column ---------------- Datatype

worldname ------------ 1 ----- (INT(10)) ----- PK , NN

regionname ----------- 1 ----- (INT(10)) ----- PK , NN

owner ------------------- 2 ----- (INT(10)

member1 -------------- 5 ----- (INT(10))

member2 -------------- 13 ----- (INT(10))

member3 -------------- 54 ----- (INT(10))

member4 -------------- 246 ----- (INT(10))

member5 -------------- 38295 ----- (INT(10))

member6 -------------- 564 ----- (INT(10))

member7 -------------- 2535 ----- (INT(10))

member8 -------------- 5364 ----- (INT(10))

member9 -------------- 411 ----- (INT(10))

member10 ------------- 9 ----- (INT(10))

which one is better performance?


问:
RedisTemplate save multiple key value pairs to hash problem
I've started using RedisTemplate in a spring app. opsForHash() has a 'put' method, but it only takes three parameters. I want to save a number of key-value pairs. This is very simple to do in node, example:

```<code> redis.hmset(hashId, [key1, val1, key2, val2 ...], (err, result) => {});
</code>```

How do I do the same with RedisTemplate or StringRedisTemplate? I want to save data to a hash as I pass them, without java appending strings when serializing

答:
Try to use the putAll Method:

From the documentation:

```<code>void putAll(H key, Map<? extends HK,? extends HV> m)
Set multiple hash fields to multiple values using data provided in m.
</code>```

Body:
I've started using RedisTemplate in a spring app. opsForHash() has a 'put' method, but it only takes three parameters. I want to save a number of key-value pairs. This is very simple to do in node, example:

 redis.hmset(hashId, [key1, val1, key2, val2 ...], (err, result) => {});

How do I do the same with RedisTemplate or StringRedisTemplate? I want to save data to a hash as I pass them, without java appending strings when serializing

Body:
Try to use the putAll Method:

From the documentation:

void putAll(H key, Map<? extends HK,? extends HV> m)
Set multiple hash fields to multiple values using data provided in m.


问:
MediumText and textArea in my form show.blade
I need your help because I am stuck... I should create a form with a text long.

In my function up(), I have this

```<code>$table->mediumText('resume');
</code>```

In my page create.blade.php, the create works.

```<code><fieldset class="form-group {{ $errors->has('resume') ? 'has-error' : '' }}">
    <label for="form-group-input-1">Résumé</label>
    <textarea name="resume" id="resume" class="form-control" required="required" value="{{ old('resume')}}"/></textarea>
    {!! $errors->first('resume', '<span class="help-block">:message</span>') !!}
</fieldset>
</code>```

However, I don't get the value (the text) on my page show.blade.php

```<code><fieldset class="form-group">
   <label for="form-group-input-1">Résumé</label>
   <textarea name="resume" class="form-control" id="form-group-input-1" readonly="true" value="{{$livres->resume}}"/></textarea>
</fieldset>
</code>```

If I don't use textarea but input type=text it works.

Do you have an idea please?

答:
instead of this

```<code><fieldset class="form-group">
  <label for="form-group-input-1">Résumé</label>
  <textarea name="resume" class="form-control" id="form-group-input-1" readonly="true"
  value="{{$livres->resume}}"/></textarea>
 </fieldset>
</code>```

use this

```<code> <fieldset class="form-group">
  <label for="form-group-input-1">Résumé</label>
  <textarea name="resume" class="form-control" id="form-group-input-1" readonly="true"/>{{$livres->resume}}</textarea>
 </fieldset>
</code>```

Body:
I need your help because I am stuck... I should create a form with a text long.

In my function up(), I have this

$table->mediumText('resume');

In my page create.blade.php, the create works.

<fieldset class="form-group {{ $errors->has('resume') ? 'has-error' : '' }}">
    Résumé
    <textarea name="resume" id="resume" class="form-control" required="required" value="{{ old('resume')}}"/></textarea>
    {!! $errors->first('resume', ':message') !!}
</fieldset>

However, I don't get the value (the text) on my page show.blade.php

<fieldset class="form-group">
   Résumé
   <textarea name="resume" class="form-control" id="form-group-input-1" readonly="true" value="{{$livres->resume}}"/></textarea>
</fieldset>

If I don't use textarea but input type=text it works.

Do you have an idea please?

Body:
instead of this

<fieldset class="form-group">
  <label for="form-group-input-1">Résumé</label>
  <textarea name="resume" class="form-control" id="form-group-input-1" readonly="true"
  value="{{$livres->resume}}"/></textarea>
 </fieldset>

use this

 <fieldset class="form-group">
  <label for="form-group-input-1">Résumé</label>
  <textarea name="resume" class="form-control" id="form-group-input-1" readonly="true"/>{{$livres->resume}}</textarea>
 </fieldset>


问:
Alignment Issue :- Second Post is not aligned properly
i am facing an alignment issue for which i have a solution.
But i wanted to know the reason behind this.
If u run the html markup which i have provided you can see that the second post is not inline with the first post.

I wanted second post to align with first post. I have the solution by using flex.But i need reason and not the solution

HTML :-

```<code><div class="_3yTtBPc-LMIvY20o00OVsF">
  <div class="_2wIS4xHyz03D-DXLdHPFxP">
    <div class="_2NwLO4_WeKC2-xigIODSyO" style="">sunt aut facere repellat provident occaecati excepturi optio reprehenderit</div>
    <div>Nik</div>
  </div>
  <div class="_2wIS4xHyz03D-DXLdHPFxP">
    <div class="_2NwLO4_WeKC2-xigIODSyO" style="
    /* min-height: 90px; */
">qui est esse</div>
    <div>Nik</div>
  </div>
  <div class="_2wIS4xHyz03D-DXLdHPFxP">
    <div class="_2NwLO4_WeKC2-xigIODSyO">ea molestias quasi exercitationem repellat qui ipsa sit aut</div>
    <div>Nik</div>
  </div>
  <div class="_2wIS4xHyz03D-DXLdHPFxP">
    <div class="_2NwLO4_WeKC2-xigIODSyO">eum et est occaecati</div>
    <div>Nik</div>
  </div>
</div>
</code>```

CSS :-

```<code>._3yTtBPc-LMIvY20o00OVsF {
  margin: auto;
  height: 200px;
  text-align: center;
}

._2wIS4xHyz03D-DXLdHPFxP {
  width: 90px;
  height: 130px;
  display: inline-block;
  padding: 20px 30px;
  margin: 10px 30px;
  border: 2px solid grey;
  box-shadow: 2px 5px 0 lightgrey;
}

._2NwLO4_WeKC2-xigIODSyO {
  max-height: 90px;
  /* white-space: nowrap; */
  overflow: hidden;
  text-overflow: ellipsis;
}

</code>```

expected :- second post should be in line with first post
actual :- second post is bit down that first post.

答:
You need to add vertical-align: top;

```<code>._2wIS4xHyz03D-DXLdHPFxP {
  width: 90px;
  height: 130px;
  display: inline-block;
  padding: 20px 30px;
  margin: 10px 30px;
  border: 2px solid grey;
  box-shadow: 2px 5px 0 lightgrey;
  vertical-align: top;
}
</code>```

Body:
i am facing an alignment issue for which i have a solution.
But i wanted to know the reason behind this.
If u run the html markup which i have provided you can see that the second post is not inline with the first post.

I wanted second post to align with first post. I have the solution by using flex.But i need reason and not the solution

HTML :-

sunt aut facere repellat provident occaecati excepturi optio reprehenderit

Nik

qui est esse

Nik

ea molestias quasi exercitationem repellat qui ipsa sit aut

Nik

eum et est occaecati

Nik

CSS :-

._3yTtBPc-LMIvY20o00OVsF {
  margin: auto;
  height: 200px;
  text-align: center;
}

._2wIS4xHyz03D-DXLdHPFxP {
  width: 90px;
  height: 130px;
  display: inline-block;
  padding: 20px 30px;
  margin: 10px 30px;
  border: 2px solid grey;
  box-shadow: 2px 5px 0 lightgrey;
}

._2NwLO4_WeKC2-xigIODSyO {
  max-height: 90px;
  /* white-space: nowrap; */
  overflow: hidden;
  text-overflow: ellipsis;
}

expected :- second post should be in line with first post
actual :- second post is bit down that first post.

Body:
You need to add vertical-align: top;

._2wIS4xHyz03D-DXLdHPFxP {
  width: 90px;
  height: 130px;
  display: inline-block;
  padding: 20px 30px;
  margin: 10px 30px;
  border: 2px solid grey;
  box-shadow: 2px 5px 0 lightgrey;
  vertical-align: top;
}


答:
Use the Set type:

```<code>A_set = Set([6,7,8,9,10,11,12])
subset_of_A_set = Set([6,9,12])

result = A_set - subset_of_A_set
</code>```

Title: array filter in python?

Body:
Use the Set type:

A_set = Set([6,7,8,9,10,11,12])
subset_of_A_set = Set([6,9,12])

result = A_set - subset_of_A_set


问:
How to share my own app apk to other using cordova
I want to share my own apk file to other, in cordova application. I had tried many plugin, but all the plugin are used to just share the app name and some description only.

https://www.npmjs.com/package/cordova-plugin-share
https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin

So I have decided to create my own plugin and I have search share apk code for java, I got the following code, and it is working fine when I call that function from MainActivity.java

```<code>   private void shareApplication() {
    ApplicationInfo app = getApplicationContext().getApplicationInfo();
    String filePath = app.sourceDir;

    Intent intent = new Intent(Intent.ACTION_SEND);

    // MIME of .apk is "application/vnd.android.package-archive".
    // but Bluetooth does not accept this. Let's use "*/*" instead.
    intent.setType("*/*");

    // Append file and send Intent
    File originalApk = new File(filePath);

    try {
        //Make new directory in new location
        File tempFile = new File(getExternalCacheDir() + "/ExtractedApk");
        //If directory doesn't exists create new
        if (!tempFile.isDirectory())
            if (!tempFile.mkdirs())
                return;
        //Get application's name and convert to lowercase
        tempFile = new File(tempFile.getPath() + "/" + getString(app.labelRes).replace(" ","").toLowerCase() + ".apk");
        //If file doesn't exists create new
        if (!tempFile.exists()) {
            if (!tempFile.createNewFile()) {
                return;
            }
        }
        //Copy file to new location
        InputStream in = new FileInputStream(originalApk);
        OutputStream out = new FileOutputStream(tempFile);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        System.out.println("File copied.");
        //Open share dialog
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
        startActivity(Intent.createChooser(intent, "Share app via"));

    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

But I want to call that function(shareApplication()) from cordova extended java file.

```<code>public class AppVersion extends CordovaPlugin {
  @Override
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    try {
      if (action.equals("shareApk")) {
            MainActivity cc=new MainActivity();
            cc.shareApplication();
            MyClass myClass = new MyClass(c);
      }
      return false;
    } catch (NameNotFoundException e) {
      callbackContext.success("N/A");
      return true;
    }
}
</code>```

But when I call the function from cordova extended class, it show following error.

答:
I have found the plugin in the following URLs, this can generate your app apk file and finally popup the available sharing capable applications. Then you can choose the application and share it.

https://github.com/merbin2012/cordova-plugin-codeplay-share-own-apk
https://www.npmjs.com/package/cordova-plugin-codeplay-share-own-apk

```<code>cordova plugin add cordova-plugin-codeplay-share-own-apk
</code>```

Body:
I want to share my own apk file to other, in cordova application. I had tried many plugin, but all the plugin are used to just share the app name and some description only.

https://www.npmjs.com/package/cordova-plugin-share
https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin

So I have decided to create my own plugin and I have search share apk code for java, I got the following code, and it is working fine when I call that function from MainActivity.java

   private void shareApplication() {
    ApplicationInfo app = getApplicationContext().getApplicationInfo();
    String filePath = app.sourceDir;

    Intent intent = new Intent(Intent.ACTION_SEND);

    // MIME of .apk is "application/vnd.android.package-archive".
    // but Bluetooth does not accept this. Let's use "*/*" instead.
    intent.setType("*/*");

    // Append file and send Intent
    File originalApk = new File(filePath);

    try {
        //Make new directory in new location
        File tempFile = new File(getExternalCacheDir() + "/ExtractedApk");
        //If directory doesn't exists create new
        if (!tempFile.isDirectory())
            if (!tempFile.mkdirs())
                return;
        //Get application's name and convert to lowercase
        tempFile = new File(tempFile.getPath() + "/" + getString(app.labelRes).replace(" ","").toLowerCase() + ".apk");
        //If file doesn't exists create new
        if (!tempFile.exists()) {
            if (!tempFile.createNewFile()) {
                return;
            }
        }
        //Copy file to new location
        InputStream in = new FileInputStream(originalApk);
        OutputStream out = new FileOutputStream(tempFile);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        System.out.println("File copied.");
        //Open share dialog
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
        startActivity(Intent.createChooser(intent, "Share app via"));

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

But I want to call that function(shareApplication()) from cordova extended java file.

public class AppVersion extends CordovaPlugin {
  @Override
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    try {
      if (action.equals("shareApk")) {
            MainActivity cc=new MainActivity();
            cc.shareApplication();
            MyClass myClass = new MyClass(c);
      }
      return false;
    } catch (NameNotFoundException e) {
      callbackContext.success("N/A");
      return true;
    }
}

But when I call the function from cordova extended class, it show following error.

Body:
I have found the plugin in the following URLs, this can generate your app apk file and finally popup the available sharing capable applications. Then you can choose the application and share it.

https://github.com/merbin2012/cordova-plugin-codeplay-share-own-apk
https://www.npmjs.com/package/cordova-plugin-codeplay-share-own-apk

cordova plugin add cordova-plugin-codeplay-share-own-apk


问:
How to get the indexes of an element of a nested list of n dimensions
I am new at Python (programming in general) and I have some problem that I dont know how to get around.
I have many different nested lists following this pattern:

Listi = [string0, string1, ..., stringn, [list0], [list1], ..., [listn]]

(The list contains a number of strings always positioned at the begining continued by a number of lists always positioned afterwards)

The lists cointained in the first list have the same exact structure as the first list.
The lists can have any number of lists inside them.

What I would like to code is a function that given a random element (a random string) finds the indexes of such element inside the list so that this element can be called from the principal list that contains it.

I would like to get the best possible way to accomplish that in terms of number of operations, but any solution at all would be immensely appreciated.

Heres some example:
Imagine I have this two lists:

```<code>l1 = ['Node_50', ['Node_48', 'Node_23'], ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]]
l2 = ['Node_50', ['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_20']], ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]]
</code>```

I would like to ge a function like this:

```<code>def functionfinder(list, element):
</code>```

such that:

```<code>indexes = functionfinder(l1, "Node_40")
</code>```

indexes would be a tuple (2, 2, 1) because:

```<code>l1[2][2][1] = Node_40
</code>```

答:
Since you are searching nested lists, a recursive routine would be best. Since you want good speed, the routine should exit as soon as the desired item is found (rather than continuing the search or looking for another one). The following should work if you actually use only lists as your containers for your strings.

```<code>def functionfinder(asequence, value, indexes_tuple=()):
    for ndx, item in enumerate(asequence):
        if item == value:
            return indexes_tuple + (ndx,) # found it here: return the answer
        if isinstance(item, list):
            result = functionfinder(item, value, indexes_tuple + (ndx,))
            if result:
                return result # found it below: stop looking for it
    return ()  # desired value not found yet

l1 = ['Node_50',
      ['Node_48', 'Node_23'],
      ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]
     ]
l2 = ['Node_50',
      ['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_20']],
      ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]
     ]

indexes = functionfinder(l1, "Node_40")
print(indexes)
</code>```

The printout from that code is what you want:

```<code>(2, 2, 1)
</code>```

If you have the indexes and you want to access the value that was searched, you could do

```<code>result = l1
for ndx in indexes:
    result = result[ndx]
</code>```

Now result holds the value you searched for.

This code could be generalized to handle other kinds of sequences such as tuples and not just lists. You would need to be careful to not recurse into a string, since Python's strings are also sequences--of characters. You want a tuple as the return value, so my code also uses them. Using an immutable type as the return value does have advantages. But using a mutable type, such as a list, might speed up the execution speed. As it is now, each new list in your parameter requires constructing a complete new tuple of indexes. Using a list could mean that you just need to append a single new index and may speed up the code. Ask if either of those possible improvements appeals to you.

Note that, since Python does not have a built-in immediate way to stop a recursive function, my code uses a returned empty tuple to note that the desired item has not yet been found. When the item is found, a non-empty tuple result is returned which signals all levels of the recursion to stop as soon as possible. This complicates the code somewhat.

Body:
I am new at Python (programming in general) and I have some problem that I dont know how to get around.
I have many different nested lists following this pattern:

Listi = [string0, string1, ..., stringn, [list0], [list1], ..., [listn]]

(The list contains a number of strings always positioned at the begining continued by a number of lists always positioned afterwards)

The lists cointained in the first list have the same exact structure as the first list.
The lists can have any number of lists inside them.

What I would like to code is a function that given a random element (a random string) finds the indexes of such element inside the list so that this element can be called from the principal list that contains it.

I would like to get the best possible way to accomplish that in terms of number of operations, but any solution at all would be immensely appreciated.

Heres some example:
Imagine I have this two lists:

l1 = ['Node_50', ['Node_48', 'Node_23'], ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]]
l2 = ['Node_50', ['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_20']], ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]]

I would like to ge a function like this:

def functionfinder(list, element):

such that:

indexes = functionfinder(l1, "Node_40")

indexes would be a tuple (2, 2, 1) because:

l1[2][2][1] = Node_40

Body:
Since you are searching nested lists, a recursive routine would be best. Since you want good speed, the routine should exit as soon as the desired item is found (rather than continuing the search or looking for another one). The following should work if you actually use only lists as your containers for your strings.

def functionfinder(asequence, value, indexes_tuple=()):
    for ndx, item in enumerate(asequence):
        if item == value:
            return indexes_tuple + (ndx,) # found it here: return the answer
        if isinstance(item, list):
            result = functionfinder(item, value, indexes_tuple + (ndx,))
            if result:
                return result # found it below: stop looking for it
    return ()  # desired value not found yet

l1 = ['Node_50',
      ['Node_48', 'Node_23'],
      ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]
     ]
l2 = ['Node_50',
      ['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_20']],
      ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]
     ]

indexes = functionfinder(l1, "Node_40")
print(indexes)

The printout from that code is what you want:

(2, 2, 1)

If you have the indexes and you want to access the value that was searched, you could do

result = l1
for ndx in indexes:
    result = result[ndx]

Now result holds the value you searched for.

This code could be generalized to handle other kinds of sequences such as tuples and not just lists. You would need to be careful to not recurse into a string, since Python's strings are also sequences--of characters. You want a tuple as the return value, so my code also uses them. Using an immutable type as the return value does have advantages. But using a mutable type, such as a list, might speed up the execution speed. As it is now, each new list in your parameter requires constructing a complete new tuple of indexes. Using a list could mean that you just need to append a single new index and may speed up the code. Ask if either of those possible improvements appeals to you.

Note that, since Python does not have a built-in immediate way to stop a recursive function, my code uses a returned empty tuple to note that the desired item has not yet been found. When the item is found, a non-empty tuple result is returned which signals all levels of the recursion to stop as soon as possible. This complicates the code somewhat.


答:
so you are looking to iteratively take 34 elements -- I'll assume you want to print the last elements of the list even if there aren't a full 34. The tool to use here is a Loop. Inside that for loop, you want to print 34 elements based on a current index, like so:

```<code>print intlist(n:n+34)
</code>```

okay, so your iteration limits. the simplest way to do this is with a do-while loop (and remember to incremement your index variable each loop):

```<code>n=0
while n < len(intlist):
    print intlist(n:n+34)
    n += 34
</code>```

there's a bug here, though. it won't print the last section of the list -- because you will get an IndexOutoFRange exception (when n+34 is too big). To fix that, you can wrap this in an try-except block, which will handle the special case by printing to the end of your list:

```<code>n=0
while n < len(intlist):
    try:
        print intlist(n:n+34)
    except:
        print intlist(n:)
    n += 34
</code>```

Title: Is there another way to print multiple list elements where the list index increases by a given amount with each print?

Body:
I have a list containing hundreds of integers. I need to take 34 integers at a time, starting from the beginning of the list and print the integers in separate rows of 34.

The problem is that I have to use multiple print (list[x:y]) and continuously change the value for x and y.

I've tried specifying each index within the list to be printed, however, this is impractical since the list may contain hundreds of values.

integer = [
    3,23,12,34,2,4,7,11,14,1,9,17,12,1,0,5,4,3,2,4,8,1,12,15,18,17,14,23,12,0,0
    ,12,34,2,21,22,24,23,1,0,4,7,3,13,16,15,3,5,11,22,9,14,20,16,3,6,2,0,10,1,12
    ,18,9,9,23,6,2,18,14,1,0,3,5,17,13,12,5,6,9,0,1,2,19,20,2,3,5,7,15,19,2,4,10
    ,15,18,17,2,6,5,3,6,12,15,18,12,15,6,20,0,9,4,1,5,4,3,7,9,0,12,3,5,7,8,17,19
    ,21,0,1,2,7,7,7,5,4,3,8,19,12,16,0,2,4,7,8,4,12,12,9,3,20,2,21,3,5,8,9,12,17
    ,8,7,3,4,6,3,14,18,21,4,3,9,19,19,3,6,8,7,13,14,18,13,15,3,4,8,7,12
]

print (integer[0:34])
print (integer[35:69])
print (integer[70:104])

Output:

[3, 23, 12, 34, 2, 4, 7, 11, 14, 1, 9, 17, 12, 1, 0, 5, 4, 3, 2, 4, 8, 1, 12, 15, 18, 17, 14, 23, 12, 0, 0, 12, 34, 2]
[22, 24, 23, 1, 0, 4, 7, 3, 13, 16, 15, 3, 5, 11, 22, 9, 14, 20, 16, 3, 6, 2, 0, 10, 1, 12, 18, 9, 9, 23, 6, 2, 18, 14]
[0, 3, 5, 17, 13, 12, 5, 6, 9, 0, 1, 2, 19, 20, 2, 3, 5, 7, 15, 19, 2, 4, 10, 15, 18, 17, 2, 6, 5, 3, 6, 12, 15, 18]

Body:
so you are looking to iteratively take 34 elements -- I'll assume you want to print the last elements of the list even if there aren't a full 34. The tool to use here is a Loop. Inside that for loop, you want to print 34 elements based on a current index, like so:

print intlist(n:n+34)

okay, so your iteration limits. the simplest way to do this is with a do-while loop (and remember to incremement your index variable each loop):

n=0
while n < len(intlist):
    print intlist(n:n+34)
    n += 34

there's a bug here, though. it won't print the last section of the list -- because you will get an IndexOutoFRange exception (when n+34 is too big). To fix that, you can wrap this in an try-except block, which will handle the special case by printing to the end of your list:

n=0
while n < len(intlist):
    try:
        print intlist(n:n+34)
    except:
        print intlist(n:)
    n += 34


问:
Executing method 1 to N times per second
Let's take the following execution example:

```<code>MyRequest request = new MyRequest(args);
request.execute(params);
</code>```

How can I perform the above 1 to n times (i.e. n=50) per second?

Edit

Furthermore, if we have i objects, each of which call n requests:

```<code>for(MyObject obj : objects) {
    // Execute n requests (i.e. in for loop)
}
</code>```

How can I ensure that the execution happens within one second?

答:
To ensure that n requests are executed in 1 Second you would have to know how long 1 execution lasts to run them sequential, otherwise you should use Threads to run them in parralel and start them with a delay to exactly fit 1 Second</p>

```<code>for(int i=0;i<n;i++){
   MyRequest request = new MyRequest(args);
   Thread th=new Thread(()-> request.execute());
   th.start();
   Thread.sleep(1000/n);
}
</code>```

Body:
Let's take the following execution example:

MyRequest request = new MyRequest(args);
request.execute(params);

How can I perform the above 1 to n times (i.e. n=50) per second?

Edit

Furthermore, if we have i objects, each of which call n requests:

for(MyObject obj : objects) {
    // Execute n requests (i.e. in for loop)
}

How can I ensure that the execution happens within one second?

Body:
To ensure that n requests are executed in 1 Second you would have to know how long 1 execution lasts to run them sequential, otherwise you should use Threads to run them in parralel and start them with a delay to exactly fit 1 Second

for(int i=0;i<n;i++){
   MyRequest request = new MyRequest(args);
   Thread th=new Thread(()-> request.execute());
   th.start();
   Thread.sleep(1000/n);
}


问:
Java 8 int array to map
I want to convert int array to

```<code>Map<Integer,Integer>
</code>```

using Java 8 stream api

```<code>int[] nums={2, 7, 11, 15, 2, 11, 2};
Map<Integer,Integer> map=Arrays
                .stream(nums)
                .collect(Collectors.toMap(e->e,1));
</code>```

I want to get a map like below, key will be integer value, value will be total count of each key

map={2->3, 7->1, 11->2, 15->1}

compiler complains "no instance(s) of type variable(s) T, U exist so that Integer confirms to Function"

appreciate any pointers to resolve this

答:
You have to call .boxed() on your Stream to convert the IntStream to a Stream<Integer>. Then you can use Collectors.groupingby() and Collectors.summingInt() to count the values:

```<code>Map<Integer, Integer> map = Arrays.stream(nums).boxed()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(i -> 1)));
</code>```

Title: Java 8 int array to map

Body:
I want to convert int array to

Map<Integer,Integer>

using Java 8 stream api

int[] nums={2, 7, 11, 15, 2, 11, 2};
Map<Integer,Integer> map=Arrays
                .stream(nums)
                .collect(Collectors.toMap(e->e,1));

I want to get a map like below, key will be integer value, value will be total count of each key

map={2->3, 7->1, 11->2, 15->1}

compiler complains "no instance(s) of type variable(s) T, U exist so that Integer confirms to Function"

appreciate any pointers to resolve this

Body:
You have to call .boxed() on your Stream to convert the IntStream to a Stream<Integer>. Then you can use Collectors.groupingby() and Collectors.summingInt() to count the values:

Map<Integer, Integer> map = Arrays.stream(nums).boxed()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(i -> 1)));


问:
can I distinguish between a string literal argument and a parameter which evaluates to a string?
I'm creating a domain-specific language. One of the macro calls looks something like this:

(my-macro foo (bar "baz" qux) yay)

With the way I've written my-macro, the second argument here is supposed to be a list of strings inside a pair of parentheses. So my-macro works as long as bar and qux evaluate to strings. Let's just say they evaluate eponymously to "bar" and "qux" and my-macro treats the second argument as "bar baz qux".

But now I've realized that I really want "baz" to retain its quotes; I want my-macro to treat the second argument as "bar \"baz\" qux". Is this possible? Inside my-macro, can I tell when I  can just use a string as-is vs when I need to add back the double quotes?

Thanks in advance!

答:
Your macro is passed the symbol FOO, the list (BAR "baz" QUX), and the symbol YAY as arguments. If you want to see if any of the elements in the second argument are a string, use something like stringp in the macro definition to test the argument.

Your macro completely controls how evaluation works in the resulting macroexpansion. It sees all its arguments un-evaluated. If you want to know something about the un-evaluated code passed as arguments, just look at it.


问:
UITableView Cell should not scroll horizontally swift iOS
I have a table view which has card kind of cells as shown in picture.
I have set the content Inset so that I can get the cells with 20px spacing in left,right and top.

    tableVw.contentInset = UIEdgeInsets(top: 20, left: 20, bottom: 0, right: 20)

Its displaying as I expected but the problem is, cells can be moved in all direction. But when I move it to right/top, it automatically comes back to original position. But when I move to left it just goes inside and don't scroll back to original position as shown in picture.

I don't want the cells to move at all or I want the cells to come back to centre if its dragged anywhere also. Please help!

答:
you need to set the clipsToBounds property true

tableview.clipsToBounds = true


问:
Recursively reverse linked list
I am having hard time understanding how this recursive code works, I have made drawings and run the code through gdb.

```<code>void RecursiveReverse(struct node** headRef)
{
  struct node* first;
  struct node* rest;

  if (*headRef == NULL) return; // empty list base case

  first = *headRef; // suppose first = {1, 2, 3}
  rest = first->next; // rest = {2, 3}

  if (rest == NULL) return; // empty rest base case

  RecursiveReverse(&rest); // Recursively reverse the smaller {2, 3} case
                           // after: rest = {3, 2}

  first->next->next = first; // put the first element on the end of the list
  first->next = NULL;

  *headRef = rest; // fix the head pointer
}
</code>```

I understand that while the recursion call stack is being built up and once the list contains only {3}, empty rest base case if (rest == NULL) is true for the first time.

After this, the recursion call stack starts to break and hits first->next->next = first; for the first time, with {2, 3},

Before this line is executed, output in gdb:

```<code>(gdb)p *first
{data = 2, next = 0x1003001f0}

(gdb) p *rest
{data = 3, next = 0x0}
</code>```

After this line is executed,

```<code>(gdb) p *rest
{data = 3, next = 0x1003000a0}
</code>```

Continuing with code execution to hit first->next->next = first;, the second time:

```<code>(gdb) p **head_ref
{data = 1, next = 0x1003000a0}

(gdb) p *rest
{data = 3, next = 0x1003000a0} // expected p *rest to be 2
</code>```

Here I expected that the local pointer rest should point to node 2, because while building up recursion call stack, **headRef pointed to node 1 and after line rest = first->next;, got executed rest pointed to node 2.

After *headRef = rest;, is executed, shouldn't headRef point to node 2?

How come that local state is lost and rest points to node 3?

答:
Let's assume that you have a list and its rest part is already reversed.

Before reversing the rest part the list had this structure

```<code>first -> first_of_rest -> second_of_rest->...->nth_of_rest->nullptr
</code>```

After reversing the rest part you will get

```<code>first -> nullptr <- first_of_rest <- second_of_rest <-...<-nth_of_rest
         |                                                      |
         ________________________________________________________
                            the rest part of the list
</code>```

So the data member next of the node first points to first_of_rest while the data member next of the node first_of_rest "points" to nullptr.

So what we need to do at this moment is to set the data member of the node first_of_rest to point to the node first

```<code>first->next->next = first;
</code>```

abd set the data member next of the node first to "point" to nullptr.

```<code>first->next = NULL;
</code>```

Thus we have

```<code>nullptr <-first <- first_of_rest <- second_of_rest <-...<-nth_of_rest
</code>```

Title: Recursively reverse linked list

Body:
I am having hard time understanding how this recursive code works, I have made drawings and run the code through gdb.

void RecursiveReverse(struct node** headRef)
{
  struct node* first;
  struct node* rest;

  if (*headRef == NULL) return; // empty list base case

  first = *headRef; // suppose first = {1, 2, 3}
  rest = first->next; // rest = {2, 3}

  if (rest == NULL) return; // empty rest base case

  RecursiveReverse(&rest); // Recursively reverse the smaller {2, 3} case
                           // after: rest = {3, 2}

  first->next->next = first; // put the first element on the end of the list
  first->next = NULL;

  *headRef = rest; // fix the head pointer
}

I understand that while the recursion call stack is being built up and once the list contains only {3}, empty rest base case if (rest == NULL) is true for the first time.

After this, the recursion call stack starts to break and hits first->next->next = first; for the first time, with {2, 3},

Before this line is executed, output in gdb:

(gdb)p *first
{data = 2, next = 0x1003001f0}

(gdb) p *rest
{data = 3, next = 0x0}

After this line is executed,

(gdb) p *rest
{data = 3, next = 0x1003000a0}

Continuing with code execution to hit first->next->next = first;, the second time:

(gdb) p **head_ref
{data = 1, next = 0x1003000a0}

(gdb) p *rest
{data = 3, next = 0x1003000a0} // expected p *rest to be 2

Here I expected that the local pointer rest should point to node 2, because while building up recursion call stack, **headRef pointed to node 1 and after line rest = first->next;, got executed rest pointed to node 2.

After *headRef = rest;, is executed, shouldn't headRef point to node 2?

How come that local state is lost and rest points to node 3?

Body:
Let's assume that you have a list and its rest part is already reversed.

Before reversing the rest part the list had this structure

first -> first_of_rest -> second_of_rest->...->nth_of_rest->nullptr

After reversing the rest part you will get

first -> nullptr <- first_of_rest <- second_of_rest <-...<-nth_of_rest
         |                                                      |
         ________________________________________________________
                            the rest part of the list

So the data member next of the node first points to first_of_rest while the data member next of the node first_of_rest "points" to nullptr.

So what we need to do at this moment is to set the data member of the node first_of_rest to point to the node first

first->next->next = first;

abd set the data member next of the node first to "point" to nullptr.

first->next = NULL;

Thus we have

nullptr <-first <- first_of_rest <- second_of_rest <-...<-nth_of_rest


问:
Compare values from two different stores in IndexedDB
I have two data structures:

Tasks: taskID (autoincremented), title, status, dueDate, description

Tags: tagID, tagName, tagColor, textColor, taskID

I'm trying to compare the taskID value of both of them, to later be able to associate a single task with multiple tags. I've written two functions, getTags() and getTasks(). I've managed to loop through both of them, getting all objects in both stores, however, i'm not quite sure how to check if the two values match.

```<code>function connectToDB() {
    window.webkitIndexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

    //check for support
    if(!window.indexedDB) {
        alert("Your browser do not support indexedDB. Please update you browser.")
    }

    //open database "KanbanDatabase" version 9.
    //db = database, tx = transaction, store = store data, index = index (seach data).
    let request = window.indexedDB.open("KanbanDatabase", 9),
        db,
        tx,
        store,
        index;

    //when creating a new databse, a store(structure) must be added
    request.onupgradeneeded = function(e) {
        let db = request.result,
        //tasks
        tasksStore = db.createObjectStore("tasksStore",{
            keyPath: "taskID", autoIncrement: true
        }),
        tasksIndex = tasksStore.createIndex("status", "status", {
            unique: false
        }),
        //tags
        tagsStore = db.createObjectStore("tagsStore", {
            keyPath: "tagID", autoIncrement: true
        }),
        tagsIndex = tagsStore.createIndex("tagID", "tagID", {
            unique: true
        });
    };

    //open database will return response.
    //error handler:
    request.onerror = function(e) {
        console.error("There was an error opening the database: " + e.target.errorCode);
    };

    //success handler:
    request.onsuccess = function(e) {
        console.log("Successfully connected to DB")
        db = request.result;
        //tasks
        tasksTx = db.transaction("tasksStore", "readwrite");
        tasksStore = tasksTx.objectStore("tasksStore");
        tasksIndex = tasksStore.index("status");

        //tags
        tagsTx = db.transaction("tagsStore", "readwrite");
        tagsStore = tagsTx.objectStore("tagsStore");
        tagsIndex = tagsStore.index("tagID");

        db.onerror = function(e) {
            console.error("ERROR " + e.target.errorCode);
        }

        function tagsToTasks() {
            let amountOfTasks = tasksIndex.count();
            let amountOfTags = tagsIndex.count();

            function getTasks() {
                for (var i = 1; i < amountOfTasks.result+1; i++) {
                    let getTasks = tasksStore.get(i);

                    getTasks.onerror = function() {
                        console.error("There was an error looping through the tasks");
                    }

                    getTasks.onsuccess = function() {
                        console.log(getTasks.result.taskID)
                    }
                }
            }

            function getTags() {
                for (var j = 1; j < amountOfTags.result+1; j++) {
                    let getTags = tagsStore.get(j);

                    getTags.onerror = function() {
                        console.error("There was en error looping through the tags");
                    }

                    getTags.onsuccess = function() {
                        let result = getTags.result.taskID;

                        return result;
                    }
                }
            }

            function compareID() {
                //what to do?
            }

            amountOfTasks.onerror = function() {
                console.error("There was an error finding the amount of tasks");
            }

            amountOfTasks.onsuccess = function() {
                getTasks();
            }

            amountOfTags.onerror = function() {
                console.error("There was an error finding the amount of tags");
            }

            amountOfTags.onsuccess = function() {
                getTags();
            }

        }

        //fire functions
        tagsToTasks();
        listTasks();

        //close DB conection once transaction is complete.
        tasksTx.oncomplete = function() {
            db.close();
        }

        tagsTx.oncomplete = function() {
            db.close();
        }
    }
}
</code>```

Edit: to clarify: I need to compare two values in two different stores. The problem starts in the tagsToTasks() function; how can i compare the values returned from getTags.result.taskID in the getTags() function to the getTasks.result.taskID in the getTasks() function?

答:
First error is here.

```<code>window.webkitIndexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;`
</code>```

You are assigning it to window.webkitIndexedDb but checking for window.indexedDb in the next line.

I'd suggest using a local const instead of attempting to overwrite global variables.

Like so,

```<code>const indexedDb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

if (!indexedDb) return ....
</code>```

Next, you can use a cursor or the getAll method to retrieve all objects. Also, you can't return the task from the onSuccess event handler, you need to assign it a variable from a parent scope. Like so,

```<code>let tasks = [];
tasksStore.getAll().onsuccess = function(event) {
   tasks = event.target.result
   attachTags(tasks);
};

function attachTags(tasks) {
  tags.openCursor().onsuccess = function(event) {
  var cursor = event.target.result;
  if (cursor) {
    const task = tasks.find(t => t.taskId == cursor.value.taskId);
    if (!task.tags) task.tags = []
       task.tags.push(cursor.value) ;
    cursor.continue();
  }
  else {
    return;
  }
};
}
</code>```

looks like you will have to go through callback hell to do this. I'm using the find method to pick the task with the taskId of the current tag pointed by the cursor at cursor.value and then I'm creating an array of tags for that task and pushing the tags into it. Looking at your data model, I assumed you wanted to associate each tag with the relevant task through the taskId foreign key.

The problem with the way you've set up things is that indexedDB uses callbacks to return values and nowhere in your code are you saving these values and passing on to the functions that need them. You've written callbacks that essentially do nothing with the values they receive. You cannot return a value out of a callback, because the callback gets called by the API, not your code. you need to assign values to variables outside the callback or do the processing inside the callback. Callbacks execute asynchronously to each other so there is no guarantee that your code will execute in the sequence you've written it in, which leaves you with no choice but to setup the next callback from the current callback, this is referred to as callback hell. Promises help alleviate this, so if you are going to use this in production, I would recommend a library such as this
https://github.com/jakearchibald/idb that exposes a more usable Api.

Body:
I have two data structures:

Tasks: taskID (autoincremented), title, status, dueDate, description

Tags: tagID, tagName, tagColor, textColor, taskID

I'm trying to compare the taskID value of both of them, to later be able to associate a single task with multiple tags. I've written two functions, getTags() and getTasks(). I've managed to loop through both of them, getting all objects in both stores, however, i'm not quite sure how to check if the two values match.

function connectToDB() {
    window.webkitIndexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

    //check for support
    if(!window.indexedDB) {
        alert("Your browser do not support indexedDB. Please update you browser.")
    }

    //open database "KanbanDatabase" version 9.
    //db = database, tx = transaction, store = store data, index = index (seach data).
    let request = window.indexedDB.open("KanbanDatabase", 9),
        db,
        tx,
        store,
        index;

    //when creating a new databse, a store(structure) must be added
    request.onupgradeneeded = function(e) {
        let db = request.result,
        //tasks
        tasksStore = db.createObjectStore("tasksStore",{
            keyPath: "taskID", autoIncrement: true
        }),
        tasksIndex = tasksStore.createIndex("status", "status", {
            unique: false
        }),
        //tags
        tagsStore = db.createObjectStore("tagsStore", {
            keyPath: "tagID", autoIncrement: true
        }),
        tagsIndex = tagsStore.createIndex("tagID", "tagID", {
            unique: true
        });
    };

    //open database will return response.
    //error handler:
    request.onerror = function(e) {
        console.error("There was an error opening the database: " + e.target.errorCode);
    };

    //success handler:
    request.onsuccess = function(e) {
        console.log("Successfully connected to DB")
        db = request.result;
        //tasks
        tasksTx = db.transaction("tasksStore", "readwrite");
        tasksStore = tasksTx.objectStore("tasksStore");
        tasksIndex = tasksStore.index("status");

        //tags
        tagsTx = db.transaction("tagsStore", "readwrite");
        tagsStore = tagsTx.objectStore("tagsStore");
        tagsIndex = tagsStore.index("tagID");

        db.onerror = function(e) {
            console.error("ERROR " + e.target.errorCode);
        }

        function tagsToTasks() {
            let amountOfTasks = tasksIndex.count();
            let amountOfTags = tagsIndex.count();

            function getTasks() {
                for (var i = 1; i < amountOfTasks.result+1; i++) {
                    let getTasks = tasksStore.get(i);

                    getTasks.onerror = function() {
                        console.error("There was an error looping through the tasks");
                    }

                    getTasks.onsuccess = function() {
                        console.log(getTasks.result.taskID)
                    }
                }
            }

            function getTags() {
                for (var j = 1; j < amountOfTags.result+1; j++) {
                    let getTags = tagsStore.get(j);

                    getTags.onerror = function() {
                        console.error("There was en error looping through the tags");
                    }

                    getTags.onsuccess = function() {
                        let result = getTags.result.taskID;

                        return result;
                    }
                }
            }

            function compareID() {
                //what to do?
            }

            amountOfTasks.onerror = function() {
                console.error("There was an error finding the amount of tasks");
            }

            amountOfTasks.onsuccess = function() {
                getTasks();
            }

            amountOfTags.onerror = function() {
                console.error("There was an error finding the amount of tags");
            }

            amountOfTags.onsuccess = function() {
                getTags();
            }

        }

        //fire functions
        tagsToTasks();
        listTasks();

        //close DB conection once transaction is complete.
        tasksTx.oncomplete = function() {
            db.close();
        }

        tagsTx.oncomplete = function() {
            db.close();
        }
    }
}

Edit: to clarify: I need to compare two values in two different stores. The problem starts in the tagsToTasks() function; how can i compare the values returned from getTags.result.taskID in the getTags() function to the getTasks.result.taskID in the getTasks() function?

Body:
First error is here.

window.webkitIndexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;`

You are assigning it to window.webkitIndexedDb but checking for window.indexedDb in the next line.

I'd suggest using a local const instead of attempting to overwrite global variables.

Like so,

const indexedDb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

if (!indexedDb) return ....

Next, you can use a cursor or the getAll method to retrieve all objects. Also, you can't return the task from the onSuccess event handler, you need to assign it a variable from a parent scope. Like so,

let tasks = [];
tasksStore.getAll().onsuccess = function(event) {
   tasks = event.target.result
   attachTags(tasks);
};

function attachTags(tasks) {
  tags.openCursor().onsuccess = function(event) {
  var cursor = event.target.result;
  if (cursor) {
    const task = tasks.find(t => t.taskId == cursor.value.taskId);
    if (!task.tags) task.tags = []
       task.tags.push(cursor.value) ;
    cursor.continue();
  }
  else {
    return;
  }
};
}

looks like you will have to go through callback hell to do this. I'm using the find method to pick the task with the taskId of the current tag pointed by the cursor at cursor.value and then I'm creating an array of tags for that task and pushing the tags into it. Looking at your data model, I assumed you wanted to associate each tag with the relevant task through the taskId foreign key.

The problem with the way you've set up things is that indexedDB uses callbacks to return values and nowhere in your code are you saving these values and passing on to the functions that need them. You've written callbacks that essentially do nothing with the values they receive. You cannot return a value out of a callback, because the callback gets called by the API, not your code. you need to assign values to variables outside the callback or do the processing inside the callback. Callbacks execute asynchronously to each other so there is no guarantee that your code will execute in the sequence you've written it in, which leaves you with no choice but to setup the next callback from the current callback, this is referred to as callback hell. Promises help alleviate this, so if you are going to use this in production, I would recommend a library such as this
https://github.com/jakearchibald/idb that exposes a more usable Api.


问:
Unidentified Protocol murray on port 1123
I conducted a basic nmap scan of a box I have set up below is the output.

```<code>$ nmap xxx.xx.org

Starting Nmap 7.40SVN ( https://nmap.org ) at 2017-05-17 13:25 GMT
Nmap scan report for xxx.xx.xx (xx.xx.5.180)
Host is up (0.00069s latency).
rDNS record for xx.xx.5.180: www.xxx.org
Not shown: 988 filtered ports
PORT      STATE  SERVICE
20/tcp    closed ftp-data
21/tcp    open   ftp
53/tcp    open   domain
80/tcp    open   http
110/tcp   open   pop3
143/tcp   open   imap
443/tcp   open   https
993/tcp   open   imaps
995/tcp   open   pop3s
1123/tcp  open   murray
2030/tcp  open   device2
10000/tcp open   snet-sensor-mgmt

Nmap done: 1 IP address (1 host up) scanned in 4.94 seconds
</code>```

what cought my interest was murray port, I dont seem to find what is that making that port open.

答:
That's me! I'm the author of murray. It was a webshots-like system, for windows and os/2 and I registered port 1123 for it.
Alas, you're probably not running murray, so it's some other program that just happens to be using that port.

```<code>sudo netstat -napt | grep 1123
</code>```

and that will tell you what process is actually holding that port, and that might give you a clue as to what's really using it.

Body:
I conducted a basic nmap scan of a box I have set up below is the output.

$ nmap xxx.xx.org

Starting Nmap 7.40SVN ( https://nmap.org ) at 2017-05-17 13:25 GMT
Nmap scan report for xxx.xx.xx (xx.xx.5.180)
Host is up (0.00069s latency).
rDNS record for xx.xx.5.180: www.xxx.org
Not shown: 988 filtered ports
PORT      STATE  SERVICE
20/tcp    closed ftp-data
21/tcp    open   ftp
53/tcp    open   domain
80/tcp    open   http
110/tcp   open   pop3
143/tcp   open   imap
443/tcp   open   https
993/tcp   open   imaps
995/tcp   open   pop3s
1123/tcp  open   murray
2030/tcp  open   device2
10000/tcp open   snet-sensor-mgmt

Nmap done: 1 IP address (1 host up) scanned in 4.94 seconds

what cought my interest was murray port, I dont seem to find what is that making that port open.

Body:
That's me! I'm the author of murray. It was a webshots-like system, for windows and os/2 and I registered port 1123 for it.
Alas, you're probably not running murray, so it's some other program that just happens to be using that port.

sudo netstat -napt | grep 1123

and that will tell you what process is actually holding that port, and that might give you a clue as to what's really using it.


问:
C# - skip generics
How I can pass parameters of a generic type in my methods?</p>

```<code>public Type<T, U, V> { ... }

public void Method(??? arg) // where ??? is Type<T, U, V>
{
  ...
}
</code>```

答:
Carry the generic parameters to your method definition</p>

```<code>public void Method<T,U,V>(Type<T,U,V> arg) // where ??? is Type<T, U, V>
{
  ...
}
</code>```

Title: C# - skip generics

Body:
How I can pass parameters of a generic type in my methods?

public Type<T, U, V> { ... }

public void Method(??? arg) // where ??? is Type<T, U, V>
{
  ...
}

Body:
Carry the generic parameters to your method definition

public void Method<T,U,V>(Type<T,U,V> arg) // where ??? is Type<T, U, V>
{
  ...
}


问:
How do I create Conda environment in Windows 10
I am trying to setup a conda environment in windows command promt so I can create a python discord bot but I get an error, I tried creating the environment in Anaconda prompt and it worked but pycharm didn't recognise it. How do I create the environment in windows promt so it is recognised by pycharm and so that when I import discord, it can be used normally. (Currently says there's no module named discord even though I installed it). I am using this tutorial : Conda env setup video for discord bot , around minute 7:05 of the video is when this youtuber starts explaining how to create a conda env and he gets no errors while I do.
This is the error I get :

C:\Users\PC>conda create -n bot python=3.6

WARNING: The conda.compat module is deprecated and will be removed in a future release.
  Collecting package metadata: failed

CondaHTTPError: HTTP 000 CONNECTION FAILED for url https://repo.anaconda.com/pkgs/msys2/win-64/repodata.json.bz2
  Elapsed: -

An HTTP error occurred when trying to retrieve this URL.
  HTTP errors are often intermittent, and a simple retry will get you on your way.

If your current network has https://www.anaconda.com blocked, please file
  a support request with your network engineering team.

SSLError(MaxRetryError('HTTPSConnectionPool(host=\'repo.anaconda.com\', port=443): Max retries exceeded with url: /pkgs/msys2/win-64/repodata.json.bz2 (Caused by SSLError("Can\'t connect to HTTPS URL because the SSL module is not available."))'))

I have installed python 3.6.8. which is needed for this to work but the problem seems to be with the windows promt error, 10:40 minute mark of the tutorial is when he starts setting up a configuration for his project and his environment has a python symbol but mine has a conda symbol because I used Anaconda powershell to setup the env which obviously doesn't work. And I tried setting it up in windows promt but I get the error shown above. So how do I fix this?

答: I found the solution, I just needed to put the interpreter as python rather than anaconda.</p>


问:
Angular2, what is the correct way to disable an anchor element?
I'm working on an Angular2 application, and I need to display -- but disable an  HTML element. What is the correct way to do this?

Updated

Please note the *ngFor, this would prevent the option of using *ngIf and not rendering the  altogether.

```<code><a *ngFor="let link of links"
   href="#"
   [class.disabled]="isDisabled(link)"
   (click)="onClick(link)">
   {{ link.name }}
</a>
</code>```

The TypeScript component has a method that looks like this:

```<code>onClick(link: LinkObj) {
    // Do something relevant with the object...
    return false;
}
</code>```

I need to actually prevent the element from being clickable, not just appear that it is with the CSS. I was assuming that I needed to potentially bind to the [disabled] attribute at first, but this is incorrect as the anchor element doesn't have a disabled property.

I looked at and considered using the pointer-events: none but this prevents my style of cursor: not-allowed from working -- and this is part of the requirement.

答:
Just use

```<code><a [ngClass]="{'disabled': your_condition}"> This a tag is disabled</a>
</code>```

Example:

```<code> <a [ngClass]="{'disabled': name=='junaid'}"> This a tag is disabled</a>
</code>```

Body:
I'm working on an Angular2 application, and I need to display -- but disable an  HTML element. What is the correct way to do this?

Updated

Please note the *ngFor, this would prevent the option of using *ngIf and not rendering the  altogether.

   {{ link.name }}

The TypeScript component has a method that looks like this:

onClick(link: LinkObj) {
    // Do something relevant with the object...
    return false;
}

I need to actually prevent the element from being clickable, not just appear that it is with the CSS. I was assuming that I needed to potentially bind to the [disabled] attribute at first, but this is incorrect as the anchor element doesn't have a disabled property.

I looked at and considered using the pointer-events: none but this prevents my style of cursor: not-allowed from working -- and this is part of the requirement.

Body:
Just use

<a [ngClass]="{'disabled': your_condition}"> This a tag is disabled</a>

Example:

 <a [ngClass]="{'disabled': name=='junaid'}"> This a tag is disabled</a>


问:
Accessing elements of arrays within an array
Example:

```<code>matrix = np.zeros((2, 2), dtype=np.ndarray)
matrix[0, 0] = np.array([1, 2])
matrix[0, 1] = np.array([3, 4])
matrix[1, 0] = np.array([5, 6])
matrix[1, 1] = np.array([7, 8])
</code>```

I would like to create a matrix from the left entries of each array, i.e.

```<code>[[1, 3], [5, 7]]
</code>```

Is there a shorthand way of doing this? I have tried matrix[:,:][0] but this doesn't yield what I want...

Any help would be much appreciated!

答:
You can use for-loop:

```<code>import numpy as np

matrix = np.zeros((2, 2), dtype=np.ndarray)
matrix[0, 0] = np.array([1, 2])
matrix[0, 1] = np.array([3, 4])
matrix[1, 0] = np.array([5, 6])
matrix[1, 1] = np.array([7, 8])

array = [[matrix[i,j][0] for j in range(2)] for i in range(2)]
</code>```

result: [[1, 3], [5, 7]]

Body:
Example:

matrix = np.zeros((2, 2), dtype=np.ndarray)
matrix[0, 0] = np.array([1, 2])
matrix[0, 1] = np.array([3, 4])
matrix[1, 0] = np.array([5, 6])
matrix[1, 1] = np.array([7, 8])

I would like to create a matrix from the left entries of each array, i.e.

[[1, 3], [5, 7]]

Is there a shorthand way of doing this? I have tried matrix[:,:][0] but this doesn't yield what I want...

Any help would be much appreciated!

Body:
You can use for-loop:

import numpy as np

matrix = np.zeros((2, 2), dtype=np.ndarray)
matrix[0, 0] = np.array([1, 2])
matrix[0, 1] = np.array([3, 4])
matrix[1, 0] = np.array([5, 6])
matrix[1, 1] = np.array([7, 8])

array = [[matrix[i,j][0] for j in range(2)] for i in range(2)]

result: [[1, 3], [5, 7]]


问:
I'm trying to understand how substring call is working in this code?
I know how substring works, but I was trying to understand how it works in the code below. The goal was to find the longest common prefix in an array of strings. The string input was {flower, flow, fleece}. It looks like substring is just taking the entire word of flower, when it's not 0, each time, as 0 to length-1 is going to give the entire word.

```<code> public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    String prefix = strs[0];
    for (int i = 1; i < strs.length; i++)
        while (strs[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
            if (prefix.isEmpty()) return "";
        }
    return prefix;
}
</code>```

The output is fl. I'm just trying to understand why.

答:
the endIndex in substring() is exclusive. So, what the code does is remove the last character from the prefix variable.</p>

```<code>String hello = "hello";
System.out.println(hello.substring(0,hello.length));
// hello
System.out.println(hello.substring(0,hello.length - 1));
// hell
</code>```

Body:
I know how substring works, but I was trying to understand how it works in the code below. The goal was to find the longest common prefix in an array of strings. The string input was {flower, flow, fleece}. It looks like substring is just taking the entire word of flower, when it's not 0, each time, as 0 to length-1 is going to give the entire word.

 public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    String prefix = strs[0];
    for (int i = 1; i < strs.length; i++)
        while (strs[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
            if (prefix.isEmpty()) return "";
        }
    return prefix;
}

The output is fl. I'm just trying to understand why.

Body:
the endIndex in substring() is exclusive. So, what the code does is remove the last character from the prefix variable.

String hello = "hello";
System.out.println(hello.substring(0,hello.length));
// hello
System.out.println(hello.substring(0,hello.length - 1));
// hell


问:
How to iterate over table for getting values of checkbox with checked state?
I have to access and get the values of rows with input checked state.

```<code><table>
<thead>
<tr> <th>#</th> <th>Value 1</th> <th>Value 2</th> <th>Value 3</th> </tr>
</thead>
<tbody>
<tr>
  <td><input type='checkbox' name='1'></td> <td>1</td> <td>1</td> <td>1 </td>
</tr>
<tr>
  <td><input type='checkbox' name='2'></td> <td>2</td> <td>2</td> <td>2 </td>
</tr>
<tr>
  <td><input type='checkbox' name='3'></td> <td>3</td> <td>3</td> <td>3 </td>
</tr>
<tr>
  <td><input type='checkbox' name='4'></td> <td>4</td> <td>4</td> <td>4 </td>
</tr>
</tbody>
</code>```

Suppose I checked the checkbox 1 and 2 the first two line, I try to access just the values of these rows.

What is happening: or the values of all rows is being accessed or When I selected 2 rows just only one is showed.

```<code>$("table tbody tr input:checkbox:checked").each(function(){
        console.log($("table tbody tr").html());
     });
</code>```

答:
You need to use .closest() along with $(this)

```<code>$("table tbody tr input:checkbox:checked").each(function(){
   console.log($(this).closest("tr").html());
});
</code>```

Working sample:-

$("table tbody tr input:checkbox:checked").each(function(){
   console.log($(this).closest("tr").html());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>#</th>
      <th>Value 1</th>
      <th>Value 2</th>
      <th>Value 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type='checkbox' name='1' checked></td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
    </tr>
    <tr>
      <td><input type='checkbox' name='2' checked></td>
      <td>2</td>
      <td>2</td>
      <td>2</td>
    </tr>
    <tr>
      <td><input type='checkbox' name='3'></td>
      <td>3</td>
      <td>3</td>
      <td>3</td>
    </tr>
    <tr>
      <td><input type='checkbox' name='4'></td>
      <td>4</td>
      <td>4</td>
      <td>4</td>
    </tr>
  </tbody>
</table></code>```

Or You need to use .parents() along with $(this)

```<code>$("table tbody tr input:checkbox:checked").each(function(){
   console.log($(this).parents("tr").html());
});
</code>```

Working sample:-

$("table tbody tr input:checkbox:checked").each(function(){
   console.log($(this).parents("tr").html());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>#</th>
      <th>Value 1</th>
      <th>Value 2</th>
      <th>Value 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type='checkbox' name='1' checked></td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
    </tr>
    <tr>
      <td><input type='checkbox' name='2' checked></td>
      <td>2</td>
      <td>2</td>
      <td>2</td>
    </tr>
    <tr>
      <td><input type='checkbox' name='3'></td>
      <td>3</td>
      <td>3</td>
      <td>3</td>
    </tr>
    <tr>
      <td><input type='checkbox' name='4'></td>
      <td>4</td>
      <td>4</td>
      <td>4</td>
    </tr>
  </tbody>
</table></code>```

Body:
I have to access and get the values of rows with input checked state.

 #	 Value 1	 Value 2	 Value 3

  <input type='checkbox' name='1'>	 1	 1	 1

  <input type='checkbox' name='2'>	 2	 2	 2

  <input type='checkbox' name='3'>	 3	 3	 3

  <input type='checkbox' name='4'>	 4	 4	 4

Suppose I checked the checkbox 1 and 2 the first two line, I try to access just the values of these rows.

What is happening: or the values of all rows is being accessed or When I selected 2 rows just only one is showed.

$("table tbody tr input:checkbox:checked").each(function(){
        console.log($("table tbody tr").html());
     });

Body:
You need to use .closest() along with $(this)

$("table tbody tr input:checkbox:checked").each(function(){
   console.log($(this).closest("tr").html());
});

Working sample:-

$("table tbody tr input:checkbox:checked").each(function(){
   console.log($(this).closest("tr").html());
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>#</th>
      <th>Value 1</th>
      <th>Value 2</th>
      <th>Value 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type='checkbox' name='1' checked></td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
    </tr>
    <tr>
      <td><input type='checkbox' name='2' checked></td>
      <td>2</td>
      <td>2</td>
      <td>2</td>
    </tr>
    <tr>
      <td><input type='checkbox' name='3'></td>
      <td>3</td>
      <td>3</td>
      <td>3</td>
    </tr>
    <tr>
      <td><input type='checkbox' name='4'></td>
      <td>4</td>
      <td>4</td>
      <td>4</td>
    </tr>
  </tbody>
</table>

Or You need to use .parents() along with $(this)

$("table tbody tr input:checkbox:checked").each(function(){
   console.log($(this).parents("tr").html());
});

Working sample:-

$("table tbody tr input:checkbox:checked").each(function(){
   console.log($(this).parents("tr").html());
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>#</th>
      <th>Value 1</th>
      <th>Value 2</th>
      <th>Value 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type='checkbox' name='1' checked></td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
    </tr>
    <tr>
      <td><input type='checkbox' name='2' checked></td>
      <td>2</td>
      <td>2</td>
      <td>2</td>
    </tr>
    <tr>
      <td><input type='checkbox' name='3'></td>
      <td>3</td>
      <td>3</td>
      <td>3</td>
    </tr>
    <tr>
      <td><input type='checkbox' name='4'></td>
      <td>4</td>
      <td>4</td>
      <td>4</td>
    </tr>
  </tbody>
</table>


问:
OpenGL shader language; how to specify precision for vec4?
I'm writing a Qt OpenGL application, just starting out with GLSL, and am trying to compile a "simple" fragment shader I found in an example on the web:

#version 320 es
out vec4 fColor;

void main()
{
    fColor = vec4 (0.0, 0.0, 1.0, 1.0);
}
```

<p>But when trying to add this shader from source, I get this error message from Qt's <code>addShaderFromSourceFile()</code>:</p>

<blockquote>
  <p>QOpenGLShader::compile(Fragment):<br>
  0:3(12): warning: extension <code>GL_ARB_fragment_coord_conventions</code> unsupported in fragment shader<br>
  0:1(1): error: No precision specified in this scope for type <code>vec4</code></p>
</blockquote>

<p>What is the proper syntax to declare a precision for type <code>vec4</code>?<br>
I cannot seem to find an example of how to to this for <code>vec4</code>, and trying things like this:</p>

```precision mediump vec4;
```

...results in a syntax error.

Note that I want the shader to run on an embedded system, hence the "#version 320 es" line at the beginning.

答:
vec4 is not a vaild type for a default precision qualifier.

The type in default Precision Qualifiers has to be either int, float or any opaque type (e.g. a sampler is a opaque type).

The precision statement

precision mediump float;
```

<p>affects all floating points (e.g. <code>float</code>, <code>vec2</code>, <code>vec3</code>, <code>vec4</code>, <code>mat3</code>, ...)</p>

<p>A precision qualifier can also be set to single variable:</p>

<pre class="lang-c prettyprint-override"><code>out mediump vec4 fColor;
</code>```

this will overwrite the default precision qualifier.

For details see OpenGL ES Shading Language 3.20 Specification - 4.7. Precision and Precision Qualifiers.

Body:
I'm writing a Qt OpenGL application, just starting out with GLSL, and am trying to compile a "simple" fragment shader I found in an example on the web:

#version 320 es
out vec4 fColor;

void main()
{
    fColor = vec4 (0.0, 0.0, 1.0, 1.0);
}

But when trying to add this shader from source, I get this error message from Qt's addShaderFromSourceFile():

QOpenGLShader::compile(Fragment):

  0:3(12): warning: extension GL_ARB_fragment_coord_conventions unsupported in fragment shader

  0:1(1): error: No precision specified in this scope for type vec4

What is the proper syntax to declare a precision for type vec4?

I cannot seem to find an example of how to to this for vec4, and trying things like this:

precision mediump vec4;

...results in a syntax error.

Note that I want the shader to run on an embedded system, hence the "#version 320 es" line at the beginning.

Body:
vec4 is not a vaild type for a default precision qualifier.

The type in default Precision Qualifiers has to be either int, float or any opaque type (e.g. a sampler is a opaque type).

The precision statement

precision mediump float;

affects all floating points (e.g. float, vec2, vec3, vec4, mat3, ...)

A precision qualifier can also be set to single variable:

out mediump vec4 fColor;

this will overwrite the default precision qualifier.

For details see OpenGL ES Shading Language 3.20 Specification - 4.7. Precision and Precision Qualifiers.


问:
php - Insert data from checkbox array into MySQL
I have a form for registering for weekly summer camps. There are checkboxes to select which camp the person is signing up for that look like this:

```<code><div class="pscdiv"><input type="checkbox" class="psc" name="camps[]" value="psc_1"/><label for="psc_1">AM - Week 1: Camp Description</label></div>
</code>```

There are about 30 of them total. What I'm trying to do is take the $_POST['camps'] variable on the next page and break it into something I can insert into a MySQL table that has a structure like this:

regid | psc_1 | psc_2 | psc_3 | ...

My code:

```<code>
    if(!empty($_POST['camps'])) {
$boxes=$_POST['camps'];
while (list ($k,$camp) = @each ($boxes)) {
    $camp_string .= "'$camp',";
}
}</p>

<p>// The above to create a comma separated string</p>

<p>$camp_string = (substr($camp_string,-1) == ',') ? substr($camp_string, 0, -1) : $camp_string;
// To remove the trailing comma</p>

<p>$newreg_camps = mysql_query("INSERT INTO camps_registered (regid,$camp_string) VALUES ($regid,$camp_string)");
```

The column names (other than regid which I specify earlier in the script) are the same as the data being put into them. It was the easiest thing I could think of at the time.

I'm not sure what I'm missing.

--
Update#1 (in reference to a comment below)

```<code>
if(!empty($_POST['camps'])) {
    $box=$_POST['camps'];
    while (list ($key,$val) = @each ($box)) {
    $camp_totals += $campcost[$val];
    echo "$campdesc[$val] - $$campcost[$val]<br />";
}
}
```

答:
Why not name the checkboxes something different like the names of the columns, so that your $_POST comes back as:

```<code>// print_r($_POST);
array(
     'regID' => 1,
     'camp_filmore' => 1,
     'camp_greenwald' => 1
     'camp_idunno' => 1
);
</code>```

From there it's fairly simple to build your query:

```<code>$query = "INSERT INTO registered (".implode(array_keys($_POST), ", ") . ") ".
    "VALUES (" . implode(array_values($_POST), ", ").")";
</code>```

You should obviously check to make sure the values of $_POST are properly escaped and sanitized before inserting.

Body:
I have a form for registering for weekly summer camps. There are checkboxes to select which camp the person is signing up for that look like this:

<input type="checkbox" class="psc" name="camps[]" value="psc_1"/>AM - Week 1: Camp Description

There are about 30 of them total. What I'm trying to do is take the $_POST['camps'] variable on the next page and break it into something I can insert into a MySQL table that has a structure like this:

regid | psc_1 | psc_2 | psc_3 | ...

My code:

    if(!empty($_POST['camps'])) {
$boxes=$_POST['camps'];
while (list ($k,$camp) = @each ($boxes)) {
    $camp_string .= "'$camp',";
}
}

// The above to create a comma separated string

$camp_string = (substr($camp_string,-1) == ',') ? substr($camp_string, 0, -1) : $camp_string;
// To remove the trailing comma

$newreg_camps = mysql_query("INSERT INTO camps_registered (regid,$camp_string) VALUES ($regid,$camp_string)");

The column names (other than regid which I specify earlier in the script) are the same as the data being put into them. It was the easiest thing I could think of at the time.

I'm not sure what I'm missing.

--
Update#1 (in reference to a comment below)

if(!empty($_POST['camps'])) {
    $box=$_POST['camps'];
    while (list ($key,$val) = @each ($box)) {
    $camp_totals += $campcost[$val];
    echo "$campdesc[$val] - $$campcost[$val]
";
}
}

Body:
Why not name the checkboxes something different like the names of the columns, so that your $_POST comes back as:

// print_r($_POST);
array(
     'regID' => 1,
     'camp_filmore' => 1,
     'camp_greenwald' => 1
     'camp_idunno' => 1
);

From there it's fairly simple to build your query:

$query = "INSERT INTO registered (".implode(array_keys($_POST), ", ") . ") ".
    "VALUES (" . implode(array_values($_POST), ", ").")";

You should obviously check to make sure the values of $_POST are properly escaped and sanitized before inserting.


问:
What is the difference between char s[] and char *s?
In C, one can use a string literal in a declaration like this:

```<code>char s[] = "hello";
</code>```

or like this:

```<code>char *s = "hello";
</code>```

So what is the difference? I want to know what actually happens in terms of storage duration, both at compile and run time.

答:
```<code>char *s1 = "Hello world"; // Points to fixed character string which is not allowed to modify
char s2[] = "Hello world"; // As good as fixed array of characters in string so allowed to modify

// s1[0] = 'J'; // Illegal
s2[0] = 'J'; // Legal
</code>```

Body:
In C, one can use a string literal in a declaration like this:

char s[] = "hello";

or like this:

char *s = "hello";

So what is the difference? I want to know what actually happens in terms of storage duration, both at compile and run time.