问:
How to call data from 2 diferent table by id in eloquent?
thats the controller

```<code>public function hitung($request, $response, $args)

{

    $datauser = User::with(['usia','aktivitas'])->find($args['id']);

    $tinggi         = $datauser['tinggi'];
    $berat          = $datauser['berat'];
    $nama           = $datauser['nama'];
    $umur           = $datauser['umur'];
    $aktivitas      = $datauser['aktivitaas_id'];
    $usia           = $datauser['usia_id'];
    $nilai          = $datauser->aktivitas->nilai;
    $energy         = $datauser->usia->energy;
    $protein        = $datauser->usia->protein;
    $lemak          = $datauser->usia->lemak;
    $karbohidrat    = $datauser->usia->karbohidrat;

    $amb = 655 + (9.6 * $berat) + (1.8 * $tinggi) - (4.7 * $umur);
    $amb = round($amb);

    $energytotal = $amb * $nilai + $energy;
    $energytotal = round($energytotal);
    $protein     = (15 * $energytotal / 100) + $protein;
    $protein = round($protein);
    $lemak       = (25 * $energytotal / 100) + $lemak;
    $lemak = round($lemak);
    $karbohidrat = ($energytotal - ($protein + $lemak)) + $karbohidrat;
    $karbohidrat= round($karbohidrat);

    return $response ->withJson([
            'Nama'  => $nama,
            'total_energy' => $energytotal ,
            'Protein'=> $protein,
            'lemak'=> $lemak,
            'Karbohidrat'=> $karbohidrat,
            ]);

}
</code>```

thats the user model:

```<code>    <?php

namespace App\models;

use Illuminate\Database\Eloquent\Model;

class User extends Model

{
    public   $timestamps  = false;

protected $fillable = ['username', 'password', 'nama', 'tinggi', 'berat', 'umur', 'usia_id', 'aktivitas_id'];

protected $table    = "users";

 public function usia()
{
    return $this->belongsTo('App\Models\Usia');
}

public function aktivitas()
{
    return $this->belongsTo('App\Models\Aktivitas');
}

    public function forum()
{
    return $this->hasMany('App\Models\Forum');
    }

}
</code>```

thats the aktivitas model:

```<code>        <?php

    namespace App\models;

    use Illuminate\Database\Eloquent\Model;

    class Aktivitas extends Model

{

    protected $table    = "aktivitas";
public function user()
{
    return $this->hasMany('App\Models\User');
}

}
</code>```

thats the usia model ,

```<code>  <?php

namespace App\models;

use Illuminate\Database\Eloquent\Model;

class Usia extends Model
{
protected $table    = "usia";

public function user()
{
    return $this->hasMany('App\Models\User');
    }

}
</code>```

this code is work in local , but when i hosting it , it didnt work , please need help for my exam ...

i think the problem is in this code ,

```<code>$datauser = User::with(['usia','aktivitas'])->find($args['id']);
</code>```

any different way to do it ?

答:
I guess your local is Windows and remote host is Linux

first of all you should know windows file and folder name is not case sensitive and there is no different between Models and models in windows OS

but Linux file and directory name  is Case Sensitive

in your codes:

```<code>namespace App\models;
</code>```

and

```<code>return $this->hasMany('App\Models\User');
</code>```

somewhere you use Models and models

you should check directory name and rename it anywhere you write wrong word

Body:
thats the controller

public function hitung($request, $response, $args)

{

    $datauser = User::with(['usia','aktivitas'])->find($args['id']);

    $tinggi         = $datauser['tinggi'];
    $berat          = $datauser['berat'];
    $nama           = $datauser['nama'];
    $umur           = $datauser['umur'];
    $aktivitas      = $datauser['aktivitaas_id'];
    $usia           = $datauser['usia_id'];
    $nilai          = $datauser->aktivitas->nilai;
    $energy         = $datauser->usia->energy;
    $protein        = $datauser->usia->protein;
    $lemak          = $datauser->usia->lemak;
    $karbohidrat    = $datauser->usia->karbohidrat;

    $amb = 655 + (9.6 * $berat) + (1.8 * $tinggi) - (4.7 * $umur);
    $amb = round($amb);

    $energytotal = $amb * $nilai + $energy;
    $energytotal = round($energytotal);
    $protein     = (15 * $energytotal / 100) + $protein;
    $protein = round($protein);
    $lemak       = (25 * $energytotal / 100) + $lemak;
    $lemak = round($lemak);
    $karbohidrat = ($energytotal - ($protein + $lemak)) + $karbohidrat;
    $karbohidrat= round($karbohidrat);

    return $response ->withJson([
            'Nama'  => $nama,
            'total_energy' => $energytotal ,
            'Protein'=> $protein,
            'lemak'=> $lemak,
            'Karbohidrat'=> $karbohidrat,
            ]);

}

thats the user model:

    <?php

namespace App\models;

use Illuminate\Database\Eloquent\Model;

class User extends Model

{
    public   $timestamps  = false;

protected $fillable = ['username', 'password', 'nama', 'tinggi', 'berat', 'umur', 'usia_id', 'aktivitas_id'];

protected $table    = "users";

 public function usia()
{
    return $this->belongsTo('App\Models\Usia');
}

public function aktivitas()
{
    return $this->belongsTo('App\Models\Aktivitas');
}

    public function forum()
{
    return $this->hasMany('App\Models\Forum');
    }

}

thats the aktivitas model:

        <?php

    namespace App\models;

    use Illuminate\Database\Eloquent\Model;

    class Aktivitas extends Model

{

    protected $table    = "aktivitas";
public function user()
{
    return $this->hasMany('App\Models\User');
}

}

thats the usia model ,

  <?php

namespace App\models;

use Illuminate\Database\Eloquent\Model;

class Usia extends Model
{
protected $table    = "usia";

public function user()
{
    return $this->hasMany('App\Models\User');
    }

}

this code is work in local , but when i hosting it , it didnt work , please need help for my exam ...

i think the problem is in this code ,

$datauser = User::with(['usia','aktivitas'])->find($args['id']);

any different way to do it ?

Body:
I guess your local is Windows and remote host is Linux

first of all you should know windows file and folder name is not case sensitive and there is no different between Models and models in windows OS

but Linux file and directory name  is Case Sensitive

in your codes:

namespace App\models;

and

return $this->hasMany('App\Models\User');

somewhere you use Models and models

you should check directory name and rename it anywhere you write wrong word


来源: stackexchange

问:
Android Browser textarea scrolls all over the place, is unusable
So I've built a nice, shiny HTML5 application that is targeted at mobile Safari, and Android's default browser. The Android versions I'm testing it on are 2.1 and 2.2.

My app has a textarea on one of its pages, and this textarea tends to have a good amount of text in it at times. Its basically a free-form writing field.

This works as expected in iOS. However on Android, as you type, the screen scrolls wildly up and down on every keystroke, often you can't see what it is you're typing as you type, and you get dizzy from all the jumping around. Furthermore, if the content within the textarea exceeds its height, it appears to be impossible to scroll within it.

Don't even get me started on landscape mode. The above issues are even more pronounced there.

This feels like a bug with Android as there really isn't anything fancy about my textarea. I've stripped it down to the bare essentials, and it behaves the same.

Wondering if anyone else has had this much fun with their textareas on Android, and could maybe give some advice, or at least empathize?

It seems that Google has managed to mostly solve this in the Gmail web interface for Android. I'm guessing there's some JS magic going on because my markup/CSS is identical.

答:
I experience this behavior on nearly every page. Here on StackOverflow, on a wordpress blog and many more.

I can only image that this is a usability bug/issue in the android browser and this is why I prefer native UI/application :)

ContentLicense: CC BY-SA 2.5


问:
Deserialize JSON object xamarin C#
I am getting the following error in Xamarin cross platform while deserializing the JSON Object. I have tried to do it with dictionary. But, everything gives me the same exception.

```<code>Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[NBStudents.Models.jsonobjectclass+User]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.Path 'data.name', line 4, position 11.
</code>```

My JSON Object Class:

```<code>public class jsonobjectclass
{
    public class User
    {
        public string name { get; set; }
        public string email { get; set; }
        public string phone { get; set; }
        public string current_group { get; set; }
        public List<UserGroups> user_groups { get; set; }
    }

    public class UserGroups
    {
        [JsonProperty("10")]
        public string Student { get; set; }
        [JsonProperty("15")]
        public string Tutor { get; set; }
        [JsonProperty("11")]
        public string Parent { get; set; }
    }

    public class Token
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string token_type { get; set; }
        public string scope { get; set; }
        public string refresh_token { get; set; }
        public string error { get; set; }
    }

    public class UserResponse
    {
        public string msg { get; set; }
        public List<User> data { get; set; }
        public bool error { get; set; }
    }
}
</code>```

My Code to Deserialize JSON:

```<code>public static async Task<jsonobjectclass.UserResponse> UserRetrievalTask(string token, string apiUrl)
    {
        var jsonObject = new jsonobjectclass.UserResponse();
        string readHttpResponse;

        using (var httpClient = new HttpClient())
        {
            using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl))
            {
                httpRequestMessage.Headers.Add("Authorization", "Bearer " + token);
                using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
                {
                    readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    var jObject = JObject.Parse(readHttpResponse);
                    try
                    {
                        jsonObject = JsonConvert.DeserializeObject<jsonobjectclass.UserResponse>(jObject.ToString());
                    }
                    catch(Exception ex)
                    {
                        string excep = ex.ToString();
                        readHttpResponse = excep;
                    }
                }
            }
        }
        return jsonObject;
    }
</code>```

My JSON String:

```<code>{{
  "msg": null,
  "data": {
  "name": "geoit",
  "email": "rokesh@geoit.in",
  "phone": null,
  "current_group": "11",
  "user_groups": {
   "11": "Parent"
   }
},
"error": false
}}
</code>```

Please Help me to solve this.

Thanks,
Rokesh

答:
It should be an array the opening and closing brackets should be square brackets:

[

```<code>{ "msg": null,"data":
</code>```

[ {
          "name": "geoit",
          "email": "rokesh@geoit.in",
          "phone": null,
          "current_group": "11",
          "user_groups":

[{
           "11": "Parent"
           }
]

}
],

"error": false
        }

]

Also in your code, you dont need var jObject = JObject.Parse(readHttpResponse); since the readHttpResponse is already a JSON string which you can deserialzie into an object.

ContentLicense: CC BY-SA 3.0

Title: Deserialize JSON object xamarin C#

Body:
I am getting the following error in Xamarin cross platform while deserializing the JSON Object. I have tried to do it with dictionary. But, everything gives me the same exception.

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[NBStudents.Models.jsonobjectclass+User]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.Path 'data.name', line 4, position 11.

My JSON Object Class:

public class jsonobjectclass
{
    public class User
    {
        public string name { get; set; }
        public string email { get; set; }
        public string phone { get; set; }
        public string current_group { get; set; }
        public List<UserGroups> user_groups { get; set; }
    }

    public class UserGroups
    {
        [JsonProperty("10")]
        public string Student { get; set; }
        [JsonProperty("15")]
        public string Tutor { get; set; }
        [JsonProperty("11")]
        public string Parent { get; set; }
    }

    public class Token
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string token_type { get; set; }
        public string scope { get; set; }
        public string refresh_token { get; set; }
        public string error { get; set; }
    }

    public class UserResponse
    {
        public string msg { get; set; }
        public List<User> data { get; set; }
        public bool error { get; set; }
    }
}

My Code to Deserialize JSON:

public static async Task<jsonobjectclass.UserResponse> UserRetrievalTask(string token, string apiUrl)
    {
        var jsonObject = new jsonobjectclass.UserResponse();
        string readHttpResponse;

        using (var httpClient = new HttpClient())
        {
            using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl))
            {
                httpRequestMessage.Headers.Add("Authorization", "Bearer " + token);
                using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
                {
                    readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    var jObject = JObject.Parse(readHttpResponse);
                    try
                    {
                        jsonObject = JsonConvert.DeserializeObject<jsonobjectclass.UserResponse>(jObject.ToString());
                    }
                    catch(Exception ex)
                    {
                        string excep = ex.ToString();
                        readHttpResponse = excep;
                    }
                }
            }
        }
        return jsonObject;
    }

My JSON String:

{{
  "msg": null,
  "data": {
  "name": "geoit",
  "email": "rokesh@geoit.in",
  "phone": null,
  "current_group": "11",
  "user_groups": {
   "11": "Parent"
   }
},
"error": false
}}

Please Help me to solve this.

Thanks,
Rokesh

Body:
It should be an array the opening and closing brackets should be square brackets:

[

{ "msg": null,"data":

[ {
          "name": "geoit",
          "email": "rokesh@geoit.in",
          "phone": null,
          "current_group": "11",
          "user_groups":

[{
           "11": "Parent"
           }
]

}
],

"error": false
        }

]

Also in your code, you dont need var jObject = JObject.Parse(readHttpResponse); since the readHttpResponse is already a JSON string which you can deserialzie into an object.


问:
failed to open stream using include
Hello all this is a simple question which is already there in stack overflow but I tried all the possible answers still it's not fixed

I need to include config file which is under assets folder i tried the following code

```<code>include_once '../config.php' ;
</code>```

am getting error like this

```<code>Warning: include(assets/config.php): failed to open stream: No such file or directory in E:\xampp\htdocs\project\assets\handler\ContactHandler.php on line 4

Warning: include(): Failed opening 'assets/config.php' for inclusion (include_path='E:\xampp\php\PEAR') in E:\xampp\htdocs\project\assets\handler\ContactHandler.php on line 4
</code>```

kindly suggest me a possible way  to include config file in ContactHandler.php

ContachHandler.php

```<code><?php

include_once 'E:\xampp\htdocs\project\assets\config.php';

echo "ddddd";
exit;
 include (CONTROLLER.'ContactController.php');
$form = $_POST['form'];
$cnt_controller = new ContactController();
switch ($form)

{

    case 'AddContact':
        $cnt_controller->AddContact($_POST);
        break;
    case 'ContactUs':
    $cnt_controller->ContactUs($_POST);
        break;

}

?>
</code>```

答:
Check to see if your include path changed and check file/folder permissions.

Try out this code:

```<code><?php
$config_path = '../config.php' ;
if (file_exists($config_path)){
    require_once $config_path;
}
else {
    $config_path = 'config.php';
    if (file_exists($config_path)) {
        require_once $config_path;
    }
    else {
        $config_path = '../../config.php';
        require_once $config_path;
    }
}

echo "ddddd";
echo $config_path;
exit;
?>
</code>```

For testing set static path:

```<code>include_once 'E:\xampp\htdocs\project\assets\config.php';
</code>```

Hope this helps!

Title: failed to open stream using include

Body:
Hello all this is a simple question which is already there in stack overflow but I tried all the possible answers still it's not fixed

I need to include config file which is under assets folder i tried the following code

include_once '../config.php' ;

am getting error like this

Warning: include(assets/config.php): failed to open stream: No such file or directory in E:\xampp\htdocs\project\assets\handler\ContactHandler.php on line 4

Warning: include(): Failed opening 'assets/config.php' for inclusion (include_path='E:\xampp\php\PEAR') in E:\xampp\htdocs\project\assets\handler\ContactHandler.php on line 4

kindly suggest me a possible way  to include config file in ContactHandler.php

ContachHandler.php

<?php

include_once 'E:\xampp\htdocs\project\assets\config.php';

echo "ddddd";
exit;
 include (CONTROLLER.'ContactController.php');
$form = $_POST['form'];
$cnt_controller = new ContactController();
switch ($form)

{

    case 'AddContact':
        $cnt_controller->AddContact($_POST);
        break;
    case 'ContactUs':
    $cnt_controller->ContactUs($_POST);
        break;

}

?>

Body:
Check to see if your include path changed and check file/folder permissions.

Try out this code:

<?php
$config_path = '../config.php' ;
if (file_exists($config_path)){
    require_once $config_path;
}
else {
    $config_path = 'config.php';
    if (file_exists($config_path)) {
        require_once $config_path;
    }
    else {
        $config_path = '../../config.php';
        require_once $config_path;
    }
}

echo "ddddd";
echo $config_path;
exit;
?>

For testing set static path:

include_once 'E:\xampp\htdocs\project\assets\config.php';

Hope this helps!


问:
AWS CLI get download S3 URL for private bucket from AWS CLI
I could upload a file to a private S3 bucket successfully using following command:

aws s3 cp "myfile.txt" "s3://myfolder/myfile.txt" --region=us-east-1 --output=json

I would like to issue a AWS CLI command to return me a temporary URL download for myfile.txt and does anyone know how to?

I googled and look like I have to do some signing to get temporary URL such as: http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html

答:
aws cli now supports presign command. You can run

```<code>$ aws s3 presign s3://test-bucket/test-file.txt
https://test-bucket/test-file.txt?Expires=1499152189&Signature=some-sha
</code>```

This will generate an url which you can share it with anyone to download that file in 3600 seconds.

You can change time period with --expires-in

```<code>$ aws s3 presign s3://test-bucket/test-file.txt --expires-in 600
</code>```

The generated url will expire in 10 minutes.

You can read more about presign in aws cli docs.

Body:
aws cli now supports presign command. You can run

$ aws s3 presign s3://test-bucket/test-file.txt
https://test-bucket/test-file.txt?Expires=1499152189&Signature=some-sha

This will generate an url which you can share it with anyone to download that file in 3600 seconds.

You can change time period with --expires-in

$ aws s3 presign s3://test-bucket/test-file.txt --expires-in 600

The generated url will expire in 10 minutes.

You can read more about presign in aws cli docs.


问:
What's the role of EX stage for branching in Pipelined MIPS w Forwarding?
Consider the following Pipelined Processor structure:

Notice that the condition test for branching (the = circuit), as well as the target address calculation for the next instruction in case of branch taken are executed in the ID phase - as a way to save on stalls/flushes (as opposed to doing all that in the EX phase and forwarding the results in the MEM phase of the given branch instruction).

Since all the work gets done in Instruction Decode stage, why bother waiting for the given branching instruction to reach the EX stage? Does the EX stage ALU unit have a role in this, somehow?

Thank you in advance.

答:
Since all the work gets done in Instruction Decode stage, why bother waiting for the given branching instruction to reach the EX stage? Does the EX stage ALU unit have a role in this, somehow?

The branch instruction is decoded and resolved in the Decode stage only and we do not wait for it to go to the EX stage.

Like you pointed out in the question, both the branch result and the target address calculation is done in the DEC stage. The hardware takes care of the RAW hazards by forwarding the required data from the correct stages (notice the little mux'es right after the RegFile is read). As a result the branch equality check sees the correct operands and the result drives the PCSrcD signal. This signal further decides the output of the first Mux in the diagram (which essentially decides between PC+4 or Branch Target. Hence it becomes safe and quick to do this in the DEC stage itself.

Also, none of the  branch instruction related signals (PCSrcD, BranchD, PCBranchD) make it to the EX stage. If you see the inputs to the ISS/EX register, it doesn't take in any of the above mentioned signals. Hence, the information isn't passed the to EX stage and the branch is completely resolved and retired at the end of the DEC stage itself.


问:
Adding StructFields to an existing schema
I created a class "Attribute". Each class object has a name, a datatype and a boolean value (nullable or not). All objects are saved to a ListBuffer.

I try to create a schema from the list and pass each value to the StructField(). Initiating works but unfortunately no further items are getting added to the schema.

```<code>def create_schema_from_attr_list(attr_list: ListBuffer[Attribute]): StructType = {
  // Get first list item and initiate schema
  var schema = StructType(StructField(attr_list(0).name, attr_list(0).data_type, attr_list(0).nullable) :: Nil)

  // Add remaining items
  for (i <- 1 until attr_list.length) {
    schema.add(attr_list(i).name, attr_list(i).data_type, attr_list(i).nullable)
    println("Test " + attr_list(i).name.toString())
  }
  return schema
}
</code>```

答:
The add method doesn't modify the schema in place. Think it a little bit like the string concatenation methods in Java.

You can make your code behave as you want by simply reassigning the result of the addition to schema itself:

```<code>def create_schema_from_attr_list(attr_list: ListBuffer[Attribute]): StructType = {

  // Get first list item and initiate schema
  var schema = StructType(StructField(attr_list(0).name, attr_list(0).data_type, attr_list(0).nullable) :: Nil)

  // Add remaining items
  for (i <- 1 until attr_list.length) {
    schema = schema.add(attr_list(i).name, attr_list(i).data_type, _list(i).nullable) // here
    println("Test " + attr_list(i).name.toString())
  }
  return schema

}
</code>```

Another solution, probably simpler, is to just process the items within the ListBuffer to make a StructField out of each attribute and pass the result directly to the StructType constructor (which accepts the ListBuffer's parent class Seq as a parameter).

```<code>def attributeToStructField(attr: Attribute): StructField =
  StructField(attr.name, attr.data_type, attr.nullable)

def attributesToSchema(attrs: ListBuffer[Attribute]): StructType =
  StructType(attrs.map(attributeToStructField))
</code>```

If you are not familiar with the map function: it's defined over all collections and takes a function A => B which turns a ListBuffer[A] into a ListBuffer[B] (or any other collection, for that matter). You'll encounter this kinds of higher-order functions all other the place in Scala and Spark.

ContentLicense: CC BY-SA 4.0

Body:
I created a class "Attribute". Each class object has a name, a datatype and a boolean value (nullable or not). All objects are saved to a ListBuffer.

I try to create a schema from the list and pass each value to the StructField(). Initiating works but unfortunately no further items are getting added to the schema.

def create_schema_from_attr_list(attr_list: ListBuffer[Attribute]): StructType = {
  // Get first list item and initiate schema
  var schema = StructType(StructField(attr_list(0).name, attr_list(0).data_type, attr_list(0).nullable) :: Nil)

  // Add remaining items
  for (i <- 1 until attr_list.length) {
    schema.add(attr_list(i).name, attr_list(i).data_type, attr_list(i).nullable)
    println("Test " + attr_list(i).name.toString())
  }
  return schema
}

Body:
The add method doesn't modify the schema in place. Think it a little bit like the string concatenation methods in Java.

You can make your code behave as you want by simply reassigning the result of the addition to schema itself:

def create_schema_from_attr_list(attr_list: ListBuffer[Attribute]): StructType = {

  // Get first list item and initiate schema
  var schema = StructType(StructField(attr_list(0).name, attr_list(0).data_type, attr_list(0).nullable) :: Nil)

  // Add remaining items
  for (i <- 1 until attr_list.length) {
    schema = schema.add(attr_list(i).name, attr_list(i).data_type, _list(i).nullable) // here
    println("Test " + attr_list(i).name.toString())
  }
  return schema

}

Another solution, probably simpler, is to just process the items within the ListBuffer to make a StructField out of each attribute and pass the result directly to the StructType constructor (which accepts the ListBuffer's parent class Seq as a parameter).

def attributeToStructField(attr: Attribute): StructField =
  StructField(attr.name, attr.data_type, attr.nullable)

def attributesToSchema(attrs: ListBuffer[Attribute]): StructType =
  StructType(attrs.map(attributeToStructField))

If you are not familiar with the map function: it's defined over all collections and takes a function A => B which turns a ListBuffer[A] into a ListBuffer[B] (or any other collection, for that matter). You'll encounter this kinds of higher-order functions all other the place in Scala and Spark.


问:
User Interface Design in Flex
I'm familiar with Actionscript and Flex. But when it comes to design the interface in Flex, I find myself that do not know where to start. I like to know what are the online resources/books to create the cool user interfaces like TweekDeck and Adobe Digital Edition.</p>

答:
Look into Flex Catalyst.  It is still green -- not nearly as capable as Expression Blend on the Silverlight side -- but it is a pretty good start.  Catalyst is the tool that designers can use to apply their Illustrator/Photoshop art to the skins in your app.

Unfortunately a lot is not skinnable via Catalyst.  It is also one-way at this time (the two-way beta is far from being useful IMO) which makes the Dev/Designer workflow cumbersome at best.  That being said, I have an amazing looking app based on work my designer is doing in Catalyst.  It takes some work to get it over into your app, but it can be done, and the results can be fantastic.

Title: User Interface Design in Flex


问:
DateTime.Now vs system time
Let's imagine that this little program runs:

```<code>while (true)
{
    Console.WriteLine($"{DateTime.UtcNow} -> {DateTime.Now} tz={TimeZone.CurrentTimeZone.StandardName} / {TimeZoneInfo.Local.StandardName}");
    await Task.Delay(TimeSpan.FromSeconds(1));
}
</code>```

When I change the system's time zone when the program is running the app does not see the change. The timezone and the time is as if the timezone has not changed.

In order for the app to display the new time and time zone I need to restart the app.

If I change the system time the time change is picked up immediately.

It would be great if you could help me with three questions:

is this documented anywhere?

why isn't the timezone change picked up while the application is running?

can I do anything so that the app picks up timezone changes while it's running?

Here's a little screenshot to show the .NET app using time different than the operating system:

BTW. On Windows IOT on Raspberry Pi, my experiment shows that if I restart the app it will show the new timezone, but the 'old' time. The new time will be picked up after restarting the the system.

答:
You can check the following msdn link. It clearly states the following :

Notes to Callers: Local time zone data is cached after CurrentTimeZone
  is first used to retrieve time zone information. If the system's local
  time zone subsequently changes, the CurrentTimeZone property does not
  reflect this change. If you need to handle time zone changes while
  your application is running, use the TimeZoneInfo class and call its
  TimeZoneInfo.ClearCachedData method.

is this documented anywhere?
Yes, as stated above.

why isn't the timezone change picked up while the application is running?
Because the timezone information is cached.

can I do anything so that the app picks up timezone changes while it's running?
Yes, by using the TimeZoneInfo class and calling its TimeZoneInfo.ClearCachedData method.

Title: DateTime.Now vs system time

Body:
Let's imagine that this little program runs:

while (true)
{
    Console.WriteLine($"{DateTime.UtcNow} -> {DateTime.Now} tz={TimeZone.CurrentTimeZone.StandardName} / {TimeZoneInfo.Local.StandardName}");
    await Task.Delay(TimeSpan.FromSeconds(1));
}

When I change the system's time zone when the program is running the app does not see the change. The timezone and the time is as if the timezone has not changed.

In order for the app to display the new time and time zone I need to restart the app.

If I change the system time the time change is picked up immediately.

It would be great if you could help me with three questions:

is this documented anywhere?

why isn't the timezone change picked up while the application is running?

can I do anything so that the app picks up timezone changes while it's running?

Here's a little screenshot to show the .NET app using time different than the operating system:

BTW. On Windows IOT on Raspberry Pi, my experiment shows that if I restart the app it will show the new timezone, but the 'old' time. The new time will be picked up after restarting the the system.


问:
How to store MySQL date in Javascript array?
I have searched over the Internet, there is a lot of way to store MySQL records into Javascript array though PHP, like this one. However I can't really store the date record in Javascript.

Let say,

My MySQL date record rows in column called holiday_date: 2017-06-25, 2017-06-26, 2017-06-27.

How can I store in Javascript after I converted them into json by

```<code><?php
    $sql = "SELECT public_holiday.holiday_date
            FROM public_holiday";
    $result = mysqli_query($conn, $sql);

    $result_array = Array();

    while($row = mysqli_fetch_assoc($result))
    {
         $result_array[] = $row;
    }

    $json_array = json_encode($result_array);

    echo $json_array;
  ?>
</code>```

?

I have tried to store them into a javascript date array like

```<code>var holidays = [<?php //sample array for example
        $loop_one = true;
        foreach ($result_array as $date)
        {
            if ($loop_one)
            {
                echo "'new Date(\'$date\')'";
                $loop_one=false;
            }
            else
            {
                echo ", 'new Date(\'$date\')'";
            }
        }
?>];
</code>```

but all of these are invalid.

I need your help, much appreciated.

答:
To get a javaScript date object array you need to change your script code only no need to change the PHP code.

You can use JSON.parse and forEach loop.

Try like this

```<code><script>
    var holidays = '<?php  echo $json_array;?>';
    holidays=JSON.parse(holidays);
    var holidayArray=[];
    holidays.forEach(function (key) {
        holidayArray.push(new Date(key));
    });
    console.log(holidays);
    console.log(holidayArray);
</script>
</code>```

It will produce an out put as

I thing it will help you.

Body:
I have searched over the Internet, there is a lot of way to store MySQL records into Javascript array though PHP, like this one. However I can't really store the date record in Javascript.

Let say,

My MySQL date record rows in column called holiday_date: 2017-06-25, 2017-06-26, 2017-06-27.

How can I store in Javascript after I converted them into json by

<?php
    $sql = "SELECT public_holiday.holiday_date
            FROM public_holiday";
    $result = mysqli_query($conn, $sql);

    $result_array = Array();

    while($row = mysqli_fetch_assoc($result))
    {
         $result_array[] = $row;
    }

    $json_array = json_encode($result_array);

    echo $json_array;
  ?>

?

I have tried to store them into a javascript date array like

var holidays = [<?php //sample array for example
        $loop_one = true;
        foreach ($result_array as $date)
        {
            if ($loop_one)
            {
                echo "'new Date(\'$date\')'";
                $loop_one=false;
            }
            else
            {
                echo ", 'new Date(\'$date\')'";
            }
        }
?>];

but all of these are invalid.

I need your help, much appreciated.

Body:
To get a javaScript date object array you need to change your script code only no need to change the PHP code.

You can use JSON.parse and forEach loop.

Try like this

<script>
    var holidays = '<?php  echo $json_array;?>';
    holidays=JSON.parse(holidays);
    var holidayArray=[];
    holidays.forEach(function (key) {
        holidayArray.push(new Date(key));
    });
    console.log(holidays);
    console.log(holidayArray);
</script>

It will produce an out put as

I thing it will help you.


问:
RegEx for alphanumeric and some certain special characters
I am trying to allow English alphabets, numeric values  and the following characters only:

- # $ % & * ( ) [ ] , . / - _ +

I have managed to come up with the following code

```<code><form id="accountForm" action="">
   <input type="text" name="my_input">
</form>

$(function() {

    $.validator.addMethod("accept", function(value, element, param) {
        return value.match(new RegExp("." + param + "$"));
    }, 'Only English is allowed');

    $( "#accountForm" ).validate({
        rules: {
            my_input : {
                required: true,
                accept: '[a-zA-Z0-9@%#&()/+*$,._\\-]+$'
            }

        }
    });
 });
</code>```

But there are some problems :

If I try to add [ ] the code completely stops working

If I add other characters that or not in the list above, after any alphabets it does not show any error message. Example : ABC你好

If I enter just a letter it gives an error.

Here's a demo of my code: https://jsfiddle.net/w2p1rdbd/1/

Could you please show me how to fix this?

Thank you very much!

答:
I don't see any need for manipulating the regex in the accept method. ( The new RegExp("." + param + "$")). This will make your regexend up like .[a-zA-Z0-9@%#&()/+*$,._\\-]+$$.

And the start of the line should be anchored with a ^ (matching the start of the string) to disallow foreign characters in the beginning.

I removed the . and $ in your example, added the ^ to the "original" regex (ending up with ^[a-zA-Z0-9@%#&()/+*$,._\\-]+$) and it appears to be working.

Your code modified:

$(function() {

        $.validator.addMethod("accept", function(value, element, param) {
            return value.match(new RegExp(param));
        }, 'Only English is allowed');

        $( "#accountForm" ).validate({
            rules: {
                my_input : {
                    required: true,
                    accept: '^[a-zA-Z0-9@%#&()/+*$,._\\-]+$'
                }
            }
        });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>

<form id="accountForm" action="">
<input type="text" name="my_input">
</form></code>```

Body:
I am trying to allow English alphabets, numeric values  and the following characters only:

- # $ % & * ( ) [ ] , . / - _ +

I have managed to come up with the following code

<form id="accountForm" action="">
   <input type="text" name="my_input">
</form>

$(function() {

    $.validator.addMethod("accept", function(value, element, param) {
        return value.match(new RegExp("." + param + "$"));
    }, 'Only English is allowed');

    $( "#accountForm" ).validate({
        rules: {
            my_input : {
                required: true,
                accept: '[a-zA-Z0-9@%#&()/+*$,._\\-]+$'
            }

        }
    });
 });

But there are some problems :

If I try to add [ ] the code completely stops working

If I add other characters that or not in the list above, after any alphabets it does not show any error message. Example : ABC你好

If I enter just a letter it gives an error.

Here's a demo of my code: https://jsfiddle.net/w2p1rdbd/1/

Could you please show me how to fix this?

Thank you very much!

Body:
I don't see any need for manipulating the regex in the accept method. ( The new RegExp("." + param + "$")). This will make your regexend up like .[a-zA-Z0-9@%#&()/+*$,._\\-]+$$.

And the start of the line should be anchored with a ^ (matching the start of the string) to disallow foreign characters in the beginning.

I removed the . and $ in your example, added the ^ to the "original" regex (ending up with ^[a-zA-Z0-9@%#&()/+*$,._\\-]+$) and it appears to be working.

Your code modified:

$(function() {

        $.validator.addMethod("accept", function(value, element, param) {
            return value.match(new RegExp(param));
        }, 'Only English is allowed');

        $( "#accountForm" ).validate({
            rules: {
                my_input : {
                    required: true,
                    accept: '^[a-zA-Z0-9@%#&()/+*$,._\\-]+$'
                }
            }
        });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>

<form id="accountForm" action="">
<input type="text" name="my_input">
</form>


问:
how to manage ui in nexus 4 and 6
I am a developer and I am recently facing  a issue that the client want the images and buttons in exact same place in all the android devices such as: Motorola, nexus 4, nexus 6, nexus 5. When i develop the user interface  it changes its position as the device changes. I have 70 user interface screens , I cannot create multiple screens, and Dimensions layout also. I tried with weight and relative layout, constraint layout but the problem is same.

Edit: Images of how it looks on a Nexus 6 emulator and Nexus 4 emulator

http://imgur.com/a/96WaV

答:
So There are two ways to make your app compatible with all devices.

Option one

You have to create all images(slices) used in your app with compatible of all dimens(mdpi,hdpi, xhdpi, xxhdpi and xxxhdpi).

to check out resolutions and size of all devices, you can go here for reference Device List.

Option two

You have to create only xxhdpi images and manage it with dimens of mdpi,hdpi, xhdpi, xxhdpi and xxxhdpi (it is not proper way but can help you).

There is good library for all dimens that you can use. All Dimens Lib

Title: how to manage ui in nexus 4 and 6


问:
losing fields during validation - nested serializer create()
I don't understand why specific fields are being dropped within validated_data.

When POSTing input to create() a new instance, the following line:
thisLabel = ClassificationLabel.objects.get(identifier=label.identifier)
 throws an error because the identifier attribute is not present:

```<code>AttributeError at /api/v1/policies/
</code>```

'collections.OrderedDict' object has no attribute 'identifier

I have the following serializers within Django REST framework:

serializers.py:

```<code>class ClassificationLabelDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = ClassificationLabel
        fields = ('displayName', 'helpText', 'identifier', 'backgroundColour', 'foregroundColour', 'comment', 'description', 'lastChanged', 'revision')
        read_only_fields = ('identifier', 'lastChanged', 'revision',)

class PolicySerializer(serializers.ModelSerializer):
    labels = ClassificationLabelDetailSerializer(many=True)

    class Meta:
        model = Policy
        fields = ('displayName', 'identifier', 'labels', 'lastChanged', 'description', 'comment')
        read_only_fields = ('identifier', 'lastChanged',)

    def create(self,validated_data):
        labelData = validated_data.pop('labels')
        thisPolicy = Policy.objects.create(**validated_data)
        for label in labelData:
            for k, v in label.items():
                print(k, v)
            thisLabel = ClassificationLabel.objects.get(identifier=label.identifier)#insert organisational filter here
            PolicyMemberClassificationLabel.objects.create(policy=thisPolicy, label=thisLabel, order=index)
        return thisPolicy
</code>```

models.py:

```<code>class ClassificationLabel(models.Model):
    displayName = models.CharField(max_length = 32)
    helpText = models.TextField(max_length = 140, blank=True)
    backgroundColour = models.CharField(max_length=8)
    foregroundColour = models.CharField(max_length=8)
    description = models.TextField(max_length = 256, blank=True)
    comment = models.TextField(max_length = 1024, blank=True)
    lastChanged = models.DateTimeField(auto_now=True, editable=False)
    identifier = models.CharField(max_length = 128, blank=True, editable=False)
    revision = models.PositiveIntegerField(default=1, editable=False)

    def __str__(self):
        return self.displayName + " - " + self.identifier

    def save(self, *args, **kwargs):
        self.revision += 1
        #the following code generates a unique identifier and checks it for collisions against existing identifiers
        if not self.identifier:
            stringCheck = False
            while stringCheck is False:
                newString = str(uuid.uuid4())
                newString.replace('-', '')
                doesStringExist = ClassificationLabel.objects.filter(identifier=newString).exists()
                if doesStringExist is False:
                    stringCheck = True
            self.identifier = newString
        super(ClassificationLabel, self).save(*args, **kwargs) # Call the "real" save() method.

class Policy(models.Model):
    description = models.TextField(max_length = 256, blank=True)
    comment = models.TextField(max_length = 1024, blank=True)
    lastChanged = models.DateTimeField(auto_now =True)
    displayName = models.CharField(max_length = 64)
    identifier = models.CharField(max_length = 128, blank=True)
    labels = models.ManyToManyField(ClassificationLabel, through='PolicyMemberClassificationLabel')
    revision = models.PositiveIntegerField(default=1)

    class Meta:
        verbose_name_plural = 'Policies'

    def __str__(self):
        return self.displayName + " - " + self.identifier

    def save(self, *args, **kwargs):
        self.revision += 1
        #the following code generates a unique identifier and checks it for collisions against existing identifiers
        if not self.identifier:
            stringCheck = False
            while stringCheck is False:
                newString = str(uuid.uuid4())
                newString.replace('-', '')
                doesStringExist = Policy.objects.filter(identifier=newString).count()
                if doesStringExist == 0:
                    stringCheck = True
            self.identifier = newString
            super(Policy, self).save() # Call the "real" save() method.

class PolicyMemberClassificationLabel(models.Model):
    label = models.ForeignKey(ClassificationLabel, related_name='memberLabels')
    policy = models.ForeignKey(Policy, related_name='parentPolicy')
    order = models.PositiveSmallIntegerField(blank=True)
</code>```

when sending the following via POST it's dropping the identifier, lastChanged and revision fields from the nested representation within validated_data.

```<code>{
  "labels": [
    {
      "displayName": "Test name",
      "helpText": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book. Wayfarers sartorial authentic, small batch readymade disrupt col",
      "identifier": "fa27e9bd-5007-4874-b10c-46b63c7c8a86",
      "backgroundColour": "#808900",
      "foregroundColour": "#000000",
      "comment": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "description": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "lastChanged": "2017-07-03T09:26:20.450681Z",
      "revision": 2
    },
    {
      "displayName": "Test name 1",
      "helpText": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "identifier": "29c968dd-8b83-4374-962d-32b9ef527e1b",
      "backgroundColour": "#9f0500",
      "foregroundColour": "#FFFFFF",
      "comment": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "description": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "lastChanged": "2017-07-03T09:25:52.955293Z",
      "revision": 2
    }
  ]
}
</code>```

I can see that the serializer .is_valid() is True for the PolicySerializer

when I look at validated_data those three fields are missing (the rest are there)

I've tried commenting out the read_only_fields and that doesn't seem to make any difference

I've been referencing the DRF documentation here

I've ensured that the client's content-type is set correctly, since there was a similar problem here

other people seem to be having similar problems

My question: How do I get the identifier field within the validated_data of the nested representation?

答:
In ClassificationLabelDetailSerializer you have set identifier as a read_only field, and the documentation states:

Read-only fields are included in the API output, but should not be
   included in the input during create or update operations.

This means they do not get passed to validated_data as they should not be used for write operations.

Remove identifier from the read_only fields and it should work. If you need that serializer elsewhere with identifier as read_only, you should then create another serializer for the nested labels.

Body:
I don't understand why specific fields are being dropped within validated_data.

When POSTing input to create() a new instance, the following line:
thisLabel = ClassificationLabel.objects.get(identifier=label.identifier)
 throws an error because the identifier attribute is not present:

AttributeError at /api/v1/policies/

'collections.OrderedDict' object has no attribute 'identifier

I have the following serializers within Django REST framework:

serializers.py:

class ClassificationLabelDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = ClassificationLabel
        fields = ('displayName', 'helpText', 'identifier', 'backgroundColour', 'foregroundColour', 'comment', 'description', 'lastChanged', 'revision')
        read_only_fields = ('identifier', 'lastChanged', 'revision',)

class PolicySerializer(serializers.ModelSerializer):
    labels = ClassificationLabelDetailSerializer(many=True)

    class Meta:
        model = Policy
        fields = ('displayName', 'identifier', 'labels', 'lastChanged', 'description', 'comment')
        read_only_fields = ('identifier', 'lastChanged',)

    def create(self,validated_data):
        labelData = validated_data.pop('labels')
        thisPolicy = Policy.objects.create(**validated_data)
        for label in labelData:
            for k, v in label.items():
                print(k, v)
            thisLabel = ClassificationLabel.objects.get(identifier=label.identifier)#insert organisational filter here
            PolicyMemberClassificationLabel.objects.create(policy=thisPolicy, label=thisLabel, order=index)
        return thisPolicy

models.py:

class ClassificationLabel(models.Model):
    displayName = models.CharField(max_length = 32)
    helpText = models.TextField(max_length = 140, blank=True)
    backgroundColour = models.CharField(max_length=8)
    foregroundColour = models.CharField(max_length=8)
    description = models.TextField(max_length = 256, blank=True)
    comment = models.TextField(max_length = 1024, blank=True)
    lastChanged = models.DateTimeField(auto_now=True, editable=False)
    identifier = models.CharField(max_length = 128, blank=True, editable=False)
    revision = models.PositiveIntegerField(default=1, editable=False)

    def __str__(self):
        return self.displayName + " - " + self.identifier

    def save(self, *args, **kwargs):
        self.revision += 1
        #the following code generates a unique identifier and checks it for collisions against existing identifiers
        if not self.identifier:
            stringCheck = False
            while stringCheck is False:
                newString = str(uuid.uuid4())
                newString.replace('-', '')
                doesStringExist = ClassificationLabel.objects.filter(identifier=newString).exists()
                if doesStringExist is False:
                    stringCheck = True
            self.identifier = newString
        super(ClassificationLabel, self).save(*args, **kwargs) # Call the "real" save() method.

class Policy(models.Model):
    description = models.TextField(max_length = 256, blank=True)
    comment = models.TextField(max_length = 1024, blank=True)
    lastChanged = models.DateTimeField(auto_now =True)
    displayName = models.CharField(max_length = 64)
    identifier = models.CharField(max_length = 128, blank=True)
    labels = models.ManyToManyField(ClassificationLabel, through='PolicyMemberClassificationLabel')
    revision = models.PositiveIntegerField(default=1)

    class Meta:
        verbose_name_plural = 'Policies'

    def __str__(self):
        return self.displayName + " - " + self.identifier

    def save(self, *args, **kwargs):
        self.revision += 1
        #the following code generates a unique identifier and checks it for collisions against existing identifiers
        if not self.identifier:
            stringCheck = False
            while stringCheck is False:
                newString = str(uuid.uuid4())
                newString.replace('-', '')
                doesStringExist = Policy.objects.filter(identifier=newString).count()
                if doesStringExist == 0:
                    stringCheck = True
            self.identifier = newString
            super(Policy, self).save() # Call the "real" save() method.

class PolicyMemberClassificationLabel(models.Model):
    label = models.ForeignKey(ClassificationLabel, related_name='memberLabels')
    policy = models.ForeignKey(Policy, related_name='parentPolicy')
    order = models.PositiveSmallIntegerField(blank=True)

when sending the following via POST it's dropping the identifier, lastChanged and revision fields from the nested representation within validated_data.

{
  "labels": [
    {
      "displayName": "Test name",
      "helpText": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book. Wayfarers sartorial authentic, small batch readymade disrupt col",
      "identifier": "fa27e9bd-5007-4874-b10c-46b63c7c8a86",
      "backgroundColour": "#808900",
      "foregroundColour": "#000000",
      "comment": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "description": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "lastChanged": "2017-07-03T09:26:20.450681Z",
      "revision": 2
    },
    {
      "displayName": "Test name 1",
      "helpText": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "identifier": "29c968dd-8b83-4374-962d-32b9ef527e1b",
      "backgroundColour": "#9f0500",
      "foregroundColour": "#FFFFFF",
      "comment": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "description": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "lastChanged": "2017-07-03T09:25:52.955293Z",
      "revision": 2
    }
  ]
}

I can see that the serializer .is_valid() is True for the PolicySerializer

when I look at validated_data those three fields are missing (the rest are there)

I've tried commenting out the read_only_fields and that doesn't seem to make any difference

I've been referencing the DRF documentation here

I've ensured that the client's content-type is set correctly, since there was a similar problem here

other people seem to be having similar problems

My question: How do I get the identifier field within the validated_data of the nested representation?


问:
inter processes shared memory and pthread_barrier: how to be safe?
I wanted a simple solution for inter processes barrier. Here a solution: solution

But I am totally lost with mmap... With my first try, it fails one out of ten times (segfault or deadlock).

I understand my problem comes from a synchronization issue, but I can't find it. I found an example to set up mmaped memory (example), but I am not sure it is good for a mmaped pthread_barrier.

Here an extract of my code:

```<code>#define MMAP_FILE "/tmp/mmapped_bigdft.bin"

void init_barrier() {
  pthread_barrier_t *shared_mem_barrier;
  pthread_barrierattr_t barattr;
  pthread_barrierattr_setpshared(&barattr, PTHREAD_PROCESS_SHARED);

  hbcast_fd = open(MMAP_FILE, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
  result = lseek(hbcast_fd, sizeof(pthread_barrier_t)-1, SEEK_SET);
  result = write(hbcast_fd, "", 1);
  shared_mem_barrier = (pthread_barrier_t*) mmap(0, sizeof(pthread_barrier_t), PROT_READ | PROT_WRITE, MAP_SHARED, hbcast_fd, 0);
  if (mpi_rank == 0) {
    int err = pthread_barrier_init(shared_mem_barrier, &barattr, host_size);
  }
  MPI_Barrier(some_communicator);
}
</code>```

Questions:

do I miss something in mmap initialization?

which operation should be performed by all processes, and which should be by only one?

New question

Which is safier for managing pthread barrier? Or are they based on the same mechanism?

shmget

shm_open

mmap

another one

答:
You don't want to open the file with O_TRUNC for every process. Every time you do that, you'll truncate the file again and potentially invalidate the previous mmap operations you've performed (the affect on previous mmap's when changing the file size is generally undefined).

That aside, I don't think you can have a semaphore in a mmap'd memory and have it function correctly (it may on some OS platforms, so I doubt it's generally guaranteed to function the way you want).

What you really want to use is shared memory. Do man on " shmget" and "shmat" to learn how to create and map shared memory. You'll probably still need a file to pass the shared memory ID around, and you should be careful about freeing a shared memory ID during application crashes by registering signal handlers. Otherwise you can leave zombie shared memory allocations sitting around and overrun your OS resource limits. You'll know that happened if you get ENOSPC when attempting to create the shared memory segment on your master thread.

Body:
I wanted a simple solution for inter processes barrier. Here a solution: solution

But I am totally lost with mmap... With my first try, it fails one out of ten times (segfault or deadlock).

I understand my problem comes from a synchronization issue, but I can't find it. I found an example to set up mmaped memory (example), but I am not sure it is good for a mmaped pthread_barrier.

Here an extract of my code:

#define MMAP_FILE "/tmp/mmapped_bigdft.bin"

void init_barrier() {
  pthread_barrier_t *shared_mem_barrier;
  pthread_barrierattr_t barattr;
  pthread_barrierattr_setpshared(&barattr, PTHREAD_PROCESS_SHARED);

  hbcast_fd = open(MMAP_FILE, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
  result = lseek(hbcast_fd, sizeof(pthread_barrier_t)-1, SEEK_SET);
  result = write(hbcast_fd, "", 1);
  shared_mem_barrier = (pthread_barrier_t*) mmap(0, sizeof(pthread_barrier_t), PROT_READ | PROT_WRITE, MAP_SHARED, hbcast_fd, 0);
  if (mpi_rank == 0) {
    int err = pthread_barrier_init(shared_mem_barrier, &barattr, host_size);
  }
  MPI_Barrier(some_communicator);
}

Questions:

do I miss something in mmap initialization?

which operation should be performed by all processes, and which should be by only one?

New question

Which is safier for managing pthread barrier? Or are they based on the same mechanism?

shmget

shm_open

mmap

another one


问:
How to use ldapsearch on a Domain Name instead of a specific host
I have a bash script that runs ldapsearch with no problems except it points to a DC that is sometimes not available.

The script uses a -h (for host) option to point to a specific Domain Controller (DC). I would like to point to the domain name instead so that it will still execute in case that particular DC is down.

Example

In our environment, we have 20 DC's under my.company.com. So my ldapsearch query uses the the 1st DC in Bldg 1 with the following option which works:

```<code>-H ldaps://bldg1dc01.my.company.com:636
</code>```

If bldg1dc01 is down, the script will not execute. So I'd like to point the script to something like:

```<code>-H ldaps://my.company.com:636
</code>```

But when I do that, I get:

```<code>ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1)
</code>```

What is the syntax to query the domain name (my.company.com) instead of the specific DC, that way my script works even if that DC is down?

答:
EDIT :

After further researches, I looked at the ldapsearch command as I did not know the possibility to provide multiple URI.

The man states (for the ldap-utils package command) :

Specify URI(s) referring to the ldap server(s); a list of URI,
  separated by whitespace or commas is expected; only the
  protocol/host/port fields are allowed. As an exception, if no
  host/port is specified, but a DN is, the DN is used to look up the
  corresponding host(s) using the DNS SRV records, according to RFC
  2782. The DN must be a non-empty sequence of AVAs whose attribute type is "dc" (domain component), and must be escaped according to RFC 2396.

So there is the possibility to use DNS result to make the ldapsearch.

Example with google.com :

```<code>#  dig -t srv _ldaps._tcp.google.com +short
5 0 636 ldap.google.com.
</code>```

So if I do the search with (escaping the URI) :

```<code># ldapsearch -H ldaps:///dc%3Dgoogle%2Cdc%3Dcom -v
ldap_initialize( ldaps://ldap.google.com:636 )
^C
</code>```

So the command is able to look for DNS SRV records

My bad asserting what I believed was the only way to do it without further research

Not relevant, but the informations could be used in case no DNS reccords is available

There is no problem with your syntax. This is a misunderstanding of what the ldapsearch does and what LDAP is.

LDAP is a protocol, ldapsearch command is a client which communicates implementing this protocol.

It is the same as saying I try to connect to https://my.company.com on port 443 and it doesn't work, but when I do it on https://web01.my.company.com it works.

You need to have something listening on port 443 on my.company.com and load-balances/proxies the requests.

It is the same for LDAP.

Body:
I have a bash script that runs ldapsearch with no problems except it points to a DC that is sometimes not available.

The script uses a -h (for host) option to point to a specific Domain Controller (DC). I would like to point to the domain name instead so that it will still execute in case that particular DC is down.

Example

In our environment, we have 20 DC's under my.company.com. So my ldapsearch query uses the the 1st DC in Bldg 1 with the following option which works:

-H ldaps://bldg1dc01.my.company.com:636

If bldg1dc01 is down, the script will not execute. So I'd like to point the script to something like:

-H ldaps://my.company.com:636

But when I do that, I get:

ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1)

What is the syntax to query the domain name (my.company.com) instead of the specific DC, that way my script works even if that DC is down?

Body:
EDIT :

After further researches, I looked at the ldapsearch command as I did not know the possibility to provide multiple URI.

The man states (for the ldap-utils package command) :

Specify URI(s) referring to the ldap server(s); a list of URI,
  separated by whitespace or commas is expected; only the
  protocol/host/port fields are allowed. As an exception, if no
  host/port is specified, but a DN is, the DN is used to look up the
  corresponding host(s) using the DNS SRV records, according to RFC
  2782. The DN must be a non-empty sequence of AVAs whose attribute type is "dc" (domain component), and must be escaped according to RFC 2396.

So there is the possibility to use DNS result to make the ldapsearch.

Example with google.com :

#  dig -t srv _ldaps._tcp.google.com +short
5 0 636 ldap.google.com.

So if I do the search with (escaping the URI) :

# ldapsearch -H ldaps:///dc%3Dgoogle%2Cdc%3Dcom -v
ldap_initialize( ldaps://ldap.google.com:636 )
^C

So the command is able to look for DNS SRV records

My bad asserting what I believed was the only way to do it without further research

Not relevant, but the informations could be used in case no DNS reccords is available

There is no problem with your syntax. This is a misunderstanding of what the ldapsearch does and what LDAP is.

LDAP is a protocol, ldapsearch command is a client which communicates implementing this protocol.

It is the same as saying I try to connect to https://my.company.com on port 443 and it doesn't work, but when I do it on https://web01.my.company.com it works.

You need to have something listening on port 443 on my.company.com and load-balances/proxies the requests.

It is the same for LDAP.


问:
Troubleshooting ssh key for gitlab clone/push/pull
I've tried following solutions, so I did generated new ssh key for my gitlab account, when I do ssh -v git@gitlab.com I've got Permissions denied (publickey)..

Second solution is Working with non-default SSH key pair paths, so I've generated new key for that and my ~/.ssh/config is looking like this

```<code>  # GitLab.com server
  Host gitlab.com
  RSAAuthentication yes
  IdentityFile ~/.ssh/id_rsa_gitlab.pub
</code>```

Both key's are added to my gitlab account, and when I try to troubleshoot ssh with:
ssh -i ~/.ssh/id_rsa_gitlab.pub -p 122 git@gitlab.com I've got nothing, literally when I type that to the terminal nothing is happening, and when I type shh -vvv git@gitlab.com the result is this:

```<code>  OpenSSH_7.2p2 Ubuntu-4ubuntu2.2, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /home/petar/.ssh/config
debug1: /home/petar/.ssh/config line 2: Applying options for gitlab.com
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "gitlab.com" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to gitlab.com [52.167.219.168] port 22.
debug1: Connection established.
debug1: identity file /home/petar/.ssh/id_rsa_gitlab.pub type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/petar/.ssh/id_rsa_gitlab.pub-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.2 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to gitlab.com:22 as 'git'
debug3: hostkeys_foreach: reading file "/home/petar/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/petar/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from gitlab.com
debug3: order_hostkeyalgs: prefer hostkeyalgs: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw
debug3: hostkeys_foreach: reading file "/home/petar/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/petar/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from gitlab.com
debug3: hostkeys_foreach: reading file "/home/petar/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/petar/.ssh/known_hosts:4
debug3: load_hostkeys: loaded 1 keys from 52.167.219.168
debug1: Host 'gitlab.com' is known and matches the ECDSA host key.
debug1: Found key in /home/petar/.ssh/known_hosts:3
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS received
debug2: key: /home/petar/.ssh/id_rsa_gitlab.pub (0x562dd6bb8c80), explicit, agent
debug2: key: ppilipovic84@gmail.com (0x562dd6bbde10), agent
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/petar/.ssh/id_rsa_gitlab.pub
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug1: Offering RSA public key: ppilipovic84@gmail.com
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).
</code>```

Can someone please explain me how to fix this?

答:
The IdentityFile should point to the private key, not to the public key:

```<code> IdentityFile ~/.ssh/id_rsa_gitlab
</code>```

Body:
I've tried following solutions, so I did generated new ssh key for my gitlab account, when I do ssh -v git@gitlab.com I've got Permissions denied (publickey)..

Second solution is Working with non-default SSH key pair paths, so I've generated new key for that and my ~/.ssh/config is looking like this

  # GitLab.com server
  Host gitlab.com
  RSAAuthentication yes
  IdentityFile ~/.ssh/id_rsa_gitlab.pub

Both key's are added to my gitlab account, and when I try to troubleshoot ssh with:
ssh -i ~/.ssh/id_rsa_gitlab.pub -p 122 git@gitlab.com I've got nothing, literally when I type that to the terminal nothing is happening, and when I type shh -vvv git@gitlab.com the result is this:

  OpenSSH_7.2p2 Ubuntu-4ubuntu2.2, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /home/petar/.ssh/config
debug1: /home/petar/.ssh/config line 2: Applying options for gitlab.com
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "gitlab.com" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to gitlab.com [52.167.219.168] port 22.
debug1: Connection established.
debug1: identity file /home/petar/.ssh/id_rsa_gitlab.pub type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/petar/.ssh/id_rsa_gitlab.pub-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.2 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to gitlab.com:22 as 'git'
debug3: hostkeys_foreach: reading file "/home/petar/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/petar/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from gitlab.com
debug3: order_hostkeyalgs: prefer hostkeyalgs: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw
debug3: hostkeys_foreach: reading file "/home/petar/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/petar/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from gitlab.com
debug3: hostkeys_foreach: reading file "/home/petar/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/petar/.ssh/known_hosts:4
debug3: load_hostkeys: loaded 1 keys from 52.167.219.168
debug1: Host 'gitlab.com' is known and matches the ECDSA host key.
debug1: Found key in /home/petar/.ssh/known_hosts:3
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS received
debug2: key: /home/petar/.ssh/id_rsa_gitlab.pub (0x562dd6bb8c80), explicit, agent
debug2: key: ppilipovic84@gmail.com (0x562dd6bbde10), agent
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/petar/.ssh/id_rsa_gitlab.pub
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug1: Offering RSA public key: ppilipovic84@gmail.com
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).

Can someone please explain me how to fix this?

Body:
The IdentityFile should point to the private key, not to the public key:

 IdentityFile ~/.ssh/id_rsa_gitlab


答:
looks like MySQL DATETIME - Change only the date

```<code>UPDATE tabelname
SET colname = CONCAT(DATE(colname), ' ', 7, DATE_FORMAT(colname, ':%i:%s'))
WHERE id = 123;
</code>```

Where 7 stands for the new hour you want for this record's datetime column

Title: How to update only the hour from a DATETIME field in MySQL?

Body:
I want to update a DateTime column where it will change the hours only without modifying anything else. I can't use to add an interval as the values all are different. There is many different dates too. So need to change the hour of exact desired date as where condition.

Ex:

*************************************************
**        Before       *|*         After       **
************************|************************
** 2017-07-24 19:06:15 *|* 2017-07-24 15:06:15 **
** 2017-07-24 17:12:23 *|* 2017-07-24 15:12:23 **
** 2017-07-24 23:00:03 *|* 2017-07-24 15:00:03 **
** 2017-07-24 20:33:56 *|* 2017-07-24 15:33:56 **
** 2017-07-24 18:19:31 *|* 2017-07-24 15:19:31 **
** 2017-07-24 16:43:47 *|* 2017-07-24 15:43:47 **
*************************************************

Want to do it with MySQL query only without using any programming language.

Body:
looks like MySQL DATETIME - Change only the date

UPDATE tabelname
SET colname = CONCAT(DATE(colname), ' ', 7, DATE_FORMAT(colname, ':%i:%s'))
WHERE id = 123;

Where 7 stands for the new hour you want for this record's datetime column


问:
Match width of items in a loop with javascript or jQuery
I made a function to match the width of some elements in a loop where they will expand themselves up to the maximum wide element.

```<code>// Function: Match width
var _so20170704_match_width = function( item ) {
    var max_item_width = 0;

    item.each(function(index) {
        max_item_width = Math.max( max_item_width, parseInt( $(this).width() ) );
    });

    // might not necessary
    // but taking time, to keep the elements' default width intact
    // while looping through 'em
    setTimeout(function() {
        item.width(max_item_width);
    }, 100);
}
</code>```

I called it like below:

```<code>_so20170704_match_width( $('.match-width') );
</code>```

It's working just as expected.

Problem

Problem is, not all the page refresh is okay. On some page refreshes the .width() somehow behaving like it's taking the .outerWidth() or like so. Because the set width's working a bit wider.

With a console.log($(this).width()) and console.log(max_item_width) the values I got are like below:

```
+====================+=======+
|                ×   |   ✓   |
+====================+=======+
| this_item:    177  |  152  |
| max_width:    177  |  152  |
+--------------------+-------+
| this_item:    174  |  150  |
| max_width:    177  |  152  |
+--------------------+-------+
| this_item:    229  |  196  |
| max_width:    229  |  196  |
+--------------------+-------+
| this_item:    265  |  232  |
| max_width:    265  |  232  |
+====================+=======+
| max_width:    265  |  232  |
+====================+=======+
```

Here, × denotes "Not working width identification", and ✓ denotes "Working width identification".

Why the .width() is varying on the same element on some of the page refresh? If I press Ctrl + F5 to clear cache and refresh, it's a ×. And after that, if I continuously refresh the page with F5 only, it's a ✓. I kept the page idle for some time, then I pressed F5, but it's a ×.

Why?

What I tried

It's even behaving the same whether I change the calculation to a manual one:

```<code>if( parseInt( $(this).width() ) > max_item_width ) {
    max_item_width = parseInt( $(this).width() );
}
</code>```

And I also took time setting the width by replacing 100 with 1000, but the behavior is same.

Edit: Fiddle

jQuery(document).ready(function($) {

  // Function: Match width
  var _so20170704_match_width = function(item) {
    var max_item_width = 0;

    item.each(function(index) {
      max_item_width = Math.max(max_item_width, parseInt($(this).width()));
    });

    // might not necessary
    // but taking time, to keep the elements' default width intact
    // while looping through 'em
    setTimeout(function() {
      item.width(max_item_width);
    }, 100);
  }

  _so20170704_match_width($('.package-title'));

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*,
 :after,
 :before {
  box-sizing: border-box;
}

body {
  font-family: 'Roboto Condensed', Arial, Helvetica, sans-serif;
  font-size: 14px;
  line-height: 1.428571429;
  color: #333;
}

h2 {
  margin-top: 20px;
  margin-bottom: 10px;
  font-weight: 500;
  line-height: 1.1;
}

.package-title {
  color: #fff;
  background-color: #414142;
  border: 1px solid #fed307;
  border-radius: 10px;
  padding: 1px 15px 13px;
  display: inline-block;
  position: relative;
  font-size: 28px;
  z-index: 9;
}

.package-subtitle {
  display: block;
  position: absolute;
  bottom: 0;
  left: 100px;
  padding: 1px 5px;
  font-size: 14px;
  background-color: #fed307;
  color: #414142;
  font-family: 'Roboto Condensed', Arial, Helvetica, sans-serif;
  font-weight: 400;
}</code>```

<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed|Roboto:700" rel="stylesheet">

Package 1 TitlePackage 1 Subtitle

Package 2Package 2 Subtitle

Package 3 TtlPackage 3 Subtitle

Package 4 Title LargerPackage 4 Subtitle

```

Suspect: Embedded Font

While making the fiddle, I suspected that, the font embedding might causing the issue. I tried, disabling all the @font-face declarations in my code, and then when I's refreshing (by any ways) it's performing perfect.

So the issue noted is:

On cache clear the font embed refreshes itself and the jQuery function detects the widths with default fonts (width: 265 confirmed with default font). But then the condensed embedded font loaded up, and the width shrunken a bit. And that's causing the issue.

答:
Okay, while making the Fiddle after the suggestion of @MehulJoshi, I suspected that, the embedded condensed font's causing the issue. So I's looking for a way to check whether all the fonts are loaded or not.

With the help of this StackOverflow thread I changed the following line of code:

```<code>_so20170704_match_width( $('.match-width') );
</code>```

with the code below:

```<code>document.fonts.ready.then(function () {
    _so20170704_match_width( $('.match-width') );
});
</code>```

Please read the attached SO thread before using this. It's a new feature, and works Chrome 35+ and Firefox 41+.

The way to solve the issue is:

When all the embedded fonts are ready (this is crucial)

Check for widths

Get the max width

Set the max width

Body:
I made a function to match the width of some elements in a loop where they will expand themselves up to the maximum wide element.

// Function: Match width
var _so20170704_match_width = function( item ) {
    var max_item_width = 0;

    item.each(function(index) {
        max_item_width = Math.max( max_item_width, parseInt( $(this).width() ) );
    });

    // might not necessary
    // but taking time, to keep the elements' default width intact
    // while looping through 'em
    setTimeout(function() {
        item.width(max_item_width);
    }, 100);
}

I called it like below:

_so20170704_match_width( $('.match-width') );

It's working just as expected.

Problem

Problem is, not all the page refresh is okay. On some page refreshes the .width() somehow behaving like it's taking the .outerWidth() or like so. Because the set width's working a bit wider.

With a console.log($(this).width()) and console.log(max_item_width) the values I got are like below:

+====================+=======+
|                ×   |   ✓   |
+====================+=======+
| this_item:    177  |  152  |
| max_width:    177  |  152  |
+--------------------+-------+
| this_item:    174  |  150  |
| max_width:    177  |  152  |
+--------------------+-------+
| this_item:    229  |  196  |
| max_width:    229  |  196  |
+--------------------+-------+
| this_item:    265  |  232  |
| max_width:    265  |  232  |
+====================+=======+
| max_width:    265  |  232  |
+====================+=======+

Here, × denotes "Not working width identification", and ✓ denotes "Working width identification".

Why the .width() is varying on the same element on some of the page refresh? If I press Ctrl + F5 to clear cache and refresh, it's a ×. And after that, if I continuously refresh the page with F5 only, it's a ✓. I kept the page idle for some time, then I pressed F5, but it's a ×.

Why?

What I tried

It's even behaving the same whether I change the calculation to a manual one:

if( parseInt( $(this).width() ) > max_item_width ) {
    max_item_width = parseInt( $(this).width() );
}

And I also took time setting the width by replacing 100 with 1000, but the behavior is same.

Edit: Fiddle

jQuery(document).ready(function($) {

  // Function: Match width
  var _so20170704_match_width = function(item) {
    var max_item_width = 0;

    item.each(function(index) {
      max_item_width = Math.max(max_item_width, parseInt($(this).width()));
    });

    // might not necessary
    // but taking time, to keep the elements' default width intact
    // while looping through 'em
    setTimeout(function() {
      item.width(max_item_width);
    }, 100);
  }

  _so20170704_match_width($('.package-title'));

});

*,
 :after,
 :before {
  box-sizing: border-box;
}

body {
  font-family: 'Roboto Condensed', Arial, Helvetica, sans-serif;
  font-size: 14px;
  line-height: 1.428571429;
  color: #333;
}

h2 {
  margin-top: 20px;
  margin-bottom: 10px;
  font-weight: 500;
  line-height: 1.1;
}

.package-title {
  color: #fff;
  background-color: #414142;
  border: 1px solid #fed307;
  border-radius: 10px;
  padding: 1px 15px 13px;
  display: inline-block;
  position: relative;
  font-size: 28px;
  z-index: 9;
}

.package-subtitle {
  display: block;
  position: absolute;
  bottom: 0;
  left: 100px;
  padding: 1px 5px;
  font-size: 14px;
  background-color: #fed307;
  color: #414142;
  font-family: 'Roboto Condensed', Arial, Helvetica, sans-serif;
  font-weight: 400;
}

<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed|Roboto:700" rel="stylesheet">

Package 1 TitlePackage 1 Subtitle

Package 2Package 2 Subtitle

Package 3 TtlPackage 3 Subtitle

Package 4 Title LargerPackage 4 Subtitle

Suspect: Embedded Font

While making the fiddle, I suspected that, the font embedding might causing the issue. I tried, disabling all the @font-face declarations in my code, and then when I's refreshing (by any ways) it's performing perfect.

So the issue noted is:

On cache clear the font embed refreshes itself and the jQuery function detects the widths with default fonts (width: 265 confirmed with default font). But then the condensed embedded font loaded up, and the width shrunken a bit. And that's causing the issue.

Body:
Okay, while making the Fiddle after the suggestion of @MehulJoshi, I suspected that, the embedded condensed font's causing the issue. So I's looking for a way to check whether all the fonts are loaded or not.

With the help of this StackOverflow thread I changed the following line of code:

_so20170704_match_width( $('.match-width') );

with the code below:

document.fonts.ready.then(function () {
    _so20170704_match_width( $('.match-width') );
});

Please read the attached SO thread before using this. It's a new feature, and works Chrome 35+ and Firefox 41+.

The way to solve the issue is:

When all the embedded fonts are ready (this is crucial)

Check for widths

Get the max width

Set the max width


问:
Yii2 Pjax Delete not working
I am trying to make an Ajax GridView using Pjax with delete button. Deleting goes with no Ajax. I am new to Yii2 so any help would be appreciated. Thank you.

index.php

```<code><?php Pjax::begin(['id' => 'countries']) ?>
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'title',

        ['class' => 'yii\grid\ActionColumn',
            'buttons' => [
                'delete' => function ($url, $model, $key) {
                    return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
                        'title' => Yii::t('yii', 'Delete'),
                        'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
                        'data-method' => 'post',
                    ]);
                },
            ]
        ],
    ],
]); ?>
<?php Pjax::end() ?>
</code>```

Controller

```<code>public function actionDelete($id)
{
    $model = new Category();
    $this->findModel($id)->delete();
    $dataProvider = new ActiveDataProvider([
        'query' => Category::find(),
    ]);
    return $this->render('index', [
        'dataProvider' => $dataProvider,
        'model' => $model,
    ]);
}
</code>```

This is public function actionIndex() in the Controller

```<code>public function actionIndex()
{
    $model = new Category();

    $dataProvider = new ActiveDataProvider([
        'query' => Category::find(),
    ]);

    if ($model->load(Yii::$app->request->post()) && $model->save())
    {
        $model = new Category();
    }
    return $this->render('index', [
        'dataProvider' => $dataProvider,
        'model' => $model,
    ]);
}
</code>```

答:
Can use like this:

in view:

```<code>'delete' => function ($url, $model, $key) {
  $options = [
    'title' => Yii::t('common', 'delete'),
    'aria-label' => Yii::t('common', 'delete'),
    'data-pjax' => 'w0',//id
    'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
    'data-method' => 'post',
    'class' => 'btn btn-xs btn-danger'
  ];
  return Html:: a('<i class="fa fa-fw fa-trash"></i>', [
    'delete',
    'id' => $model -> id
  ], $options);
}
</code>```

in controller:

```<code>$this -> findModel($id) -> delete ();
$searchModel = new AdminSearch();
//get the referer url
$url = Yii::$app -> request -> referrer;
$arr = parse_url($url, PHP_URL_QUERY);
parse_str($arr, $output);//get the $_GET array
$dataProvider = $searchModel -> search($output);
return $this -> render('index', [
  'searchModel' => $searchModel,
  'dataProvider' => $dataProvider,
]);
</code>```

Title: Yii2 Pjax Delete not working

Body:
I am trying to make an Ajax GridView using Pjax with delete button. Deleting goes with no Ajax. I am new to Yii2 so any help would be appreciated. Thank you.

index.php

<?php Pjax::begin(['id' => 'countries']) ?>
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'title',

        ['class' => 'yii\grid\ActionColumn',
            'buttons' => [
                'delete' => function ($url, $model, $key) {
                    return Html::a('', $url, [
                        'title' => Yii::t('yii', 'Delete'),
                        'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
                        'data-method' => 'post',
                    ]);
                },
            ]
        ],
    ],
]); ?>
<?php Pjax::end() ?>

Controller

public function actionDelete($id)
{
    $model = new Category();
    $this->findModel($id)->delete();
    $dataProvider = new ActiveDataProvider([
        'query' => Category::find(),
    ]);
    return $this->render('index', [
        'dataProvider' => $dataProvider,
        'model' => $model,
    ]);
}

This is public function actionIndex() in the Controller

public function actionIndex()
{
    $model = new Category();

    $dataProvider = new ActiveDataProvider([
        'query' => Category::find(),
    ]);

    if ($model->load(Yii::$app->request->post()) && $model->save())
    {
        $model = new Category();
    }
    return $this->render('index', [
        'dataProvider' => $dataProvider,
        'model' => $model,
    ]);
}

Body:
Can use like this:

in view:

'delete' => function ($url, $model, $key) {
  $options = [
    'title' => Yii::t('common', 'delete'),
    'aria-label' => Yii::t('common', 'delete'),
    'data-pjax' => 'w0',//id
    'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
    'data-method' => 'post',
    'class' => 'btn btn-xs btn-danger'
  ];
  return Html:: a('<i class="fa fa-fw fa-trash"></i>', [
    'delete',
    'id' => $model -> id
  ], $options);
}

in controller:

$this -> findModel($id) -> delete ();
$searchModel = new AdminSearch();
//get the referer url
$url = Yii::$app -> request -> referrer;
$arr = parse_url($url, PHP_URL_QUERY);
parse_str($arr, $output);//get the $_GET array
$dataProvider = $searchModel -> search($output);
return $this -> render('index', [
  'searchModel' => $searchModel,
  'dataProvider' => $dataProvider,
]);