问:
Powershell Web Data Fetching
I am not sure what I am doing wrong. I am trying to fetch the data from URL below.

But I am not getting anything in return using the code below.

What I want to fetch (34)

Powershell Code

```<code>$downloadURL     = 'https://example.html'
$downloadRequest = Invoke-WebRequest -Uri $downloadURL
</code>```

Result

Data not in the output code from Powershell

答:
The page is dynamically created with JavaScript. It is hard to get the data by using Invoke-WebRequest cmdlet. Instead of that, try to use Internet Explorer COM object like this:

```<code>$url = 'https://example.com'
$ie = New-Object -ComObject InternetExplorer.Application
$ie.Visible = $false
$ie.Navigate2($url)
while($ie.ReadyState -ne 4) { Start-Sleep 1 }
$ie.document.body.getElementsByClassName('example-class-name')::outerHTML
$ie.document.body.getElementsByClassName('example-class-name')::textContent
</code>```

For more information, see this article.

Title: Powershell Web Data Fetching

Body:
I am not sure what I am doing wrong. I am trying to fetch the data from URL below.

But I am not getting anything in return using the code below.

What I want to fetch (34)

Powershell Code

$downloadURL     = 'https://example.html'
$downloadRequest = Invoke-WebRequest -Uri $downloadURL

Result

Data not in the output code from Powershell

Body:
The page is dynamically created with JavaScript. It is hard to get the data by using Invoke-WebRequest cmdlet. Instead of that, try to use Internet Explorer COM object like this:

$url = 'https://example.com'
$ie = New-Object -ComObject InternetExplorer.Application
$ie.Visible = $false
$ie.Navigate2($url)
while($ie.ReadyState -ne 4) { Start-Sleep 1 }
$ie.document.body.getElementsByClassName('example-class-name')::outerHTML
$ie.document.body.getElementsByClassName('example-class-name')::textContent

For more information, see this article.


来源: stackexchange

问:
Android Studio: Android Manifest doesn't exists or has incorrect root tag
I got this error on Android Studio (AS):

How I got it:

I created an AS Project from scratch and everything was fine.
Then a popup showed up, and (if I recall correctly) was saying something like: "Android Framework detected". I pressed "Yes' and some changes happened to the project/module. And after that I got the above error

Edit:

In my case the problem was not Gradle related. It had to do with IntelliJ/Android Studio configuration, an .iml file in particular.
I realized that after reading this informative post here.

答: I had this problem with a multi-module project when I renamed the app module. In my case to solve the problem I had to manually update the app module name in the project's settings.gradle file (Android Studio didn't update that value)</p>

ContentLicense: CC BY-SA 3.0


问:
Laravel Ajax request, Auth:login returns false! but user is logged in after refresh
I want to log users in with ajax request and after login in controller, redirect users to dashboard with javascript.

The Problem is when I use Auth:login($user) in controller, it returns false and my return line in controller is not reached.  when I refresh the page manually I see that user is logged in !!

Backend (pseudo code):

```<code>    $r = $request->all();
    $user = User::where('email', $r['email'])->first();

    Auth::login($user);  // this returns false

    return [  // this line is not reached
        'status' > 'success'
    ];
</code>```

Front End :

```<code>$.ajax({
       type: 'Post',
       url: '/login/js-login',
       data: user_data,
       success: function (res) {
        if (res.data.status == 'success') {
         toastr.success(" LoginSuccessfull!")
         window.location.replace("https://www.example.com");
      } else {
         toastr.error('Error Login!')
      }

      });
</code>```

答:
I doubt that you are using Auth::login in api.php which is stateless.

Either you need to use Token base authentication or use Auth::login in web.php which is statefull

If you are using laravel version < 5.3 then middleware should be web not api

Auth:logn returns void so you can use

```<code>Auth::login($user);
return [
    'status' => Auth:check()
];
</code>```

check() Determine if the current user is authenticated.

Body:
I want to log users in with ajax request and after login in controller, redirect users to dashboard with javascript.

The Problem is when I use Auth:login($user) in controller, it returns false and my return line in controller is not reached.  when I refresh the page manually I see that user is logged in !!

Backend (pseudo code):

    $r = $request->all();
    $user = User::where('email', $r['email'])->first();

    Auth::login($user);  // this returns false

    return [  // this line is not reached
        'status' > 'success'
    ];

Front End :

$.ajax({
       type: 'Post',
       url: '/login/js-login',
       data: user_data,
       success: function (res) {
        if (res.data.status == 'success') {
         toastr.success(" LoginSuccessfull!")
         window.location.replace("https://www.example.com");
      } else {
         toastr.error('Error Login!')
      }

      });

Body:
I doubt that you are using Auth::login in api.php which is stateless.

Either you need to use Token base authentication or use Auth::login in web.php which is statefull

If you are using laravel version < 5.3 then middleware should be web not api

Auth:logn returns void so you can use

Auth::login($user);
return [
    'status' => Auth:check()
];

check() Determine if the current user is authenticated.


问:
C# Nullable Equality Operations, Why does null <= null resolve as false?
Why is it that in .NET

```<code>null >= null
</code>```

resolves as false, but

```<code>null == null
</code>```

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

答:
It seems like the compiler treats null as if they're integer types.
VS2008 remarks: "Comparing with null of type 'int?' always produces 'false'"

Body:
Why is it that in .NET

null >= null

resolves as false, but

null == null

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

ContentLicense: CC BY-SA 2.5


问:
Mac OSX - IllegalStateException: The driver is not executable:
Im new to Mac OSX. Downloaded my Robotframework(Selenium & Java) project from git and tried to execute the code locally wherein I received the below error.

Suite setup failed:
IllegalStateException: The driver is not executable: /Users/roja/Documents/GitHub/testautomation/chromedrivers/chromedriver_osx

To rectify this issue, I followed the below but it didnt work.

Upgraded the selenium-java and standalone version from 2.53.1 to 3.4.0.

Driver path specified to Users/roja/automation

Chromedriver upgraded from 2.31 to 2.33

And the same driver version updated even in the path specified in the exception above.

Also Im unsure why the path is defaulted to /Users/roja/Documents/GitHub/testautomation/chromedrivers/chromedriver_osx.

My git projects are saved in the path usr/local/git/testautomation and chromedriver also saved in the same. please clarify and provide me a solution.

Below code written for launching the browser,

```<code>public void LaunchBrowser() throws InterruptedException {
System.setProperty("Webdriver.chrome.driver", "/Users/roja/Automation/chromedriver_osx");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
</code>```

答:
Quick installation of the latest ChromeDriver

To install the latest version of ChromeDriver:

Mac users with Homebrew:

```<code>brew tap homebrew/cask && brew cask install chromedriver
</code>```

Original answered Nov 15 '17 at 12:04

The error IllegalStateException: The driver is not executable: /Users/roja/Documents/GitHub/testautomation/chromedrivers/chromedriver_osx says it all. You have to make exactly 4 changes as follows :

Change Webdriver.chrome.driver as :

```<code>webdriver.chrome.driver
</code>```

Change /Users/roja/Automation/chromedriver_osx as we need to include the name of the webdriver binary i.e. chromedriver as a value :

```<code>/Users/roja/Automation/chromedriver_osx/chromedriver
</code>```

Change driver = new ChromeDriver(); as :

```<code>WebDriver driver = new ChromeDriver();
</code>```

Remove unwanted throws InterruptedException to keep your code short and simple.

Body:
Im new to Mac OSX. Downloaded my Robotframework(Selenium & Java) project from git and tried to execute the code locally wherein I received the below error.

Suite setup failed:
IllegalStateException: The driver is not executable: /Users/roja/Documents/GitHub/testautomation/chromedrivers/chromedriver_osx

To rectify this issue, I followed the below but it didnt work.

Upgraded the selenium-java and standalone version from 2.53.1 to 3.4.0.

Driver path specified to Users/roja/automation

Chromedriver upgraded from 2.31 to 2.33

And the same driver version updated even in the path specified in the exception above.

Also Im unsure why the path is defaulted to /Users/roja/Documents/GitHub/testautomation/chromedrivers/chromedriver_osx.

My git projects are saved in the path usr/local/git/testautomation and chromedriver also saved in the same. please clarify and provide me a solution.

Below code written for launching the browser,

public void LaunchBrowser() throws InterruptedException {
System.setProperty("Webdriver.chrome.driver", "/Users/roja/Automation/chromedriver_osx");
driver = new ChromeDriver();
driver.manage().window().maximize();
}

Body:
Quick installation of the latest ChromeDriver

To install the latest version of ChromeDriver:

Mac users with Homebrew:

brew tap homebrew/cask && brew cask install chromedriver

Original answered Nov 15 '17 at 12:04

The error IllegalStateException: The driver is not executable: /Users/roja/Documents/GitHub/testautomation/chromedrivers/chromedriver_osx says it all. You have to make exactly 4 changes as follows :

Change Webdriver.chrome.driver as :

webdriver.chrome.driver

Change /Users/roja/Automation/chromedriver_osx as we need to include the name of the webdriver binary i.e. chromedriver as a value :

/Users/roja/Automation/chromedriver_osx/chromedriver

Change driver = new ChromeDriver(); as :

WebDriver driver = new ChromeDriver();

Remove unwanted throws InterruptedException to keep your code short and simple.

ContentLicense: CC BY-SA 4.0


问:
How to color the slider in shiny to the right of the value instead of to the left?
I am building an app with shiny and use a slider pretty much as the one shown in Shiny gallery (http://shiny.rstudio.com/gallery/slider-bar-and-slider-range.html). By default it gets coloured blue to the left of the chosen value (in this example from 0 to 50). Is there a way to get it coloured to the right of the chosen value: e.i. from 50 to 100?

The reason I would like to do it, is that the user should read it as "all values from the threshold to max", so colouring from the min to the threshold would be misleading.

Has anybody an idea on that?
Maria

答:
There's probably a better way, but here's a quick css option: </p>

```<code>library(shiny)
shinyApp(
  ui = fluidPage(

    tags$head( tags$style( type = "text/css", '
      .irs-line-mid{
        background: #428bca ;
        border: 1px solid #428bca ;
      }
      .irs-line-right{
        background: #428bca ;
      }
      .irs-bar {
        background: linear-gradient(to bottom, #DDD -50%, #FFF 150%);
        border-top: 1px solid #CCC ;
        border-bottom: 1px solid #CCC ;
      }
      .irs-bar-edge {
        background: inherit ;
        border: inherit ;
      }

    ')),

    sliderInput( "slider", label  = "Slider", min = 0, max = 100, value = 50)
  ), server = function(input,output){}
)
</code>```

Body:
There's probably a better way, but here's a quick css option:

library(shiny)
shinyApp(
  ui = fluidPage(

    tags$head( tags$style( type = "text/css", '
      .irs-line-mid{
        background: #428bca ;
        border: 1px solid #428bca ;
      }
      .irs-line-right{
        background: #428bca ;
      }
      .irs-bar {
        background: linear-gradient(to bottom, #DDD -50%, #FFF 150%);
        border-top: 1px solid #CCC ;
        border-bottom: 1px solid #CCC ;
      }
      .irs-bar-edge {
        background: inherit ;
        border: inherit ;
      }

    ')),

    sliderInput( "slider", label  = "Slider", min = 0, max = 100, value = 50)
  ), server = function(input,output){}
)


问:
Not getting Firebase database data
I am developing app to display user score that store in firebase database but after running application it won't display data in listview

below is my code:-

```<code>listViewLeaderBoard = (ListView) findViewById(R.id.listView_leader_board);

        reference = FirebaseDatabase.getInstance().getReference("score");

        leaderBoards = new ArrayList<>();

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                    LeaderBoard leaderBoard = postSnapshot.getValue(LeaderBoard.class);
                    leaderBoards.add(0,leaderBoard);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        //Collections.sort(leaderBoards);
        CustomLeaderBoardAdapter adapter = new CustomLeaderBoardAdapter(getApplicationContext(),R.layout.leader_board_list_layout,leaderBoards);
        listViewLeaderBoard.setAdapter(adapter);
        adapter.notifyDataSetChanged();
</code>```

Database snapshot:-

Output:-

答:
try this:</p>

```<code>listViewLeaderBoard = (ListView) findViewById(R.id.listView_leader_board);

    reference = FirebaseDatabase.getInstance().getReference("score");

    leaderBoards = new ArrayList<>();

    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                LeaderBoard leaderBoard = postSnapshot.getValue(LeaderBoard.class);
                leaderBoards.add(leaderBoard);
         CustomLeaderBoardAdapter adapter = new CustomLeaderBoardAdapter(getApplicationContext(),R.layout.leader_board_list_layout,leaderBoards);
    listViewLeaderBoard.setAdapter(adapter);
    adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

Title: Not getting Firebase database data

Body:
I am developing app to display user score that store in firebase database but after running application it won't display data in listview

below is my code:-

listViewLeaderBoard = (ListView) findViewById(R.id.listView_leader_board);

        reference = FirebaseDatabase.getInstance().getReference("score");

        leaderBoards = new ArrayList<>();

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                    LeaderBoard leaderBoard = postSnapshot.getValue(LeaderBoard.class);
                    leaderBoards.add(0,leaderBoard);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        //Collections.sort(leaderBoards);
        CustomLeaderBoardAdapter adapter = new CustomLeaderBoardAdapter(getApplicationContext(),R.layout.leader_board_list_layout,leaderBoards);
        listViewLeaderBoard.setAdapter(adapter);
        adapter.notifyDataSetChanged();

Database snapshot:-

Output:-

Body:
try this:

listViewLeaderBoard = (ListView) findViewById(R.id.listView_leader_board);

    reference = FirebaseDatabase.getInstance().getReference("score");

    leaderBoards = new ArrayList<>();

    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                LeaderBoard leaderBoard = postSnapshot.getValue(LeaderBoard.class);
                leaderBoards.add(leaderBoard);
         CustomLeaderBoardAdapter adapter = new CustomLeaderBoardAdapter(getApplicationContext(),R.layout.leader_board_list_layout,leaderBoards);
    listViewLeaderBoard.setAdapter(adapter);
    adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


问:
How to disable an Android button?
I have created a layout that contains two buttons, Next and Previous. In between the buttons I'm generating some dynamic views. So when I first launch the application I want to disable the "Previous" button since there wont be any previous views. I also want to disable the "Next" button when there are not more views to display. Is there anyway to disable the buttons?

答:
In Kotlin, if you refer the Button View with id then, enable/disable button as like

layout.xml

```<code><Button
   android:id="@+id/btn_start"
   android:layout_width="100dp"
   android:layout_height="50dp"
   android:text="@string/start"
   android:layout_alignParentBottom="true"/>
</code>```

activity.kt

```<code>  btn_start.isEnabled = true   //to enable button
  btn_start.isEnabled = false  //to disable button
</code>```

Title: How to disable an Android button?

Body:
In Kotlin, if you refer the Button View with id then, enable/disable button as like

layout.xml

<Button
   android:id="@+id/btn_start"
   android:layout_width="100dp"
   android:layout_height="50dp"
   android:text="@string/start"
   android:layout_alignParentBottom="true"/>

activity.kt

  btn_start.isEnabled = true   //to enable button
  btn_start.isEnabled = false  //to disable button


问:
JSON to ASP.NET Web API error: (500) Internal Server Error
I'm trying to send a object via JSON to a web API but I keep running into and exception

My client side action is:

```<code>    public string SubmitNewIncident(Incident input)
    {
        string response = String.Empty;
        string serialisedJSON = String.Empty;

        input.Type = 0;

        serialisedJSON = JsonConvert.SerializeObject(input);
        string fpath = String.Format(@"C:\dev\serialisedJSONLog_{0}.txt", DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"));
        System.IO.File.WriteAllText(fpath, serialisedJSON);

        using (WebClient wc = new WebClient())
        {
            wc.Headers[HttpRequestHeader.ContentType] = "application/json";
            try
            {
                response = wc.UploadString(new Uri("http://localhost:25657/api/RaiseNew"), serialisedJSON);
            }
            catch(Exception ex)
            {
                string path = String.Format(@"C:\dev\ErrorLog_{0}.txt", DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"));
                System.IO.File.WriteAllText(path, ex.ToString());
                throw ex;
            }
        }

        return (response);
    }
</code>```

The JSON string looks ok, but is very long. My server side code is:

```<code>public class RaiseNewController : ApiController
{
    // GET api/raisenew
    [HttpGet]
    public HttpStatusCode Get()
    {
        return HttpStatusCode.OK;
    }

    //POST api/raisenew
    [HttpPost]
    public int Post([FromBody] Incident input)
    {
        input.AssignedTo = AssignNewTicket(input.AppID ?? 0);

        return 0;
    }
</code>```

The value of the string serialisedJSON is too long to post here

When I call the action and upload the JSON string I get the following exception:

```<code>    System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
</code>```

答:
I think what you have is telling the ASP.Net to look for a property called value in the POSTed data.

I'd personally let ASP.Net handle the deserialization automatically.

```<code>[HttpPost]
public int Post(Incident incident)
{
    Process(incident);

    return 0;
}
</code>```

Body:
I'm trying to send a object via JSON to a web API but I keep running into and exception

My client side action is:

    public string SubmitNewIncident(Incident input)
    {
        string response = String.Empty;
        string serialisedJSON = String.Empty;

        input.Type = 0;

        serialisedJSON = JsonConvert.SerializeObject(input);
        string fpath = String.Format(@"C:\dev\serialisedJSONLog_{0}.txt", DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"));
        System.IO.File.WriteAllText(fpath, serialisedJSON);

        using (WebClient wc = new WebClient())
        {
            wc.Headers[HttpRequestHeader.ContentType] = "application/json";
            try
            {
                response = wc.UploadString(new Uri("http://localhost:25657/api/RaiseNew"), serialisedJSON);
            }
            catch(Exception ex)
            {
                string path = String.Format(@"C:\dev\ErrorLog_{0}.txt", DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"));
                System.IO.File.WriteAllText(path, ex.ToString());
                throw ex;
            }
        }

        return (response);
    }

The JSON string looks ok, but is very long. My server side code is:

public class RaiseNewController : ApiController
{
    // GET api/raisenew
    [HttpGet]
    public HttpStatusCode Get()
    {
        return HttpStatusCode.OK;
    }

    //POST api/raisenew
    [HttpPost]
    public int Post([FromBody] Incident input)
    {
        input.AssignedTo = AssignNewTicket(input.AppID ?? 0);

        return 0;
    }

The value of the string serialisedJSON is too long to post here

When I call the action and upload the JSON string I get the following exception:

    System.Net.WebException: The remote server returned an error: (500) Internal Server Error.

Body:
I think what you have is telling the ASP.Net to look for a property called value in the POSTed data.

I'd personally let ASP.Net handle the deserialization automatically.

[HttpPost]
public int Post(Incident incident)
{
    Process(incident);

    return 0;
}


问:
Html click element vs selecting the content
Is there any way to differentiate between clicking a div element and selecting its content,

What I am looking for is to trigger click action only if the div was clicked
but not when its contents were selected

```<code><div onClick="funA">
    Allow content to be copied if selected, else perform funA when clicked
</div>
</code>```

Current onClick behavior triggers when I try to select the content and copy it, as soon as i unpress the click, But I want to not trigger funA or detect its selected and control it somehow.
I hope the question is clear enough, else I will add more specifics to the quesiton.

答:
you can see the difference this way : </p>

```<code><div id='click'>
    Allow content to be copied if selected, else perform funA when clicked
</div>
$('#click').click(function() {
    var sel = getSelection().toString();
    if(!sel){
        alert("clicked");
    }
});
</code>```

Body:
Is there any way to differentiate between clicking a div element and selecting its content,

What I am looking for is to trigger click action only if the div was clicked
but not when its contents were selected

    Allow content to be copied if selected, else perform funA when clicked

Current onClick behavior triggers when I try to select the content and copy it, as soon as i unpress the click, But I want to not trigger funA or detect its selected and control it somehow.
I hope the question is clear enough, else I will add more specifics to the quesiton.

Body:
you can see the difference this way :

<div id='click'>
    Allow content to be copied if selected, else perform funA when clicked
</div>
$('#click').click(function() {
    var sel = getSelection().toString();
    if(!sel){
        alert("clicked");
    }
});


问:
POST immediately after select a file
I have the following HTML code

```<code><form action="/script/upload_key.py" method="POST" enctype="multipart/form-data">
    Key filename: <input name="file_1" type="file">
    <input name="submit" type="submit">
</form>
</code>```

which gives me the following stuff.

I was wondering

How I can use JavaScript, to eliminate the need of Submit button. That's mean, once I Choose File, the selected file will be uploaded immediately?

How can I make sure the field to display selected file name is long enough, so that ... will not be shown?

答:
Rough guess at what you want - when the text field changes it will trigger the form submission

```<code>$('.target').change(function() {
  document.forms["myform"].submit();
});
</code>```

Edit: Sorry, I've used jQuery...

If you submit the form onchange, you won't notice the field get populated and therefore should not need to change the text length. If you desire to, I would get the character count of the string in the field and then apply a size attribute to the input

```<code>mylength = document.getElementById('myfield').value
document.getElementById('myfield').size = mylength;
</code>```

Title: POST immediately after select a file

Body:
I have the following HTML code

<form action="/script/upload_key.py" method="POST" enctype="multipart/form-data">
    Key filename: <input name="file_1" type="file">
    <input name="submit" type="submit">
</form>

which gives me the following stuff.

I was wondering

How I can use JavaScript, to eliminate the need of Submit button. That's mean, once I Choose File, the selected file will be uploaded immediately?

How can I make sure the field to display selected file name is long enough, so that ... will not be shown?

Body:
Rough guess at what you want - when the text field changes it will trigger the form submission

$('.target').change(function() {
  document.forms["myform"].submit();
});

Edit: Sorry, I've used jQuery...

If you submit the form onchange, you won't notice the field get populated and therefore should not need to change the text length. If you desire to, I would get the character count of the string in the field and then apply a size attribute to the input

mylength = document.getElementById('myfield').value
document.getElementById('myfield').size = mylength;


问:
Javascript arrays with email address and password
I work with PHP and I am more familiar with it. I have tried an array in Javascript but keep getting a syntax error and I am not sure why. I have Googled arrays and I do not seem to get the answer.

Here is my array of Users in Javascript:

```<code>var users = [
    [
      emailAddress: 'david@email.com',
      password: 'secretCat';
    ],
    [
      emailAddress: 'john@email.com',
      password: 'secretCatTwo';
    ],

    [
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree';
    ],

    [
       emailAddress: 'susan@email.com',
       password: 'secretCatFour';
    ],

];
</code>```

Am I supposed to do it differently in Javascript?

答:
You need an array of objects, you can't use name: value structure as array item, should be like :

```<code>var users = [
    {
      emailAddress: 'david@email.com',
      password: 'secretCat'
    },
    {
      emailAddress: 'john@email.com',
      password: 'secretCatTwo'
    },

    {
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree'
    },

    {
       emailAddress: 'susan@email.com',
       password: 'secretCatFour'
    }
];
</code>```

By removing the extra ; and using the object braces {}.

Hope this helps.

Body:
I work with PHP and I am more familiar with it. I have tried an array in Javascript but keep getting a syntax error and I am not sure why. I have Googled arrays and I do not seem to get the answer.

Here is my array of Users in Javascript:

var users = [
    [
      emailAddress: 'david@email.com',
      password: 'secretCat';
    ],
    [
      emailAddress: 'john@email.com',
      password: 'secretCatTwo';
    ],

    [
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree';
    ],

    [
       emailAddress: 'susan@email.com',
       password: 'secretCatFour';
    ],

];

Am I supposed to do it differently in Javascript?

Body:
You need an array of objects, you can't use name: value structure as array item, should be like :

var users = [
    {
      emailAddress: 'david@email.com',
      password: 'secretCat'
    },
    {
      emailAddress: 'john@email.com',
      password: 'secretCatTwo'
    },

    {
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree'
    },

    {
       emailAddress: 'susan@email.com',
       password: 'secretCatFour'
    }
];

By removing the extra ; and using the object braces {}.

Hope this helps.


问:
Why does SQL Server say this is wrong?
I have the table "User"

```<code>id         int
username   varchar(40)
joindate   date
email      varchar(60)
password   nvarchar(100)
</code>```

I want to execute the following query

```<code>INSERT INTO User (username, joinDate, email, password)
VALUES ('Kristian', '15/11/2017', 'foo@outlook.com', 'password')
</code>```

SQL Server 2014 throws an error

Incorrect syntax near keyword 'User'

What am I doing wrong?

答:
"User" is a reserved word, and as such will need to be wrapped in square parenthesis.

```<code>INSERT INTO [User] (username, joinDate, email, password)
VALUES ('Kristian', '15/11/2017', 'foo@outlook.com', 'password')
</code>```

As rather strongly pointed out in the comments, changing the table name would be the preferable course of action, if you are able to do so.

Title: Why does SQL Server say this is wrong?

Body:
I have the table "User"

id         int
username   varchar(40)
joindate   date
email      varchar(60)
password   nvarchar(100)

I want to execute the following query

INSERT INTO User (username, joinDate, email, password)
VALUES ('Kristian', '15/11/2017', 'foo@outlook.com', 'password')

SQL Server 2014 throws an error

Incorrect syntax near keyword 'User'

What am I doing wrong?

Body:
"User" is a reserved word, and as such will need to be wrapped in square parenthesis.

INSERT INTO [User] (username, joinDate, email, password)
VALUES ('Kristian', '15/11/2017', 'foo@outlook.com', 'password')

As rather strongly pointed out in the comments, changing the table name would be the preferable course of action, if you are able to do so.


问:
ffmpeg - Creates a Terminal like Text Video Instead of Slide Show Of Images
I am using ffmpeg encoder to render Images in my Android App with the Help of this Library

The following Command is used to Render video from a list of images.

```<code>String command[] = {"-r","1/5","-i",gpxfile.getAbsolutePath(),"-c:v","libx264","-vf","fps=25","-pix_fmt","yuv420p",root.getAbsolutePath()+"/"+"video.mp4"};
</code>```

and here the gpxfile is my text file that contains the following

```<code>    file '/storage/emulated/0/DCIM/Camera/P_20170807_143916.jpg'
    duration 2
    file '/storage/emulated/0/DCIM/Pic/P_20170305_142948.jpg'
    duration 5
    file '/storage/emulated/0/DCIM/Camera/P_20170305_142939.jpg'
    duration 6
    file '/storage/emulated/0/DCIM/Pic/P_20170305_142818.jpg'
    duration 2
</code>```

My Problem is While Running the Command it renders a Terminal Like Black Screen with the TextPaths inside the file instead of a Video...!!!
 Any Suggestions...??

Here is my Project Source Code

答:
Finally i got the Correct Command from Deepak.</p>

```<code>String command[] = {"-y", "-f", "concat", "-safe", "0", "-i", gpxfile.getAbsolutePath(), "-vsync", "vfr", "-pix_fmt", "yuv420p", root.getAbsolutePath()+"/"+"video.mp4"};
</code>```

Body:
I am using ffmpeg encoder to render Images in my Android App with the Help of this Library

The following Command is used to Render video from a list of images.

String command[] = {"-r","1/5","-i",gpxfile.getAbsolutePath(),"-c:v","libx264","-vf","fps=25","-pix_fmt","yuv420p",root.getAbsolutePath()+"/"+"video.mp4"};

and here the gpxfile is my text file that contains the following

    file '/storage/emulated/0/DCIM/Camera/P_20170807_143916.jpg'
    duration 2
    file '/storage/emulated/0/DCIM/Pic/P_20170305_142948.jpg'
    duration 5
    file '/storage/emulated/0/DCIM/Camera/P_20170305_142939.jpg'
    duration 6
    file '/storage/emulated/0/DCIM/Pic/P_20170305_142818.jpg'
    duration 2

My Problem is While Running the Command it renders a Terminal Like Black Screen with the TextPaths inside the file instead of a Video...!!!
 Any Suggestions...??

Here is my Project Source Code

Body:
Finally i got the Correct Command from Deepak.

String command[] = {"-y", "-f", "concat", "-safe", "0", "-i", gpxfile.getAbsolutePath(), "-vsync", "vfr", "-pix_fmt", "yuv420p", root.getAbsolutePath()+"/"+"video.mp4"};


问:
Java Array/List with stable index on remove
I'm looking for a data structure like ArrayList which elements don't get reindexed after removing a single one from it.

As an example scenario, Consider having a list as following psoudocode:

```<code>A(0) = m
A(1) = n
A(2) = o
A(3) = p
A(4) = q
</code>```

Using ArrayAdapter, issuing a A.remove(2) results in:

```<code>A(0) = m
A(1) = n
A(2) = p      // index decremented
A(3) = q      // index decremented
</code>```

which is not my desired behaviour. I'm looking for a list/array/map/set/collection/whatever which gives a result like this:

```<code>A(0) = m
A(1) = n
A(3) = p      // index persisted
A(4) = q      // index persisted
</code>```

It "can" be done using a integer counter combined with a Map but i'm wondering if a cleaner solution is already available.

Dirty approach using Map and integer counter:

```<code>HashMap<Integer, Object> map = new HashMap<>();
int indexCounter = 0;

public void insertItem(Object o){
    map.put(indexCounter, o);
    indexCounter++;
}
</code>```

Any ideas?

Edit:
To clearify, by m, n, o, ... i mean different values. These are not necessarily string and can be any kind of objects. That's a pseudocode.

More than that, Using NULL or mock values would not be an option in my case. Although, i'm looking for a general solution, not a specific one for my case. Thanks for sharing btw.

Edit 2:
Actually, im looking for a data structure, not a hack or trick. Thus, if there is not such a thing provided in Java, the correct answer to this question would be a straight conclusive "No, there isn't such a thing".

答:
You can make your own method thats replaces the value at a specific index to an empty String... </p>

```<code>public void resetA_AtIndex(int index)
{
   A.remove(index);
   A.add(index, "");
}
</code>```

Body:
I'm looking for a data structure like ArrayList which elements don't get reindexed after removing a single one from it.

As an example scenario, Consider having a list as following psoudocode:

A(0) = m
A(1) = n
A(2) = o
A(3) = p
A(4) = q

Using ArrayAdapter, issuing a A.remove(2) results in:

A(0) = m
A(1) = n
A(2) = p      // index decremented
A(3) = q      // index decremented

which is not my desired behaviour. I'm looking for a list/array/map/set/collection/whatever which gives a result like this:

A(0) = m
A(1) = n
A(3) = p      // index persisted
A(4) = q      // index persisted

It "can" be done using a integer counter combined with a Map but i'm wondering if a cleaner solution is already available.

Dirty approach using Map and integer counter:

HashMap<Integer, Object> map = new HashMap<>();
int indexCounter = 0;

public void insertItem(Object o){
    map.put(indexCounter, o);
    indexCounter++;
}

Any ideas?

Edit:
To clearify, by m, n, o, ... i mean different values. These are not necessarily string and can be any kind of objects. That's a pseudocode.

More than that, Using NULL or mock values would not be an option in my case. Although, i'm looking for a general solution, not a specific one for my case. Thanks for sharing btw.

Edit 2:
Actually, im looking for a data structure, not a hack or trick. Thus, if there is not such a thing provided in Java, the correct answer to this question would be a straight conclusive "No, there isn't such a thing".

Body:
You can make your own method thats replaces the value at a specific index to an empty String...

public void resetA_AtIndex(int index)
{
   A.remove(index);
   A.add(index, "");
}


问:
Convert JSON like string to python dict
Now I have a string like json from http requests, but the keys are not in the format of string. For example,

```<code>    >>> data_string = """
        {
        server_id: 1,
        server_status: 200,
        client: "client2",
        content: [ {id: 0, info: "info0"}, {id: 2, info: "info2"} ]
        }
    """
</code>```

I want to format it by JSON for easily extracting fields of the data string. I have a solution that using eval in python,

```<code>    eval(data_string, type('Dummy', (dict,), dict(__getitem__ = lambda s, n: n))())
</code>```

And it gives me the right data:

```<code>   {'server_id': 1, 'server_status': 200, 'client': 'client2', 'content': [{'id': 0, 'info': 'info0'}, {'id': 2, 'info': 'info2'}]}
</code>```

Please help me understand the tricks of the code. Thx.

PS: I have tried json but failed. However, yaml.load(data_string) works.

答:
This line

```<code>eval(data_string, type('Dummy', (dict,), dict(__getitem__ = lambda s, n: n))())
</code>```

is a very ugly way to do the same as

```<code>class Dummy(dict):
    def __getitem__(self, key):
        return key

globals_obj = Dummy()
eval(data_string, globals_obj)
</code>```

and then this globals_obj is passed into the globals parameter of eval. The globals must be a mapping object that maps names to values. Now when the eval encounters a variable being used, it will consult this mapping object, as if by globals_obj['variable_name']. The __getitem__ method simply returns the given key as a value, therefore globals_obj[42] -> 42, globals_obj[None]-> None  and so forth.

This all is very insecure - if the server wants to be malicious the api couldreturn code like __import__('os').system('execute an evil command').

If this is JavaScript but not JSON, you might be able to use the demjson module in strict=False mode. It is certainly better than using eval and might be better than using YAML as YAML parsers might be insecure. And these bugs might be easily remotely exploitable.

```<code>>>> import demjson
>>> data_string = """
...         {
...         server_id: 1,
...         server_status: 200,
...         client: "client2",
...         content: [ {id: 0, info: "info0"}, {id: 2, info: "info2"} ]
...         }
...     """
>>> demjson.decode(data_string, strict=False)
{'server_id': 1, 'server_status': 200, 'client': 'client2', 'content': [{'id': 0, 'info': 'info0'}, {'id': 2, 'info': 'info2'}]}
</code>```

Title: Convert JSON like string to python dict

Body:
Now I have a string like json from http requests, but the keys are not in the format of string. For example,

    >>> data_string = """
        {
        server_id: 1,
        server_status: 200,
        client: "client2",
        content: [ {id: 0, info: "info0"}, {id: 2, info: "info2"} ]
        }
    """

I want to format it by JSON for easily extracting fields of the data string. I have a solution that using eval in python,

    eval(data_string, type('Dummy', (dict,), dict(__getitem__ = lambda s, n: n))())

And it gives me the right data:

   {'server_id': 1, 'server_status': 200, 'client': 'client2', 'content': [{'id': 0, 'info': 'info0'}, {'id': 2, 'info': 'info2'}]}

Please help me understand the tricks of the code. Thx.

PS: I have tried json but failed. However, yaml.load(data_string) works.

Body:
This line

eval(data_string, type('Dummy', (dict,), dict(__getitem__ = lambda s, n: n))())

is a very ugly way to do the same as

class Dummy(dict):
    def __getitem__(self, key):
        return key

globals_obj = Dummy()
eval(data_string, globals_obj)

and then this globals_obj is passed into the globals parameter of eval. The globals must be a mapping object that maps names to values. Now when the eval encounters a variable being used, it will consult this mapping object, as if by globals_obj['variable_name']. The __getitem__ method simply returns the given key as a value, therefore globals_obj[42] -> 42, globals_obj[None]-> None  and so forth.

This all is very insecure - if the server wants to be malicious the api couldreturn code like __import__('os').system('execute an evil command').

If this is JavaScript but not JSON, you might be able to use the demjson module in strict=False mode. It is certainly better than using eval and might be better than using YAML as YAML parsers might be insecure. And these bugs might be easily remotely exploitable.

>>> import demjson
>>> data_string = """
...         {
...         server_id: 1,
...         server_status: 200,
...         client: "client2",
...         content: [ {id: 0, info: "info0"}, {id: 2, info: "info2"} ]
...         }
...     """
>>> demjson.decode(data_string, strict=False)
{'server_id': 1, 'server_status': 200, 'client': 'client2', 'content': [{'id': 0, 'info': 'info0'}, {'id': 2, 'info': 'info2'}]}


问:
Type-Erasure Error when using Generics without a Collection
I want to implement the Either monad in Java.
With the following code, I get the error Erasure of method Either(V) is the same as another method in type Either<T,V>
I don't see how T and V are type erased to the same type so that it causes an error.

```<code>public class Either<T, V> {
    private T t;
    private V v;

    public Either(T t) {
        this.t = t;
    }

    public Either(V v) {
        this.v = v;
    }
}
</code>```

Related posts, but not duplicates:

The following posts address two constructors, one with Collection<T> and another with Collection<V>. The problem is that both parameters to the constructors will be type erased to Collection and therefore they have the same type signature.

My post is not a duplicate since the primary types are different.

Erasure of method is the same as another method in type

Java name clash error, a method has the same erasure as another method

The following post addresses methods, one with compareTo(Real r) and another with compareTo(Object o)

My post is not a duplicate since the types T and V are not related, at least not in a way that I see.

Implementing Comparable, compareTo name clash: "have the same erasure, yet neither overrides the other"

Questions

Why does this type-erasure error occur?

How do I resolve this error to implement the Either monad in Java?

答:
Apparently, it is the same problem as Implementing Comparable, compareTo name clash: "have the same erasure, yet neither overrides the other" , except my question has a flavor of generics.

The generic types cannot be resolved on runtime since they have been translated to Object.
Therefore, public Either(T t) -> public Either(Object t)
and public Either(V v) -> public Either(Object v), which have the same type signature.

To solve the problem, one can do the following:

```<code>public class Either<T, V> {
    private T t;
    private V v;

    private Either(T t, V v) {
        this.t = t;
        this.v = v;
    }

    public static Either instaceOfT(T t) {
        return new Either<>(t, null);
    }

    public static Either instaceOfV(V v) {
        return new Either<>(null, v);
    }
}
</code>```

Body:
I want to implement the Either monad in Java.
With the following code, I get the error Erasure of method Either(V) is the same as another method in type Either<T,V>
I don't see how T and V are type erased to the same type so that it causes an error.

public class Either<T, V> {
    private T t;
    private V v;

    public Either(T t) {
        this.t = t;
    }

    public Either(V v) {
        this.v = v;
    }
}

Related posts, but not duplicates:

The following posts address two constructors, one with Collection<T> and another with Collection<V>. The problem is that both parameters to the constructors will be type erased to Collection and therefore they have the same type signature.

My post is not a duplicate since the primary types are different.

Erasure of method is the same as another method in type

Java name clash error, a method has the same erasure as another method

The following post addresses methods, one with compareTo(Real r) and another with compareTo(Object o)

My post is not a duplicate since the types T and V are not related, at least not in a way that I see.

Implementing Comparable, compareTo name clash: "have the same erasure, yet neither overrides the other"

Questions

Why does this type-erasure error occur?

How do I resolve this error to implement the Either monad in Java?

Body:
Apparently, it is the same problem as Implementing Comparable, compareTo name clash: "have the same erasure, yet neither overrides the other" , except my question has a flavor of generics.

The generic types cannot be resolved on runtime since they have been translated to Object.
Therefore, public Either(T t) -> public Either(Object t)
and public Either(V v) -> public Either(Object v), which have the same type signature.

To solve the problem, one can do the following:

public class Either<T, V> {
    private T t;
    private V v;

    private Either(T t, V v) {
        this.t = t;
        this.v = v;
    }

    public static Either instaceOfT(T t) {
        return new Either<>(t, null);
    }

    public static Either instaceOfV(V v) {
        return new Either<>(null, v);
    }
}


问:
Why the code is executing again even after the if condition returning false value?
Consider below code :

```<code><?php
  function test() {
    static $count = 0;

    $count++;
    echo $count."<br>";
    if($count < 2) {
      test();
      echo "In last line...".$count."<br>";
    }
    $count--;
    echo "Count Value : ".$count."<br>";
  }
  test();
?>
</code>```

Output is as below :

```<code>1
2
Count Value : 1
In last line...1
Count Value : 0
</code>```

I'm confused about the following part from the above output which is outlined with red colored border.

I want to know after if returning false on becoming $count = 2 the immediately following code line  echo "Count Value : ".$count."
"; gets executed. Then, it is expected to stop the flow as it's the last statement.

Why the program flow is not stopping after printing the line Count
Value : 1?

Then how the last two lines from the output are generating?

Who is calling the test() function again?

How does the static variable getting reset to 0 again and printing the last two lines of the output?

Does in recursion the remaining code after the function call gets executed as many times as the recursive function got called upon failure of the test condition?

答:
Please find the execution...</p>

```<code>1.first time calling test()
  -> initialized  static $count = 0;
  -> $count++//$count = 1
  -> echo $count."<br>";// output 1
  -> if($count < 2) { // here $count is 1 condition passed

2.calling from if statement test()
  -> static $count = 0; // as it is static variable will not lose its value when the function exits and will still hold that value should the function be called again // so here $count is 1
  -> $count++ //$count = 2
   -> echo $count."<br>";// output 2
  ->if($count < 2) { // here $count is 2 condition failed
  -> $count--;$count is 1
  -> output Count Value : 1
  -> calling from if statement test() is completed.
  -> prints next statement "In last line...".$count."<br>";//In last line...1 //value from first time calling test() // output In last line...1
  -> $count--;$count is 0
  -> Count Value : 0
</code>```

Body:
Consider below code :

<?php
  function test() {
    static $count = 0;

    $count++;
    echo $count."
";
    if($count < 2) {
      test();
      echo "In last line...".$count."
";
    }
    $count--;
    echo "Count Value : ".$count."
";
  }
  test();
?>

Output is as below :

1
2
Count Value : 1
In last line...1
Count Value : 0

I'm confused about the following part from the above output which is outlined with red colored border.

I want to know after if returning false on becoming $count = 2 the immediately following code line  echo "Count Value : ".$count."
"; gets executed. Then, it is expected to stop the flow as it's the last statement.

Why the program flow is not stopping after printing the line Count
Value : 1?

Then how the last two lines from the output are generating?

Who is calling the test() function again?

How does the static variable getting reset to 0 again and printing the last two lines of the output?

Does in recursion the remaining code after the function call gets executed as many times as the recursive function got called upon failure of the test condition?

Body:
Please find the execution...

1.first time calling test()
  -> initialized  static $count = 0;
  -> $count++//$count = 1
  -> echo $count."<br>";// output 1
  -> if($count < 2) { // here $count is 1 condition passed

2.calling from if statement test()
  -> static $count = 0; // as it is static variable will not lose its value when the function exits and will still hold that value should the function be called again // so here $count is 1
  -> $count++ //$count = 2
   -> echo $count."<br>";// output 2
  ->if($count < 2) { // here $count is 2 condition failed
  -> $count--;$count is 1
  -> output Count Value : 1
  -> calling from if statement test() is completed.
  -> prints next statement "In last line...".$count."<br>";//In last line...1 //value from first time calling test() // output In last line...1
  -> $count--;$count is 0
  -> Count Value : 0


问:
Error: no "view" mailcap rules found for type "application/pdf" pythonanywhere server log
I'm trying to Use lolviz and graphviz to visualize data structures, but there is no output. This is the error I get in server logs: groupn.pythonanywhere.com.server.log

Warning: 2017-11-14 16:32:24 Illegal attribute sides in  - ignored 2017-11-14 16:32:24
Warning: 2017-11-14 16:32:24 Illegal attribute sides in  - ignored 2017-11-14 16:32:24 in label of node node140165832004944 2017-11-14 16:32:24
Warning: 2017-11-14 16:32:24 Illegal attribute sides in  - ignored 2017-11-14 16:32:24 in label of node node140165832024136 2017-11-14 16:32:24
Error: no "view" mailcap rules found for type "application/pdf" 2017-11-14 16:32:24 /usr/bin/xdg-open: 461: /usr/bin/xdg-open: 2017-11-14 16:32:24
 links2: not found
```

<p>This is where the function is in my views.py</p>

```elif 'show' in request.POST:
                data = callviz(s).view(filename=None, directory=None, cleanup=True)
                return render(request, 'file/stacks.html', {'form': form, 'data': data})
```

答: view is trying to open the generated viz as a PDF on PythonAnywhere. That's not a particularly useful thing to do in a web app. Generate the viz into some format that you can embed in to a web page or offer for download.</p>

Body:
I'm trying to Use lolviz and graphviz to visualize data structures, but there is no output. This is the error I get in server logs: groupn.pythonanywhere.com.server.log

Warning: 2017-11-14 16:32:24 Illegal attribute sides in  - ignored 2017-11-14 16:32:24
Warning: 2017-11-14 16:32:24 Illegal attribute sides in  - ignored 2017-11-14 16:32:24 in label of node node140165832004944 2017-11-14 16:32:24
Warning: 2017-11-14 16:32:24 Illegal attribute sides in  - ignored 2017-11-14 16:32:24 in label of node node140165832024136 2017-11-14 16:32:24
Error: no "view" mailcap rules found for type "application/pdf" 2017-11-14 16:32:24 /usr/bin/xdg-open: 461: /usr/bin/xdg-open: 2017-11-14 16:32:24
 links2: not found

This is where the function is in my views.py

elif 'show' in request.POST:
                data = callviz(s).view(filename=None, directory=None, cleanup=True)
                return render(request, 'file/stacks.html', {'form': form, 'data': data})


答:
```<code><?php
function test()
{
    static $count = 0;

    $count++;
    echo $count."<br>";//first output is 1
    if($count < 2) //first time condition true(i.e 1<2) and second time it is false
   {
      test();
/* here you again calling same function then $count will became 2 and you did not return anything here so next code will get executed after complete of 2nd time function. if you set **return false** here then your marked output does not execute*/
  echo "In last line...".$count."<br>";//Here $count will be 1 because its continuing first statement
    }
    $count--;//first time $count is 2 here but you are decremented here so 1
             // second time $count is 1 because continuing first statement and again its decremented so value will became 0.
    echo "Count Value : ".$count."<br>";// first output is 1//second output is 0
}
test();
?>
</code>```

Title: Why the code is executing again even after the if condition returning false value?


问:
Find hashed (bcyrpt) code in database and validate it with input (Laravel)
I have a simple form with a single input field where you can submit a code (respectively a key). In my database are a bunch of codes stored (in clear text) and if the form input matches with one of those codes you get access to some Stuff.

This is the way I am finding out which code has been used to fetch the data

```<code>$usedCode = Stuff::where('code', $request->code)->get();
</code>```

Now while this works perfect I wanted to add some security to it. Because if somebody has access to my database he can just read the codes.

I tried to bcrypt all the codes but then of course the method above does not work anymore.

I know it is not possible to "decrypt" the hashed codes but how can I solve this?
Or is there no security breach I need to worry about and I should just use the clear text?

答:
I would rather suggest you implement rate limiting. Only one request per minute per visitor and 24 hr block when entering more than 3 invalid codes consecutively. That way they can't spam you with millions of requests to guess codes.

When someone has access to your database all bets are off anyhow. When you find out you've been hacked/database stolen you have other things to worry about.

At this moment it seems your strategy only exists out of a code entering and then you get your Stuff™

Add a layer of security/verification by also entering an email, that the user must be logged in, or a second key that was supplied with it or separately that only legit users can have.

You can then hash the codes with user_id/special extra key, or whatever to find the right lookup key. This is only obfuscation, but will make it impossible for people to harvest the codes and then request all the Stuff™ you have.

When hackers get access to your php code also, all bets are completely off you better wipe slates clean.

edit

Another possible idea I had:
Store TheKeyCode™ + Stuff™ primary key  in database KeyStorage. All that database does is store the codes users use. KeyStorage must have a different user and password than your production database

Store Stuff™ + Stuff™PK in your production database.

Only for key lookup you set up a connection to the KeyStorage database. That script is also the only place where those details are guarded.
That way IF your website has a weakness that someone can pull empty your production database, they won't get the key codes. And if your key code script is secure and contains no flaws, they have no way to connect to the KeyStorage.

```<code>$dsn = 'mysql:dbname=KeyStorage;host=127.0.0.1';
$user = 'keymaster';
$password = 'zuul';

try {
    $dbh = new PDO($dsn, $user, $password);
    $stmt = $dbh->prepare("SELECT stuff_tm_id FROM gozer WHERE code=:code LIMIT 1");
    $stmt->bindParam(':code', $code, PDO::PARAM_STR, 12);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $stuff = Stufff::find($row['stuff_tm_id']);
} catch (PDOException $e) {
    echo 'Where is the gatekeeper';
}
</code>```

Body:
I have a simple form with a single input field where you can submit a code (respectively a key). In my database are a bunch of codes stored (in clear text) and if the form input matches with one of those codes you get access to some Stuff.

This is the way I am finding out which code has been used to fetch the data

$usedCode = Stuff::where('code', $request->code)->get();

Now while this works perfect I wanted to add some security to it. Because if somebody has access to my database he can just read the codes.

I tried to bcrypt all the codes but then of course the method above does not work anymore.

I know it is not possible to "decrypt" the hashed codes but how can I solve this?
Or is there no security breach I need to worry about and I should just use the clear text?

Body:
I would rather suggest you implement rate limiting. Only one request per minute per visitor and 24 hr block when entering more than 3 invalid codes consecutively. That way they can't spam you with millions of requests to guess codes.

When someone has access to your database all bets are off anyhow. When you find out you've been hacked/database stolen you have other things to worry about.

At this moment it seems your strategy only exists out of a code entering and then you get your Stuff™

Add a layer of security/verification by also entering an email, that the user must be logged in, or a second key that was supplied with it or separately that only legit users can have.

You can then hash the codes with user_id/special extra key, or whatever to find the right lookup key. This is only obfuscation, but will make it impossible for people to harvest the codes and then request all the Stuff™ you have.

When hackers get access to your php code also, all bets are completely off you better wipe slates clean.

edit

Another possible idea I had:
Store TheKeyCode™ + Stuff™ primary key  in database KeyStorage. All that database does is store the codes users use. KeyStorage must have a different user and password than your production database

Store Stuff™ + Stuff™PK in your production database.

Only for key lookup you set up a connection to the KeyStorage database. That script is also the only place where those details are guarded.
That way IF your website has a weakness that someone can pull empty your production database, they won't get the key codes. And if your key code script is secure and contains no flaws, they have no way to connect to the KeyStorage.

$dsn = 'mysql:dbname=KeyStorage;host=127.0.0.1';
$user = 'keymaster';
$password = 'zuul';

try {
    $dbh = new PDO($dsn, $user, $password);
    $stmt = $dbh->prepare("SELECT stuff_tm_id FROM gozer WHERE code=:code LIMIT 1");
    $stmt->bindParam(':code', $code, PDO::PARAM_STR, 12);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $stuff = Stufff::find($row['stuff_tm_id']);
} catch (PDOException $e) {
    echo 'Where is the gatekeeper';
}


答:
Array in Javascript cannot replicate Associative array in PHP.

For your use case you would have to have array of objects like this.

```<code>var users = [
    {
      emailAddress: 'david@email.com',
      password: 'secretCat';
    },
    {
      emailAddress: 'john@email.com',
      password: 'secretCatTwo';
    },
    {
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree';
    },
    {
       emailAddress: 'susan@email.com',
       password: 'secretCatFour';
    }
 ];
</code>```

Title: Javascript arrays with email address and password

Body:
I work with PHP and I am more familiar with it. I have tried an array in Javascript but keep getting a syntax error and I am not sure why. I have Googled arrays and I do not seem to get the answer.

Here is my array of Users in Javascript:

var users = [
    [
      emailAddress: 'david@email.com',
      password: 'secretCat';
    ],
    [
      emailAddress: 'john@email.com',
      password: 'secretCatTwo';
    ],

    [
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree';
    ],

    [
       emailAddress: 'susan@email.com',
       password: 'secretCatFour';
    ],

];

Am I supposed to do it differently in Javascript?

Body:
Array in Javascript cannot replicate Associative array in PHP.

For your use case you would have to have array of objects like this.

var users = [
    {
      emailAddress: 'david@email.com',
      password: 'secretCat';
    },
    {
      emailAddress: 'john@email.com',
      password: 'secretCatTwo';
    },
    {
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree';
    },
    {
       emailAddress: 'susan@email.com',
       password: 'secretCatFour';
    }
 ];


问:
react native - arrow notation
```<code><TouchableHighlight
  onPressIn={this._onPressIn}
>

_onPressIn = () => {
  this.setState({ pressing: true });
}
//1. works

_onPressIn(){
  this.setState({ pressing: true });
}
//2. error
</code>```

```<code><TouchableHighlight
  onPress={this._onPress}
>

_onPress(){
  Alert.alert('','HELLO');
}
//3. works

_onPress=()=>{
  Alert.alert('','HELLO');
}
//4. works
</code>```

I can't speak English very well. So I'm not sure if you will get what I say, but I will try hard to make you understand my words.

Are there something difference between 1 and 2 ??
If it exist, then why 3 and 4 have same result??

I have thought there's no difference between 1 and 2.. But example 1 is working normally, the other is not..

答:
If your are not using an arrow function you have to bind "this" to your Button. e.g: </p>

```<code><TouchableHighlight
  onPressIn={this._onPressIn.bind(this)}
>
</code>```

<p>should work for case #2. </p>

Title: react native - arrow notation

Body:
<TouchableHighlight
  onPressIn={this._onPressIn}
>

_onPressIn = () => {
  this.setState({ pressing: true });
}
//1. works

_onPressIn(){
  this.setState({ pressing: true });
}
//2. error

<TouchableHighlight
  onPress={this._onPress}
>

_onPress(){
  Alert.alert('','HELLO');
}
//3. works

_onPress=()=>{
  Alert.alert('','HELLO');
}
//4. works

I can't speak English very well. So I'm not sure if you will get what I say, but I will try hard to make you understand my words.

Are there something difference between 1 and 2 ??
If it exist, then why 3 and 4 have same result??

I have thought there's no difference between 1 and 2.. But example 1 is working normally, the other is not..

Body:
If your are not using an arrow function you have to bind "this" to your Button. e.g:

<TouchableHighlight
  onPressIn={this._onPressIn.bind(this)}
>

should work for case #2.


问:
TRUNCATE in SQL Server rolls back on failure of last TRUNCATE
I am starting a transaction and executing multiple truncate table statements but if last fails then it rolls back all truncate. I am trying to depict the same behavior on SQL Server command prompt.

I am trying to execute following SQL statements in SQL Server 2012:

```<code>create table pkt1(id integer)
GO

create table pkt2(id integer)
GO

insert into pkt1 values(10)
insert into pkt1 values(20)

insert into pkt2 values(10)
insert into pkt2 values(20)

select * from pkt1
</code>```

Output:

```<code>id
------
10
20

select * from pkt2
</code>```

Result:

```<code>id
------
10
20

begin transaction
   truncate table pkt1;
   truncate table pkt2;
   truncate table pkt3;
   commit;
</code>```

Error:

Msg 4701, Level 16, State 1, Server PNI6W11198, Line 4

  Cannot find the object "pkt3" because it does not exist or you do not have permissions.

```<code>select * from pkt2
</code>```

Output:

```<code>id
------
10
20

select * from pkt1
</code>```

Output:

```<code>id
-----
10
20
</code>```

TRUNCATE is supposed to be Transact SQL and should commit earlier truncate for pkt1 and pkt2. But it does rollback for all.

Is this expected behavior?

答:
Table pkt3 does not exist so that script fails.

Your transaction brackets all three truncate statements : one fails - they all fail

Body:
I am starting a transaction and executing multiple truncate table statements but if last fails then it rolls back all truncate. I am trying to depict the same behavior on SQL Server command prompt.

I am trying to execute following SQL statements in SQL Server 2012:

create table pkt1(id integer)
GO

create table pkt2(id integer)
GO

insert into pkt1 values(10)
insert into pkt1 values(20)

insert into pkt2 values(10)
insert into pkt2 values(20)

select * from pkt1

Output:

id
------
10
20

select * from pkt2

Result:

id
------
10
20

begin transaction
   truncate table pkt1;
   truncate table pkt2;
   truncate table pkt3;
   commit;

Error:

Msg 4701, Level 16, State 1, Server PNI6W11198, Line 4

  Cannot find the object "pkt3" because it does not exist or you do not have permissions.

select * from pkt2

Output:

id
------
10
20

select * from pkt1

Output:

id
-----
10
20

TRUNCATE is supposed to be Transact SQL and should commit earlier truncate for pkt1 and pkt2. But it does rollback for all.

Is this expected behavior?


问:
Normalizing by dividing by max value VS sum of all values
I'm implementing a Gaussian filter in which, as explained in one Dimensional gauss convolution function in Matlab, I'm normalising the filter coefficients by dividing them by sum of all the coefficients.   Normalizing by max value or by total value? explains that normalisation can be done by dividing by maximum of the coefficients too.

I'm unable to get the point that what should be the conditions/specifications to be considered in choosing the normalising factor?

答: Conventionally, you should divide by the sum of all the coefficients, so that the DC gain is unity (i.e. low frequency signals are not changed by the filter).


问:
Python taking extra space in command line arguments
When I have the following code portion in python and suppose we execute this python file with a input file input.txt as the first command line argument.

```<code>import os
import sys
with open(sys.argv[1],"r") as input:
</code>```

Suppose the name of the python file is file.py and input.txt is the argument to this, so the command is as follows,

```<code>>>file.py input.txt
</code>```

I am getting the following error:

```<code>Traceback (most recent call last):
File "C:\Users\hdutta\Desktop\file.py", line 3, in <module>
with open(sys.argv[1],"r") as input:
IOError: [Errno 2] No such file or directory: ' input.txt'
</code>```

Looks like it is taking an extra space at the first argument. Why is it so? Am I missing something. This was working before. But I have a new system now and I am facing this issue.

I got some clue in the link -- Python argparse adds extra space before an argument

But I am unable to modify sys.argv = if there is any way to do that.

答:
Hmm weird

But you could do:

```<code>sys.argv[1].lstrip().strip() # Will remove any spaces to left / right of the string.
</code>```

Body:
When I have the following code portion in python and suppose we execute this python file with a input file input.txt as the first command line argument.

import os
import sys
with open(sys.argv[1],"r") as input:

Suppose the name of the python file is file.py and input.txt is the argument to this, so the command is as follows,

>>file.py input.txt

I am getting the following error:

Traceback (most recent call last):
File "C:\Users\hdutta\Desktop\file.py", line 3, in <module>
with open(sys.argv[1],"r") as input:
IOError: [Errno 2] No such file or directory: ' input.txt'

Looks like it is taking an extra space at the first argument. Why is it so? Am I missing something. This was working before. But I have a new system now and I am facing this issue.

I got some clue in the link -- Python argparse adds extra space before an argument

But I am unable to modify sys.argv = if there is any way to do that.

Body:
Hmm weird

But you could do:

sys.argv[1].lstrip().strip() # Will remove any spaces to left / right of the string.


问:
Select, default value in AngularJS
Hey I have problem with set default value in select problem is started when I set inside array objects. How can I fix this problem??

HTML

```<code><div ng-app="select" ng-controller="checking">
  <select ng-model="lala" ng-options="item.name for item in arrayName">
  </select>
</div>
</code>```

JavaScript

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

app.controller('checking', ($scope)=> {
  $scope.arrayName = [{'name':'first'}, {'name':'second'}, {'name':'third'}];
  $scope.lala = "first";
});
</code>```

https://codepen.io/Turqus/pen/EbvGzv?editors=1111

答:
You can try below example you have to change array bit</p>

```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
    <select ng-model="prop.value" ng-options="v for v in prop.values">
    </select>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope)
{
    $scope.prop =
    {
        "type": "select",
        "name": "Service",
        "value": "first",
        "values": ['first','second','third']
    };
});
</script>
</code>```

Title: Select, default value in AngularJS

Body:
Hey I have problem with set default value in select problem is started when I set inside array objects. How can I fix this problem??

HTML

  <select ng-model="lala" ng-options="item.name for item in arrayName">
  </select>

JavaScript

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

app.controller('checking', ($scope)=> {
  $scope.arrayName = [{'name':'first'}, {'name':'second'}, {'name':'third'}];
  $scope.lala = "first";
});

https://codepen.io/Turqus/pen/EbvGzv?editors=1111

Body:
You can try below example you have to change array bit

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
    <select ng-model="prop.value" ng-options="v for v in prop.values">
    </select>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope)
{
    $scope.prop =
    {
        "type": "select",
        "name": "Service",
        "value": "first",
        "values": ['first','second','third']
    };
});
</script>


问:
Docker Oracle12c Enterprise image created from container symlink broken
We are trying to create a docker image from a container based on the Oracle 12c Enterprise Edition image from docker store (https://store.docker.com/images/oracle-database-enterprise-edition). We have the container working ok and then, after stopping the container we create an image based on that container with the following command.

```<code>docker commit Oracle_12 oracle/oradb:1
</code>```

Then, we try to run a container using the commited image with the following command:

```<code>docker run -d -it --name oradb_cont -p 1512:1521 -p 5500:5500 oracle/oradb:1
</code>```

This container fails with the following error:

```<code>Start up Oracle Database
Wed Nov 15 10:31:29 UTC 2017
start database
start listener
The database is ready for use .
tail: cannot open '/u01/app/oracle/diag/rdbms/orclcdb/ORCLCDB/trace/alert_ORCLCDB.log' for reading: No such file or directory
tail: no files remaining
</code>```

The container is "Exited" although the message "The database is ready for use".
We have attached a bash to the container to inspect where the missing file is. And the result seems to be that the "/diag" folder is a broken symlink:

Starting the original Oracle 12c container and attaching a bash, the folder is present. It seems symlink is broken or the file is not present only in the image created from the container.

答:
The problem is that /ORCL is a data volume. The commit operation does not include any files that are inside volumes. You can check the commit documentation for more info.

Thus when starting the new instance, it appears that somehow the log file is being referenced and has not been yet created. Your current container is in an inconsistent state, as the files under '/ORCL' that were present in the commited container are missing from the new instance.

If you are running the new instance on a new machine you need to migrate the old volume into the new machine. You can find the volume of the old container by running docker inspect -f '{{ .Mounts }}' <old-container-name>, and migrate as specified in  How to port data-only volumes from one host to another?

If you are running the new instance on the same machine, just mount the old volume using: <volume-name-or-id>:/ORCL

In general, as a best practice, you shouldn't rely on the commit command to get identical instances of a container. Rather build a DockerFile which extends the base image, and then add customizations by selecting only the necessary files to copy over on the new instance.

Body:
We are trying to create a docker image from a container based on the Oracle 12c Enterprise Edition image from docker store (https://store.docker.com/images/oracle-database-enterprise-edition). We have the container working ok and then, after stopping the container we create an image based on that container with the following command.

docker commit Oracle_12 oracle/oradb:1

Then, we try to run a container using the commited image with the following command:

docker run -d -it --name oradb_cont -p 1512:1521 -p 5500:5500 oracle/oradb:1

This container fails with the following error:

Start up Oracle Database
Wed Nov 15 10:31:29 UTC 2017
start database
start listener
The database is ready for use .
tail: cannot open '/u01/app/oracle/diag/rdbms/orclcdb/ORCLCDB/trace/alert_ORCLCDB.log' for reading: No such file or directory
tail: no files remaining

The container is "Exited" although the message "The database is ready for use".
We have attached a bash to the container to inspect where the missing file is. And the result seems to be that the "/diag" folder is a broken symlink:

Starting the original Oracle 12c container and attaching a bash, the folder is present. It seems symlink is broken or the file is not present only in the image created from the container.


问:
js async/await throws error on using this keyword
So, here's the code

```<code>let x = await this.storeFileName(fileName);
</code>```

So, I've declared the storeFileName function as async and I'm also returning a promise and everything till here is fine. But I'm getting an error that says :

SyntaxError: Unexpected token this which is pointing to the 'this' followed by the await keyword

Btw I'm using an ES6 class and the this keyword refers to the object of that class.

It works without the await keyword but if I put await it throws an error.

What am I doing wrong? Everything seems correct. Can someone throw some light on me.

UPDATE :

These are the two functions.

```<code>   async encodeName(x){
     return new Promise((resolve,reject)=>{
        const cipher = crypto.createCipher('aes192', this.PASSWORD);
        let encrypted = cipher.update(x,'utf8', 'hex');
        encrypted += cipher.final('hex');
        if(encrypted.length>240){
         let x = await this.storeFileName(encrypted);
         resolve(`@Fn ${x}`);
      }
      resolve(encrypted);
     });
   }

   async storeFileName(x){
     return new Promise((resolve,reject)=>{
      let doc = { encName: x };
      filesDb = new db(`${this.mntpnt}/__CORE_rigel.pro/x100.db`);
      filesDb.insert(doc,(err,newdoc)=>{
        err?reject():resolve(newdoc._id);
      });
     });
   }
</code>```

Btw, I'm doing this on node.js

UPDATE 2 :

Here is the error message

```<code>A JavaScript error occurred in the main process
Uncaught Exception:
/home/teja/Documents/Rigel/components/diskEncryptor.js:32
        let x = await this.storeFileName(encrypted);
                      ^^^^
SyntaxError: Unexpected token this
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/teja/Documents/Rigel/index.js:4:23)
</code>```

答:
You are creating a new function

return new Promise((resolve,reject)=>{

you should declare that function as async too:

return new Promise(async (resolve,reject)=>{

The new function will be

```<code>async function encodeName(x){
 return new Promise(async (resolve,reject)=>{
    const cipher = crypto.createCipher('aes192', this.PASSWORD);
    let encrypted = cipher.update(x,'utf8', 'hex');
    encrypted += cipher.final('hex');
    if(encrypted.length>240){
     let x = await this.storeFileName(encrypted);
     resolve(`@Fn ${x}`);
    }
    resolve(encrypted);
 });
}
</code>```

Body:
So, here's the code

let x = await this.storeFileName(fileName);

So, I've declared the storeFileName function as async and I'm also returning a promise and everything till here is fine. But I'm getting an error that says :

SyntaxError: Unexpected token this which is pointing to the 'this' followed by the await keyword

Btw I'm using an ES6 class and the this keyword refers to the object of that class.

It works without the await keyword but if I put await it throws an error.

What am I doing wrong? Everything seems correct. Can someone throw some light on me.

UPDATE :

These are the two functions.

   async encodeName(x){
     return new Promise((resolve,reject)=>{
        const cipher = crypto.createCipher('aes192', this.PASSWORD);
        let encrypted = cipher.update(x,'utf8', 'hex');
        encrypted += cipher.final('hex');
        if(encrypted.length>240){
         let x = await this.storeFileName(encrypted);
         resolve(`@Fn ${x}`);
      }
      resolve(encrypted);
     });
   }

   async storeFileName(x){
     return new Promise((resolve,reject)=>{
      let doc = { encName: x };
      filesDb = new db(`${this.mntpnt}/__CORE_rigel.pro/x100.db`);
      filesDb.insert(doc,(err,newdoc)=>{
        err?reject():resolve(newdoc._id);
      });
     });
   }

Btw, I'm doing this on node.js

UPDATE 2 :

Here is the error message

A JavaScript error occurred in the main process
Uncaught Exception:
/home/teja/Documents/Rigel/components/diskEncryptor.js:32
        let x = await this.storeFileName(encrypted);
                      ^^^^
SyntaxError: Unexpected token this
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/teja/Documents/Rigel/index.js:4:23)

Body:
You are creating a new function

return new Promise((resolve,reject)=>{

you should declare that function as async too:

return new Promise(async (resolve,reject)=>{

The new function will be

async function encodeName(x){
 return new Promise(async (resolve,reject)=>{
    const cipher = crypto.createCipher('aes192', this.PASSWORD);
    let encrypted = cipher.update(x,'utf8', 'hex');
    encrypted += cipher.final('hex');
    if(encrypted.length>240){
     let x = await this.storeFileName(encrypted);
     resolve(`@Fn ${x}`);
    }
    resolve(encrypted);
 });
}