问:
How to fetch data from two tables based on session variable php?
Actually im trying to display data from 2 tables on database based on current session, basically, i had read many article and forum on how to solve this problem but i still facing them till now. so those are data and code that already i did:

```<code><?php
include('db.php');

$sql="SELECT*
FROM users
INNER JOIN details ON users.id= details.id LIMIT 1 WHERE users.id ='$loggedin_id' " ;

$result=mysqli_query($db,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($db));
exit();
}
?>
</code>```

so here, i got this error:
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE users.id = '16'' at line 3". so if i only use this query:

```<code> $sql="SELECT* FROM users INNER JOIN details ON users.id= details.id"
</code>```

it will display all data in my database, but i only need data from current session.

here is my session.php file:

```<code><?php
include('db.php');
session_start();
$user_check=$_SESSION['sess_username'];
$ses_sql=mysqli_query($db,"select username,id from users where username='$user_check' ");
$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$loggedin_session=$row['username'];
$loggedin_id=$row['id'];
$role = $_SESSION['sess_userrole'];
if(!isset($loggedin_session) && $role!="user"){
  header('Location: index.php?err=2');
}
?>
</code>```

this is my tables detail:
table users
table details

hope someone can help me, im new with my sql and php. tq

答:
I think your query should be like below: </p>

```<code>$sql = "SELECT * FROM users
INNER JOIN details ON users.id= details.id  WHERE users.id = $loggedin_id ";
</code>```

Body:
Actually im trying to display data from 2 tables on database based on current session, basically, i had read many article and forum on how to solve this problem but i still facing them till now. so those are data and code that already i did:

<?php
include('db.php');

$sql="SELECT*
FROM users
INNER JOIN details ON users.id= details.id LIMIT 1 WHERE users.id ='$loggedin_id' " ;

$result=mysqli_query($db,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($db));
exit();
}
?>

so here, i got this error:
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE users.id = '16'' at line 3". so if i only use this query:

 $sql="SELECT* FROM users INNER JOIN details ON users.id= details.id"

it will display all data in my database, but i only need data from current session.

here is my session.php file:

<?php
include('db.php');
session_start();
$user_check=$_SESSION['sess_username'];
$ses_sql=mysqli_query($db,"select username,id from users where username='$user_check' ");
$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$loggedin_session=$row['username'];
$loggedin_id=$row['id'];
$role = $_SESSION['sess_userrole'];
if(!isset($loggedin_session) && $role!="user"){
  header('Location: index.php?err=2');
}
?>

this is my tables detail:
table users
table details

hope someone can help me, im new with my sql and php. tq

Body:
I think your query should be like below:

$sql = "SELECT * FROM users
INNER JOIN details ON users.id= details.id  WHERE users.id = $loggedin_id ";


来源: stackexchange

问:
Path name can't find in java

Project File

config Folder

specificfiles.props

This is where my properties located but still it can't find the path..

I tried this

```<code>input = MainClass.class.getResourceAsStream("/config/specificfiles.props");
        if(input==null){
                System.out.println("Sorry, unable to find ");
            return;
        }
</code>```

and also this

```<code>String filename = "specificfiles.props";
        input = MainClass.class.getClassLoader().getResourceAsStream(filename);
        if(input==null){
                System.out.println("Sorry, unable to find " + filename);
            return;
        }
</code>```

I also tried these things no work.

specificfiles.props

/specificfiles.props

config/specificfiles.props

ProjectName/config/specificfiles.props

I try to search on other questions here but nothing solves my problem..
Please help!

答:
Resources and files are completely different, don't confuse them.

Resources are searched in the class path, therefore they are usually not placed in the root folder of the project but besides the source code. Or in Maven projects into src/main/resources.

ContentLicense: CC BY-SA 3.0

Title: Path name can't find in java

Body:
Project File

config Folder

specificfiles.props

This is where my properties located but still it can't find the path..

I tried this

input = MainClass.class.getResourceAsStream("/config/specificfiles.props");
        if(input==null){
                System.out.println("Sorry, unable to find ");
            return;
        }

and also this

String filename = "specificfiles.props";
        input = MainClass.class.getClassLoader().getResourceAsStream(filename);
        if(input==null){
                System.out.println("Sorry, unable to find " + filename);
            return;
        }

I also tried these things no work.

specificfiles.props

/specificfiles.props

config/specificfiles.props

ProjectName/config/specificfiles.props

I try to search on other questions here but nothing solves my problem..
Please help!


问:
type lost when using java8 stream api
code first:

```<code>    net.sf.json.JSONArray ja = new net.sf.json.JSONArray();
    for (int i = 0; i < 3; i++) {
        net.sf.json.JSONObject obj = new net.sf.json.JSONObject();
        obj.put("number", "k"+i);
        ja.add(obj);
    }
    System.out.println(ja.stream().map(s->((net.sf.json.JSONObject)s).getString("number")).peek(s->System.out.println(s.getClass())).collect(Collectors.joining(";")));
</code>```

as you can see, I try to get a String of JSONObject and join them. And it works above like this:

```<code>    class java.lang.String
    class java.lang.String
    class java.lang.String
    k0;k1;k2
</code>```

However ja.stream().map(s->((JSONObject)s).getString("number")) seems return not a Stream<String> but Stream<Object> which I couldn't append String intermidiate operation like .map(s->s.substring(3)). In other words, type lost.

So can anybody give any advice?

答:
Breaking down your stream statement does result in:

```<code>net.sf.json.JSONArray ja = new net.sf.json.JSONArray();
Stream stream1 = ja.stream();
Stream stream2 = stream1.map(s -> ((JSONObject) s).getString("number"));
</code>```

As you can see, stream1 is not of a generic type. Hence any transformations will not produce a generic type out of a non generic type. Changing either variable ja or variable stream1 to a generic type will result in a Stream<String> for variable stream2:

```<code>net.sf.json.JSONArray ja = new net.sf.json.JSONArray();
Stream<Object> stream1 = ja.stream();
Stream<String> stream2 = stream1.map(s -> ((JSONObject) s).getString("number"));
</code>```

Hence if you want to preserve type information you need a generic type which may carry it.

Title: type lost when using java8 stream api

Body:
code first:

    net.sf.json.JSONArray ja = new net.sf.json.JSONArray();
    for (int i = 0; i < 3; i++) {
        net.sf.json.JSONObject obj = new net.sf.json.JSONObject();
        obj.put("number", "k"+i);
        ja.add(obj);
    }
    System.out.println(ja.stream().map(s->((net.sf.json.JSONObject)s).getString("number")).peek(s->System.out.println(s.getClass())).collect(Collectors.joining(";")));

as you can see, I try to get a String of JSONObject and join them. And it works above like this:

    class java.lang.String
    class java.lang.String
    class java.lang.String
    k0;k1;k2

However ja.stream().map(s->((JSONObject)s).getString("number")) seems return not a Stream<String> but Stream<Object> which I couldn't append String intermidiate operation like .map(s->s.substring(3)). In other words, type lost.

So can anybody give any advice?

Body:
Breaking down your stream statement does result in:

net.sf.json.JSONArray ja = new net.sf.json.JSONArray();
Stream stream1 = ja.stream();
Stream stream2 = stream1.map(s -> ((JSONObject) s).getString("number"));

As you can see, stream1 is not of a generic type. Hence any transformations will not produce a generic type out of a non generic type. Changing either variable ja or variable stream1 to a generic type will result in a Stream<String> for variable stream2:

net.sf.json.JSONArray ja = new net.sf.json.JSONArray();
Stream<Object> stream1 = ja.stream();
Stream<String> stream2 = stream1.map(s -> ((JSONObject) s).getString("number"));

Hence if you want to preserve type information you need a generic type which may carry it.


问:
How to create the = and + key with kbd tag?
+ or += can't create the following key.

[

How to create a key gui which chracter + is at the top of  character = with kbd tag or something else?

答:
In Plain HTML

Use the
 tag to break the signs as follows

The markup

```<code><kbd>+<br/>=</kbd>
</code>```

The output

+
=

The code

+
=```
</div>
</div>
</p>

<h2>In JavaScript</h2>

<h3>How to do this</h3>

<blockquote>
  <p>Get the innerHTML of <code>kbd</code> tag, use JavaScript <code>split</code> function with <code>""</code>, then it will split each character and make an array.
  Then Join the array with <code><br /></code> and then add it as the <code>innerHTML</code> of the same <code>kbd</code> tag</p>
</blockquote>

<h3>References</h3>

<ol>
<li>String.prototype.split</li>
<li>Array.prototype.join</li>
<li>element.innerHTML</li>
</ol>

<h3>Code</h3>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var kbd=document.getElementsByTagName("kbd")[0];
kbd.innerHTML=kbd.innerHTML.split("").join("<br />");</code>```

+=```
</div>
</div>
</p>

<blockquote>
  <p>In JavaScript, it is recommended to put the JavaScript just above the closing <code></body></code> tag. Then only it can find the corresponding element.</p>
</blockquote>

<p>That is</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <kbd>+=</kbd>
  <script>
      var kbd=document.getElementsByTagName("kbd")[0];
      kbd.innerHTML=kbd.innerHTML.split("").join("<br />");
  </script>
</body></code>```

In JavaScript, based on Events

Try clicking on the button and the  will change.

function change(index){
  var kbd=document.getElementsByTagName("kbd")[0];
  kbd.innerHTML=kbd.innerHTML.split("").join("
");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><kbd>+=</kbd>
<br />
<button onclick="change();">Change(0)</button></code>```

JavaScript Solution if you want to change multiple items.

Try clicking on the button and the corresponding  will be changed.

function change(index){
  var kbd=document.getElementsByTagName("kbd")[index];
  kbd.innerHTML=kbd.innerHTML.split("").join("
");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><kbd>+=</kbd>
<br />
<button onclick="change(0);">Change(0)</button>
<br />
<kbd>+=</kbd>
<br />
<button onclick="change(1);">Change(1)</button>
<br />
<kbd>+=</kbd>
<br />
<button onclick="change(2);">Change(2)</button>
<br />
<kbd>+=</kbd>
<br />
<button onclick="change(3);">Change(3)</button></code>```

Body:
In Plain HTML

Use the <br /> tag to break the signs as follows

The markup

<kbd>+<br/>=</kbd>

The output

+
=

The code

<kbd>+<br />=</kbd>

In JavaScript

How to do this

Get the innerHTML of kbd tag, use JavaScript split function with "", then it will split each character and make an array.
  Then Join the array with <br /> and then add it as the innerHTML of the same kbd tag

References

String.prototype.split

Array.prototype.join

element.innerHTML

Code

var kbd=document.getElementsByTagName("kbd")[0];
kbd.innerHTML=kbd.innerHTML.split("").join("<br />");

<kbd>+=</kbd>

In JavaScript, it is recommended to put the JavaScript just above the closing </body> tag. Then only it can find the corresponding element.

That is

<body>
  <kbd>+=</kbd>
  <script>
      var kbd=document.getElementsByTagName("kbd")[0];
      kbd.innerHTML=kbd.innerHTML.split("").join("<br />");
  </script>
</body>

In JavaScript, based on Events

Try clicking on the button and the <kbd> will change.

function change(index){
  var kbd=document.getElementsByTagName("kbd")[0];
  kbd.innerHTML=kbd.innerHTML.split("").join("<br />");
}

<kbd>+=</kbd>
<br />
<button onclick="change();">Change(0)</button>

JavaScript Solution if you want to change multiple items.

Try clicking on the button and the corresponding <kbd> will be changed.

function change(index){
  var kbd=document.getElementsByTagName("kbd")[index];
  kbd.innerHTML=kbd.innerHTML.split("").join("<br />");
}

<kbd>+=</kbd>
<br />
<button onclick="change(0);">Change(0)</button>
<br />
<kbd>+=</kbd>
<br />
<button onclick="change(1);">Change(1)</button>
<br />
<kbd>+=</kbd>
<br />
<button onclick="change(2);">Change(2)</button>
<br />
<kbd>+=</kbd>
<br />
<button onclick="change(3);">Change(3)</button>


问:
how to multiply ith maximum element in two list , and then get summation of the results
list1=[1,2,3,4,5,6,7]
list2=[6,4,5]
I want to compute multiplication of ith maximum element pair from the two list, and then summation of the results, like 6*7+5*6+4*5.
Is there any python trick with short coding.</p>

答:
you may try this way...</p>

```<code>list1=[2,3,4,5,7,1,6]
list2 = [4,6,5]

list1 = sorted(list1,reverse = True)
list2 = sorted(list2, reverse=True)
sum = 0
length = min(len(list1),len(list2))
for i in range(length):
    sum =sum + list1[i]*list2[i]
print sum
</code>```

Body:
you may try this way...

list1=[2,3,4,5,7,1,6]
list2 = [4,6,5]

list1 = sorted(list1,reverse = True)
list2 = sorted(list2, reverse=True)
sum = 0
length = min(len(list1),len(list2))
for i in range(length):
    sum =sum + list1[i]*list2[i]
print sum


问:
Laravel : Removing an element from a collection array
i use a variable called $users to "pluck" only the emails from my users table, using:

$users = user::all()->pluck('email');

when i dd($users), i get this

```<code>```
Collection {#214 ▼
  #items: array:8 [▼
    0 => "adminone@example.com"
    1 => "admintwo@example.com"
    2 => "Adobot@example.com"
    3 => "Lawly@example.com"
    4 => "Cerms@example.com"
    5 => "Charlie@example.com"
    6 => "test@example.com"
    7 => "test001@example.com"
  ]
}
```
</code>```

meaning that $users isn't purely an array, i get various types of errors when i treat it like an array.

my question is, in php (in a Laravel Framework) how do i remove a specific user's email from the variable above? or is there a better way to use "pluck" so that it returns an array instead?

thanks in advance.

答:
You would want to use ->forget()

```<code>$collection->forget($key);
</code>```

Or you can use reject method

```<code>$newColection = $collection->reject(function($element) {
    return $element === 'emailaddress@';
});
</code>```

Body:
i use a variable called $users to "pluck" only the emails from my users table, using:

$users = user::all()->pluck('email');

when i dd($users), i get this

Collection {#214 ▼
  #items: array:8 [▼
    0 => "adminone@example.com"
    1 => "admintwo@example.com"
    2 => "Adobot@example.com"
    3 => "Lawly@example.com"
    4 => "Cerms@example.com"
    5 => "Charlie@example.com"
    6 => "test@example.com"
    7 => "test001@example.com"
  ]
}

meaning that $users isn't purely an array, i get various types of errors when i treat it like an array.

my question is, in php (in a Laravel Framework) how do i remove a specific user's email from the variable above? or is there a better way to use "pluck" so that it returns an array instead?

thanks in advance.

Body:
You would want to use ->forget()

$collection->forget($key);

Or you can use reject method

$newColection = $collection->reject(function($element) {
    return $element === 'emailaddress@';
});


问:
Merging dev and live prestashop databases
I have extensive modifications to carry out on a prestashop 1.6 site.

I have created a local copy, and am tracking filesystem changes in git.

However a lot of changes in prestashop are stored in the database, specifically in my case:

Installing and configuring a new module

Uninstalling a module

Adding shop categories and changing the hierarchy

Changing module positions

and generally modifying what modules appear in what hooks.

During the dev process, the live site has received numerous new orders, customers, subscribers etc, so the databases are out of sync.

I have solved similar problems in other frameworks by dumping and importing specific tables in the db, or using the frameworks built in migrations functionality, but i cannot find any advise specifically for prestashop.

How is this handled?

Considering that the dev site has probably undergone more diverse changes than the live one, i wonder if it would be easier to copy the new orders etc over to the dev site then overwrite the whole thing?

答:
For modules the information is stored in all tables which start with modules.
Module config values are stored in configuration and configuration_lang. Make sure you also copy custom module tables of course.

Shop categories information is in all tables which start with category.

Module hooks information is in all tables which start with hook.

However as Raghubendra Singh said in his answer this is very risky task, if you really really want to do it, I suggest you create another local copy of currently live site and first try the process between two local copies and make sure everything works correctly.


问:
Import Android projects in Android Studio
I want to use a sample Android project in Android Studio.
it project struct is different. how to use that sample project.

the project structure is like

what I tried:

I try to open projects as "Open projects as Eclipse ADT, Gradle, etc..".
After opening, the application is not runnable using the run icon (icon not in green color).

答:
In Android Studio, You have to import the Project

```<code>File->New->import project
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In Android Studio, You have to import the Project

File->New->import project


问:
CORS setting on google cloud bucket
I am trying to configure CORS on a google bucket.I want to set CORS config every time i create a new bucket. I want to get this done by  Cloud Storage Client Libraries, not using XML API. Is there a way around it?</p>

答:
None of the Cloud Storage Client Libraries in any language appear to provide the ability to directly set the CORS config. So it seems the only options are either to use the XML API with the cors param or else to do it from the command line using gsutil and a JSON config file, like this:

```<code>gsutil cors set cors-json-file.json gs://[my-bucket]
</code>```

Where cors-json-file.json is something like this:

```<code>[
  {
    "origin": ["*"],
    "responseHeader": ["Content-Type"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]
</code>```

Title: CORS setting on google cloud bucket

Body:
None of the Cloud Storage Client Libraries in any language appear to provide the ability to directly set the CORS config. So it seems the only options are either to use the XML API with the cors param or else to do it from the command line using gsutil and a JSON config file, like this:

gsutil cors set cors-json-file.json gs://[my-bucket]

Where cors-json-file.json is something like this:

[
  {
    "origin": ["*"],
    "responseHeader": ["Content-Type"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]


问:
Is there a C# equivalent to access-modifier regions in C++
It's possible to declare variables with the below structure in C++

```<code>private:
public:
protected:
    float bla1;
    float bla2;
    float bla3;
</code>```

Is there an equivalent in C#? It seems rather tedious having to repeat yourself;

```<code>protected float bla1;
protected float bla2;
protected float bla3;
</code>```

答: No there isn't such a thing. In fact, it's designed to be like that to make code more readable. This applies to both C# and Java.</p>

OwnerDisplayName: Adam Naylor

Body:
It's possible to declare variables with the below structure in C++

private:
public:
protected:
    float bla1;
    float bla2;
    float bla3;

Is there an equivalent in C#? It seems rather tedious having to repeat yourself;

protected float bla1;
protected float bla2;
protected float bla3;

OwnerDisplayName: Mehrdad Afshari

ContentLicense: CC BY-SA 2.5


问:
(CodeIgniter query builder) I'm getting a database insert error even though the insertion process works fine in the background
```<code>public function answerSurvey() {
    $id = $this->uri->segment(3);
    $i = 0;
    $reserved = $this->mAttendee->getReserve($id, $this->session->username);
    $zxc = $reserved->registration_id;
    foreach ($_POST as $sample) {
        $value = $this->input->post("question_$i");
        $question = $this->input->post("id_$i");
        $qwe = array('answer_value' => $value, 'question_id' => $question, 'user_id' => $id);
        $this->MSurvey->addAnswer($qwe,$zxc);
        $i++;
    }
    redirect(base_url() . "attendee/viewEvent/$id");
</code>```

Above is the snippet in my controller where I pass data from my looped post values into the database. When I run this method, I get a database error that says something along the lines like

'answer_value' and 'question_i' cannot be null

even though as you can see I passed data onto these values through the $value and $question variables. When I checked the database, the process of insertion seems to be working fine as my data is passed onto the tables. Why am I getting this error and how can I fix it? My current solution was disabling the debugging in the database config. Thank you.

答:
I see that you have much more elements in array $_POST than you expected in your loop eg. for array

```<code>array(
    'question_0' => 'a',
    'question_1' => 'b',
    'id_0' => '1',
    'id_1' => '2',
);
</code>```

Your loop will iterate 4 times so for third and fourth iteration it will generate errors because items like question_3, question_4 etc. does not exists in $_POST so $this->input->post("id_$i") returns NULL.

Body:
public function answerSurvey() {
    $id = $this->uri->segment(3);
    $i = 0;
    $reserved = $this->mAttendee->getReserve($id, $this->session->username);
    $zxc = $reserved->registration_id;
    foreach ($_POST as $sample) {
        $value = $this->input->post("question_$i");
        $question = $this->input->post("id_$i");
        $qwe = array('answer_value' => $value, 'question_id' => $question, 'user_id' => $id);
        $this->MSurvey->addAnswer($qwe,$zxc);
        $i++;
    }
    redirect(base_url() . "attendee/viewEvent/$id");

Above is the snippet in my controller where I pass data from my looped post values into the database. When I run this method, I get a database error that says something along the lines like

'answer_value' and 'question_i' cannot be null

even though as you can see I passed data onto these values through the $value and $question variables. When I checked the database, the process of insertion seems to be working fine as my data is passed onto the tables. Why am I getting this error and how can I fix it? My current solution was disabling the debugging in the database config. Thank you.

Body:
I see that you have much more elements in array $_POST than you expected in your loop eg. for array

array(
    'question_0' => 'a',
    'question_1' => 'b',
    'id_0' => '1',
    'id_1' => '2',
);

Your loop will iterate 4 times so for third and fourth iteration it will generate errors because items like question_3, question_4 etc. does not exists in $_POST so $this->input->post("id_$i") returns NULL.


问:
How to make a drag & drop for NSTableCellView like this
I'm trying to implement a drag & drop for NSTableCellView look like screenshot, but the only thing i can do just the text, not a whole cell like screenshot bellow :(

答:
Drag and Drop Programming

The Dragged Image

The image that is dragged in a dragging session is simply an image
  that represents the data on the pasteboard. Although a dragging
  destination can access the image, its primary concern is with the
  pasteboard data that the image represents—the dragging operation that
  a destination ultimately performs is on the pasteboard data, not on
  the image itself.

See Custom drag image with NSTableView as drag source


问:
Merge default options containing object with JSON Object
I need to merge these two objects to get below output using JS. Thanks in advance and its ok to use jquery library if needed

var defaultOptions = {
        count:3
    };

    var JSON = {
      one:{
        title:"something",
        count:15
      },
      two:{
        title:"another"
      }
    }

    // expecting

    var JSON = {
      one:{
        title:"something",
        count:15
      },
      two:{
        title:"another",
        count:3
      }
    }```

答:
Try this.

var defaultOptions = {
        count:3
    };

    var someObject = {
      one:{
        title:"something",
        count:15
      },
      two:{
        title:"another"
      }
    }

   for (var property in someObject) {
    if (someObject[property].count == undefined) {
       console.log(someObject[property]);
       someObject[property].count = defaultOptions.count;
       console.log(someObject[property]);
    }
}```


问:
How to create dynamic folder selection parameter in Jankins pipeline
I am trying to use Jenkins as a tool as an automation build.
So, I need to create a pipline with parameter that helps me to select an appropriate directory where I start a build batch file.
By the moment, I have found how to select a directory as a parameter by usage of Extensible Choice plugin.
But it allows me to select a folder at one level, but I need to go deeper and get an oportunity to select via multilevel directory levels.
For example, select directory at level1 and than at level2 and finaly at level3.
Could you please give me any advise how to do that?</p>

答: Use groovy script in pipeline job to dynamically assign the directory </p>


问:
sizeof operator in c
please can anybody help me to implement sizeof() operator in c..

i know the usage .. but i was not able to implement it.

答: You cannot implement sizeof() as a library function, it is a compiler intrinsic. Are you writing a compiler?

Title: sizeof operator in c


问:
Using void pointers in function signarture
I've recently inherited some (undocumented) C code that contains several instances of this pattern:

```<code>void my_function(void *_foo, const void *_bar) {
    MyType *foo = (MyType *)_foo;
    MyType *bar = (MyType *)_bar;
</code>```

I'm pretty familiar with C but I can't for the life of me figure out why the function consumes void pointers. Isn't this just going to suppress potentially helpful compiler warnings if the wrong type is passed in anywhere? Or is there a sensible method behind it that I am new to?

答:
Generally, the void * is used as an abstraction i.e. you can pass pointers of different types using void * to a function and later depending on appropriate conditions, you can typecast the void * to the correct type and use it.

Another usage could be when the calling function is in a logically separate unit like a library and doesn't have access to the correct type to which the pointer belongs. But, still the data has to pass through that function.

I used to use such abstraction mechanisms with callbacks. For Example, if I am calling a library which function which eventually calls my callback and I want some data of application in my callback, but, the library function has no use of it, then I will pass such data typecasted as void * to the library function and on receiving that data in the callback, I will typecast it to appropriate type and use it.

Body:
I've recently inherited some (undocumented) C code that contains several instances of this pattern:

void my_function(void *_foo, const void *_bar) {
    MyType *foo = (MyType *)_foo;
    MyType *bar = (MyType *)_bar;

I'm pretty familiar with C but I can't for the life of me figure out why the function consumes void pointers. Isn't this just going to suppress potentially helpful compiler warnings if the wrong type is passed in anywhere? Or is there a sensible method behind it that I am new to?


问:
d3 javascript series chart

I am trying to create this particular d3 application where a series of data can be dynamically displayed like this. Each segment contains two pieces of data.

The first step is to print the circles so there is sufficient space between the series but also the largest circle is always under the smaller circle.

//version 3 -- with correct labels and legend--
http://jsfiddle.net/0ht35rpb/33/

//******version 2 fiddle******
http://jsfiddle.net/1oka61mL/10/

-- How to set the diagonal labels properly - same angles, aligned properly?
-- Add legend?
-- Mask the bottom pointers in an opposite color then continue the line in a different color?

//******Latest Jsfiddle******
http://jsfiddle.net/0ht35rpb/26/

```<code>var width = 600;
var height = 400;
var svg = d3.select('svg').attr("width", width).attr("height", height);

//Count
//Checkins
//Popularity

var data = [{
  "name": "Twitter",
  "items": [{
    "id": 0,
    "label": "Count",
    "value": 200
  }, {
    "id": 1,
    "label": "Checkins",
    "value": 1000
  }, {
    "id": 2,
    "label": "Popularity",
    "value": 30
  }]
}, {
  "name": "Facebook",
  "items": [{
    "id": 0,
    "label": "Count",
    "value": 500
  }, {
    "id": 1,
    "label": "Checkins",
    "value": 300
  }, {
    "id": 2,
    "label": "Popularity",
    "value": 740
  }]
}, {
  "name": "Ebay",
  "items": [{
    "id": 0,
    "label": "Count",
    "value": 4000
  }, {
    "id": 1,
    "label": "Checkins",
    "value": 1000
  }, {
    "id": 2,
    "label": "Popularity",
    "value": 40
  }]
}, {
  "name": "Foursquare",
  "items": [{
    "id": 0,
    "label": "Count",
    "value": 2000
  }, {
    "id": 1,
    "label": "Checkins",
    "value": 3000
  }, {
    "id": 2,
    "label": "Popularity",
    "value": 4500
  }]
}];

var outerRadius = [];
// organise the data.
// Insert indices and sort items in each series
// keep a running total of max circle size in each series
// for later positioning
var x = 0;
var totalWidth = d3.sum(
  data.map(function(series) {
    series.items.forEach(function(item, i) {
      item.index = i;
    });
    series.items.sort(function(a, b) {
      return b.value - a.value;
    });
    var maxr = Math.sqrt(series.items[0].value);
    outerRadius.push(maxr);
    x += maxr;
    series.xcentre = x;
    x += maxr;
    return maxr * 2;
  })
);

// make scales for position and colour
var scale = d3.scale.linear().domain([0, totalWidth]).range([0, width]);
//var colScale = d3.scale.category10();

function colores_google(n) {
  var colores_g = ["#f7b363", "#448875", "#c12f39", "#2b2d39", "#f8dd2f"];
  return colores_g[n % colores_g.length];
}

// add a group per series, position the group according to the values and position scale  we calculated above
var groups = svg.selectAll("g").data(data);
groups.enter().append("g");
groups.attr("transform", function(d) {
  return ("translate(" + d.xcentre + ",0)");
});

// then add circles per series, biggest first as items are sorted
// colour according to index (the property we inserted previously so we can
// keep track of their original position in the series)
var circles = groups.selectAll("circle").data(function(d) {
  return d.items;
}, function(d) {
  return d.index;
});
circles.enter().append("circle").attr("cy", height / 2).attr("cx", 0);

circles
  .attr("r", function(d) {
    return Math.sqrt(d.value);
  })
  .style("fill", function(d) {
    return colores_google(d.index);
  });

var labelsgroups = svg.selectAll("text").data(data);
labelsgroups.enter().append("text");
labelsgroups
  .attr("y", function(d, i) {
    d.y = 300;
    d.cy = 200;
    return 300;
  })
  .attr("x", function(d) {
    d.x = d.xcentre;
    d.cx = d.xcentre;
    return d.xcentre;
  })
  .text(function(d) {
    return d.name;
  })
  .each(function(d) {
    var bbox = this.getBBox();
    d.sx = d.x - bbox.width / 2 - 2;
    d.ox = d.x + bbox.width / 2 + 2;
    d.sy = d.oy = d.y + 5;
  })
  .attr("text-anchor", "middle");

var pointersgroups = svg.selectAll("path.pointer").data(data);
pointersgroups.enter().append("path");
pointersgroups
  .attr("class", "pointer")
  .attr("marker-end", "url(#circ)");

pointersgroups
  .attr("d", function(d) {
    return "M" + (d.xcentre) + "," + (d.oy - 25) + "L" + (d.xcentre) + "," + (d.sy - 25) + " " + d.xcentre + "," + (d.cy);
  })

function fetchValue(items, label) {
  for (i = 0; i <= items.length; i++) {
    if (items[i].label == label) {
      return items[i].value;
    }
  }
}

function fetchRadius(items, label) {
  for (i = 0; i <= items.length; i++) {
    if (items[i].label == label) {
      return Math.sqrt(items[i].value);
    }
  }
}

/*
var labels1groups = svg.selectAll(".label1").data(data);
labels1groups.enter().append("text");
labels1groups
  .attr("class", "label1")
  .attr("y", function(d, i) {
    d.y = 100;
    d.cy = 100;
    return 100;
  })
  .attr("x", function(d) {
    d.x = d.xcentre;
    d.cx = d.xcentre+50;
    return d.xcentre+50;
  })
  .text(function(d) {
    return fetchValue(d.items, "Count");
  })
  .attr("transform", function(d, i) {
            return "translate(" + (15 * i) + "," + (i * 45) + ") rotate(-45)";

  })
  .each(function(d) {
    var bbox = this.getBBox();
    d.sx = d.x - bbox.width / 2 - 2;
    d.ox = d.x + bbox.width / 2 + 2;
    d.sy = d.oy = d.y ;
  })
  .attr("text-anchor", "left");

*/

var gridSize = 100;

var labels1groups = svg.selectAll(".label2")
  .data(data)
  .enter().append("text")
  .text(function(d) {
    return fetchValue(d.items, "Count");
    //return d;
  })
  .attr("x", function(d, i) {

    d.x = i * gridSize + 50;
    d.cx = i * gridSize + 50;

    return i * gridSize;
  })
  .attr("y", function(d, i) {
    d.y = 105;
    d.cy = 50;
    return 0;
  })
  .attr("transform", function(d, i) {
    return "translate(" + gridSize / 2 + ", -6)" +
      "rotate(-45 " + ((i + 0.5) * gridSize) + " " + (-6) + ")";
  })
  .each(function(d) {
    var bbox = this.getBBox();
    d.sx = d.x - bbox.width / 2 - 2;
    d.ox = d.x + bbox.width / 2 + 2;
    d.sy = d.oy = d.y;
  })
  .style("text-anchor", "end")
  .attr("class", function(d, i) {
    return ((i >= 8 && i <= 16) ?
      "timeLabel mono axis axis-worktime" :
      "timeLabel mono axis");
  });

var pointers1groups = svg.selectAll("path.pointer1").data(data);
pointers1groups.enter().append("path");
pointers1groups
  .attr("class", "pointer1")
  .attr("marker-end", "url(#circ)");

pointers1groups
  .attr("d", function(d, i) {

    //d.y = outerRadius[i];
    //d.y = d.oy - d.cy;
    //fetchRadius(d.items, "Count");

    //(d.xcentre+100)
    // + " " + d.cx + "," + d.cy

    //return "M "+ (d.xcentre) +" 25 ,L "+ dist +" 75";

    return "M" + (d.xcentre) + "," + (d.y + d.oy - fetchRadius(d.items, "Count") - 10) + "L" + (d.xcentre + 80) + "," + d.cy;

  })
</code>```

//Older Jsfiddle
http://jsfiddle.net/59bunh8u/51/

```<code>var rawData = [{
    "name": "Twitter",
    "items" : [
        {
            "label" : "15 billion",
            "unit" : "per day",
            "value" : 1500
        },
        {
            "label" : "450 checkins",
            "unit" : "per day",
            "value" : 450
        }
    ]
},
{
    "name": "Facebook",
    "items" : [
        {
            "label" : "5 billion",
            "unit" : "per day",
            "value" : 5000
        },
        {
            "label" : "2000 checkins",
            "unit" : "per day",
            "value" : 2000
        }
    ]
}];

$.each(rawData, function(index, value) {
    var total = 0;
    var layerSet = [];
    var ratios = [25, 100];

    $.each(value["items"], function(i, v) {
        total += v["value"];
    });

    value["total"] = total;
});

var w = $this.data("width");
var h = $this.data("height");

var el = $this;

var margin = {
    top: 65,
    right: 90,
    bottom: 5,
    left: 150
};

var svg = d3.select(el[0]).append("svg")
    .attr("class", "series")
    .attr("width", w + margin.left + margin.right)
    .attr("height", h + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var defs = svg.append("svg:defs");

$.each(rawData, function(i, v) {
    circleDraw(i, v["items"]);
});

//calculates where each element should be placed
function calculateDistance (d, i, items) {
    var dcx = 0;
    for (var k = 0; k < i; k++) {
      dcx += Math.sqrt(items[k].value);
    }
    return dcx + 10 * i;
}

function getPercentage(value, total) {
    return ((value / total) * 100);
}

function circleDraw(index, data){
    data.sort(function(a, b) {
        return parseFloat(b.value) - parseFloat(a.value);
    });

    var circlelayer = svg.append("g")
      .attr("class", "circlelayer");

    var circle = circlelayer.selectAll("circle")
      .data(data);

    circle.enter().append("circle")
        .attr("class", function(d, i) {
            if (i == 0) {
              return "blue";
            }
            return "gold";
        })
        .attr("cy", 60)
        .attr("cx", function(d, i) {
            return calculateDistance(d, index, data);
        })
        .attr("r", function(d, i) {
            return Math.sqrt(d.value);
        });

    circle.exit().remove();
}
</code>```

答:
Here is how you could drawn the lines:

```<code>groups.append("line")
  .attr("class", "pointer1")
  .attr("marker-end", "url(#circ)")
  .attr("x1", 0)
  .attr("y1", height / 2)
  .attr("x2", 0)
  .attr("y2",height - 10);

  var linesG = svg.selectAll(".slines").data(data)
                            .enter().append("g")
              .attr("transform", function(d) {
                return ("translate(" + d.xcentre + "," + height/2 +") rotate(-45)");
              });

  linesG.append("line")
    .attr("class", "pointer1")
    .attr("marker-end", "url(#circ)")
    .attr("x1", 0)
    .attr("y1", 0)
    .attr("x2", 150)
    .attr("y2", 0);

  linesG.append("text")
        .text(function(d) {
        return fetchValue(d.items, "Count");
      })
      .attr("text-anchor", "end")
     .attr("y", -5)
     .attr("x", 150);
</code>```

Updated jsfiddle

Title: d3 javascript series chart

Body:
I am trying to create this particular d3 application where a series of data can be dynamically displayed like this. Each segment contains two pieces of data.

The first step is to print the circles so there is sufficient space between the series but also the largest circle is always under the smaller circle.

//version 3 -- with correct labels and legend--
http://jsfiddle.net/0ht35rpb/33/

//******version 2 fiddle******
http://jsfiddle.net/1oka61mL/10/

-- How to set the diagonal labels properly - same angles, aligned properly?
-- Add legend?
-- Mask the bottom pointers in an opposite color then continue the line in a different color?

//******Latest Jsfiddle******
http://jsfiddle.net/0ht35rpb/26/

var width = 600;
var height = 400;
var svg = d3.select('svg').attr("width", width).attr("height", height);

//Count
//Checkins
//Popularity

var data = [{
  "name": "Twitter",
  "items": [{
    "id": 0,
    "label": "Count",
    "value": 200
  }, {
    "id": 1,
    "label": "Checkins",
    "value": 1000
  }, {
    "id": 2,
    "label": "Popularity",
    "value": 30
  }]
}, {
  "name": "Facebook",
  "items": [{
    "id": 0,
    "label": "Count",
    "value": 500
  }, {
    "id": 1,
    "label": "Checkins",
    "value": 300
  }, {
    "id": 2,
    "label": "Popularity",
    "value": 740
  }]
}, {
  "name": "Ebay",
  "items": [{
    "id": 0,
    "label": "Count",
    "value": 4000
  }, {
    "id": 1,
    "label": "Checkins",
    "value": 1000
  }, {
    "id": 2,
    "label": "Popularity",
    "value": 40
  }]
}, {
  "name": "Foursquare",
  "items": [{
    "id": 0,
    "label": "Count",
    "value": 2000
  }, {
    "id": 1,
    "label": "Checkins",
    "value": 3000
  }, {
    "id": 2,
    "label": "Popularity",
    "value": 4500
  }]
}];

var outerRadius = [];
// organise the data.
// Insert indices and sort items in each series
// keep a running total of max circle size in each series
// for later positioning
var x = 0;
var totalWidth = d3.sum(
  data.map(function(series) {
    series.items.forEach(function(item, i) {
      item.index = i;
    });
    series.items.sort(function(a, b) {
      return b.value - a.value;
    });
    var maxr = Math.sqrt(series.items[0].value);
    outerRadius.push(maxr);
    x += maxr;
    series.xcentre = x;
    x += maxr;
    return maxr * 2;
  })
);

// make scales for position and colour
var scale = d3.scale.linear().domain([0, totalWidth]).range([0, width]);
//var colScale = d3.scale.category10();

function colores_google(n) {
  var colores_g = ["#f7b363", "#448875", "#c12f39", "#2b2d39", "#f8dd2f"];
  return colores_g[n % colores_g.length];
}

// add a group per series, position the group according to the values and position scale  we calculated above
var groups = svg.selectAll("g").data(data);
groups.enter().append("g");
groups.attr("transform", function(d) {
  return ("translate(" + d.xcentre + ",0)");
});

// then add circles per series, biggest first as items are sorted
// colour according to index (the property we inserted previously so we can
// keep track of their original position in the series)
var circles = groups.selectAll("circle").data(function(d) {
  return d.items;
}, function(d) {
  return d.index;
});
circles.enter().append("circle").attr("cy", height / 2).attr("cx", 0);

circles
  .attr("r", function(d) {
    return Math.sqrt(d.value);
  })
  .style("fill", function(d) {
    return colores_google(d.index);
  });

var labelsgroups = svg.selectAll("text").data(data);
labelsgroups.enter().append("text");
labelsgroups
  .attr("y", function(d, i) {
    d.y = 300;
    d.cy = 200;
    return 300;
  })
  .attr("x", function(d) {
    d.x = d.xcentre;
    d.cx = d.xcentre;
    return d.xcentre;
  })
  .text(function(d) {
    return d.name;
  })
  .each(function(d) {
    var bbox = this.getBBox();
    d.sx = d.x - bbox.width / 2 - 2;
    d.ox = d.x + bbox.width / 2 + 2;
    d.sy = d.oy = d.y + 5;
  })
  .attr("text-anchor", "middle");

var pointersgroups = svg.selectAll("path.pointer").data(data);
pointersgroups.enter().append("path");
pointersgroups
  .attr("class", "pointer")
  .attr("marker-end", "url(#circ)");

pointersgroups
  .attr("d", function(d) {
    return "M" + (d.xcentre) + "," + (d.oy - 25) + "L" + (d.xcentre) + "," + (d.sy - 25) + " " + d.xcentre + "," + (d.cy);
  })

function fetchValue(items, label) {
  for (i = 0; i <= items.length; i++) {
    if (items[i].label == label) {
      return items[i].value;
    }
  }
}

function fetchRadius(items, label) {
  for (i = 0; i <= items.length; i++) {
    if (items[i].label == label) {
      return Math.sqrt(items[i].value);
    }
  }
}

/*
var labels1groups = svg.selectAll(".label1").data(data);
labels1groups.enter().append("text");
labels1groups
  .attr("class", "label1")
  .attr("y", function(d, i) {
    d.y = 100;
    d.cy = 100;
    return 100;
  })
  .attr("x", function(d) {
    d.x = d.xcentre;
    d.cx = d.xcentre+50;
    return d.xcentre+50;
  })
  .text(function(d) {
    return fetchValue(d.items, "Count");
  })
  .attr("transform", function(d, i) {
            return "translate(" + (15 * i) + "," + (i * 45) + ") rotate(-45)";

  })
  .each(function(d) {
    var bbox = this.getBBox();
    d.sx = d.x - bbox.width / 2 - 2;
    d.ox = d.x + bbox.width / 2 + 2;
    d.sy = d.oy = d.y ;
  })
  .attr("text-anchor", "left");

*/

var gridSize = 100;

var labels1groups = svg.selectAll(".label2")
  .data(data)
  .enter().append("text")
  .text(function(d) {
    return fetchValue(d.items, "Count");
    //return d;
  })
  .attr("x", function(d, i) {

    d.x = i * gridSize + 50;
    d.cx = i * gridSize + 50;

    return i * gridSize;
  })
  .attr("y", function(d, i) {
    d.y = 105;
    d.cy = 50;
    return 0;
  })
  .attr("transform", function(d, i) {
    return "translate(" + gridSize / 2 + ", -6)" +
      "rotate(-45 " + ((i + 0.5) * gridSize) + " " + (-6) + ")";
  })
  .each(function(d) {
    var bbox = this.getBBox();
    d.sx = d.x - bbox.width / 2 - 2;
    d.ox = d.x + bbox.width / 2 + 2;
    d.sy = d.oy = d.y;
  })
  .style("text-anchor", "end")
  .attr("class", function(d, i) {
    return ((i >= 8 && i <= 16) ?
      "timeLabel mono axis axis-worktime" :
      "timeLabel mono axis");
  });

var pointers1groups = svg.selectAll("path.pointer1").data(data);
pointers1groups.enter().append("path");
pointers1groups
  .attr("class", "pointer1")
  .attr("marker-end", "url(#circ)");

pointers1groups
  .attr("d", function(d, i) {

    //d.y = outerRadius[i];
    //d.y = d.oy - d.cy;
    //fetchRadius(d.items, "Count");

    //(d.xcentre+100)
    // + " " + d.cx + "," + d.cy

    //return "M "+ (d.xcentre) +" 25 ,L "+ dist +" 75";

    return "M" + (d.xcentre) + "," + (d.y + d.oy - fetchRadius(d.items, "Count") - 10) + "L" + (d.xcentre + 80) + "," + d.cy;

  })

//Older Jsfiddle
http://jsfiddle.net/59bunh8u/51/

var rawData = [{
    "name": "Twitter",
    "items" : [
        {
            "label" : "15 billion",
            "unit" : "per day",
            "value" : 1500
        },
        {
            "label" : "450 checkins",
            "unit" : "per day",
            "value" : 450
        }
    ]
},
{
    "name": "Facebook",
    "items" : [
        {
            "label" : "5 billion",
            "unit" : "per day",
            "value" : 5000
        },
        {
            "label" : "2000 checkins",
            "unit" : "per day",
            "value" : 2000
        }
    ]
}];

$.each(rawData, function(index, value) {
    var total = 0;
    var layerSet = [];
    var ratios = [25, 100];

    $.each(value["items"], function(i, v) {
        total += v["value"];
    });

    value["total"] = total;
});

var w = $this.data("width");
var h = $this.data("height");

var el = $this;

var margin = {
    top: 65,
    right: 90,
    bottom: 5,
    left: 150
};

var svg = d3.select(el[0]).append("svg")
    .attr("class", "series")
    .attr("width", w + margin.left + margin.right)
    .attr("height", h + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var defs = svg.append("svg:defs");

$.each(rawData, function(i, v) {
    circleDraw(i, v["items"]);
});

//calculates where each element should be placed
function calculateDistance (d, i, items) {
    var dcx = 0;
    for (var k = 0; k < i; k++) {
      dcx += Math.sqrt(items[k].value);
    }
    return dcx + 10 * i;
}

function getPercentage(value, total) {
    return ((value / total) * 100);
}

function circleDraw(index, data){
    data.sort(function(a, b) {
        return parseFloat(b.value) - parseFloat(a.value);
    });

    var circlelayer = svg.append("g")
      .attr("class", "circlelayer");

    var circle = circlelayer.selectAll("circle")
      .data(data);

    circle.enter().append("circle")
        .attr("class", function(d, i) {
            if (i == 0) {
              return "blue";
            }
            return "gold";
        })
        .attr("cy", 60)
        .attr("cx", function(d, i) {
            return calculateDistance(d, index, data);
        })
        .attr("r", function(d, i) {
            return Math.sqrt(d.value);
        });

    circle.exit().remove();
}

Body:
Here is how you could drawn the lines:

groups.append("line")
  .attr("class", "pointer1")
  .attr("marker-end", "url(#circ)")
  .attr("x1", 0)
  .attr("y1", height / 2)
  .attr("x2", 0)
  .attr("y2",height - 10);

  var linesG = svg.selectAll(".slines").data(data)
                            .enter().append("g")
              .attr("transform", function(d) {
                return ("translate(" + d.xcentre + "," + height/2 +") rotate(-45)");
              });

  linesG.append("line")
    .attr("class", "pointer1")
    .attr("marker-end", "url(#circ)")
    .attr("x1", 0)
    .attr("y1", 0)
    .attr("x2", 150)
    .attr("y2", 0);

  linesG.append("text")
        .text(function(d) {
        return fetchValue(d.items, "Count");
      })
      .attr("text-anchor", "end")
     .attr("y", -5)
     .attr("x", 150);

Updated jsfiddle


问:
Writing a shell script to generate wave files
I was looking at writing a script to convert the contents of a .txt file to .wav files.

The command that currently does is :

```<code>text2wave textFileName.txt -o wavFileName.wav
</code>```

So, pretty simple command. It looks at what's inside the .txt file and converts it all to a .wav file. But what I would like to do is have just one .txt that contains a number of lines and each of those lines would be converted to a .wav file. For example : line 0, line 1, line 2, ... to be converted into 0.wav, 1.wav, 2.wav, ... etc

Any ideas on how to achieve this? I'm also open to different approaches.

答:
```<code>#!/bin/bash

i=1
filename=/path/to/text/file

while read -r line
do
    echo $line > somefile.txt
    text2wave somefile.txt -o $i.wav
    i=$((i+1))

done < "$filename"
</code>```

I think this would do your job of extracting each line and converting into respective .wav file.

Body:
I was looking at writing a script to convert the contents of a .txt file to .wav files.

The command that currently does is :

text2wave textFileName.txt -o wavFileName.wav

So, pretty simple command. It looks at what's inside the .txt file and converts it all to a .wav file. But what I would like to do is have just one .txt that contains a number of lines and each of those lines would be converted to a .wav file. For example : line 0, line 1, line 2, ... to be converted into 0.wav, 1.wav, 2.wav, ... etc

Any ideas on how to achieve this? I'm also open to different approaches.

Body:
#!/bin/bash

i=1
filename=/path/to/text/file

while read -r line
do
    echo $line > somefile.txt
    text2wave somefile.txt -o $i.wav
    i=$((i+1))

done < "$filename"

I think this would do your job of extracting each line and converting into respective .wav file.


问:
Git Revert Remote Branch
I am stuck with this problem: there have been a few commits, including some merged commits which have corrupted the remote development branch.

I have the commit where everything was fine. I want to revert all changes post this commit. Effectively, I want the commit where everything was fine to be the active branch locally and remotely.

答:
The safest way to approach this would be to git revert the bad commits locally, and then just push your branch to the remote as your normally would.  Because you have merge commits in there, you will probably have to handle each revert commit one-by-one.  For non merge commits, just use this:

```<code>git revert <SHA-1>
</code>```

where you would replace <SHA-1> with the actual hash of the commit you want to revert.  For merge commits, it gets trickier, because you need to tell Git which of the two parents paths you want to follow.  You will be doing one of the following two options:

```<code>git revert <SHA-1> -m 1
git revert <SHA-1> -m 2
</code>```

The -m 1 option tells Git to follow the path of the first parent, and the -m 2 option tells Git to follow the second parent.  To be safe, you should inspect the git log of the branch in question, and find the merge commit which is a candidate for reverting.  You should see something like this:

```<code>commit 599ee3d46d61d60a7ebdf584b06f78eba647526d
Merge: ece921f 57945bb
Author: Jon Skeet <jon.skeet@google.com>
Date:   Wed Mar 29 10:01:29 2017 +0000
</code>```

The ece921f is the first parent, and the 57945bb is the second parent.  Decide which one you want, and then revert accordingly.  If, for example, you wanted to follow the first parent, you would revert using this:

```<code>git revert 599ee3d -m 1
</code>```

If your branch is not being shared by anyone else, then perhaps the fastest way to get what you want would be to just hard reset your local branch, and then force push it to the remote.  Something like this:

```<code>git checkout your_branch
git reset --hard HEAD~5    # assuming you want to nuke the last 5 bad commits
git push --force origin your_branch
</code>```

But this option should only be considered if the branch is not shared with other people, or if it is, with knowledge that doing this force push could cause problems and confusion for others sharing this branch.

Title: Git Revert Remote Branch

Body:
The safest way to approach this would be to git revert the bad commits locally, and then just push your branch to the remote as your normally would.  Because you have merge commits in there, you will probably have to handle each revert commit one-by-one.  For non merge commits, just use this:

git revert <SHA-1>

where you would replace <SHA-1> with the actual hash of the commit you want to revert.  For merge commits, it gets trickier, because you need to tell Git which of the two parents paths you want to follow.  You will be doing one of the following two options:

git revert <SHA-1> -m 1
git revert <SHA-1> -m 2

The -m 1 option tells Git to follow the path of the first parent, and the -m 2 option tells Git to follow the second parent.  To be safe, you should inspect the git log of the branch in question, and find the merge commit which is a candidate for reverting.  You should see something like this:

commit 599ee3d46d61d60a7ebdf584b06f78eba647526d
Merge: ece921f 57945bb
Author: Jon Skeet <jon.skeet@google.com>
Date:   Wed Mar 29 10:01:29 2017 +0000

The ece921f is the first parent, and the 57945bb is the second parent.  Decide which one you want, and then revert accordingly.  If, for example, you wanted to follow the first parent, you would revert using this:

git revert 599ee3d -m 1

If your branch is not being shared by anyone else, then perhaps the fastest way to get what you want would be to just hard reset your local branch, and then force push it to the remote.  Something like this:

git checkout your_branch
git reset --hard HEAD~5    # assuming you want to nuke the last 5 bad commits
git push --force origin your_branch

But this option should only be considered if the branch is not shared with other people, or if it is, with knowledge that doing this force push could cause problems and confusion for others sharing this branch.


问:
how to Show/Hide button C# ASP.Net <No Panel>
I have below code

```<code><div class="modal‐footer">
<div class="row">
  <div class="col-md-6" runat="server" id="d1">
    <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />
  </div>
  <div class="col-md-6" runat="server" id="d2">
    <asp:Button runat="server" ID="SubmitBtn"  OnClick="SubmmitBtn_Click" CssClass="btn btn-success btn-block" Text="Submit" />
  </div>
  <div class="col-md-6" runat="server" id="d3">
    <asp:Button runat="server" ID="ApproveBtn" OnClick="ApproveBtn_Click" CssClass="btn btn-success btn-block" Text="Approve" />
  </div>
  <div class="col-md-6" runat="server" id="d4">
    <asp:Button runat="server" ID="RejectBtn" OnClick="RejectBtn_Click" CssClass="btn btn-danger btn-block" Text="Reject" />
  </div>
</div>
</div>
</code>```

I need to show only Update Button, under condition. Example,

```<code>if a=="Pending"; only UpdateBtn will be shown.
</code>```

Currently I cannot work with Panel (Even it is success, because my function will be corrupted if i use panel)

Please do help me on this. Ive read lot of forum and tried many approaches but failed.

This is how i declare the (aa) in the back code : public string rfcStatus

this is back code:

```<code>namespace AA.Search
{
public partial class Default : System.Web.UI.Page
{
    private string _searchText;
    public string aa;
    public string poaQa = "No";
    SearchMgt search = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (Request.QueryString["idno"] != null)
                {
                    _searchText = Request.QueryString["idno"];
                    SearchText.InnerHtml = _searchText;
                    aa = "Pending"
                    BindData();
                }
            }
            else
            {
                Response.Redirect("~/AccessDenied.aspx");
            }
        }
    }
</code>```

答:
Based on my understanding I believe you should do the following.

js

```<code>$(function() {
  var aa = ""; // Global Variable

  var btnID = $("#d1"); //Obtain element desired

  if (aa === "pending") { //Used strictly equals for precision.

    $(btnID).show(); //Make sure your buttons are hidden initially if needed with .hide()

  } else {
    $(btnID).hide();
  }
});
</code>```

aspx

```<code><div class="col-md-6" runat="server" id="d1">
  <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />
</div>
</code>```

I hope this helps.

Body:
I have below code

    <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />

    <asp:Button runat="server" ID="SubmitBtn"  OnClick="SubmmitBtn_Click" CssClass="btn btn-success btn-block" Text="Submit" />

    <asp:Button runat="server" ID="ApproveBtn" OnClick="ApproveBtn_Click" CssClass="btn btn-success btn-block" Text="Approve" />

    <asp:Button runat="server" ID="RejectBtn" OnClick="RejectBtn_Click" CssClass="btn btn-danger btn-block" Text="Reject" />

I need to show only Update Button, under condition. Example,

if a=="Pending"; only UpdateBtn will be shown.

Currently I cannot work with Panel (Even it is success, because my function will be corrupted if i use panel)

Please do help me on this. Ive read lot of forum and tried many approaches but failed.

This is how i declare the (aa) in the back code : public string rfcStatus

this is back code:

namespace AA.Search
{
public partial class Default : System.Web.UI.Page
{
    private string _searchText;
    public string aa;
    public string poaQa = "No";
    SearchMgt search = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (Request.QueryString["idno"] != null)
                {
                    _searchText = Request.QueryString["idno"];
                    SearchText.InnerHtml = _searchText;
                    aa = "Pending"
                    BindData();
                }
            }
            else
            {
                Response.Redirect("~/AccessDenied.aspx");
            }
        }
    }

Body:
Based on my understanding I believe you should do the following.

js

$(function() {
  var aa = ""; // Global Variable

  var btnID = $("#d1"); //Obtain element desired

  if (aa === "pending") { //Used strictly equals for precision.

    $(btnID).show(); //Make sure your buttons are hidden initially if needed with .hide()

  } else {
    $(btnID).hide();
  }
});

aspx

<div class="col-md-6" runat="server" id="d1">
  <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />
</div>

I hope this helps.


问:
How to add new nodes / neurons dynamically in tensorflow
If I want to add new nodes to on of my tensorflow layers on the fly, how can I do that?

For example if I want to change the amount of hidden nodes from 10 to 11 after the model has been training for a while. Also, assume I know what value I want the weights coming in and out of this node/neuron to be.

I can create a whole new graph, but is there a different/better way?

答:
Let us assume that res is output taking into account there are 10 hidden layers and let us call 10th hidden layer layer10. So what you do is

```<code>res = f(layer10)
</code>```

where f is some function which operates on layer10 and returns resulting tensor.

Pre-create layer11 as some operation on layer10 and res2 as output from layer11.

Now running you just evaluate res which will use on 10 layers. When you want to use 11 layers use res2. If you know the weights then you can assign it like tensor.assign(val).eval()

Body:
Let us assume that res is output taking into account there are 10 hidden layers and let us call 10th hidden layer layer10. So what you do is

res = f(layer10)

where f is some function which operates on layer10 and returns resulting tensor.

Pre-create layer11 as some operation on layer10 and res2 as output from layer11.

Now running you just evaluate res which will use on 10 layers. When you want to use 11 layers use res2. If you know the weights then you can assign it like tensor.assign(val).eval()


问:
Keep sap.m.MultiComboBox permanently open even after selecting an option
Is it possible to keep sap.m.MultiComboBox open by disabling the drop down toggle upon selecting a checkbox option or any other way of achieving the same.</p>

答:
Have you looked into using a SelectList? I believe this emulates what you are trying to achieve

https://sapui5.hana.ondemand.com/explored.html#/sample/sap.m.sample.SelectList/preview


问:
How adding redundant data can get rid of complex join in Denormalization?
I was going through Denormalizaition definition and I am wondering how adding redundant data can get rid of complex join ? </p>

答:
Consider the following two relations:

```<code>Department (department_id PK, department_name, manager_employee_id)
Employee (employee_id PK, employee_name, department_id)
</code>```

To get a list of employee names together with their managers' names, we would need a query like the following:

```<code>SELECT e.employee_name, m.employee_name AS manager_name
FROM Employee AS e
INNER JOIN Department AS d ON e.department_id = d.department_id
INNER JOIN Employee AS m ON d.manager_employee_id = m.employee_id
</code>```

Now, if we denormalize the transitive functional dependency employee_id -> department_id -> manager_employee_id -> employee_name into the Employee table, our tables could look like this:

```<code>Department (department_id PK, department_name, manager_employee_id)
Employee (employee_id PK, employee_name, department_id, manager_employee_id, manager_name)
</code>```

Practically, this might not be a good design since the redundancies could result in data consistency if it's not carefully kept in sync. However, we'll ignore that risk for the purpose of this example.

With the new tables, we can now get the list of employee and manager names like this:

```<code>SELECT employee_name, manager_name
FROM Employee
</code>```

Redundancy can help some queries to be expressed more simply, but it can introduce a risk of data inconsistency which needs to be carefully considered and controlled. Redundancy also requires more storage space and can make queries slower, since fewer rows can fit into a page on disk. On the other hand, it can make some queries faster by eliminating joins or calculations, and it can even be used to enforce consistency. Each case needs to be considered on its own merits.

Body:
Consider the following two relations:

Department (department_id PK, department_name, manager_employee_id)
Employee (employee_id PK, employee_name, department_id)

To get a list of employee names together with their managers' names, we would need a query like the following:

SELECT e.employee_name, m.employee_name AS manager_name
FROM Employee AS e
INNER JOIN Department AS d ON e.department_id = d.department_id
INNER JOIN Employee AS m ON d.manager_employee_id = m.employee_id

Now, if we denormalize the transitive functional dependency employee_id -> department_id -> manager_employee_id -> employee_name into the Employee table, our tables could look like this:

Department (department_id PK, department_name, manager_employee_id)
Employee (employee_id PK, employee_name, department_id, manager_employee_id, manager_name)

Practically, this might not be a good design since the redundancies could result in data consistency if it's not carefully kept in sync. However, we'll ignore that risk for the purpose of this example.

With the new tables, we can now get the list of employee and manager names like this:

SELECT employee_name, manager_name
FROM Employee

Redundancy can help some queries to be expressed more simply, but it can introduce a risk of data inconsistency which needs to be carefully considered and controlled. Redundancy also requires more storage space and can make queries slower, since fewer rows can fit into a page on disk. On the other hand, it can make some queries faster by eliminating joins or calculations, and it can even be used to enforce consistency. Each case needs to be considered on its own merits.


问:
Google Place Picker Android Studio
Does anyone know how to implement Google Place Picker API in Android Studio? Tried tutorials, unsuccessful. I want a working AutoComplete Text Field that has places show up and when you click on the place it will display in the Google Map Fragment.</p>

答:
Add the dependency to yourbuild.gradle (replace <version-number> with the  version you want, which you can find, for example, at Gradle, Please):

```<code>compile "com.google.android.gms:play-services-places:<version-number>"
</code>```

Add your key to your AndroidManifest.xml:

```<code><meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/map_api_key"/>
</code>```

Your Activity/Fragment needs these attributes and methods:

```<code>private final static int PLACE_PICKER_REQUEST = 999;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    checkPermissionOnActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
        switch (requestCode){
        case PLACE_PICKER_REQUEST:
            Place place = PlacePicker.getPlace(this, data);
            String placeName = String.format("Place: %s", place.getName());
            double latitude = place.getLatLng().latitude;
            double longitude = place.getLatLng().longitude;

        }
    }
}
</code>```

finally, this is the code to open a PlacePicker

```<code>PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
     // for activty
     startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
     // for fragment
     //startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
     e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
     e.printStackTrace();
}

</code>```

Title: Google Place Picker Android Studio

Body:
Add the dependency to yourbuild.gradle (replace <version-number> with the  version you want, which you can find, for example, at Gradle, Please):

compile "com.google.android.gms:play-services-places:<version-number>"

Add your key to your AndroidManifest.xml:

<meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/map_api_key"/>

Your Activity/Fragment needs these attributes and methods:

private final static int PLACE_PICKER_REQUEST = 999;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    checkPermissionOnActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
        switch (requestCode){
        case PLACE_PICKER_REQUEST:
            Place place = PlacePicker.getPlace(this, data);
            String placeName = String.format("Place: %s", place.getName());
            double latitude = place.getLatLng().latitude;
            double longitude = place.getLatLng().longitude;

        }
    }
}

finally, this is the code to open a PlacePicker

PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
     // for activty
     startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
     // for fragment
     //startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
     e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
     e.printStackTrace();
}


问:
Renaming coredata .xcdatamodeld file and migration
We had a 2 separated apps that we have merged to 2 targets in the same workspace. Both had their core data model (app1.xcdatamodeld and app2.xcdatamodeld).

Now that both are in the same workspace there is no need for 2 models as they are 99% similar. So I want to change the name of the .xcdatamodeld package to allApps.xcdatamodeld. I was able to rename it but I do not find any reference about the behaviour of migration when doing so.

This is the error -

```<code>2015-07-28 09:04:06.079 AppName[51306:1423128] CoreData: error:
-addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/shani/Library/Developer/CoreSimulator/Devices/EA75A69F-B108-4036-AB3D-B923F83D16DE/data/Containers/Data/Application/B1CB3AF3-DEF4-40DF-9A61-721063ECBB1D/Documents/AppName.sqlite
options:{
    NSInferMappingModelAutomaticallyOption = 1;
    NSMigratePersistentStoresAutomaticallyOption = 1;
    NSSQLitePragmasOption =     {
        "journal_mode" = WAL;
    }; } ... returned error Error Domain=NSCocoaErrorDomain Code=134130 "The operation couldn’t be completed. (Cocoa error
134130.)" UserInfo=0x7fc39c194360 {URL=file:///Users/shani/Library/Developer/CoreSimulator/Devices/EA75A69F-B108-4036-AB3D-B923F83D16DE/data/Containers/Data/Application/B1CB3AF3-DEF4-40DF-9A61-721063ECBB1D/Documents/AppName.sqlite,
metadata={
    NSPersistenceFrameworkVersion = 519;
    NSStoreModelVersionHashes =     {
        Attempt = <b4d1e878 69a97917 e751a67c 89e1887a ae4df1dc f380e4ee c9585f60 f39ff51e>;
        BookmarkFlashcard = <33112f7c 2fa20bec eb2e019c b5d619b4 92be2547 a65fabee 1ac86ab7 92dd77bb>;
        BookmarkQuestion = <38634b49 71f0d43c 6f9fbba9 bc2f1b81 675c9b3c f2da017e fc8de9d8 4e18a4a0>;
        Category = <b0e4d91b 0c0ebc71 ed0f403c 9a0eec20 fc1686aa 0169bc60 4bcc7e57 165bce15>;
    };
    NSStoreModelVersionHashesVersion = 3;
    NSStoreModelVersionIdentifiers =     (
        ""
    );
    NSStoreType = SQLite;
    NSStoreUUID = "F1B37CD0-8B89-4893-A262-1013C3544026";
    "_NSAutoVacuumLevel" = 2; }, reason=Can't find model for source store} with userInfo dictionary {
    URL = "file:///Users/shani/Library/Developer/CoreSimulator/Devices/EA75A69F-B108-4036-AB3D-B923F83D16DE/data/Containers/Data/Application/B1CB3AF3-DEF4-40DF-9A61-721063ECBB1D/Documents/AppName.sqlite";
    metadata =     {
        NSPersistenceFrameworkVersion = 519;
        NSStoreModelVersionHashes =         {
            Attempt = <b4d1e878 69a97917 e751a67c 89e1887a ae4df1dc f380e4ee c9585f60 f39ff51e>;
            BookmarkFlashcard = <33112f7c 2fa20bec eb2e019c b5d619b4 92be2547 a65fabee 1ac86ab7 92dd77bb>;
            BookmarkQuestion = <38634b49 71f0d43c 6f9fbba9 bc2f1b81 675c9b3c f2da017e fc8de9d8 4e18a4a0>;
            Category = <b0e4d91b 0c0ebc71 ed0f403c 9a0eec20 fc1686aa 0169bc60 4bcc7e57 165bce15>;
        };
        NSStoreModelVersionHashesVersion = 3;
        NSStoreModelVersionIdentifiers =         (
            ""
        );
        NSStoreType = SQLite;
        NSStoreUUID = "F1B37CD0-8B89-4893-A262-1013C3544026";
        "_NSAutoVacuumLevel" = 2;
    };
    reason = "Can't find model for source store"; } 2015-07-28 09:04:06.089 AppName[51306:1423128] CoreData: annotation:
NSPersistentStoreCoordinator's current model hashes are {
    Attempt = <b4d1e878 69a97917 e751a67c 89e1887a ae4df1dc f380e4ee c9585f60 f39ff51e>;
    BookmarkFlashcard = <33112f7c 2fa20bec eb2e019c b5d619b4 92be2547 a65fabee 1ac86ab7 92dd77bb>;
    BookmarkQuestion = <38634b49 71f0d43c 6f9fbba9 bc2f1b81 675c9b3c f2da017e fc8de9d8 4e18a4a0>;
    Category = <b0e4d91b 0c0ebc71 ed0f403c 9a0eec20 fc1686aa 0169bc60 4bcc7e57 165bce15>; }
</code>```

Is there a way to rename name1.xdatamodel to name2.xdatamodel in an app that is already in production ?

Thanks

答:
Just click right click on .xcdatamodeld Show in Finder and Rename it.
Remove from bundle exiting one and Drag and drop Renamed .xcdatamodeld, Now clean the build, Check before run relationship between models if have and  Run again. </p>

Body:
We had a 2 separated apps that we have merged to 2 targets in the same workspace. Both had their core data model (app1.xcdatamodeld and app2.xcdatamodeld).

Now that both are in the same workspace there is no need for 2 models as they are 99% similar. So I want to change the name of the .xcdatamodeld package to allApps.xcdatamodeld. I was able to rename it but I do not find any reference about the behaviour of migration when doing so.

This is the error -

2015-07-28 09:04:06.079 AppName[51306:1423128] CoreData: error:
-addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/shani/Library/Developer/CoreSimulator/Devices/EA75A69F-B108-4036-AB3D-B923F83D16DE/data/Containers/Data/Application/B1CB3AF3-DEF4-40DF-9A61-721063ECBB1D/Documents/AppName.sqlite
options:{
    NSInferMappingModelAutomaticallyOption = 1;
    NSMigratePersistentStoresAutomaticallyOption = 1;
    NSSQLitePragmasOption =     {
        "journal_mode" = WAL;
    }; } ... returned error Error Domain=NSCocoaErrorDomain Code=134130 "The operation couldn’t be completed. (Cocoa error
134130.)" UserInfo=0x7fc39c194360 {URL=file:///Users/shani/Library/Developer/CoreSimulator/Devices/EA75A69F-B108-4036-AB3D-B923F83D16DE/data/Containers/Data/Application/B1CB3AF3-DEF4-40DF-9A61-721063ECBB1D/Documents/AppName.sqlite,
metadata={
    NSPersistenceFrameworkVersion = 519;
    NSStoreModelVersionHashes =     {
        Attempt = <b4d1e878 69a97917 e751a67c 89e1887a ae4df1dc f380e4ee c9585f60 f39ff51e>;
        BookmarkFlashcard = <33112f7c 2fa20bec eb2e019c b5d619b4 92be2547 a65fabee 1ac86ab7 92dd77bb>;
        BookmarkQuestion = <38634b49 71f0d43c 6f9fbba9 bc2f1b81 675c9b3c f2da017e fc8de9d8 4e18a4a0>;
        Category = <b0e4d91b 0c0ebc71 ed0f403c 9a0eec20 fc1686aa 0169bc60 4bcc7e57 165bce15>;
    };
    NSStoreModelVersionHashesVersion = 3;
    NSStoreModelVersionIdentifiers =     (
        ""
    );
    NSStoreType = SQLite;
    NSStoreUUID = "F1B37CD0-8B89-4893-A262-1013C3544026";
    "_NSAutoVacuumLevel" = 2; }, reason=Can't find model for source store} with userInfo dictionary {
    URL = "file:///Users/shani/Library/Developer/CoreSimulator/Devices/EA75A69F-B108-4036-AB3D-B923F83D16DE/data/Containers/Data/Application/B1CB3AF3-DEF4-40DF-9A61-721063ECBB1D/Documents/AppName.sqlite";
    metadata =     {
        NSPersistenceFrameworkVersion = 519;
        NSStoreModelVersionHashes =         {
            Attempt = <b4d1e878 69a97917 e751a67c 89e1887a ae4df1dc f380e4ee c9585f60 f39ff51e>;
            BookmarkFlashcard = <33112f7c 2fa20bec eb2e019c b5d619b4 92be2547 a65fabee 1ac86ab7 92dd77bb>;
            BookmarkQuestion = <38634b49 71f0d43c 6f9fbba9 bc2f1b81 675c9b3c f2da017e fc8de9d8 4e18a4a0>;
            Category = <b0e4d91b 0c0ebc71 ed0f403c 9a0eec20 fc1686aa 0169bc60 4bcc7e57 165bce15>;
        };
        NSStoreModelVersionHashesVersion = 3;
        NSStoreModelVersionIdentifiers =         (
            ""
        );
        NSStoreType = SQLite;
        NSStoreUUID = "F1B37CD0-8B89-4893-A262-1013C3544026";
        "_NSAutoVacuumLevel" = 2;
    };
    reason = "Can't find model for source store"; } 2015-07-28 09:04:06.089 AppName[51306:1423128] CoreData: annotation:
NSPersistentStoreCoordinator's current model hashes are {
    Attempt = <b4d1e878 69a97917 e751a67c 89e1887a ae4df1dc f380e4ee c9585f60 f39ff51e>;
    BookmarkFlashcard = <33112f7c 2fa20bec eb2e019c b5d619b4 92be2547 a65fabee 1ac86ab7 92dd77bb>;
    BookmarkQuestion = <38634b49 71f0d43c 6f9fbba9 bc2f1b81 675c9b3c f2da017e fc8de9d8 4e18a4a0>;
    Category = <b0e4d91b 0c0ebc71 ed0f403c 9a0eec20 fc1686aa 0169bc60 4bcc7e57 165bce15>; }

Is there a way to rename name1.xdatamodel to name2.xdatamodel in an app that is already in production ?

Thanks


问:
How to download a csv file in IE and safari with out using download attribute?
i have a csv file link "http://spatialkeydocs.s3.amazonaws.com/FL_insurance_sample.csv.zip". my application is angularjs appliction, for downloading this i have used "download" attribute it is working fine in chrome and firefox. but this is not working in the IE and safari because download attribute is not supported by the IE and Safari browsers. could you guys please suggest me how to make it work for IE and safari. if possible can one share plunker ?
Thanks in advance !</p>

答:
Here is the code I used on my last project. It's not perfect, but it passed QA in all browsers and IE9+.

```<code>downloadCSV(data,fileName){
  var blob = new Blob([data], {type:  "text/plain;charset=utf-8;"});
  var anchor = angular.element('<a/>');

  if (window.navigator.msSaveBlob) { // IE
    window.navigator.msSaveOrOpenBlob(blob, fileName)
  } else if (navigator.userAgent.search("Firefox") !== -1) { // Firefox
    anchor.css({display: 'none'});
    angular.element(document.body).append(anchor);

    anchor.attr({
      href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
      target: '_blank',
      download: fileName
    })[0].click();

    anchor.remove();
  } else { // Chrome
    anchor.attr({
      href: URL.createObjectURL(blob),
      target: '_blank',
      download: fileName
    })[0].click();
  }
}
</code>```

Using the ms specific API worked best for us in IE. Also note that some browsers require the anchor to actually be in the DOM for the download attribute to work, whereas Chrome, for example, does not. Also, we found some inconsistencies with how Blobs work in various browsers. Some browsers also have an export limit. This allows the largest possible CSV export in each browser afaik.

Body:
Here is the code I used on my last project. It's not perfect, but it passed QA in all browsers and IE9+.

downloadCSV(data,fileName){
  var blob = new Blob([data], {type:  "text/plain;charset=utf-8;"});
  var anchor = angular.element('<a/>');

  if (window.navigator.msSaveBlob) { // IE
    window.navigator.msSaveOrOpenBlob(blob, fileName)
  } else if (navigator.userAgent.search("Firefox") !== -1) { // Firefox
    anchor.css({display: 'none'});
    angular.element(document.body).append(anchor);

    anchor.attr({
      href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
      target: '_blank',
      download: fileName
    })[0].click();

    anchor.remove();
  } else { // Chrome
    anchor.attr({
      href: URL.createObjectURL(blob),
      target: '_blank',
      download: fileName
    })[0].click();
  }
}

Using the ms specific API worked best for us in IE. Also note that some browsers require the anchor to actually be in the DOM for the download attribute to work, whereas Chrome, for example, does not. Also, we found some inconsistencies with how Blobs work in various browsers. Some browsers also have an export limit. This allows the largest possible CSV export in each browser afaik.


问:
Get session cookie name
Is it possible to get session cookie name in medium trust level? The code below works in full trust, but throws a security exception in medium trust level.</p>

```<code>string sessionCookieName = ((SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState")).CookieName;
</code>```

答:
You can use HTTP_COOKIE server variable from the Request object, to get the cookie string that was included with the request.

```<code>string cookieString = Request.ServerVariables["HTTP_COOKIE"]
</code>```

If what you want is to obtain the session cookie name from the web.config, why don't you add a simple entry in the appSettings section containing the session cookie name?

```<code>    <appSettings>
        <add key="SessionCookieName" value="__SessionCookieName"/>
    <appSetting>

    <sessionState cookieName="__SessionCookieName"  />
</code>```

Then you can read the web.config setting value by using the following code:

```<code>public static bool SessionCookieName
{
    get { return ConfigurationManager.AppSettings["SessionCookieName"]; }
}
</code>```

Title: Get session cookie name

Body:
Is it possible to get session cookie name in medium trust level? The code below works in full trust, but throws a security exception in medium trust level.

string sessionCookieName = ((SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState")).CookieName;

Body:
You can use HTTP_COOKIE server variable from the Request object, to get the cookie string that was included with the request.

string cookieString = Request.ServerVariables["HTTP_COOKIE"]

If what you want is to obtain the session cookie name from the web.config, why don't you add a simple entry in the appSettings section containing the session cookie name?

    <appSettings>
        <add key="SessionCookieName" value="__SessionCookieName"/>
    <appSetting>

    <sessionState cookieName="__SessionCookieName"  />

Then you can read the web.config setting value by using the following code:

public static bool SessionCookieName
{
    get { return ConfigurationManager.AppSettings["SessionCookieName"]; }
}


问:
AWS Lambda Performance issues
I use aws api gateway integrated with aws lambda(java), but I'm seeing some serious problems in this approach. The concept of removing the server and having your app scaled out of the box is really nice but here are the problem I'm facing. My lambda is doing 2 simple things- validate the payload received from the client and then send it to a kinesis stream for further processing from another lambda(you will ask why I don't send directly to the stream and only use 1 lambda for all of the operations. Let's just say that I want to separate the logic and have a layer of abstraction and also be able to tell the client that he's sending invalid data.).

In the implementation of the lambda I integrated the spring DI. So far so good. I started making performance testing. I simulated 50 concurrent users making 4 requests each with 5 seconds between the requests. So what happened- In the lambda's coldstart I initialize the spring's application context but it seems that having so many simultaneous requests when the lambda was not started is doing some strange things. Here's a screenshot of the times the context was initialized for.

What we can see from the screenshot is that the times for initializing the context have big difference. My assumption of what happening is that when so many requests are received and there's no "active" lambda it initializes a lambda container for every one of them and in the same time it "blocks" some of them(the ones with the big times of 18s) until the others already started are ready. So maybe it has some internal limit of the containers it can start at the same time. The problem is that if you don't have equally distributed traffic this will happen from time to time and some of the requests will timeout. We don't want this to happen.

So next thing was to do some tests without spring container as my thought was "ok, the initialization is heavy, let's just make plain old java objects initialization". And unfortunatelly the same thing happened(maybe just reduced the 3s container initialization for some of the requests). Here is a more detailed screenshot of the test data:

So I logged the whole lambda execution time(from construction to the end), the kinesis client initialization and the actual sending of the data to the stream as these are the heaviest operations in the lambda. We still have these big times of 18s or something but the interesting thing is that the times are somehow proportional. So if the whole lambda takes 18s, around 7-8s is the client initialization and 6-7 for sending the data to the stream and 4-5 seconds left for the other operations in the lambda which for the moment is only validation. On the other hand if we take one of the small times(which means that it reuses an already started lambda),i.e. 820ms, it takes 100ms for the kinesis client initialization and 340 for the data sending and 400ms for the validation. So this pushes me again to the thoughts that internally it makes some sleeps because of some limits. The next screenshot is showing what is happening on the next round of requests when the lamda is already started:

So we don't have this big times, yes we still have some relatively big delta in some of the request(which for me is also strange), but the things looks much better.

So I'm looking for a clarification from someone who knows actually what is happening under the hood, because this is not a good behavior for a serious application which is using the cloud because of it's "unlimited" possibilities.

And another question is related to another limit of the lambda-200 concurrent invocations in all lambdas within an account in a region. For me this is also a big limitation for a big application with lots of traffic. So as my business case in the moment(I don't know for the future) is more or less fire and forget the request. And I'm starting to think of changing the logic in the way that the gateway sends the data directly to the stream and the other lambda is taking care of the validation and the further processing. Yes, I'm loosing the current abstraction(which I don't need at the moment) but I'm increasing the application availability many times. What do you think?

答:
You can proxy straight to the Kinesis stream via API Gateway. You would lose some control in terms of validation and transformation, but you won't have the cold start latency that you're seeing from Lambda.

You can use the API Gateway mapping template to transform the data and if validation is important, you could potentially do that at the processing Lambda on the other side of the stream.

Title: AWS Lambda Performance issues


问:
replace multiple values in json/jsObject/string
I have a response from a web service and want to replace some values in the response with my custom values.

One way is to write a tree traverser and then check for the value and replace with my custom value

so the response is some what like this:

```<code>[
  {
    "name": "n1",
    "value": "v1",
    "children": [
      {
        "name": "n2",
        "value": "v2"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v3"
  }
]
</code>```

now my custom map is like this

```<code>const map = {
  "v1": "v11",
  "v2": "v22",
  "v3": "v33"
};
</code>```

All I want is

```<code>[
  {
    "name": "n1",
    "value": "v11",
    "children": [
      {
        "name": "n2",
        "value": "v22"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v33"
  }
]
</code>```

I was thinking if I could stringify my response and then replace values using a custom build regex from my map of values.

Will it be faster as compared to tree traverser?

If yes, how should I do that?

somewhat like this

originalString.replace(regexp, function (replacement))

答:
The tree traversal is faster

Note that some things could be done more efficiently in the regex implementation but I still think there are some more bottlenecks to explain.

Why the regex is slow:

There are probably many more reasons why the regex is slower but I'll explain at least one significant reason:

When you're using regex to find and replace, you're using creating new strings every time and performing your matches every time. Regex expressions can be very expensive and my implementation isn't particularly cheap.

Why is the tree traversal faster:

In the tree traversal, I'm mutating the object directly. This doesn't require creating new string objects or any new objects at all. We're also not performing a full search on the whole string every time as well.

RESULTS

run the performance test below. The test using console.time to record how long it takes. See the the tree traversal is much faster.

function usingRegex(obj, map) {
  return JSON.parse(Object.keys(map).map(oldValue => ({
    oldValue,
    newValue: map[oldValue]
  })).reduce((json, {
    oldValue,
    newValue
  }) => {
    return json.replace(
      new RegExp(`"value":"(${oldValue})"`),
      () => `"value":"${newValue}"`
    );
  }, JSON.stringify(obj)));
}

function usingTree(obj, map) {
  function traverse(children) {
    for (let item of children) {
      if (item && item.value) {
        // get a value from a JS object is O(1)!
        item.value = map[item.value];
      }
      if (item && item.children) {
        traverse(item.children)
      }
    }
  }

  traverse(obj);
  return obj; // mutates
}

const obj = JSON.parse(`[
  {
    "name": "n1",
    "value": "v1",
    "children": [
      {
        "name": "n2",
        "value": "v2"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v3"
  }
]`);

const map = {
  "v1": "v11",
  "v2": "v22",
  "v3": "v33"
};

// show that each function is working first
console.log('== TEST THE FUNCTIONS ==');
console.log('usingRegex', usingRegex(obj, map));
console.log('usingTree', usingTree(obj, map));

const iterations = 10000; // ten thousand
console.log('== DO 10000 ITERATIONS ==');
console.time('regex implementation');
for (let i = 0; i < iterations; i += 1) {
  usingRegex(obj, map);
}
console.timeEnd('regex implementation');

console.time('tree implementation');
for (let i = 0; i < iterations; i += 1) {
  usingTree(obj, map);
}
console.timeEnd('tree implementation');```

Body:
I have a response from a web service and want to replace some values in the response with my custom values.

One way is to write a tree traverser and then check for the value and replace with my custom value

so the response is some what like this:

[
  {
    "name": "n1",
    "value": "v1",
    "children": [
      {
        "name": "n2",
        "value": "v2"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v3"
  }
]

now my custom map is like this

const map = {
  "v1": "v11",
  "v2": "v22",
  "v3": "v33"
};

All I want is

[
  {
    "name": "n1",
    "value": "v11",
    "children": [
      {
        "name": "n2",
        "value": "v22"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v33"
  }
]

I was thinking if I could stringify my response and then replace values using a custom build regex from my map of values.

Will it be faster as compared to tree traverser?

If yes, how should I do that?

somewhat like this

originalString.replace(regexp, function (replacement))


问:
Automatically passing focus betwen EditText
Since my question asking about separating characters that are typed in an EditText into groups or blocks didn't receive much attention, I've come here with another question on an alternative way to accomplish what I need.

So, my idea is to have four EditText that have 4 char length. Now what I want is to change the focus as the user type, from an EdutText to another when the limit is reached.
Example: Let's say we have EditText A, B, C, D; the first to gain focus is EditText A, then when the chars length at A reach 4, the focus passes to EditText B and so on and stops At D.

I'm trying something like the code bellow, but the focus is not requested when the length reaches 4 chars.

```<code>inputFieldA.requestFocus();

    inputFieldA.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldB.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldB.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldC.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldC.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldD.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldD.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                //send all to Main EditText (A + B + C + D)
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
</code>```

So I'm here asking if there is a way to do that.

答:
```<code> if(inputFieldA.toString().trim().length() == 4){
            inputFieldB.requestFocus();
  }
</code>```

replace this lines in onTextChange() methode.

Body:
Since my question asking about separating characters that are typed in an EditText into groups or blocks didn't receive much attention, I've come here with another question on an alternative way to accomplish what I need.

So, my idea is to have four EditText that have 4 char length. Now what I want is to change the focus as the user type, from an EdutText to another when the limit is reached.
Example: Let's say we have EditText A, B, C, D; the first to gain focus is EditText A, then when the chars length at A reach 4, the focus passes to EditText B and so on and stops At D.

I'm trying something like the code bellow, but the focus is not requested when the length reaches 4 chars.

inputFieldA.requestFocus();

    inputFieldA.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldB.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldB.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldC.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldC.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                inputFieldD.requestFocus();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    inputFieldD.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if(s.toString().trim().length() == 4){
                //send all to Main EditText (A + B + C + D)
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

So I'm here asking if there is a way to do that.

Body:
 if(inputFieldA.toString().trim().length() == 4){
            inputFieldB.requestFocus();
  }

replace this lines in onTextChange() methode.


答:
I have the commit where everything was fine. I want to revert all changes post this commit.

Revert all the commits after the working-commit. You can revert a range of commit like:

```<code>$ git revert <fromCommit>..<toCommit>

$ git add .
$ git commit -m 'Revert some commits'
$ git push origin HEAD
</code>```

Title: Git Revert Remote Branch

Body:
I am stuck with this problem: there have been a few commits, including some merged commits which have corrupted the remote development branch.

I have the commit where everything was fine. I want to revert all changes post this commit. Effectively, I want the commit where everything was fine to be the active branch locally and remotely.

Body:
I have the commit where everything was fine. I want to revert all changes post this commit.

Revert all the commits after the working-commit. You can revert a range of commit like:

$ git revert <fromCommit>..<toCommit>

$ git add .
$ git commit -m 'Revert some commits'
$ git push origin HEAD