问:
Vertical align the child elements with different height
I am trying to achieve a vertically aligned child elements which have different heights.

Following is what I want to implement. Currently I set a different negative top margin on both buttons. I feel this can be done in a more cleaner way with a single generic ruling. Please share your thoughts.

Following is the code to illustrate the problem:

.container {
  padding: 35px 2px;
  border: 1px solid gray;
}

.title {
  font-size: 18px;
}

.action-button {
  float: right;
  height: 50px;
  width: 100px;

}

.small-screen {
  width: 160px;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>HTML:

<div class="container">

  <span class="title">
    Card header
  </span>

  <button class="action-button">
    Action
  </button>

</div>

<br/>

<div class="container">

  <span class="title small-screen">
    Card header title here is longer
  </span>

  <button class="action-button">
    Action
  </button>

</div></code>```

Link to JSFiddle

答:
Use display:table along with table-cell with vertical align
  middle property

.container {
    padding: 35px 2px;
    border: 1px solid gray;
    display: table;
    width: 100%;
    vertical-align: middle;
}

.title {
    font-size: 18px;
    display: table-cell;
    vertical-align: middle;
}

.action-button {
    float: right;
    height: 50px;
    width: 100px;
    display: table-cell;
    vertical-align: middle;
}

.small-screen {
  width: 160px;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>HTML:

<div class="container">

  <span class="title">
    Card header
  </span>

  <button class="action-button">
    Action
  </button>

</div>

<br/>

<div class="container">

  <span class="title small-screen">
    Card header title here is longer
  </span>

  <button class="action-button">
    Action
  </button>

</div></code>```

Body:
I am trying to achieve a vertically aligned child elements which have different heights.

Following is what I want to implement. Currently I set a different negative top margin on both buttons. I feel this can be done in a more cleaner way with a single generic ruling. Please share your thoughts.

Following is the code to illustrate the problem:

.container {
  padding: 35px 2px;
  border: 1px solid gray;
}

.title {
  font-size: 18px;
}

.action-button {
  float: right;
  height: 50px;
  width: 100px;

}

.small-screen {
  width: 160px;
  display: inline-block;
}

HTML:

    Card header

  <button class="action-button">
    Action
  </button>

    Card header title here is longer

  <button class="action-button">
    Action
  </button>

Link to JSFiddle

Body:
Use display:table along with table-cell with vertical align
  middle property

.container {
    padding: 35px 2px;
    border: 1px solid gray;
    display: table;
    width: 100%;
    vertical-align: middle;
}

.title {
    font-size: 18px;
    display: table-cell;
    vertical-align: middle;
}

.action-button {
    float: right;
    height: 50px;
    width: 100px;
    display: table-cell;
    vertical-align: middle;
}

.small-screen {
  width: 160px;
  display: inline-block;
}

HTML:

<div class="container">

  <span class="title">
    Card header
  </span>

  <button class="action-button">
    Action
  </button>

</div>

<br/>

<div class="container">

  <span class="title small-screen">
    Card header title here is longer
  </span>

  <button class="action-button">
    Action
  </button>

</div>


来源: stackexchange

问:
Angular: how to submit form group on enter key pressed
I have a form which submits a request to the database to filter some data in a grid. The form is submitted when submit button is pressed but I need it to submit the form when enter key is pressed also.

HTML

```<code><form [formGroup]="bmForm"
    (keyup.enter)="onSearchClicked()"
    (ngSubmit)="onSearchClicked()">
    <div class="form-group">
        <div>
           <label>Full Text Search</label>
           <input type="name" class="form-control" id="search"
                formControlName="ftSearch"
                placeholder="Full Text Search">
        </div>
        <div>
            <label>Identifier</label>
            <input type="name" class="form-control" id="search"
                formControlName="id"
                placeholder="Identifier">
        </div>
    </div>
    <button
        type="submit"
        class="btn btn-primary mr-2"
        (keyup.enter)="onSearchClicked()"
        (keydown.enter)="onSearchClicked()">
        Search
    </button>
</form>
</code>```

I have tried using (keyup.enter)="onSearchClicked()" in the <form> &  <button> tag without making changes to the Typescript but have had no success. Currently the Enter tab refreshes the page when clicked.

答:
Ok. take a look at my example:
remove button events they are unnecessary. define submit event in your form as (ngSubmit) or define it only in button. you dont need more.

```<code><form [formGroup]="searchForm" (ngSubmit)="search()">
    <div class="input-group no-border">
        <input type="text" value="" formControlName="key" class="form-control" placeholder="Search...">
    </div>
</form>
</code>```

and this is the search method:

```<code>search() {
    this.alert.info('Not yet implemented!');
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a form which submits a request to the database to filter some data in a grid. The form is submitted when submit button is pressed but I need it to submit the form when enter key is pressed also.

HTML

<form [formGroup]="bmForm"
    (keyup.enter)="onSearchClicked()"
    (ngSubmit)="onSearchClicked()">

           Full Text Search
           <input type="name" class="form-control" id="search"
                formControlName="ftSearch"
                placeholder="Full Text Search">

            Identifier
            <input type="name" class="form-control" id="search"
                formControlName="id"
                placeholder="Identifier">

    <button
        type="submit"
        class="btn btn-primary mr-2"
        (keyup.enter)="onSearchClicked()"
        (keydown.enter)="onSearchClicked()">
        Search
    </button>
</form>

I have tried using (keyup.enter)="onSearchClicked()" in the <form> &  <button> tag without making changes to the Typescript but have had no success. Currently the Enter tab refreshes the page when clicked.

Body:
Ok. take a look at my example:
remove button events they are unnecessary. define submit event in your form as (ngSubmit) or define it only in button. you dont need more.

<form [formGroup]="searchForm" (ngSubmit)="search()">
    <div class="input-group no-border">
        <input type="text" value="" formControlName="key" class="form-control" placeholder="Search...">
    </div>
</form>

and this is the search method:

search() {
    this.alert.info('Not yet implemented!');
}


问:
Check for special characters (/*-+_@&$#%) in a string?
How do I check a string to make sure it contains numbers, letters, or space only?</p>

答:
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:

```<code>using System;
using System.Linq;

namespace CheckStringContent
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get a password to check
            Console.WriteLine("Please input a Password: ");
            string userPassword = Console.ReadLine();

            //Check the string
            bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));

            //Write results to console
            Console.WriteLine($"Symbols are present: {symbolCheck}");
        }
    }
}
</code>```

This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.

ContentLicense: CC BY-SA 2.5

Body:
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:

using System;
using System.Linq;

namespace CheckStringContent
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get a password to check
            Console.WriteLine("Please input a Password: ");
            string userPassword = Console.ReadLine();

            //Check the string
            bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));

            //Write results to console
            Console.WriteLine($"Symbols are present: {symbolCheck}");
        }
    }
}

This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.


问:
How to create teams in firebase crashlytics after migration from fabric?
I have migrated from fabric to firebase by connecting apps via console but I am not getting crash report emails from firebase. I added different users from "Users and Permissions" as suggested here. But I am still not getting email notifications on crash. I tried creating custom role from google cloud console but I am not able to see that in my firebase console. Only case where I am getting mails is when I am adding new user as "Owner" which I think is not right because it would mean I should give full access to all team members. Has anyone faced such issue before?

P.S.: Crashes are logged in console but I am not getting email notifications on crash.

答:
You can configure your email preferences from Alert Settings under the alert icon on the top left of the console. What does this window look like in your firebase console?

Next you need to have at least view permissions on the project to receive e-mail notification. Project owners and editors get email alerts by default. More information on this can be found here.


问:
Money format using float in c#
So I'm going to be creating an app using realmdb - realm does not support decimal data types as of yet so I have been looking for an equivalent. If you could imagine object 1 returns 50, object 2 returns 50 & object 3 returns 12 = 112 but after 30% it should return £78.40 - Right now its returning £78.4

Below is my current code.

```<code>        Console.WriteLine("Object Costs");
        float ObjectOne = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Object 2 Costs");
        float ObjectTwo = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Object 3 Costs");
        float ObjectThree = Convert.ToInt32(Console.ReadLine());

        float Total = ObjectOne + ObjectTwo + ObjectThree;

        Console.WriteLine("Total: " + NewLine + "£" + Total);

        Console.WriteLine("DISCOUNTED - 30% OFF!!!");

        Console.WriteLine(NewLine + "Final Total: " + "£" + (Total - Math.Round((Total / 100 * 30), 2, MidpointRounding.AwayFromZero)));
</code>```

答:
You can format your float value using ToString("0.00");

```<code>var discountedRate = (Total - Math.Round((Total / 100 * 30), 2, MidpointRounding.AwayFromZero)).ToString("0.00");

Console.WriteLine($"Final Total:£ {discountedRate}");
</code>```

Try it online

Just a note: If you are dealing with money then use decimal instead of float

From MSDN:

The decimal type has more precision and a smaller range than both
  float and double, it's appropriate for financial and monetary
  calculations.

Title: Money format using float in c#

Body:
So I'm going to be creating an app using realmdb - realm does not support decimal data types as of yet so I have been looking for an equivalent. If you could imagine object 1 returns 50, object 2 returns 50 & object 3 returns 12 = 112 but after 30% it should return £78.40 - Right now its returning £78.4

Below is my current code.

        Console.WriteLine("Object Costs");
        float ObjectOne = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Object 2 Costs");
        float ObjectTwo = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Object 3 Costs");
        float ObjectThree = Convert.ToInt32(Console.ReadLine());

        float Total = ObjectOne + ObjectTwo + ObjectThree;

        Console.WriteLine("Total: " + NewLine + "£" + Total);

        Console.WriteLine("DISCOUNTED - 30% OFF!!!");

        Console.WriteLine(NewLine + "Final Total: " + "£" + (Total - Math.Round((Total / 100 * 30), 2, MidpointRounding.AwayFromZero)));

Body:
You can format your float value using ToString("0.00");

var discountedRate = (Total - Math.Round((Total / 100 * 30), 2, MidpointRounding.AwayFromZero)).ToString("0.00");

Console.WriteLine($"Final Total:£ {discountedRate}");

Try it online

Just a note: If you are dealing with money then use decimal instead of float

From MSDN:

The decimal type has more precision and a smaller range than both
  float and double, it's appropriate for financial and monetary
  calculations.


问:
How to get text content of one h3 at a time in javascript?
I am having difficulty to get text content of h1 at a time when I click on any button element . Can anyone help me out please?     </p>

```<code>    <div id="makeSelection" ><h1>Text Content 1</h1>
    <button onclick="eveent()">Click Me</button>
    </div>
    <div id="makeSelection" ><h1>Text Content 2</h1>
        <button onclick="eveent()">Click Me</button>
    </div>
    <div id="makeSelection" ><h1>Text Content 3</h1>
        <button onclick="eveent()">Click Me</button>
    </div>

     function eveent(){

        var text = document.getElementById('makeSelection').textContent;

        console.log(text);

                    }
</code>```

答:
A simple example with plain Javascript to read the content of clicked div  </p>

```<code>  <html>
        <head>
            <script>
            function eveent(c) {
                alert(c.childNodes[0].innerText);
            }
            </script>
        </head>
        <body>
         <div class="makeSelection" onclick="eveent(this)"><h1>Text Content 1</h1></div>
         <div class="makeSelection" onclick="eveent(this)"><h1>Text Content 2</h1></div>
         <div class="makeSelection" onclick="eveent(this)"><h1>Text Content 3</h1></div>
        </body>
    </html>
</code>```

Body:
I am having difficulty to get text content of h1 at a time when I click on any button element . Can anyone help me out please?

Text Content 1

    <button onclick="eveent()">Click Me</button>

Text Content 2

        <button onclick="eveent()">Click Me</button>

Text Content 3

        <button onclick="eveent()">Click Me</button>

     function eveent(){

        var text = document.getElementById('makeSelection').textContent;

        console.log(text);

                    }

Body:
A simple example with plain Javascript to read the content of clicked div

  <html>
        <head>
            <script>
            function eveent(c) {
                alert(c.childNodes[0].innerText);
            }
            </script>
        </head>
        <body>
         <div class="makeSelection" onclick="eveent(this)"><h1>Text Content 1</h1></div>
         <div class="makeSelection" onclick="eveent(this)"><h1>Text Content 2</h1></div>
         <div class="makeSelection" onclick="eveent(this)"><h1>Text Content 3</h1></div>
        </body>
    </html>


问:
PHP/MySQL resetting flags in a view
So, I have an application that I'm writing and at it is, for the most part, working well.

However, there's some unexpected behaviour that I cannot, for the life of me, understand why it is behaving as such.

The code creates a view from a MySQL table, and then a series of questions are asked. These are simple yes/no questions, and (depending on the result) true flags are set to false.  When there is only one true flag remaining, it then loads a page which is supposed to display a card with information about the character that was left.

The yes/no is iterating the view and changing flags as it should.  However, when there is one character remaining, it's resetting all the flags back to true, and displaying all the characters, instead of the one.  It has to be something to do with the MySQL, but I cannot see what it could be.

Below is the results.class.php in which the finalResult method resides.

```<code><?php

class result
{
    protected $Conn;

    public function __construct($Conn)
    {
        $this->Conn = $Conn;

    }

    public function dropResult()
    {
        $drop = "DROP VIEW if EXISTS result;";
        $stmt = $this->Conn->prepare($drop);
        $stmt->execute(array());
    }

    public function createResult()
    {
        $view = "CREATE VIEW result AS SELECT id, flag, name, image, quote FROM person;";
        $stmt = $this->Conn->prepare($view);
        $stmt->execute(array());
        return $view;
    }

    public function resetFlag()
    {
        $update = "UPDATE person SET flag = true";
        $stmt = $this->Conn->prepare($update);
        $stmt->execute(array());

        }

    public function selectResult()
    {
        $select= "SELECT id, flag from result";
        $stmt = $this->Conn->prepare($select);
        $stmt->execute(array());
        $select = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $select;
    }
    Public function iterateResult($id)
    {
        $changeFlag = "UPDATE result SET flag = false WHERE  id= :id";
        $stmt = $this->Conn->prepare($changeFlag);
        $stmt->execute(array(':id' => $id));

    }
    public function countResult()
    {
        $flag = "SELECT flag from result WHERE flag = true";
        $stmt = $this->Conn->prepare($flag);
        $stmt->execute(array());
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function finalResult()
    {
        $characterResult = "SELECT name, image, quote FROM result WHERE flag = true;";
        $stmt = $this->Conn->prepare($characterResult);
        $stmt->execute(array());
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

}

?>
</code>```

And here is the results.php code

```<code><?php
$result = new result($Conn);
$dropResult = $result->dropResult();
$createResult = $result->createResult();
$resetFlag = $result ->resetFlag();
$finalCharacter = $result->finalResult();
$smarty->assign('result', $finalCharacter);

?>
</code>```

I'm sure it's something really simple, but I just can't see the wood for the trees here.  Any tips?

PS...  Originally, I had the selectResult method as the method that was called for $finalCharacter, so I created a new method out of sheer desperation!!!

答: Fixed it.  Turns out that I had the resetFlag method in TWO controllers, so the method was being used in the result page and resetting the flags to 1.  Removed the method call in the result page and bob's your uncle.  Thanks for the help...  very much appreciated.</p>

Title: PHP/MySQL resetting flags in a view

Body:
So, I have an application that I'm writing and at it is, for the most part, working well.

However, there's some unexpected behaviour that I cannot, for the life of me, understand why it is behaving as such.

The code creates a view from a MySQL table, and then a series of questions are asked. These are simple yes/no questions, and (depending on the result) true flags are set to false.  When there is only one true flag remaining, it then loads a page which is supposed to display a card with information about the character that was left.

The yes/no is iterating the view and changing flags as it should.  However, when there is one character remaining, it's resetting all the flags back to true, and displaying all the characters, instead of the one.  It has to be something to do with the MySQL, but I cannot see what it could be.

Below is the results.class.php in which the finalResult method resides.

<?php

class result
{
    protected $Conn;

    public function __construct($Conn)
    {
        $this->Conn = $Conn;

    }

    public function dropResult()
    {
        $drop = "DROP VIEW if EXISTS result;";
        $stmt = $this->Conn->prepare($drop);
        $stmt->execute(array());
    }

    public function createResult()
    {
        $view = "CREATE VIEW result AS SELECT id, flag, name, image, quote FROM person;";
        $stmt = $this->Conn->prepare($view);
        $stmt->execute(array());
        return $view;
    }

    public function resetFlag()
    {
        $update = "UPDATE person SET flag = true";
        $stmt = $this->Conn->prepare($update);
        $stmt->execute(array());

        }

    public function selectResult()
    {
        $select= "SELECT id, flag from result";
        $stmt = $this->Conn->prepare($select);
        $stmt->execute(array());
        $select = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $select;
    }
    Public function iterateResult($id)
    {
        $changeFlag = "UPDATE result SET flag = false WHERE  id= :id";
        $stmt = $this->Conn->prepare($changeFlag);
        $stmt->execute(array(':id' => $id));

    }
    public function countResult()
    {
        $flag = "SELECT flag from result WHERE flag = true";
        $stmt = $this->Conn->prepare($flag);
        $stmt->execute(array());
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function finalResult()
    {
        $characterResult = "SELECT name, image, quote FROM result WHERE flag = true;";
        $stmt = $this->Conn->prepare($characterResult);
        $stmt->execute(array());
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

}

?>

And here is the results.php code

<?php
$result = new result($Conn);
$dropResult = $result->dropResult();
$createResult = $result->createResult();
$resetFlag = $result ->resetFlag();
$finalCharacter = $result->finalResult();
$smarty->assign('result', $finalCharacter);

?>

I'm sure it's something really simple, but I just can't see the wood for the trees here.  Any tips?

PS...  Originally, I had the selectResult method as the method that was called for $finalCharacter, so I created a new method out of sheer desperation!!!


问:
Mokito Unit test NoSuchMethodError: org.json.JSONObject.keySet()?
I am trying to do unit testing using mockito for below JSONobject.

```<code>JSONObject obj =  new JSONObject(JsonString);
obj.put("newEntry","UserId")
Set<String> objKeySet = obj.keySet();
</code>```

Added Dependency

```<code>        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>
</code>```

Error

```<code> java.lang.NoSuchMethodError: org.json.JSONObject.keySet()Ljava/util/Set;
</code>```

My question is why mokito runner is not able to find method keySet() however put mehod is working fine. how can i fix it.

Thanks in advance

答:
I could able to fix it by adding the exclusions sections to pom.xml file</p>

```<code>     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.json</groupId>
                <artifactId>json</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.vaadin.external.google</groupId>
                <artifactId>android-json</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</code>```

Body:
I am trying to do unit testing using mockito for below JSONobject.

JSONObject obj =  new JSONObject(JsonString);
obj.put("newEntry","UserId")
Set<String> objKeySet = obj.keySet();

Added Dependency

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>

Error

 java.lang.NoSuchMethodError: org.json.JSONObject.keySet()Ljava/util/Set;

My question is why mokito runner is not able to find method keySet() however put mehod is working fine. how can i fix it.

Thanks in advance

Body:
I could able to fix it by adding the exclusions sections to pom.xml file

     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.json</groupId>
                <artifactId>json</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.vaadin.external.google</groupId>
                <artifactId>android-json</artifactId>
            </exclusion>
        </exclusions>
    </dependency>


问:
Cakephp 3 query with conditions array build in foreach loop
Hello i want to use an array as condition.
For example i have services with a zip as combination

12345 => cleaning,
54321 => cleaning

now i build my array together in a foreach loop

```<code>$searcharray = [];
foreach($services as $key => $val){
    searcharray[] = array('service' => $val['service'], 'zip' => $val['zip']);
}
</code>```

My search array lookes like this:

```<code>[
    (int) 0 => [
        'service' => 'cleaning',
        'zip' => '12345'
    ],
    (int) 1 => [
        'service' => 'cleaning',
        'zip' => '54321'
    ]
]
</code>```

Then i try to get the data from my request table

```<code>$this->loadModel('Requests');
$openrequests = $this->Requests->find('all', array(
  'conditions' => array(
    'OR' => array(
      $searcharray
    )
  )
));
</code>```

It didnt work maybe of the keys in the array, because i set after the $searcharray for example [1] and then it works. I dont want to write the condition as string, but how can i solve it?

答:
You have nested the conditions one level too deep.

Your $searcharray is already nested correctly, if you nest it again as in your example, then you're basically creating an OR node with only one child (which in turn has children itself), which is interpreted as basically "nothing", as you need at least two children for an operator to be used. The children in the array nested one level deeper will then be interpreted as AND, as that is the default when no operator is specified.

Long story short, just pass $searcharray as is:

```<code>'conditions' => [
    'OR' => $searcharray,
]
</code>```

See also

Cookbook > Database Access & ORM > Query Builder > Advanced Conditions

Body:
Hello i want to use an array as condition.
For example i have services with a zip as combination

12345 => cleaning,
54321 => cleaning

now i build my array together in a foreach loop

$searcharray = [];
foreach($services as $key => $val){
    searcharray[] = array('service' => $val['service'], 'zip' => $val['zip']);
}

My search array lookes like this:

[
    (int) 0 => [
        'service' => 'cleaning',
        'zip' => '12345'
    ],
    (int) 1 => [
        'service' => 'cleaning',
        'zip' => '54321'
    ]
]

Then i try to get the data from my request table

$this->loadModel('Requests');
$openrequests = $this->Requests->find('all', array(
  'conditions' => array(
    'OR' => array(
      $searcharray
    )
  )
));

It didnt work maybe of the keys in the array, because i set after the $searcharray for example [1] and then it works. I dont want to write the condition as string, but how can i solve it?

Body:
You have nested the conditions one level too deep.

Your $searcharray is already nested correctly, if you nest it again as in your example, then you're basically creating an OR node with only one child (which in turn has children itself), which is interpreted as basically "nothing", as you need at least two children for an operator to be used. The children in the array nested one level deeper will then be interpreted as AND, as that is the default when no operator is specified.

Long story short, just pass $searcharray as is:

'conditions' => [
    'OR' => $searcharray,
]

See also

Cookbook > Database Access & ORM > Query Builder > Advanced Conditions


问:
Proxy model for Multiple models in Django
I would like to display a model in the django admin but with the logic to choose between 2 models to display.

Current Implementation:

Models

```<code>class User(models.Model):
   created = models.DateTimeField(auto_now_add=True, null=True)
   last_updated = models.DateTimeField(auto_now=True)
   name = models.CharField(max_length=30, blank=True)

class ExpectedNames(User):
   class Meta:
      proxy=True`
</code>```

Admin

@admin.register(ExpectedNames)
class ExpectedNamesAdmin(admin.ModelAdmin):
    date_hierarchy = 'created'

What I Would like to DO: # something like this

Models

```<code>class User(models.Model):
    created = models.DateTimeField(auto_now_add=True, null=True)
    last_updated = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=30, blank=True)

class User2(models.Model):
    created = models.DateTimeField(auto_now_add=True, null=True)
    last_updated = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=30, blank=True)

class ExpectedNames(User):
    class Meta:
        proxy=True

    if name == "Rick":
    return User
    else:
    return User2
</code>```

Admin

@admin.register(ExpectedNames)
class ExpectedNamesAdmin(admin.ModelAdmin):
    date_hierarchy = 'created'

Any suggestions not sure if this is the correct way to do this.

答:
I use magic method new in same situation.

I have model Documen with field document_type. If document_type is 'contract' i want ContractProxy, if 'offer' - OfferProxy.
For do this I create new proxy:

class RelatedDocumentProxy(Document):

    class Meta:
        proxy = True

    def __new__(cls, *args, **kwargs):
        doc_type = args[1]
        if doc_type == 'contract':
            return ContractProxy(*args, **kwargs)
        return OfferProxy(*args, **kwargs)```

document_type is first field and will first arg who pass to method

Body:
I would like to display a model in the django admin but with the logic to choose between 2 models to display.

Current Implementation:

Models

class User(models.Model):
   created = models.DateTimeField(auto_now_add=True, null=True)
   last_updated = models.DateTimeField(auto_now=True)
   name = models.CharField(max_length=30, blank=True)

class ExpectedNames(User):
   class Meta:
      proxy=True`

Admin

@admin.register(ExpectedNames)
class ExpectedNamesAdmin(admin.ModelAdmin):
    date_hierarchy = 'created'

What I Would like to DO: # something like this

Models

class User(models.Model):
    created = models.DateTimeField(auto_now_add=True, null=True)
    last_updated = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=30, blank=True)

class User2(models.Model):
    created = models.DateTimeField(auto_now_add=True, null=True)
    last_updated = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=30, blank=True)

class ExpectedNames(User):
    class Meta:
        proxy=True

    if name == "Rick":
    return User
    else:
    return User2

Admin

@admin.register(ExpectedNames)
class ExpectedNamesAdmin(admin.ModelAdmin):
    date_hierarchy = 'created'

Any suggestions not sure if this is the correct way to do this.

Body:
I use magic method new in same situation.

I have model Documen with field document_type. If document_type is 'contract' i want ContractProxy, if 'offer' - OfferProxy.
For do this I create new proxy:

class RelatedDocumentProxy(Document):

    class Meta:
        proxy = True

    def __new__(cls, *args, **kwargs):
        doc_type = args[1]
        if doc_type == 'contract':
            return ContractProxy(*args, **kwargs)
        return OfferProxy(*args, **kwargs)

document_type is first field and will first arg who pass to method


问:
Remove array item if it has a duplicate id
I have an array with the following values:

```<code>expandedComponents: {
  components: [
    {componentName: "hero", componentId: "hero-5856bvC6"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "footer", componentId: "footer-cUSAiiVd"}
  ]
}
</code>```

I want to filter out any array items with a duplicate componentId.

```<code>this.removeDuplicatesBy(x => x.componentId, this.expandedComponents['components']);

removeDuplicatesBy(keyFn, array) {
  var set = new Set();
  return array.filter(function(x) {
    var key = keyFn(x), isNew = !set.has(key);
    if (isNew) set.add(key);
    return isNew;
  });
 }
</code>```

However nothing seems to be happening and the duplicate features fields still persists. How do I fix this?

答:
One liner - Using Set

components = [{componentName:"hero",componentId:"hero-5856bvC6"},{componentName:"features",componentId:"features-iAnIKgJN"},{componentName:"features",componentId:"features-ncf3WpTA"},{componentName:"features",componentId:"features-iAnIKgJN"},{componentName:"features",componentId:"features-ncf3WpTA"},{componentName:"footer",componentId:"footer-cUSAiiVd"}];
console.log(components.filter((set => f => !set.has(f.componentId) && set.add(f.componentId))(new Set)))```

Taken From

JavaScript sets's are not supported by old browser Read Here and Here, but you can use polyfill for old browsers support

Body:
I have an array with the following values:

expandedComponents: {
  components: [
    {componentName: "hero", componentId: "hero-5856bvC6"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "footer", componentId: "footer-cUSAiiVd"}
  ]
}

I want to filter out any array items with a duplicate componentId.

this.removeDuplicatesBy(x => x.componentId, this.expandedComponents['components']);

removeDuplicatesBy(keyFn, array) {
  var set = new Set();
  return array.filter(function(x) {
    var key = keyFn(x), isNew = !set.has(key);
    if (isNew) set.add(key);
    return isNew;
  });
 }

However nothing seems to be happening and the duplicate features fields still persists. How do I fix this?

Body:
One liner - Using Set

components = [{componentName:"hero",componentId:"hero-5856bvC6"},{componentName:"features",componentId:"features-iAnIKgJN"},{componentName:"features",componentId:"features-ncf3WpTA"},{componentName:"features",componentId:"features-iAnIKgJN"},{componentName:"features",componentId:"features-ncf3WpTA"},{componentName:"footer",componentId:"footer-cUSAiiVd"}];
console.log(components.filter((set => f => !set.has(f.componentId) && set.add(f.componentId))(new Set)))

Taken From

JavaScript sets's are not supported by old browser Read Here and Here, but you can use polyfill for old browsers support


问:
input file Update images inside database
So im trying to change the image thats already inside the database but i cant seem to make it work i kept looking at tutorials and other related questions but couldnt find the exact solution.

this is what i have in php

```<code>// Als de knop van de formulier is ingedrukt update de data dat van de database afkomt

if (isset($_POST['update'])) {

if (isset($_GET['id'])) {
          $chauffeurs_id = $_GET['id'];
        }

if (isset($_POST['Chauffeurs_foto'])) {
            $Chauffeurs_foto = $_POST['Chauffeurs_foto'];
        }

$sql = "SELECT * FROM chauffeurs ORDER BY 'chauffeurs_geboortedatum ASC";
        $sql = "UPDATE `chauffeurs`
        SET `Chauffeurs_foto`=$Chauffeurs_foto
        WHERE `id`='$chauffeurs_id'";

$result = $conn->query($sql);

        if ($result == TRUE){
            echo "Aanpassingen zijn voltooid.";
        }else{
            echo "Error:" . $sql . "<br>" . $conn->error;
        }
    }

if (isset($_GET['id'])) {
      $id = $_GET['id'];

$sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $id = $row['id'];
            $chauffeurs_foto = $row['chauffeurs_foto'];
}
$backId = $_SESSION['krijgid'];
</code>```

Here is my html code:

```<code><!-- Formulier waar alles in komt om te veranderen -->
<form action="" method="post" enctype='multipart/form-data' >
          <fieldset>
           <legend>Gegevens chauffeur:</legend>
             <div class="form-group col-md-4">

//I did it like this so i could style the input file

<input type="file" name="file" id="file"  class="inputfile" value="data:image/jpeg;base64, <?php.base64_encode($row['chauffeurs_foto']).?>" />
<label class="btn btn primary"for="file">Choose a file</label>

<input type="submit" value="Chauffeur Aanpassen" name="update">
</fieldset>
</form>
</div>
</code>```

If anyone of you has a solution i would greatly appreciate it cause i need to finish it for my internship if not i'm just going to keep searching.

答:
File uploads can be tricky. May I suggest you start by reading the documentation on file uploading first?

You will see that your upload can best be reached using the $_FILES array. You will need to store the uploaded data in a variable, using the file_get_contents() method. And it's the file data you'll be uploading to your mySQL server.

Your code should look something like this:

```<code>$foto = file_get_contents($_FILES['file']['tmp_name']);
$sql = "UPDATE `chauffeurs` SET `Chauffeurs_foto`='{$foto}' WHERE `id`='$chauffeurs_id'";
</code>```

Finally, it's generally not good practise to store file data in your database, as the database size can get out of hand if the number of files you're storing in it grows. You're better off storing files (and images) separately and only storing a file reference in the database.

Body:
So im trying to change the image thats already inside the database but i cant seem to make it work i kept looking at tutorials and other related questions but couldnt find the exact solution.

this is what i have in php

// Als de knop van de formulier is ingedrukt update de data dat van de database afkomt

if (isset($_POST['update'])) {

if (isset($_GET['id'])) {
          $chauffeurs_id = $_GET['id'];
        }

if (isset($_POST['Chauffeurs_foto'])) {
            $Chauffeurs_foto = $_POST['Chauffeurs_foto'];
        }

$sql = "SELECT * FROM chauffeurs ORDER BY 'chauffeurs_geboortedatum ASC";
        $sql = "UPDATE `chauffeurs`
        SET `Chauffeurs_foto`=$Chauffeurs_foto
        WHERE `id`='$chauffeurs_id'";

$result = $conn->query($sql);

        if ($result == TRUE){
            echo "Aanpassingen zijn voltooid.";
        }else{
            echo "Error:" . $sql . "
" . $conn->error;
        }
    }

if (isset($_GET['id'])) {
      $id = $_GET['id'];

$sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $id = $row['id'];
            $chauffeurs_foto = $row['chauffeurs_foto'];
}
$backId = $_SESSION['krijgid'];

Here is my html code:

<form action="" method="post" enctype='multipart/form-data' >
          <fieldset>
           <legend>Gegevens chauffeur:</legend>

//I did it like this so i could style the input file

<input type="file" name="file" id="file"  class="inputfile" value="data:image/jpeg;base64, <?php.base64_encode($row['chauffeurs_foto']).?>" />
Choose a file

<input type="submit" value="Chauffeur Aanpassen" name="update">
</fieldset>
</form>

If anyone of you has a solution i would greatly appreciate it cause i need to finish it for my internship if not i'm just going to keep searching.

Body:
File uploads can be tricky. May I suggest you start by reading the documentation on file uploading first?

You will see that your upload can best be reached using the $_FILES array. You will need to store the uploaded data in a variable, using the file_get_contents() method. And it's the file data you'll be uploading to your mySQL server.

Your code should look something like this:

$foto = file_get_contents($_FILES['file']['tmp_name']);
$sql = "UPDATE `chauffeurs` SET `Chauffeurs_foto`='{$foto}' WHERE `id`='$chauffeurs_id'";

Finally, it's generally not good practise to store file data in your database, as the database size can get out of hand if the number of files you're storing in it grows. You're better off storing files (and images) separately and only storing a file reference in the database.


问:
Correctly return boolean variable from python module
I'm sure this is absurdly simple but I have been unable to get it working.

I want to convert a boolean variable to True in a module and return it to my main.

file: test

```<code>import module as mo

value = False
mo.x(value)
print(value)
</code>```

2. file: module

```<code>def x(value):
    value = True
    return value
</code>```

But this code is not working. When I print out the value it gives me a False.
Does anybody know how to return the value so it's True?
Or is it even possible to change a boolean value in another module and return it afterwards?

答:
You're not printing the return value of the funtion. For that, you should

v = mo.x(value)
print(v)
```

Otherwise, you're printing the local variable value.

Body:
I'm sure this is absurdly simple but I have been unable to get it working.

I want to convert a boolean variable to True in a module and return it to my main.

file: test

import module as mo

value = False
mo.x(value)
print(value)

2. file: module

def x(value):
    value = True
    return value

But this code is not working. When I print out the value it gives me a False.
Does anybody know how to return the value so it's True?
Or is it even possible to change a boolean value in another module and return it afterwards?

Body:
You're not printing the return value of the funtion. For that, you should

v = mo.x(value)
print(v)

Otherwise, you're printing the local variable value.


问:
no network in Android x86 on VirtualBox 4.1.2
My issue is nearly identical to this question. I tried those solution and none worked. But I am using a different Android x86 image. I'm using the ICS (4.0-RC1) asus_laptop image. (I tried a different image previously and couldn't get it to install.)

I installed VirtualBox 4.1.12 on Kubuntu 12.04. I followed these steps and installed the android-x86-4.0-RC1-asus_laptop.iso image in my VM. It boots up and works correctly except for networking.

Alt-F1 netcfg shows no interfaces up except the lo (127.0.0.1). eth0, which should be available, is not shown. That prevents me from trying the solution here.

New references I'm checking out:

Android ICS x86 on VirtualBox with Internet Connection

http://groups.google.com/group/android-x86/browse_thread/thread/30fa23d81cddfab1/2e480f6b9cbf773d

How to setup network for Android Honeycomb in VirtualBox?

答: I had to enable WiFi in the Android settings and select the virtual network created by VirtualBox. In my case it was called "VirtWifi", which is a fake WiFi network using my computer network.</p>

ContentLicense: CC BY-SA 3.0


答:
You are printing out value instead of the result of mo.x(value).

In your test.py, try the following:

```<code>import module as mo

value = False
value = mo.x(value)
print(value)
</code>```

and the output will be:

```<code>>>> True
</code>```

Note that the variables defined inside a function have a local scope. This means that value variable inside function x is only accessible within the function and is not the same as the value variable in your test.py module.

Title: Correctly return boolean variable from python module

Body:
You are printing out value instead of the result of mo.x(value).

In your test.py, try the following:

import module as mo

value = False
value = mo.x(value)
print(value)

and the output will be:

>>> True

Note that the variables defined inside a function have a local scope. This means that value variable inside function x is only accessible within the function and is not the same as the value variable in your test.py module.


问:
I want to create a Menu in shape of semi circle, with N number of menu-items
I want to create a menu like this,

.

But not getting perfect centre points for menu items(UIButton),
I'm using Stride(from:) in getCirclePoints() to get CGPoint for menu-items with equal spacing from starting and ending angle.

numberOfViews variable contains the number of menu-items that i want to place.

If numberOfViews = 5 then, the output will be

.

Anyone is having better idea to create such dynamic menu, or help me out in this piece of code.

Thank you.

```<code>class ViewController: UIViewController {

    @IBOutlet weak var btnMenu: UIButton!

    var numberOfViews: Int = 4
    var arrPoints: [CGPoint] = []
    var arrMenuItems = [UIButton]()

    var menuFrame: CGRect!
    var itemFrame: [CGRect] = []
    var isMenuOpen = false

    override func viewDidLoad() {
        super.viewDidLoad()
        prepareUI()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
}

extension ViewController {

    @IBAction func btnMenuTapped(_ sender: UIButton) {
        menu(open: isMenuOpen)
    }
}

extension ViewController {

    func prepareUI() {
        createMenuItems()
        storeFrame()
        btnMenu.makeRounded(0, isFullyRounded: true)
        menu(open: false, withDuration: 0.0001)
    }

    func createMenuItems() {
        arrPoints = getCirclePoints(centerPoint: btnMenu.center, radius: (self.view.bounds.width/CGFloat(numberOfViews) + 25), n: numberOfViews)
        for i in 0..<numberOfViews {
            drawMenuItem(for: i)
        }
    }

    func drawMenuItem(for index: Int) {
        var menuItem: UIButton
        let rect = CGRect(x: arrPoints[index].x, y: arrPoints[index].y, width: 50, height: 50)
        menuItem = UIButton(frame: rect)
        menuItem.makeRounded(0, isFullyRounded: true)
        menuItem.backgroundColor = UIColor.randomColor
        arrMenuItems.append(menuItem)
        view.addSubview(menuItem)
    }

    func getCirclePoints(centerPoint point: CGPoint, radius: CGFloat, n: Int)->[CGPoint] {
        let result: [CGPoint] = stride(from: -168, to: 12, by: Double(180 / n)).map {
            let bearing = CGFloat($0) * .pi / 180
            let x = point.x + radius * cos(bearing)
            let y = point.y + radius * sin(bearing)
            return CGPoint(x: x, y: y)
        }
        return result
    }

    func storeFrame() {
        menuFrame = btnMenu.frame
    }

    func menu(open isOpen: Bool, withDuration duration: Double = 0.5) {
        if isOpen {
            self.view.bringSubviewToFront(self.btnMenu)
            UIView.animate(withDuration: duration, animations: {
                for element in self.arrMenuItems {
                    element.frame = self.menuFrame
                }
            }) { (completed) in
                self.isMenuOpen = !self.isMenuOpen
            }
        }else {
            UIView.animate(withDuration: duration, animations: {
                for (index, element) in self.arrMenuItems.enumerated() {
                    element.frame = CGRect(x: self.arrPoints[index].x, y: self.arrPoints[index].y, width: element.frame.width, height: element.frame.height)
                }
                self.view.layoutIfNeeded()
            }) { (completed) in
                self.isMenuOpen = !self.isMenuOpen
            }
        }
    }
}

extension UIButton {

    func makeRounded(_ cornerRadius: CGFloat, isFullyRounded: Bool) {
        if isFullyRounded {
            self.layer.cornerRadius = self.frame.width / 2
        }else {
            self.layer.cornerRadius = cornerRadius
        }
    }
}

// MARK:- Color extension
extension UIColor {

    // To get random color
    static var randomColor: UIColor {
        return UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1.0)
    }
}
</code>```

答: you can use fan-menu Library for semi circle menu</p>

Body:
I want to create a menu like this,

.

But not getting perfect centre points for menu items(UIButton),
I'm using Stride(from:) in getCirclePoints() to get CGPoint for menu-items with equal spacing from starting and ending angle.

numberOfViews variable contains the number of menu-items that i want to place.

If numberOfViews = 5 then, the output will be

.

Anyone is having better idea to create such dynamic menu, or help me out in this piece of code.

Thank you.

class ViewController: UIViewController {

    @IBOutlet weak var btnMenu: UIButton!

    var numberOfViews: Int = 4
    var arrPoints: [CGPoint] = []
    var arrMenuItems = [UIButton]()

    var menuFrame: CGRect!
    var itemFrame: [CGRect] = []
    var isMenuOpen = false

    override func viewDidLoad() {
        super.viewDidLoad()
        prepareUI()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
}

extension ViewController {

    @IBAction func btnMenuTapped(_ sender: UIButton) {
        menu(open: isMenuOpen)
    }
}

extension ViewController {

    func prepareUI() {
        createMenuItems()
        storeFrame()
        btnMenu.makeRounded(0, isFullyRounded: true)
        menu(open: false, withDuration: 0.0001)
    }

    func createMenuItems() {
        arrPoints = getCirclePoints(centerPoint: btnMenu.center, radius: (self.view.bounds.width/CGFloat(numberOfViews) + 25), n: numberOfViews)
        for i in 0..<numberOfViews {
            drawMenuItem(for: i)
        }
    }

    func drawMenuItem(for index: Int) {
        var menuItem: UIButton
        let rect = CGRect(x: arrPoints[index].x, y: arrPoints[index].y, width: 50, height: 50)
        menuItem = UIButton(frame: rect)
        menuItem.makeRounded(0, isFullyRounded: true)
        menuItem.backgroundColor = UIColor.randomColor
        arrMenuItems.append(menuItem)
        view.addSubview(menuItem)
    }

    func getCirclePoints(centerPoint point: CGPoint, radius: CGFloat, n: Int)->[CGPoint] {
        let result: [CGPoint] = stride(from: -168, to: 12, by: Double(180 / n)).map {
            let bearing = CGFloat($0) * .pi / 180
            let x = point.x + radius * cos(bearing)
            let y = point.y + radius * sin(bearing)
            return CGPoint(x: x, y: y)
        }
        return result
    }

    func storeFrame() {
        menuFrame = btnMenu.frame
    }

    func menu(open isOpen: Bool, withDuration duration: Double = 0.5) {
        if isOpen {
            self.view.bringSubviewToFront(self.btnMenu)
            UIView.animate(withDuration: duration, animations: {
                for element in self.arrMenuItems {
                    element.frame = self.menuFrame
                }
            }) { (completed) in
                self.isMenuOpen = !self.isMenuOpen
            }
        }else {
            UIView.animate(withDuration: duration, animations: {
                for (index, element) in self.arrMenuItems.enumerated() {
                    element.frame = CGRect(x: self.arrPoints[index].x, y: self.arrPoints[index].y, width: element.frame.width, height: element.frame.height)
                }
                self.view.layoutIfNeeded()
            }) { (completed) in
                self.isMenuOpen = !self.isMenuOpen
            }
        }
    }
}

extension UIButton {

    func makeRounded(_ cornerRadius: CGFloat, isFullyRounded: Bool) {
        if isFullyRounded {
            self.layer.cornerRadius = self.frame.width / 2
        }else {
            self.layer.cornerRadius = cornerRadius
        }
    }
}

// MARK:- Color extension
extension UIColor {

    // To get random color
    static var randomColor: UIColor {
        return UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1.0)
    }
}


问:
Get Value from JSON for a given Key where parent key names are dynamic
I have a json string which starts like this:

```<code>{ "0" :
{"Jquery77768" :
    {"nodeData":
        {"id":32, "name": "Bob"}
        ----
</code>```

I need to get the value which is there in the id key.
I tried to do something like this:

```<code>var obj = JSON.parse(myJsonString);
var myID = obj[0].Jquery77768.nodeData.id;
</code>```

but this does not work. Also the second node name Jquery77768 is dynamic and will change every time.

How can I get the value of the id field?

答:
Since you mentioned dynamic key names (Jquery77768), It will be better to get the Object.values. (Assuming one key as in data).

```<code>var myID = Object.values(obj["0"])[0].nodeData.id;
</code>```

Body:
I have a json string which starts like this:

{ "0" :
{"Jquery77768" :
    {"nodeData":
        {"id":32, "name": "Bob"}
        ----

I need to get the value which is there in the id key.
I tried to do something like this:

var obj = JSON.parse(myJsonString);
var myID = obj[0].Jquery77768.nodeData.id;

but this does not work. Also the second node name Jquery77768 is dynamic and will change every time.

How can I get the value of the id field?

Body:
Since you mentioned dynamic key names (Jquery77768), It will be better to get the Object.values. (Assuming one key as in data).

var myID = Object.values(obj["0"])[0].nodeData.id;


问:
Get instance of subtype of a model with Eloquent
I have an Animal model, based on the animal table.

This table contains a type field, that can contain values such as cat or dog.

I would like to be able to create objects such as :

```<code>class Animal extends Model { }
class Dog extends Animal { }
class Cat extends Animal { }
</code>```

Yet, being able to fetch an animal like this :

```<code>$animal = Animal::find($id);
</code>```

But where $animal would be an instance of Dog or Cat depending on the type field, that I can check using instance of or that will work with type hinted methods. The reason is that 90% of the code is shared, but one can bark, and the other can meow.

I know that I can do Dog::find($id), but it's not what I want : I can determine the type of the object only once it was fetched. I could also fetch the Animal, and then run find() on the right object, but this is doing two database calls, which I obviously don't want.

I tried to look for a way to "manually" instantiate an Eloquent model like Dog from Animal, but I could not find any method corresponding. Any idea or method I missed please ?

答:
As the OP stated inside his comments: The database design is already set and therefore Laravel's Polymorphic Relationships seems not to be an option here.

I like the answer of Chris Neal because I had to do something similar recently (writing my own Database Driver to support Eloquent for dbase/DBF files) and gained a lot experience with the internals of Laravel's Eloquent ORM.

I've added my personal flavour to it to make the code more dynamic while keeping an explicit mapping per model.

Supported features which I quickly tested:

Animal::find(1) works as asked in your question

Animal::all() works as well

Animal::where(['type' => 'dog'])->get() will return AnimalDog-objects as a collection

Dynamic object mapping per eloquent-class which uses this trait

Fallback to Animal-model in case there is no mapping configured (or a new mapping appeared in the DB)

Disadvantages:

It's rewriting the model's internal newInstance() and newFromBuilder() entirely (copy and paste). This means if there will be any update from the framework to this member functions you'll need to adopt the code by hand.

I hope it helps and I'm up for any suggestions, questions and additional use-cases in your scenario. Here are the use-cases and examples for it:

```<code>class Animal extends Model
{
    use MorphTrait; // You'll find the trait in the very end of this answer

    protected $morphKey = 'type'; // This is your column inside the database
    protected $morphMap = [ // This is the value-to-class mapping
        'dog' => AnimalDog::class,
        'cat' => AnimalCat::class,
    ];

}

class AnimalCat extends Animal {}
class AnimalDog extends Animal {}
</code>```

And this is an example of how it can be used and below the respective results for it:

```<code>$cat = Animal::find(1);
$dog = Animal::find(2);
$new = Animal::find(3);
$all = Animal::all();

echo sprintf('ID: %s - Type: %s - Class: %s - Data: %s', $cat->id, $cat->type, get_class($cat), $cat, json_encode($cat->toArray())) . PHP_EOL;
echo sprintf('ID: %s - Type: %s - Class: %s - Data: %s', $dog->id, $dog->type, get_class($dog), $dog, json_encode($dog->toArray())) . PHP_EOL;
echo sprintf('ID: %s - Type: %s - Class: %s - Data: %s', $new->id, $new->type, get_class($new), $new, json_encode($new->toArray())) . PHP_EOL;

dd($all);
</code>```

which results the following:

```<code>ID: 1 - Type: cat - Class: App\AnimalCat - Data: {"id":1,"type":"cat"}
ID: 2 - Type: dog - Class: App\AnimalDog - Data: {"id":2,"type":"dog"}
ID: 3 - Type: new-animal - Class: App\Animal - Data: {"id":3,"type":"new-animal"}

// Illuminate\Database\Eloquent\Collection {#1418
//  #items: array:2 [
//    0 => App\AnimalCat {#1419
//    1 => App\AnimalDog {#1422
//    2 => App\Animal {#1425
</code>```

And in case you want you use the MorphTrait here is of course the full code for it:

```<code><?php namespace App;

trait MorphTrait
{

    public function newInstance($attributes = [], $exists = false)
    {
        // This method just provides a convenient way for us to generate fresh model
        // instances of this current model. It is particularly useful during the
        // hydration of new objects via the Eloquent query builder instances.
        if (isset($attributes['force_class_morph'])) {
            $class = $attributes['force_class_morph'];
            $model = new $class((array)$attributes);
        } else {
            $model = new static((array)$attributes);
        }

        $model->exists = $exists;

        $model->setConnection(
            $this->getConnectionName()
        );

        $model->setTable($this->getTable());

        return $model;
    }

    /**
     * Create a new model instance that is existing.
     *
     * @param array $attributes
     * @param string|null $connection
     * @return static
     */
    public function newFromBuilder($attributes = [], $connection = null)
    {
        $newInstance = [];
        if ($this->isValidMorphConfiguration($attributes)) {
            $newInstance = [
                'force_class_morph' => $this->morphMap[$attributes->{$this->morphKey}],
            ];
        }

        $model = $this->newInstance($newInstance, true);

        $model->setRawAttributes((array)$attributes, true);

        $model->setConnection($connection ?: $this->getConnectionName());

        $model->fireModelEvent('retrieved', false);

        return $model;
    }

    private function isValidMorphConfiguration($attributes): bool
    {
        if (!isset($this->morphKey) || empty($this->morphMap)) {
            return false;
        }

        if (!array_key_exists($this->morphKey, (array)$attributes)) {
            return false;
        }

        return array_key_exists($attributes->{$this->morphKey}, $this->morphMap);
    }
}

</code>```

Body:
I have an Animal model, based on the animal table.

This table contains a type field, that can contain values such as cat or dog.

I would like to be able to create objects such as :

class Animal extends Model { }
class Dog extends Animal { }
class Cat extends Animal { }

Yet, being able to fetch an animal like this :

$animal = Animal::find($id);

But where $animal would be an instance of Dog or Cat depending on the type field, that I can check using instance of or that will work with type hinted methods. The reason is that 90% of the code is shared, but one can bark, and the other can meow.

I know that I can do Dog::find($id), but it's not what I want : I can determine the type of the object only once it was fetched. I could also fetch the Animal, and then run find() on the right object, but this is doing two database calls, which I obviously don't want.

I tried to look for a way to "manually" instantiate an Eloquent model like Dog from Animal, but I could not find any method corresponding. Any idea or method I missed please ?

Body:
As the OP stated inside his comments: The database design is already set and therefore Laravel's Polymorphic Relationships seems not to be an option here.

I like the answer of Chris Neal because I had to do something similar recently (writing my own Database Driver to support Eloquent for dbase/DBF files) and gained a lot experience with the internals of Laravel's Eloquent ORM.

I've added my personal flavour to it to make the code more dynamic while keeping an explicit mapping per model.

Supported features which I quickly tested:

Animal::find(1) works as asked in your question

Animal::all() works as well

Animal::where(['type' => 'dog'])->get() will return AnimalDog-objects as a collection

Dynamic object mapping per eloquent-class which uses this trait

Fallback to Animal-model in case there is no mapping configured (or a new mapping appeared in the DB)

Disadvantages:

It's rewriting the model's internal newInstance() and newFromBuilder() entirely (copy and paste). This means if there will be any update from the framework to this member functions you'll need to adopt the code by hand.

I hope it helps and I'm up for any suggestions, questions and additional use-cases in your scenario. Here are the use-cases and examples for it:

class Animal extends Model
{
    use MorphTrait; // You'll find the trait in the very end of this answer

    protected $morphKey = 'type'; // This is your column inside the database
    protected $morphMap = [ // This is the value-to-class mapping
        'dog' => AnimalDog::class,
        'cat' => AnimalCat::class,
    ];

}

class AnimalCat extends Animal {}
class AnimalDog extends Animal {}

And this is an example of how it can be used and below the respective results for it:

$cat = Animal::find(1);
$dog = Animal::find(2);
$new = Animal::find(3);
$all = Animal::all();

echo sprintf('ID: %s - Type: %s - Class: %s - Data: %s', $cat->id, $cat->type, get_class($cat), $cat, json_encode($cat->toArray())) . PHP_EOL;
echo sprintf('ID: %s - Type: %s - Class: %s - Data: %s', $dog->id, $dog->type, get_class($dog), $dog, json_encode($dog->toArray())) . PHP_EOL;
echo sprintf('ID: %s - Type: %s - Class: %s - Data: %s', $new->id, $new->type, get_class($new), $new, json_encode($new->toArray())) . PHP_EOL;

dd($all);

which results the following:

ID: 1 - Type: cat - Class: App\AnimalCat - Data: {"id":1,"type":"cat"}
ID: 2 - Type: dog - Class: App\AnimalDog - Data: {"id":2,"type":"dog"}
ID: 3 - Type: new-animal - Class: App\Animal - Data: {"id":3,"type":"new-animal"}

// Illuminate\Database\Eloquent\Collection {#1418
//  #items: array:2 [
//    0 => App\AnimalCat {#1419
//    1 => App\AnimalDog {#1422
//    2 => App\Animal {#1425

And in case you want you use the MorphTrait here is of course the full code for it:

<?php namespace App;

trait MorphTrait
{

    public function newInstance($attributes = [], $exists = false)
    {
        // This method just provides a convenient way for us to generate fresh model
        // instances of this current model. It is particularly useful during the
        // hydration of new objects via the Eloquent query builder instances.
        if (isset($attributes['force_class_morph'])) {
            $class = $attributes['force_class_morph'];
            $model = new $class((array)$attributes);
        } else {
            $model = new static((array)$attributes);
        }

        $model->exists = $exists;

        $model->setConnection(
            $this->getConnectionName()
        );

        $model->setTable($this->getTable());

        return $model;
    }

    /**
     * Create a new model instance that is existing.
     *
     * @param array $attributes
     * @param string|null $connection
     * @return static
     */
    public function newFromBuilder($attributes = [], $connection = null)
    {
        $newInstance = [];
        if ($this->isValidMorphConfiguration($attributes)) {
            $newInstance = [
                'force_class_morph' => $this->morphMap[$attributes->{$this->morphKey}],
            ];
        }

        $model = $this->newInstance($newInstance, true);

        $model->setRawAttributes((array)$attributes, true);

        $model->setConnection($connection ?: $this->getConnectionName());

        $model->fireModelEvent('retrieved', false);

        return $model;
    }

    private function isValidMorphConfiguration($attributes): bool
    {
        if (!isset($this->morphKey) || empty($this->morphMap)) {
            return false;
        }

        if (!array_key_exists($this->morphKey, (array)$attributes)) {
            return false;
        }

        return array_key_exists($attributes->{$this->morphKey}, $this->morphMap);
    }
}


问:
How to pass data to a Javascript (!) that is called via ajax?
I have a validation-javascript for a form, that is called via AJAX und gives back a result. In the AJAX-Call I pass some data-parameters, but I don't know how to read these in the validation-script.

```<code>...
$.ajax({
            url: validation.js",
            dataType: "script",
            data: { validate: 'true' },
            success: function () {
...
</code>```

In the validation.js I want to read the parameter validate, like I would when I was calling PHP ($_GET['validate']).

Is that possible? In the Browser-console, I can see, that the script is called with "validation.js?validate=true", but how can I access validate in the Javascript?

It is really hard to look up, because all I find is "Passing Parameters to/from PHP" and "getting Parameters with JS by url-substring-stuff"..

Thank you,

Paco

EDIT
What I was trying to do:
extend a working Javascript with a (client-side) validation-function, that can be extended over time, without touching the rest of the script.
And I wanted to use the success-callback of the AJAX-call to react to the validation-result.

main.js

```<code>// validate Input on update
  $.ajax({
    url: validation.js",
      dataType: "script",
      data: { validation: validation },
        success: function () {
          var result = validate();
            // validation not successful
            if (!result.valid) { ... }
</code>```

validation.js

```<code>function validate() {

    var result = {
        valid: true,
        data: ''
    };

    if(foo) {
        result.valid = false;
        result.data = "There was an error: ...";
    }
    return result;

}
</code>```

This was my first idea and it worked well, apart from the data-parameter in the AJAX-Call, which came later and which I couldn't evaluate.
But I guess this still is xy-problem and there is a better and easier way with just writing a function as @quentin suggested..

Body:
I have a validation-javascript for a form, that is called via AJAX und gives back a result. In the AJAX-Call I pass some data-parameters, but I don't know how to read these in the validation-script.

...
$.ajax({
            url: validation.js",
            dataType: "script",
            data: { validate: 'true' },
            success: function () {
...

In the validation.js I want to read the parameter validate, like I would when I was calling PHP ($_GET['validate']).

Is that possible? In the Browser-console, I can see, that the script is called with "validation.js?validate=true", but how can I access validate in the Javascript?

It is really hard to look up, because all I find is "Passing Parameters to/from PHP" and "getting Parameters with JS by url-substring-stuff"..

Thank you,

Paco

EDIT
What I was trying to do:
extend a working Javascript with a (client-side) validation-function, that can be extended over time, without touching the rest of the script.
And I wanted to use the success-callback of the AJAX-call to react to the validation-result.

main.js

// validate Input on update
  $.ajax({
    url: validation.js",
      dataType: "script",
      data: { validation: validation },
        success: function () {
          var result = validate();
            // validation not successful
            if (!result.valid) { ... }

validation.js

function validate() {

    var result = {
        valid: true,
        data: ''
    };

    if(foo) {
        result.valid = false;
        result.data = "There was an error: ...";
    }
    return result;

}

This was my first idea and it worked well, apart from the data-parameter in the AJAX-Call, which came later and which I couldn't evaluate.
But I guess this still is xy-problem and there is a better and easier way with just writing a function as @quentin suggested..

Body:
Ajax is designed to make an HTTP request so that server-side code can process the request and provide an appropriate response.

jQuery's script dataType is designed to be used when the server-side code responds with a JavaScript.

You should not use it if you want to pass data to client-side JavaScript (which appears to be the case here).

(That said, I expect it is possible if you write your script so it uses document.currentScript to locate the <script> element (assuming jQuery creates one and doesn't just eval the response), then extract the src property of it and then parse the query string).

If you want to process the data with client-side JS. Don't use Ajax. Just define a function:

function validate(data) {
}

… and pass the data to it: validate({ validate: 'true' }).

And if you want to use Ajax, then write some server-side code. If you want to do it in JavaScript, then use Node.js with Express, and respond with JSON and not a script.


问:
What's the Proper Way of Publishing an NPM Package with Kendo UI as Its Dependency?
I created an Angular library to publish as an NPM package and I've made it work. However, when I tried using Kendo UI Button for my component inside the library, I can publish to NPM but it's not very usable. After installing the NPM package in another Angular app, it won't work and I had to manually install Kendo UI Button using this command:

ng add @progress/kendo-angular-buttons

Afterward, I tried also using that command inside my library project, it added a node_modules folder inside my library folder. Aside from that, it also updated the package.json for my library. After publishing once again and reinstalling in my other app, it now works!

However, there are a redundant node_modules inside my library folder and I don't want this. Can I skip using ng add inside my library folder and just copy the dependencies added when that command is run?

答:
I forgot to add the Kendo UI styles in my styles array.

Generate library

ng add @progress/kendo-angular-buttons

Add Kendo UI Button imports to library module

Edit library package.json and ng-package.json to add Kendo UI dependencies

dependencies and whitelistedNonPeerDependencies

ng build library

Go inside dist/lib, Publish to NPM

use npm init, npm login, npm publish

npm install library in another Angular app

Add Kendo CSS to styles array in angular.json

```<code>"styles": [
  {
    "input": "node_modules/@progress/kendo-theme-default/dist/all.css"
  },
  "src/styles.css"
]
</code>```

Body:
I forgot to add the Kendo UI styles in my styles array.

Generate library

ng add @progress/kendo-angular-buttons

Add Kendo UI Button imports to library module

Edit library package.json and ng-package.json to add Kendo UI dependencies

dependencies and whitelistedNonPeerDependencies

ng build library

Go inside dist/lib, Publish to NPM

use npm init, npm login, npm publish

npm install library in another Angular app

Add Kendo CSS to styles array in angular.json

"styles": [
  {
    "input": "node_modules/@progress/kendo-theme-default/dist/all.css"
  },
  "src/styles.css"
]


答: This happens because you are returning "True" value but you dont assign it to "value" variable. So, you are just making the call to the function but not using the return value.</p>


问:
How to create live tracking in react native?
Can anyone tell me please , how to create live tracking in react native ? Using geolocation ,react native maps or other dependencies, i wanna make a tracking driver like uber </p>

答:
Hope you have installed react-native-maps and added the necessary packages to your application. Use the below given code in componentDidMount(). The below given code will be called whenever your location will be changed. and it will provide you the updated location. Here you will also find the heading, you can use heading to show the vehicle direction or alignment.

```<code>this.watchId = navigator.geolocation.watchPosition(
  (position) => {
    this.locationPermission = true;
    console.log('Watch Position response', position);
    const { coordinate } = this.state;
    const { latitude, longitude } = position.coords;
    const newCoordinate = {
      latitude,
      longitude
    };
    if (Platform.OS === 'android') {
      if (this.marker) { this.marker._component.animateMarkerToCoordinate(newCoordinate, 500); }
    }
    else {
      coordinate.timing(newCoordinate).start();
    }

    this.setState({
      marker: {
        latlng: {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
        }
      },
      heading: position.coords.heading,
    })

    );

  },
  (error) => this.setState({ error: error.message }),
  { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 10 },
);
</code>```

Body:
Hope you have installed react-native-maps and added the necessary packages to your application. Use the below given code in componentDidMount(). The below given code will be called whenever your location will be changed. and it will provide you the updated location. Here you will also find the heading, you can use heading to show the vehicle direction or alignment.

this.watchId = navigator.geolocation.watchPosition(
  (position) => {
    this.locationPermission = true;
    console.log('Watch Position response', position);
    const { coordinate } = this.state;
    const { latitude, longitude } = position.coords;
    const newCoordinate = {
      latitude,
      longitude
    };
    if (Platform.OS === 'android') {
      if (this.marker) { this.marker._component.animateMarkerToCoordinate(newCoordinate, 500); }
    }
    else {
      coordinate.timing(newCoordinate).start();
    }

    this.setState({
      marker: {
        latlng: {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
        }
      },
      heading: position.coords.heading,
    })

    );

  },
  (error) => this.setState({ error: error.message }),
  { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 10 },
);


问:
How to replace special character in string with tcl script?
In file.txt

```<code>obj = "hi/this/is[1]/script"
</code>```

convert the string to

```<code>obj = "hi/this/is\[1]/script"
</code>```

Is there a way to do this in tcl?

答:
If you want to replace all occurrences of a character, string map is pretty suitable:

```<code># Careful with the quoting here
set obj [string map [list {[} {\[}] $obj]
</code>```

If you want to just replace the first occurrence, regsub is a better tool

```<code>set obj [regsub {\[} $obj {\\&}]
</code>```

(The & becomes the matched string, and we need to be careful with backslashes in both the RE and the substitution text.)

Body:
In file.txt

obj = "hi/this/is[1]/script"

convert the string to

obj = "hi/this/is\[1]/script"

Is there a way to do this in tcl?

Body:
If you want to replace all occurrences of a character, string map is pretty suitable:

# Careful with the quoting here
set obj [string map [list {[} {\[}] $obj]

If you want to just replace the first occurrence, regsub is a better tool

set obj [regsub {\[} $obj {\\&}]

(The & becomes the matched string, and we need to be careful with backslashes in both the RE and the substitution text.)


问:
How to read an existing TimeStamp?
I am working on somebody else's code and am getting a JSON-Object with an existing TimeStamp:

```<code>"lastModification": 1582013867500
</code>```

Well, I am struggling to read this. I checked the TimeStamp docs but still I don't know how to read that.
Can anybody help?

Thank you!

答:
Unix epoch or POSIX time or Unix timestamp - number of seconds elapsed since midnight proleptic Coordinated Universal Time (UTC) of January 1, 1970.

Your current timestamp is written in milliseconds.

You can use conversion tools to read it online, like https://www.epochconverter.com/.

Java Time library supports both seconds and milliseconds conversions:

```<code>LocalDateTime.ofInstant(Instant.ofEpochMilli(lastModification),
                        TimeZone.getDefault().toZoneId());

// OR using ZoneId

LocalDateTime.ofInstant(Instant.ofEpochMilli(lastModification),
                        ZoneId.systemDefault());
LocalDateTime.ofInstant(Instant.ofEpochSecond(lastModification),
                        ZoneId.systemDefault());
</code>```

Title: How to read an existing TimeStamp?

Body:
I am working on somebody else's code and am getting a JSON-Object with an existing TimeStamp:

"lastModification": 1582013867500

Well, I am struggling to read this. I checked the TimeStamp docs but still I don't know how to read that.
Can anybody help?

Thank you!

Body:
Unix epoch or POSIX time or Unix timestamp - number of seconds elapsed since midnight proleptic Coordinated Universal Time (UTC) of January 1, 1970.

Your current timestamp is written in milliseconds.

You can use conversion tools to read it online, like https://www.epochconverter.com/.

Java Time library supports both seconds and milliseconds conversions:

LocalDateTime.ofInstant(Instant.ofEpochMilli(lastModification),
                        TimeZone.getDefault().toZoneId());

// OR using ZoneId

LocalDateTime.ofInstant(Instant.ofEpochMilli(lastModification),
                        ZoneId.systemDefault());
LocalDateTime.ofInstant(Instant.ofEpochSecond(lastModification),
                        ZoneId.systemDefault());


问:
How to get text content of one h3 at a time in javascript?
I am having difficulty to get text content of h1 at a time when I click on any button element . Can anyone help me out please?     </p>

```<code>    <div id="makeSelection" ><h1>Text Content 1</h1>
    <button onclick="eveent()">Click Me</button>
    </div>
    <div id="makeSelection" ><h1>Text Content 2</h1>
        <button onclick="eveent()">Click Me</button>
    </div>
    <div id="makeSelection" ><h1>Text Content 3</h1>
        <button onclick="eveent()">Click Me</button>
    </div>

     function eveent(){

        var text = document.getElementById('makeSelection').textContent;

        console.log(text);

                    }
</code>```

答:
try to get the h1 inside "makeSelection" and make button outs</p>

```<code><div id="makeSelection"><h1>Text Content 1
  </h1>
function eveent(){

        var text = document.querySelector("#makeSelection h1").innerText
}
</code>```

Body:
I am having difficulty to get text content of h1 at a time when I click on any button element . Can anyone help me out please?

Text Content 1

    <button onclick="eveent()">Click Me</button>

Text Content 2

        <button onclick="eveent()">Click Me</button>

Text Content 3

        <button onclick="eveent()">Click Me</button>

     function eveent(){

        var text = document.getElementById('makeSelection').textContent;

        console.log(text);

                    }

Body:
try to get the h1 inside "makeSelection" and make button outs

<div id="makeSelection"><h1>Text Content 1
  </h1>
function eveent(){

        var text = document.querySelector("#makeSelection h1").innerText
}


问:
ImproperlyConfigured urls.py in Django
I have the following error and I can't figure out what to change in my urls.py to fix this:

```<code>django.core.exceptions.ImproperlyConfigured: The included URLconf 'MLtest.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
</code>```

Here's what my urls.py looks like:

```<code>from django.contrib import admin
from django.urls import path, include
from MLT import views
import debug_toolbar

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.thankYou),
    path(r'^__debug__', include(debug_toolbar.urls)),
]
</code>```

views.py:

```<code>from django.shortcuts import render
from django.template import RequestContext
from django.utils.translation import gettext as _

def thankYou(request):
    text = _("this is some random text")
    return render(request, 'thank_you.html', {'text': text})
</code>```

答: You mustn't use regex with path() function.Your last url path(r'^__debug__', include(debug_toolbar.urls)) contains regex expression. You can see url definitions here

Title: ImproperlyConfigured urls.py in Django

Body:
I have the following error and I can't figure out what to change in my urls.py to fix this:

django.core.exceptions.ImproperlyConfigured: The included URLconf 'MLtest.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

Here's what my urls.py looks like:

from django.contrib import admin
from django.urls import path, include
from MLT import views
import debug_toolbar

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.thankYou),
    path(r'^__debug__', include(debug_toolbar.urls)),
]

views.py:

from django.shortcuts import render
from django.template import RequestContext
from django.utils.translation import gettext as _

def thankYou(request):
    text = _("this is some random text")
    return render(request, 'thank_you.html', {'text': text})


问:
JS: Algorithm to group dates by years and months in a tree
I have a list of dates like this:

```<code>2019-12-15
2020-01-15
2020-01-23
</code>```

I want to present them in a tree like so:

```<code>2019
  |__12
     |__15
2020
  |__01
     |__15
     |__23
</code>```

is there an algorithm that can help achieve this with a good performance ? because the list of dates can get bigger and I'm afraid to face slow parsing algorithm.

Thanks in advance.

答:
You could take an object and get the parts for nested objects by checking the property and take this property or add a new object as property.

var data = ['2019-12-15', '2020-01-15', '2020-01-23'],
    tree = data.reduce((t, s) => {
        s.split('-').reduce((o, k) => o[k] = o[k] || {}, t);
        return t;
    }, {});

console.log(tree);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

A fast approach.

var data = ['2019-12-15', '2020-01-15', '2020-01-23'],
    tree = {};

for (const date of data) {
    let temp = tree;
    for (const key of date.split('-')) {
        if (!temp[key]) temp[key] = {};
        temp = temp[key];
    }
}

console.log(tree);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have a list of dates like this:

2019-12-15
2020-01-15
2020-01-23

I want to present them in a tree like so:

2019
  |__12
     |__15
2020
  |__01
     |__15
     |__23

is there an algorithm that can help achieve this with a good performance ? because the list of dates can get bigger and I'm afraid to face slow parsing algorithm.

Thanks in advance.

Body:
You could take an object and get the parts for nested objects by checking the property and take this property or add a new object as property.

var data = ['2019-12-15', '2020-01-15', '2020-01-23'],
    tree = data.reduce((t, s) => {
        s.split('-').reduce((o, k) => o[k] = o[k] || {}, t);
        return t;
    }, {});

console.log(tree);

.as-console-wrapper { max-height: 100% !important; top: 0; }

A fast approach.

var data = ['2019-12-15', '2020-01-15', '2020-01-23'],
    tree = {};

for (const date of data) {
    let temp = tree;
    for (const key of date.split('-')) {
        if (!temp[key]) temp[key] = {};
        temp = temp[key];
    }
}

console.log(tree);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to access MainPage instance from App on Xamarin?
I preload webview content then assign to MainPage.Content, it's easy from MainPage class. How can I access MainPage class instance and set Content from App.xaml.cs?

WWW.cs

```<code>public static class WWW
{
    public static WebView MyWeb;
    ...
}
</code>```

MainPage.xaml.cs

```<code>public partial class MainPage : ContentPage
{
    ...
    public MainPage()
    {
       InitializeComponent();
       Content = WWW.MyWeb;
    }
    ...
 }
</code>```

App.xaml.cs

```<code>protected override void OnAppLinkRequestReceived(Uri uri)
{

   //This line won't refresh the visible webview
   //WWW.MyWeb.Source = uri.ToString();

   //So I try to preload the url then update the Content

   //Preload page html
   string baseUrl = uri.GetLeftPart(UriPartial.Authority);
   string html = Get(uri.ToString());
   WWW.MyWeb.Source = new Xamarin.Forms.HtmlWebViewSource() { BaseUrl = baseUrl, Html = html };

   //Now it's time to update MainPage's Content:
   //**Question is: How can I access MainPage instance and it's Content?**

   base.OnAppLinkRequestReceived(uri);

 }
</code>```

Update: I think the definition of MainPage makes the confusion:

```<code>public App()
{

     InitializeComponent();
     MainPage = new MainPage();

}
</code>```

答:
The declaration is below:

```<code>MainPage = new MainPage();
</code>```

Since type of MainPage is Page and new MainPage() instantiates ContentPage the fix is:

```<code>((ContentPage)MainPage).Content = WWW.MyWeb;
</code>```

Body:
I preload webview content then assign to MainPage.Content, it's easy from MainPage class. How can I access MainPage class instance and set Content from App.xaml.cs?

WWW.cs

public static class WWW
{
    public static WebView MyWeb;
    ...
}

MainPage.xaml.cs

public partial class MainPage : ContentPage
{
    ...
    public MainPage()
    {
       InitializeComponent();
       Content = WWW.MyWeb;
    }
    ...
 }

App.xaml.cs

protected override void OnAppLinkRequestReceived(Uri uri)
{

   //This line won't refresh the visible webview
   //WWW.MyWeb.Source = uri.ToString();

   //So I try to preload the url then update the Content

   //Preload page html
   string baseUrl = uri.GetLeftPart(UriPartial.Authority);
   string html = Get(uri.ToString());
   WWW.MyWeb.Source = new Xamarin.Forms.HtmlWebViewSource() { BaseUrl = baseUrl, Html = html };

   //Now it's time to update MainPage's Content:
   //**Question is: How can I access MainPage instance and it's Content?**

   base.OnAppLinkRequestReceived(uri);

 }

Update: I think the definition of MainPage makes the confusion:

public App()
{

     InitializeComponent();
     MainPage = new MainPage();

}

Body:
The declaration is below:

MainPage = new MainPage();

Since type of MainPage is Page and new MainPage() instantiates ContentPage the fix is:

((ContentPage)MainPage).Content = WWW.MyWeb;


问:
why cerr flushes the buffer of cout
```<code>#include <iostream>
using std::cout;
using std::endl;
using std::cerr;
#include <cstdio>

int   main( )
{
    char pbuffer[BUFSIZ];
    setbuf(stdout, pbuffer);
    cout << "hello cout" ;
    sleep(5);
    cerr << "hello cerr";
    sleep(5);
    cout << "\nAll   done " << endl;
    sleep(5);
    return 0;
}
</code>```

after I compile and run the program above, it's output is :

```<code>hello couthello cerr
All   done
</code>```

but I think it should be:

```<code>hello cerrhello cout
All   done
</code>```

I want to know, why cerr flushes the buffer of cout ?

答:
First, a stream is allowed to flush whenever it feels like it.  I possible that some implementations of iostream do change buffering policies when outputting to an interactive device.  Unless you intentionally flush between outputs on the two streams, the order they appear is more or less unspecified; all you can count on is that a single << to cerr will not have characters from cout inserted into it.  In your case, the implementation is synchronizing cout and cerr in some way.  (You might want to see what happens if you redirect their output to different files.  Or to the same non-interactive file—C++ makes no distinction between interactive devices and others, but C does, and I expect that most C++ implementations follow C in this respect.)

FWIW, the two guarantees concerning order are:

cout is tied to cin, so any attempt to read on cin will flush cout, and

cerr has unitbuf set, so it will be flushed at the end of every << operator.

The idea behind the latter is, I think, to obtain something similar to C's line buffering, which C++ doesn't support directly—although if you use std::endl, you get the same effect as line buffering.

Title: why cerr flushes the buffer of cout

Body:
#include <iostream>
using std::cout;
using std::endl;
using std::cerr;
#include <cstdio>

int   main( )
{
    char pbuffer[BUFSIZ];
    setbuf(stdout, pbuffer);
    cout << "hello cout" ;
    sleep(5);
    cerr << "hello cerr";
    sleep(5);
    cout << "\nAll   done " << endl;
    sleep(5);
    return 0;
}

after I compile and run the program above, it's output is :

hello couthello cerr
All   done

but I think it should be:

hello cerrhello cout
All   done

I want to know, why cerr flushes the buffer of cout ?


答:
correct your url as below:</p>

```<code>urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.thankYou),
    path('__debug__/', include(debug_toolbar.urls)),
]
</code>```

Title: ImproperlyConfigured urls.py in Django

Body:
correct your url as below:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.thankYou),
    path('__debug__/', include(debug_toolbar.urls)),
]


答:
This timestamp is a moment in time since January 1st, 1970, represented in milliseconds.

You can make it readable using a little java.time like this:

```<code>public static void main(String[] args) {
    long millis = 1582013867500L;
    Instant instant = Instant.ofEpochMilli(millis);
    ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC);
    System.out.println(zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}
</code>```

The output is

2020-02-18T08:17:47.5Z
```

Title: How to read an existing TimeStamp?

Body:
This timestamp is a moment in time since January 1st, 1970, represented in milliseconds.

You can make it readable using a little java.time like this:

public static void main(String[] args) {
    long millis = 1582013867500L;
    Instant instant = Instant.ofEpochMilli(millis);
    ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC);
    System.out.println(zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}

The output is

2020-02-18T08:17:47.5Z


问:
How fix the Datetime picker localization problem
I have a problem with the date, for example if I enter the date 18/02/2020, the date is saved in the database is 17/02/2020 22:00:00 !!!
normally is a time zone problem or not? how to correct this problem and thank's.if i want save the date with UTC, how to do that ?

code .html :

<ng-template #datepicker>
  {{cell.label}} *

    <ng-container *ngIf="cell.type === 'date';else select2">
      <mat-form-field class="date-Picker-br-object">
        <input [disabled]="!cell.editable" name="{{cell.id}}" [required]="cell.required" style="width: 100% !important;" matInput [matDatepicker]="i" [(ngModel)]="cell.value" [disabled]="!cell.editable">
        <mat-datepicker-toggle matSuffix [for]="i"></mat-datepicker-toggle>
        <mat-datepicker #i></mat-datepicker>
      </mat-form-field>
    </ng-container>

{{msgRequired(cell.label)}}

{{otherErrorMessages[i]}}

</ng-template>
```

答:
I fixed my problem.I created a component, i named format-datepicker.

format-datepicker.ts :

```<code>import { NativeDateAdapter, DateAdapter, MAT_DATE_FORMATS, MatDateFormats } from "@angular/material";
import * as moment from 'moment';

export class AppDateAdapter extends NativeDateAdapter {

    parse(value: any): Date | null {
        if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
          const str = value.split('/');
          const year = Number(str[2]);
          const month = Number(str[1]) - 1;
          const date = Number(str[0]);
          return new Date(Date.UTC(year, month, date));
        }
        const timestamp = typeof value === 'number' ? value : Date.parse(value);
        return isNaN(timestamp) ? null : new Date(timestamp);
      }

      createDate(year: number, month: number, date: number): Date {
        return new Date(Date.UTC(year, month, date));
      }

      format(date: Date, displayFormat: Object): string {
        let now = moment();
        if (displayFormat === 'input') {
          let day: string = date.getUTCDate().toString();
          day = +day < 10 ? '0' + day : day;
          let month: string = (date.getUTCMonth() + 1).toString();
          month = +month < 10 ? '0' + month : month;
          let year = date.getUTCFullYear();
          return `${day}/${month}/${year}`;

        }
        // new Date(date.toDateString()).getUTCDate();
        return date.toDateString();

      }

   private _to2digit(n: number) {
       return (n);
       //return ('00' + n).slice(-2);
   }
}

export const APP_DATE_FORMATS =
{
   parse: {
       dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
   },
   display: {
       // dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
       dateInput: 'input',
       // monthYearLabel: { month: 'short', year: 'numeric', day: 'numeric' },
       monthYearLabel: 'inputMonth',
       dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
       monthYearA11yLabel: {year: 'numeric', month: 'long'},
   }
}
</code>```

format-datepicker.html :

```<code><mat-form-field>
  <input matInput placeholder="Select Date" [matDatepicker]="datepickerRef" name="datepicker" ngModel #dateCtrl="ngModel" required readonly/>
  <mat-datepicker-toggle [for]="datepickerRef" matSuffix></mat-datepicker-toggle>
  <mat-datepicker #datepickerRef></mat-datepicker>
  <mat-error *ngIf="dateCtrl.errors?.required && deptCtrl.touched">Choose date</mat-error>
  </mat-form-field>
</code>```

and in my app.component.ts :

```<code>import {DateAdapter, MAT_DATE_FORMATS} from '@angular/material/core';
import { AppDateAdapter, APP_DATE_FORMATS } from '../format-datepicker/format-datepicker.component';

@Component({
  selector: 'app-my selector',
  templateUrl: './my page.html',
  styleUrls: ['./my page.css'],
  providers: [
    {provide: DateAdapter, useClass: AppDateAdapter},
    {provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS}
  ]
})
</code>```

Body:
I fixed my problem.I created a component, i named format-datepicker.

format-datepicker.ts :

import { NativeDateAdapter, DateAdapter, MAT_DATE_FORMATS, MatDateFormats } from "@angular/material";
import * as moment from 'moment';

export class AppDateAdapter extends NativeDateAdapter {

    parse(value: any): Date | null {
        if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
          const str = value.split('/');
          const year = Number(str[2]);
          const month = Number(str[1]) - 1;
          const date = Number(str[0]);
          return new Date(Date.UTC(year, month, date));
        }
        const timestamp = typeof value === 'number' ? value : Date.parse(value);
        return isNaN(timestamp) ? null : new Date(timestamp);
      }

      createDate(year: number, month: number, date: number): Date {
        return new Date(Date.UTC(year, month, date));
      }

      format(date: Date, displayFormat: Object): string {
        let now = moment();
        if (displayFormat === 'input') {
          let day: string = date.getUTCDate().toString();
          day = +day < 10 ? '0' + day : day;
          let month: string = (date.getUTCMonth() + 1).toString();
          month = +month < 10 ? '0' + month : month;
          let year = date.getUTCFullYear();
          return `${day}/${month}/${year}`;

        }
        // new Date(date.toDateString()).getUTCDate();
        return date.toDateString();

      }

   private _to2digit(n: number) {
       return (n);
       //return ('00' + n).slice(-2);
   }
}

export const APP_DATE_FORMATS =
{
   parse: {
       dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
   },
   display: {
       // dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
       dateInput: 'input',
       // monthYearLabel: { month: 'short', year: 'numeric', day: 'numeric' },
       monthYearLabel: 'inputMonth',
       dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
       monthYearA11yLabel: {year: 'numeric', month: 'long'},
   }
}

format-datepicker.html :

<mat-form-field>
  <input matInput placeholder="Select Date" [matDatepicker]="datepickerRef" name="datepicker" ngModel #dateCtrl="ngModel" required readonly/>
  <mat-datepicker-toggle [for]="datepickerRef" matSuffix></mat-datepicker-toggle>
  <mat-datepicker #datepickerRef></mat-datepicker>
  <mat-error *ngIf="dateCtrl.errors?.required && deptCtrl.touched">Choose date</mat-error>
  </mat-form-field>

and in my app.component.ts :

import {DateAdapter, MAT_DATE_FORMATS} from '@angular/material/core';
import { AppDateAdapter, APP_DATE_FORMATS } from '../format-datepicker/format-datepicker.component';

@Component({
  selector: 'app-my selector',
  templateUrl: './my page.html',
  styleUrls: ['./my page.css'],
  providers: [
    {provide: DateAdapter, useClass: AppDateAdapter},
    {provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS}
  ]
})


问:
How to share Run/Debug Configurations in a version controlled project in Android Studio?
This should be really easy but for some reason I can't get it working. Google/Android Studio guys recommend to avoid having .idea and *.iml files under version control and use "Import project" instead. Works fine, no problem.

However, if I want to share a run/debug configuration, I check the "Share" checkbox in the "Run/Debug Configurations" dialog which in turn creates .idea/configurations/name.xml. All right, let's put an exception in .gitignore for this file.

Now, what happens:

git checkout (gradle files + .idea/configurations/name.xml)

Import project (all the .idea and *.iml files are generated)

Run -> Edit Configurations... -> do I see the shared configuration there? Nope!

It's because the configuration must be referenced by .idea/workspace.xml file. But everyone recommends to avoid having this file versioned because it contains user settings so it should be generated automatically.

So how to solve this chicken-egg problem?

答:
For me it was enough to add the "runConfigurations" folder to version control.

All Configurations have to have "Share" checked as to provide a seperate file for them.

Then once project is checked out all configurations are runnable again.

This works perfectly in Android Studio 3.5.3. (With my flutter repository)