问:
Localization fails in Visual Studio
I'm using VS2015 and I'm working on an ASP.NET MVC5 project. In my resources file I have this :

```<code>Name : Kisi_Gösterecek_Kişi
Value : Gösterecek Kişi
</code>```

In my View, I have this :

```<code><th width="45%">@Html.DisplayNameFor(model => model.ContactKisi)</th>
</code>```

As an error, I get this :

Cannot retrieve property 'Name' because localization failed.
  Type 'MyProject.Resources' is not public or does not contain a public static
  string property with the name 'Kisi_Gösterecek_Kiþi'.

I know that this is some kind of localization error. But I don't know how to solve it. Can you tell me how to fix this? Thanks.

答:
In Addition to the Answers given, verify the "DisplayAttribute" provided on the ViewModel, e.g.:

```<code>                                                                 check this
                                                                     ||
                                                                     \/
[Display(ResourceType = typeof(MyProject.Resources), Name = "Kisi_Gosterecek_Kisi")]
public string ContactKisi { get; set; }
</code>```

Verify that the Name provided as string is exactly matching the Key in the Resource file, incuding all special characters (you shouldn't use any though), and if you need to, you might want to ensure that the same Encoding of the File is used, e.g. "UTF-8"

Title: Localization fails in Visual Studio

Body:
I'm using VS2015 and I'm working on an ASP.NET MVC5 project. In my resources file I have this :

Name : Kisi_Gösterecek_Kişi
Value : Gösterecek Kişi

In my View, I have this :

@Html.DisplayNameFor(model => model.ContactKisi)

As an error, I get this :

Cannot retrieve property 'Name' because localization failed.
  Type 'MyProject.Resources' is not public or does not contain a public static
  string property with the name 'Kisi_Gösterecek_Kiþi'.

I know that this is some kind of localization error. But I don't know how to solve it. Can you tell me how to fix this? Thanks.

Body:
In Addition to the Answers given, verify the "DisplayAttribute" provided on the ViewModel, e.g.:

                                                                 check this
                                                                     ||
                                                                     \/
[Display(ResourceType = typeof(MyProject.Resources), Name = "Kisi_Gosterecek_Kisi")]
public string ContactKisi { get; set; }

Verify that the Name provided as string is exactly matching the Key in the Resource file, incuding all special characters (you shouldn't use any though), and if you need to, you might want to ensure that the same Encoding of the File is used, e.g. "UTF-8"


来源: stackexchange

问:
How can we do full text search in mysql with special characters like copyright (©), trademark (™), registered ®?
For example I have a item_table with description, alias fields, both are indexed like : FULLTEXT KEY ft_desc_alias_ngram (description,alias).

And I have some items like:

```<code>Test Item 1 ©
Test Item 2 ®
Test Item 3 ™
Test Item 4 © ® ™
</code>```

Now I would like to search for items that have ©, ® or anyone © ® ™.
To search only © I am using the query:

```<code>SELECT * FROM item_table WHERE match(description, alias) Against('©' IN NATURAL LANGUAGE MODE);
</code>```

but getting no result found.

答:
MySQL's built-in fulltext parser is designed for searching for words, not for single characters and comes with default minimum word length setting of 3 (innodb) or 4 (myisam) These settings mean that no words shorter than 3 or 4 words get indexed and therefore will not be found by a fulltext search. If you change these limits, then the fulltext indexes must be rebuilt - but again, the default fulltext parser was not really meant for searching a single character. Also, you must not forget that natural language mode searches on myisam tables do not return results for words that appear in more than 50% of the records because such words are considered a noise.

If you really would like to search for a single character using fulltext index, then use MySQL's ngram parser with token size set to 1 because you are not looking for a word, just for a character.

However, this index would not be useful for searching words within the same fields.

ContentLicense: CC BY-SA 3.0

Body:
For example I have a item_table with description, alias fields, both are indexed like : FULLTEXT KEY ft_desc_alias_ngram (description,alias).

And I have some items like:

Test Item 1 ©
Test Item 2 ®
Test Item 3 ™
Test Item 4 © ® ™

Now I would like to search for items that have ©, ® or anyone © ® ™.
To search only © I am using the query:

SELECT * FROM item_table WHERE match(description, alias) Against('©' IN NATURAL LANGUAGE MODE);

but getting no result found.


问:
How to get the active_id of one2many in odoo 9?
In the below method complete_operation I used to print active id, but it display None. I want to display current id of mrp.production. mrp.operations is one2many field of mrp.production.

class mrpProduction(models.Model):
    _inherit = "mrp.production"

    end_date = fields.Datetime('Scheduled End Date')
    operations = fields.One2many('mrp.operations','operation_id', 'Operations')

class mrpOperations(models.Model):
    _name = "mrp.operations"

    name = fields.Many2one("custom.operations", "Operation Name")
    status = fields.Selection([('Completed','Completed'),('Pending','Pending')],'Status')
    operation_id = fields.Integer()

    @api.multi
    def complete_operation(self):
        print self.id
        active_id=self.env.context.get('active_id')
        print active_id,'--'
```

答:
There's also a variable called active_ids in the context.
active_id is actually active_ids[0].</p>

```<code>        active_ids=self.env.context.get('active_ids')
</code>```

Body:
There's also a variable called active_ids in the context.
active_id is actually active_ids[0].

        active_ids=self.env.context.get('active_ids')


问:
How does AsReference on the ProtoMemberAttribute work
I have a distributed client - server application (multiple servers). The user can send data from one server to another. This is only allowed of the (customer defined) structure (aka DataType) is identical on all servers.

Therefore I do serialize the DataType with protobuf-net and compare the MD5 hash of the binary data.

But here is the catch: the binary data is different (and therefore the MD5 hash) but all attributes (decorated with ProtoMemberAttribute) have the exact same value!

I have several fields which have [ProtoMember(5, AsReference = true)] defined - which I suspect that the generation of the internal identification tag is not deterministic.

Does anyone know how that generation works in detail?

Is it in general a bad idea to rely on binary protobuf equality?

We are using VS2010. Net 4.0. an protobuf-net 2.0.0.668.

答:
I'm not aware of a reason it would be non-deterministic, but I also wouldn't absolutely guarantee it in every case.

Is it in general a bad idea to rely on binary protobuf equality?

Yes, it is. The format itself has multiple things where the same data can be presented differently:

fields can be in any order; libraries should present them in an ascending order, but are not required to

merged (concatenated) data can, as an example of the above, mean that semantically identical data can have multiple forms, since (as long as the fields don't collide) "chunk A, chunk B" should be semantically the same as "chunk B, chunk A"

the format does not explicitly disallow subnormal forms for varint encoding; by which I mean that the normal and expected representation of 5 is 0x05, but 0x8500, 0x858000, 0x85808000 (etc) are also all perfectly legal varint representations of 5

if you're using dynamic typing (protobuf-net only, not a core protobuf feature), then the type's assembly version will be part of the output; this can change


问:
Java: How to get the last word of the dynamic string
I have below string which I need to capture last word.

Below is my code but its not getting the last word.

The string at below location is dynamic and is not static string.

```<code>String secques1 = driver.findElement(By.xpath("//*[@class='small-12 medium-4 medium-offset-4 columns']/div/div/div/div[1]/div/div[1]/label")).getText();

String lastWord = secques1.substring(secques1.lastIndexOf(" ")+1);`
</code>```

答:
The result of getText() is always with  blank.
And you made a mistake that if the secques1 end with bank the program will throw exception.
so ,you need to do like this:

```<code>String secques1 = driver.findElement(By.xpath("//*[@class='small-12 medium-4 medium-offset-4 columns']/div/div/div/div[1]/div/div[1]/label")).getText().trim();
</code>```

add trim()

```<code>String lastWord = secques1.substring(secques1.length()-1);
</code>```

Body:
I have below string which I need to capture last word.

Below is my code but its not getting the last word.

The string at below location is dynamic and is not static string.

String secques1 = driver.findElement(By.xpath("//*[@class='small-12 medium-4 medium-offset-4 columns']/div/div/div/div[1]/div/div[1]/label")).getText();

String lastWord = secques1.substring(secques1.lastIndexOf(" ")+1);`

Body:
The result of getText() is always with  blank.
And you made a mistake that if the secques1 end with bank the program will throw exception.
so ,you need to do like this:

String secques1 = driver.findElement(By.xpath("//*[@class='small-12 medium-4 medium-offset-4 columns']/div/div/div/div[1]/div/div[1]/label")).getText().trim();

add trim()

String lastWord = secques1.substring(secques1.length()-1);


问:
How can instantiate the type in java
```<code>package crawler;

import org.apache.http.client.*;
import org.apache.http.client.methods.*;

class Crawler{

    public static void main(String args[]){

    HttpClient httpclient = new HttpClient();     // **HERE!!!!!!!!!**

    GetMethod getMethod = new GetMethod("http://www.google.com");

    int statusCode = httpclient.executeMethod(getMethod);

    System.out.println("response=" + getMethod.getResponseBodyAsString());;

    getMethod.releaseConnection();

    }

}
</code>```

The HttpClient from Apache Httpclient.

the code:

```<code>@SuppressWarnings("deprecation")
public interface HttpClient
</code>```

how can fix the problem "HttpClient httpclient = new HttpClient(); "?
THANKS!

答:
HttpClient  is an interface. YTou can't do that.

Correct way is

```<code>HttpClient client = HttpClientBuilder.create().build();
</code>```

Title: How can instantiate the type in java

Body:
package crawler;

import org.apache.http.client.*;
import org.apache.http.client.methods.*;

class Crawler{

    public static void main(String args[]){

    HttpClient httpclient = new HttpClient();     // **HERE!!!!!!!!!**

    GetMethod getMethod = new GetMethod("http://www.google.com");

    int statusCode = httpclient.executeMethod(getMethod);

    System.out.println("response=" + getMethod.getResponseBodyAsString());;

    getMethod.releaseConnection();

    }

}

The HttpClient from Apache Httpclient.

the code:

@SuppressWarnings("deprecation")
public interface HttpClient

how can fix the problem "HttpClient httpclient = new HttpClient(); "?
THANKS!

Body:
HttpClient  is an interface. YTou can't do that.

Correct way is

HttpClient client = HttpClientBuilder.create().build();


问:
Get data using post request in REST API Codeigniter
I am working with REST API for the first time in codeigniter.
I have following function in api

```<code> public function cource_topics_post() {
        $username = $this->input->post('username');
        //$value=$this->uri->segment(3);
        $this->response(array('status' => 1, 'username' =>  $username ));
    }
</code>```

but

```<code>$username = $this->input->post('username');
</code>```

isn't working. need help

My controller is as follows

```<code>    <?php

header("Access-Control-Allow-Origin: *");
require(APPPATH . '/libraries/REST_Controller.php');

class Admin extends REST_Controller {
    function __construct() {
        parent::__construct();
        $this->load->helper('file');
        $this->load->helper(array('form', 'url'));
    }

    public function cource_topics_post() {
        $username = $this->post('username');
        $password = $this->post('password');
        //$value=$this->uri->segment(3);
        $user = "faizan";
        $pass = "faizan";
        if($username == $user && $password == $pass){
            $this->response(array('status' => 1, 'logged in as' =>  $username ));
        }
        else{
            $this->response(array('status' => 0, 'Could not login' => 'incorrect username password'));
        }
    }

}
</code>```

I am using rest_controller.

答: check Rest config for POST, is activated ?

Body:
I am working with REST API for the first time in codeigniter.
I have following function in api

 public function cource_topics_post() {
        $username = $this->input->post('username');
        //$value=$this->uri->segment(3);
        $this->response(array('status' => 1, 'username' =>  $username ));
    }

but

$username = $this->input->post('username');

isn't working. need help

My controller is as follows

    <?php

header("Access-Control-Allow-Origin: *");
require(APPPATH . '/libraries/REST_Controller.php');

class Admin extends REST_Controller {
    function __construct() {
        parent::__construct();
        $this->load->helper('file');
        $this->load->helper(array('form', 'url'));
    }

    public function cource_topics_post() {
        $username = $this->post('username');
        $password = $this->post('password');
        //$value=$this->uri->segment(3);
        $user = "faizan";
        $pass = "faizan";
        if($username == $user && $password == $pass){
            $this->response(array('status' => 1, 'logged in as' =>  $username ));
        }
        else{
            $this->response(array('status' => 0, 'Could not login' => 'incorrect username password'));
        }
    }

}

I am using rest_controller.


问:
Xdebug is not getting enabled for PHP Version 7.0.1 in xampp
I have tried to enable the xdebug for this specific php version by changing the php.ini [XDebug] code to required format as below. Still no changes in the phpinfo.

```<code>zend_extension = "\xampp\php\ext\php_xdebug-2.5.0-7.1-vc14-nts-x86_64.dll"
xdebug.remote_enable = 1
xdebug.remote_handler = "dbgp"
xdebug.remote_host = "127.0.0.1"
xdebug.remote_port=9000
</code>```

I have tried with both nts & ts (32/64) xdebug versions. Please anyone help me out..

答:
You definitely need to use the Thread Safe version and not the nts version

The XDEBUG extension must match the compiled version of your Apache and PHP i.e. if Apache/PHP are 32 bit then so must XDEBUG be 32bit

Try putting the drive letter into the zend_extension = "C:\xampp\php\ext\php_xdebug-2.5.0-7.1-vc14-nts-x86_64.dll line. Assuming your XAMPP is installed on C:

You also specify PHP7.0.1 in the title but you are using the XDEBUG for PHP7.1 If you are really using PHP7.0.1 then you need to use php_xdebug-2.5.1-7.0-vc14.dll

Body:
I have tried to enable the xdebug for this specific php version by changing the php.ini [XDebug] code to required format as below. Still no changes in the phpinfo.

zend_extension = "\xampp\php\ext\php_xdebug-2.5.0-7.1-vc14-nts-x86_64.dll"
xdebug.remote_enable = 1
xdebug.remote_handler = "dbgp"
xdebug.remote_host = "127.0.0.1"
xdebug.remote_port=9000

I have tried with both nts & ts (32/64) xdebug versions. Please anyone help me out..


问:
Hide vertical scrollbar in 2 tables, but allow full scroll in one table
I want to be able to scroll the whole table together, but having just one vertical scrollbar at the right.
(The scroll can be done by using the vertical scrollbar at the right, through mousewheel or arrows)

I was able to do that, except that I can't hide the vertical scrollbar from the .fixedTable-body and when I use the mousewheel or arrows hover the .fixedTable-sidebar and .fixedTable-body tables, the vertical scrollbar at the right just acts weird.

What I was able to do:

Implement and connect the scroll in all tables body (Js in working fiddle below);

Hide vertical scrollbar in .fixedTable-sidebar for Webkit browsers and IE (haven't found solution to hide for FF) --> this was done by:

.fixedTable-sidebar::-webkit-scrollbar {
    display: none; /* hide scrollbar for Webkit Browsers */
}
.fixedTable-sidebar {
    -ms-overflow-style: none; /* hide scrollbar for IE */
}
```

<p><strong>What I have tried:</strong></p>

<ul>
<li>the pseudo class <code>:vertical</code> for webkit browsers, but doesn't work;</li>
</ul>

<pre class="lang-js prettyprint-override"><code>.fixedTable-body::-webkit-scrollbar:vertical {
    display: none;
}
</code>```

Not sure if this -ms-overflow-y-style exists for IE, but I tried and doesn't work either;

.fixedTable-body {
    -ms-overflow-y-style: none;
}
```

Also tried to hide the vertical scrollbar with padding, but wasn't able to do it.

EDIT

I was able to hide the vertical scrollbars from .fixedTable-sidebar and .fixedTable-body by creating an outer div in both elements and giving it overflow: hidden, then make the inner elements .fixedTable-sidebar and .fixedTable-body slightly bigger width > 100% --> with this I was able to hide the scrollbars for all browsers.

Now the only problem is the behaviour of the right vertical scrollbar when scroll over the .fixedTable-sidebar and .fixedTable-body (by using the mouse wheel or the keypad arrows)

See Updated Fiddle

答:
Well, I found a solution to hide the vertical bar at the middle of the table, but the vertical bar from the right still acts weird, but here it goes in case someone needs it :)

I was able to hide the vertical scrollbars from .fixedTable-sidebar and .fixedTable-body by creating an outer div in both elements and giving it overflow: hidden, then make the inner elements .fixedTable-sidebar and .fixedTable-body slightly bigger width > 100% --> with this I was able to hide the scrollbars for all browsers --> so it's a cross-browser solution

Updated Fiddle --> Only 1 vertical and 1 horizontal scrollbar table (with multiple tables inside and fixed header)

P.S.: I will open another question regarding the weird behaviour of the vertical scrollbar, then I'll post a link here :)

Body:
I want to be able to scroll the whole table together, but having just one vertical scrollbar at the right.
(The scroll can be done by using the vertical scrollbar at the right, through mousewheel or arrows)

I was able to do that, except that I can't hide the vertical scrollbar from the .fixedTable-body and when I use the mousewheel or arrows hover the .fixedTable-sidebar and .fixedTable-body tables, the vertical scrollbar at the right just acts weird.

What I was able to do:

Implement and connect the scroll in all tables body (Js in working fiddle below);

Hide vertical scrollbar in .fixedTable-sidebar for Webkit browsers and IE (haven't found solution to hide for FF) --> this was done by:

.fixedTable-sidebar::-webkit-scrollbar {
    display: none; /* hide scrollbar for Webkit Browsers */
}
.fixedTable-sidebar {
    -ms-overflow-style: none; /* hide scrollbar for IE */
}

What I have tried:

the pseudo class :vertical for webkit browsers, but doesn't work;

.fixedTable-body::-webkit-scrollbar:vertical {
    display: none;
}

Not sure if this -ms-overflow-y-style exists for IE, but I tried and doesn't work either;

.fixedTable-body {
    -ms-overflow-y-style: none;
}

Also tried to hide the vertical scrollbar with padding, but wasn't able to do it.

EDIT

I was able to hide the vertical scrollbars from .fixedTable-sidebar and .fixedTable-body by creating an outer div in both elements and giving it overflow: hidden, then make the inner elements .fixedTable-sidebar and .fixedTable-body slightly bigger width > 100% --> with this I was able to hide the scrollbars for all browsers.

Now the only problem is the behaviour of the right vertical scrollbar when scroll over the .fixedTable-sidebar and .fixedTable-body (by using the mouse wheel or the keypad arrows)

See Updated Fiddle


问:
submit from view to controller returns failure message
I'm a newbie in MVC. The questions which im asking here may be very basic. But without solving that I couldnt cross the road of learning.

I have a simple controller and two views. My requirement is initially a view will be loaded and on a button click, this will be loaded in to another view. Since I dont know how to post from a view to controller without using an ajax submit, I attempted that and it works. But at the end, it is redirecting to the second view but later showing the ajax fail alert. Couldnt identify, where exactly it goes wrong. Below given the code.

Controller.

```<code>public class DashboardController : Controller
    {
        //
        // GET: /Dashboard/
        [HttpPost]
        public ActionResult LoginResult()
        {
            string strName = Request["username"].ToString();
            return View("Validateresult");
        }
        public ActionResult Index()
        {
            return View();
        }
}
</code>```

View1

```<code>@model MvcApplication5.Models.Employee
@{
    ViewBag.Title = "Dashboard";
}
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

    <h2>Dashboard</h2>

 @using (Html.BeginForm("LoginResult", "Dashboard", FormMethod.Post))
    {
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }
<script>

    $(function () {
        $('#ajax_method').click(function (e) {
            e.preventDefault();
            var postData = {
                username: $("#username").val()

            };
            $.ajax({
                type: "POST",
                url: "/Dashboard/LoginResult",                            //Your Action name in the DropDownListConstroller.cs
                data: { username: $('#username').val() },  //Parameter in this function, Is case sensitive and also type must be string

                dataType: "json"

            }).done(function (data) {
                //Successfully pass to server and get response
                if (data.result = "OK") {
                    window.location.href = "Validateresult";
                    alert("submit successfully.");
                }
            }).fail(function (response) {
                if (response.status != 0) {
                    alert(1);
                    alert(response.status + " " + response.statusText);
                }
            });
        });

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

View2

```<code>@{
    ViewBag.Title = "Validateresult";
}

<h2>Validateresult</h2>
</code>```

Model

```<code>public class Employee
    {

            public string username { get; set; }
            public string age { get; set; }

    }
</code>```

Can someone suggest a better solution to submit a view to controller and to another view   or how to solve this issue?

答:
Here' a simple example. 1st view Test loads. Clicking submit posts back to your controller with the model and then redirects to view Test2.

```<code>public class TestController : Controller
    {
        //
        // GET: /Test/

        [HttpGet]
        public ActionResult Test()
        {
            var model = new CurrentViewModel();
            return View("Test", model);

        }

        [HttpGet]
        public ActionResult Test2()
        {
            var model = new CurrentViewModel();
            return View("Test2", model);

        }

        [HttpPost]
        public ActionResult TestPost(CurrentViewModel model)
        {
            return RedirectToAction("Test2");
        }
    }
</code>```

Test view with submit button.

```<code>    @using (Html.BeginForm("TestPost", "Test", FormMethod.Post))
    {
        <button type="submit">Submit</button>
    }
</code>```

Body:
I'm a newbie in MVC. The questions which im asking here may be very basic. But without solving that I couldnt cross the road of learning.

I have a simple controller and two views. My requirement is initially a view will be loaded and on a button click, this will be loaded in to another view. Since I dont know how to post from a view to controller without using an ajax submit, I attempted that and it works. But at the end, it is redirecting to the second view but later showing the ajax fail alert. Couldnt identify, where exactly it goes wrong. Below given the code.

Controller.

public class DashboardController : Controller
    {
        //
        // GET: /Dashboard/
        [HttpPost]
        public ActionResult LoginResult()
        {
            string strName = Request["username"].ToString();
            return View("Validateresult");
        }
        public ActionResult Index()
        {
            return View();
        }
}

View1

@model MvcApplication5.Models.Employee
@{
    ViewBag.Title = "Dashboard";
}

Dashboard

 @using (Html.BeginForm("LoginResult", "Dashboard", FormMethod.Post))
    {
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }

View2

@{
    ViewBag.Title = "Validateresult";
}

Validateresult

Model

public class Employee
    {

            public string username { get; set; }
            public string age { get; set; }

    }

Can someone suggest a better solution to submit a view to controller and to another view   or how to solve this issue?

Body:
Here' a simple example. 1st view Test loads. Clicking submit posts back to your controller with the model and then redirects to view Test2.

public class TestController : Controller
    {
        //
        // GET: /Test/

        [HttpGet]
        public ActionResult Test()
        {
            var model = new CurrentViewModel();
            return View("Test", model);

        }

        [HttpGet]
        public ActionResult Test2()
        {
            var model = new CurrentViewModel();
            return View("Test2", model);

        }

        [HttpPost]
        public ActionResult TestPost(CurrentViewModel model)
        {
            return RedirectToAction("Test2");
        }
    }

Test view with submit button.

    @using (Html.BeginForm("TestPost", "Test", FormMethod.Post))
    {
        <button type="submit">Submit</button>
    }


问:
Tomcat Thread pool per webapp
Does tomcat supports thread pool configuration for each webapp.
I think all webapps share the pool configured for the connector in tomcat.

Let's say I have webapps A and B, and A is more critical webapp. Let's
say my connector's pool size is 100, and there are 100 concurrent
requests destined for A and B each (so total 200 requests here). I
would like to allocate 70 threads to process A's requests, and only 30
for B's.

Note : We dont want to use multiple tomcat instances running,or run applications on different ports
We need same container config except the thread configuration per webapp..

Is there any example config /link for the same.

答:
Tomcat does not support it.
Thread pool setting is specified at executor or connector level in server.xml and cannot be specified at application level (in context.xml).

See also:
https://serverfault.com/questions/351830/tomcat-configure-maxthreads-per-webapp

Title: Tomcat Thread pool per webapp


问:
Codeigniter real time/date (ticking)
Can someone can show me how to create time/date ticking in Codeigniter and explain that code? I am really confused right now, because started learning CI few days ago. I woud love to take date and time from server not from user PC. This is what ive done so far and stucked.

this is view file

```<code>    <script>
    $(document).ready(function() {
            setInterval(timestamp, 1000);
        });

        function timestamp() {
            $.ajax({
            url: 'index.php',
            success: function(data) {
                $('#timestamp').html(data);
            },
        });
    }

    </script>
</head>
<body>
    <div class = "page">
        <header>
            <time id="timestamp">
                <?php
                    date_default_timezone_set('YOUR TIMEZONE');
                    echo date('l d F Y - H:i:s');
                ?>
            </time>
</code>```

答: The task you want to achieve will be achieved by Javascript and not by Codeigniter. Read this post : Creating real time ticking clock</p>

Title: Codeigniter real time/date (ticking)

Body:
Can someone can show me how to create time/date ticking in Codeigniter and explain that code? I am really confused right now, because started learning CI few days ago. I woud love to take date and time from server not from user PC. This is what ive done so far and stucked.

this is view file

            <time id="timestamp">
                <?php
                    date_default_timezone_set('YOUR TIMEZONE');
                    echo date('l d F Y - H:i:s');
                ?>
            </time>


问:
Primefaces wizard showing progress
I want to use Primefaces to display a wizard pretty much similar to the one shown in the showcase, but with some kind of tabview that displays the progress of the user, thus combining the wizard with the tabView.

Because I think this is quite a common requirement I was wondering if anyone tried the same and could give me some suggestions on how to do it?

答: Checkout primefaces latest release 2.2 that has a new feature of wizard progress step by step</p>

ContentLicense: CC BY-SA 2.5

Title: Primefaces wizard showing progress


问:
How can i pass 'n' number of requests based on value extracted from json path extractor
In Jmeter, I have extracted a value from json. The value is 2. My requirement is I need to send following HTTP samplers.
Here it is 2.
So I need to send the following 2 http requests.
http://IP:PORT/users/0?authSSOId
http://IP:PORT/users/1?authSSOId

If its 'n' request I need to pass upto 'n' counts in the url
How can i Achieve this

答: You can add loop controller which will execute HTTP request as per your extracted count. Structure will look like below:


问:
Mocking open function with mock_open
So I have function in my Django app business logic I want to test:

```<code>def parse_sectors_from_csv():
    sectors_csv = open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv'))
    sectors_csv_reader = csv.DictReader(sectors_csv)
    return [
        {
            'model': 'sector.sector',
            'id': index,
            'fields': {
                'name': row.get('Sector'),
                'slug': slugify(row['Sector']),
                'type_id': row.get('Type_Id')
            }
        }
        for index, row in enumerate(sectors_csv_reader, 1)
    ]
</code>```

I already test it for file existence and for existence of heading row.

Now I want to mock

```<code>open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv'))
</code>```

In my test.py I wrote

```<code>with patch('__builtin__.open', mock_open(read_data=sectors_csv_mock), create=True) as m:
        sectors = service.parse_sectors_from_csv()
        print('Sectors:', sectors)
        self.assertEqual(expected_sectors, sectors)
</code>```

But as I understand, it's passes empty file to function as it prints Sectors: []

I read mock_open dock for a few times and still can't figure it out.

```<code>>>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
...     with open('foo') as h: # what's happening here?
...         result = h.read() # here?
...
>>> m.assert_called_once_with('foo') # and here?
>>> assert result == 'bibble'
</code>```

答:
First rule of mocking: don't mock the objects/methods where they are defined, mock them where they are used. So no __builtin__.open but my_app.my_file.open

Second, I don't know what mock_open is but you can do it the normal mock way:

```<code>with mock.patch('my_app.my_file.open') as mocked_open:
    mocked_open.return_value = StringIO('foo')
</code>```

This works no matter what.

P.S.

Always use with when handling files

Title: Mocking open function with mock_open

Body:
So I have function in my Django app business logic I want to test:

def parse_sectors_from_csv():
    sectors_csv = open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv'))
    sectors_csv_reader = csv.DictReader(sectors_csv)
    return [
        {
            'model': 'sector.sector',
            'id': index,
            'fields': {
                'name': row.get('Sector'),
                'slug': slugify(row['Sector']),
                'type_id': row.get('Type_Id')
            }
        }
        for index, row in enumerate(sectors_csv_reader, 1)
    ]

I already test it for file existence and for existence of heading row.

Now I want to mock

open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv'))

In my test.py I wrote

with patch('__builtin__.open', mock_open(read_data=sectors_csv_mock), create=True) as m:
        sectors = service.parse_sectors_from_csv()
        print('Sectors:', sectors)
        self.assertEqual(expected_sectors, sectors)

But as I understand, it's passes empty file to function as it prints Sectors: []

I read mock_open dock for a few times and still can't figure it out.

>>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
...     with open('foo') as h: # what's happening here?
...         result = h.read() # here?
...
>>> m.assert_called_once_with('foo') # and here?
>>> assert result == 'bibble'

Body:
First rule of mocking: don't mock the objects/methods where they are defined, mock them where they are used. So no __builtin__.open but my_app.my_file.open

Second, I don't know what mock_open is but you can do it the normal mock way:

with mock.patch('my_app.my_file.open') as mocked_open:
    mocked_open.return_value = StringIO('foo')

This works no matter what.

P.S.

Always use with when handling files


问:
sending a POST request with Google's C++ native client
Can someone give an example of how to send a POST request with Google's C++ native client? The question has been asked before, but Google's documentation is not very helpful (and in some cases non-existent). And yes, I have been scouring github for help, but to no avail. </p>

答:
Did you have a look at the NativeClient SDK's examples?

In the nacl_sdk\pepper_\examples\api\url_loader folder you'll find an example of how to use the URLLoader.


问:
Sort a flat, associative array by numeric values, then by non-numeric keys
I have an array of string keys with numeric values to be used to create a list of tags with the number of occurrences of each tag resembling this:

```<code>$arrTags = [
    'mango' => 2,
    'orange' => 4,
    'apple' => 2,
    'banana' => 3
];
</code>```

I want to display the tags in a list with descending values, then the
tag names ascending to produce:

```<code>orange (4)
banana (3)
apple (2)
mango (2)
</code>```

arsort() is not suitable because it will put mango before apple. I'm guessing that usort() may be the way, but I'm not finding a suitable example in the comments on php.net.

答:
```<code>//preserve arrays keys for later use
$ar1= array_keys($your_array);

//preserve array's values for later use
$ar2= array_values($your_array);

//perform sorting by value and then by key
array_multisort($ar2, SORT_DESC, $ar1, SORT_DESC);

//combine sorted values and keys arrays to new array
$sorted_array = array_combine($ar1, $ar2);
</code>```

Must be ok.

ContentLicense: CC BY-SA 4.0

Body:
I have an array of string keys with numeric values to be used to create a list of tags with the number of occurrences of each tag resembling this:

$arrTags = [
    'mango' => 2,
    'orange' => 4,
    'apple' => 2,
    'banana' => 3
];

I want to display the tags in a list with descending values, then the
tag names ascending to produce:

orange (4)
banana (3)
apple (2)
mango (2)

arsort() is not suitable because it will put mango before apple. I'm guessing that usort() may be the way, but I'm not finding a suitable example in the comments on php.net.

Body:
//preserve arrays keys for later use
$ar1= array_keys($your_array);

//preserve array's values for later use
$ar2= array_values($your_array);

//perform sorting by value and then by key
array_multisort($ar2, SORT_DESC, $ar1, SORT_DESC);

//combine sorted values and keys arrays to new array
$sorted_array = array_combine($ar1, $ar2);

Must be ok.


问:
Properly notifying all listeners of a system wide named manual reset event and then immediately resetting it
I have a system-wide manual reset event that I create by doing the following:

```<code>EventWaitHandle notifyEvent = new EventWaitHandle(false, EventResetMode.ManualReset, notifyEventName, out createdEvent);
</code>```

Several processes create this event (e.g. it is shared amongst them). It is used for notifying when something gets updated.

I'd like to be able to set this event so that all of processes waiting on it are signaled and then immediately reset it so that subsequent Waits on the event are blocked.

If I do a

```<code>notifyEvent.Set();
notifyEvent.Reset();
</code>```

It will sometimes notify all listening processes.

If I do a

```<code>notifyEvent.Set();
Thread.Sleep(0);
notifyEvent.Reset();
</code>```

More processes get notified (I assumed this would happen since the scheduler has a chance to run).

And if I do

```<code>notifyEvent.Set();
Thread.Sleep(100);
notifyEvent.Reset();
</code>```

Then everything seems to work out fine and all processes (e.g. ~8) get notified consistently. I don't like the use of a "magic number" for the Sleep call.

Is there a better way to notify all listeners of an OS event in other processes that an event has occurred so that everyone listening to it at the time of notification receive the event signal and then immediately reset the event so that anyone else that goes to listen to the event will block?

UPDATE: A Semaphore doesn't seem to be a good fit here since the number of listeners to the event can vary over time. It is not known in advance how many listeners there will be when an even needs to be notified.

答:
You're using the EventWaitHandle class incorrectly. A reset event shouldn't be used to signal multiple threads. Instead, you need to create a reset event for each thread and then when you're ready loop through them all and use Set(). The master thread should not be calling the Reset() method. Each thread should be responsible for closing the gate behind them so to speak.

Here's a basic example:

```<code>static class Program
{
    static void Main()
    {
        List<ThreadState> states = new List<ThreadState>();
        ThreadState myState;
        Thread myThread;
        string data = "";

        for (int i = 0; i < 4; i++)
        {
            myThread = new Thread(Work);
            myState = new ThreadState();
            myState.gate = new EventWaitHandle(false, EventResetMode.ManualReset);
            myState.running = true;
            myState.index = i + 1;
            states.Add(myState);
            myThread.Start(myState);
        }

        Console.WriteLine("Enter q to quit.");

        while (data != "q")
        {
            data = Console.ReadLine();
            if (data != "q")
                foreach (ThreadState state in states)
                    state.gate.Set();
        }

        foreach (ThreadState state in states)
        {
            state.running = false;
            state.gate.Set();
        }

        Console.WriteLine("Press any key to quit.");
        Console.ReadKey();
    }

    static void Work(Object param)
    {
        ThreadState state = (ThreadState)param;
        while (state.running)
        {
            Console.WriteLine("Thread #" + state.index + " waiting...");
            state.gate.WaitOne();
            Console.WriteLine("Thread #" + state.index + " gate opened.");
            state.gate.Reset();
            Console.WriteLine("Thread #" + state.index + " gate closed.");
        }
        Console.WriteLine("Thread #" + state.index + " terminating.");
    }

    private class ThreadState
    {
        public int index;
        public EventWaitHandle gate;
        public bool running;
    }
}
</code>```

OwnerDisplayName: Jeff Moser

Body:
I have a system-wide manual reset event that I create by doing the following:

EventWaitHandle notifyEvent = new EventWaitHandle(false, EventResetMode.ManualReset, notifyEventName, out createdEvent);

Several processes create this event (e.g. it is shared amongst them). It is used for notifying when something gets updated.

I'd like to be able to set this event so that all of processes waiting on it are signaled and then immediately reset it so that subsequent Waits on the event are blocked.

If I do a

notifyEvent.Set();
notifyEvent.Reset();

It will sometimes notify all listening processes.

If I do a

notifyEvent.Set();
Thread.Sleep(0);
notifyEvent.Reset();

More processes get notified (I assumed this would happen since the scheduler has a chance to run).

And if I do

notifyEvent.Set();
Thread.Sleep(100);
notifyEvent.Reset();

Then everything seems to work out fine and all processes (e.g. ~8) get notified consistently. I don't like the use of a "magic number" for the Sleep call.

Is there a better way to notify all listeners of an OS event in other processes that an event has occurred so that everyone listening to it at the time of notification receive the event signal and then immediately reset the event so that anyone else that goes to listen to the event will block?

UPDATE: A Semaphore doesn't seem to be a good fit here since the number of listeners to the event can vary over time. It is not known in advance how many listeners there will be when an even needs to be notified.

LastEditorDisplayName: Jeff Moser

Body:
You're using the EventWaitHandle class incorrectly. A reset event shouldn't be used to signal multiple threads. Instead, you need to create a reset event for each thread and then when you're ready loop through them all and use Set(). The master thread should not be calling the Reset() method. Each thread should be responsible for closing the gate behind them so to speak.

Here's a basic example:

static class Program
{
    static void Main()
    {
        List<ThreadState> states = new List<ThreadState>();
        ThreadState myState;
        Thread myThread;
        string data = "";

        for (int i = 0; i < 4; i++)
        {
            myThread = new Thread(Work);
            myState = new ThreadState();
            myState.gate = new EventWaitHandle(false, EventResetMode.ManualReset);
            myState.running = true;
            myState.index = i + 1;
            states.Add(myState);
            myThread.Start(myState);
        }

        Console.WriteLine("Enter q to quit.");

        while (data != "q")
        {
            data = Console.ReadLine();
            if (data != "q")
                foreach (ThreadState state in states)
                    state.gate.Set();
        }

        foreach (ThreadState state in states)
        {
            state.running = false;
            state.gate.Set();
        }

        Console.WriteLine("Press any key to quit.");
        Console.ReadKey();
    }

    static void Work(Object param)
    {
        ThreadState state = (ThreadState)param;
        while (state.running)
        {
            Console.WriteLine("Thread #" + state.index + " waiting...");
            state.gate.WaitOne();
            Console.WriteLine("Thread #" + state.index + " gate opened.");
            state.gate.Reset();
            Console.WriteLine("Thread #" + state.index + " gate closed.");
        }
        Console.WriteLine("Thread #" + state.index + " terminating.");
    }

    private class ThreadState
    {
        public int index;
        public EventWaitHandle gate;
        public bool running;
    }
}

OwnerDisplayName: Spencer Ruport


问:
Ruby loop question and dumping results into YAML file
I am working on a Ruby script that will dump a key, value pair into a yaml file. But for some reason my loop is only grabbing the last instance in the loop. There should be multiple key value pairs.

Code:

```<code># Model for languages Table
class Language < ActiveRecord::Base
end

# Model for elements Table
class Element < ActiveRecord::Base
  has_many :element_translations
end

# Model for element_translations Table
class ElementTranslation < ActiveRecord::Base
  belongs_to :element
end

# Find ALL languages
lang = Language.all
# Get all elements
elements = Element.where("human_readable IS NOT NULL")
info = ''

elements.each do |el|
  lang.each do |l|
    et = el.element_translations.where("language_id = ?", l.id)
    et.each do |tran|
      info = {
        el.human_readable.to_s => tran.content.to_s
      }
    end
    File.open(l.code.to_s + ".yml", "w", :encoding => "UTF-8") do |f|
      YAML.dump(info, f)
    end
  end
end
</code>```

Any ideas?

答:
In this loop

```<code>et.each do |tran|
  info = {
    el.human_readable.to_s => tran.content.to_s
  }
end
</code>```

you repeatedly create new hash with one key el.human_readable.to_s with different values. However, even if you'll redo it as

```<code>info = {}
et.each do |tran|
  info[el.human_readable.to_s] = tran.content.to_s
end
</code>```

you won't get more than 1 result, because key isn't changing - you'll just repeatedly assign it different values. What exactly do you want to get dumped? May be you'd want an array here, not key-value map?

```<code>info_array = []
et.each do |tran|
  info_array << tran.content.to_s
end
info = { el.human_readable.to_s => info_array }
</code>```

Body:
I am working on a Ruby script that will dump a key, value pair into a yaml file. But for some reason my loop is only grabbing the last instance in the loop. There should be multiple key value pairs.

Code:

# Model for languages Table
class Language < ActiveRecord::Base
end

# Model for elements Table
class Element < ActiveRecord::Base
  has_many :element_translations
end

# Model for element_translations Table
class ElementTranslation < ActiveRecord::Base
  belongs_to :element
end

# Find ALL languages
lang = Language.all
# Get all elements
elements = Element.where("human_readable IS NOT NULL")
info = ''

elements.each do |el|
  lang.each do |l|
    et = el.element_translations.where("language_id = ?", l.id)
    et.each do |tran|
      info = {
        el.human_readable.to_s => tran.content.to_s
      }
    end
    File.open(l.code.to_s + ".yml", "w", :encoding => "UTF-8") do |f|
      YAML.dump(info, f)
    end
  end
end

Any ideas?

Body:
In this loop

et.each do |tran|
  info = {
    el.human_readable.to_s => tran.content.to_s
  }
end

you repeatedly create new hash with one key el.human_readable.to_s with different values. However, even if you'll redo it as

info = {}
et.each do |tran|
  info[el.human_readable.to_s] = tran.content.to_s
end

you won't get more than 1 result, because key isn't changing - you'll just repeatedly assign it different values. What exactly do you want to get dumped? May be you'd want an array here, not key-value map?

info_array = []
et.each do |tran|
  info_array << tran.content.to_s
end
info = { el.human_readable.to_s => info_array }


问:
How to find all permissions for all users in a sql?
```<code>CREATE TABLE Users(UserId int,UserName nvarchar(15), Permisions int)
CREATE TABLE Permissions(PermissionId int,Title NVARCHAR(15))
</code>```

I Have this Permissions Table with this data:

```<code>Id  Title
--------------
1   'Read'
2   'Write'
4   'Update'
8   'Delete'
</code>```

And Users Table

```<code>Id  UserName    Permission
-----------------------------------
1   'David'     3
2   'Sara'      12
3   'Maryam'    15
</code>```

in this case 'David' has 'Read' and 'Write' Access (1+2=3)
'Sara' has 'Update' and 'Delete' Access(4+8=12)
and 'Maryam' has 'Read', 'Write', 'Update' and 'Delete' Access(1+2+4+8=15)

How to Join this tables in sql and query with following result

```<code>UserName        Title
------------------------------
'David'         'Read'
'David'         'Write'
'Sara'          'Update'
'Sara'          'Delete'
'Maryam'        'Read'
'Maryam'        'Write'
'Maryam'        'Update'
'Maryam'        'Delete'
</code>```

答:
Assuming permissions at the lower level are included in higher levels, this would work...

```<code>with CTE as
(
select p.*, sum(id) over (order by id) as p_level
from PermissionTable p
)
select u.*, p.*
from UserTable u
inner join CTE p
on u.permission >= p.p_level
</code>```

Otherwise

```<code>with CTE as
(
select a.Title, a.id + b.id as p_level
from PermissionTable a
cross join PermissionTable b
)
select u.*, p.*
from UserTable u
inner join CTE p
on u.permission = p.p_level
</code>```

Body:
CREATE TABLE Users(UserId int,UserName nvarchar(15), Permisions int)
CREATE TABLE Permissions(PermissionId int,Title NVARCHAR(15))

I Have this Permissions Table with this data:

Id  Title
--------------
1   'Read'
2   'Write'
4   'Update'
8   'Delete'

And Users Table

Id  UserName    Permission
-----------------------------------
1   'David'     3
2   'Sara'      12
3   'Maryam'    15

in this case 'David' has 'Read' and 'Write' Access (1+2=3)
'Sara' has 'Update' and 'Delete' Access(4+8=12)
and 'Maryam' has 'Read', 'Write', 'Update' and 'Delete' Access(1+2+4+8=15)

How to Join this tables in sql and query with following result

UserName        Title
------------------------------
'David'         'Read'
'David'         'Write'
'Sara'          'Update'
'Sara'          'Delete'
'Maryam'        'Read'
'Maryam'        'Write'
'Maryam'        'Update'
'Maryam'        'Delete'

Body:
Assuming permissions at the lower level are included in higher levels, this would work...

with CTE as
(
select p.*, sum(id) over (order by id) as p_level
from PermissionTable p
)
select u.*, p.*
from UserTable u
inner join CTE p
on u.permission >= p.p_level

Otherwise

with CTE as
(
select a.Title, a.id + b.id as p_level
from PermissionTable a
cross join PermissionTable b
)
select u.*, p.*
from UserTable u
inner join CTE p
on u.permission = p.p_level


问:
How to rotate a vtk scene around a specific point?
I have a 3D vtk scene representing a point cloud, displayed through a QVTKWidget.
vtk7.1, Qt5.8.

I want to be able to rotate the scene around specific coordinates, but I don't know how to proceed.

I like the trackball interaction. I just need to set the center, but I'm a bit lost in VTK api.
I think I can do this by changing the rotation matrix : InvTranslation + Rotation + Translation should do the trick. I see two ways of doing it :

1)

Get the Rotation Matrix computed by VTK

Generate a new matrix

Apply the matrix.

2)

set a transform to vtk to apply before the process

set a transform to vtk to apply after the process

Am I in the right direction? If yes, how I can implement one of these solutions..?

Thank i advance,

Etienne.

答:
Problem solved. The change of focale would also change the view. SO, I aplied a few geometric transform, and there it is. </p>

```<code>// vtk Element /////////////////////////////////////////////////////////
vtkRenderWindowInteractor *rwi = widget->GetInteractor();
vtkRenderer *renderer = widget->GetRenderWindow()->GetRenderers()->GetFirstRenderer();
vtkCamera *camera = renderer->GetActiveCamera();

// Camera Parameters ///////////////////////////////////////////////////
double *focalPoint = camera->GetFocalPoint();
double *viewUp = camera->GetViewUp();
double *position = camera->GetPosition();
double axis[3];
axis[0] = -camera->GetViewTransformMatrix()->GetElement(0,0);
axis[1] = -camera->GetViewTransformMatrix()->GetElement(0,1);
axis[2] = -camera->GetViewTransformMatrix()->GetElement(0,2);

// Build The transformatio /////////////////////////////////////////////////
vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();
transform->Identity();

transform->Translate(d->center[0], d->center[1], d->center[2]);
transform->RotateWXYZ(rxf, viewUp); // Azimuth
transform->RotateWXYZ(ryf, axis);   // Elevation
transform->Translate(-d->center[0], -d->center[1], -d->center[2]);

double newPosition[3];
transform->TransformPoint(position,newPosition); // Transform Position
double newFocalPoint[3];
transform->TransformPoint(focalPoint, newFocalPoint); // Transform Focal Point

camera->SetPosition(newPosition);
camera->SetFocalPoint(newFocalPoint);

// Orhthogonalize View Up //////////////////////////////////////////////////
camera->OrthogonalizeViewUp();
renderer->ResetCameraClippingRange();

rwi->Render();
</code>```

Body:
Problem solved. The change of focale would also change the view. SO, I aplied a few geometric transform, and there it is.

// vtk Element /////////////////////////////////////////////////////////
vtkRenderWindowInteractor *rwi = widget->GetInteractor();
vtkRenderer *renderer = widget->GetRenderWindow()->GetRenderers()->GetFirstRenderer();
vtkCamera *camera = renderer->GetActiveCamera();

// Camera Parameters ///////////////////////////////////////////////////
double *focalPoint = camera->GetFocalPoint();
double *viewUp = camera->GetViewUp();
double *position = camera->GetPosition();
double axis[3];
axis[0] = -camera->GetViewTransformMatrix()->GetElement(0,0);
axis[1] = -camera->GetViewTransformMatrix()->GetElement(0,1);
axis[2] = -camera->GetViewTransformMatrix()->GetElement(0,2);

// Build The transformatio /////////////////////////////////////////////////
vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();
transform->Identity();

transform->Translate(d->center[0], d->center[1], d->center[2]);
transform->RotateWXYZ(rxf, viewUp); // Azimuth
transform->RotateWXYZ(ryf, axis);   // Elevation
transform->Translate(-d->center[0], -d->center[1], -d->center[2]);

double newPosition[3];
transform->TransformPoint(position,newPosition); // Transform Position
double newFocalPoint[3];
transform->TransformPoint(focalPoint, newFocalPoint); // Transform Focal Point

camera->SetPosition(newPosition);
camera->SetFocalPoint(newFocalPoint);

// Orhthogonalize View Up //////////////////////////////////////////////////
camera->OrthogonalizeViewUp();
renderer->ResetCameraClippingRange();

rwi->Render();


问:
How can I make Intent From Activity to Fragment in android?
Like this. It is working good from fragment to activity.</p>
```<code>Intent intent = new Intent(Location.this,MessageActivity.class);
startActivity(intent);
</code>```

答:
```<code>Fragment myFragment  = new MyFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.youLayout, myFragment
                            fragmentTransaction.addToBackStack("youfragment");
                            fragmentTransaction.commit();
</code>```

Body:
Like this. It is working good from fragment to activity.

Intent intent = new Intent(Location.this,MessageActivity.class);
startActivity(intent);


问:
Repeated code in two js functions, how to eliminate and make code elegant
Okay so I have the following javascript code:

```<code><script type="text/javascript">
window.onload=function() {
    // variables for the different pulldown menu's
    var selectPotency = document.getElementById("select-potency");
    var selectEssence = document.getElementById("select-essence");
    var selectAspect = document.getElementById("select-aspect");

    // defualt values of runes
    document.getElementById('potencyRune').innerHTML = 'Jode';
    document.getElementById('essenceRune').innerHTML = 'Oko';
    document.getElementById('aspectRune').innerHTML = 'Ta';

    // start with white glyph text
    document.getElementById('glyph').style.color = "#FFF";
    document.getElementById('select-potency').style.color = 'inherit';
    document.getElementById('select-essence').style.color = 'inherit';
    document.getElementById('select-aspect').style.color = 'inherit';

    // lookup tables for runes and translations
    var PotencyTable1 = {...};
    var PotencyTable0 = {...};
    var EssenceTable = {...};
    var AspectTable = {...};

    // This function changes the potency rune from select-potency
    selectPotency.onchange=function getPotency() {
        var potency = this.value;
        var elem = document.getElementById('select-essence');
        var polarity = elem.options[elem.selectedIndex].value;

        if (polarity == 0) {
            document.getElementById('potencyRune').innerHTML = PotencyTable0[potency]();
        }
        if (polarity == 1) {
            document.getElementById('potencyRune').innerHTML = PotencyTable1[potency]();
        }
    }

    // This function changes the essence rune from select-essence
    selectEssence.onchange=function getEssence() {
        var essence  = this.options[this.selectedIndex].text;
        var polarity = this.options[this.selectedIndex].value;

        var elem = document.getElementById('select-potency');
        var potency = elem.options[elem.selectedIndex].value;

        document.getElementById('essenceRune').innerHTML = EssenceTable[essence]();

        if (polarity == 0) {
            document.getElementById('potencyRune').innerHTML = PotencyTable0[potency]();
        }
        if (polarity == 1) {
            document.getElementById('potencyRune').innerHTML = PotencyTable1[potency]();
        }
    }

    // This function changes the color of the glyph name & aspect rune from select-aspect
    selectAspect.onchange=function getAspect() {
        var aspect = this.value;
        var colour = $(this).find('option:selected').attr('data-color');

        document.getElementById('glyph').style.color = colour;
        document.getElementById('aspectRune').innerHTML = AspectTable[aspect]();
    }
}
</code>```

Now there's 3 different areas where I have code repeated because I don't know how else to do it:

1) the //default values of runes - each of the 3 different functions sets these values when the user makes their selection from the drop down, but I don't know how to make these functions run at page load to get the initial values of the drop down selects so I've done it this way to set the default values.

2) the //start with white glyph text - again, similar to #1, I don't know how to make the getAspect function run at page load to set the color white so i'm manually setting the text color white.

3) in functions getPotency and getEssence there are two if statements that are completely identical. they belong to the getPotency function but the getEssence function also changes them but I didn't know how to make a call to it so i'm repeating the code.

4) lastly, if you have any alterations to make my code more elegant/professional I would greatly appreciate it. I'm self taught and this is my first time dabbling with javascript.

Thank you very much in advance for all your feedback!

Here's the website I've got soo far with the code

答:
Typically this is the kind of question better suited to Code Review, but since it is clear that you put some time and effort into your question I will provide an answer on this site anyways.

Here are a few pointers to help you understand how I went about refactoring your code:

Have each Table store values as strings, instead of functions that return strings;

Combine your PotencyTables together using arrays of length 2, which has the side effect of removing the need to use an if statement when accessing runes based on polarity;

Default #glyph color (#fff) and color: inherit on #glyph >
select  would be better set by CSS instead of JavaScript;

Change innerHTML to textContent when you're not inserting tags;

Move each

          Lethal's ESODEX

            Enchanting

   <select id="select-potency">
    <option value="trifling">LVL .1 - Trifling</option>
    <option value="inferior">LVL .5 - Inferior</option>
    <option value="petty">LVL 10 - Petty</option>
    <option value="slight">LVL 15 - Slight</option>
    <option value="minor">LVL 20 - Minor</option>
    <option value="lesser">LVL 25 - Lesser</option>
    <option value="moderate">LVL 30 - Moderate</option>
    <option value="average">LVL 35 - Average</option>
    <option value="strong">LVL 40 - Strong</option>
    <option value="major">LVL C10 - Major</option>
    <option value="greater">LVL C30 - Greater</option>
    <option value="grand">LVL C50 - Grand</option>
    <option value="splendid">LVL C70 - Splendid</option>
    <option value="monumental">LVL C100- Monumental</option>
   </select>
    Glyph of
   <select id="select-essence" name="essence-all">
    <option>Absorb Health</option>
    <option>Absorb Magicka</option>
    <option>Absorb Stamina</option>
    <option>Bashing</option>
    <option>Crushing</option>
    <option>Decrease Health</option>
    <option>Decrease Physical Harm</option>
    <option>Decrease Spell Harm</option>
    <option>Disease Resist</option>
    <option>Fire Resist</option>
    <option>Flame</option>
    <option>Foulness</option>
    <option>Frost</option>
    <option>Frost Resist</option>
    <option>Hardening</option>
    <option>Health</option>
    <option>Health Regen</option>
    <option>Increase Magical Harm</option>
    <option>Increase Physical Harm</option>
    <option>Magicka</option>
    <option>Magicka Regen</option>
    <option>Poison</option>
    <option>Poison Resist</option>
    <option>Potion Boost</option>
    <option>Potion Speed</option>
    <option>Rage</option>
    <option>Reduce Feat Cost</option>
    <option>Reduce Spell Cost</option>
    <option>Shielding</option>
    <option>Shock</option>
    <option>Shock Resist</option>
    <option>Stamina</option>
    <option>Stamina Regen</option>
    <option>Weakening</option>
   </select>

   <select id="select-aspect">
    <option style="color:#FFF;" value="base">Base</option>
    <option style="color:#2DC50E;" value="fine">Fine</option>
    <option style="color:#3A92FF;" value="superior">Superior</option>
    <option style="color:#A02EF7;" value="artifact">Artifact</option>
    <option style="color:#E5CB51;" value="legendary">Legendary</option>
   </select>

          Last Updated Mar. 26, 2017

          For ESO version: 2.7.10
          © Copyright 2017

  <script type="text/javascript">
    var Potency = {
      $select: document.getElementById("select-potency"),
      $rune: document.getElementById('potencyRune'),
      runes: {
        "trifling": ["Jode", "Jora"],
        "inferior": ["Notade", "Porade"],
        "petty": ["Ode", "Jera"],
        "slight": ["Tade", "Jejora"],
        "minor": ["Jayde", "Odra"],
        "lesser": ["Edode", "Pojora"],
        "moderate": ["Pojode", "Edora"],
        "average": ["Rekude", "Jaera"],
        "strong": ["Hade", "Pora"],
        "major": ["Idode", "Denara"],
        "greater": ["Pode", "Rera"],
        "grand": ["Kedeko", "Derado"],
        "splendid": ["Rede", "Recura"],
        "monumental": ["Kude", "Cura"]
      }
    }

    var Essence = {
      $select: document.getElementById("select-essence"),
      $rune: document.getElementById('essenceRune'),
      runes: {
        "Absorb Health": "Oko",
        "Absorb Magicka": "Makko",
        "Absorb Stamina": "Deni",
        "Bashing": "Jaedi / Kaderi",
        "Crushing": "Deteri",
        "Decrease Health": "Okoma",
        "Decrease Physical Harm": "Lire / Taderi",
        "Decrease Spell Harm": "Makderi",
        "Disease Resist": "Haoko",
        "Fire Resist": "Rakeipa",
        "Flame": "Rakeipa",
        "Foulness": "Haoko",
        "Frost": "Dekeipa",
        "Frost Resist": "Dekeipa",
        "Hardening": "Deteri",
        "Health": "Oko",
        "Health Regen": "Okoma",
        "Increase Magical Harm": "Makderi",
        "Increase Physical Harm": "Lire / Taderi",
        "Magicka": "Makko",
        "Magicka Regen": "Makkoma",
        "Poison": "Kuoko",
        "Poison Resist": "Kuoko",
        "Potion Boost": "Oru",
        "Potion Speed": "Oru",
        "Rage": "Okori",
        "Reduce Feat Cost": "Denima",
        "Reduce Spell Cost": "Makkoma",
        "Shielding": "Jaedi / Kaderi",
        "Shock": "Meip",
        "Shock Resist": "Meip",
        "Stamina": "Deni",
        "Stamina Regen": "Denima",
        "Weakening": "Okori"
      },
      polarities: {
        "Absorb Health": 0,
        "Absorb Magicka": 0,
        "Absorb Stamina": 0,
        "Bashing": 1,
        "Crushing": 0,
        "Decrease Health": 0,
        "Decrease Physical Harm": 0,
        "Decrease Spell Harm": 0,
        "Disease Resist": 0,
        "Fire Resist": 0,
        "Flame": 1,
        "Foulness": 1,
        "Frost": 1,
        "Frost Resist": 0,
        "Hardening": 1,
        "Health": 1,
        "Health Regen": 1,
        "Increase Magical Harm": 1,
        "Increase Physical Harm": 1,
        "Magicka": 1,
        "Magicka Regen": 1,
        "Poison": 1,
        "Poison Resist": 0,
        "Potion Boost": 1,
        "Potion Speed": 0,
        "Rage": 1,
        "Reduce Feat Cost": 0,
        "Reduce Spell Cost": 0,
        "Shielding": 0,
        "Shock": 1,
        "Shock Resist": 0,
        "Stamina": 1,
        "Stamina Regen": 1,
        "Weakening": 0
      }
    }

    var Aspect = {
      $select: document.getElementById("select-aspect"),
      $rune: document.getElementById('aspectRune'),
      runes: {
        "base": "Ta",
        "fine": "Jejota",
        "superior": "Denata",
        "artifact": "Rekuta",
        "legendary": "Kuta"
      },
      colors: {
        "base": "#FFF",
        "fine": "#2DC50E",
        "superior": "#3A92FF",
        "artifact": "#A02EF7",
        "legendary": "#E5CB51"
      }
    }

    var glyph = document.getElementById('glyph')

    function update() {
      var potency = Potency.$select.value
      var essence = Essence.$select.value
      var aspect = Aspect.$select.value

      var polarity = Essence.polarities[essence]
      var color = Aspect.colors[aspect]

      glyph.style.color = color

      Potency.$rune.textContent = Potency.runes[potency][polarity]
      Essence.$rune.textContent = Essence.runes[essence]
      Aspect.$rune.textContent = Aspect.runes[aspect]
    }

    [Potency, Essence, Aspect].forEach(function(E) {
      E.$select.addEventListener('change', update)
    })

    update()
  </script>

  <script type="text/javascript">
    $(".fade").click(function(event) {
      event.preventDefault();
      linkLocation = this.href;
      $("body").fadeOut(1000, redirectPage);
    });

    function redirectPage() {
      window.location = linkLocation;
    }
  </script>

```

Body:
Typically this is the kind of question better suited to Code Review, but since it is clear that you put some time and effort into your question I will provide an answer on this site anyways.

Here are a few pointers to help you understand how I went about refactoring your code:

Have each Table store values as strings, instead of functions that return strings;

Combine your PotencyTables together using arrays of length 2, which has the side effect of removing the need to use an if statement when accessing runes based on polarity;

Default #glyph color (#fff) and color: inherit on #glyph >
select  would be better set by CSS instead of JavaScript;

Change innerHTML to textContent when you're not inserting tags;

Move each <script> just before the </body> tag to avoid the need to use onload;

Use a different, nested data structure to store your <select>, rune, and table of lookup values all in one place (one each for Potency, Essence, and Aspect);

select.options[select.selectedIndex].value can be shortened to select.value;

Put your colors and polarities inside your nested data structure instead of embedded in HTML;

Combine all event listeners into a single update function, and add them to each of your selects with a forEach loop; and

Call update() once before the end of your script instead of setting the default runes manually.

When running the snippet below, be sure to click "Full Page" or else the content gets cut off.

Refactored Code:

#glyph > select {
  color: inherit;
}

<!DOCTYPE html>
<html>

<head>
  <link rel="icon" sizes="16x16 32x32" href="http://dstealth.com/favicon.ico">
  <link rel="stylesheet" type="text/css" href="http://eso.dstealth.com/style.css" />
  <title>ESODEX - Enchanting Glyph Calculator</title>
  <meta name="viewport" content="width=device-width, height=device-height, initial-scale=0.85, minimum-scale=0.85">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<body>
  <div id="body">
    <div id="header" class="fog">
      <div id="table-cell">
        <div align="center">
          <span class="f30">Lethal's ESODEX</span><br/>
          <span class="f20 teal fog">&nbsp;&nbsp;Enchanting&nbsp;&nbsp;</span>
        </div>
      </div>
    </div>
    <div id="smoketop">&nbsp;</div>
    <div id="wrapper">
      <div id="fogcontent" class="fogcontent">
        <div id="content" align="center">
          <br/>
          <span id="glyph">
   <select id="select-potency">
    <option value="trifling">LVL .1 - Trifling</option>
    <option value="inferior">LVL .5 - Inferior</option>
    <option value="petty">LVL 10 - Petty</option>
    <option value="slight">LVL 15 - Slight</option>
    <option value="minor">LVL 20 - Minor</option>
    <option value="lesser">LVL 25 - Lesser</option>
    <option value="moderate">LVL 30 - Moderate</option>
    <option value="average">LVL 35 - Average</option>
    <option value="strong">LVL 40 - Strong</option>
    <option value="major">LVL C10 - Major</option>
    <option value="greater">LVL C30 - Greater</option>
    <option value="grand">LVL C50 - Grand</option>
    <option value="splendid">LVL C70 - Splendid</option>
    <option value="monumental">LVL C100- Monumental</option>
   </select>
   &nbsp;Glyph of&nbsp;
   <select id="select-essence" name="essence-all">
    <option>Absorb Health</option>
    <option>Absorb Magicka</option>
    <option>Absorb Stamina</option>
    <option>Bashing</option>
    <option>Crushing</option>
    <option>Decrease Health</option>
    <option>Decrease Physical Harm</option>
    <option>Decrease Spell Harm</option>
    <option>Disease Resist</option>
    <option>Fire Resist</option>
    <option>Flame</option>
    <option>Foulness</option>
    <option>Frost</option>
    <option>Frost Resist</option>
    <option>Hardening</option>
    <option>Health</option>
    <option>Health Regen</option>
    <option>Increase Magical Harm</option>
    <option>Increase Physical Harm</option>
    <option>Magicka</option>
    <option>Magicka Regen</option>
    <option>Poison</option>
    <option>Poison Resist</option>
    <option>Potion Boost</option>
    <option>Potion Speed</option>
    <option>Rage</option>
    <option>Reduce Feat Cost</option>
    <option>Reduce Spell Cost</option>
    <option>Shielding</option>
    <option>Shock</option>
    <option>Shock Resist</option>
    <option>Stamina</option>
    <option>Stamina Regen</option>
    <option>Weakening</option>
   </select>
   &nbsp;
   <select id="select-aspect">
    <option style="color:#FFF;" value="base">Base</option>
    <option style="color:#2DC50E;" value="fine">Fine</option>
    <option style="color:#3A92FF;" value="superior">Superior</option>
    <option style="color:#A02EF7;" value="artifact">Artifact</option>
    <option style="color:#E5CB51;" value="legendary">Legendary</option>
   </select><br/>
  </span>
          <br/>
          <hr><br/><br/>
          <div id="runes" class="f15">
            <span id="potencyRune">&nbsp;</span>&nbsp;&nbsp;
            <span id="essenceRune">&nbsp;</span>&nbsp;&nbsp;
            <span id="aspectRune">&nbsp;</span>
          </div>
          <br/><br/><br/><br/>
        </div>
      </div>
    </div>
    <div id="smokebot">&nbsp;</div>
    <div id="footer" class="fog" align="center">
      <div id="table-cell">
        <div align="center">
          <span class="f10">Last Updated Mar. 26, 2017</span><br/><br/>
          <span id="align-left" class="f10">For ESO version: 2.7.10</span>
          <span id="align-right" class="f10">&copy; Copyright 2017</span>
        </div>
      </div>
    </div>
  </div>

  <script type="text/javascript">
    var Potency = {
      $select: document.getElementById("select-potency"),
      $rune: document.getElementById('potencyRune'),
      runes: {
        "trifling": ["Jode", "Jora"],
        "inferior": ["Notade", "Porade"],
        "petty": ["Ode", "Jera"],
        "slight": ["Tade", "Jejora"],
        "minor": ["Jayde", "Odra"],
        "lesser": ["Edode", "Pojora"],
        "moderate": ["Pojode", "Edora"],
        "average": ["Rekude", "Jaera"],
        "strong": ["Hade", "Pora"],
        "major": ["Idode", "Denara"],
        "greater": ["Pode", "Rera"],
        "grand": ["Kedeko", "Derado"],
        "splendid": ["Rede", "Recura"],
        "monumental": ["Kude", "Cura"]
      }
    }

    var Essence = {
      $select: document.getElementById("select-essence"),
      $rune: document.getElementById('essenceRune'),
      runes: {
        "Absorb Health": "Oko",
        "Absorb Magicka": "Makko",
        "Absorb Stamina": "Deni",
        "Bashing": "Jaedi / Kaderi",
        "Crushing": "Deteri",
        "Decrease Health": "Okoma",
        "Decrease Physical Harm": "Lire / Taderi",
        "Decrease Spell Harm": "Makderi",
        "Disease Resist": "Haoko",
        "Fire Resist": "Rakeipa",
        "Flame": "Rakeipa",
        "Foulness": "Haoko",
        "Frost": "Dekeipa",
        "Frost Resist": "Dekeipa",
        "Hardening": "Deteri",
        "Health": "Oko",
        "Health Regen": "Okoma",
        "Increase Magical Harm": "Makderi",
        "Increase Physical Harm": "Lire / Taderi",
        "Magicka": "Makko",
        "Magicka Regen": "Makkoma",
        "Poison": "Kuoko",
        "Poison Resist": "Kuoko",
        "Potion Boost": "Oru",
        "Potion Speed": "Oru",
        "Rage": "Okori",
        "Reduce Feat Cost": "Denima",
        "Reduce Spell Cost": "Makkoma",
        "Shielding": "Jaedi / Kaderi",
        "Shock": "Meip",
        "Shock Resist": "Meip",
        "Stamina": "Deni",
        "Stamina Regen": "Denima",
        "Weakening": "Okori"
      },
      polarities: {
        "Absorb Health": 0,
        "Absorb Magicka": 0,
        "Absorb Stamina": 0,
        "Bashing": 1,
        "Crushing": 0,
        "Decrease Health": 0,
        "Decrease Physical Harm": 0,
        "Decrease Spell Harm": 0,
        "Disease Resist": 0,
        "Fire Resist": 0,
        "Flame": 1,
        "Foulness": 1,
        "Frost": 1,
        "Frost Resist": 0,
        "Hardening": 1,
        "Health": 1,
        "Health Regen": 1,
        "Increase Magical Harm": 1,
        "Increase Physical Harm": 1,
        "Magicka": 1,
        "Magicka Regen": 1,
        "Poison": 1,
        "Poison Resist": 0,
        "Potion Boost": 1,
        "Potion Speed": 0,
        "Rage": 1,
        "Reduce Feat Cost": 0,
        "Reduce Spell Cost": 0,
        "Shielding": 0,
        "Shock": 1,
        "Shock Resist": 0,
        "Stamina": 1,
        "Stamina Regen": 1,
        "Weakening": 0
      }
    }

    var Aspect = {
      $select: document.getElementById("select-aspect"),
      $rune: document.getElementById('aspectRune'),
      runes: {
        "base": "Ta",
        "fine": "Jejota",
        "superior": "Denata",
        "artifact": "Rekuta",
        "legendary": "Kuta"
      },
      colors: {
        "base": "#FFF",
        "fine": "#2DC50E",
        "superior": "#3A92FF",
        "artifact": "#A02EF7",
        "legendary": "#E5CB51"
      }
    }

    var glyph = document.getElementById('glyph')

    function update() {
      var potency = Potency.$select.value
      var essence = Essence.$select.value
      var aspect = Aspect.$select.value

      var polarity = Essence.polarities[essence]
      var color = Aspect.colors[aspect]

      glyph.style.color = color

      Potency.$rune.textContent = Potency.runes[potency][polarity]
      Essence.$rune.textContent = Essence.runes[essence]
      Aspect.$rune.textContent = Aspect.runes[aspect]
    }

    [Potency, Essence, Aspect].forEach(function(E) {
      E.$select.addEventListener('change', update)
    })

    update()
  </script>

  <script type="text/javascript">
    $(".fade").click(function(event) {
      event.preventDefault();
      linkLocation = this.href;
      $("body").fadeOut(1000, redirectPage);
    });

    function redirectPage() {
      window.location = linkLocation;
    }
  </script>
</body>

</html>


问:
Force Laravel to log in a user using legacy authentication
I am trying to slowly integrate Laravel into a legacy PHP application. One of the tasks is to automatically register a Laravel user session when a user logs in to the old app. I am not trying to implement Laravel authentication, I really just want to piggyback off of existing functionality and force a specific user to be logged in without checking credentials.  What I have so far has been cobbled together from other people's hacks I have found around:

```<code>// Laravel authentication hook - Boostrap application
require_once getcwd() . '/../laravel/bootstrap/autoload.php';
$app = require_once getcwd() . '/../laravel/bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Console\Kernel');
$kernel->bootstrap();
$app->boot();

// Start Laravel session
$request = Illuminate\Http\Request::capture();
$response = $app->make('Symfony\Component\HttpFoundation\Response');
$startSession = new Illuminate\Session\Middleware\StartSession($app['session']);
// Associate server session with the authenticating user id
// I have also tried loading user model instance and then $app['auth']->login($user)
$app['auth']->loginUsingId($user_id);

$app['session']->driver()->start();
// Terminate middleware response chain with naked response
$response = $startSession->handle($request, function() use($response) {
    return $response; // This response will have session cookie attached to it
});

$response->send();
</code>```

After this I get a laravel_session cookie that has contents on the client. During the login request after the code above executes, if I dd(Auth::user()) then I get the user I just logged in with. However, on subsequent requests Auth::user() and $this->request->user()  both return null in all contexts.

How can I force an active Laravel user session without actually authenticating that will persist across requests?

The ultimate outcome is that Laravel will be running as a 'sub-application' underneath the legacy app while existing features are pulled in one by one so that both will exist for a period of time until all features are implemented in Laravel and it will replace the existing app in full. If it makes more sense to try to take over the legacy authentication with Laravel rather than the other way around I'm open to that, but I'd rather avoid having to change the underlying users table (legacy authentication is happening over LDAP, so there are no passwords locally, there's no remember_token, but that's easy enough to add if I have to). I really am just looking for the shortest path with the least amount of effort/headache.

答:
I would suggest it's worth considering having Laravel as the main app, allowing a pass-through to the legacy code for routes that you've not yet converted. I did this with a huge legacy app that had everything you'd expect from an app written 10 years ago, and though making it all work together was a pain at the start (similar to the issues you're having, but reversed), as it got completed I was merely deleting old code until there was nothing left. With your approach, I can't see what will happen when it's time to finally retire the old code.

I ended up with:

```<code>/app
  /Console
  /Http
  etc...
  /old
    /lib
    /screens
    /config
    index.php
</code>```

An OldController was setup with:

```<code>/**
 * Catches all routes for old code
 *
 * @codeCoverageIgnore
 * @return \Illuminate\Http\Response
 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
 */
public function index($all = null)
{
    ob_start();
    require __DIR__.'/../../old/index.php';
    $html = ob_get_clean();
    return response()->string($html);
}
</code>```

The old/index.php had to do things like:

```<code>// TODO: In place to avoid E_DEPRECATED errors for mysql
error_reporting(E_ALL ^ E_DEPRECATED);
session_start();

// Allow all hardcoded includes in old/ to work
$path = __DIR__;
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

// Set up the global user to suit old code
if (Auth::user()) {
    $myUser = Auth::user()->toArray();
    $myUser['requests'] = getRequestList($myUser['uid']);
    $loggedin = true;
    Log::debug('using Auth::user() id ' . $myUser['uid']);
} else {
    $loggedin = false;
}
// Translate Laravel flashed data to existing message arrays
if (session()->has('login_error_array')) {
    $login_error_array = session()->get('login_error_array');
}
</code>```

I did some questionable things by always using Laravel auth and a LegacyHasher for old passwords, in AuthController:

```<code> /**
 * Login
 *
 * @return \Illuminate\Http\RedirectResponse
 */
public function postLogin()
{
    // Logic is a bit cleaner to follow if we fail late instead of early
    if ($this->hasParams(['login_email', 'login_password'])) {
        // Login using Laravel password
        $credentials = [
            'email' => strtolower(Input::get('login_email')),
            'password' => Input::get('login_password'),
            'active' => ['Y', 'B']
            ];

        // Use the extended user provider to allow using an array of values in the credentials
        $provider = new ExtendedEloquentUserProvider(new BcryptHasher(), config('auth.model'));
        Auth::setProvider($provider);
        if (Auth::attempt($credentials, Input::has('login_remember'))) {

            Log::info(sprintf('successful login from: %s', $credentials['email']));

            return redirect('/');
        }

        // Try with legacy password
        $provider = new ExtendedEloquentUserProvider(new LegacyHasher(), config('auth.model'));
        Auth::setProvider($provider);
        if (Auth::attempt($credentials, Input::has('login_remember'))) {
            // Save correctly hashed password
            // TODO: Only add this once this is definitely working ok as it messes up the DB for legacy code
            //Auth::user()->password = Hash::make(Input::get('login_password'));
            //Auth::user()->save();
            Log::info(
                sprintf(
                    'legacy password for login %s, id %d',
                    $credentials['email'],
                    Auth::user()->uid
                )
            );

            Log::info(sprintf('successful login from: %s', $credentials['email']));

            return redirect('/');
        }
    }

    Log::warning(sprintf('login failed for: %s', Input::get('login_email')));
    // TODO: Use flashed errors for legacy compatibility
    session()->flash('login_error_array', ['Wrong Username or Password']);

    return redirect('login.htm')->withInput();
}
</code>```

LegacyHasher (yes, it did...)

```<code>/**
 * Check the given plain value against a hash.
 *
 * @param  string $value
 * @param  string $hashedValue
 * @param  array  $options
 * @return bool
 */
public function check($value, $hashedValue, array $options = array())
{
    // Unused param
    $options = [];
    return md5($value) == $hashedValue;
}
</code>```

And a load of other stuff that is way beyond scope here. But it is doable, though painful. After a fair while working on this, all old code is removed and I've got a full testable Laravel app. It's got a few hundred TODOs scattered around liberally, but is much more manageable.

I'm happy to help with more details if you choose to go in this direction.

Body:
I am trying to slowly integrate Laravel into a legacy PHP application. One of the tasks is to automatically register a Laravel user session when a user logs in to the old app. I am not trying to implement Laravel authentication, I really just want to piggyback off of existing functionality and force a specific user to be logged in without checking credentials.  What I have so far has been cobbled together from other people's hacks I have found around:

// Laravel authentication hook - Boostrap application
require_once getcwd() . '/../laravel/bootstrap/autoload.php';
$app = require_once getcwd() . '/../laravel/bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Console\Kernel');
$kernel->bootstrap();
$app->boot();

// Start Laravel session
$request = Illuminate\Http\Request::capture();
$response = $app->make('Symfony\Component\HttpFoundation\Response');
$startSession = new Illuminate\Session\Middleware\StartSession($app['session']);
// Associate server session with the authenticating user id
// I have also tried loading user model instance and then $app['auth']->login($user)
$app['auth']->loginUsingId($user_id);

$app['session']->driver()->start();
// Terminate middleware response chain with naked response
$response = $startSession->handle($request, function() use($response) {
    return $response; // This response will have session cookie attached to it
});

$response->send();

After this I get a laravel_session cookie that has contents on the client. During the login request after the code above executes, if I dd(Auth::user()) then I get the user I just logged in with. However, on subsequent requests Auth::user() and $this->request->user()  both return null in all contexts.

How can I force an active Laravel user session without actually authenticating that will persist across requests?

The ultimate outcome is that Laravel will be running as a 'sub-application' underneath the legacy app while existing features are pulled in one by one so that both will exist for a period of time until all features are implemented in Laravel and it will replace the existing app in full. If it makes more sense to try to take over the legacy authentication with Laravel rather than the other way around I'm open to that, but I'd rather avoid having to change the underlying users table (legacy authentication is happening over LDAP, so there are no passwords locally, there's no remember_token, but that's easy enough to add if I have to). I really am just looking for the shortest path with the least amount of effort/headache.

Body:
I would suggest it's worth considering having Laravel as the main app, allowing a pass-through to the legacy code for routes that you've not yet converted. I did this with a huge legacy app that had everything you'd expect from an app written 10 years ago, and though making it all work together was a pain at the start (similar to the issues you're having, but reversed), as it got completed I was merely deleting old code until there was nothing left. With your approach, I can't see what will happen when it's time to finally retire the old code.

I ended up with:

/app
  /Console
  /Http
  etc...
  /old
    /lib
    /screens
    /config
    index.php

An OldController was setup with:

/**
 * Catches all routes for old code
 *
 * @codeCoverageIgnore
 * @return \Illuminate\Http\Response
 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
 */
public function index($all = null)
{
    ob_start();
    require __DIR__.'/../../old/index.php';
    $html = ob_get_clean();
    return response()->string($html);
}

The old/index.php had to do things like:

// TODO: In place to avoid E_DEPRECATED errors for mysql
error_reporting(E_ALL ^ E_DEPRECATED);
session_start();

// Allow all hardcoded includes in old/ to work
$path = __DIR__;
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

// Set up the global user to suit old code
if (Auth::user()) {
    $myUser = Auth::user()->toArray();
    $myUser['requests'] = getRequestList($myUser['uid']);
    $loggedin = true;
    Log::debug('using Auth::user() id ' . $myUser['uid']);
} else {
    $loggedin = false;
}
// Translate Laravel flashed data to existing message arrays
if (session()->has('login_error_array')) {
    $login_error_array = session()->get('login_error_array');
}

I did some questionable things by always using Laravel auth and a LegacyHasher for old passwords, in AuthController:

 /**
 * Login
 *
 * @return \Illuminate\Http\RedirectResponse
 */
public function postLogin()
{
    // Logic is a bit cleaner to follow if we fail late instead of early
    if ($this->hasParams(['login_email', 'login_password'])) {
        // Login using Laravel password
        $credentials = [
            'email' => strtolower(Input::get('login_email')),
            'password' => Input::get('login_password'),
            'active' => ['Y', 'B']
            ];

        // Use the extended user provider to allow using an array of values in the credentials
        $provider = new ExtendedEloquentUserProvider(new BcryptHasher(), config('auth.model'));
        Auth::setProvider($provider);
        if (Auth::attempt($credentials, Input::has('login_remember'))) {

            Log::info(sprintf('successful login from: %s', $credentials['email']));

            return redirect('/');
        }

        // Try with legacy password
        $provider = new ExtendedEloquentUserProvider(new LegacyHasher(), config('auth.model'));
        Auth::setProvider($provider);
        if (Auth::attempt($credentials, Input::has('login_remember'))) {
            // Save correctly hashed password
            // TODO: Only add this once this is definitely working ok as it messes up the DB for legacy code
            //Auth::user()->password = Hash::make(Input::get('login_password'));
            //Auth::user()->save();
            Log::info(
                sprintf(
                    'legacy password for login %s, id %d',
                    $credentials['email'],
                    Auth::user()->uid
                )
            );

            Log::info(sprintf('successful login from: %s', $credentials['email']));

            return redirect('/');
        }
    }

    Log::warning(sprintf('login failed for: %s', Input::get('login_email')));
    // TODO: Use flashed errors for legacy compatibility
    session()->flash('login_error_array', ['Wrong Username or Password']);

    return redirect('login.htm')->withInput();
}

LegacyHasher (yes, it did...)

/**
 * Check the given plain value against a hash.
 *
 * @param  string $value
 * @param  string $hashedValue
 * @param  array  $options
 * @return bool
 */
public function check($value, $hashedValue, array $options = array())
{
    // Unused param
    $options = [];
    return md5($value) == $hashedValue;
}

And a load of other stuff that is way beyond scope here. But it is doable, though painful. After a fair while working on this, all old code is removed and I've got a full testable Laravel app. It's got a few hundred TODOs scattered around liberally, but is much more manageable.

I'm happy to help with more details if you choose to go in this direction.


问:
Android Geocoder getFromLocationName fails with valid address
I'm trying to get latitude and longitude of specific addresses using
    addressList = geoCoder.getFromLocationName(locationName, 1);

For most addresses this works just fine, but there are some valid addresses, like "Lentoasemantie 1, Vantaa", which returns empty array. The strange thing is that the valid addresses used to work 4 days ago, but not anymore while most of the addresses continue to work.

So, this looks like Google backend problem and I'm wondering should I report this to Google (where / how?) or switch away from using Geocoder, because it's inherently unreliable?

答:
Geocoder Android API is not as efficient as the Google Maps Geocoding API so I suggest you to use this one instead of Geocoder.
You can find below the function to get location from address through Volley queue (For Lentoasemantie 1, Vantaa, it works) :</p>

```<code>public void getLocationFromAddress(String address) {
    String url = "https://maps.googleapis.com/maps/api/geocode/json?address="
            + Uri.encode(address) + "&sensor=true&key=API_KEY";
    RequestQueue queue = Volley.newRequestQueue(this);
    JsonObjectRequest stateReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            JSONObject location;
            try {
                // Get JSON Array called "results" and then get the 0th
                // complete object as JSON
                location = response.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
                // Get the value of the attribute whose name is
                // "formatted_string"
                if (location.getDouble("lat") != 0 && location.getDouble("lng") != 0) {
                    LatLng latLng = new LatLng(location.getDouble("lat"), location.getDouble("lng"));

                    //Do what you want
                }
            } catch (JSONException e1) {
                e1.printStackTrace();

            }
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Error.Response", error.toString());
        }
    });
    // add it to the queue
    queue.add(stateReq);

}
</code>```

Body:
Geocoder Android API is not as efficient as the Google Maps Geocoding API so I suggest you to use this one instead of Geocoder.
You can find below the function to get location from address through Volley queue (For Lentoasemantie 1, Vantaa, it works) :

public void getLocationFromAddress(String address) {
    String url = "https://maps.googleapis.com/maps/api/geocode/json?address="
            + Uri.encode(address) + "&sensor=true&key=API_KEY";
    RequestQueue queue = Volley.newRequestQueue(this);
    JsonObjectRequest stateReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            JSONObject location;
            try {
                // Get JSON Array called "results" and then get the 0th
                // complete object as JSON
                location = response.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
                // Get the value of the attribute whose name is
                // "formatted_string"
                if (location.getDouble("lat") != 0 && location.getDouble("lng") != 0) {
                    LatLng latLng = new LatLng(location.getDouble("lat"), location.getDouble("lng"));

                    //Do what you want
                }
            } catch (JSONException e1) {
                e1.printStackTrace();

            }
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Error.Response", error.toString());
        }
    });
    // add it to the queue
    queue.add(stateReq);

}