问:
JavaScript does not work when I put it on the server
I have a code that when I run it from any part of the PC without putting it on the server it works perfectly, but when I put it on the server and I call it, it gives me the following error:

Uncaught ReferenceError: crearLienzo is not defined
    at onload ((index):81)

I do not understand why this happens. Thank you all!

```<code><html>
<head>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" >
    var movimientos = new Array();
    var pulsado;
    function crearLienzo() {
    var canvasDiv = document.getElementById('lienzo');
canvas = document.createElement('canvas');
canvas.setAttribute('width', 200);
canvas.setAttribute('height', 200);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if(typeof G_vmlCanvasManager != 'undefined') {
    canvas = G_vmlCanvasManager.initElement(canvas);
}
context = canvas.getContext("2d");

    $('#canvas').mousedown(function(e){
      pulsado = true;
      movimientos.push([e.pageX - this.offsetLeft,
          e.pageY - this.offsetTop,
          false]);
      repinta();
    });

    $('#canvas').mousemove(function(e){
      if(pulsado){
          movimientos.push([e.pageX - this.offsetLeft,
              e.pageY - this.offsetTop,
              true]);
        repinta();
      }
    });

    $('#canvas').mouseup(function(e){
      pulsado = false;
    });

    $('#canvas').mouseleave(function(e){
      pulsado = false;
    });
    repinta();

}

    function repinta() {
        // función para dibujar en el lienzo los movimientos del ratón que hemos
        // recogido en la variable "movimientos"
         canvas.width = canvas.width; // Limpia el lienzo

  context.strokeStyle = "#0000a0";
  context.lineJoin = "round";
  context.lineWidth = 6;

  for(var i=0; i < movimientos.length; i++)
  {
    context.beginPath();
    if(movimientos[i][2] && i){
      context.moveTo(movimientos[i-1][0], movimientos[i-1][1]);
     }else{
      context.moveTo(movimientos[i][0], movimientos[i][1]);
     }
     context.lineTo(movimientos[i][0], movimientos[i][1]);
     context.closePath();
     context.stroke();
  }
}
function convertCanvasToImage(canvas) {
       var image = new Image();
       image.src = canvas[0].toDataURL("image/png");
        alert(image);
       return image;
}
</script>
</head>
<body style="background: #eee;" onload="crearLienzo()">
<div id="lienzo" style="width: 200px; height: 200px; background: #fff;"></div>
<button type="button" onclick="convertCanvasToImage($('#canvas'));">aa</button>

</body>
</html>
</code>```

答:
Use jQuery library from googleapis library. Include your script tag before the end of the body tag.

```<code><html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body style="background: #eee;" onload="crearLienzo()">
<div id="lienzo" style="width: 200px; height: 200px; background: #fff;"></div>
<button type="button" onclick="convertCanvasToImage($('#canvas'));">aa</button>
<script type="text/javascript" >
    var movimientos = new Array();
    var pulsado;
    function crearLienzo() { alert('hea');
    var canvasDiv = document.getElementById('lienzo');
canvas = document.createElement('canvas');
canvas.setAttribute('width', 200);
canvas.setAttribute('height', 200);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if(typeof G_vmlCanvasManager != 'undefined') {
    canvas = G_vmlCanvasManager.initElement(canvas);
}
context = canvas.getContext("2d");

    $('#canvas').mousedown(function(e){
      pulsado = true;
      movimientos.push([e.pageX - this.offsetLeft,
          e.pageY - this.offsetTop,
          false]);
      repinta();
    });

    $('#canvas').mousemove(function(e){
      if(pulsado){
          movimientos.push([e.pageX - this.offsetLeft,
              e.pageY - this.offsetTop,
              true]);
        repinta();
      }
    });

    $('#canvas').mouseup(function(e){
      pulsado = false;
    });

    $('#canvas').mouseleave(function(e){
      pulsado = false;
    });
    repinta();

}

    function repinta() {
        // función para dibujar en el lienzo los movimientos del ratón que hemos
        // recogido en la variable "movimientos"
         canvas.width = canvas.width; // Limpia el lienzo

  context.strokeStyle = "#0000a0";
  context.lineJoin = "round";
  context.lineWidth = 6;

  for(var i=0; i < movimientos.length; i++)
  {
    context.beginPath();
    if(movimientos[i][2] && i){
      context.moveTo(movimientos[i-1][0], movimientos[i-1][1]);
     }else{
      context.moveTo(movimientos[i][0], movimientos[i][1]);
     }
     context.lineTo(movimientos[i][0], movimientos[i][1]);
     context.closePath();
     context.stroke();
  }
}
function convertCanvasToImage(canvas) {
       var image = new Image();
       image.src = canvas[0].toDataURL("image/png");
        alert(image);
       return image;
}
</script>

</body>
</html>
</code>```

This way it will work everywhere. Also as script tag is included at the end of the body tag, it will load after all the css and image files are loaded.

Body:
I have a code that when I run it from any part of the PC without putting it on the server it works perfectly, but when I put it on the server and I call it, it gives me the following error:

Uncaught ReferenceError: crearLienzo is not defined
    at onload ((index):81)

I do not understand why this happens. Thank you all!

<button type="button" onclick="convertCanvasToImage($('#canvas'));">aa</button>

Body:
Use jQuery library from googleapis library. Include your script tag before the end of the body tag.

<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body style="background: #eee;" onload="crearLienzo()">
<div id="lienzo" style="width: 200px; height: 200px; background: #fff;"></div>
<button type="button" onclick="convertCanvasToImage($('#canvas'));">aa</button>
<script type="text/javascript" >
    var movimientos = new Array();
    var pulsado;
    function crearLienzo() { alert('hea');
    var canvasDiv = document.getElementById('lienzo');
canvas = document.createElement('canvas');
canvas.setAttribute('width', 200);
canvas.setAttribute('height', 200);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if(typeof G_vmlCanvasManager != 'undefined') {
    canvas = G_vmlCanvasManager.initElement(canvas);
}
context = canvas.getContext("2d");

    $('#canvas').mousedown(function(e){
      pulsado = true;
      movimientos.push([e.pageX - this.offsetLeft,
          e.pageY - this.offsetTop,
          false]);
      repinta();
    });

    $('#canvas').mousemove(function(e){
      if(pulsado){
          movimientos.push([e.pageX - this.offsetLeft,
              e.pageY - this.offsetTop,
              true]);
        repinta();
      }
    });

    $('#canvas').mouseup(function(e){
      pulsado = false;
    });

    $('#canvas').mouseleave(function(e){
      pulsado = false;
    });
    repinta();

}

    function repinta() {
        // función para dibujar en el lienzo los movimientos del ratón que hemos
        // recogido en la variable "movimientos"
         canvas.width = canvas.width; // Limpia el lienzo

  context.strokeStyle = "#0000a0";
  context.lineJoin = "round";
  context.lineWidth = 6;

  for(var i=0; i < movimientos.length; i++)
  {
    context.beginPath();
    if(movimientos[i][2] && i){
      context.moveTo(movimientos[i-1][0], movimientos[i-1][1]);
     }else{
      context.moveTo(movimientos[i][0], movimientos[i][1]);
     }
     context.lineTo(movimientos[i][0], movimientos[i][1]);
     context.closePath();
     context.stroke();
  }
}
function convertCanvasToImage(canvas) {
       var image = new Image();
       image.src = canvas[0].toDataURL("image/png");
        alert(image);
       return image;
}
</script>

</body>
</html>

This way it will work everywhere. Also as script tag is included at the end of the body tag, it will load after all the css and image files are loaded.


来源: stackexchange

问:
Passing Id from one view to another when Button is clicked in Laravel 5.4
```<code>I am using response from xml server. I am trying to display the different detail view when each BUtton is pressed respectively.When the Button is pressed, I want to send the Id of each button to the detailed page and I want to display that Id on the detailed page too.

My Button for clicking and passing ID to next view respective to each button clicked is:

 <a href='{{route('Detailed',["Id" => $flight["Id"]])}}'>SELECT NOW</a>
$flight["Id"] is the response value that I get from the xml server
</code>```

My route is for passing Id is: Id is what I want to pass from one view to another and display in second view

```<code>Route::get('/Detailed/{Id}',[
        'as' => 'Detailed', 'uses'=>'FlightController@show'
]);
</code>```

My controller function to display is:
    public function show($Id)
    {}

It gives me error saying that:

```<code>Missing required parameters for [Route: Detailed] [URI: Detailed/{Id}] in view.blade.php.
Please anyone help me

But if give direct value in button route
such as ID value then,

<a href='{{route('Detailed',["Id" => "1234"])}}'>SELECT NOW</a>

It works exactly what I expect.

Notes the Id value that I get is from simple_xml_response from server.
</code>```

答:
Try this:

Route

```<code>Route::get('detailed/{id}', 'FlightController@show')->name('detailed');
</code>```

Controller

```<code>public function show($id) {}
</code>```

Blade

```<code><a href='{{route('detailed', '1234')}}'>SELECT NOW</a>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using response from xml server. I am trying to display the different detail view when each BUtton is pressed respectively.When the Button is pressed, I want to send the Id of each button to the detailed page and I want to display that Id on the detailed page too.

My Button for clicking and passing ID to next view respective to each button clicked is:

  $flight["Id"]])}}'>SELECT NOW
$flight["Id"] is the response value that I get from the xml server

My route is for passing Id is: Id is what I want to pass from one view to another and display in second view

Route::get('/Detailed/{Id}',[
        'as' => 'Detailed', 'uses'=>'FlightController@show'
]);

My controller function to display is:
    public function show($Id)
    {}

It gives me error saying that:

Missing required parameters for [Route: Detailed] [URI: Detailed/{Id}] in view.blade.php.
Please anyone help me

But if give direct value in button route
such as ID value then,

 "1234"])}}'>SELECT NOW

It works exactly what I expect.

Notes the Id value that I get is from simple_xml_response from server.

Body:
Try this:

Route

Route::get('detailed/{id}', 'FlightController@show')->name('detailed');

Controller

public function show($id) {}

Blade

<a href='{{route('detailed', '1234')}}'>SELECT NOW</a>


问:
Write a text into file
I just started new project in Visual Studio 2017 and I tried to write some text into file. But after I run my code, no file is created.

```<code>int main()
{
    ofstream file_program("D:\test2.txt", ios::out);
    if (file_program.is_open())
    {
        file_program << "test";
        cout << "OK";

        file_program.close();
    }

    int age;
    cin >> age;

    return 0;
}
</code>```

What am i doing wrong?

答:
In C++ you have to escape the backslash.

```<code>"D:\test2.txt"
</code>```

Here you have '\t' which is effectively a tabulator.

```<code>"D:\\test2.txt"
</code>```

Would be correct.

Title: Write a text into file

Body:
I just started new project in Visual Studio 2017 and I tried to write some text into file. But after I run my code, no file is created.

int main()
{
    ofstream file_program("D:\test2.txt", ios::out);
    if (file_program.is_open())
    {
        file_program << "test";
        cout << "OK";

        file_program.close();
    }

    int age;
    cin >> age;

    return 0;
}

What am i doing wrong?

Body:
In C++ you have to escape the backslash.

"D:\test2.txt"

Here you have '\t' which is effectively a tabulator.

"D:\\test2.txt"

Would be correct.


问:
I want Jenkins job to build every two weeks
Will this expression run the build every other Friday at noon? Assume i set this up on a Friday?

0 12 * * */14

I tried 0 12 * * FRI/14 but Jenkins returned an error.

I ma trying to run a code report job every two weeks to match scrum.

答:
I had the same issue, the easy work around I found was to create another job that run weekly.

This job was a simple groovy script that does the following:

```<code>import jenkins.model.*;
def job = Jenkins.instance.getJob('JobNameToRunEveryTwoWeek')
job.setDisabled(!job.isDisabled())
</code>```

Since Jenkins does not offer the functionnality its the best easy solution I could find. If you have better solution feel free to let me know.

Body:
I had the same issue, the easy work around I found was to create another job that run weekly.

This job was a simple groovy script that does the following:

import jenkins.model.*;
def job = Jenkins.instance.getJob('JobNameToRunEveryTwoWeek')
job.setDisabled(!job.isDisabled())

Since Jenkins does not offer the functionnality its the best easy solution I could find. If you have better solution feel free to let me know.


问:
What does git fetch followed by checkout FETCH_HEAD do?
What does the following command do:

```<code>git fetch <remote> <branch> && git checkout FETCH_HEAD
</code>```

I have only one local branch (master) and I execute the above command. What changes to my local repository should I expect and how can I verify (see) them?

答:
You are probably aware of what the first part of your command will do.  git fetch <remote> <some_branch> will update the local tracking branch of the branch you specify.  But this will not alter the actual local corresponding some_branch on your machine.

When you do a git fetch, Git has a special ref called FETCH_HEAD which points to the branch which was just fetched.  In this case, it would point to remote/some_branch, since this is the branch which was just fetched.  By doing

```<code>git checkout FETCH_HEAD
</code>```

you would be checking out origin/some_branch in a detached HEAD state.  This may or not may not be what you intend, but in any case, your compound command would not actually update the local some_branch.  To do that, you would need an additional git merge step, or to just do a git pull from some_branch.

Body:
What does the following command do:

git fetch <remote> <branch> && git checkout FETCH_HEAD

I have only one local branch (master) and I execute the above command. What changes to my local repository should I expect and how can I verify (see) them?

Body:
You are probably aware of what the first part of your command will do.  git fetch <remote> <some_branch> will update the local tracking branch of the branch you specify.  But this will not alter the actual local corresponding some_branch on your machine.

When you do a git fetch, Git has a special ref called FETCH_HEAD which points to the branch which was just fetched.  In this case, it would point to remote/some_branch, since this is the branch which was just fetched.  By doing

git checkout FETCH_HEAD

you would be checking out origin/some_branch in a detached HEAD state.  This may or not may not be what you intend, but in any case, your compound command would not actually update the local some_branch.  To do that, you would need an additional git merge step, or to just do a git pull from some_branch.


问:
VBA Macro - Export table data from Excel file to Word and create a section for each worksheet
I use a macro in VBA for exporting data coming from Excel into Word.

```<code>Sub ExportToWord()
    Set obj = CreateObject("Word.Application")
    obj.Visible = True
    Set newobj = obj.Documents.Add

    For Each ws In ActiveWorkbook.Sheets
        ws.UsedRange.Copy
        newobj.ActiveWindow.Selection.PasteExcelTable False, False, False
        newobj.ActiveWindow.Selection.InsertBreak Type:=7
    Next
        newobj.ActiveWindow.Selection.TypeBackspace
        newobj.ActiveWindow.Selection.TypeBackspace

    obj.Activate
    newobj.SaveAs Filename:=Application.ActiveWorkbook.Path & "\OLD\" & Split(ActiveWorkbook.Name, ".")(0)
End Sub
</code>```

All data and table layout are retrieved in Word. The Procedure will copy usedRange of each Worksheet to Word and page break by each Worksheet.

I would like to update this script by putting the name of the worksheet just before the copy/paste data for each worksheet.

Could you tell me how to do that?

After updated the code:

```<code>Sub export_workbook_to_word()
    Dim sheetName As String
    Set obj = CreateObject("Word.Application")
    obj.Visible = True
    Set newobj = obj.Documents.Add

    For Each ws In ActiveWorkbook.Sheets
        sheetName = ws.Name
        ws.UsedRange.Copy
        newobj.ActiveWindow.TypeText ws.Name
        newobj.ActiveWindow.Selection.PasteExcelTable False, False, False
        newobj.ActiveWindow.Selection.InsertBreak Type:=7

    Next
        newobj.ActiveWindow.Selection.TypeBackspace
        newobj.ActiveWindow.Selection.TypeBackspace

    obj.Activate
    newobj.SaveAs Filename:=Application.ActiveWorkbook.Path & "\" & Split(ActiveWorkbook.Name, ".")(0)

End Sub
</code>```

I obtain the error Object doesn't support this property or method on the line newobj.ActiveWindow.TypeText ws.Name

Could you please help me?

答:
Try adding this to declarations:

```<code>    Dim sheetName as String
</code>```

And this below the For Each statement

```<code>    sheetName = ws.Name
    newobj.ActiveWindow.TypeText (sheetName)
</code>```

Body:
I use a macro in VBA for exporting data coming from Excel into Word.

Sub ExportToWord()
    Set obj = CreateObject("Word.Application")
    obj.Visible = True
    Set newobj = obj.Documents.Add

    For Each ws In ActiveWorkbook.Sheets
        ws.UsedRange.Copy
        newobj.ActiveWindow.Selection.PasteExcelTable False, False, False
        newobj.ActiveWindow.Selection.InsertBreak Type:=7
    Next
        newobj.ActiveWindow.Selection.TypeBackspace
        newobj.ActiveWindow.Selection.TypeBackspace

    obj.Activate
    newobj.SaveAs Filename:=Application.ActiveWorkbook.Path & "\OLD\" & Split(ActiveWorkbook.Name, ".")(0)
End Sub

All data and table layout are retrieved in Word. The Procedure will copy usedRange of each Worksheet to Word and page break by each Worksheet.

I would like to update this script by putting the name of the worksheet just before the copy/paste data for each worksheet.

Could you tell me how to do that?

After updated the code:

Sub export_workbook_to_word()
    Dim sheetName As String
    Set obj = CreateObject("Word.Application")
    obj.Visible = True
    Set newobj = obj.Documents.Add

    For Each ws In ActiveWorkbook.Sheets
        sheetName = ws.Name
        ws.UsedRange.Copy
        newobj.ActiveWindow.TypeText ws.Name
        newobj.ActiveWindow.Selection.PasteExcelTable False, False, False
        newobj.ActiveWindow.Selection.InsertBreak Type:=7

    Next
        newobj.ActiveWindow.Selection.TypeBackspace
        newobj.ActiveWindow.Selection.TypeBackspace

    obj.Activate
    newobj.SaveAs Filename:=Application.ActiveWorkbook.Path & "\" & Split(ActiveWorkbook.Name, ".")(0)

End Sub

I obtain the error Object doesn't support this property or method on the line newobj.ActiveWindow.TypeText ws.Name

Could you please help me?

Body:
Try adding this to declarations:

    Dim sheetName as String

And this below the For Each statement

    sheetName = ws.Name
    newobj.ActiveWindow.TypeText (sheetName)


问:
ASP.NET MVC - OutputCacheAttribute - Is it disabled in debug?
Can anyone confirm whether the OutputCacheAttribute caches pages when running as Debug? Or only in Release builds?

Thanks

答: I confirm that OutputCacheAttribute caches pages when running in Debug mode.</p>

ContentLicense: CC BY-SA 2.5


问:
Calculation of duration from two dates during load data in datagridview
I have two columns which contains a start-date and end-date. I want to calculate the difference between those two.

I could do that after my grid has finished loading but is there any chance for doing that when I load my data to the grid?

My short code snippet from my load code

```<code>DataTable dt = new DataTable();
dt.Columns.Add("StartTime", typeof(DateTime));
dt.Columns.Add("EndTime", typeof(DateTime));
dt.Columns.Add("Duration", typeof(string));

foreach (string File in Files) {
    XDocument doc = XDocument.Load(MyXMLLocation + "\\" + File);
    XElement root = doc.Root;
    root.Descendants();

    string rootName = root.Name.LocalName;
    string logBookName = (string)root.Element("LogbookName");

    foreach (XElement timeSlot in root.Descendants("TimeSlot")) {
        DataRow newRow = dt.Rows.Add();

        newRow["StartTime"] = (DateTime)timeSlot.Elements().Where(x => x.Name.LocalName == "StartTime").FirstOrDefault();
        newRow["EndTime"] = (DateTime)timeSlot.Elements().Where(x => x.Name.LocalName == "EndTime").FirstOrDefault();
        newRow["Duration"] = "something";
</code>```

答:
This will give you difference of time</p>

```<code>    newRow["Duration"] = newRow["StartTime"].Subtract(newRow["EndTime"]).TotalMinutes;
</code>```

Body:
I have two columns which contains a start-date and end-date. I want to calculate the difference between those two.

I could do that after my grid has finished loading but is there any chance for doing that when I load my data to the grid?

My short code snippet from my load code

DataTable dt = new DataTable();
dt.Columns.Add("StartTime", typeof(DateTime));
dt.Columns.Add("EndTime", typeof(DateTime));
dt.Columns.Add("Duration", typeof(string));

foreach (string File in Files) {
    XDocument doc = XDocument.Load(MyXMLLocation + "\\" + File);
    XElement root = doc.Root;
    root.Descendants();

    string rootName = root.Name.LocalName;
    string logBookName = (string)root.Element("LogbookName");

    foreach (XElement timeSlot in root.Descendants("TimeSlot")) {
        DataRow newRow = dt.Rows.Add();

        newRow["StartTime"] = (DateTime)timeSlot.Elements().Where(x => x.Name.LocalName == "StartTime").FirstOrDefault();
        newRow["EndTime"] = (DateTime)timeSlot.Elements().Where(x => x.Name.LocalName == "EndTime").FirstOrDefault();
        newRow["Duration"] = "something";

Body:
This will give you difference of time

    newRow["Duration"] = newRow["StartTime"].Subtract(newRow["EndTime"]).TotalMinutes;


问:
Paper border on plotly R graph
Not sure if R's plot_ly function has this capability (i havent been able to find it), but figured I'd ask). Plot_ly does have a paper_bgcolor parameter that changes the color of the paper that the plot is on, as such:

```<code>mydf = data.frame(x = 1:5, y = 1:5)

plot_ly(mydf) %>%
  add_trace(x = ~x, y = ~x, type = 'scatter', mode = 'markers',
            marker = list(size = 24)) %>%
  layout(paper_bgcolor = 'red')
</code>```

I am not interested in changing the paper color, but rather the paper border. That is, I'd like a red box around the outer edge of the paper. Does anybody know a simple way to do this?

EDIT — I think I may have to use the grid package for this / it could be done with grid, but I'm curious first if it's possible without incorporating another package.

答:
One possibility would be to modify the CSS file used by Plotly.

Find the location of your directory storing the plotly-min.js and the CSS file

```<code>p <- plot_ly()
p$dependencies[[4]]$src$file
</code>```

Output:

1
  "/that/is/my/directory/Documents/R/win-library/3.4/plotly/htmlwidgets/lib/plotlyjs"

Go to this directory and copy plotly-htmlwidgets.css to a new file, e.g. plotly-htmlwidgets_red.css

Add the following lines to the new file

```<code>div.svg-container {
  outline:5px solid red;
}
</code>```

Tell plotly to use your new CSS file

```<code>p <- plot_ly()
p$dependencies[[4]]$stylesheet <- "plotly-htmlwidgets_red.css"
</code>```

Result

Title: Paper border on plotly R graph

Body:
Not sure if R's plot_ly function has this capability (i havent been able to find it), but figured I'd ask). Plot_ly does have a paper_bgcolor parameter that changes the color of the paper that the plot is on, as such:

mydf = data.frame(x = 1:5, y = 1:5)

plot_ly(mydf) %>%
  add_trace(x = ~x, y = ~x, type = 'scatter', mode = 'markers',
            marker = list(size = 24)) %>%
  layout(paper_bgcolor = 'red')

I am not interested in changing the paper color, but rather the paper border. That is, I'd like a red box around the outer edge of the paper. Does anybody know a simple way to do this?

EDIT — I think I may have to use the grid package for this / it could be done with grid, but I'm curious first if it's possible without incorporating another package.

Body:
One possibility would be to modify the CSS file used by Plotly.

Find the location of your directory storing the plotly-min.js and the CSS file

p <- plot_ly()
p$dependencies[[4]]$src$file

Output:

1
  "/that/is/my/directory/Documents/R/win-library/3.4/plotly/htmlwidgets/lib/plotlyjs"

Go to this directory and copy plotly-htmlwidgets.css to a new file, e.g. plotly-htmlwidgets_red.css

Add the following lines to the new file

div.svg-container {
  outline:5px solid red;
}

Tell plotly to use your new CSS file

p <- plot_ly()
p$dependencies[[4]]$stylesheet <- "plotly-htmlwidgets_red.css"

Result


问:
laravel curl not working on azure
I am connecting my two apps (laravel with python) using curl command. It is working absolutely fine on my local server without changing a single line but when it gives me following error when on azure server

POST https://myweb.com/searchJobs 500 ()

my code is

```<code>$ch = curl_init();

    //URL to send the request to

    curl_setopt($ch, CURLOPT_URL, 'http://python-scrapper-python001.azurewebsites.net/myfunction');

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));

    //We are doing a post request
    curl_setopt($ch, CURLOPT_POST, 1);

    //adding the post data to request
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);

    //Return instead of outputting directly
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $output = curl_exec($ch);
        curl_close($ch);
</code>```

is there any security protocol that I need to update on azure or what can be possible issue?

答:
Actually these lines were working fine on localhost but not on azure

```<code>$arr = "";
$arr['hello'] = '7';
</code>```

so I changed them as

```<code>$arr = [];
$arr['hello'] = '7';
</code>```

Though i don't no why azure didn't run it. If php convert it to an array on localhost than it must run on azure as well

Title: laravel curl not working on azure

Body:
I am connecting my two apps (laravel with python) using curl command. It is working absolutely fine on my local server without changing a single line but when it gives me following error when on azure server

POST https://myweb.com/searchJobs 500 ()

my code is

$ch = curl_init();

    //URL to send the request to

    curl_setopt($ch, CURLOPT_URL, 'http://python-scrapper-python001.azurewebsites.net/myfunction');

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));

    //We are doing a post request
    curl_setopt($ch, CURLOPT_POST, 1);

    //adding the post data to request
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);

    //Return instead of outputting directly
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $output = curl_exec($ch);
        curl_close($ch);

is there any security protocol that I need to update on azure or what can be possible issue?

Body:
Actually these lines were working fine on localhost but not on azure

$arr = "";
$arr['hello'] = '7';

so I changed them as

$arr = [];
$arr['hello'] = '7';

Though i don't no why azure didn't run it. If php convert it to an array on localhost than it must run on azure as well


问:
Do users have problems adopting Silverlight?
My group is thinking about switching our platform for web UI from ASP.net to Silverlight for several reasons. To be clear, these are business websites that provide a service to our users, we develop and host them ourselves.

Has anyone switched their business / intranet web site from a traditional server-based web technology such as ASP.net to Silverlight? Or have you added Silverlight to your website? If so...

Have your users complained or resisted installing Silverlight?

Have any significant number of users been unable to install Silverlight?

Have they commented on the look or responsiveness of Silverlight UI?

What other comments have they had?

In short, are my web site's users gonna freak if I start using Silverlight on my page?

If your answer is "It depends" then please give an idea of what the determining factors are.

As an aside, is there an easy way to detect how many of your users install / have already installed Silverlight?

Edit:

Thanks for the answers so far! I may be reaching, but has anyone yet had concrete experience with deploying a Silverlight app?  I was wondering if anyone had gone through this and if their users had any major issues.

答:
I would also say that if you're aiming for something available to everyone no matter what Operating System they might use. Silverlight is probably not the way to go at the moment.

If you really want something interactive, I would go the flex way. As flash is freely available on most platform. Mac/Linux/Windows and mobile devices.

And because I don't really value flash/silverlight.

I would say to do something with Ajax and javascript effects (prototype, jQuery or any other javascript lib I don't know). It should reduce the load time for users.

Switching completely to flash or silverlight might be a terrible idea...as for me, flash always make my firefox unstable...memory leak and things like that. As for silverlight, I do not have any support for it on my Os.

OwnerDisplayName: TJB

LastEditorDisplayName: TJB

OwnerDisplayName: Sybiam


问:
Generating unique number sequence for use as entity key for app engine datastore
Has anyone got any example code for creating a unique number sequence to be used as keys for an entity in a Google app engine datastore?

Would like to use sequential order numbers as the key.

答: You might want to look at How to implement "autoincrement" on Google AppEngine where you find a implementation of sequence numbers.</p>


问:
strange message from gradle (AndroidStudio).
From one second to the other I got the following error with Gradle in AndroidStudio and I have no clue what to do with it.

Error when trying to start my app:

```<code>Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_map_testApkCopy'.
   > Could not find com.android.support:appcompat-v7:27.0.1.
     Required by:
         project :app
         project :app > com.android.support:design:25.0.0
   > Could not find com.android.support:support-v4:27.0.1.
     Required by:
         project :app > com.android.support:design:25.0.0
         project :app > com.android.support:design:25.0.0 > com.android.support:transition:25.0.0
   > Could not find com.android.support:support-annotations:27.0.1.
     Required by:
         project :app > com.android.support:design:25.0.0 > com.android.support:recyclerview-v7:25.0.0
         project :app > com.android.support:design:25.0.0 > com.android.support:recyclerview-v7:25.0.0 > com.android.support:support-compat:25.0.0
   > Could not find com.android.support:support-annotations:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
   > Could not find com.android.support:support-core-utils:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
   > Could not find com.android.support:appcompat-v7:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
   > Could not find com.android.support:cardview-v7:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
   > Could not find com.android.support:customtabs:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
   > Could not find com.android.support:support-v4:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
</code>```

build.gradle : (Mobile: app) (Did not changed since month. Compared with repo and no change)

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

android {
    signingConfigs {
        sapps {
            keyAlias 'keyalias'
            keyPassword 'xxxxxx'
            storeFile file('C:/eclipse/keystore/mykeystore')
            storePassword 'xxxxxx'
        }
    }
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "appid"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 179
        versionName "2.54"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        resValue "string", "appID", "wgd"
        manifestPlaceholders = [iconpath: "@drawable/icon", versionCode:"161", versionName:"2.37"]

    }
    buildTypes {
        demo {
            buildConfigField "String", "appID", "\"WGD\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.sapps
            resValue "string", "app_name", "Chronica"
            manifestPlaceholders = [iconpath: "@drawable/icon", facebookid:"@string/facebook_app_id_demo"]
            applicationIdSuffix '.chronicbrowser'
        }
        demo_test {
            buildConfigField "String", "appID", "\"WGD_TEST\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.sapps
            debuggable true

            resValue "string", "app_name", "Chronica Test"
            manifestPlaceholders = [iconpath: "@drawable/icon", facebookid:"@string/facebook_app_id_demo"]
            applicationIdSuffix '.chronicbrowser_wgd_test'
        }
        timeline {

            buildConfigField "String", "appID", "\"WG\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.sapps
            resValue "string", "app_name", "WorldHistory"
            applicationIdSuffix '.chronicbrowser_wg_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_timeline", facebookid:"@string/facebook_app_id_timeline"]
        }
        timeline_test {
            buildConfigField "String", "appID", "\"WG_TEST\""
            minifyEnabled false
            debuggable true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldHistory Test"
            applicationIdSuffix '.chronicbrowser_wg_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_timeline_test", facebookid:"@string/facebook_app_id_timeline"]
            signingConfig signingConfigs.sapps
        }
        map {
            buildConfigField "String", "appID", "\"WG_MAPS\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldHistory Atlas"
            applicationIdSuffix '.chronicbrowser_maps_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_maps", facebookid:"@string/facebook_app_id_maps"]
            signingConfig signingConfigs.sapps
        }
        map_test {
            buildConfigField "String", "appID", "\"WG_MAPS_TEST\""
            //resValue "string", "RES_appID", "wgd"
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldHistory Atlas Test"
            applicationIdSuffix '.chronicbrowser_maps_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_maps_test", facebookid:"@string/facebook_app_id_maps"]
            signingConfig signingConfigs.sapps

        }
        worldwarII {
            buildConfigField "String", "appID", "\"WW2\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldWar II"
            applicationIdSuffix '.chronicbrowser_ww2_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_ww2", facebookid:"@string/facebook_app_id_ww2"]
            signingConfig signingConfigs.sapps

        }
        worldwarII_test {
            buildConfigField "String", "appID", "\"WW2_TEST\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldWar II Test"
            applicationIdSuffix '.chronicbrowser_ww2_en_test'
            manifestPlaceholders = [iconpath: "@drawable/icon_ww2", facebookid:"@string/facebook_app_id_ww2"]
            signingConfig signingConfigs.sapps
        }
    }
    compileOptions.encoding = 'ISO-8859-1'
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:design:25.0.0'
    testCompile 'junit:junit:4.12'
    compile files('libs/lvl.jar')
    compile files('libs/google-play-services.jar')
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile files('libs/GoogleConversionTrackingSdk-2.2.4.jar')
}

repositories {
    mavenCentral()
}
</code>```

Can someone help me ?

答:
It is probably due of compile 'com.facebook.android:facebook-android-sdk:[4,5)'. Change it with

```<code>compile('com.facebook.android:facebook-android-sdk:[4,5)') {
         exclude group: 'com.android.support'
}
</code>```

it is the only one that has an open version.

Body:
From one second to the other I got the following error with Gradle in AndroidStudio and I have no clue what to do with it.

Error when trying to start my app:

Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_map_testApkCopy'.
   > Could not find com.android.support:appcompat-v7:27.0.1.
     Required by:
         project :app
         project :app > com.android.support:design:25.0.0
   > Could not find com.android.support:support-v4:27.0.1.
     Required by:
         project :app > com.android.support:design:25.0.0
         project :app > com.android.support:design:25.0.0 > com.android.support:transition:25.0.0
   > Could not find com.android.support:support-annotations:27.0.1.
     Required by:
         project :app > com.android.support:design:25.0.0 > com.android.support:recyclerview-v7:25.0.0
         project :app > com.android.support:design:25.0.0 > com.android.support:recyclerview-v7:25.0.0 > com.android.support:support-compat:25.0.0
   > Could not find com.android.support:support-annotations:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
   > Could not find com.android.support:support-core-utils:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
   > Could not find com.android.support:appcompat-v7:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
   > Could not find com.android.support:cardview-v7:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
   > Could not find com.android.support:customtabs:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
   > Could not find com.android.support:support-v4:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0

build.gradle : (Mobile: app) (Did not changed since month. Compared with repo and no change)

apply plugin: 'com.android.application'

android {
    signingConfigs {
        sapps {
            keyAlias 'keyalias'
            keyPassword 'xxxxxx'
            storeFile file('C:/eclipse/keystore/mykeystore')
            storePassword 'xxxxxx'
        }
    }
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "appid"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 179
        versionName "2.54"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        resValue "string", "appID", "wgd"
        manifestPlaceholders = [iconpath: "@drawable/icon", versionCode:"161", versionName:"2.37"]

    }
    buildTypes {
        demo {
            buildConfigField "String", "appID", "\"WGD\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.sapps
            resValue "string", "app_name", "Chronica"
            manifestPlaceholders = [iconpath: "@drawable/icon", facebookid:"@string/facebook_app_id_demo"]
            applicationIdSuffix '.chronicbrowser'
        }
        demo_test {
            buildConfigField "String", "appID", "\"WGD_TEST\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.sapps
            debuggable true

            resValue "string", "app_name", "Chronica Test"
            manifestPlaceholders = [iconpath: "@drawable/icon", facebookid:"@string/facebook_app_id_demo"]
            applicationIdSuffix '.chronicbrowser_wgd_test'
        }
        timeline {

            buildConfigField "String", "appID", "\"WG\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.sapps
            resValue "string", "app_name", "WorldHistory"
            applicationIdSuffix '.chronicbrowser_wg_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_timeline", facebookid:"@string/facebook_app_id_timeline"]
        }
        timeline_test {
            buildConfigField "String", "appID", "\"WG_TEST\""
            minifyEnabled false
            debuggable true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldHistory Test"
            applicationIdSuffix '.chronicbrowser_wg_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_timeline_test", facebookid:"@string/facebook_app_id_timeline"]
            signingConfig signingConfigs.sapps
        }
        map {
            buildConfigField "String", "appID", "\"WG_MAPS\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldHistory Atlas"
            applicationIdSuffix '.chronicbrowser_maps_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_maps", facebookid:"@string/facebook_app_id_maps"]
            signingConfig signingConfigs.sapps
        }
        map_test {
            buildConfigField "String", "appID", "\"WG_MAPS_TEST\""
            //resValue "string", "RES_appID", "wgd"
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldHistory Atlas Test"
            applicationIdSuffix '.chronicbrowser_maps_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_maps_test", facebookid:"@string/facebook_app_id_maps"]
            signingConfig signingConfigs.sapps

        }
        worldwarII {
            buildConfigField "String", "appID", "\"WW2\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldWar II"
            applicationIdSuffix '.chronicbrowser_ww2_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_ww2", facebookid:"@string/facebook_app_id_ww2"]
            signingConfig signingConfigs.sapps

        }
        worldwarII_test {
            buildConfigField "String", "appID", "\"WW2_TEST\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldWar II Test"
            applicationIdSuffix '.chronicbrowser_ww2_en_test'
            manifestPlaceholders = [iconpath: "@drawable/icon_ww2", facebookid:"@string/facebook_app_id_ww2"]
            signingConfig signingConfigs.sapps
        }
    }
    compileOptions.encoding = 'ISO-8859-1'
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:design:25.0.0'
    testCompile 'junit:junit:4.12'
    compile files('libs/lvl.jar')
    compile files('libs/google-play-services.jar')
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile files('libs/GoogleConversionTrackingSdk-2.2.4.jar')
}

repositories {
    mavenCentral()
}

Can someone help me ?

Body:
It is probably due of compile 'com.facebook.android:facebook-android-sdk:[4,5)'. Change it with

compile('com.facebook.android:facebook-android-sdk:[4,5)') {
         exclude group: 'com.android.support'
}

it is the only one that has an open version.


问:
How to implement correctly own javascript library, angular 4
I want to implement my own javascript library in an andular4-cli project. Because its my own library, its not possible to include the library with npm.

tsconfig.json

```<code>{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "allowJs": true,
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "baseUrl": "",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}
</code>```

I implemented the library in angular.cli.json

```<code>"assets/myownlib.js"
</code>```

The component i want to use the library:

```<code>import { Component, OnInit } from '@angular/core';
import {DataService} from './tempdatagia.service';
import {MyLib} from '../../assets/myownlib';

@Component({
  selector: 'app-paho',
  templateUrl: './paho.component.html',
  styleUrls: ['./paho.component.css']
})
export class PahoComponent {
  // Create a client instance
  client: any;

  constructor(private tempdata: DataService) {

    this.client = new MyLib.MQTT.Client('wpsdemo.gia.rwth-aachen.de', 8080,  'Steffen');

    this.onMessage();
    this.onConnectionLost();
    // connect the client
    this.client.connect({onSuccess: this.onConnected.bind(this)});
  }
 .
 .
 .
}
</code>```

ERROR

in line import {MyLib} from '../../assets/myownlib';:

 "allow js is not set"

"cannot find namespace 'MyLib'."

答:
I want to answer my question, how to generally export his own JavaScript lybrary in an angular 4 project. This is maybe only one solution of hundreds to include his own JavaScript library, but in my opinion this is the easiest and fastest one.

Generally, if you want to use an JavaScript library in angular 4, you will mostly need a yourlib.d.ts file. There are some posibilities to do it without, but for me none was working!

So you have to create your yourlib.d.ts file to use it to provide typescript type information about an API that's written in JavaScript.

For more information about ".d.ts"

To create your ".d.ts" File you have to define all your functions and method from the JavaScript library in your ".d.ts" File.
Just search them by hand and declare them in your ".d.ts" File.

Your declaration should be look like (excerpt from mine):

```<code>export declare namespace MyLib {
    export namespace MQTT {
        export class Client {
            geosubscribe(topicfilter: string, temporalfilter: string, spatialfilter: string, spatialrelation: string, subscribeOptions: Object): void;
            geounsubscribe(topicfilter: string, temporalfilter: string, spatialfilter: string, subscribeOptions: Object): void;
            send(message: Message): void;
            geosend(message: Message): void;

     export class Message {
            constructor(payload: any);
            payloadString: string;
            geometry: string;
            timestamp: string;
        }
export class WireMessage {
            encode(): ArrayBuffer;
            decodeMessage(input: ArrayBuffer, pos: number): Array<any>;
            writeUint16(input: number, buffer: ArrayBuffer, offset: number): number;
            writeString(input: string, utf8Length: number, buffer: ArrayBuffer, offset: number): number;
            readUint16(buffer: ArrayBuffer, offset: number): number;
            encodeMBI(num: number): Array<any>;

        }
    }
}
</code>```

Body:
I want to implement my own javascript library in an andular4-cli project. Because its my own library, its not possible to include the library with npm.

tsconfig.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "allowJs": true,
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "baseUrl": "",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

I implemented the library in angular.cli.json

"assets/myownlib.js"

The component i want to use the library:

import { Component, OnInit } from '@angular/core';
import {DataService} from './tempdatagia.service';
import {MyLib} from '../../assets/myownlib';

@Component({
  selector: 'app-paho',
  templateUrl: './paho.component.html',
  styleUrls: ['./paho.component.css']
})
export class PahoComponent {
  // Create a client instance
  client: any;

  constructor(private tempdata: DataService) {

    this.client = new MyLib.MQTT.Client('wpsdemo.gia.rwth-aachen.de', 8080,  'Steffen');

    this.onMessage();
    this.onConnectionLost();
    // connect the client
    this.client.connect({onSuccess: this.onConnected.bind(this)});
  }
 .
 .
 .
}

ERROR

in line import {MyLib} from '../../assets/myownlib';:

 "allow js is not set"

"cannot find namespace 'MyLib'."

Body:
I want to answer my question, how to generally export his own JavaScript lybrary in an angular 4 project. This is maybe only one solution of hundreds to include his own JavaScript library, but in my opinion this is the easiest and fastest one.

Generally, if you want to use an JavaScript library in angular 4, you will mostly need a yourlib.d.ts file. There are some posibilities to do it without, but for me none was working!

So you have to create your yourlib.d.ts file to use it to provide typescript type information about an API that's written in JavaScript.

For more information about ".d.ts"

To create your ".d.ts" File you have to define all your functions and method from the JavaScript library in your ".d.ts" File.
Just search them by hand and declare them in your ".d.ts" File.

Your declaration should be look like (excerpt from mine):

export declare namespace MyLib {
    export namespace MQTT {
        export class Client {
            geosubscribe(topicfilter: string, temporalfilter: string, spatialfilter: string, spatialrelation: string, subscribeOptions: Object): void;
            geounsubscribe(topicfilter: string, temporalfilter: string, spatialfilter: string, subscribeOptions: Object): void;
            send(message: Message): void;
            geosend(message: Message): void;

     export class Message {
            constructor(payload: any);
            payloadString: string;
            geometry: string;
            timestamp: string;
        }
export class WireMessage {
            encode(): ArrayBuffer;
            decodeMessage(input: ArrayBuffer, pos: number): Array<any>;
            writeUint16(input: number, buffer: ArrayBuffer, offset: number): number;
            writeString(input: string, utf8Length: number, buffer: ArrayBuffer, offset: number): number;
            readUint16(buffer: ArrayBuffer, offset: number): number;
            encodeMBI(num: number): Array<any>;

        }
    }
}


答:
You are using a lower version of the support library than the one required by the other components. try</p>

```<code>  compile 'com.android.support:appcompat-v7:27.0.1'
  compile 'com.android.support:design:27.0.1'
</code>```

Title: strange message from gradle (AndroidStudio).

Body:
You are using a lower version of the support library than the one required by the other components. try

  compile 'com.android.support:appcompat-v7:27.0.1'
  compile 'com.android.support:design:27.0.1'


问:
I don't have build files for webpack
I have installed webpack globally with npm install webpack -g.

I have also installed babel using npm install --save-dev babel-loader babel-core.

Any time I type webpack to get build files, I get this:

C:\Sites\Learn-React>webpack

Hash: 5d44ddfc6932f448e682

Version: webpack 2.2.1
Time: 71ms

ERROR in Entry module not found: Error: Can't resolve 'babel' in 'C:\Sites\Learn-React'
BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.
You need to specify 'babel-loader' instead of 'babel'.

Any idea on how this can be solved?

Thanks.

答:
Change your module loaders and make sure to use the suffix '-loader'.

So for e.g:

```<code>const path = require('path');

module.exports = {
 entry : './javascript/src/app.js',
 output: {
    path    : path.resolve(__dirname, 'javascript/dist'),
    filename: 'build.js'
 },
 module: {
    loaders: [
        {
            test   : /\.js$/,
            // Wrong
            // loader : 'babel',

            //Correct
            loader : 'babel-loader',
            exclude: /node_modules/
        }
    ]
  }
};
</code>```

Title: I don't have build files for webpack

Body:
Change your module loaders and make sure to use the suffix '-loader'.

So for e.g:

const path = require('path');

module.exports = {
 entry : './javascript/src/app.js',
 output: {
    path    : path.resolve(__dirname, 'javascript/dist'),
    filename: 'build.js'
 },
 module: {
    loaders: [
        {
            test   : /\.js$/,
            // Wrong
            // loader : 'babel',

            //Correct
            loader : 'babel-loader',
            exclude: /node_modules/
        }
    ]
  }
};


问:
How to set condition on UI route in angularjs
I'm new in angular and working on UI routing. My issue is how to set condition when user route to new state. What i want is, when user submit the form it should authenticate form data through Mobile OTP popup before going to next state. In my code everything works fine till form but when user submit form, otp popup open but its get hide when its route to new state. So i think i need to put some condition when user go to next state.
Here are my codes

//APP.JS FILE

```<code>.state('main.step4', {
        url: '/step2/step3/step4',
        templateUrl: 'pages/step4.html'
        }
</code>```

//Controller.js

```<code>$scope.getStep2Form = function($index, selectCarList) {
            $scope.selectCar.step2Form = selectCarList;
            $scope.step2Data = $scope.selectCar;
            console.log($scope.step2Data);
        }
        $scope.getStep3Form = function(step3FormData) {
            $scope.selectCar.step3Data = step3FormData;
            console.log($scope.selectCar);

        }
        $scope.showotp=function(){
            open_modal_menu()
        }
</code>```

//CUSTOM.js

```<code>function open_modal_menu() {
            $('.modal-menu').toggleClass('active-modal-menu');
            $('.modal-menu-overlay').addClass('active-overlay');
        }
</code>```

//SERVICES.js

```<code>angular.module('carmobApp.services', [])

.factory('carListDataFactry', function($http) {

var carListData = [];
return {
  all: function() {
    return $http.get("scripts/content.json").then(function(response) {
      carListData = response.data;
      //console.log(teamListData);
      return carListData;
    });

  },
  get: function(selectCarId) {
    for (var i = 0; i < carListData.length; i++) {
      if (carListData[i].id === parseInt(selectCarId)) {
        //console.log(carListData[i]);
        return carListData[i];
      }
    }
    return null;
  }

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

//HTML

```<code><a ui-sref="main.step4" class="button button-green button-full button-icon submitBtn" ng-model="selectCar.step3Data" ng-click="showotp(); getStep3Form(step3FormData)" ng-disabled="selectCarform.$invalid">
    <i class="ion-arrow-right-c" style="color:#fff;"></i> PROCEED NEXT
</a>
</code>```

答:
You can use something like this

```<code>app.run(function($transitions) {
  $transitions.onSuccess({}, (transition) => {
  console.log(transition.to())
  console.log(transition.from())
 });
})
</code>```

and it fire when the route was changed

or if problem with rendering

In this case, with the opening popup window on-click you need to send as parameters $event. And inside function

```<code>$event.preventDefault()
</code>```

it`s prevent rout changing in URL.

and on the last step add something like

```<code>$state.go('state name')
</code>```

Body:
I'm new in angular and working on UI routing. My issue is how to set condition when user route to new state. What i want is, when user submit the form it should authenticate form data through Mobile OTP popup before going to next state. In my code everything works fine till form but when user submit form, otp popup open but its get hide when its route to new state. So i think i need to put some condition when user go to next state.
Here are my codes

//APP.JS FILE

.state('main.step4', {
        url: '/step2/step3/step4',
        templateUrl: 'pages/step4.html'
        }

//Controller.js

$scope.getStep2Form = function($index, selectCarList) {
            $scope.selectCar.step2Form = selectCarList;
            $scope.step2Data = $scope.selectCar;
            console.log($scope.step2Data);
        }
        $scope.getStep3Form = function(step3FormData) {
            $scope.selectCar.step3Data = step3FormData;
            console.log($scope.selectCar);

        }
        $scope.showotp=function(){
            open_modal_menu()
        }

//CUSTOM.js

function open_modal_menu() {
            $('.modal-menu').toggleClass('active-modal-menu');
            $('.modal-menu-overlay').addClass('active-overlay');
        }

//SERVICES.js

angular.module('carmobApp.services', [])

.factory('carListDataFactry', function($http) {

var carListData = [];
return {
  all: function() {
    return $http.get("scripts/content.json").then(function(response) {
      carListData = response.data;
      //console.log(teamListData);
      return carListData;
    });

  },
  get: function(selectCarId) {
    for (var i = 0; i < carListData.length; i++) {
      if (carListData[i].id === parseInt(selectCarId)) {
        //console.log(carListData[i]);
        return carListData[i];
      }
    }
    return null;
  }

};
});

//HTML

     PROCEED NEXT

Body:
You can use something like this

app.run(function($transitions) {
  $transitions.onSuccess({}, (transition) => {
  console.log(transition.to())
  console.log(transition.from())
 });
})

and it fire when the route was changed

or if problem with rendering

In this case, with the opening popup window on-click you need to send as parameters $event. And inside function

$event.preventDefault()

it`s prevent rout changing in URL.

and on the last step add something like

$state.go('state name')


问:
How can i pass data from django template to angular 4?
I am having angular 4 application integrated with django. Angular 4 is just for showing some data in django template and i am having some RESTful api in django.I have used webpack to compile .ts files to js and included in django templates.I am getting the angular content in django templates and it works fine.

I am having angular component code

```<code>import { Component,OnInit } from '@angular/core';
import {Http, Response} from '@angular/http';
@Component({selector: 'my-component',
            template: '<ul>
                       <li *ngFor="let res in results">
                        {{res}}
                       </li></ul>'
})
export class MyComponent {
results: {};
constructor(private http: Http) {

}
app_func(){
    this.http.get('http://someurl/id/test.json').subscribe( res => {
        this.results = res.json();
    })
}
ngOnInit(): void {
this.app_func();
}
</code>```

And django template

```<code>{% block bundles %}
    {% render_bundle 'main' %}
{% endblock bundles %}

{% block breadcrumbs %}
{{ block.super }}
{% breadcrumb test.name 'detail' test.id %}
{% endblock breadcrumbs %}

{% block content %}
<div class="row">
   <div class="col-md-12 col-md-offset-0">
    <div class="test" id="results">
        <my-component>Loading...<my-component>
    </div>
   </div>
 </div>
{% endblock content %}
</code>```

I am getting the angular templates when i am using the static url (i.e exact url) in angular component.

But i need to pass the {{test.id}} (which is from django views) value to angular component and use this id in url to get json,because its dynamic url not static.How can i do that any ideas??

答:
In angular component file you can make the method as public and use it in the js file or inside script tag in html to pass the data or value.Call the function after the compiled js bundle is loaded.

Angular component code

```<code>import { Component,OnInit,NgZone,OnDestroy } from '@angular/core';
import {Http, Response} from '@angular/http';
@Component({selector: 'my-component',
        template: '<ul>
                   <li *ngFor="let res in results">
                    {{res}}
                   </li></ul>'
})
export class MyComponent {
results: {};
constructor(private http: Http,private zone:NgZone) {}
app_func(test_id){
this.zone.run(() =>
    this.http.get('http://someurl/'+test_id+'/test.json').subscribe( res =>
    {
        this.results = res.json();
    })
);
}
ngOnInit(): void {
(<any>window).app_func = this.app_func.bind(this);
}
ngOnDestroy() {
(<any>window).app_func = null;
}
</code>```

And django template

```<code>{% block bundles %}
{% render_bundle 'main' %}
{% endblock bundles %}

{% block breadcrumbs %}
{{ block.super }}
{% breadcrumb test.name 'detail' test.id %}
{% endblock breadcrumbs %}

{% block scripts %}
<script>
app_func(test_id='{{test.id}}');
</script>
{% endblock scripts %}

{% block content %}
<div class="row">
<div class="col-md-12 col-md-offset-0">
<div class="test" id="results">
    <my-component>Loading...<my-component>
</div>
</div>
</div>
{% endblock content %}
</code>```

Body:
I am having angular 4 application integrated with django. Angular 4 is just for showing some data in django template and i am having some RESTful api in django.I have used webpack to compile .ts files to js and included in django templates.I am getting the angular content in django templates and it works fine.

I am having angular component code

import { Component,OnInit } from '@angular/core';
import {Http, Response} from '@angular/http';
@Component({selector: 'my-component',
            template: '

                        {{res}}

'
})
export class MyComponent {
results: {};
constructor(private http: Http) {

}
app_func(){
    this.http.get('http://someurl/id/test.json').subscribe( res => {
        this.results = res.json();
    })
}
ngOnInit(): void {
this.app_func();
}

And django template

{% block bundles %}
    {% render_bundle 'main' %}
{% endblock bundles %}

{% block breadcrumbs %}
{{ block.super }}
{% breadcrumb test.name 'detail' test.id %}
{% endblock breadcrumbs %}

{% block content %}

        <my-component>Loading...<my-component>

{% endblock content %}

I am getting the angular templates when i am using the static url (i.e exact url) in angular component.

But i need to pass the {{test.id}} (which is from django views) value to angular component and use this id in url to get json,because its dynamic url not static.How can i do that any ideas??

Body:
In angular component file you can make the method as public and use it in the js file or inside script tag in html to pass the data or value.Call the function after the compiled js bundle is loaded.

Angular component code

import { Component,OnInit,NgZone,OnDestroy } from '@angular/core';
import {Http, Response} from '@angular/http';
@Component({selector: 'my-component',
        template: '<ul>
                   <li *ngFor="let res in results">
                    {{res}}
                   </li></ul>'
})
export class MyComponent {
results: {};
constructor(private http: Http,private zone:NgZone) {}
app_func(test_id){
this.zone.run(() =>
    this.http.get('http://someurl/'+test_id+'/test.json').subscribe( res =>
    {
        this.results = res.json();
    })
);
}
ngOnInit(): void {
(<any>window).app_func = this.app_func.bind(this);
}
ngOnDestroy() {
(<any>window).app_func = null;
}

And django template

{% block bundles %}
{% render_bundle 'main' %}
{% endblock bundles %}

{% block breadcrumbs %}
{{ block.super }}
{% breadcrumb test.name 'detail' test.id %}
{% endblock breadcrumbs %}

{% block scripts %}
<script>
app_func(test_id='{{test.id}}');
</script>
{% endblock scripts %}

{% block content %}
<div class="row">
<div class="col-md-12 col-md-offset-0">
<div class="test" id="results">
    <my-component>Loading...<my-component>
</div>
</div>
</div>
{% endblock content %}


问:
How to hide alt text using CSS when the image is not present?
Is it possible to hide the alt text using CSS in all the browsers,

I tried with color:transparent, it is working in all browsers except IE.

Is it possible to do it in IE using CSS?. Thanks in advance for any help.

答:
This worked:

img {
  color: rgba(0, 0, 0, 0) !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="example.jpg" alt="text you don't want to show for those who can see, but make it visible for screen readers" /></code>```

transparent neither worked for me.

Body:
This worked:

img {
  color: rgba(0, 0, 0, 0) !important;
}

<img src="example.jpg" alt="text you don't want to show for those who can see, but make it visible for screen readers" />

transparent neither worked for me.

ContentLicense: CC BY-SA 4.0


问:
wicked pdf doesnt find my assets in production
I have a problem with my CSS of wicked pdf
Everything work in local but it not find the pdf.css in production

```<code>ActionView::Template::Error (The asset "components/pdf.css" is not present in the asset pipeline.):
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<%= wicked_pdf_stylesheet_link_tag 'components/pdf.css' %>
 </head>
<body>
<%= yield %>
</code>```

My pdf.html.erb

```<code><!doctype html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    <%= wicked_pdf_stylesheet_link_tag 'components/pdf' %>
  </head>
  <body>
      <%= yield %>
  </body>
</html>
</code>```

my components/pdf.css

```<code>.document-pdf {
  background-image: asset-data-url("fond.png");
  background-size: 23cm 13cm;
  background-color: white;
  background-repeat: no-repeat;
  background-position: 50% 70%;
  font-family: "Helvetica Neue", Helvetica;
}
</code>```

答:
Have you added pdf.css to precompiled assets in initializers/assets.rb?

```<code>Rails.application.config.assets.precompile += ['pdf.css']
</code>```

Body:
I have a problem with my CSS of wicked pdf
Everything work in local but it not find the pdf.css in production

ActionView::Template::Error (The asset "components/pdf.css" is not present in the asset pipeline.):

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<%= wicked_pdf_stylesheet_link_tag 'components/pdf.css' %>

<%= yield %>

My pdf.html.erb

<!doctype html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    <%= wicked_pdf_stylesheet_link_tag 'components/pdf' %>

      <%= yield %>

my components/pdf.css

.document-pdf {
  background-image: asset-data-url("fond.png");
  background-size: 23cm 13cm;
  background-color: white;
  background-repeat: no-repeat;
  background-position: 50% 70%;
  font-family: "Helvetica Neue", Helvetica;
}

Body:
Have you added pdf.css to precompiled assets in initializers/assets.rb?

Rails.application.config.assets.precompile += ['pdf.css']


问:
Retrieving the IP geo location
I have two .CSV files, one including IP addresses :

76.83.179.64

76.83.179.64

187.42.62.209

89.142.219.5

and the other includes IP ranges and country names as follow:

```<code> ip_from|  ip_to|  country_name|

|16777216|16777471|Australia|
</code>```

What I have done so far is as follow:

load the data : ip_from, ip_to and country name

```<code>val rdd1 = sqlContext.read.format("csv").option("inferSchema",
"true").load("/FileStore/tables/locations.CSV")
val df2 = rdd1.toDF()
</code>```

load the data and converts from IP to Long

```<code>val rdd2 = sc.textFile("/FileStore/tables/ipaddress.csv")
def ipToLong(ipAddress: String): Long = {
ipAddress.split("\\.").reverse.zipWithIndex
.map(a=>a._1.toInt*math.pow(256,a._2).toLong).sum
}
val df1 = rdd2.map(x=>ipToLong(x)).toDF()
</code>```

Now, what user defined function should I write to join both DFs(or look up) and retrieve the country name according the ip address?

Title: Retrieving the IP geo location

Body:
I have two .CSV files, one including IP addresses :

76.83.179.64

76.83.179.64

187.42.62.209

89.142.219.5

and the other includes IP ranges and country names as follow:

 ip_from|  ip_to|  country_name|

|16777216|16777471|Australia|

What I have done so far is as follow:

load the data : ip_from, ip_to and country name

val rdd1 = sqlContext.read.format("csv").option("inferSchema",
"true").load("/FileStore/tables/locations.CSV")
val df2 = rdd1.toDF()

load the data and converts from IP to Long

val rdd2 = sc.textFile("/FileStore/tables/ipaddress.csv")
def ipToLong(ipAddress: String): Long = {
ipAddress.split("\\.").reverse.zipWithIndex
.map(a=>a._1.toInt*math.pow(256,a._2).toLong).sum
}
val df1 = rdd2.map(x=>ipToLong(x)).toDF()

Now, what user defined function should I write to join both DFs(or look up) and retrieve the country name according the ip address?

Body:
You can use left_outer join along with a UDF that does the ip-to-long conversion like in the following example:

val dfIP = Seq(
  ("76.83.179.64"),
  ("76.83.179.64"),
  ("187.42.62.209"),
  ("89.142.219.5")
).toDF("ip")

val dfRange = Seq(
  (1000000000L, 1500000000L, "Country A"),
  (1500000000L, 3000000000L, "Country B"),
  (3000000000L, 4000000000L, "Country C")
).toDF("ip_from", "ip_to", "country_name")

def ipToLong = udf(
  (ip: String) =>
    ip.split("\\.").reverse.zipWithIndex.map(
      a => a._1.toInt * math.pow(256,a._2).toLong
    ).sum
)

val dfJoined = dfIP.join(
  dfIPRange,
  ipToLong($"ip") >= $"ip_from" && ipToLong($"ip") < $"ip_to",
  "left_outer"
)

dfJoined.show
+-------------+----------+----------+------------+
|           ip|   ip_from|     ip_to|country_name|
+-------------+----------+----------+------------+
| 76.83.179.64|1000000000|1500000000|   Country A|
| 76.83.179.64|1000000000|1500000000|   Country A|
|187.42.62.209|3000000000|4000000000|   Country C|
| 89.142.219.5|1500000000|3000000000|   Country B|
+-------------+----------+----------+------------+


问:
Python spyder: changing a function in another file takes no effect
Using spyder 3.2.4 with python.

When I call i function (in another file) lets call it my_func() from my main script, it uses the "old version" of that function. Clarification:

If i change my_func and save that file, the new version of the function is used if called from my main script, BUT only if I run the entire main script.

If i just run the lines with my_func (using run cell or run selected lines) the OLD version of my_func (before the changes was mad) is used.

I though my_func had to be "reimported" (from myOtherFile import my_func), so I try to run those lines as well, but the old version of the function (not changed) is still used.

Did I misunderstand something or is this a really, really serious bug? If i close down spyder and restart it it works (it uses the new version of the function) but that's an unacceptable solution.

答:
(Spyder maintainer here) This is not a bug, it's the way Python works. However, the normal behavior can be improved by making our IPython consoles to load the %autoreload IPython magic. With that change, after saving a file you'll immediately get the code on it reloaded in your console.

We'll do this in our 3.2.5 version (to be released on December 2017).


问:
How to sort strings by a different value
I've tried looking for an existing question but wasn't sure how to phrase this and this retrieved no results anywhere :(

Anyway, I have a class of "Order Items" that has different properties. These order items are for clothing, so they will have a size (string).

Because I am OCD about these sorts of things, I would like to have the elements sorted not by the sizes as alphanumeric values, but by the sizes in a custom order.

I would also like to not have this custom order hard-coded if possible.

To break it down, if I have a list of these order items with a size in each one, like so:

```<code>2XL
S
5XL
M
</code>```

With alphanumeric sorting it would be in this order:

```<code>2XL
5XL
M
S
</code>```

But I would like to sort this list into this order (from smallest size to largest):

```<code>S
M
2XL
5XL
</code>```

The only way I can think of to do this is to have a hard-coded array of the sizes and to sort by their index, then when I need to grab the size value I can grab the size order array[i] value. But, as I said, I would prefer this order not to be hard-coded.

The reason I would like the order to be dynamic is the order items are loaded from files on the hard disk at runtime, and also added/edited/deleted by the user at run-time, and they may contain a size that I haven't hard-coded, for example I could hard code all the way from 10XS to 10XL but if someone adds the size "110cm" (aka a Medium), it will turn up somewhere in the order that I don't want it to, assuming the program doesn't crash and burn.

I can't quite wrap my head around how to do this.

答:
I implemented TShirtSizeComparer with base class Comparer<object>. Of course you have to adjust it to the sizes and objects you have available:

```<code>public class TShirtSizeComparer : Comparer<object>
{
    // Compares TShirtSizes and orders them by size
    public override int Compare(object x, object y)
    {
        var _sizesInOrder = new List<string> { "None", "XS", "S", "M", "L", "XL", "XXL", "XXXL", "110 cl", "120 cl", "130 cl", "140 cl", "150 cl" };
        var indexX = -9999;
        var indexY = -9999;
        if (x is TShirt)
        {
            indexX = _sizesInOrder.IndexOf(((TShirt)x).Size);
            indexY = _sizesInOrder.IndexOf(((TShirt)y).Size);
        }
        else if (x is TShirtListViewModel)
        {
            indexX = _sizesInOrder.IndexOf(((TShirtListViewModel)x).Size);
            indexY = _sizesInOrder.IndexOf(((TShirtListViewModel)y).Size);
        }
        else if (x is MySelectItem)
        {
            indexX = _sizesInOrder.IndexOf(((MySelectItem)x).Value);
            indexY = _sizesInOrder.IndexOf(((MySelectItem)y).Value);
        }
        if (indexX > -1 && indexY > -1)
        {
            return indexX.CompareTo(indexY);
        }
        else if (indexX > -1)
        {
            return -1;
        }
        else if (indexY > -1)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
}
</code>```

To use it you just have a List or whatever your object is and do:

```<code>tshirtList.Sort(new TShirtSizeComparer());
</code>```

The order you have "hard-coded" is prioritized and the rest is put to the back.

I'm sure it can be done a bit smarter and more generalized to avoid hard-coding it all. You could e.g. look for sizes ending with an "S" and then check how many X's (e.g. XXS) or the number before X (e.g. 2XS) and sort by that, and then repeat for "L" and perhaps other "main sizes".

Body:
I've tried looking for an existing question but wasn't sure how to phrase this and this retrieved no results anywhere :(

Anyway, I have a class of "Order Items" that has different properties. These order items are for clothing, so they will have a size (string).

Because I am OCD about these sorts of things, I would like to have the elements sorted not by the sizes as alphanumeric values, but by the sizes in a custom order.

I would also like to not have this custom order hard-coded if possible.

To break it down, if I have a list of these order items with a size in each one, like so:

2XL
S
5XL
M

With alphanumeric sorting it would be in this order:

2XL
5XL
M
S

But I would like to sort this list into this order (from smallest size to largest):

S
M
2XL
5XL

The only way I can think of to do this is to have a hard-coded array of the sizes and to sort by their index, then when I need to grab the size value I can grab the size order array[i] value. But, as I said, I would prefer this order not to be hard-coded.

The reason I would like the order to be dynamic is the order items are loaded from files on the hard disk at runtime, and also added/edited/deleted by the user at run-time, and they may contain a size that I haven't hard-coded, for example I could hard code all the way from 10XS to 10XL but if someone adds the size "110cm" (aka a Medium), it will turn up somewhere in the order that I don't want it to, assuming the program doesn't crash and burn.

I can't quite wrap my head around how to do this.

Body:
I implemented TShirtSizeComparer with base class Comparer<object>. Of course you have to adjust it to the sizes and objects you have available:

public class TShirtSizeComparer : Comparer<object>
{
    // Compares TShirtSizes and orders them by size
    public override int Compare(object x, object y)
    {
        var _sizesInOrder = new List<string> { "None", "XS", "S", "M", "L", "XL", "XXL", "XXXL", "110 cl", "120 cl", "130 cl", "140 cl", "150 cl" };
        var indexX = -9999;
        var indexY = -9999;
        if (x is TShirt)
        {
            indexX = _sizesInOrder.IndexOf(((TShirt)x).Size);
            indexY = _sizesInOrder.IndexOf(((TShirt)y).Size);
        }
        else if (x is TShirtListViewModel)
        {
            indexX = _sizesInOrder.IndexOf(((TShirtListViewModel)x).Size);
            indexY = _sizesInOrder.IndexOf(((TShirtListViewModel)y).Size);
        }
        else if (x is MySelectItem)
        {
            indexX = _sizesInOrder.IndexOf(((MySelectItem)x).Value);
            indexY = _sizesInOrder.IndexOf(((MySelectItem)y).Value);
        }
        if (indexX > -1 && indexY > -1)
        {
            return indexX.CompareTo(indexY);
        }
        else if (indexX > -1)
        {
            return -1;
        }
        else if (indexY > -1)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
}

To use it you just have a List or whatever your object is and do:

tshirtList.Sort(new TShirtSizeComparer());

The order you have "hard-coded" is prioritized and the rest is put to the back.

I'm sure it can be done a bit smarter and more generalized to avoid hard-coding it all. You could e.g. look for sizes ending with an "S" and then check how many X's (e.g. XXS) or the number before X (e.g. 2XS) and sort by that, and then repeat for "L" and perhaps other "main sizes".


问:
Using strsplit within dplyr::mutate (without tibble::data_frame) raises "Evaluation error: non-character argument"
Edit: there was a typo in my df creation, with a missing _ on the last value of MediaName; this is now corrected.

I want to create a new variable TrialId in a data frame as part of the value of another variable MediaName depending on the value of a third variable Phase, and thought I could do that using strsplit and ifelse within a dplyr::mutate as follows:

```<code>library(dplyr)

# Creating a simple data frame for the example
df <- data.frame(Phase = c(rep("Familiarisation",8),rep("Test",3)),
                 MediaName = c("Flip_A1_G1","Reg_B2_S1","Reg_A2_G1","Flip_B1_S1",
                               "Reg_A1_G2","Flip_B2_S2","Reg_A2_G2","Flip_B1_S2",
                               "HC_A1L","TC_B1R","RC_BL_2R"))

# Creating a new column
df <- df %>%
  mutate(TrialId = ifelse(Phase == "Familiarisation",
                          sapply(strsplit(MediaName, "_"), "[", 2),
                          sapply(strsplit(MediaName, "_"), "[", 1)))
</code>```

The expected result being

```<code>> df$TrialId
[1] "A1" "B2" "A2" "B1" "A1" "B2" "A2" "B1" "HC" "TC" "RC"
</code>```

However this gives me the following error because, I believe, of the strsplit:

```<code>Error in mutate_impl(.data, dots) :
  Evaluation error: non-character argument.
</code>```

I know from this SO question that I can easily solve my issue by defining, in this small example, my data frame as a tibble::data_frame, without knowing why this solves the issue. I can't do exactly that though as in my actual code df comes from reading a csv file (with read.csv()). I have been thinking that using df <- df %>% as_tibble() %>% mutate(...) would solve the issue in a similar way, but it doesn't (why?).

Is there a way to actually use tibble even when reading files? Or is there another way of achieving what I need to do, without using strsplit maybe?

I'm also reading on this other SO question that you can use tidyr::separate but it isn't doing exactly what I want as I need to keep either the first or second value depending on the value of Phase.

答:
You can try:

```<code>library(tidyverse)
# your first data
df_old <- data.frame(Phase = c(rep("Familiarisation",8),rep("Test",3)),
                 MediaName = c("Flip_A1_G1","Reg_B2_S1","Reg_A2_G1","Flip_B1_S1",
                               "Reg_A1_G2","Flip_B2_S2","Reg_A2_G2","Flip_B1_S2",
                               "HC_A1L","TC_B1R","RC_BL2R"))
df_old %>%
  separate(MediaName, into=letters[1:3], sep="_", fill = "left", remove = FALSE) %>%
  select(Phase, MediaName, TrialId=b)
             Phase  MediaName TrialId
1  Familiarisation Flip_A1_G1      A1
2  Familiarisation  Reg_B2_S1      B2
3  Familiarisation  Reg_A2_G1      A2
4  Familiarisation Flip_B1_S1      B1
5  Familiarisation  Reg_A1_G2      A1
6  Familiarisation Flip_B2_S2      B2
7  Familiarisation  Reg_A2_G2      A2
8  Familiarisation Flip_B1_S2      B1
9             Test     HC_A1L      HC
10            Test     TC_B1R      TC
11            Test    RC_BL2R      RC
</code>```

It is a hardcoded solution according the provided sample data. Separate by "_", if there are onyl two instead of three "_" fill NAs from the left side. Finally, select the columns you need.

Edit

With your new data it is somewhat more complicated. but you can try:

```<code>df %>%
  add_column(MediaName_keep=df$MediaName) %>%
  group_by(MediaName_keep) %>%
  separate_rows(MediaName, sep="_") %>%
  mutate(n=1:n()) %>%
  filter((Phase == "Familiarisation" & n == 2) | (Phase == "Test" & n == 1)) %>%
  select(Phase, MediaName=MediaName_keep, TrialId=MediaName)
# A tibble: 11 x 3
# Groups:   MediaName [11]
             Phase  MediaName TrialId
            <fctr>     <fctr>   <chr>
 1 Familiarisation Flip_A1_G1      A1
 2 Familiarisation  Reg_B2_S1      B2
 3 Familiarisation  Reg_A2_G1      A2
 4 Familiarisation Flip_B1_S1      B1
 5 Familiarisation  Reg_A1_G2      A1
 6 Familiarisation Flip_B2_S2      B2
 7 Familiarisation  Reg_A2_G2      A2
 8 Familiarisation Flip_B1_S2      B1
 9            Test     HC_A1L      HC
10            Test     TC_B1R      TC
11            Test   RC_BL_2R      RC
</code>```

The idea is the same. Separate, but at this time add and count the new rows by MediaName_keep, then filter according your needs.

Body:
Edit: there was a typo in my df creation, with a missing _ on the last value of MediaName; this is now corrected.

I want to create a new variable TrialId in a data frame as part of the value of another variable MediaName depending on the value of a third variable Phase, and thought I could do that using strsplit and ifelse within a dplyr::mutate as follows:

library(dplyr)

# Creating a simple data frame for the example
df <- data.frame(Phase = c(rep("Familiarisation",8),rep("Test",3)),
                 MediaName = c("Flip_A1_G1","Reg_B2_S1","Reg_A2_G1","Flip_B1_S1",
                               "Reg_A1_G2","Flip_B2_S2","Reg_A2_G2","Flip_B1_S2",
                               "HC_A1L","TC_B1R","RC_BL_2R"))

# Creating a new column
df <- df %>%
  mutate(TrialId = ifelse(Phase == "Familiarisation",
                          sapply(strsplit(MediaName, "_"), "[", 2),
                          sapply(strsplit(MediaName, "_"), "[", 1)))

The expected result being

> df$TrialId
[1] "A1" "B2" "A2" "B1" "A1" "B2" "A2" "B1" "HC" "TC" "RC"

However this gives me the following error because, I believe, of the strsplit:

Error in mutate_impl(.data, dots) :
  Evaluation error: non-character argument.

I know from this SO question that I can easily solve my issue by defining, in this small example, my data frame as a tibble::data_frame, without knowing why this solves the issue. I can't do exactly that though as in my actual code df comes from reading a csv file (with read.csv()). I have been thinking that using df <- df %>% as_tibble() %>% mutate(...) would solve the issue in a similar way, but it doesn't (why?).

Is there a way to actually use tibble even when reading files? Or is there another way of achieving what I need to do, without using strsplit maybe?

I'm also reading on this other SO question that you can use tidyr::separate but it isn't doing exactly what I want as I need to keep either the first or second value depending on the value of Phase.

Body:
You can try:

library(tidyverse)
# your first data
df_old <- data.frame(Phase = c(rep("Familiarisation",8),rep("Test",3)),
                 MediaName = c("Flip_A1_G1","Reg_B2_S1","Reg_A2_G1","Flip_B1_S1",
                               "Reg_A1_G2","Flip_B2_S2","Reg_A2_G2","Flip_B1_S2",
                               "HC_A1L","TC_B1R","RC_BL2R"))
df_old %>%
  separate(MediaName, into=letters[1:3], sep="_", fill = "left", remove = FALSE) %>%
  select(Phase, MediaName, TrialId=b)
             Phase  MediaName TrialId
1  Familiarisation Flip_A1_G1      A1
2  Familiarisation  Reg_B2_S1      B2
3  Familiarisation  Reg_A2_G1      A2
4  Familiarisation Flip_B1_S1      B1
5  Familiarisation  Reg_A1_G2      A1
6  Familiarisation Flip_B2_S2      B2
7  Familiarisation  Reg_A2_G2      A2
8  Familiarisation Flip_B1_S2      B1
9             Test     HC_A1L      HC
10            Test     TC_B1R      TC
11            Test    RC_BL2R      RC

It is a hardcoded solution according the provided sample data. Separate by "_", if there are onyl two instead of three "_" fill NAs from the left side. Finally, select the columns you need.

Edit

With your new data it is somewhat more complicated. but you can try:

df %>%
  add_column(MediaName_keep=df$MediaName) %>%
  group_by(MediaName_keep) %>%
  separate_rows(MediaName, sep="_") %>%
  mutate(n=1:n()) %>%
  filter((Phase == "Familiarisation" & n == 2) | (Phase == "Test" & n == 1)) %>%
  select(Phase, MediaName=MediaName_keep, TrialId=MediaName)
# A tibble: 11 x 3
# Groups:   MediaName [11]
             Phase  MediaName TrialId
            <fctr>     <fctr>   <chr>
 1 Familiarisation Flip_A1_G1      A1
 2 Familiarisation  Reg_B2_S1      B2
 3 Familiarisation  Reg_A2_G1      A2
 4 Familiarisation Flip_B1_S1      B1
 5 Familiarisation  Reg_A1_G2      A1
 6 Familiarisation Flip_B2_S2      B2
 7 Familiarisation  Reg_A2_G2      A2
 8 Familiarisation Flip_B1_S2      B1
 9            Test     HC_A1L      HC
10            Test     TC_B1R      TC
11            Test   RC_BL_2R      RC

The idea is the same. Separate, but at this time add and count the new rows by MediaName_keep, then filter according your needs.


问:
Overwriting default CSS and JS in CakePHP 3
How do I remove the current CSS files from CakePHP 3 and add my own?

I have removed these codes from default.ctp:

```<code><?= $this->Html->css('base.css') ?>
<?= $this->Html->css('cake.css') ?>
<?= $this->fetch('script') ?>
</code>```

But still its showing the default CSS?

答: In CakePHP 3 the default install carries the full HTML document in Templates/Pages/home.ctp. Try to remove it there also.

Body:
How do I remove the current CSS files from CakePHP 3 and add my own?

I have removed these codes from default.ctp:

<?= $this->Html->css('base.css') ?>
<?= $this->Html->css('cake.css') ?>
<?= $this->fetch('script') ?>

But still its showing the default CSS?


问:
Shuffle an Array and Return a New One in JS
I want to know how to shuffle an array and return a NEW array. So far I have seen this solution in Stack Overflow:

How to randomize (shuffle) a JavaScript array?

This solution works perfectly in returning the same array shuffled, but I don't really understand why. Can anyone explain this and help me revise it so that it returns a new array?

Thanks!

答:
Maybe useful for you

var original = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var copy = [].concat(original);
copy.sort(function(){
  return 0.5 - Math.random();
});
console.log(copy);```


问:
Was my C file generated from Pro*C
We are in the process of inhereting an application from another developer. To support it properly we are first auditing what's working and what's missing in the application, and if all the fonts compile to the matching binaries.

During this process, we found a C file, which to my little knowledge in the subject, seems to have been generated from a Pro*C file.

When confronted, the previous developer says it is NOT generated from a Pro*C and that he just modifies it in Visual Studio (Odd). It seems close to imposible to maintain such a file as it is. Let me show you some things in it:

```<code>/* CUD (Compilation Unit Data) Array */
static short sqlcud0[] =
{12,4130,31,0,0,
5,0,0,0,0,0,27,980,0,0,4,4,0,1,0,1,9,0,0,1,10,0,0,1,10,0,0,1,10,0,0,
36,0,0,2,60,0,4,984,0,0,1,0,0,1,0,2,3,0,0,
55,0,0,3,74,0,2,1000,0,0,3,3,0,1,0,1,3,0,0,1,3,0,0,1,3,0,0,
82,0,0,4,0,0,29,1077,0,0,0,0,0,1,0,
</code>```

This array goes on for over 17 thousand characters.

Or even:

```<code>static struct sqlcxp sqlfpn =
{
    10,
    "nameoftheCfile.pc"
};
</code>```

So, I was wondering, is it possible that he is really using some Visual Studio tool to generate this C file, and it's not really a ProC?
Is it possible that Visual Studio or other tool generates this file, and he is unaware that it comes from a ProC file?
Is it possible to confirm a 100% that this is actually a compiled Pro*C file?

I'm hoping this is just a misunderstanding with the previous developer and not that he is refusing to give us the original fonts...

Thanks in advance.

答:
Yes, it was generated by ProC. sqlcud or CUD (Compilation Unit Data) Array, is generated by ProC, but it´s structure was not revealed by Oracle.

Also, we found an old manual in the developers site where it proudly stated that Pro*C was used to create the software.

Thanks everyone.

Title: Was my C file generated from Pro*C

Body:
We are in the process of inhereting an application from another developer. To support it properly we are first auditing what's working and what's missing in the application, and if all the fonts compile to the matching binaries.

During this process, we found a C file, which to my little knowledge in the subject, seems to have been generated from a Pro*C file.

When confronted, the previous developer says it is NOT generated from a Pro*C and that he just modifies it in Visual Studio (Odd). It seems close to imposible to maintain such a file as it is. Let me show you some things in it:

/* CUD (Compilation Unit Data) Array */
static short sqlcud0[] =
{12,4130,31,0,0,
5,0,0,0,0,0,27,980,0,0,4,4,0,1,0,1,9,0,0,1,10,0,0,1,10,0,0,1,10,0,0,
36,0,0,2,60,0,4,984,0,0,1,0,0,1,0,2,3,0,0,
55,0,0,3,74,0,2,1000,0,0,3,3,0,1,0,1,3,0,0,1,3,0,0,1,3,0,0,
82,0,0,4,0,0,29,1077,0,0,0,0,0,1,0,

This array goes on for over 17 thousand characters.

Or even:

static struct sqlcxp sqlfpn =
{
    10,
    "nameoftheCfile.pc"
};

So, I was wondering, is it possible that he is really using some Visual Studio tool to generate this C file, and it's not really a ProC?
Is it possible that Visual Studio or other tool generates this file, and he is unaware that it comes from a ProC file?
Is it possible to confirm a 100% that this is actually a compiled Pro*C file?

I'm hoping this is just a misunderstanding with the previous developer and not that he is refusing to give us the original fonts...

Thanks in advance.


问:
Reading the first 10 bytes of a file in Java
```<code>    for (String name : filenames) {
FileInputStream in = new FileInputStream(input.readUTF());
    int byteCounter = 0;
    int rowCounter = 0;
    long bufferCounter = 0;
    byte[] b = new byte[8];
    int read;

    //in.skip(10);
    //while((read = in.read()) != -1){
    while((read = in.read(b, 0, 10)) != -1){
        byteCounter ++;
        if (byteCounter != 1000){
            if (rowCounter == 16){
                System.out.println("\n");
                rowCounter = 0;
            }
        System.out.print(Integer.toHexString(read) + "\t");
            bufferCounter ++;
            rowCounter ++;
        }else{
                byteCounter = 0;
                try{
                    Thread.sleep(200);
                }catch(InterruptedException e) {
                }
        }
    }
    System.out.println("\n"+"================"+"\n");
}
</code>```

Hi there, I was hoping someone might be able to help me with an issue I've been having. I'm trying to get my program to read in the first 10 bytes of a specified file. I can get it to work with the skip() but obviously this does the opposite of what I want (it removes the first 10 instead)
I've looked all over to no avail, if you can help me out, that'd be great.
You can probably see that I've tried to enter the read(b, off, len) into the code already but this just produces random characters as an output rather than the actual hex characters I want 74 65 71 etc (Edit: These random characters seem to be the hex code for the number of bytes read. So for a text file that has 23 hex chars in it, it produces a a 3 (or in other words: 10,10,3 = 23)

答:
```<code>byte[] b = new byte[10];
new DataInputStream(new FileInputStream(input.readUTF())).readFully(b);
</code>```

This is the simplest way, but it throws in case there are less than 10 bytes available. In case you don't want it, use a loop. Somehow I don't get what you're doing, it really doesn't look like reading the first 10 bytes: if (byteCounter != 1000)

Body:
    for (String name : filenames) {
FileInputStream in = new FileInputStream(input.readUTF());
    int byteCounter = 0;
    int rowCounter = 0;
    long bufferCounter = 0;
    byte[] b = new byte[8];
    int read;

    //in.skip(10);
    //while((read = in.read()) != -1){
    while((read = in.read(b, 0, 10)) != -1){
        byteCounter ++;
        if (byteCounter != 1000){
            if (rowCounter == 16){
                System.out.println("\n");
                rowCounter = 0;
            }
        System.out.print(Integer.toHexString(read) + "\t");
            bufferCounter ++;
            rowCounter ++;
        }else{
                byteCounter = 0;
                try{
                    Thread.sleep(200);
                }catch(InterruptedException e) {
                }
        }
    }
    System.out.println("\n"+"================"+"\n");
}

Hi there, I was hoping someone might be able to help me with an issue I've been having. I'm trying to get my program to read in the first 10 bytes of a specified file. I can get it to work with the skip() but obviously this does the opposite of what I want (it removes the first 10 instead)
I've looked all over to no avail, if you can help me out, that'd be great.
You can probably see that I've tried to enter the read(b, off, len) into the code already but this just produces random characters as an output rather than the actual hex characters I want 74 65 71 etc (Edit: These random characters seem to be the hex code for the number of bytes read. So for a text file that has 23 hex chars in it, it produces a a 3 (or in other words: 10,10,3 = 23)

Body:
byte[] b = new byte[10];
new DataInputStream(new FileInputStream(input.readUTF())).readFully(b);

This is the simplest way, but it throws in case there are less than 10 bytes available. In case you don't want it, use a loop. Somehow I don't get what you're doing, it really doesn't look like reading the first 10 bytes: if (byteCounter != 1000)