问:
Windows Git: unknown error occurred while reading the configuration files
Prior questions like Can't use git: "git fatal: unknown error occurred while reading the configuration files" talk about this error message:

```<code>G:\dev\some-repo> git status
fatal: unknown error occurred while reading the configuration files
</code>```

…and answers go through various basic troubleshooting around finding config files, making sure those paths aren't directories, etc.

I've verified that my C:\Users\chas\.gitconfig file is a file, and aside from that, all the configuration files can be read as far as I can tell -- or, at least, I see values from all of the locations I'm aware of:

```<code>$ git config -l --show-origin
fatal: error processing config file(s)
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        core.symlinks=false
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        core.autocrlf=true
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        color.diff=auto
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        color.status=auto
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        color.branch=auto
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        color.interactive=true
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        pack.packsizelimit=2g
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        help.format=html
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        http.sslcainfo=/ssl/certs/ca-bundle.crt
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        diff.astextplain.textconv=astextplain
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        rebase.autosquash=true
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        filter.lfs.clean=git-lfs clean -- %f
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        filter.lfs.smudge=git-lfs smudge -- %f
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        filter.lfs.process=git-lfs filter-process
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        filter.lfs.required=true
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        credential.helper=manager
file:C:/Users/chas/.gitconfig   user.name=Chas Emerick
file:C:/Users/chas/.gitconfig   user.email=chas@cemerick.com
file:C:/Users/chas/.gitconfig   push.default=matching
</code>```

Note:

fatal: error processing config file(s) message preceding all of the config entries

All of the above happens whether I'm in a repo or not

that my user-level file appears to be getting consumed properly

removing C:\Users\chas\.gitconfig entirely does not resolve the problem

The listing above is from using a self-contained/"portable" git executable/environment and using git-bash; the same problem persists when git is installed, and using git-bash from there, or git via cmd.exe.

Git version: 2.15.0; Windows 10 Pro, version 1709, OS build 16299.19

Help?

答:
Double-check if

the error persists when using git config -l --show-origin outside of any git repo (in which case that might be related to the local repo you are in)

the error persists when using a simplified PATH (to rule out any other program side-effect)

There should 3 files (in addition to a possible local repo config file):

```<code>file:"C:\\ProgramData/Git/config"                     core.symlinks=false
...
file:"C:\\prgs\\git\\latest\\mingw64/etc/gitconfig"   core.symlinks=false
...
file:C:/Users/VonC/.gitconfig                         core.autocrlf=false
</code>```

Or at least, the first one (C:\\ProgramData) should not point to a non-existent file.

See more at "Windows-specific Git configuration settings; where are they set?".

The page "Getting Started - First-Time Git Setup" mentions:

On Windows systems, Git looks for :

the .gitconfig file in the $HOME directory (C:\Users\$USER for most people).

It also still looks for /etc/gitconfig, although it’s relative to the MSys root, which is wherever you decide to install Git on your Windows system when you run the installer.

If you are using version 2.x or later of Git for Windows, there is also a system-level config file at C:\Documents and Settings\All Users\Application Data\Git\config on Windows XP, and in C:\ProgramData\Git\config on Windows Vista and newer.

  This config file can only be changed by git config -f <file> as an admin.

See git-for-windows/git commit 153328b, regarding the discussion between the libgit2 and the Git for Windows project, on how they could share Git configuration to avoid duplication (or worse: skew).

Body:
Prior questions like Can't use git: "git fatal: unknown error occurred while reading the configuration files" talk about this error message:

G:\dev\some-repo> git status
fatal: unknown error occurred while reading the configuration files

…and answers go through various basic troubleshooting around finding config files, making sure those paths aren't directories, etc.

I've verified that my C:\Users\chas\.gitconfig file is a file, and aside from that, all the configuration files can be read as far as I can tell -- or, at least, I see values from all of the locations I'm aware of:

$ git config -l --show-origin
fatal: error processing config file(s)
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        core.symlinks=false
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        core.autocrlf=true
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        color.diff=auto
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        color.status=auto
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        color.branch=auto
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        color.interactive=true
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        pack.packsizelimit=2g
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        help.format=html
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        http.sslcainfo=/ssl/certs/ca-bundle.crt
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        diff.astextplain.textconv=astextplain
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        rebase.autosquash=true
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        filter.lfs.clean=git-lfs clean -- %f
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        filter.lfs.smudge=git-lfs smudge -- %f
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        filter.lfs.process=git-lfs filter-process
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        filter.lfs.required=true
file:"G:\\Downloads\\Git\\mingw64/etc/gitconfig"        credential.helper=manager
file:C:/Users/chas/.gitconfig   user.name=Chas Emerick
file:C:/Users/chas/.gitconfig   user.email=chas@cemerick.com
file:C:/Users/chas/.gitconfig   push.default=matching

Note:

fatal: error processing config file(s) message preceding all of the config entries

All of the above happens whether I'm in a repo or not

that my user-level file appears to be getting consumed properly

removing C:\Users\chas\.gitconfig entirely does not resolve the problem

The listing above is from using a self-contained/"portable" git executable/environment and using git-bash; the same problem persists when git is installed, and using git-bash from there, or git via cmd.exe.

Git version: 2.15.0; Windows 10 Pro, version 1709, OS build 16299.19

Help?

Body:
Double-check if

the error persists when using git config -l --show-origin outside of any git repo (in which case that might be related to the local repo you are in)

the error persists when using a simplified PATH (to rule out any other program side-effect)

There should 3 files (in addition to a possible local repo config file):

file:"C:\\ProgramData/Git/config"                     core.symlinks=false
...
file:"C:\\prgs\\git\\latest\\mingw64/etc/gitconfig"   core.symlinks=false
...
file:C:/Users/VonC/.gitconfig                         core.autocrlf=false

Or at least, the first one (C:\\ProgramData) should not point to a non-existent file.

See more at "Windows-specific Git configuration settings; where are they set?".

The page "Getting Started - First-Time Git Setup" mentions:

On Windows systems, Git looks for :

the .gitconfig file in the $HOME directory (C:\Users\$USER for most people).

It also still looks for /etc/gitconfig, although it’s relative to the MSys root, which is wherever you decide to install Git on your Windows system when you run the installer.

If you are using version 2.x or later of Git for Windows, there is also a system-level config file at C:\Documents and Settings\All Users\Application Data\Git\config on Windows XP, and in C:\ProgramData\Git\config on Windows Vista and newer.

  This config file can only be changed by git config -f <file> as an admin.

See git-for-windows/git commit 153328b, regarding the discussion between the libgit2 and the Git for Windows project, on how they could share Git configuration to avoid duplication (or worse: skew).


来源: stackexchange

问:
App Intent with Eddystone Beacons and Nearby
I would like to open a certain instagram profile in the App when a user clicks on a Nearby Notification.

I have three fields to fill out:

Intent scheme

Intent path

App package name

The package name is fairly clear (com.instagram.android). But when I only fill this field, the app store opens first. There I have to click on "open" to open Instagram. What am I doing wrong? The only app intent tutorials I found are about direct app integration and not of much use.

答:
Maybe you should add some content at your app like this:

```<code><intent-filter>
    <action android:name="android.intent.action.VIEW"/>
    <category android:name="android.intent.category.BROWSABLE"/>
    <category android:name="android.intent.category.DEFAULT"/>

    <data
        android:host="scan"
        android:pathPrefix="/profile/foo"
        android:scheme="fb"/>
</intent-filter>
</code>```

You can see more information here.

ContentLicense: CC BY-SA 3.0

Body:
Maybe you should add some content at your app like this:

<intent-filter>
    <action android:name="android.intent.action.VIEW"/>
    <category android:name="android.intent.category.BROWSABLE"/>
    <category android:name="android.intent.category.DEFAULT"/>

    <data
        android:host="scan"
        android:pathPrefix="/profile/foo"
        android:scheme="fb"/>
</intent-filter>

You can see more information here.


问:
Parallelizing reduce operation
Could a usual 'max' operation as below be distributed as a reduce operation on multiple cores by simply changing stream to parallelstream?<br>
How does the final reconcile  happen (without an explicit combiner) between the outcomes of the different threads? </p>

```<code>List<Employee> emps = new ArrayList<>();
emps.add(new Employee("Roy1",32));
emps.add(new Employee("Roy2",12));
emps.add(new Employee("Roy3",22));
emps.add(new Employee("Roy4",42));
emps.add(new Employee("Roy5",52));

Integer maxSal= emps.parallelStream().mapToInt(e -> e.getSalary()).reduce((a,b)->Math.max(a, b)).getAsInt();

System.out.println("Maximum in parallel " + maxSal);
</code>```

答:
Yes, reduce can be parallelized. However, this requires that you pass an associative operator. Excerpt from java.util.stream JavaDoc:

Associativity

An operator or function op is associative if the following holds:

(a op b) op c == a op (b op c)

The importance of this to parallel evaluation can be seen if we expand this to four terms:

a op b op c op d == (a op b) op (c op d)

So we can evaluate (a op b) in parallel with (c op d), and then invoke op on the results.
  Examples of associative operations include numeric addition, min, and max, and string concatenation.

Title: Parallelizing reduce operation

Body:
Could a usual 'max' operation as below be distributed as a reduce operation on multiple cores by simply changing stream to parallelstream?

How does the final reconcile  happen (without an explicit combiner) between the outcomes of the different threads?

List<Employee> emps = new ArrayList<>();
emps.add(new Employee("Roy1",32));
emps.add(new Employee("Roy2",12));
emps.add(new Employee("Roy3",22));
emps.add(new Employee("Roy4",42));
emps.add(new Employee("Roy5",52));

Integer maxSal= emps.parallelStream().mapToInt(e -> e.getSalary()).reduce((a,b)->Math.max(a, b)).getAsInt();

System.out.println("Maximum in parallel " + maxSal);


问:
change icon at row in data-table with out affect other icon at each row
I have fa-square-o up the table
and I used while loop to fill data-table from data-base
in one column I have two icons of font awesome one is fa-star-o and another is fa-square-o.
I use jQuery to change icon on click.
When i click in on icon is working probably but the other icon has same class in other row is hidden.

This is HTML Code for square upper table

```<code><li class="dropdown li-inv-h">
  <a class="dropdown-toggle" data-toggle="dropdown" href="#">
     <i class=" i-invo"><span class="caret"></span></i></a>
     <ul class="dropdown-menu">
       <li><a href="#">All</a></li>
       <li><a href="#">Nothing</a></li>
       <li><a href="#">Is reading</a></li>
       <li><a href="#">Not reading</a></li>
       <li><a href="#">Delete</a></li>
     </ul>
     <a href="#"><i class="fa fa-square-o" ></i></a>
</li>
</code>```

This is PHP Code for column has Font Awesome in side While loop

```<code>while($row = mysqli_fetch_assoc($qry)){
echo ' <tr>
<td class="col-lg-1">
   <span><i class="fa fa-square-o sqr" id="'.$row["id"].'"></i></span>
   <span class="fa-m-inv"><i class="fa fa-star-o str" id="'.$row["id"].'"></i></span>
</td>
<td class="col-lg-1">'.$row["name"].'</td>
</tr>
</code>```

My java-script is

```<code>$('.sqr').click(function(){
    if ($(this).hasClass("fa-square-o")) {
        $("i.fa-square-o").removeClass("fa-square-o");
        $(this).addClass("fa-check-square-o");
        $(this).css({'color':'blue'});
    }else{
        $("i.fa-square-o").removeClass("fa-check-square-o");
        $(this).addClass("fa-square-o");
        $(this).css({'color':'black'});
    }
});
$('.str').click(function(){
        //var id = $(this).attr("id");
    if ($(this).hasClass("fa-star-o")) {
        $("i.fa-star-o").removeClass("fa-star-o");
        $(this).addClass("fa-star");
        $(this).css({'color':'yellow'});
    }else{
        $("i.fa-star-o").removeClass("fa-star");
        $(this).addClass("fa-star-o");
        $(this).css({'color':'black'});
    }
});
</code>```

T

$('.sqr').click(function(){
  if ($(this).hasClass("fa-square-o")) {
   $("i.fa-square-o").removeClass("fa-square-o");
   $(this).addClass("fa-check-square-o");
   $(this).css({'color':'blue'});
  }else{
   $("i.fa-square-o").removeClass("fa-check-square-o");
   $(this).addClass("fa-square-o");
   $(this).css({'color':'black'});
  }
 });
 $('.str').click(function(){
  if ($(this).hasClass("fa-star-o")) {
   $("i.fa-star-o").removeClass("fa-star-o");
   $(this).addClass("fa-star");
   $(this).css({'color':'red'});
  }else{
   $("i.fa-star-o").removeClass("fa-star");
   $(this).addClass("fa-star-o");
   $(this).css({'color':'black'});
  }
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<li class="dropdown li-inv-h">

    <i class=" i-invo"><span class="caret"></span></i>
    <ul class="dropdown-menu">
      <li>Checked</li>
      <li>Unchecked</li>
      <li>Reading</li>
      <li>Unreading</li>
      <li>Delete</li>
    </ul>
    <i class="fa fa-square-o" ></i>
</li>
<table id="data-table" class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th>User</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="col-lg-1">
      <span>
        <i class="fa fa-square-o sqr"></i>
      </span>
      <span>
        <i class="fa fa-star-o str"></i>
      </span>
    </td>
    <td>Name1</td>
  </tr>
  <tr>
    <td class="col-lg-1">
      <span>
        <i class="fa fa-square-o sqr"></i>
      </span>
      <span>
        <i class="fa fa-star-o str"></i>
      </span>
    </td>
    <td>Name2</td>
  </tr>
  <tr>
    <td class="col-lg-1">
      <span>
        <i class="fa fa-square-o sqr"></i>
      </span>
      <span>
        <i class="fa fa-star-o str"></i>
      </span>
    </td>
    <td>Name3</td>
  </tr>
  <tr>
    <td class="col-lg-1">
      <span>
        <i class="fa fa-square-o sqr"></i>
      </span>
      <span>
        <i class="fa fa-star-o str"></i>
      </span>
    </td>
    <td>Name4</td>
  </tr>
</tbody>
</table></code>```

The problem for me not in php code but in java-script via font-icon change, When i click in one icon in row all other icon in other row is effective. that mean i have one empty star in each row when i click this star is remove from this row and com other star fill by yellow color but in my code when i click star all other star in each row is remove also.

I want Fix this problem, also i want when any class has fa-check-square-o change fa-icon upper table to fa-minus-square and add id of row to array to make one event choice like delete.

I read more post and not found post nearly this

Thank you every one.

答:
Change $("i.fa-star-o").removeClass("fa-star-o"); To

$(this).removeClass("fa-star-o");

$('.sqr').click(function(){
  if ($(this).hasClass("fa-square-o")) {
   $(this).removeClass("fa-square-o");
   $(this).addClass("fa-check-square-o");
   $(this).css({'color':'blue'});
  }else{
   $(this).removeClass("fa-check-square-o");
   $(this).addClass("fa-square-o");
   $(this).css({'color':'black'});
  }
 });
 $('.str').click(function(){
  if ($(this).hasClass("fa-star-o")) {
   $(this).removeClass("fa-star-o");
   $(this).addClass("fa-star");
   $(this).css({'color':'red'});
  }else{
   $(this).removeClass("fa-star");
   $(this).addClass("fa-star-o");
   $(this).css({'color':'black'});
  }
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<li class="dropdown li-inv-h">

    <i class=" i-invo"><span class="caret"></span></i>
    <ul class="dropdown-menu">
      <li>Checked</li>
      <li>Unchecked</li>
      <li>Reading</li>
      <li>Unreading</li>
      <li>Delete</li>
    </ul>
    <i class="fa fa-square-o" ></i>
</li>
<table id="data-table" class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th>User</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="col-lg-1">
      <span>
        <i class="fa fa-square-o sqr"></i>
      </span>
      <span>
        <i class="fa fa-star-o str"></i>
      </span>
    </td>
    <td>Name1</td>
  </tr>
  <tr>
    <td class="col-lg-1">
      <span>
        <i class="fa fa-square-o sqr"></i>
      </span>
      <span>
        <i class="fa fa-star-o str"></i>
      </span>
    </td>
    <td>Name2</td>
  </tr>
  <tr>
    <td class="col-lg-1">
      <span>
        <i class="fa fa-square-o sqr"></i>
      </span>
      <span>
        <i class="fa fa-star-o str"></i>
      </span>
    </td>
    <td>Name3</td>
  </tr>
  <tr>
    <td class="col-lg-1">
      <span>
        <i class="fa fa-square-o sqr"></i>
      </span>
      <span>
        <i class="fa fa-star-o str"></i>
      </span>
    </td>
    <td>Name4</td>
  </tr>
</tbody>
</table></code>```

Body:
I have fa-square-o up the table
and I used while loop to fill data-table from data-base
in one column I have two icons of font awesome one is fa-star-o and another is fa-square-o.
I use jQuery to change icon on click.
When i click in on icon is working probably but the other icon has same class in other row is hidden.

This is HTML Code for square upper table

All

Nothing

Is reading

Not reading

Delete

This is PHP Code for column has Font Awesome in side While loop

while($row = mysqli_fetch_assoc($qry)){
echo '

'.$row["name"].'

My java-script is

$('.sqr').click(function(){
    if ($(this).hasClass("fa-square-o")) {
        $("i.fa-square-o").removeClass("fa-square-o");
        $(this).addClass("fa-check-square-o");
        $(this).css({'color':'blue'});
    }else{
        $("i.fa-square-o").removeClass("fa-check-square-o");
        $(this).addClass("fa-square-o");
        $(this).css({'color':'black'});
    }
});
$('.str').click(function(){
        //var id = $(this).attr("id");
    if ($(this).hasClass("fa-star-o")) {
        $("i.fa-star-o").removeClass("fa-star-o");
        $(this).addClass("fa-star");
        $(this).css({'color':'yellow'});
    }else{
        $("i.fa-star-o").removeClass("fa-star");
        $(this).addClass("fa-star-o");
        $(this).css({'color':'black'});
    }
});

T

$('.sqr').click(function(){
  if ($(this).hasClass("fa-square-o")) {
   $("i.fa-square-o").removeClass("fa-square-o");
   $(this).addClass("fa-check-square-o");
   $(this).css({'color':'blue'});
  }else{
   $("i.fa-square-o").removeClass("fa-check-square-o");
   $(this).addClass("fa-square-o");
   $(this).css({'color':'black'});
  }
 });
 $('.str').click(function(){
  if ($(this).hasClass("fa-star-o")) {
   $("i.fa-star-o").removeClass("fa-star-o");
   $(this).addClass("fa-star");
   $(this).css({'color':'red'});
  }else{
   $("i.fa-star-o").removeClass("fa-star");
   $(this).addClass("fa-star-o");
   $(this).css({'color':'black'});
  }
 });

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Checked

Unchecked

Reading

Unreading

Delete

    User

    Name1

    Name2

    Name3

    Name4

The problem for me not in php code but in java-script via font-icon change, When i click in one icon in row all other icon in other row is effective. that mean i have one empty star in each row when i click this star is remove from this row and com other star fill by yellow color but in my code when i click star all other star in each row is remove also.

I want Fix this problem, also i want when any class has fa-check-square-o change fa-icon upper table to fa-minus-square and add id of row to array to make one event choice like delete.

I read more post and not found post nearly this

Thank you every one.

Body:
Change $("i.fa-star-o").removeClass("fa-star-o"); To

$(this).removeClass("fa-star-o");

$('.sqr').click(function(){
  if ($(this).hasClass("fa-square-o")) {
   $(this).removeClass("fa-square-o");
   $(this).addClass("fa-check-square-o");
   $(this).css({'color':'blue'});
  }else{
   $(this).removeClass("fa-check-square-o");
   $(this).addClass("fa-square-o");
   $(this).css({'color':'black'});
  }
 });
 $('.str').click(function(){
  if ($(this).hasClass("fa-star-o")) {
   $(this).removeClass("fa-star-o");
   $(this).addClass("fa-star");
   $(this).css({'color':'red'});
  }else{
   $(this).removeClass("fa-star");
   $(this).addClass("fa-star-o");
   $(this).css({'color':'black'});
  }
 });

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<li class="dropdown li-inv-h">
    <a class="dropdown-toggle" data-toggle="dropdown" href="#">
    <i class=" i-invo"><span class="caret"></span></i></a>
    <ul class="dropdown-menu">
      <li><a href="#">Checked</a></li>
      <li><a href="#">Unchecked</a></li>
      <li><a href="#">Reading</a></li>
      <li><a href="#">Unreading</a></li>
      <li><a href="#">Delete</a></li>
    </ul>
    <a href="#"><i class="fa fa-square-o" ></i></a>
</li>
<table id="data-table" class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th>User</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="col-lg-1">
      <span>
        <i class="fa fa-square-o sqr"></i>
      </span>
      <span>
        <i class="fa fa-star-o str"></i>
      </span>
    </td>
    <td>Name1</td>
  </tr>
  <tr>
    <td class="col-lg-1">
      <span>
        <i class="fa fa-square-o sqr"></i>
      </span>
      <span>
        <i class="fa fa-star-o str"></i>
      </span>
    </td>
    <td>Name2</td>
  </tr>
  <tr>
    <td class="col-lg-1">
      <span>
        <i class="fa fa-square-o sqr"></i>
      </span>
      <span>
        <i class="fa fa-star-o str"></i>
      </span>
    </td>
    <td>Name3</td>
  </tr>
  <tr>
    <td class="col-lg-1">
      <span>
        <i class="fa fa-square-o sqr"></i>
      </span>
      <span>
        <i class="fa fa-star-o str"></i>
      </span>
    </td>
    <td>Name4</td>
  </tr>
</tbody>
</table>


问:
I have 2 functions in my Javascript.One has multiple ajax calls to get the data and other displays the data.The functions are not executed in sequence
```<code>Sample Code

$( document ).ready(function() {
    getData();
    LoadData();
});

function getData() {
        alert('getData');
        Data='';
        $.ajax({
            type: "GET",
            url: "http://localhost:34126/SAL/FCDataService.svc/GetMonthlyInvValue",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {},
            processdata: true,
            async: false,
            success: function (json) {
                Data= json;
               alert('Data:' + Data);
            },
            error: function (e) {
                alert('error ' + e.status + '  ' + e.responseText);
            }
        });

}

function LoadData() {
        alert('LoadData');

    }
</code>```

The expected Output:
getData
Data:{"label": "Jan", "Value": "1"}
LoadData

The actual Output :
getData
LoadData
Data:{"label": "Jan", "Value": "1"}

What am I doing wrong.Please help me!!

答:
AJAX is asynchronous process ans ajax request start in different thread, so JavaScript not wait for AJAX response, so there is two possible way to handle it

Make AJAX request in synchronous process, by pass async:false in jquery AJAX parameter

call getData() function in AJAX callback liks success/error or done/faild callback something like

$.ajax({
  // your code
}).done(function(data) {
   getData()
}).fail(function(data){
});

Body:
Sample Code

$( document ).ready(function() {
    getData();
    LoadData();
});

function getData() {
        alert('getData');
        Data='';
        $.ajax({
            type: "GET",
            url: "http://localhost:34126/SAL/FCDataService.svc/GetMonthlyInvValue",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {},
            processdata: true,
            async: false,
            success: function (json) {
                Data= json;
               alert('Data:' + Data);
            },
            error: function (e) {
                alert('error ' + e.status + '  ' + e.responseText);
            }
        });

}

function LoadData() {
        alert('LoadData');

    }

The expected Output:
getData
Data:{"label": "Jan", "Value": "1"}
LoadData

The actual Output :
getData
LoadData
Data:{"label": "Jan", "Value": "1"}

What am I doing wrong.Please help me!!


问:
how to "sort" polygons 3d?
I am still working on my "javascript 3d engine" (link inside stackoverflow).
at First, all my polygons were faces of cubes, so sorting them by average Z was working fine.
but now I've "evolved" and I want to draw my polygons (which may contain more than 4 vertices)
in the right order, namely, those who are close to the camera will be drawn last.

basically,
I know how to rotate them and "perspective"-ize them into 2D,
but don't know how to draw them in the right order.

just to clarify:

```<code>//my 3d shape = array of polygons
//polygon = array of vertices
//vertex = point with x,y,z
//rotation is around (0,0,0) and my view point is (0,0,something) I guess.
</code>```

can anyone help?

p.s: some "catch phrases" I came up with, looking for the solution: z-buffering, ray casting (?!), plane equations, view vector, and so on - guess I need a simple to understand answer so that's why I asked this one. thanks.

p.s2: i don't mind too much about overlapping or intersecting polygons... so maybe the painter's algorthm indeed might be good. but: what is it exactly? how do I decide the distance of a polygon?? a polygon has many points.

答:
I think you will have some ideas by investigating BSP tree ( binary spaces partition tree ), even if the algo will require to split some of your polygon in two.
Some example could be find here http://www.devmaster.net/articles/bsp-trees/ or by google for BSP tree. Posting some code as a reply is, in my opinion, not serious since is a complex topic.</p>

ContentLicense: CC BY-SA 2.5

Title: how to "sort" polygons 3d?

Body:
I am still working on my "javascript 3d engine" (link inside stackoverflow).
at First, all my polygons were faces of cubes, so sorting them by average Z was working fine.
but now I've "evolved" and I want to draw my polygons (which may contain more than 4 vertices)
in the right order, namely, those who are close to the camera will be drawn last.

basically,
I know how to rotate them and "perspective"-ize them into 2D,
but don't know how to draw them in the right order.

just to clarify:

//my 3d shape = array of polygons
//polygon = array of vertices
//vertex = point with x,y,z
//rotation is around (0,0,0) and my view point is (0,0,something) I guess.

can anyone help?

p.s: some "catch phrases" I came up with, looking for the solution: z-buffering, ray casting (?!), plane equations, view vector, and so on - guess I need a simple to understand answer so that's why I asked this one. thanks.

p.s2: i don't mind too much about overlapping or intersecting polygons... so maybe the painter's algorthm indeed might be good. but: what is it exactly? how do I decide the distance of a polygon?? a polygon has many points.


问:
Split na array to a multidimensional array alphabetically
I have a PHP array returned to me in the following format:

```<code>[0] => Array
        (
            [mainCatID] => 2
            [mainCatCode] => cat2
            [mainCatDesc] => Acupuncture
            [mainCatAddedDate] => 2016-10-12 10:22:49
            [mainCatStatus] => active
        )

[1] => Array
    (
        [mainCatID] => 3
        [mainCatCode] => cat3
        [mainCatDesc] => Medical
        [mainCatAddedDate] => 2016-10-12 10:22:49
        [mainCatStatus] => active
    )

[2] => Array
    (
        [mainCatID] => 4
        [mainCatCode] => cat4
        [mainCatDesc] => Aids & Hiv
        [mainCatAddedDate] => 2016-10-12 10:22:49
        [mainCatStatus] => active
    )

[3] => Array
    (
        [mainCatID] => 1
        [mainCatCode] => cat1
        [mainCatDesc] => Brains
        [mainCatAddedDate] => 2016-10-12 10:22:49
        [mainCatStatus] => active
    )
</code>```

What I would like to achieve is to split the array into different alphabetical "chunks" based on the [mainCatDesc] first alphabet. So the result is expected to be like the following:

A

Accupunture
Aids & Hiv

B

Brains

M

Medical

Thanks for the help in advance! Cheers!

Edited *

so far I only have

```<code>$con = open_connection();
$allMainCatArray = getAllMainCat($con);
close_connection($con);

echo "```";
print_r($allMainCatArray);
echo "```";
</code>```

答:
Do this simple loop:</p>

```<code>$newArray = [];//create a new array
foreach($array as $item) {
   $letter = $item['mainCatDesc'][0];//get the first letter

   if (!ctype_alpha($letter)) {//test if its letter
     $newArray['#'][] = $item['mainCatDesc'];

   } else if(count($newArray[$letter])) {//test if the letter is in the array
      $newArray[$letter][] = $item['mainCatDesc'];//save the value
   } else {
       $newArray[$letter] = [$item['mainCatDesc']];
   }
}
</code>```

Body:
I have a PHP array returned to me in the following format:

[0] => Array
        (
            [mainCatID] => 2
            [mainCatCode] => cat2
            [mainCatDesc] => Acupuncture
            [mainCatAddedDate] => 2016-10-12 10:22:49
            [mainCatStatus] => active
        )

[1] => Array
    (
        [mainCatID] => 3
        [mainCatCode] => cat3
        [mainCatDesc] => Medical
        [mainCatAddedDate] => 2016-10-12 10:22:49
        [mainCatStatus] => active
    )

[2] => Array
    (
        [mainCatID] => 4
        [mainCatCode] => cat4
        [mainCatDesc] => Aids & Hiv
        [mainCatAddedDate] => 2016-10-12 10:22:49
        [mainCatStatus] => active
    )

[3] => Array
    (
        [mainCatID] => 1
        [mainCatCode] => cat1
        [mainCatDesc] => Brains
        [mainCatAddedDate] => 2016-10-12 10:22:49
        [mainCatStatus] => active
    )

What I would like to achieve is to split the array into different alphabetical "chunks" based on the [mainCatDesc] first alphabet. So the result is expected to be like the following:

A

Accupunture
Aids & Hiv

B

Brains

M

Medical

Thanks for the help in advance! Cheers!

Edited *

so far I only have

$con = open_connection();
$allMainCatArray = getAllMainCat($con);
close_connection($con);

echo "
";
print_r($allMainCatArray);
echo "
";

Body:
Do this simple loop:

$newArray = [];//create a new array
foreach($array as $item) {
   $letter = $item['mainCatDesc'][0];//get the first letter

   if (!ctype_alpha($letter)) {//test if its letter
     $newArray['#'][] = $item['mainCatDesc'];

   } else if(count($newArray[$letter])) {//test if the letter is in the array
      $newArray[$letter][] = $item['mainCatDesc'];//save the value
   } else {
       $newArray[$letter] = [$item['mainCatDesc']];
   }
}


问:
How to show tabs one by one while swiping in a view pager in android
I need a TabLayout which shows only two tabs on it's initial stage.
After swiping active tab will be in center, next tab will be in left side and previous tab will be on right side.
 How can I do that?

Below are the exact scenario snapshots:

 pls anyone advice me.?

答:
After long time search got the solution by using the library PagerSlidingTabStrip.

app:pstsPaddingMiddle="true"
app:pstsTabPaddingLeftRight="80dp"

This made the trick.


问:
UserDefaults Bool FAIL
I'm trying to save below data using UserDefaults but when I pass isDefault bool, it does not work. But if I remove isDefault it works fine.

https://gist.github.com/n1tesh/4de0fea9514e392e35e241786f51e98b

```<code>struct User {

    var userContact  = CNContact()
    var recipientContact: CNContact?
    var isDefault: Bool = false
    init(userContact: CNContact, recipientContact: CNContact? = nil, isDefault: Bool) {
        self.userContact = userContact
        self.recipientContact = recipientContact
        self.isDefault = isDefault
    }

}

extension User {
    @objc(_TtCV6testUD4User6Coding)class Coding: NSObject, NSCoding {

        let model: User?

        init(model: User) {
            self.model = model
            super.init()
        }

        func encode(with aCoder: NSCoder) {
            guard let model = self.model else {
                return
            }

            aCoder.encode(model.userContact, forKey: "userContact")
            aCoder.encode(model.recipientContact, forKey: "recipientContact")
            aCoder.encode(model.isDefault, forKey: "isDefault")

        }

        required init?(coder aDecoder: NSCoder) {
            guard let userContact = aDecoder.decodeObject(forKey: "userContact") as? CNContact,let isDefault = aDecoder.decodeObject(forKey: "isDefault") as? Bool  else  {
                    return nil
            }
          let recipientContact = aDecoder.decodeObject(forKey: "recipientContact") as? CNContact

            model = User(userContact: userContact, recipientContact: recipientContact, isDefault: isDefault)
            super.init()
        }

    }
}
</code>```

答:
In terms of NSCoding Bool is not an object. Use the dedicated method decodeBool(forKey

```<code>let isDefault = aDecoder.decodeBool(forKey: "isDefault")
</code>```

The result is a non-optional Bool

Title: UserDefaults Bool FAIL

Body:
I'm trying to save below data using UserDefaults but when I pass isDefault bool, it does not work. But if I remove isDefault it works fine.

https://gist.github.com/n1tesh/4de0fea9514e392e35e241786f51e98b

struct User {

    var userContact  = CNContact()
    var recipientContact: CNContact?
    var isDefault: Bool = false
    init(userContact: CNContact, recipientContact: CNContact? = nil, isDefault: Bool) {
        self.userContact = userContact
        self.recipientContact = recipientContact
        self.isDefault = isDefault
    }

}

extension User {
    @objc(_TtCV6testUD4User6Coding)class Coding: NSObject, NSCoding {

        let model: User?

        init(model: User) {
            self.model = model
            super.init()
        }

        func encode(with aCoder: NSCoder) {
            guard let model = self.model else {
                return
            }

            aCoder.encode(model.userContact, forKey: "userContact")
            aCoder.encode(model.recipientContact, forKey: "recipientContact")
            aCoder.encode(model.isDefault, forKey: "isDefault")

        }

        required init?(coder aDecoder: NSCoder) {
            guard let userContact = aDecoder.decodeObject(forKey: "userContact") as? CNContact,let isDefault = aDecoder.decodeObject(forKey: "isDefault") as? Bool  else  {
                    return nil
            }
          let recipientContact = aDecoder.decodeObject(forKey: "recipientContact") as? CNContact

            model = User(userContact: userContact, recipientContact: recipientContact, isDefault: isDefault)
            super.init()
        }

    }
}

Body:
In terms of NSCoding Bool is not an object. Use the dedicated method decodeBool(forKey

let isDefault = aDecoder.decodeBool(forKey: "isDefault")

The result is a non-optional Bool


问:
convert date and time from onetimezone to anothertimezone in php
```<code> $fromTz=">America/chicago"; //Time zone for UM6
 $toTz="America/Adak" ;//Time Zone for UM4
 $date = new DateTime($time, new DateTimeZone($fromTz));
 echo "<br>America/chicago Time ".$date->format('Y-m-d H:i:s');
 $date->setTimezone(new DateTimeZone($toTz));
 $time= $date->format('Y-m-d H:i:s');
 echo "<br>Time For $toTz ".$time;
</code>```

I have convert the date and time from onetimezone to another timezone in php.

I want to convert UM6 To UM4,UM5,UM7,UM8

but i don'nt know the value of UM5,UM7 and UM8
like UM4="America/Adak"

So what the value for UM5,UM7 and UM8

答:
use this, use this function for convert time zone.</p>

```<code>function converTotimezone($time="",$toTz='',$fromTz=''){
    // timezone by php friendly values
    $date = new DateTime($time, new DateTimeZone($fromTz));
    $date->setTimezone(new DateTimeZone($toTz));
    $time= $date->format('Y-m-d H:i:s');
    return $time;
}
</code>```

Body:
 $fromTz=">America/chicago"; //Time zone for UM6
 $toTz="America/Adak" ;//Time Zone for UM4
 $date = new DateTime($time, new DateTimeZone($fromTz));
 echo "
America/chicago Time ".$date->format('Y-m-d H:i:s');
 $date->setTimezone(new DateTimeZone($toTz));
 $time= $date->format('Y-m-d H:i:s');
 echo "
Time For $toTz ".$time;

I have convert the date and time from onetimezone to another timezone in php.

I want to convert UM6 To UM4,UM5,UM7,UM8

but i don'nt know the value of UM5,UM7 and UM8
like UM4="America/Adak"

So what the value for UM5,UM7 and UM8

Body:
use this, use this function for convert time zone.

function converTotimezone($time="",$toTz='',$fromTz=''){
    // timezone by php friendly values
    $date = new DateTime($time, new DateTimeZone($fromTz));
    $date->setTimezone(new DateTimeZone($toTz));
    $time= $date->format('Y-m-d H:i:s');
    return $time;
}


问:
Why do i need to import modules everytime in webpack bundle?
Im using webpack to generate a bundle file, namely app.bundle.js. It seems to be the case that in each seperate js file I need to import the modules it will use.

I've been trying to wrap my head around this but it eludes me hard. The way i understand the bundling process is, put simplified: it takes all the files you've specified and merges them into one big output file.

That should mean that a class is declared ONCE in that big file and that should be enough to serve as a reference for all the others. Why do i need to import it again and again and again when it should simply just be there at the top of the bundle file being availabe for every other piece of code written thereafter?

P.S ( A simple example )

I've got the following files:

A.js

```<code>class A {
    doIt(){
      console.log(this);
    }
}
</code>```

B.js:

```<code>import {A} from "a.js";

class B extends A {

}
</code>```

main.js:

```<code>import {A} from "a.js"
import {B} from "b.js"
</code>```

To use B in main.js i NEED to import A as well. And if A had another subclass i'd need to import that too. This, to me, looks insane, to the point that i'd prefer to afix everything on window.

If anyone knows, please help me understand what im missing.

答:
Webpack takes all the files you've specified and merges them into one big output file to pull in the dependant Modules at the right time, in the correct scope.

so if we have:

```<code>// sum.js
</code>```

var sum = function (a, b) {
    return a + b;};

// multiply.js

```<code>// slightly contrived here - we're going to repeatedly sum to multiply, to illustrate dependency
// interaction
var multiply = function (a, b) {
    var total = 0;
    for (var i = 0; i < b; i++) {
        total = sum(a, total);
    }
    return total;
};
</code>```

// index.js

```<code>- our application logic
var totalMultiply = multiply(5, 3);
var totalSum = sum(5, 3);

console.log('Product of 5 and 3 = ' + totalMultiply);
console.log('Sum of 5 and 3 = ' + totalSum);
</code>```

// index.html

```<code>- our entry point to our application
<html>
<head>
    <script src="src/sum.js"></script>
    <script src="src/multiply.js"></script>
    <script src="src/index.js"></script>
</head>
</html>
</code>```

the output of this would be:

```<code>Product of 5 and 3 = 15
index.js:17 Sum of 5 and 3 = 8
</code>```

If we get the order wrong in index.html our application won't work.If index.js is included before either of the other dependencies,or if sum.js is included after multiply.js we will get errors. That is the point from the bundle file.

Webpack can pull all of our dependencies into a single filebundle file,meaning that only one dependency would need to be downloaded.

2- Making Dependencies Available, And Linking Them

CommonJS uses module.exports to export - or make available - functions or variables to other code. It uses require to then pull in these exported values.

// sum.js

```<code>var sum = function (a, b) {
    return a + b;
};
module.exports = sum;
</code>```

// multiply.js

```<code>var sum = require('./sum');

var multiply = function (a, b) {
    var total = 0;
    for (var i = 0; i < b; i++) {
        total = sum(a, total);
    }
    return total;
};
module.exports = multiply;
</code>```

// index.js

```<code>- our application logic
var multiply = require('./multiply');
var sum = require('./sum');

var totalMultiply = multiply(5, 3);
var totalSum = sum(5, 3);

console.log('Product of 5 and 3 = ' + totalMultiply);
console.log('Sum of 5 and 3 = ' + totalSum);
</code>```

Notice that we've made both sum and multiply available to other code and we've pulled in these exported functions in both multiple.js and index.js.

Notice too that our index.html now only needs to pull in a single file - bundle.js.

We can expose what we want and keep other code effectively private

that is the whole point, you need to tell webpack which modules you need them to communicate and share data with each other. As in webpack Each module has a smaller surface area than a full program, making verification, debugging, and testing trivial. Well-written modules provide solid abstractions and encapsulation boundaries, so that each module has a coherent design and a clear purpose within the overall application.

We also reduce web calls from 3 (sum.js, multiply.js and index.js) to
a single call - this will help speed loading times.

Notice i wouldn't recommend exposing libraries or modules as global unless you really do need it, i.e. the point of a module system is to explicitly declare dependencies.

ProvidePlugin: This plugin makes a module available as a variable in every module. The module is required only if you use the variable.

Example: Make $ and jQuery available in every module without writing require("jquery").

```<code>new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
})
</code>```

So:

```<code>// app.js
$.ajax(...);
</code>```

Is effectively transpiled into:

```<code>// slightly contrived here - we're going to repeatedly sum to multiply, to illustrate dependency
// interaction
var multiply = function (a, b) {
    var total = 0;
    for (var i = 0; i < b; i++) {
        total = sum(a, total);
    }
    return total;
};
</code>```0

webpack will generate a code of loading of the specified module the same as it it does it for import or require.

further read: Webpack ProvidePlugin: how not to write the import/require sheet at the beginning of module javascript

Body:
Im using webpack to generate a bundle file, namely app.bundle.js. It seems to be the case that in each seperate js file I need to import the modules it will use.

I've been trying to wrap my head around this but it eludes me hard. The way i understand the bundling process is, put simplified: it takes all the files you've specified and merges them into one big output file.

That should mean that a class is declared ONCE in that big file and that should be enough to serve as a reference for all the others. Why do i need to import it again and again and again when it should simply just be there at the top of the bundle file being availabe for every other piece of code written thereafter?

P.S ( A simple example )

I've got the following files:

A.js

class A {
    doIt(){
      console.log(this);
    }
}

B.js:

import {A} from "a.js";

class B extends A {

}

main.js:

import {A} from "a.js"
import {B} from "b.js"

To use B in main.js i NEED to import A as well. And if A had another subclass i'd need to import that too. This, to me, looks insane, to the point that i'd prefer to afix everything on window.

If anyone knows, please help me understand what im missing.

Body:
Webpack takes all the files you've specified and merges them into one big output file to pull in the dependant Modules at the right time, in the correct scope.

so if we have:

// sum.js

var sum = function (a, b) {
    return a + b;};

// multiply.js

// slightly contrived here - we're going to repeatedly sum to multiply, to illustrate dependency
// interaction
var multiply = function (a, b) {
    var total = 0;
    for (var i = 0; i < b; i++) {
        total = sum(a, total);
    }
    return total;
};

// index.js

- our application logic
var totalMultiply = multiply(5, 3);
var totalSum = sum(5, 3);

console.log('Product of 5 and 3 = ' + totalMultiply);
console.log('Sum of 5 and 3 = ' + totalSum);

// index.html

- our entry point to our application
<html>
<head>
    <script src="src/sum.js"></script>
    <script src="src/multiply.js"></script>
    <script src="src/index.js"></script>
</head>
</html>

the output of this would be:

Product of 5 and 3 = 15
index.js:17 Sum of 5 and 3 = 8

If we get the order wrong in index.html our application won't work.If index.js is included before either of the other dependencies,or if sum.js is included after multiply.js we will get errors. That is the point from the bundle file.

Webpack can pull all of our dependencies into a single filebundle file,meaning that only one dependency would need to be downloaded.

2- Making Dependencies Available, And Linking Them

CommonJS uses module.exports to export - or make available - functions or variables to other code. It uses require to then pull in these exported values.

// sum.js

var sum = function (a, b) {
    return a + b;
};
module.exports = sum;

// multiply.js

var sum = require('./sum');

var multiply = function (a, b) {
    var total = 0;
    for (var i = 0; i < b; i++) {
        total = sum(a, total);
    }
    return total;
};
module.exports = multiply;

// index.js

- our application logic
var multiply = require('./multiply');
var sum = require('./sum');

var totalMultiply = multiply(5, 3);
var totalSum = sum(5, 3);

console.log('Product of 5 and 3 = ' + totalMultiply);
console.log('Sum of 5 and 3 = ' + totalSum);

Notice that we've made both sum and multiply available to other code and we've pulled in these exported functions in both multiple.js and index.js.

Notice too that our index.html now only needs to pull in a single file - bundle.js.

We can expose what we want and keep other code effectively private

that is the whole point, you need to tell webpack which modules you need them to communicate and share data with each other. As in webpack Each module has a smaller surface area than a full program, making verification, debugging, and testing trivial. Well-written modules provide solid abstractions and encapsulation boundaries, so that each module has a coherent design and a clear purpose within the overall application.

We also reduce web calls from 3 (sum.js, multiply.js and index.js) to
a single call - this will help speed loading times.

Notice i wouldn't recommend exposing libraries or modules as global unless you really do need it, i.e. the point of a module system is to explicitly declare dependencies.

ProvidePlugin: This plugin makes a module available as a variable in every module. The module is required only if you use the variable.

Example: Make $ and jQuery available in every module without writing require("jquery").

new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
})

So:

// app.js
$.ajax(...);

Is effectively transpiled into:

// app.js
require('jquery').ajax(...);

webpack will generate a code of loading of the specified module the same as it it does it for import or require.

further read: Webpack ProvidePlugin: how not to write the import/require sheet at the beginning of module javascript


问:
Google Storage ArgumentException when setting CORS config
Following Google docs, when using GoogleCloud Storage console:

```<code>mysef@myproject:~$ cat cors-json-file.json
[
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]
</code>```

then I get the following error:

```<code>myself@myproject:~$ gsutil cors set cors-json-file.json gs://mybucket
Setting CORS on gs://mybucket/...
ArgumentException: JSON CORS data could not be loaded from: [
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]
</code>```

same error when I remove "method", "maxAgeSeconds" or add "responseHeader".

答: I had the same problem and it was caused by the type of quotes used. By opening the json-file in a plain text editor and change the quote to standard ones fixed the problem.</p>

ContentLicense: CC BY-SA 4.0

Body:
Following Google docs, when using GoogleCloud Storage console:

mysef@myproject:~$ cat cors-json-file.json
[
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

then I get the following error:

myself@myproject:~$ gsutil cors set cors-json-file.json gs://mybucket
Setting CORS on gs://mybucket/...
ArgumentException: JSON CORS data could not be loaded from: [
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

same error when I remove "method", "maxAgeSeconds" or add "responseHeader".


问:
Dreamweaver cc SQL Query
I know this question have been asked many times before and I have searched and tried figure out where I am going wrong and I can't seem to do it.

Any help would be apreciated.  Thanks in advance.

I have a dreamweaver cc Update query already set up and it works great.  I want to now add an image to my database.

Here is my query:

```<code>    $image = $_FILES['speakerimage']['tmp_name'];
    $imgContent = addslashes(file_get_contents($image));
    $updateSQL = sprintf("UPDATE Speakers SET speaker=%s,     chkSportsCeleb=%s, chkEntertainment=%s, chkEmcee=%s, chkCFLAA=%s, chkKeynote=%s, chkAutioneer=%s, speakerImg=%s WHERE speakerID=%s",
                   GetSQLValueString($_POST['speaker'], "text"),
                   GetSQLValueString(isset($_POST['SportsCeleb']) ? "true" : "", "defined","1","0"),
                   GetSQLValueString(isset($_POST['Entertainment']) ? "true" : "", "defined","1","0"),
                   GetSQLValueString(isset($_POST['Emcee']) ? "true" : "", "defined","1","0"),
                   GetSQLValueString(isset($_POST['CFLAA']) ? "true" : "", "defined","1","0"),
                   GetSQLValueString(isset($_POST['Keynote']) ? "true" : "", "defined","1","0"),
                   GetSQLValueString(isset($_POST['Autioneer']) ? "true" : "", "defined","1","0"),
                   $imgContent,
                   GetSQLValueString($_POST['speakerID'], "int"));
</code>```

When I preview my code in the browser this is what I  get:

```<code>   query = UPDATE Speakers SET speaker='John Doe', chkSportsCeleb=1, chkEntertainment=0, chkEmcee=0, chkCFLAA=1, chkKeynote=1, chkAutioneer=0, speakerImg= WHERE speakerID=59  You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE speakerID=59' at line 1
</code>```

I believe the image content should show up as gibberish.  I just can't figure out how to re-write this.

Thanks

Roland

答:
Try loading the image into a variable and then directly specifying it in your UPDATE statement:

```<code>$image = $_FILES['speakerimage']['tmp_name'];
$imgContent = addslashes(file_get_contents($image));
$updateSQL = sprintf("UPDATE Speakers SET speaker=%s,     chkSportsCeleb=%s, chkEntertainment=%s, chkEmcee=%s, chkCFLAA=%s, chkKeynote=%s, chkAutioneer=%s, $imgContent WHERE speakerID=%s",
// ...
</code>```

Title: Dreamweaver cc SQL Query

Body:
I know this question have been asked many times before and I have searched and tried figure out where I am going wrong and I can't seem to do it.

Any help would be apreciated.  Thanks in advance.

I have a dreamweaver cc Update query already set up and it works great.  I want to now add an image to my database.

Here is my query:

    $image = $_FILES['speakerimage']['tmp_name'];
    $imgContent = addslashes(file_get_contents($image));
    $updateSQL = sprintf("UPDATE Speakers SET speaker=%s,     chkSportsCeleb=%s, chkEntertainment=%s, chkEmcee=%s, chkCFLAA=%s, chkKeynote=%s, chkAutioneer=%s, speakerImg=%s WHERE speakerID=%s",
                   GetSQLValueString($_POST['speaker'], "text"),
                   GetSQLValueString(isset($_POST['SportsCeleb']) ? "true" : "", "defined","1","0"),
                   GetSQLValueString(isset($_POST['Entertainment']) ? "true" : "", "defined","1","0"),
                   GetSQLValueString(isset($_POST['Emcee']) ? "true" : "", "defined","1","0"),
                   GetSQLValueString(isset($_POST['CFLAA']) ? "true" : "", "defined","1","0"),
                   GetSQLValueString(isset($_POST['Keynote']) ? "true" : "", "defined","1","0"),
                   GetSQLValueString(isset($_POST['Autioneer']) ? "true" : "", "defined","1","0"),
                   $imgContent,
                   GetSQLValueString($_POST['speakerID'], "int"));

When I preview my code in the browser this is what I  get:

   query = UPDATE Speakers SET speaker='John Doe', chkSportsCeleb=1, chkEntertainment=0, chkEmcee=0, chkCFLAA=1, chkKeynote=1, chkAutioneer=0, speakerImg= WHERE speakerID=59  You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE speakerID=59' at line 1

I believe the image content should show up as gibberish.  I just can't figure out how to re-write this.

Thanks

Roland

Body:
Try loading the image into a variable and then directly specifying it in your UPDATE statement:

$image = $_FILES['speakerimage']['tmp_name'];
$imgContent = addslashes(file_get_contents($image));
$updateSQL = sprintf("UPDATE Speakers SET speaker=%s,     chkSportsCeleb=%s, chkEntertainment=%s, chkEmcee=%s, chkCFLAA=%s, chkKeynote=%s, chkAutioneer=%s, $imgContent WHERE speakerID=%s",
// ...


问:
R Replace character data containing exponent (e.g. E+11, E+20) with number of 0's that is dynamic
I have a dataframe df_before which one of columns contains values such as:

```<code>id
123456789
1.11E+2
3.52E+4
5.60E+5
0001112345857RAE
</code>```

and would like to convert them in df_after to:

```<code>id
123456789
111
35200
560000
0001112345857RAE
</code>```

Basically I want to strip off the period . and replace any E+XX with 0's according to the number/ power of the exponent. This is what I have tried:

```<code> df_after$id <- ifelse(str_detect(df_before$id, "E\\+\\d+$"),
                                gsub("E\\+\\d+",
                                     strrep("0", as.numeric(gsub(".*E\\+(\\d+)$", "\\1", df_before$id)) - 2),
                                     gsub("\\.", "", df_before$id)),
                                df_before$id)
</code>```

Each smaller chunk of the above codes worked with 1 single input, for example this:

```<code>strrep("0", as.numeric(gsub(".*E\\+(\\d+)$", "\\1", "6.32E+3")))
</code>```

results in:

```<code>"000" # which is as expected
</code>```

also:

```<code>gsub("E\\+\\d+",
    strrep("0", as.numeric(gsub(".*E\\+(\\d+)$", "\\1", "6.32E+3")) - 2),
    gsub("\\.", "", "6.32E+3"))
</code>```

gives:

```<code>"6320" # as expected and desired
</code>```

But when I applied it to the whole column using ifelse and str_detect (which also works as expected for those entries containing E+XX, it runs very slowly and returned NA's and some values like 6320NA000NA000NA000NA000....<truncated>

Could someone please assist me in fixing this block of code so it will work with the dataframe column?

Thank you so much!

答:
We can use as.numeric to convert the numeric values while the non-numeric becomes NA. Using is.na, then we index and assign those values that are only numeric to the 'id' column

```<code>df_after <- df_before
v1 <- as.numeric(df_before$id)
i1 <- !is.na(v1)
df_after$id[i1] <- v1[i1]
df_after
#              id
#1        123456789
#2              111
#3            35200
#4           560000
#5 0001112345857RAE
</code>```

Body:
I have a dataframe df_before which one of columns contains values such as:

id
123456789
1.11E+2
3.52E+4
5.60E+5
0001112345857RAE

and would like to convert them in df_after to:

id
123456789
111
35200
560000
0001112345857RAE

Basically I want to strip off the period . and replace any E+XX with 0's according to the number/ power of the exponent. This is what I have tried:

 df_after$id <- ifelse(str_detect(df_before$id, "E\\+\\d+$"),
                                gsub("E\\+\\d+",
                                     strrep("0", as.numeric(gsub(".*E\\+(\\d+)$", "\\1", df_before$id)) - 2),
                                     gsub("\\.", "", df_before$id)),
                                df_before$id)

Each smaller chunk of the above codes worked with 1 single input, for example this:

strrep("0", as.numeric(gsub(".*E\\+(\\d+)$", "\\1", "6.32E+3")))

results in:

"000" # which is as expected

also:

gsub("E\\+\\d+",
    strrep("0", as.numeric(gsub(".*E\\+(\\d+)$", "\\1", "6.32E+3")) - 2),
    gsub("\\.", "", "6.32E+3"))

gives:

"6320" # as expected and desired

But when I applied it to the whole column using ifelse and str_detect (which also works as expected for those entries containing E+XX, it runs very slowly and returned NA's and some values like 6320NA000NA000NA000NA000....<truncated>

Could someone please assist me in fixing this block of code so it will work with the dataframe column?

Thank you so much!

Body:
We can use as.numeric to convert the numeric values while the non-numeric becomes NA. Using is.na, then we index and assign those values that are only numeric to the 'id' column

df_after <- df_before
v1 <- as.numeric(df_before$id)
i1 <- !is.na(v1)
df_after$id[i1] <- v1[i1]
df_after
#              id
#1        123456789
#2              111
#3            35200
#4           560000
#5 0001112345857RAE


答:
There is no problem on parallelizing a stream provided that operations (including inner ones) have good properties. API says (for reduction):

[...] a properly constructed reduce operation is inherently parallelizable,
  so long as the function(s) used to process the elements are
  associative and stateless. [...]

And there is a definition (in the docs) of associative and stateless :

Stateless operations, such as filter and map, retain no state from
  previously seen element when processing a new element -- each element
  can be processed independently of operations on other elements.

and

An operator or function op is associative if the following holds:

```<code> (a op b) op c == a op (b op c)
</code>```

The importance of this to parallel evaluation can be seen if we expand this to four terms:

```<code> a op b op c op d == (a op b) op (c op d)
</code>```

So we can evaluate (a op b) in parallel with (c op d), and then invoke op on the results.

Roughly, if operation is associative and stateless that means that you can apply it in any order you want to get the result. So any good generic gathering can be applied. Remember that Java 8 streams are based on Fork-Join pool, so the gathering is well-known. Tutorial on the subject shows the basics:

```<code>if (my portion of the work is small enough)
  do the work directly
else
  split my work into two pieces
  invoke the two pieces and wait for the results
</code>```

Title: Parallelizing reduce operation

Body:
Could a usual 'max' operation as below be distributed as a reduce operation on multiple cores by simply changing stream to parallelstream?

How does the final reconcile  happen (without an explicit combiner) between the outcomes of the different threads?

List<Employee> emps = new ArrayList<>();
emps.add(new Employee("Roy1",32));
emps.add(new Employee("Roy2",12));
emps.add(new Employee("Roy3",22));
emps.add(new Employee("Roy4",42));
emps.add(new Employee("Roy5",52));

Integer maxSal= emps.parallelStream().mapToInt(e -> e.getSalary()).reduce((a,b)->Math.max(a, b)).getAsInt();

System.out.println("Maximum in parallel " + maxSal);

Body:
There is no problem on parallelizing a stream provided that operations (including inner ones) have good properties. API says (for reduction):

[...] a properly constructed reduce operation is inherently parallelizable,
  so long as the function(s) used to process the elements are
  associative and stateless. [...]

And there is a definition (in the docs) of associative and stateless :

Stateless operations, such as filter and map, retain no state from
  previously seen element when processing a new element -- each element
  can be processed independently of operations on other elements.

and

An operator or function op is associative if the following holds:

 (a op b) op c == a op (b op c)

The importance of this to parallel evaluation can be seen if we expand this to four terms:

 a op b op c op d == (a op b) op (c op d)

So we can evaluate (a op b) in parallel with (c op d), and then invoke op on the results.

Roughly, if operation is associative and stateless that means that you can apply it in any order you want to get the result. So any good generic gathering can be applied. Remember that Java 8 streams are based on Fork-Join pool, so the gathering is well-known. Tutorial on the subject shows the basics:

if (my portion of the work is small enough)
  do the work directly
else
  split my work into two pieces
  invoke the two pieces and wait for the results


问:
ValueError: Tensor Tensor("Const:0", shape=(), dtype=float32) may not be fed with tf.placeholder
I'm trying to make speech recognition system with tensorflow.

Input data is an numpy array of size 50000 X 1.

Output data (mapping data) is an numpy array of size 400 X 1.

Input and mapping data is passed in batches of 2 in a list.

I've used this tutorial to design the neural network. Following is the code snippet:

For RNN:

```<code>input_data = tf.placeholder(tf.float32, [batch_size, sound_constants.MAX_ROW_SIZE_IN_DATA, sound_constants.MAX_COLUMN_SIZE_IN_DATA], name="train_input")
target = tf.placeholder(tf.float32, [batch_size, sound_constants.MAX_ROW_SIZE_IN_TXT, sound_constants.MAX_COLUMN_SIZE_IN_TXT], name="train_output")

fwd_cell = tf.nn.rnn_cell.BasicLSTMCell(num_hidden, state_is_tuple=True, forget_bias=1.0)

# creating one backward cell
bkwd_cell = tf.nn.rnn_cell.BasicLSTMCell(num_hidden, state_is_tuple=True, forget_bias=1.0)

# creating bidirectional RNN
val, _, _ = tf.nn.static_bidirectional_rnn(fwd_cell, bkwd_cell, tf.unstack(input_data), dtype=tf.float32)
</code>```

For feeding data:

```<code>feed = {g['input_data'] : trb[0], g['target'] : trb[1], g['dropout'] : 0.6}
accuracy_, _ = sess.run([g['accuracy'], g['ts']], feed_dict=feed)
accuracy += accuracy_
</code>```

When I ran the code, I got this error:

```<code>Traceback (most recent call last):
  File "/home/wolborg/PycharmProjects/speech-to-text-rnn/src/rnn_train_1.py", line 205, in <module>
    tr_losses, te_losses = train_network(g)
  File "/home/wolborg/PycharmProjects/speech-to-text-rnn/src/rnn_train_1.py", line 177, in train_network
    accuracy_, _ = sess.run([g['accuracy'], g['ts']], feed_dict=feed)
  File "/home/wolborg/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 895, in run
    run_metadata_ptr)
  File "/home/wolborg/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1102, in _run
    raise ValueError('Tensor %s may not be fed.' % subfeed_t)
ValueError: Tensor Tensor("Const:0", shape=(), dtype=float32) may not be fed.

Process finished with exit code 1
</code>```

Earlier, I was facing this issue with tf.sparse_placeholder, then after some browsing, I changed input type to tf.placeholder and made related changes. Now I'm clueless on where I'm making the error.

Please suggest something as how should I feed data.

Entire code:

```<code>import tensorflow as tf

# for taking MFCC and label input
import numpy as np
import rnn_input_data_1
import sound_constants

# input constants

# Training Parameters
num_input = 10 # mfcc data input
training_data_size = 8 # determines number of files in training and testing module
testing_data_size = num_input - training_data_size

# Network Parameters
learning_rate = 0.0001 # for large training set, it can be set 0.001
num_hidden = 200 # number of hidden layers
num_classes = 28 # total alphabet classes (a-z) + extra symbols (', ' ')
epoch = 1 # number of iterations
batch_size = 2 # number of batches

mfcc_coeffs, text_data = rnn_input_data_1.mfcc_and_text_encoding()

class DataGenerator:
    def __init__(self, data_size):
    self.ptr = 0
    self.epochs = 0
    self.data_size = data_size

    def next_batch(self):
    self.ptr += batch_size
    if self.ptr > self.data_size:
        self.epochs += 1
        self.ptr = 0

    return mfcc_coeffs[self.ptr-batch_size : self.ptr], text_data[self.ptr-batch_size : self.ptr]

def reset_graph():
    if 'sess' in globals() and sess:
    sess.close()
    tf.reset_default_graph()

def struct_network():

    print ('Inside struct network !!')

    reset_graph()

    input_data = tf.placeholder(tf.float32, [batch_size, sound_constants.MAX_ROW_SIZE_IN_DATA, sound_constants.MAX_COLUMN_SIZE_IN_DATA], name="train_input")
    target = tf.placeholder(tf.float32, [batch_size, sound_constants.MAX_ROW_SIZE_IN_TXT, sound_constants.MAX_COLUMN_SIZE_IN_TXT], name="train_output")

    keep_prob = tf.constant(1.0)

    fwd_cell = tf.nn.rnn_cell.BasicLSTMCell(num_hidden, state_is_tuple=True, forget_bias=1.0)

    # creating one backward cell
    bkwd_cell = tf.nn.rnn_cell.BasicLSTMCell(num_hidden, state_is_tuple=True, forget_bias=1.0)

    # creating bidirectional RNN
    val, _, _ = tf.nn.static_bidirectional_rnn(fwd_cell, bkwd_cell, tf.unstack(input_data), dtype=tf.float32)

    # adding dropouts
    val = tf.nn.dropout(val, keep_prob)

    val = tf.transpose(val, [1, 0, 2])
    last = tf.gather(val, int(val.get_shape()[0]) - 1)

    # creating bidirectional RNN
    print ('BiRNN created !!')

    print ('Last Size: ', last.get_shape())

    weight = tf.Variable(tf.truncated_normal([num_hidden * 2, sound_constants.MAX_ROW_SIZE_IN_TXT]))
    bias = tf.Variable(tf.constant(0.1, shape=[sound_constants.MAX_ROW_SIZE_IN_TXT]))

    # mapping to 28 output classes
    logits = tf.matmul(last, weight) + bias
    prediction = tf.nn.softmax(logits)
    prediction = tf.reshape(prediction, shape = [batch_size, sound_constants.MAX_ROW_SIZE_IN_TXT, sound_constants.MAX_COLUMN_SIZE_IN_TXT])

    # getting probability distribution
    mat1 = tf.cast(tf.argmax(prediction,1),tf.float32)
    correct = tf.equal(prediction, target)
    accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))

    logits = tf.reshape(logits, shape=[batch_size, sound_constants.MAX_ROW_SIZE_IN_TXT, sound_constants.MAX_COLUMN_SIZE_IN_TXT])

    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=target))
    train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)

    # returning components as dictionary elements
    return {'input_data' : input_data,
        'target' : target,
        'dropout': keep_prob,
        'loss': loss,
        'ts': train_step,
        'preds': prediction,
        'accuracy': accuracy
        }

def train_network(graph):

    # initialize tensorflow session and all variables
    # tf_gpu_config = tf.ConfigProto(allow_soft_placement = True, log_device_placement = True)
    # tf_gpu_config.gpu_options.allow_growth = True

    # with tf.Session(config = tf_gpu_config) as sess:
    with tf.Session() as sess:

    train_instance = DataGenerator(training_data_size)
    test_instance = DataGenerator(testing_data_size)

    print ('Training data size: ', train_instance.data_size)
    print ('Testing data size: ', test_instance.data_size)

    sess.run(tf.global_variables_initializer())
    print ('Starting session...')
    step, accuracy = 0, 0
    tr_losses, te_losses = [], []
    current_epoch = 0
    while current_epoch < epoch:
        step += 1
        trb = train_instance.next_batch()

        feed = {g['input_data'] : trb[0], g['target'] : trb[1], g['dropout'] : 0.6}
        accuracy_, _ = sess.run([g['accuracy'], g['ts']], feed_dict=feed)
        accuracy += accuracy_

        if train_instance.epochs > current_epoch:
            current_epoch += 1
            tr_losses.append(accuracy / step)
            step, accuracy = 0, 0

            #eval test set
            te_epoch = test_instance.epochs
            while test_instance.epochs == te_epoch:
                step += 1
                print ('Testing round ', step)
                trc = test_instance.next_batch()
                feed = {g['input_data']: trc[0], g['target']: trc[1]}
                accuracy_ = sess.run([g['accuracy']], feed_dict=feed)[0]
                accuracy += accuracy_

            te_losses.append(accuracy / step)
            step, accuracy = 0,0
            print("Accuracy after epoch", current_epoch, " - tr:", tr_losses[-1], "- te:", te_losses[-1])

    return tr_losses, te_losses

g = struct_network()
tr_losses, te_losses = train_network(g)
</code>```

答: You defined keep_prob as a tf.constant, but then trying to feed the value into it. Replace keep_prob = tf.constant(1.0) with keep_prob = tf.placeholder(tf.float32,[]) or keep_prob = tf.placeholder_with_default(1.0,[])

Body:
I'm trying to make speech recognition system with tensorflow.

Input data is an numpy array of size 50000 X 1.

Output data (mapping data) is an numpy array of size 400 X 1.

Input and mapping data is passed in batches of 2 in a list.

I've used this tutorial to design the neural network. Following is the code snippet:

For RNN:

input_data = tf.placeholder(tf.float32, [batch_size, sound_constants.MAX_ROW_SIZE_IN_DATA, sound_constants.MAX_COLUMN_SIZE_IN_DATA], name="train_input")
target = tf.placeholder(tf.float32, [batch_size, sound_constants.MAX_ROW_SIZE_IN_TXT, sound_constants.MAX_COLUMN_SIZE_IN_TXT], name="train_output")

fwd_cell = tf.nn.rnn_cell.BasicLSTMCell(num_hidden, state_is_tuple=True, forget_bias=1.0)

# creating one backward cell
bkwd_cell = tf.nn.rnn_cell.BasicLSTMCell(num_hidden, state_is_tuple=True, forget_bias=1.0)

# creating bidirectional RNN
val, _, _ = tf.nn.static_bidirectional_rnn(fwd_cell, bkwd_cell, tf.unstack(input_data), dtype=tf.float32)

For feeding data:

feed = {g['input_data'] : trb[0], g['target'] : trb[1], g['dropout'] : 0.6}
accuracy_, _ = sess.run([g['accuracy'], g['ts']], feed_dict=feed)
accuracy += accuracy_

When I ran the code, I got this error:

Traceback (most recent call last):
  File "/home/wolborg/PycharmProjects/speech-to-text-rnn/src/rnn_train_1.py", line 205, in <module>
    tr_losses, te_losses = train_network(g)
  File "/home/wolborg/PycharmProjects/speech-to-text-rnn/src/rnn_train_1.py", line 177, in train_network
    accuracy_, _ = sess.run([g['accuracy'], g['ts']], feed_dict=feed)
  File "/home/wolborg/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 895, in run
    run_metadata_ptr)
  File "/home/wolborg/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1102, in _run
    raise ValueError('Tensor %s may not be fed.' % subfeed_t)
ValueError: Tensor Tensor("Const:0", shape=(), dtype=float32) may not be fed.

Process finished with exit code 1

Earlier, I was facing this issue with tf.sparse_placeholder, then after some browsing, I changed input type to tf.placeholder and made related changes. Now I'm clueless on where I'm making the error.

Please suggest something as how should I feed data.

Entire code:

import tensorflow as tf

# for taking MFCC and label input
import numpy as np
import rnn_input_data_1
import sound_constants

# input constants

# Training Parameters
num_input = 10 # mfcc data input
training_data_size = 8 # determines number of files in training and testing module
testing_data_size = num_input - training_data_size

# Network Parameters
learning_rate = 0.0001 # for large training set, it can be set 0.001
num_hidden = 200 # number of hidden layers
num_classes = 28 # total alphabet classes (a-z) + extra symbols (', ' ')
epoch = 1 # number of iterations
batch_size = 2 # number of batches

mfcc_coeffs, text_data = rnn_input_data_1.mfcc_and_text_encoding()

class DataGenerator:
    def __init__(self, data_size):
    self.ptr = 0
    self.epochs = 0
    self.data_size = data_size

    def next_batch(self):
    self.ptr += batch_size
    if self.ptr > self.data_size:
        self.epochs += 1
        self.ptr = 0

    return mfcc_coeffs[self.ptr-batch_size : self.ptr], text_data[self.ptr-batch_size : self.ptr]

def reset_graph():
    if 'sess' in globals() and sess:
    sess.close()
    tf.reset_default_graph()

def struct_network():

    print ('Inside struct network !!')

    reset_graph()

    input_data = tf.placeholder(tf.float32, [batch_size, sound_constants.MAX_ROW_SIZE_IN_DATA, sound_constants.MAX_COLUMN_SIZE_IN_DATA], name="train_input")
    target = tf.placeholder(tf.float32, [batch_size, sound_constants.MAX_ROW_SIZE_IN_TXT, sound_constants.MAX_COLUMN_SIZE_IN_TXT], name="train_output")

    keep_prob = tf.constant(1.0)

    fwd_cell = tf.nn.rnn_cell.BasicLSTMCell(num_hidden, state_is_tuple=True, forget_bias=1.0)

    # creating one backward cell
    bkwd_cell = tf.nn.rnn_cell.BasicLSTMCell(num_hidden, state_is_tuple=True, forget_bias=1.0)

    # creating bidirectional RNN
    val, _, _ = tf.nn.static_bidirectional_rnn(fwd_cell, bkwd_cell, tf.unstack(input_data), dtype=tf.float32)

    # adding dropouts
    val = tf.nn.dropout(val, keep_prob)

    val = tf.transpose(val, [1, 0, 2])
    last = tf.gather(val, int(val.get_shape()[0]) - 1)

    # creating bidirectional RNN
    print ('BiRNN created !!')

    print ('Last Size: ', last.get_shape())

    weight = tf.Variable(tf.truncated_normal([num_hidden * 2, sound_constants.MAX_ROW_SIZE_IN_TXT]))
    bias = tf.Variable(tf.constant(0.1, shape=[sound_constants.MAX_ROW_SIZE_IN_TXT]))

    # mapping to 28 output classes
    logits = tf.matmul(last, weight) + bias
    prediction = tf.nn.softmax(logits)
    prediction = tf.reshape(prediction, shape = [batch_size, sound_constants.MAX_ROW_SIZE_IN_TXT, sound_constants.MAX_COLUMN_SIZE_IN_TXT])

    # getting probability distribution
    mat1 = tf.cast(tf.argmax(prediction,1),tf.float32)
    correct = tf.equal(prediction, target)
    accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))

    logits = tf.reshape(logits, shape=[batch_size, sound_constants.MAX_ROW_SIZE_IN_TXT, sound_constants.MAX_COLUMN_SIZE_IN_TXT])

    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=target))
    train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)

    # returning components as dictionary elements
    return {'input_data' : input_data,
        'target' : target,
        'dropout': keep_prob,
        'loss': loss,
        'ts': train_step,
        'preds': prediction,
        'accuracy': accuracy
        }

def train_network(graph):

    # initialize tensorflow session and all variables
    # tf_gpu_config = tf.ConfigProto(allow_soft_placement = True, log_device_placement = True)
    # tf_gpu_config.gpu_options.allow_growth = True

    # with tf.Session(config = tf_gpu_config) as sess:
    with tf.Session() as sess:

    train_instance = DataGenerator(training_data_size)
    test_instance = DataGenerator(testing_data_size)

    print ('Training data size: ', train_instance.data_size)
    print ('Testing data size: ', test_instance.data_size)

    sess.run(tf.global_variables_initializer())
    print ('Starting session...')
    step, accuracy = 0, 0
    tr_losses, te_losses = [], []
    current_epoch = 0
    while current_epoch < epoch:
        step += 1
        trb = train_instance.next_batch()

        feed = {g['input_data'] : trb[0], g['target'] : trb[1], g['dropout'] : 0.6}
        accuracy_, _ = sess.run([g['accuracy'], g['ts']], feed_dict=feed)
        accuracy += accuracy_

        if train_instance.epochs > current_epoch:
            current_epoch += 1
            tr_losses.append(accuracy / step)
            step, accuracy = 0, 0

            #eval test set
            te_epoch = test_instance.epochs
            while test_instance.epochs == te_epoch:
                step += 1
                print ('Testing round ', step)
                trc = test_instance.next_batch()
                feed = {g['input_data']: trc[0], g['target']: trc[1]}
                accuracy_ = sess.run([g['accuracy']], feed_dict=feed)[0]
                accuracy += accuracy_

            te_losses.append(accuracy / step)
            step, accuracy = 0,0
            print("Accuracy after epoch", current_epoch, " - tr:", tr_losses[-1], "- te:", te_losses[-1])

    return tr_losses, te_losses

g = struct_network()
tr_losses, te_losses = train_network(g)


问:
Garble JavaScript code before sending to client-side
How can I garble JavaScript code before sending it to client-side? I don't want to expose functionalities. The code is already compressed using jsmin.

答:
Javascript is interpreted plaintext.  As such any obfuscation is a placebo at best and easily reversed.

More to the point, if you're writing enough Javascript to constitute a work valuable enough to protect, you're doing something wrong.

My Javascript these days consists of including jQuery, a handful of plug-ins and some code to activate those plug-ins and do some styling.

I have a hard time envisioning writing anything in Javascript significant enough that I'd care about protecting it, which is just as well because you can't protect it.  Not really.

OwnerDisplayName: Rakesh

OwnerDisplayName: cletus


问:
AndroidStudio 3.0: Java 8 stream not compile (Call requires API level 24)
Java 8, and I install new Android Studio 3.0.

Add code:

```<code> List<String> myList =   Arrays.asList("a1", "a2", "b1", "c2", "c1");

        myList
                .stream()
                .filter(s -> s.startsWith("c"))
                .map(String::toUpperCase)
                .sorted()
                .forEach(System.out::println);
</code>```

But I get compile error:

```<code>Call requires API level 24 (current min is 15) java.util.stream.Collection
</code>```

答:
While there is a bunch of Java 1.8 support in Android Studio 3.0 (lambdas, method references, default interface methods), not all of 1.8 is supported for all Android APIs.  In particular, java.util.stream is not supported until API 24.

See the developer docs: https://developer.android.com/studio/write/java8-support.html#supported_features

A good library to get backported Java 1.8 libraries such as java.util.stream is StreamSupport: https://github.com/streamsupport/streamsupport

Body:
Java 8, and I install new Android Studio 3.0.

Add code:

 List<String> myList =   Arrays.asList("a1", "a2", "b1", "c2", "c1");

        myList
                .stream()
                .filter(s -> s.startsWith("c"))
                .map(String::toUpperCase)
                .sorted()
                .forEach(System.out::println);

But I get compile error:

Call requires API level 24 (current min is 15) java.util.stream.Collection


问:
CICD using VSTS
With CICD done, On every commit VSTS creates the build and deploys it to the target environment successfully.

I want to understand how the build is done, is it incremental OR full build every time I commit the change in the .net project.

If anytime I want to rollback, to the previous working build does VSTS does it or I need to configure or follow some procedures to do it hassle free ?

答:
If you are using Hosted agent, it is full build every time. (Need to download source, build whole projects)

If you are using private build agent and do not clear anything (e.g. In Get sources, clean is false; Visual Studio Build task, clean option unchecked), part of build will be up to date if source not be changed. (can just download the updated files and skip some build targets if build results are up to date)

The VSTS can’t rollback the build, you can roll back changes, then rebuild and redeploy. There is a blog about rollback: Implement Rollback with Release Management.

Title: CICD using VSTS


问:
Scala, Spark, Geotrellis Rdd CRS reprojection
I load a set of point from a CSV file to a RDD:

```<code>case class yieldrow(Elevation:Double,DryYield:Double)

val points :RDD[PointFeature[yieldrow]] = lines.map { line =>
  val fields = line.split(",")
  val point = Point(fields(1).toDouble,fields(0).toDouble)
  Feature(point, yieldrow(fields(4).toDouble,fields(20)))
}
</code>```

Then get:

```<code>points: org.apache.spark.rdd.RDD[geotrellis.vector.PointFeature[yieldrow]]
</code>```

Now need to reproject from EPSG:4326 to  EPSG:3270

So I create the CRS from and to:

```<code>val crsFrom : geotrellis.proj4.CRS =  geotrellis.proj4.CRS.fromName("EPSG:4326")
val crsTo : geotrellis.proj4.CRS =  geotrellis.proj4.CRS.fromEpsgCode(32720)
</code>```

But I can not create the transform and also i don not know:

Hot to apply a transform to a single point:

```<code>val pt = Point( -64.9772376007928, -33.6408083223936)
</code>```

How to use the mapGeom method of Feature to make a CRS transformation ?

```<code>points.map(_.mapGeom(?????))
points.map(feature => feature.mapGeom(????))
</code>```

How to use ReprojectPointFeature(pointfeature) ?

The documentation not have basic code samples.

Any help will be appreciate

答:
I'll start from the last question:

Indeed to perform a reproject on a PointFeature you can use ReprojectPointFeature implict case class. To use it just be sure that you have import geotrellis.vector._ in reproject function call scope.

```<code>import geotrellis.vector._
points.map(_.reproject(crsFrom, crsTo))
</code>```

The same import works for a Point too:

```<code>import geotrellis.vector._
pt.reproject(crsFrom, crsTo)
points.map(_.mapGeom(_.reproject(crsFrom, crsTo)))
</code>```

Body:
I load a set of point from a CSV file to a RDD:

case class yieldrow(Elevation:Double,DryYield:Double)

val points :RDD[PointFeature[yieldrow]] = lines.map { line =>
  val fields = line.split(",")
  val point = Point(fields(1).toDouble,fields(0).toDouble)
  Feature(point, yieldrow(fields(4).toDouble,fields(20)))
}

Then get:

points: org.apache.spark.rdd.RDD[geotrellis.vector.PointFeature[yieldrow]]

Now need to reproject from EPSG:4326 to  EPSG:3270

So I create the CRS from and to:

val crsFrom : geotrellis.proj4.CRS =  geotrellis.proj4.CRS.fromName("EPSG:4326")
val crsTo : geotrellis.proj4.CRS =  geotrellis.proj4.CRS.fromEpsgCode(32720)

But I can not create the transform and also i don not know:

Hot to apply a transform to a single point:

val pt = Point( -64.9772376007928, -33.6408083223936)

How to use the mapGeom method of Feature to make a CRS transformation ?

points.map(_.mapGeom(?????))
points.map(feature => feature.mapGeom(????))

How to use ReprojectPointFeature(pointfeature) ?

The documentation not have basic code samples.

Any help will be appreciate

Body:
I'll start from the last question:

Indeed to perform a reproject on a PointFeature you can use ReprojectPointFeature implict case class. To use it just be sure that you have import geotrellis.vector._ in reproject function call scope.

import geotrellis.vector._
points.map(_.reproject(crsFrom, crsTo))

The same import works for a Point too:

import geotrellis.vector._
pt.reproject(crsFrom, crsTo)
points.map(_.mapGeom(_.reproject(crsFrom, crsTo)))


问:
How to run all .go files within current directory through the command line (multi file package)
I'm a newcomer to Go. I extremely like the language, but I quickly realised that I needed to start dividing my files due to an increase in program size.

go run main.go (with main.go having been the file with my main() function)

didn't work and I hit a barrier for a while, because I had no clue how to get my program working.

Some quick searching lead me to the answer of

go run main.go other.go ..

where by typing all the files that my package main consists of, I could get the programming running. However, this is utterly cumbersome and frustrating to do each time.

I write the following self-answered question in order to prevent others like myself who may again hit this barrier.

答:
just use this

```<code>go run *.go
</code>```

it will work assuming u don't have any test files

Body:
just use this

go run *.go

it will work assuming u don't have any test files


问:
ERangeError on Delphi XE
I'm migrating a software from Delphi 5 to Delphi XE.
I've already corrected a lot of differences, and i can now compile my code.

The problem happening is that sometimes (in some places of the code), I'm getting the error "Range Check Error".

For exemple, in this code:

```<code>function CopyChar(Ori : string; var Des : Array of char) : Boolean;
var Msg     : string;
    Counter : integer;
    SizeDes : integer;
begin
    SizeDes:= SizeOf(Des);
    for Counter:= 1 to SizeDes do begin
        Des[Counter-1]:= ' ';
    end;
    Ori:= Trim(Ori);
    Msg:= '';
    SizeDes:= Min(Length(Ori),SizeDes);
    for Counter:= 1 to SizeDes do begin
        Des[Counter-1]:= char(Ori[Counter]);
    end;
    CopyChar:= True;
end;
</code>```

I get the error at runtime when passing by the line Des[Counter-1] := ' ';
The error occurr not at the first time it passes through the loop, but after lot of times.

I've tried to disable Rance Checking ($R) but it does nos solves my problem.
I've also tried to change the type of "Counter" to Cardinal and LongWord, with no success

I would be glad for any helpful idea!

Thanks.

答:
The code should read something like this:

```<code>function CopyChar(Ori : string; var Des : Array of char) : Boolean;
var Msg     : string;
    Counter : integer;
    LenDes  : integer;
begin
    LenDes:= Length(Des);
    for Counter:= 1 to LenDes do begin
        Des[Counter-1]:= ' ';
    end;
    Ori:= Trim(Ori);
    Msg:= '';
    LenDes:= Min(Length(Ori),LenDes);
    for Counter:= 1 to LenDes do begin
        Des[Counter-1]:= char(Ori[Counter]);
    end;
    CopyChar:= True;
end;
</code>```

I guess your problem is to do with Char now being 2 bytes wide (in Delphi 5 it was 1 byte wide) although I have never used SizeOf on an open array and don't even know what it does!

There are a couple of other issues with this code.  The return value seems a little pointless since it can only ever return True.  It could also be somewhat compressed like so:

```<code>procedure CopyChar(Ori: string; var Des: array of char);
var
  i: Integer;
begin
  Ori := Trim(Ori);
  for i := 1 to Length(Des) do begin
    if i<=Length(Ori) then
      Des[i-1] := Ori[i];
    else
      Des[i-1] := ' ';
  end;
end;
</code>```

Title: ERangeError on Delphi XE

Body:
I'm migrating a software from Delphi 5 to Delphi XE.
I've already corrected a lot of differences, and i can now compile my code.

The problem happening is that sometimes (in some places of the code), I'm getting the error "Range Check Error".

For exemple, in this code:

function CopyChar(Ori : string; var Des : Array of char) : Boolean;
var Msg     : string;
    Counter : integer;
    SizeDes : integer;
begin
    SizeDes:= SizeOf(Des);
    for Counter:= 1 to SizeDes do begin
        Des[Counter-1]:= ' ';
    end;
    Ori:= Trim(Ori);
    Msg:= '';
    SizeDes:= Min(Length(Ori),SizeDes);
    for Counter:= 1 to SizeDes do begin
        Des[Counter-1]:= char(Ori[Counter]);
    end;
    CopyChar:= True;
end;

I get the error at runtime when passing by the line Des[Counter-1] := ' ';
The error occurr not at the first time it passes through the loop, but after lot of times.

I've tried to disable Rance Checking ($R) but it does nos solves my problem.
I've also tried to change the type of "Counter" to Cardinal and LongWord, with no success

I would be glad for any helpful idea!

Thanks.

Body:
The code should read something like this:

function CopyChar(Ori : string; var Des : Array of char) : Boolean;
var Msg     : string;
    Counter : integer;
    LenDes  : integer;
begin
    LenDes:= Length(Des);
    for Counter:= 1 to LenDes do begin
        Des[Counter-1]:= ' ';
    end;
    Ori:= Trim(Ori);
    Msg:= '';
    LenDes:= Min(Length(Ori),LenDes);
    for Counter:= 1 to LenDes do begin
        Des[Counter-1]:= char(Ori[Counter]);
    end;
    CopyChar:= True;
end;

I guess your problem is to do with Char now being 2 bytes wide (in Delphi 5 it was 1 byte wide) although I have never used SizeOf on an open array and don't even know what it does!

There are a couple of other issues with this code.  The return value seems a little pointless since it can only ever return True.  It could also be somewhat compressed like so:

procedure CopyChar(Ori: string; var Des: array of char);
var
  i: Integer;
begin
  Ori := Trim(Ori);
  for i := 1 to Length(Des) do begin
    if i<=Length(Ori) then
      Des[i-1] := Ori[i];
    else
      Des[i-1] := ' ';
  end;
end;


问:
Angular filter with multiple dropdown
I am trying to filter with multiple dropdowns.
For example, when narrowing down by two numbers of value and num, there is no corresponding data when searching with "value = 1, num = 5", but data of "id = '000'" is displayed It will result.
Where should I fix it?

plunker:http://plnkr.co/edit/IBRDuHYtSCUFV1xNxjh4?p=preview

HTML

```<code><body ng-controller="MainCtrl">
<div>
    <div>
        <div>
            <span>value</span>
            <select class="form-control" ng-model="value_1">
                <option ng-repeat="value in product_value" value="{{value}}">{{value}}</option>
            </select>
            <span>num</span>
            <select class="form-control" ng-model="num_1">
                <option ng-repeat="num in product_num" value="{{num}}">{{num}}</option>
            </select>
        </div>
        <div>
            <span>value</span>
            <select class="form-control" ng-model="value_2">
                <option ng-repeat="value in product_value" value="{{value}}">{{value}}</option>
            </select>
            <span>num</span>
            <select class="form-control" ng-model="num_2">
                <option ng-repeat="num in product_num" value="{{num}}">{{num}}</option>
            </select>
        </div>
    </div>
      <table>
        <tr>
          <th>
            id
          </th>
          <th>
            name
          </th>
        </tr>
        <tr ng-repeat="products in products | filter:{main:{value:value_1}} | filter:{main:{num:num_1}} |
         filter:{main:{value:value_2}} | filter:{main:{num:num_2}}">
          <td>{{products.id}}</td>
          <td>{{products.name}}</td>
        </tr>
      </table>
</div>
</code>```

JS

```<code>var app = angular.module('TestMode', []);

app.controller('MainCtrl', function($scope, $filter) {
  $scope.product_value = ["1", "2", "3", "4", "5"];
  $scope.product_num = ["1", "2", "3", "4", "5"];
  $scope.products = [
      {
        id: "000",
        name:'A',
        main:[
            {
              value: "1",
              num: "1"
            },{
              value: "1",
              num: "2"
            },{
              value: "1",
              num: "3"
            },{
              value: "2",
              num: "4"
            },{
              value: "2",
              num: "5"
            }
        ]
      },{
        id: "001",
        name:'B',
        main:[
            {
              value: "5",
              num: "5"
            },{
              value: "5",
              num: "4"
            },{
              value: "5",
              num: "3"
            },{
              value: "4",
              num: "2"
            },{
              value: "4",
              num: "1"
            }
        ]
      }
    ];

});
</code>```

答:
Use this below code instead of yours.

```<code> ng-repeat="products in products | filter:{main:{value:value_1,num:num_1}} |
 filter:{main:{value:value_2,num:num_2}}"
</code>```

Working demo : http://plnkr.co/edit/K5Xq3QOo1Kfs5Lw5yiAJ?p=preview

Title: Angular filter with multiple dropdown

Body:
I am trying to filter with multiple dropdowns.
For example, when narrowing down by two numbers of value and num, there is no corresponding data when searching with "value = 1, num = 5", but data of "id = '000'" is displayed It will result.
Where should I fix it?

plunker:http://plnkr.co/edit/IBRDuHYtSCUFV1xNxjh4?p=preview

HTML

            value
            <select class="form-control" ng-model="value_1">
                <option ng-repeat="value in product_value" value="{{value}}">{{value}}</option>
            </select>
            num
            <select class="form-control" ng-model="num_1">
                <option ng-repeat="num in product_num" value="{{num}}">{{num}}</option>
            </select>

            value
            <select class="form-control" ng-model="value_2">
                <option ng-repeat="value in product_value" value="{{value}}">{{value}}</option>
            </select>
            num
            <select class="form-control" ng-model="num_2">
                <option ng-repeat="num in product_num" value="{{num}}">{{num}}</option>
            </select>

            id

            name

          {{products.id}}
          {{products.name}}

JS

var app = angular.module('TestMode', []);

app.controller('MainCtrl', function($scope, $filter) {
  $scope.product_value = ["1", "2", "3", "4", "5"];
  $scope.product_num = ["1", "2", "3", "4", "5"];
  $scope.products = [
      {
        id: "000",
        name:'A',
        main:[
            {
              value: "1",
              num: "1"
            },{
              value: "1",
              num: "2"
            },{
              value: "1",
              num: "3"
            },{
              value: "2",
              num: "4"
            },{
              value: "2",
              num: "5"
            }
        ]
      },{
        id: "001",
        name:'B',
        main:[
            {
              value: "5",
              num: "5"
            },{
              value: "5",
              num: "4"
            },{
              value: "5",
              num: "3"
            },{
              value: "4",
              num: "2"
            },{
              value: "4",
              num: "1"
            }
        ]
      }
    ];

});

Body:
Use this below code instead of yours.

 ng-repeat="products in products | filter:{main:{value:value_1,num:num_1}} |
 filter:{main:{value:value_2,num:num_2}}"

Working demo : http://plnkr.co/edit/K5Xq3QOo1Kfs5Lw5yiAJ?p=preview