问:
Update Mysql Records Onclick Bootrstrap Checkbox Toggle
I want to edit status field for selected column onclick of bootstrap checkbox toggle.....Please Help
Example :
1. if status is active then when user click then it should be update in database as inactive and reload page.
2. if status is inactive then when user click then it should be update in database as active and reload page.

Fetch Database

```<code><?php

require_once 'db_config.php';

$output = array('data' => array());

// do not fetch status 3 because it is deleted
$sql = "SELECT *,emailnotificationstable.id as sid FROM notificationslist";
$query = $connect->query($sql);

$num_rows = mysqli_num_rows($query);

$x = $num_rows;
while ($row = $query->fetch_assoc()) {
    // activate button
    $activateButton = '';
    if ($row['status'] == 1) {
            $activateButton =
            '<input type="checkbox" id="toggleBtn" name="toggleBtn" checked data-toggle="toggle" data-on="Active" data-off="Inactive" data-onstyle="success" data-offstyle="danger" data-size="mini" value="'.$row['sid'].'" onclick="editMember()">';
    } elseif ($row['status'] == 2) {
            $activateButton =
            '<input type="checkbox" id="toggleBtn" name="toggleBtn" data-toggle="toggle" data-on="Active" data-off="Inactive" data-onstyle="success" data-offstyle="danger" data-size="mini" value="'.$row['sid'].'" onclick="editMember()">';
    }

    // extra code here

    $output['data'][] = array(
        $x,
        $activateButton,
        $row['date'],
        $row['notificationname'],
        $row['employeename'],
        $createdby,
        $editedby,
        $editeddate,
        $deleteButton,

    );

    $x--;
}

// database connection close
$connect->close();

echo json_encode($output);
</code>```

Jquery

```<code>// global the manage memeber table
var mytable;

$(document).ready(function() {
    mytable = $("#mytable").DataTable({
        "ajax": "../pages/php_action/salesexe/retriveemailnotifications.php",
        "order": [],
"fnDrawCallback": function() {
    jQuery('#mytable #adBtn').bootstrapToggle();
}
        });

});

function editMember(sid = null) {
    if(sid) {

    // remove the error
    $(".form-group").removeClass('has-error').removeClass('has-success');
    $(".text-danger").remove();
    // empty the message div
    $(".edit-messages").html("");

    // remove the id
    $("#membersid").remove();
    // click on toggle button
    $("#adBtn").click(function() {

        $.ajax({
            url: 'notifstatus.php',
            type: 'post',
            data: {membersid : sid},
            dataType: 'json',
            success:function(response) {

                if(response.success == true) {
                    $(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
                          '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
                          '<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
                        '</div>');
                    // refresh the table
                    mytable.ajax.reload(null, false);

                } else {
                    $(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
                          '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
                          '<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
                        '</div>');
                }
            }
        });
    }); // click toggle btn
} else {
    alert('Error: Refresh the page again');
}
}
</code>```

Update

```<code><?php

require_once 'db_config.php';

$output = array('success' => false, 'messages' => array());

$membersId = $_POST['membersid'];

// update record to inactive
$sql = "UPDATE notificationslist SET notfistatus = '2' WHERE id = $membersId";

$query = $connect->query($sql);

if($query === TRUE) {
    $output['success'] = true;
    $output['messages'] = 'Notification trigger successfullt activated for selected user';
} else {
    $output['success'] = false;
    $output['messages'] = 'Error while activating notification trigger for selected user,';
}
// close database connection
$connect->close();

echo json_encode($output);
</code>```

答:
You're thinking way to complex with reloading a page, not using the API as you should. You only want to fetch the status and update the needed parts this means you need a proper way to identify a row in your table. Also an html id must be unique in a page better remove that.

You have a couple of options:

use datatables ajax requests so it can handle multiple edits on different cols.

toggle the button on and off using jquery and bootstrap.

Shown below is the latter:

```<code>$(function() {
  // hooking event only on buttons, can do tr's as well.
  $('.toggleBtn').click(function(){
    $.ajax({
      url: 'notifstatus.php',
      type: 'post',
      data: {
        id : $(this).val(),
        status: $(this).prop('checked')
      },
      dataType: 'json',
      success: function(response){
        if(response.success){
          $(this).bootstrapToggle('enable');
          console.log(response.message);
        } else {
          $(this).bootstrapToggle('disable');
          BootstrapDialog.show({
            title: 'failed to update status',
            message: response.status + response.messages
          });
        }
      },
      error: function(xhr, textStatus, errorThrown) {
        BootstrapDialog.show({
          title: textStatus,
          message: errorThrown
        });
      }
    });
  });
});
</code>```

Now the only response to build is the following:

```<code><?php

  require_once 'db_config.php';

  if(isset($_POST['status']) && $_POST['status']){
    // user requests to turn off
    $sql = "UPDATE notificationslist SET notfistatus = '2' WHERE id = ?"; // SQL injection, use prepared statements. fix it.
  } else {
    // user requests to turn on, other query.
  }

  $success;
  $status = 0;
  $message = 'Error while activating notification trigger for selected user,';

  if($query = $connect->query($sql)){
    if($row = $query->fetch_assoc()){
      $success = true;
      $message = 'Notification trigger successfully activated for selected user';
      $status = $row['status'];
    }
  }

  die(json_encode([
    'success'  => $success,
    'messages' => $message,
    'status'   => $status
  ]));
?>
</code>```

Should do the trick, no need to request all data to update a single value.

Body:
I want to edit status field for selected column onclick of bootstrap checkbox toggle.....Please Help
Example :
1. if status is active then when user click then it should be update in database as inactive and reload page.
2. if status is inactive then when user click then it should be update in database as active and reload page.

Fetch Database

<?php

require_once 'db_config.php';

$output = array('data' => array());

// do not fetch status 3 because it is deleted
$sql = "SELECT *,emailnotificationstable.id as sid FROM notificationslist";
$query = $connect->query($sql);

$num_rows = mysqli_num_rows($query);

$x = $num_rows;
while ($row = $query->fetch_assoc()) {
    // activate button
    $activateButton = '';
    if ($row['status'] == 1) {
            $activateButton =
            '<input type="checkbox" id="toggleBtn" name="toggleBtn" checked data-toggle="toggle" data-on="Active" data-off="Inactive" data-onstyle="success" data-offstyle="danger" data-size="mini" value="'.$row['sid'].'" onclick="editMember()">';
    } elseif ($row['status'] == 2) {
            $activateButton =
            '<input type="checkbox" id="toggleBtn" name="toggleBtn" data-toggle="toggle" data-on="Active" data-off="Inactive" data-onstyle="success" data-offstyle="danger" data-size="mini" value="'.$row['sid'].'" onclick="editMember()">';
    }

    // extra code here

    $output['data'][] = array(
        $x,
        $activateButton,
        $row['date'],
        $row['notificationname'],
        $row['employeename'],
        $createdby,
        $editedby,
        $editeddate,
        $deleteButton,

    );

    $x--;
}

// database connection close
$connect->close();

echo json_encode($output);

Jquery

// global the manage memeber table
var mytable;

$(document).ready(function() {
    mytable = $("#mytable").DataTable({
        "ajax": "../pages/php_action/salesexe/retriveemailnotifications.php",
        "order": [],
"fnDrawCallback": function() {
    jQuery('#mytable #adBtn').bootstrapToggle();
}
        });

});

function editMember(sid = null) {
    if(sid) {

    // remove the error
    $(".form-group").removeClass('has-error').removeClass('has-success');
    $(".text-danger").remove();
    // empty the message div
    $(".edit-messages").html("");

    // remove the id
    $("#membersid").remove();
    // click on toggle button
    $("#adBtn").click(function() {

        $.ajax({
            url: 'notifstatus.php',
            type: 'post',
            data: {membersid : sid},
            dataType: 'json',
            success:function(response) {

                if(response.success == true) {
                    $(".removeMessages").html('
'+
                          '<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>'+
                          '  '+response.messages+
                        '
');
                    // refresh the table
                    mytable.ajax.reload(null, false);

                } else {
                    $(".removeMessages").html('
'+
                          '<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>'+
                          '  '+response.messages+
                        '
');
                }
            }
        });
    }); // click toggle btn
} else {
    alert('Error: Refresh the page again');
}
}

Update

<?php

require_once 'db_config.php';

$output = array('success' => false, 'messages' => array());

$membersId = $_POST['membersid'];

// update record to inactive
$sql = "UPDATE notificationslist SET notfistatus = '2' WHERE id = $membersId";

$query = $connect->query($sql);

if($query === TRUE) {
    $output['success'] = true;
    $output['messages'] = 'Notification trigger successfullt activated for selected user';
} else {
    $output['success'] = false;
    $output['messages'] = 'Error while activating notification trigger for selected user,';
}
// close database connection
$connect->close();

echo json_encode($output);

Body:
You're thinking way to complex with reloading a page, not using the API as you should. You only want to fetch the status and update the needed parts this means you need a proper way to identify a row in your table. Also an html id must be unique in a page better remove that.

You have a couple of options:

use datatables ajax requests so it can handle multiple edits on different cols.

toggle the button on and off using jquery and bootstrap.

Shown below is the latter:

$(function() {
  // hooking event only on buttons, can do tr's as well.
  $('.toggleBtn').click(function(){
    $.ajax({
      url: 'notifstatus.php',
      type: 'post',
      data: {
        id : $(this).val(),
        status: $(this).prop('checked')
      },
      dataType: 'json',
      success: function(response){
        if(response.success){
          $(this).bootstrapToggle('enable');
          console.log(response.message);
        } else {
          $(this).bootstrapToggle('disable');
          BootstrapDialog.show({
            title: 'failed to update status',
            message: response.status + response.messages
          });
        }
      },
      error: function(xhr, textStatus, errorThrown) {
        BootstrapDialog.show({
          title: textStatus,
          message: errorThrown
        });
      }
    });
  });
});

Now the only response to build is the following:

<?php

  require_once 'db_config.php';

  if(isset($_POST['status']) && $_POST['status']){
    // user requests to turn off
    $sql = "UPDATE notificationslist SET notfistatus = '2' WHERE id = ?"; // SQL injection, use prepared statements. fix it.
  } else {
    // user requests to turn on, other query.
  }

  $success;
  $status = 0;
  $message = 'Error while activating notification trigger for selected user,';

  if($query = $connect->query($sql)){
    if($row = $query->fetch_assoc()){
      $success = true;
      $message = 'Notification trigger successfully activated for selected user';
      $status = $row['status'];
    }
  }

  die(json_encode([
    'success'  => $success,
    'messages' => $message,
    'status'   => $status
  ]));
?>

Should do the trick, no need to request all data to update a single value.


来源: stackexchange

问:
Set iOS Application to be a default browser
I am wondering if there is any way to make my iOS application show up as a default browser like google or safari. Thanks!</p>

答:
If you jailbreak, apparently you can.

If you want your app to be found in the app store, nope.

You can't set your app as the default browser programmatically (as that would be a security risk; imagine a malicious app changing settings to spoof as a browser to collect passwords or bank info).

And the ways you can typically get your app to be more accessible is to use extensions and the system "Share" sheet.

Here's an article that talks about all these techniques.

ContentLicense: CC BY-SA 3.0


问:
Add column to laravel user model and keep the auth register behavior
As many know, Laravel automatically creates the User model when you create a project. I then created an auth interface php artisan make:auth. The auto generated register method was working normaly. I then added a not null column to the migration for the user table. Now it isn't working anymore. I don't know where exactly the insert happens when laravel creates this auth scaffolding. I tried editing the create method in RegisterController but it didn't worked.

```<code>class RegisterController extends Controller
{

protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'tipo' => $data['tipo'], // name of the new column I added
            'password' => bcrypt($data['password']),
        ]);
    }
}
</code>```

On the register <form> I added the input field tipo. The generated code includes:

```<code><form class="form-horizontal" method="POST" action="{{ route('register') }}">

<input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>

<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required>

<select id="tipo" class="form-control" name="tipo" value="{{ old('tipo') }}" required>
                                <option value="1">Gerente</option>
                                <option value="2">Caixa</option>
                                <option value="3">Garçom</option>
</select>

<input id="password" type="password" class="form-control" name="password" required>

<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>

<button type="submit" class="btn btn-primary">
                                Registrar
</button>
</code>```

In the User class model, I added the new column to the fillable:

```<code>/protected $fillable = [
    'name', 'email', 'password', 'tipo',
];
</code>```

On the routes, web.php only Auth::routes();. If I run php artisan route:list it shows me that for the POST method the uri register leads to RegisterController@register but on the RegisterController it has only the create method I posted and validator method. So, where the registration is actually happening? In terms of laravel, where it runs the $user->save() method?

Edit: All I want to do is modify it so it include the new <input> for the new column

Edit 2: I found out that actually the code is not reaching the create method because I added  dd($data) before the return and still the same behavior, then I added some forced syntax error and also the same thing happened.

答:
Firstly, Add the recently added column to $fillable array in the app\User.php file. </p>

```<code><?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */protected $fillable = [
        'name', 'email', 'password', 'tipo'
    ];
</code>```

Body:
As many know, Laravel automatically creates the User model when you create a project. I then created an auth interface php artisan make:auth. The auto generated register method was working normaly. I then added a not null column to the migration for the user table. Now it isn't working anymore. I don't know where exactly the insert happens when laravel creates this auth scaffolding. I tried editing the create method in RegisterController but it didn't worked.

class RegisterController extends Controller
{

protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'tipo' => $data['tipo'], // name of the new column I added
            'password' => bcrypt($data['password']),
        ]);
    }
}

On the register <form> I added the input field tipo. The generated code includes:

<form class="form-horizontal" method="POST" action="{{ route('register') }}">

<input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>

<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required>

<select id="tipo" class="form-control" name="tipo" value="{{ old('tipo') }}" required>
                                <option value="1">Gerente</option>
                                <option value="2">Caixa</option>
                                <option value="3">Garçom</option>
</select>

<input id="password" type="password" class="form-control" name="password" required>

<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>

<button type="submit" class="btn btn-primary">
                                Registrar
</button>

In the User class model, I added the new column to the fillable:

/protected $fillable = [
    'name', 'email', 'password', 'tipo',
];

On the routes, web.php only Auth::routes();. If I run php artisan route:list it shows me that for the POST method the uri register leads to RegisterController@register but on the RegisterController it has only the create method I posted and validator method. So, where the registration is actually happening? In terms of laravel, where it runs the $user->save() method?

Edit: All I want to do is modify it so it include the new <input> for the new column

Edit 2: I found out that actually the code is not reaching the create method because I added  dd($data) before the return and still the same behavior, then I added some forced syntax error and also the same thing happened.

Body:
Firstly, Add the recently added column to $fillable array in the app\User.php file.

<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */protected $fillable = [
        'name', 'email', 'password', 'tipo'
    ];


问:
Is there any limit on how much text asp:label control can hold?
Should I use it if I wanna store really long text?</p>

答:
I would use <asp:literal enableviewstate='false' ... as it is apparently more lightweight than a <asp:label ...

A Literal control is much more light
  weight than a Label.. it's meant to
  write out text/html directly to the
  browser.  A Label is little bulkier
  than a Literal, but has all benefits
  of a WebControl such as styling
  options etc.

It should also be noted that a label will wrap your content with  ...  whereas  a literal does not.

ContentLicense: CC BY-SA 2.5

Body:
I would use <asp:literal enableviewstate='false' ... as it is apparently more lightweight than a <asp:label ...

A Literal control is much more light
  weight than a Label.. it's meant to
  write out text/html directly to the
  browser.  A Label is little bulkier
  than a Literal, but has all benefits
  of a WebControl such as styling
  options etc.

It should also be noted that a label will wrap your content with <span> ... </span> whereas  a literal does not.


问:
Manifest Merger failed with multiple errors in Android Studio
So, I am a beginner into Android and Java. I just began learning. While I was experimenting with Intent today, I incurred an error.

```<code>Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs
</code>```

I found some solutions here and tried to implement them, but it did not work.

This is my build.gradle :

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.0"

defaultConfig {
    applicationId "com.example.rohan.petadoptionthing"
    minSdkVersion 10
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.0'
}
</code>```

This is my AndroidManifest :

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code>package="com.example.rohan.petadoptionthing" >

<application

    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".Second"
        />

    <activity android:name=".third"/>
    <activity android:name=".MainActivity"/>

</application>
</code>```

This is my first week with coding, I am sorry if this is a really silly thing. I am really new to this and did not find any other place to ask. Sorry if I broke any rules

答:
Happened with me twice when I refractor (Rename with SHIFT + F6) the name of a field in our files and it asks you to change it everywhere and we without paying attention change the name everywhere.
For example, if you have a variable name "id" in your Java class and you rename it with SHIFT + F6. If you don't pay attention to the next dialog which will ask you wherever else it is going to change the id and you tick check all it will change all the id in your layout files from the new value.</p>

Body:
So, I am a beginner into Android and Java. I just began learning. While I was experimenting with Intent today, I incurred an error.

Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs

I found some solutions here and tried to implement them, but it did not work.

This is my build.gradle :

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.0"

defaultConfig {
    applicationId "com.example.rohan.petadoptionthing"
    minSdkVersion 10
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.0'
}

This is my AndroidManifest :

<?xml version="1.0" encoding="utf-8"?>

package="com.example.rohan.petadoptionthing" >

<application

    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".Second"
        />

    <activity android:name=".third"/>
    <activity android:name=".MainActivity"/>

</application>

This is my first week with coding, I am sorry if this is a really silly thing. I am really new to this and did not find any other place to ask. Sorry if I broke any rules


问:
I am trying to share a project in github using IntelliJ IDEA but i gives a following error

when i click Review it gives following warning message.

My project is not update in github. How to solve that problem

答: Those warnings are nothing more than warnings. You can just click "commit" and continue as normal. They mean you haven't documented your code. See here: How do I fix or correct the "Default File Template" warning in IntelliJ Idea</p>


问:
Running a batch file in relative path?
There is a batch file which I want to run it when I press the button.
My code works fine when I use absolute (full) path. But using relative path causes to occur an exception.
This is my code:

```<code>private void button1_Click(object sender, EventArgs e)
{
    //x64
    System.Diagnostics.Process batchFile_1 = new System.Diagnostics.Process();
    batchFile_1.StartInfo.FileName = @"..\myBatchFiles\BAT1\f1.bat";
    batchFile_1.StartInfo.WorkingDirectory = @".\myBatchFiles\BAT1";
    batchFile_1.Start();
}
</code>```

and the raised exception:

The system cannot find the file specified.

The directory of the batch file is:

```<code>C:\Users\GntS\myProject\bin\x64\Release\myBatchFiles\BAT1\f1.bat
</code>```

The output .exe file is located in:

```<code>C:\Users\GntS\myProject\bin\x64\Release
</code>```

I searched and none of the results helped me. What is the correct way to run a batch file in relative path?!

答:
According to JeffRSon`s answer and comments by MaciejLos and KevinGosse my problem was solved as below:

```<code>string executingAppPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

 batchFile_1.StartInfo.FileName = executingAppPath.Substring(0, executingAppPath.LastIndexOf('\\')) + "\\myBatchFiles\\BAT1\\f1.bat";
 batchFile_1.StartInfo.WorkingDirectory = executingAppPath.Substring(0, executingAppPath.LastIndexOf('\\')) + "\\myBatchFiles\\BAT1";
</code>```

An alternative way is:

```<code>string executingAppPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
batchFile_1.StartInfo.FileName = executingAppPath.Substring(6) + "\\myBatchFiles\\BAT1\\f1.bat";
batchFile_1.StartInfo.WorkingDirectory = executingAppPath.Substring(6) + "\\myBatchFiles\\BAT1";
</code>```

I report it here hoping help somebody.

Title: Running a batch file in relative path?

Body:
There is a batch file which I want to run it when I press the button.
My code works fine when I use absolute (full) path. But using relative path causes to occur an exception.
This is my code:

private void button1_Click(object sender, EventArgs e)
{
    //x64
    System.Diagnostics.Process batchFile_1 = new System.Diagnostics.Process();
    batchFile_1.StartInfo.FileName = @"..\myBatchFiles\BAT1\f1.bat";
    batchFile_1.StartInfo.WorkingDirectory = @".\myBatchFiles\BAT1";
    batchFile_1.Start();
}

and the raised exception:

The system cannot find the file specified.

The directory of the batch file is:

C:\Users\GntS\myProject\bin\x64\Release\myBatchFiles\BAT1\f1.bat

The output .exe file is located in:

C:\Users\GntS\myProject\bin\x64\Release

I searched and none of the results helped me. What is the correct way to run a batch file in relative path?!

Body:
According to JeffRSon`s answer and comments by MaciejLos and KevinGosse my problem was solved as below:

string executingAppPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

 batchFile_1.StartInfo.FileName = executingAppPath.Substring(0, executingAppPath.LastIndexOf('\\')) + "\\myBatchFiles\\BAT1\\f1.bat";
 batchFile_1.StartInfo.WorkingDirectory = executingAppPath.Substring(0, executingAppPath.LastIndexOf('\\')) + "\\myBatchFiles\\BAT1";

An alternative way is:

string executingAppPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
batchFile_1.StartInfo.FileName = executingAppPath.Substring(6) + "\\myBatchFiles\\BAT1\\f1.bat";
batchFile_1.StartInfo.WorkingDirectory = executingAppPath.Substring(6) + "\\myBatchFiles\\BAT1";

I report it here hoping help somebody.


问:
retreiving fields from asscoaied models cakephp3
I dont understand from the docs why I cant retrieve selected fields from associated data.
 I have 2 many to many relationships in the contain which displays everything fine.

```<code>$query3 = $this->find()
              ->contain(['Subjects','AvailabilityForStudents'])
              ->select([
                  'Students.id','Students.first_name','Students.last_name','Students.address_billing','Students.address_lat','Students.address_long',
                  'Students.class_year','Students.address_street','Students.address_suburb','Students.address_postcode','Students.address_state'])
               ->where(['Students.id IN' => $stids])
              ->order(['Students.first_name' => 'ASC'])
              ->hydrate(true);
</code>```

My Question is that instead of getting every field from the contained models why cant I select fields from the contained model as below?  I am not selecting based on a criteria like in matching clause?

```<code>   $query3 = $this->find()
              ->contain(['Subjects','AvailabilityForStudents'])
              ->select(['Subjects.name','Subjects.id','AvailabilityForStudents.id',
                  'Students.id','Students.first_name','Students.last_name','Students.address_billing','Students.address_lat','Students.address_long',
                  'Students.class_year','Students.address_street','Students.address_suburb','Students.address_postcode','Students.address_state'])
               ->where(['Students.id IN' => $stids])
              ->order(['Students.first_name' => 'ASC'])
              ->hydrate(true);
</code>```

//student model

```<code> $this->hasMany('AvailabilityForStudents', [
            'className' => 'AvailabilityForStudents',
            'foreignKey' => 'student_id',
            'dependent' => false,
        ]);

  $this->belongsToMany('Subjects', [
            'foreignKey' => 'student_id',
            'targetForeignKey' => 'subject_id',
            'joinTable' => 'subjects_students'
        ]);

      //update contain
 $query3 = $this->find()
                   ->contain([

                              'Subjects'=>['fields'=>['name','id','SubjectsStudents.student_id']],
                              'AvailabilityForStudents'  ])
              //   ->contain(['Subjects','AvailabilityForStudents'])
                 ->where(['Students.student_unallocated' =>  1,'Students.student_inactive' =>  0])

              ->order(['Students.first_name' => 'ASC'])
              ->hydrate(true);
</code>```

https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html

答:
You are doing right.
You can try this also,</p>

```<code> $query3 = $this->find()
                  ->contain([
                                'Subjects'=>['fields'=>['name','id','SubjectsStudents.student_id']],
                              'AvailabilityForStudents'=>['fields'=>'id']
                           ])
                  ->select(['Students.id','Students.first_name','Students.last_name','Students.address_billing','Students.address_lat','Students.address_long',
                      'Students.class_year','Students.address_street','Students.address_suburb','Students.address_postcode','Students.address_state'])
                   ->where(['Students.id IN' => $stids])
                  ->order(['Students.first_name' => 'ASC'])
                  ->hydrate(false)->toArray();
</code>```

Body:
I dont understand from the docs why I cant retrieve selected fields from associated data.
 I have 2 many to many relationships in the contain which displays everything fine.

$query3 = $this->find()
              ->contain(['Subjects','AvailabilityForStudents'])
              ->select([
                  'Students.id','Students.first_name','Students.last_name','Students.address_billing','Students.address_lat','Students.address_long',
                  'Students.class_year','Students.address_street','Students.address_suburb','Students.address_postcode','Students.address_state'])
               ->where(['Students.id IN' => $stids])
              ->order(['Students.first_name' => 'ASC'])
              ->hydrate(true);

My Question is that instead of getting every field from the contained models why cant I select fields from the contained model as below?  I am not selecting based on a criteria like in matching clause?

   $query3 = $this->find()
              ->contain(['Subjects','AvailabilityForStudents'])
              ->select(['Subjects.name','Subjects.id','AvailabilityForStudents.id',
                  'Students.id','Students.first_name','Students.last_name','Students.address_billing','Students.address_lat','Students.address_long',
                  'Students.class_year','Students.address_street','Students.address_suburb','Students.address_postcode','Students.address_state'])
               ->where(['Students.id IN' => $stids])
              ->order(['Students.first_name' => 'ASC'])
              ->hydrate(true);

//student model

 $this->hasMany('AvailabilityForStudents', [
            'className' => 'AvailabilityForStudents',
            'foreignKey' => 'student_id',
            'dependent' => false,
        ]);

  $this->belongsToMany('Subjects', [
            'foreignKey' => 'student_id',
            'targetForeignKey' => 'subject_id',
            'joinTable' => 'subjects_students'
        ]);

      //update contain
 $query3 = $this->find()
                   ->contain([

                              'Subjects'=>['fields'=>['name','id','SubjectsStudents.student_id']],
                              'AvailabilityForStudents'  ])
              //   ->contain(['Subjects','AvailabilityForStudents'])
                 ->where(['Students.student_unallocated' =>  1,'Students.student_inactive' =>  0])

              ->order(['Students.first_name' => 'ASC'])
              ->hydrate(true);

https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html

Body:
You are doing right.
You can try this also,

 $query3 = $this->find()
                  ->contain([
                                'Subjects'=>['fields'=>['name','id','SubjectsStudents.student_id']],
                              'AvailabilityForStudents'=>['fields'=>'id']
                           ])
                  ->select(['Students.id','Students.first_name','Students.last_name','Students.address_billing','Students.address_lat','Students.address_long',
                      'Students.class_year','Students.address_street','Students.address_suburb','Students.address_postcode','Students.address_state'])
                   ->where(['Students.id IN' => $stids])
                  ->order(['Students.first_name' => 'ASC'])
                  ->hydrate(false)->toArray();


问:
FFMEPG permission problem, is there any alternative solution instead of FFMPEG?
We have some kind of permenant permission problem on FFMPEG.exe to write JPEG file on to HDD.
We are using IIS and try all permission methods to ffmepg.exe, its including folder,folders, cmd.exe and any executable file, related folder, file. Also we tried many many command examples. But never went beyond the "permission denied" error messages.
We give up.
Do you know another alternative solution to pick images from flv, f4v movie files? Or %100 quaranteed method to achive this permission control on IIS?
Thank you.
---last code we try
  variables etc. aren't shown here.</p>

```<code>jpegYapKomutu = videoEditorKlasoru &"\ffmpeg.exe -i " & videoEditorKlasoru & "\deneme.flv" &" -s 480×360 -ss 00:00:"&saniyesi&" -vframes 1 -f mjpeg "&  "C:\Webhome\normworks\caglarorhan\deneme.jpg"
        WScript.Run "%COMSPEC% /C dir" & jpegYapKomutu
</code>```

答:
"Permission denied"-problems have nothing to do with FFMPEG, and you will get the same problems with any other tool.

By the way, this question probably belongs on https://serverfault.com/

Body:
We have some kind of permenant permission problem on FFMPEG.exe to write JPEG file on to HDD.
We are using IIS and try all permission methods to ffmepg.exe, its including folder,folders, cmd.exe and any executable file, related folder, file. Also we tried many many command examples. But never went beyond the "permission denied" error messages.
We give up.
Do you know another alternative solution to pick images from flv, f4v movie files? Or %100 quaranteed method to achive this permission control on IIS?
Thank you.
---last code we try
  variables etc. aren't shown here.

jpegYapKomutu = videoEditorKlasoru &"\ffmpeg.exe -i " & videoEditorKlasoru & "\deneme.flv" &" -s 480×360 -ss 00:00:"&saniyesi&" -vframes 1 -f mjpeg "&  "C:\Webhome\normworks\caglarorhan\deneme.jpg"
        WScript.Run "%COMSPEC% /C dir" & jpegYapKomutu


问:
Create a tab view on the fragment
I created a bottom navigation app, I added 2 buttons. When I click on each buttons it will move to 2  different fragments. I want to add tab view in first fragment  (black fragment). I want 3 tabs in  tab view like WhatsApp. When I slide the tab it must go to the other fragment. I tried, it is not working.

(My project is already working good the bottom navigation view, I want to add tab view in the blankfragment, java code and XML file)

Download project code

https://drive.google.com/file/d/0B_36gwgzDoNRbGd4R2NlX0RpeU0/view?usp=drivesdk!

Like this screen shot image model

答:
Look at this example, it will help you achieve what you want:

The first section is how to implement a ViewPager with BottomNavigation

MainActivity

```<code>public class MainActivity extends AppCompatActivity {

BottomNavigationView bottomNavigationView;

//This is our viewPager
private ViewPager viewPager;

//Fragments

ChatFragment chatFragment;
CallsFragment callsFragment;
ContactsFragment contactsFragment;
MenuItem prevMenuItem;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Initializing viewPager
    viewPager = (ViewPager) findViewById(R.id.viewpager);

    //Initializing the bottomNavigationView
    bottomNavigationView = (BottomNavigationView)findViewById(R.id.bottom_navigation);

    bottomNavigationView.setOnNavigationItemSelectedListener(
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.action_call:
                            viewPager.setCurrentItem(0);
                            break;
                        case R.id.action_chat:
                            viewPager.setCurrentItem(1);
                            break;
                        case R.id.action_contact:
                            viewPager.setCurrentItem(2);
                            break;
                    }
                    return false;
                }
            });

    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (prevMenuItem != null) {
                prevMenuItem.setChecked(false);
            }
            else
            {
                bottomNavigationView.getMenu().getItem(0).setChecked(false);
            }
            Log.d("page", "onPageSelected: "+position);
            bottomNavigationView.getMenu().getItem(position).setChecked(true);
            prevMenuItem = bottomNavigationView.getMenu().getItem(position);

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

   /*  //Disable ViewPager Swipe
   viewPager.setOnTouchListener(new View.OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            return true;
        }
    });
    */

    setupViewPager(viewPager);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    callsFragment=new CallsFragment();
    chatFragment=new ChatFragment();
    contactsFragment=new ContactsFragment();
    adapter.addFragment(callsFragment);
    adapter.addFragment(chatFragment);
    adapter.addFragment(contactsFragment);
    viewPager.setAdapter(adapter);
}
}
</code>```

ViewPagerAdapter:

```<code>public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}
@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFragment(Fragment fragment) {
    mFragmentList.add(fragment);
}

}
</code>```

activity_main.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="droidmentor.bnv_with_viewpager.MainActivity">

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:itemBackground="@color/colorPrimary"
        app:itemIconTint="@drawable/bottom_navigation_color_selector"
        app:itemTextColor="@drawable/bottom_navigation_color_selector"
        app:menu="@menu/menu_bottom_navigation" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_navigation"
        android:layout_alignParentTop="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</RelativeLayout>
</code>```

EDIT

This will show how to put a ViewPager inside a Fragment:

Change your fragment_blank.xml to:

```<code><?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.PagerTabStrip
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"/>

</android.support.v4.view.ViewPager>
</code>```

Inside your BlankFragment.java do this:

```<code>public class BlankFragment extends Fragment {
  @Override
  public View onCreateView(LayoutInflater inflater,
                       ViewGroup container,
                       Bundle savedInstanceState) {
    View result=inflater.inflate(R.layout.fragment_blank, container, false);
    ViewPager pager=(ViewPager)result.findViewById(R.id.pager);

    pager.setAdapter(buildAdapter());

    return(result);
  }

  private PagerAdapter buildAdapter() {
    return(new SampleAdapter(getActivity(), getChildFragmentManager()));
  }
}
</code>```

Create a Adapter I called mine SampleAdapter:

```<code>public class SampleAdapter extends FragmentPagerAdapter {
Context ctxt=null;

public SampleAdapter(Context ctxt, FragmentManager mgr) {
    super(mgr);
    this.ctxt=ctxt;
}

  @Override
    public int getCount() {
    return(10);
  }

  @Override
    public Fragment getItem(int position) {
    return(EditorFragment.newInstance(position));
  }

  @Override
    public String getPageTitle(int position) {
    return(EditorFragment.getTitle(ctxt, position));
  }
}
</code>```

MORE OPTIONS:

If you want a TabLayout inside your fragment:

```<code>ViewPager viewPager;
TabLayout tabLayout;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_blank, container, false);

    viewPager = (ViewPager) view.findViewById(R.id.viewpager);
    tabLayout = (TabLayout) view.findViewById(R.id.tab);

    return view;
 }

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    setupViewPager(viewPager);
    tabLayout.setupWithViewPager(viewPager);

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
</code>```

If you choose to do this, then you will have to place the following inside your fragment_blank:

```<code><android.support.design.widget.TabLayout
    android:id="@+id/tab"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:tabBackground="@drawable/tab_color_selector"
/>
</code>```

Title: Create a tab view on the fragment

Body:
Look at this example, it will help you achieve what you want:

The first section is how to implement a ViewPager with BottomNavigation

MainActivity

public class MainActivity extends AppCompatActivity {

BottomNavigationView bottomNavigationView;

//This is our viewPager
private ViewPager viewPager;

//Fragments

ChatFragment chatFragment;
CallsFragment callsFragment;
ContactsFragment contactsFragment;
MenuItem prevMenuItem;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Initializing viewPager
    viewPager = (ViewPager) findViewById(R.id.viewpager);

    //Initializing the bottomNavigationView
    bottomNavigationView = (BottomNavigationView)findViewById(R.id.bottom_navigation);

    bottomNavigationView.setOnNavigationItemSelectedListener(
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.action_call:
                            viewPager.setCurrentItem(0);
                            break;
                        case R.id.action_chat:
                            viewPager.setCurrentItem(1);
                            break;
                        case R.id.action_contact:
                            viewPager.setCurrentItem(2);
                            break;
                    }
                    return false;
                }
            });

    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (prevMenuItem != null) {
                prevMenuItem.setChecked(false);
            }
            else
            {
                bottomNavigationView.getMenu().getItem(0).setChecked(false);
            }
            Log.d("page", "onPageSelected: "+position);
            bottomNavigationView.getMenu().getItem(position).setChecked(true);
            prevMenuItem = bottomNavigationView.getMenu().getItem(position);

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

   /*  //Disable ViewPager Swipe
   viewPager.setOnTouchListener(new View.OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            return true;
        }
    });
    */

    setupViewPager(viewPager);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    callsFragment=new CallsFragment();
    chatFragment=new ChatFragment();
    contactsFragment=new ContactsFragment();
    adapter.addFragment(callsFragment);
    adapter.addFragment(chatFragment);
    adapter.addFragment(contactsFragment);
    viewPager.setAdapter(adapter);
}
}

ViewPagerAdapter:

public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}
@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFragment(Fragment fragment) {
    mFragmentList.add(fragment);
}

}

activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="droidmentor.bnv_with_viewpager.MainActivity">

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:itemBackground="@color/colorPrimary"
        app:itemIconTint="@drawable/bottom_navigation_color_selector"
        app:itemTextColor="@drawable/bottom_navigation_color_selector"
        app:menu="@menu/menu_bottom_navigation" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_navigation"
        android:layout_alignParentTop="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</RelativeLayout>

EDIT

This will show how to put a ViewPager inside a Fragment:

Change your fragment_blank.xml to:

<?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.PagerTabStrip
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"/>

</android.support.v4.view.ViewPager>

Inside your BlankFragment.java do this:

public class BlankFragment extends Fragment {
  @Override
  public View onCreateView(LayoutInflater inflater,
                       ViewGroup container,
                       Bundle savedInstanceState) {
    View result=inflater.inflate(R.layout.fragment_blank, container, false);
    ViewPager pager=(ViewPager)result.findViewById(R.id.pager);

    pager.setAdapter(buildAdapter());

    return(result);
  }

  private PagerAdapter buildAdapter() {
    return(new SampleAdapter(getActivity(), getChildFragmentManager()));
  }
}

Create a Adapter I called mine SampleAdapter:

public class SampleAdapter extends FragmentPagerAdapter {
Context ctxt=null;

public SampleAdapter(Context ctxt, FragmentManager mgr) {
    super(mgr);
    this.ctxt=ctxt;
}

  @Override
    public int getCount() {
    return(10);
  }

  @Override
    public Fragment getItem(int position) {
    return(EditorFragment.newInstance(position));
  }

  @Override
    public String getPageTitle(int position) {
    return(EditorFragment.getTitle(ctxt, position));
  }
}

MORE OPTIONS:

If you want a TabLayout inside your fragment:

ViewPager viewPager;
TabLayout tabLayout;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_blank, container, false);

    viewPager = (ViewPager) view.findViewById(R.id.viewpager);
    tabLayout = (TabLayout) view.findViewById(R.id.tab);

    return view;
 }

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    setupViewPager(viewPager);
    tabLayout.setupWithViewPager(viewPager);

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

If you choose to do this, then you will have to place the following inside your fragment_blank:

<android.support.design.widget.TabLayout
    android:id="@+id/tab"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:tabBackground="@drawable/tab_color_selector"
/>


问:
Local minimum function getting stuck not at minimum
Summary

My simple function performing a binary search for a local minimum often returns spurious values corresponding to exactly ¼, ½, and ¾ of the search. Why is this happening?

```<code>/**
 * minX  : the smallest input value
 * maxX  : the largest input value
 * ƒ     : a function that returns a value `y` given an `x`
 * ε     : how close in `x` the bounds must be before returning
 * return: the `x` value that produces the smallest `y`
 */
function localMinimum(minX, maxX, ƒ, ε) {
    if (ε===undefined) ε=1e-15;
    let m=minX, n=maxX, k;
    while ((n-m)>ε) {
        k = (n+m)/2;
        if (ƒ(m)<ƒ(n)) n=k;
        else           m=k;
    }
    return k;
}
</code>```

Live Demo: http://phrogz.net/svg/closest-point-on-bezier_broken.html

The demo lets you adjust a cubic Bézier curve, move the mouse around, and attempts to find a point on the curve closest to the mouse location. In the screenshots below, you can see the curve (black), the location of the mouse (centered in the gray circle), the location found on the curve (red dot), a brute-force graph of the distance from the cursor to each point on the curve (lower right corner), and the t parameter that was calculated as the local minimum (red text).

These screenshots represent the worst case. In them the mouse location is very close to the line, and the "local minimum" function is returning a point that is NOT the local minimum. If you experiment with the demo, you will see that in many cases the local minimum function is working as intended. Just…not near some of the early binary search bounds.

Guide to the Code

The localMinimum() function (line 225) is called by the closestPoint() function (line 194):

```<code>/**
 * out   : A vmath vector to modify with the point value
 * curve : Array of vectors as control points for a Bézier curve (any degree)
 * pt    : Object with .x/.y to find the point closest to
 * return: A parameter t representing the location of `out`
 */
function closestPoint(out, curve, pt, tmps) {
    let vec=vmath[ 'w' in curve[0] ? 'vec4' : 'z' in curve[0] ? 'vec3' : 'vec2' ];
    return localMinimum(0, 1,
      t => vec.squaredDistance(pt, bézierPoint(out, curve, t)));
}
</code>```

The bézierPoint() function (line 207) uses De Casteljau's algorithm to calculate a point along the curve parameterized by t. This function works as expected, tested independently of the rest of the problem.

The squaredDistance() function is part of the vmath library, and is as simple as you would imagine.

What am I missing? How is my local minima function failing?

答:
As so often happens, the moment you take the time to write up a question, the answer becomes obvious. My localMinimum() function was flawed.

If we look at the graph for the third example above and draw a line from the maximum point, we see that it is on the right side:

The way the algorithm (as shown above) is written, it immediately throws away the right half of the graph and focuses on the left. From that point on, it is doomed. It keeps moving the left bound toward the right at 0.5, but is never allowed to move the right again.

Here is a fixed version of the localMinimum() function, employing a bit of a hack. Given any bounds, it finds the spot in the middle, and then steps to the left and right "slightly" (as determined by the ε parameter) and decides which half to keep based on that.

```<code>/**
 * minX  : the smallest input value
 * maxX  : the largest input value
 * ƒ     : a function that returns a value `y` given an `x`
 * ε     : how close in `x` the bounds must be before returning
 * return: the `x` value that produces the smallest `y`
 */
function localMinimum(minX, maxX, ƒ, ε) {
    if (ε===undefined) ε=1e-10;
    let m=minX, n=maxX, k;
    while ((n-m)>ε) {
        k = (n+m)/2;
        if (ƒ(k-ε)<ƒ(k+ε)) n=k;
        else               m=k;
    }
    return k;
}
</code>```

I've uploaded a fixed version of the demo to:http://phrogz.net/svg/closest-point-on-bezier.html

Body:
Summary

My simple function performing a binary search for a local minimum often returns spurious values corresponding to exactly ¼, ½, and ¾ of the search. Why is this happening?

/**
 * minX  : the smallest input value
 * maxX  : the largest input value
 * ƒ     : a function that returns a value `y` given an `x`
 * ε     : how close in `x` the bounds must be before returning
 * return: the `x` value that produces the smallest `y`
 */
function localMinimum(minX, maxX, ƒ, ε) {
    if (ε===undefined) ε=1e-15;
    let m=minX, n=maxX, k;
    while ((n-m)>ε) {
        k = (n+m)/2;
        if (ƒ(m)<ƒ(n)) n=k;
        else           m=k;
    }
    return k;
}

Live Demo: http://phrogz.net/svg/closest-point-on-bezier_broken.html

The demo lets you adjust a cubic Bézier curve, move the mouse around, and attempts to find a point on the curve closest to the mouse location. In the screenshots below, you can see the curve (black), the location of the mouse (centered in the gray circle), the location found on the curve (red dot), a brute-force graph of the distance from the cursor to each point on the curve (lower right corner), and the t parameter that was calculated as the local minimum (red text).

These screenshots represent the worst case. In them the mouse location is very close to the line, and the "local minimum" function is returning a point that is NOT the local minimum. If you experiment with the demo, you will see that in many cases the local minimum function is working as intended. Just…not near some of the early binary search bounds.

Guide to the Code

The localMinimum() function (line 225) is called by the closestPoint() function (line 194):

/**
 * out   : A vmath vector to modify with the point value
 * curve : Array of vectors as control points for a Bézier curve (any degree)
 * pt    : Object with .x/.y to find the point closest to
 * return: A parameter t representing the location of `out`
 */
function closestPoint(out, curve, pt, tmps) {
    let vec=vmath[ 'w' in curve[0] ? 'vec4' : 'z' in curve[0] ? 'vec3' : 'vec2' ];
    return localMinimum(0, 1,
      t => vec.squaredDistance(pt, bézierPoint(out, curve, t)));
}

The bézierPoint() function (line 207) uses De Casteljau's algorithm to calculate a point along the curve parameterized by t. This function works as expected, tested independently of the rest of the problem.

The squaredDistance() function is part of the vmath library, and is as simple as you would imagine.

What am I missing? How is my local minima function failing?

Body:
As so often happens, the moment you take the time to write up a question, the answer becomes obvious. My localMinimum() function was flawed.

If we look at the graph for the third example above and draw a line from the maximum point, we see that it is on the right side:

The way the algorithm (as shown above) is written, it immediately throws away the right half of the graph and focuses on the left. From that point on, it is doomed. It keeps moving the left bound toward the right at 0.5, but is never allowed to move the right again.

Here is a fixed version of the localMinimum() function, employing a bit of a hack. Given any bounds, it finds the spot in the middle, and then steps to the left and right "slightly" (as determined by the ε parameter) and decides which half to keep based on that.

/**
 * minX  : the smallest input value
 * maxX  : the largest input value
 * ƒ     : a function that returns a value `y` given an `x`
 * ε     : how close in `x` the bounds must be before returning
 * return: the `x` value that produces the smallest `y`
 */
function localMinimum(minX, maxX, ƒ, ε) {
    if (ε===undefined) ε=1e-10;
    let m=minX, n=maxX, k;
    while ((n-m)>ε) {
        k = (n+m)/2;
        if (ƒ(k-ε)<ƒ(k+ε)) n=k;
        else               m=k;
    }
    return k;
}

I've uploaded a fixed version of the demo to:http://phrogz.net/svg/closest-point-on-bezier.html


问:
Segmentation fault after realloc in function
I have created this code to test one error, that I get in my main code, and it shares the same problem. I'm always getting either segmentation fault or corrupted data (zeros or strange numbers).

Here is the code:

```<code>int *p=NULL;
int func (int **point);

int main() {
    int num = 5647;
    p = malloc(sizeof(int)*2);
    p[0] = num;
    p[1]= 657;
    printf("%d\n", p[0]);
    printf("%d\n", p[1]);
    func(&p);
    printf("%d\n", p[0]);
    printf("%d\n", p[1]);
    printf("%d\n", p[2]);
    printf("%d\n", p[3]);
    return 0;
}

int func (int **point){
    *point = realloc(*point,sizeof(int)*4);
    if (*point==NULL){
        printf("\n abort \n");
        exit(0);
    }
    *point[0] = 867;
    *point[1]= 777;
    *point[2] = 67;
    *point[3]= 77;
}
</code>```

I'm getting the segmentation fault on the *point[1]=777;. If I'm trying to do like point[1]=777; I'm getting wrong data. With any changes in int func (int **point); or func(&p); I'm getting segmentation fault on realloc.

Please advise, I have read information about double pointers and tried to follow all solutions I found, but every time I'm getting this error.

答:
Your problem is operator precedence, change *point[0] to (*point)[0] and so forth.

What you have right now is *(point[0]). You treat a pointer to a single element as a pointer to multiple consecutive elements and then dereference some indeterminate value as an address. This results in undefined behavior, which luckily for you manifests as a crash.

After the change you first dereference point and then use that address to index into consecutive elements you allocated.

Two suggestions for improvement:

Don't assign the result of realloc directly to *point. If the call fails, then you leak the original memory. Assign it to a temporary first for verification.

Also, try not to repeat types. Instead of sizeof(int) try for sizeof(**point), i.e whatever the output buffer is supposed to point at. That way you won't have silent errors in your code if you change the type from int to something else.

```<code>void *point_check = realloc(*point,sizeof(**point)*4);
if (point_check == NULL){
    printf("\n abort \n");
    exit(0); // If this ever returns instead of exit, `*point` will not leak
}
*point = point_check;
</code>```

Body:
I have created this code to test one error, that I get in my main code, and it shares the same problem. I'm always getting either segmentation fault or corrupted data (zeros or strange numbers).

Here is the code:

int *p=NULL;
int func (int **point);

int main() {
    int num = 5647;
    p = malloc(sizeof(int)*2);
    p[0] = num;
    p[1]= 657;
    printf("%d\n", p[0]);
    printf("%d\n", p[1]);
    func(&p);
    printf("%d\n", p[0]);
    printf("%d\n", p[1]);
    printf("%d\n", p[2]);
    printf("%d\n", p[3]);
    return 0;
}

int func (int **point){
    *point = realloc(*point,sizeof(int)*4);
    if (*point==NULL){
        printf("\n abort \n");
        exit(0);
    }
    *point[0] = 867;
    *point[1]= 777;
    *point[2] = 67;
    *point[3]= 77;
}

I'm getting the segmentation fault on the *point[1]=777;. If I'm trying to do like point[1]=777; I'm getting wrong data. With any changes in int func (int **point); or func(&p); I'm getting segmentation fault on realloc.

Please advise, I have read information about double pointers and tried to follow all solutions I found, but every time I'm getting this error.

Body:
Your problem is operator precedence, change *point[0] to (*point)[0] and so forth.

What you have right now is *(point[0]). You treat a pointer to a single element as a pointer to multiple consecutive elements and then dereference some indeterminate value as an address. This results in undefined behavior, which luckily for you manifests as a crash.

After the change you first dereference point and then use that address to index into consecutive elements you allocated.

Two suggestions for improvement:

Don't assign the result of realloc directly to *point. If the call fails, then you leak the original memory. Assign it to a temporary first for verification.

Also, try not to repeat types. Instead of sizeof(int) try for sizeof(**point), i.e whatever the output buffer is supposed to point at. That way you won't have silent errors in your code if you change the type from int to something else.

void *point_check = realloc(*point,sizeof(**point)*4);
if (point_check == NULL){
    printf("\n abort \n");
    exit(0); // If this ever returns instead of exit, `*point` will not leak
}
*point = point_check;


问:
dapper - return a list of INT
From a stored procedure I am returning a list of int - simply as

```<code>SELECT ID FROM Table
</code>```

This is using dapper. Below is an attempt of what I am trying to do. I can fill an object in using the same approach but not an int object

```<code>List<int> ids = new List<int>();
int id = 0;

// Trying to fill a list of ints here
ids = connection.Query("storedprocedure", param, transaction: transaction, commandType: CommandType.StoredProcedure).Select(row => new int { id = row.ID }).ToList();
</code>```

I believe its something to do with => new int at the end of the statement. I am sure the solution is fairly simple. Just one of them fridays.

答:
This is very similar but with .ToList() as IList<int>

```<code>var ids = connection.Query<int>("storedprocedure",
param, transaction:transaction, commandType: CommandType.StoredProcedure)
.ToList() as IList<int>
</code>```

ContentLicense: CC BY-SA 4.0

Title: dapper - return a list of INT

Body:
From a stored procedure I am returning a list of int - simply as

SELECT ID FROM Table

This is using dapper. Below is an attempt of what I am trying to do. I can fill an object in using the same approach but not an int object

List<int> ids = new List<int>();
int id = 0;

// Trying to fill a list of ints here
ids = connection.Query("storedprocedure", param, transaction: transaction, commandType: CommandType.StoredProcedure).Select(row => new int { id = row.ID }).ToList();

I believe its something to do with => new int at the end of the statement. I am sure the solution is fairly simple. Just one of them fridays.

Body:
This is very similar but with .ToList() as IList<int>

var ids = connection.Query<int>("storedprocedure",
param, transaction:transaction, commandType: CommandType.StoredProcedure)
.ToList() as IList<int>


问:
Nth-of-type ignored classes
So I have this html

```<code><div>
    <div class="item"></div>
    <div class="item inactive"></div>
    <div class="item inactive"></div>
<div>
</code>```

And this css

```<code> .item.inactive:nth-of-type(1) {
     do stuff for 1st inactive
 }
 .item.inactive:nth-of-type(2) {
     do stuff for 2nd inactive
 }
</code>```

but it's not working as expected.

Instead I see this behavior

```<code> .item.inactive:nth-of-type(2) {
     stuff is happening for 1st inactive
 }
</code>```

so is it just ignoring when I specified .inactive? How would I get the effect I want?

.item {
  color: red;
}

.item.inactive:nth-of-type(2) {
  color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class='item-list'>
  <li class='item'>item 1</li>
  <li class='item inactive'>item 2</li>
  <li class='item inactive'>item 3</li>
<ul></code>```

答:
nth-of-type works on tag type and no class. when you write:

```<code>.item.inactive:nth-of-type(1) {
  color: red;
}
</code>```

affect on first div if have both class item and inactive.first div have class item and no inactive so no selected.

```<code>.item.inactive:nth-of-type(2) {
  color: blue;
}
</code>```

affect on Second div if have both class item and inactive.Second div have class item and inactive so selected.

You can use This :

```<code>div:nth-child(2) {
  color: red;
}

div:nth-child(3) {
  color: blue;
}
</code>```

div:nth-child(2) {
  color: red;
}

div:nth-child(3) {
  color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="item">This is 0</div>
  <div class="item inactive">This is 1</div>
  <div class="item inactive">This is 2</div></code>```

Title: Nth-of-type ignored classes

Body:
So I have this html

And this css

 .item.inactive:nth-of-type(1) {
     do stuff for 1st inactive
 }
 .item.inactive:nth-of-type(2) {
     do stuff for 2nd inactive
 }

but it's not working as expected.

Instead I see this behavior

 .item.inactive:nth-of-type(2) {
     stuff is happening for 1st inactive
 }

so is it just ignoring when I specified .inactive? How would I get the effect I want?

.item {
  color: red;
}

.item.inactive:nth-of-type(2) {
  color: green;
}

item 1

item 2

item 3

Body:
nth-of-type works on tag type and no class. when you write:

.item.inactive:nth-of-type(1) {
  color: red;
}

affect on first div if have both class item and inactive.first div have class item and no inactive so no selected.

.item.inactive:nth-of-type(2) {
  color: blue;
}

affect on Second div if have both class item and inactive.Second div have class item and inactive so selected.

You can use This :

div:nth-child(2) {
  color: red;
}

div:nth-child(3) {
  color: blue;
}

div:nth-child(2) {
  color: red;
}

div:nth-child(3) {
  color: blue;
}

  <div class="item">This is 0</div>
  <div class="item inactive">This is 1</div>
  <div class="item inactive">This is 2</div>


问:
How could I add current pc IP into security group with aws cli
I want to add current working PC's IP into a security group,

And enable all traffice for it. Every time I should do that manually with the web dashboard.

How could I do it with a shell script?

The following are the most common aws cli commands I used.

But I couldn't find how to add ip in a specific security group.

```<code>list_instances(){
    aws ec2 describe-instances --query 'Reservations[].Instances[].[Tags[?Key==`Name`].Value,InstanceId,PublicIpAddress,PrivateIpAddress]' --output text
}
start_instance(){
    aws ec2 start-instances --instance-ids $1
}
</code>```

答:
I came upon this post while looking for the awscli command to update security group. I thought I would share this Python script I wrote using Boto3 and Requests recently that will update the stated security group with your current IP address. Hope this can help someone.

https://github.com/JustinDevelops/AWS-SG-IP-Updater

Body:
I want to add current working PC's IP into a security group,

And enable all traffice for it. Every time I should do that manually with the web dashboard.

How could I do it with a shell script?

The following are the most common aws cli commands I used.

But I couldn't find how to add ip in a specific security group.

list_instances(){
    aws ec2 describe-instances --query 'Reservations[].Instances[].[Tags[?Key==`Name`].Value,InstanceId,PublicIpAddress,PrivateIpAddress]' --output text
}
start_instance(){
    aws ec2 start-instances --instance-ids $1
}


问:
How can I make an element on hover?
All I'm trying to do is something like this mechanism:

Here is what I've tried so far:

$(document).ready(function(){
    $('a').bind('mouseenter', function() {
      var self = $(this);
      this.iid = setInterval(function() {
        var tag_name = self.text(),
             top      = self.position().top + self.outerHeight(true),
             left     = self.position().left;
         self.append("
Some explanations about"+tag_name+"
")
         $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
      }, 525);
  }).bind('mouseleave', function(){
     this.iid && clearInterval(this.iid);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  padding: 20px;
}

a {
    color: #3e6d8e !important;
    background-color: #E1ECF4;
    padding: 2px 5px;
}
.tag_info{
  position: reletive;
  width: 130px;
  height: 30px;
  display:none;
  background-color: black;
  color: white;
}</code>```

tag1
tag2```

As you see, it will be repeated every time. How can I execute it once per hover? And why the position doesn't apply?

Also is what I'm doing a right algorithm for such thing?

Thank you.

答:
Like Dij said:

What you're doing:

setInterval - (repeats your function every 525ms)

What you want:

setTimeout - (executes your function once after 525ms delay)

Read more:

setInterval https://www.w3schools.com/jsref/met_win_setinterval.asp

setTimeout https://www.w3schools.com/jsref/met_win_settimeout.asp

Title: How can I make an element on hover?

Body:
All I'm trying to do is something like this mechanism:

Here is what I've tried so far:

$(document).ready(function(){
    $('a').bind('mouseenter', function() {
      var self = $(this);
      this.iid = setInterval(function() {
        var tag_name = self.text(),
             top      = self.position().top + self.outerHeight(true),
             left     = self.position().left;
         self.append("
Some explanations about"+tag_name+"
")
         $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
      }, 525);
  }).bind('mouseleave', function(){
     this.iid && clearInterval(this.iid);
  });
});

body{
  padding: 20px;
}

a {
    color: #3e6d8e !important;
    background-color: #E1ECF4;
    padding: 2px 5px;
}
.tag_info{
  position: reletive;
  width: 130px;
  height: 30px;
  display:none;
  background-color: black;
  color: white;
}

tag1
tag2

As you see, it will be repeated every time. How can I execute it once per hover? And why the position doesn't apply?

Also is what I'm doing a right algorithm for such thing?

Thank you.


问:
Convert std::vector<std::string> to const char* const*
I'm working with Vulkan, and I'm trying to pass my validation layer as a vector<string>. But the field ppEnabledLayerNames from VkInstanceCreateInfo only takes const char* const*. I don't understand the type and how to convert my vector's data into it.

```<code>std::vector<std::string> v = {
    "VK_LAYER_LUNARG_standard_validation"
};

const char* const* data = std::accumulate(std::next(v.begin()), v.end(),
                                    v[0],
                                    [](std::string a, std::string b) {
                                        return a + b;
                                    }).c_str();
</code>```

But when I compile, I got this :

```<code>error: cannot convert ‘const char*’ to ‘const char* const*’ in assignment
                     }).c_str();
</code>```

Here's a live example

答:
Here's a way to do it on a std::string:

```<code>const std::string str = "test";
const char* str_p = str.c_str();

const char* const* ppEnabledExtensionNames = &str_p;
</code>```

Be careful if c_str() is part of a temporary string that's getting trashed. You may need to retain a reference to the base string object until you're done with this.

Body:
I'm working with Vulkan, and I'm trying to pass my validation layer as a vector<string>. But the field ppEnabledLayerNames from VkInstanceCreateInfo only takes const char* const*. I don't understand the type and how to convert my vector's data into it.

std::vector<std::string> v = {
    "VK_LAYER_LUNARG_standard_validation"
};

const char* const* data = std::accumulate(std::next(v.begin()), v.end(),
                                    v[0],
                                    [](std::string a, std::string b) {
                                        return a + b;
                                    }).c_str();

But when I compile, I got this :

error: cannot convert ‘const char*’ to ‘const char* const*’ in assignment
                     }).c_str();

Here's a live example

Body:
Here's a way to do it on a std::string:

const std::string str = "test";
const char* str_p = str.c_str();

const char* const* ppEnabledExtensionNames = &str_p;

Be careful if c_str() is part of a temporary string that's getting trashed. You may need to retain a reference to the base string object until you're done with this.


问:
How to pass the value of variable when next page loads in JavaScript?
I have a variable named collar whose value is either red or green. It is used for random order as on or off. But in next page,it wont retain its previous value. How to do that. I am beginner in JavaScript.</p>

答: You need to use cookies or pass it to a server side back end using sessions.</p>


问:
Calling super super class method
Let's say I have three classes A, B and C.

B extends A

C extends B

All have a public void foo() method defined.

Now from C's foo() method I want to invoke A's foo() method (NOT its parent B's method but the super super class A's method).

I tried super.super.foo();, but it's invalid syntax.
How can I achieve this?

答:
Yes you can do it. This is a hack. Try not to design your program like this.</p>

```<code>class A
{
    public void method()
    { /* Code specific to A */ }
}

class B extends A
{
    @Override
    public void method()
    {
       //compares if the calling object is of type C, if yes push the call to the A's method.
       if(this.getClass().getName().compareTo("C")==0)
       {
           super.method();
       }
       else{  /*Code specific to B*/  }

    }
}

class C extends B
{
    @Override
    public void method()
    {
        /* I want to use the code specific to A without using B */
        super.method();

    }
}
</code>```

Title: Calling super super class method

Body:
Yes you can do it. This is a hack. Try not to design your program like this.

class A
{
    public void method()
    { /* Code specific to A */ }
}

class B extends A
{
    @Override
    public void method()
    {
       //compares if the calling object is of type C, if yes push the call to the A's method.
       if(this.getClass().getName().compareTo("C")==0)
       {
           super.method();
       }
       else{  /*Code specific to B*/  }

    }
}

class C extends B
{
    @Override
    public void method()
    {
        /* I want to use the code specific to A without using B */
        super.method();

    }
}


问:
How to get OS language and locale?
My app changes the language at runtime and advises the user to restart the app. I do it like this:

```<code>    typealias LanguageLocaleType = (language: String?, locale: String?, title: String)

    let elements: [LanguageLocaleType] = [
        (nil, nil, "System Default"),
        ("en", "en_US", "English"),
        ("ar", "ar_SA", "Arabic"),
    ]

    //...func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)...

    let element = elements[indexPath.row]

    guard let language = element.language else {
        // How to really reset app back to OS language/locale???
        UserDefaults.standard.removeObject(forKey: "AppleLanguages")
        UserDefaults.standard.removeObject(forKey: "AppleLocale")
        return
    }

    UserDefaults.standard.set([language], forKey: "AppleLanguages")

    if let locale = element.locale, !locale.isEmpty,
        Locale.current.identifier != locale,
        !Locale.current.identifier.hasPrefix("\(language)_") {
            UserDefaults.standard.set(locale, forKey: "AppleLocale")
    }
</code>```

I want to offer to set languages in a list with the right one selected, one of which being offered it to set language back to System Default. However, there's no way to find the OS-level language and locale that I could find. Since after I mess around with setting the UserDefaults, Bundle.main.preferredLocalizations is not reliable and do not match the system default (event when I remove the key from the User Default).

Is there a way to get the OS-level language and locale instead of the app-level?

答:
You should be able to get currently selected OS language like this.

```<code>    let language  = NSLocale.preferredLanguages[0]
</code>```

if this is not what you are looking for, refer to this answer
https://stackoverflow.com/a/30750120/809821

Title: How to get OS language and locale?

Body:
My app changes the language at runtime and advises the user to restart the app. I do it like this:

    typealias LanguageLocaleType = (language: String?, locale: String?, title: String)

    let elements: [LanguageLocaleType] = [
        (nil, nil, "System Default"),
        ("en", "en_US", "English"),
        ("ar", "ar_SA", "Arabic"),
    ]

    //...func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)...

    let element = elements[indexPath.row]

    guard let language = element.language else {
        // How to really reset app back to OS language/locale???
        UserDefaults.standard.removeObject(forKey: "AppleLanguages")
        UserDefaults.standard.removeObject(forKey: "AppleLocale")
        return
    }

    UserDefaults.standard.set([language], forKey: "AppleLanguages")

    if let locale = element.locale, !locale.isEmpty,
        Locale.current.identifier != locale,
        !Locale.current.identifier.hasPrefix("\(language)_") {
            UserDefaults.standard.set(locale, forKey: "AppleLocale")
    }

I want to offer to set languages in a list with the right one selected, one of which being offered it to set language back to System Default. However, there's no way to find the OS-level language and locale that I could find. Since after I mess around with setting the UserDefaults, Bundle.main.preferredLocalizations is not reliable and do not match the system default (event when I remove the key from the User Default).

Is there a way to get the OS-level language and locale instead of the app-level?

Body:
You should be able to get currently selected OS language like this.

    let language  = NSLocale.preferredLanguages[0]

if this is not what you are looking for, refer to this answer
https://stackoverflow.com/a/30750120/809821


问:
how can i find the sum of all integers given in the string by using JavaScript?
How do I calculate the sum of all the numbers in a string by using the JavaScript ? In the example below, the expected result would be 2+0+1+5. My attempt is below. </p>

```<code>var a = "weare20boysand15girls";
    var i;
    for(i=0; i<a.length; i++){
        var b = Number(a[i]);
        var c=0;
        c += b;
        console.log(c);
</code>```

答:
I would suggest regex solution for this. Separate number from your whole string by digits [0-9] regex and sum up them using loop.

var a = "weare20boysand15girls";
const regex = /[0-9]/g;
var num = a.match(regex);
var result=0;
num.forEach(function(match){
    result+=parseInt(match);
});
console.log(result);```

Body:
How do I calculate the sum of all the numbers in a string by using the JavaScript ? In the example below, the expected result would be 2+0+1+5. My attempt is below.

var a = "weare20boysand15girls";
    var i;
    for(i=0; i<a.length; i++){
        var b = Number(a[i]);
        var c=0;
        c += b;
        console.log(c);


问:
How to select from one column or the other?
Let's say I have a table with friends and their friendship status (0-rejected, 1-accepted)

```<code>userA   userB  status
-------------------
john    chris   1
chris   bob     1
mike    chris   1
</code>```

How do I select all of chris' friends to get an output like this?

```<code>john
bob
mike
</code>```

答:
You can use CASE expression for this, something like:

```<code>select
case when userA = 'chris' then userB when userB = 'chris' then userA end as friend_name
from  your_table
where
(userA = 'chris' or userB = 'chris') and status = 1
</code>```

Body:
Let's say I have a table with friends and their friendship status (0-rejected, 1-accepted)

userA   userB  status
-------------------
john    chris   1
chris   bob     1
mike    chris   1

How do I select all of chris' friends to get an output like this?

john
bob
mike

Body:
You can use CASE expression for this, something like:

select
case when userA = 'chris' then userB when userB = 'chris' then userA end as friend_name
from  your_table
where
(userA = 'chris' or userB = 'chris') and status = 1


问:
How do I write takeWhile using foldl?
So I am doing exercises from real world haskell book and I wrote following code for takeWhile function using foldl. </p>

```<code>myTakeWhile' :: (a->Bool) -> [a] -> [a]
myTakeWhile' f xs = foldl step [] xs
    where step x xs | f x       = x:(myTakeWhile' f xs)
                    | otherwise = []
</code>```

<p>This gives the following error, which I am unable to understand. </p>

```<code>Couldn't match type ‘a’ with ‘[a]’
      ‘a’ is a rigid type variable bound by
          the type signature for myTakeWhile' :: (a -> Bool) -> [a] -> [a]
          at p1.hs:17:17
    Expected type: [a] -> [a] -> [a]
      Actual type: a -> [a] -> [a]
    Relevant bindings include
      step :: a -> [a] -> [a] (bound at p1.hs:19:11)
      xs :: [a] (bound at p1.hs:18:16)
      f :: a -> Bool (bound at p1.hs:18:14)
      myTakeWhile' :: (a -> Bool) -> [a] -> [a] (bound at p1.hs:18:1)
    In the first argument of ‘foldl’, namely ‘step’
    In the expression: foldl step [] xs
</code>```

答:
Edit

1) Your main error, is that you are not understanding that fold does the recursion for you, you don't have to self reference the function myTakeWhile', also, fold has another type:

```<code>foldl: (b -> a -> b) -> b -> [a] -> b
</code>```

your type error in the step function on where clause is because of it.

2) Your second error, because of the definition of foldl, your takeWhile will be created from the end to the beginning, so, you should have to reverse the list (all this only because you are asking how to do it with foldl)

You can do this by using a simple lambda and an if else, is a little more readable:

```<code>myTakeWhile' f xs = foldl (\rs x -> if f x then x:rs else []) [] (reverse xs)
</code>```

example:

```<code>myTakeWhile' (<10) [1..20]
</code>```

[1,2,3,4,5,6,7,8,9]

However, with this, you just can't go over infinite list, like this:

```<code>myTakeWhile' (<10) [1..]
</code>```

It will hangs trying to create all the unevaluated expression.

Anyway, if you want to use guards and where, you should do it like this:

```<code>myTakeWhile f xs = foldl step [] (reverse xs)
  where step rs x | f x = x : rs
                  | otherwise = []
</code>```

3) Most important of all:

As @amalloy says, takeWhile is much more suitable if you implement it by using foldr :). Understand the differences between the two is crucial in some cases one using one or another can cause you performance issues, for that, you can read this question:

foldl versus foldr behavior with infinite lists

4) Finally, the correct alternative using foldr:

```<code>myTakeWhile'' f xs = foldr (\x rs -> if f x then x:rs else []) [] xs
</code>```

with this, you can use infinite list:

```<code>myTakeWhile' (<10) [1..]
</code>```

You can see the difference of how it makes the folds like this:

```<code>Prelude> foldr (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..13])
"(1+(2+(3+(4+(5+(6+(7+(8+(9+(10+(11+(12+(13+0)))))))))))))"

Prelude> foldl (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..13])
"(((((((((((((0+1)+2)+3)+4)+5)+6)+7)+8)+9)+10)+11)+12)+13)"
</code>```

This sources from https://wiki.haskell.org/Fold

Title: How do I write takeWhile using foldl?

Body:
So I am doing exercises from real world haskell book and I wrote following code for takeWhile function using foldl.

myTakeWhile' :: (a->Bool) -> [a] -> [a]
myTakeWhile' f xs = foldl step [] xs
    where step x xs | f x       = x:(myTakeWhile' f xs)
                    | otherwise = []

This gives the following error, which I am unable to understand.

Couldn't match type ‘a’ with ‘[a]’
      ‘a’ is a rigid type variable bound by
          the type signature for myTakeWhile' :: (a -> Bool) -> [a] -> [a]
          at p1.hs:17:17
    Expected type: [a] -> [a] -> [a]
      Actual type: a -> [a] -> [a]
    Relevant bindings include
      step :: a -> [a] -> [a] (bound at p1.hs:19:11)
      xs :: [a] (bound at p1.hs:18:16)
      f :: a -> Bool (bound at p1.hs:18:14)
      myTakeWhile' :: (a -> Bool) -> [a] -> [a] (bound at p1.hs:18:1)
    In the first argument of ‘foldl’, namely ‘step’
    In the expression: foldl step [] xs

Body:
Edit

1) Your main error, is that you are not understanding that fold does the recursion for you, you don't have to self reference the function myTakeWhile', also, fold has another type:

foldl: (b -> a -> b) -> b -> [a] -> b

your type error in the step function on where clause is because of it.

2) Your second error, because of the definition of foldl, your takeWhile will be created from the end to the beginning, so, you should have to reverse the list (all this only because you are asking how to do it with foldl)

You can do this by using a simple lambda and an if else, is a little more readable:

myTakeWhile' f xs = foldl (\rs x -> if f x then x:rs else []) [] (reverse xs)

example:

myTakeWhile' (<10) [1..20]

[1,2,3,4,5,6,7,8,9]

However, with this, you just can't go over infinite list, like this:

myTakeWhile' (<10) [1..]

It will hangs trying to create all the unevaluated expression.

Anyway, if you want to use guards and where, you should do it like this:

myTakeWhile f xs = foldl step [] (reverse xs)
  where step rs x | f x = x : rs
                  | otherwise = []

3) Most important of all:

As @amalloy says, takeWhile is much more suitable if you implement it by using foldr :). Understand the differences between the two is crucial in some cases one using one or another can cause you performance issues, for that, you can read this question:

foldl versus foldr behavior with infinite lists

4) Finally, the correct alternative using foldr:

myTakeWhile'' f xs = foldr (\x rs -> if f x then x:rs else []) [] xs

with this, you can use infinite list:

myTakeWhile' (<10) [1..]

You can see the difference of how it makes the folds like this:

Prelude> foldr (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..13])
"(1+(2+(3+(4+(5+(6+(7+(8+(9+(10+(11+(12+(13+0)))))))))))))"

Prelude> foldl (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..13])
"(((((((((((((0+1)+2)+3)+4)+5)+6)+7)+8)+9)+10)+11)+12)+13)"

This sources from https://wiki.haskell.org/Fold


问:
How do I disable automatic save after refactoring in Eclipse?
When I ran the Inline and Extract Local Variable refactorings, Eclipse saved my file immediately after.  Also, Undoing/Redoing these refactorings resaved the file each time.  How can I disable this behavior?

Secondary question:  Running Extract Method didn’t automatically save the file.   Why the inconsistent behavior?

答: Perhaps the question is why would you not want eclipse to save it? In my case, i didn't want eclipse to save my changes because i was running Tomcat in eclipse and it reloaded the application after each refactoring (i was changing the code as i was debugging it) and i just wanted it to continue executing with the previous code. The solution was to just configure the Publishing section of Tomcat to not publish automatically.</p>


问:
how to detect telephone numbers in a text (and replace them)?
I know it can be done for bad words (checking an array of preset words) but how to detect telephone numbers in a long text?
I'm building a website in PHP for a client who needs to avoid people using the description field to put their mobile phone numbers..(see craigslist etc..)

beside he's going to need some moderation but i was wondering if there is a way to block at least the obvious like nnn-nnn-nnnn, not asking to block other weird way of writing like HeiGHT*/four*/nine etc...

答:
I think that use a too tight regular espression would lead to loose a great number of detections.

You should check for portions of 10 consecutive chatacters containing more than 5 digits.

So it is similar you will have an analisys routine queued to be called after any message insertion due to the computational weight.

After the 6 or more digits have been isolated replace them as you prefer, including other syblings digits.
Better in any case to preserve original data, so you can try and train your detection algorithm until it works the best way.

Then you can also study your user data to create more complex euristics, such like case insensitive numbers written as letters, mixed, dot separated, etc...

It's not about write the most perfect regex, is about approaching the problem statistically and dinamically.

And remember, after you take action, user will change their insertion habits as consequence, so stats will change and you will need to learn and update your euristics.


问:
How to pass java script variables into json format
i want to pass variable values into json below is what i am trying.

In javascript i am getting values like this:

```<code>var f_name= document.getElementById("firstname").value;
var phone_number= document.getElementById("number").value;
</code>```

And then in JSON  i want to pass these values:

```<code>"Site": {
   "Name": "+f_name+",
   "Phone": "+phone_number+"
 }
</code>```

its not working. What is wrong with this?

答:
Create an object, then stringify it as JSON

```<code>var f_name       = document.getElementById("firstname").value;
var phone_number = document.getElementById("number").value;

var obj = {
    Name  : f_name,
    Phone : phone_number
}

var json = JSON.stringify(obj);
</code>```

Chances are however that you haven't understood the difference between an object and a JSON string, and that you don't really want JSON at all.

Body:
i want to pass variable values into json below is what i am trying.

In javascript i am getting values like this:

var f_name= document.getElementById("firstname").value;
var phone_number= document.getElementById("number").value;

And then in JSON  i want to pass these values:

"Site": {
   "Name": "+f_name+",
   "Phone": "+phone_number+"
 }

its not working. What is wrong with this?

Body:
Create an object, then stringify it as JSON

var f_name       = document.getElementById("firstname").value;
var phone_number = document.getElementById("number").value;

var obj = {
    Name  : f_name,
    Phone : phone_number
}

var json = JSON.stringify(obj);

Chances are however that you haven't understood the difference between an object and a JSON string, and that you don't really want JSON at all.