问:
I have to maintain value of variable which is different per user session in .net core

I have implemented a Policy based authorization in .net core mvc
  application. Code:

```<code>  protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ValidUserAuthorization requirement)
    {
        List<KeyValuePair<string, string>> parameters = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("UserAlias", context.User.Identity.Name.Split('@')[0])
        };

        var isAuthorized = this.CubeServiceManager.GetDataFromService("CheckIfAuthorized", "GET", this.ConnectionStrings.BaseAddress, parameters);

        if (isAuthorized == "true")
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
</code>```

I have added Authorize attribute at controller level which call this Async method every time. If value of isAuthorized is true then user is authorized.
  But for every call to async method, service call is being made to set the value of  isAuthorized variable, which i want to cache per session for each user.
  How can i do it in this Authorization handler.?

答:
I would suggest using memcached, also Enyim client is ported to .Net Core:
https://github.com/cnblogs/EnyimMemcachedCore</p>

Body:
I have implemented a Policy based authorization in .net core mvc
  application. Code:

  protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ValidUserAuthorization requirement)
    {
        List<KeyValuePair<string, string>> parameters = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("UserAlias", context.User.Identity.Name.Split('@')[0])
        };

        var isAuthorized = this.CubeServiceManager.GetDataFromService("CheckIfAuthorized", "GET", this.ConnectionStrings.BaseAddress, parameters);

        if (isAuthorized == "true")
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }

I have added Authorize attribute at controller level which call this Async method every time. If value of isAuthorized is true then user is authorized.
  But for every call to async method, service call is being made to set the value of  isAuthorized variable, which i want to cache per session for each user.
  How can i do it in this Authorization handler.?


来源: stackexchange

问:
super.super.func()? - Java polymorphism
Say that I in Java have 3 classes, wheres the super one has a function named func(), I now make a subclass which overrides this, and a subclass to my subclass, now working on my sub-sub-class how will I call the 'func()' of the sub class, and the superclass?

I tried casting the 'this' "pointer", but Java 'fixes' it at runtime and calls the subsub func().

Edit:
Thanks everyone; 'Skeen is back at the drawing board'.

答:
The best you can do is call super.func() in your subsub class, and have the func() implementation in your subclass also call super.func().

However, ask yourself, if I need knowledge not only of my parents implementation but also my grandparents implementation, do I have a design problem? Quite frankly this is tripping my "Something stinks in the fridge" instinct. You need to re-evaluate why you want to do this.

ContentLicense: CC BY-SA 2.5

Title: super.super.func()? - Java polymorphism


问:
RESTful API with COAP, MQTT, or other lightweight protocol
I have a working HTTP RESTful API that will receive an ID, then check against data in the database. Based on the status of the record and related records it will then return either state errors or if everything is ready to begin it will return some information about the records. It has some other functionality as well but my issue is our device we are using to collect this data does not have access to WiFi, we are planning on testing a 2G cellular solution but I know an HTTP request will be far too slow if it even completes.

What lightweight protocol can my device send a 36 char UUID to a server and get a JSON response back. I have been exploring information about MQTT and COAP but don't see much info on asking another device about a specific ID of a record it's more like ask for a hardware's status.

Furthermore, if there is a solution I can get to interface with my existing API this would be ideal.

Thanks for any help.

答:
I'm not sure why the 2G cellular solution wont play well with HTTP(S).

according to another SO answer the size of http is:

Request headers today vary
  in size from ~200 bytes to over 2KB. As applications use more cookies
  and user agents expand features, typical header sizes of 700-800 bytes
  is common.

And according to wiki you can get up to 40kbit/s. I'm not really sure what the issue is with using http(s) for this scenario.

If you use something like UDP it can be quicker and is smaller however, it's not as reliable as HTTP due to packet loss possibilities. Not to mention you can also apply gzip or another form of compression on the HTTP request to make it even smaller.

minor update

If that data is not needed right away you can do it hourly or half day batch uploads, store all the data in a local db and at certain time intervals do 1 main HTTP request that is a bit bigger but will have all the data? I'm not fully sure what your requirements are but HTTP should be fine for your case over 2G

ContentLicense: CC BY-SA 3.0


问:
How to convert html blade that contains dynamic data from database to PDF in laravel?
I'm trying to write code that converts html blade to PDF using tcpdf in laravel.

This is the controller code which i use to convert:

```<code>public function htmlToPDF()
{
    $view=view('PdfDemo');
    $html_content =$view->render();
    PDF::SetTitle('Sample PDF');
    PDF::AddPage();
    PDF::writeHTML($html_content, true, false, true, false, '');
    PDF::Output('SamplePDF.pdf');
}
</code>```

When I put static data on my view(PdfDemo) everything runs successfully, but the problem is when I put dynamic data with some variables in the blade as the following:

```<code>                        <table>
                          <?php $i=0?>
                            @if(count($names))
                                @foreach($names as $n)
                                    <tr><td>
                                    <label>Name{{$i}}:</label>{{$n}}</td>
                                    <tr><td><hr></td></tr>
                                    <?php $index = $index+1; ?>
                                @endforeach
                            @endif
                        </table>
</code>```

Here $names is the result of select statement in other function of controller, then I pass it to the blade like this:

```<code> return view('PdfDemo',compact('names'));
</code>```

In this case the blade appear exactly as I want, but when I try to convert to PDF it shows error, $name not defined.

答:
Do like this:

```<code>$view = View::make('PdfDemo',compact('names'));
$contents = (string) $view;
// or
$contents = $view->render();
</code>```

When you use View::make() it gets the HTML code of blade file as HTML content after adding dynamic variable's values.

Body:
I'm trying to write code that converts html blade to PDF using tcpdf in laravel.

This is the controller code which i use to convert:

public function htmlToPDF()
{
    $view=view('PdfDemo');
    $html_content =$view->render();
    PDF::SetTitle('Sample PDF');
    PDF::AddPage();
    PDF::writeHTML($html_content, true, false, true, false, '');
    PDF::Output('SamplePDF.pdf');
}

When I put static data on my view(PdfDemo) everything runs successfully, but the problem is when I put dynamic data with some variables in the blade as the following:

                          <?php $i=0?>
                            @if(count($names))
                                @foreach($names as $n)

                                    Name{{$i}}:{{$n}}

                                    <?php $index = $index+1; ?>
                                @endforeach
                            @endif

Here $names is the result of select statement in other function of controller, then I pass it to the blade like this:

 return view('PdfDemo',compact('names'));

In this case the blade appear exactly as I want, but when I try to convert to PDF it shows error, $name not defined.

Body:
Do like this:

$view = View::make('PdfDemo',compact('names'));
$contents = (string) $view;
// or
$contents = $view->render();

When you use View::make() it gets the HTML code of blade file as HTML content after adding dynamic variable's values.


问:
Shuffling biased random numbers
While thinking about this question and conversing with the participants, the idea came up that shuffling a finite set of clearly biased random numbers makes them random because you don't know the order in which they were chosen.  Is this true and if so can someone point to some resources?

EDIT:  I think I might have been a little unclear. Suppose a bad random numbers generator. Take n values. These are biased(the rng is bad). Is there a way through shuffling to make the output of the rng over multiple trials statistically match the output of a known good rng?

答:
I would say false, with a caveat:

I think there is random, and then there is 'random-enough'. For most applications that I have needed to work on, 'random-enough' was more than enough, i.e. picking a 'random' ad to display on a page from a list of 300 or so that have paid to be placed on that site.

I am sure a mathematician could prove my very basic 'random' selection criteria is not truly random at all, but in fact is predictable - for my clients, and for the users, nobody cares.

On the other hand if I was writing a video game to be used in Las Vegas where large amounts of money was at hand I'd define random differently (and may have a hard time coming up with truly random).

OwnerDisplayName: JPunyon

ContentLicense: CC BY-SA 4.0

Title: Shuffling biased random numbers

LastEditorDisplayName: JPunyon

OwnerDisplayName: E.J. Brennan


问:
read microsoft excel, word and powerpoint info using PHP
i want my PHPapp to read a file and tell me if it's a word, excel or powerpoint file. my first approach was to read the extension of the file. But microsoft has different file extension names, and i was also wondering about files uploaded by a mac (with no filename extension)

So, maybe the answer is using mimetypes. Do you know a better approach for this?

答:
Yes, trying to determine the MimeType is your best bet short of just try/catching to load the files with PHPWord, PHPExcel and PHPowerpoint directly to see if they throw an exception (Mark Baker correct me please if they dont throw exceptions).

See my answer to

PHP how can i check if a file is mp3 or image file?

for various ways to detect the MimeType.

You can find a number of possible MimeTypes for Office documents at

http://filext.com/faq/office_mime_types.php and

http://social.msdn.microsoft.com/Forums/en-US/exceldev/thread/87b9cd73-a41b-4fd0-94c7-dfe53e92947e


问:
Voice call from app to phone using sip and gateway
How to implement voice calls to mobile/landline numbers from app(mobile client) using SIP server and gateway. how to configure the gateway with SIP?
i'm planning to use Kamailio since it's open source.</p>

答:
You can try using an opensource turn-key solution based on Kamailio. E.g. Sipwise C5 https://www.sipwise.org/products/spce/features/

Just download it and install on a server or a VM.


问:
MSSQL slow stored proc on first run, uncached indexes?
Have a 20GB database in SQL Server 2014 behind an IIS web application - DB is queried 24/7 so it's never inactive and auto-close is off but there's a manually-triggered "daily work queue" stored procedure which runs inconsistently during the first execute.

When it's used in the morning for the first time it runs slowly - if you wait, execute again it's back to an immediate response.  Minimal other loads on the server at the same time, page life expectancy is healthy and should have necessary indexes to support this query - or at least no additional indexes are being recommended.

Been trying to approach this as a query optimisation problem and getting nowhere, so began exploring other ideas.

Restored DB from backup onto local dev server - first execution is slow, the second execution is fast and see the large (500mb+) indexes loaded via sys.dm_os_buffer_descriptors - if I run DBCC DROPCLEANBUFFERS to simulate everything being unloaded from the buffer, next execution will be slow, can watch the indexes being cached, which point it executes quickly.

Seems to fit the pattern we're experiencing and doesn't seem unreasonable to assume MSSQL might uncache data that's not been used for 10+ hours.

Have I missed something more obvious?  Assuming I'm on the right path, can't be the first person to run across this issue so must be an elegant solution out there...

答:
If your "daily work queue" change the data. Then index need to be rebuild and reload in the cache. Is the same as start an old car you need to wait a little bit.

What I do is plan those "work" at night and also program some basic query so index are load in the cache.

Also check your hardware (disk, memory) the first time you run the query the db has to bring the data from disk (slow) and store it in memory (fast but small size).


问:
sheets.count vs workbook activation
In the following code, the "Sheets.Count" in "Master.Activate" works only when the "Source" workbook is manually selected by mouse click before running the macro. Otherwise "Master.Activate" will activate the first worksheet of "Master" workbook instead of performing Sheets.Count and selecting the last sheet. That basically means that the macro has to be run from "Master" workbook but only after clicking on "Source" workbook. I would be grateful for any suggestions on how to fix that.

```<code>Dim Source As Worksheet
Set Source = Workbooks("Source.xlsx").Worksheets("Settlements")
Dim Master As Worksheet
Set Master = Workbooks("Master Bonviva.xlsm").Worksheets(Sheets.Count)

Source.Activate

For Each cell In Source.Columns("M").Cells
    If Not IsEmpty(cell) Then
        Master.Activate
            For Each cell2 In Master.Columns("J").Cells
                If Not IsEmpty(cell2) Then
                    If cell = cell2 Then
                        cell2.Offset(0, 9).Value = cell.Offset(0, -2).Value
                        cell2.Offset(0, 8).Value = cell.Offset(0, -8).Value
                    End If
                End If
            Next cell2
     End If
Next cell

End Sub
</code>```

Regards,
Bartek

答:
Try to disreagart Select and Activate. Declare the cell1 and cell2. Thus, this should work:

```<code>Public Sub TestMe()

    Dim Source As Worksheet
    Set Source = Workbooks("Source.xlsx").Worksheets("Settlements")

    Dim Master As Worksheet
    Set Master = Workbooks("Master Bonviva.xlsm").Worksheets(Sheets.Count)

    Dim cell1   As Range
    Dim cell2   As Range

    For Each cell1 In Source.Columns("M").Cells
        If Not IsEmpty(cell1) Then
            For Each cell2 In Master.Columns("J").Cells
                If Not IsEmpty(cell2) Then
                    If cell1 = cell2 Then
                        cell2.Offset(0, 9).Value = cell1.Offset(0, -2).Value
                        cell2.Offset(0, 8).Value = cell1.Offset(0, -8).Value
                    End If
                End If
            Next cell2
        End If
    Next cell1

End Sub
</code>```

How to avoid using Select in Excel VBA

In general, as a good practice, do not declare variables, which use the same name used by the VB Editor. E.g., avoid declaring cell, but use cell1 or anything else which makes sense.

Title: sheets.count vs workbook activation

Body:
In the following code, the "Sheets.Count" in "Master.Activate" works only when the "Source" workbook is manually selected by mouse click before running the macro. Otherwise "Master.Activate" will activate the first worksheet of "Master" workbook instead of performing Sheets.Count and selecting the last sheet. That basically means that the macro has to be run from "Master" workbook but only after clicking on "Source" workbook. I would be grateful for any suggestions on how to fix that.

Dim Source As Worksheet
Set Source = Workbooks("Source.xlsx").Worksheets("Settlements")
Dim Master As Worksheet
Set Master = Workbooks("Master Bonviva.xlsm").Worksheets(Sheets.Count)

Source.Activate

For Each cell In Source.Columns("M").Cells
    If Not IsEmpty(cell) Then
        Master.Activate
            For Each cell2 In Master.Columns("J").Cells
                If Not IsEmpty(cell2) Then
                    If cell = cell2 Then
                        cell2.Offset(0, 9).Value = cell.Offset(0, -2).Value
                        cell2.Offset(0, 8).Value = cell.Offset(0, -8).Value
                    End If
                End If
            Next cell2
     End If
Next cell

End Sub

Regards,
Bartek

Body:
Try to disreagart Select and Activate. Declare the cell1 and cell2. Thus, this should work:

Public Sub TestMe()

    Dim Source As Worksheet
    Set Source = Workbooks("Source.xlsx").Worksheets("Settlements")

    Dim Master As Worksheet
    Set Master = Workbooks("Master Bonviva.xlsm").Worksheets(Sheets.Count)

    Dim cell1   As Range
    Dim cell2   As Range

    For Each cell1 In Source.Columns("M").Cells
        If Not IsEmpty(cell1) Then
            For Each cell2 In Master.Columns("J").Cells
                If Not IsEmpty(cell2) Then
                    If cell1 = cell2 Then
                        cell2.Offset(0, 9).Value = cell1.Offset(0, -2).Value
                        cell2.Offset(0, 8).Value = cell1.Offset(0, -8).Value
                    End If
                End If
            Next cell2
        End If
    Next cell1

End Sub

How to avoid using Select in Excel VBA

In general, as a good practice, do not declare variables, which use the same name used by the VB Editor. E.g., avoid declaring cell, but use cell1 or anything else which makes sense.


问:
Scheduling multiple emails PHP
I've made a system that receives a query, executes it at the database and then creates an HTML table with the data returned. These tables are then saved in the system for further access, and the user can send it via email to multiple receivers.

All works well, but now I have to schedule the emails. Need to send "table X" at a week from now and "table Y" at two weeks. How can I do that? I've looked up for CRONS/WindowsTasks but I don't know how I would make it automatic for every table, since the user can keep creating different tables.

I've used CodeIgniter and PHPMailerMaster to make it happen.

Here is a screenshot of the TableViewer, it's in portuguese, but it contains:

|TITLE | CONFIG | SEND | XLS GENERATOR | LAST SENT |

For each table created. (Just so you can understand how it works)

If anyone got any ideas.

答:
Here is a function that simulates crontab in PHP. You can use this for dynamic crontabs, so each table can have it's own unique frequency.

```<code>function parse_crontab($time, $crontab) {
    // Get current minute, hour, day, month, weekday
    $time = explode(' ', date('i G j n w', strtotime($time)));
    // Split crontab by space
    $crontab = explode(' ', $crontab);
    // Foreach part of crontab
    foreach ($crontab as $k => &$v) {
        // Remove leading zeros to prevent octal comparison, but not if number is already 1 digit
        $time[$k] = preg_replace('/^0+(?=\d)/', '', $time[$k]);
        // 5,10,15 each treated as seperate parts
        $v = explode(',', $v);
        // Foreach part we now have
        foreach ($v as &$v1) {
            // Do preg_replace with regular expression to create evaluations from crontab
            $v1 = preg_replace(
                // Regex
                array(
                    // *
                    '/^\*$/',
                    // 5
                    '/^\d+$/',
                    // 5-10
                    '/^(\d+)\-(\d+)$/',
                    // */5
                    '/^\*\/(\d+)$/'
                ),
                // Evaluations
                // trim leading 0 to prevent octal comparison
                array(
                    // * is always true
                    'true',
                    // Check if it is currently that time,
                    $time[$k] . '===\0',
                    // Find if more than or equal lowest and lower or equal than highest
                    '(\1<=' . $time[$k] . ' and ' . $time[$k] . '<=\2)',
                    // Use modulus to find if true
                    $time[$k] . '%\1===0'
                ),
                // Subject we are working with
                $v1
            );
        }
        // Join 5,10,15 with `or` conditional
        $v = '(' . implode(' or ', $v) . ')';
    }
    // Require each part is true with `and` conditional
    $crontab = implode(' and ', $crontab);
    // Evaluate total condition to find if true
    return eval('return ' . $crontab . ';');
}
</code>```

It's used like this. First parameter is the current time, or time you want to check, second parameter is the crontab.

```<code>$time_to_run = parse_crontab(date('Y-m-d H:i:s'), '* * * * *')
</code>```

Title: Scheduling multiple emails PHP

Body:
Here is a function that simulates crontab in PHP. You can use this for dynamic crontabs, so each table can have it's own unique frequency.

function parse_crontab($time, $crontab) {
    // Get current minute, hour, day, month, weekday
    $time = explode(' ', date('i G j n w', strtotime($time)));
    // Split crontab by space
    $crontab = explode(' ', $crontab);
    // Foreach part of crontab
    foreach ($crontab as $k => &$v) {
        // Remove leading zeros to prevent octal comparison, but not if number is already 1 digit
        $time[$k] = preg_replace('/^0+(?=\d)/', '', $time[$k]);
        // 5,10,15 each treated as seperate parts
        $v = explode(',', $v);
        // Foreach part we now have
        foreach ($v as &$v1) {
            // Do preg_replace with regular expression to create evaluations from crontab
            $v1 = preg_replace(
                // Regex
                array(
                    // *
                    '/^\*$/',
                    // 5
                    '/^\d+$/',
                    // 5-10
                    '/^(\d+)\-(\d+)$/',
                    // */5
                    '/^\*\/(\d+)$/'
                ),
                // Evaluations
                // trim leading 0 to prevent octal comparison
                array(
                    // * is always true
                    'true',
                    // Check if it is currently that time,
                    $time[$k] . '===\0',
                    // Find if more than or equal lowest and lower or equal than highest
                    '(\1<=' . $time[$k] . ' and ' . $time[$k] . '<=\2)',
                    // Use modulus to find if true
                    $time[$k] . '%\1===0'
                ),
                // Subject we are working with
                $v1
            );
        }
        // Join 5,10,15 with `or` conditional
        $v = '(' . implode(' or ', $v) . ')';
    }
    // Require each part is true with `and` conditional
    $crontab = implode(' and ', $crontab);
    // Evaluate total condition to find if true
    return eval('return ' . $crontab . ';');
}

It's used like this. First parameter is the current time, or time you want to check, second parameter is the crontab.

$time_to_run = parse_crontab(date('Y-m-d H:i:s'), '* * * * *')


问:
Make absolute positioned parent appear on top of absolute positioned child
I'm trying to make an absolute positioned child appear behind its absolute positioned parent. The blue parent should appear above red child.

I tried setting z-index: -1 on the child, but that makes red child not visible.

.container {
  position:relative;
  background-color:grey;
  width: 500px;
  height: 500px;
}
.parent {
  background-color:blue;
  position:absolute;
  top: 50px;
  left: 10px;
  height: 100px;
  width: 100px;
  border-radius: 100%;
}
.child {
  position:absolute;
  top:-5px;
  right: 0px;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  background-color:red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
 <div class="parent">
  <div class="child"></div>
 </div>
</div></code>```

https://jsfiddle.net/dwil30/mh3qw64x/

答:
Well... it seems a bit hacky, but its your call :)

You need to specify z-index of the container since otherwise the renderer has no "base" value to compare your child with.

Here is a working fiddle:

https://jsfiddle.net/cmvwLseo/

Cheers

Body:
I'm trying to make an absolute positioned child appear behind its absolute positioned parent. The blue parent should appear above red child.

I tried setting z-index: -1 on the child, but that makes red child not visible.

.container {
  position:relative;
  background-color:grey;
  width: 500px;
  height: 500px;
}
.parent {
  background-color:blue;
  position:absolute;
  top: 50px;
  left: 10px;
  height: 100px;
  width: 100px;
  border-radius: 100%;
}
.child {
  position:absolute;
  top:-5px;
  right: 0px;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  background-color:red;
}

https://jsfiddle.net/dwil30/mh3qw64x/


问:
the data insert every-time reload the page
I created form that insert data in database but every time I reload the page the data insert again .
I use unset($_POST) to fix it but it don't fix .

How I can make it insert only one time .

```<code> <form method="post" class="job">
            <input type="text" placeholder=" course name" name="name" class="form-control input-lg">
            <input type="text" placeholder=" country " name="country" class="form-control input-lg">
            <input type="text" placeholder=" company " name="company" class="form-control input-lg">
            <input type="date" placeholder=" start " name="start" class="form-control input-lg">
            <input type="date" placeholder=" end " name="end" class="form-control input-lg">
            <input type="text" placeholder="link" name="link" class="form-control input-lg">
            <button type="submit" class="btn btn-warning btn-lg btn-block" name="addcourse" id="addcourse"> ADD COURSE </button>
</form>
</div>
<div class="col-lg-4"></div>
</div>
<?php
include("connect.php");
if (isset($_POST['addcourse'])){
        $name = $_POST["name"];
        $country = $_POST["country"];
        $company = $_POST["company"];
        $link = $_POST["link"];
        $start=$_POST["start"];
        $end=$_POST["end"];

        $newcourse="INSERT INTO courses (name,country,company,start,end,link) VALUES ('$name','$country','$company','$start','$end','$link')";
        if(!empty($name)&&!empty($country)&&!empty($company)&&!empty($link)&&!empty($start)&&!empty($end)){
        if(mysql_query($newcourse)){
            unset($_POST);
            echo "<script> alert('insert successful');  </script>";

            }
        else{ unset($_POST);
              echo "<script>alert('error');  </script>";
        }}
        else { unset($_POST);
               echo "<script>alert('fill in all field');  </script>";}
}
?>
</code>```

答:
Since the request still contains all the values, when you refresh, Php will get the same values again.
In the if statement where you check if the query is successful, add the line:

header('Location: <where you want the user to be sent to>');

If you want the user to end up the same place again, write:

header('Location: '.$_SERVER['PHP_SELF']);

Body:
I created form that insert data in database but every time I reload the page the data insert again .
I use unset($_POST) to fix it but it don't fix .

How I can make it insert only one time .

 <form method="post" class="job">
            <input type="text" placeholder=" course name" name="name" class="form-control input-lg">
            <input type="text" placeholder=" country " name="country" class="form-control input-lg">
            <input type="text" placeholder=" company " name="company" class="form-control input-lg">
            <input type="date" placeholder=" start " name="start" class="form-control input-lg">
            <input type="date" placeholder=" end " name="end" class="form-control input-lg">
            <input type="text" placeholder="link" name="link" class="form-control input-lg">
            <button type="submit" class="btn btn-warning btn-lg btn-block" name="addcourse" id="addcourse"> ADD COURSE </button>
</form>

<?php
include("connect.php");
if (isset($_POST['addcourse'])){
        $name = $_POST["name"];
        $country = $_POST["country"];
        $company = $_POST["company"];
        $link = $_POST["link"];
        $start=$_POST["start"];
        $end=$_POST["end"];

        $newcourse="INSERT INTO courses (name,country,company,start,end,link) VALUES ('$name','$country','$company','$start','$end','$link')";
        if(!empty($name)&&!empty($country)&&!empty($company)&&!empty($link)&&!empty($start)&&!empty($end)){
        if(mysql_query($newcourse)){
            unset($_POST);
            echo "";

            }
        else{ unset($_POST);
              echo "";
        }}
        else { unset($_POST);
               echo "";}
}
?>


问:
Reintroducing functions in Delphi
What was the motivation for having the reintroduce keyword in Delphi?

If you have a child class that contains a function with the same name as a virtual function in the parent class and it is not declared with the override modifier then it is a compile error. Adding the reintroduce modifier in such situations fixes the error, but I have never grasped the reasoning for the compile error.

答:
First, as it was said above, you should never ever deliberately reintroduce virtual method. The only sane use of reintroduce is when the author of the ancestor (not you) added a method that goes into conflict with your descendant and renaming your descendant method is not an option. Second, you can easily call the original version of the virtual method even in classes where you reintroduced it with different parameters:

```<code>type
  tMyFooClass = class of tMyFoo;

  tMyFoo = class
    constructor Create; virtual;
  end;

  tMyFooDescendant = class(tMyFoo)
    constructor Create(a: Integer); reintroduce;
  end;

procedure .......
var
  tmp: tMyFooClass;
begin
  // Create tMyFooDescendant instance one way
  tmp := tMyFooDescendant;
  with tmp.Create do  // please note no a: integer argument needed here
  try
    { do something }
  finally
    free;
  end;

  // Create tMyFooDescendant instance the other way
  with tMyFooDescendant.Create(20) do  // a: integer argument IS needed here
  try
    { do something }
  finally
    free;
  end;
</code>```

so what should be the purpose of reintroducing virtual method other than make things harder to read?

Title: Reintroducing functions in Delphi

LastEditorDisplayName: Jim McKeeth

Body:
First, as it was said above, you should never ever deliberately reintroduce virtual method. The only sane use of reintroduce is when the author of the ancestor (not you) added a method that goes into conflict with your descendant and renaming your descendant method is not an option. Second, you can easily call the original version of the virtual method even in classes where you reintroduced it with different parameters:

type
  tMyFooClass = class of tMyFoo;

  tMyFoo = class
    constructor Create; virtual;
  end;

  tMyFooDescendant = class(tMyFoo)
    constructor Create(a: Integer); reintroduce;
  end;

procedure .......
var
  tmp: tMyFooClass;
begin
  // Create tMyFooDescendant instance one way
  tmp := tMyFooDescendant;
  with tmp.Create do  // please note no a: integer argument needed here
  try
    { do something }
  finally
    free;
  end;

  // Create tMyFooDescendant instance the other way
  with tMyFooDescendant.Create(20) do  // a: integer argument IS needed here
  try
    { do something }
  finally
    free;
  end;

so what should be the purpose of reintroducing virtual method other than make things harder to read?


问:
Using pyspark to connect to PostgreSQL
I am trying to connect to a database with pyspark and I am using the following code:

```<code>sqlctx = SQLContext(sc)
df = sqlctx.load(
    url = "jdbc:postgresql://[hostname]/[database]",
    dbtable = "(SELECT * FROM talent LIMIT 1000) as blah",
    password = "MichaelJordan",
    user =  "ScottyPippen",
    source = "jdbc",
    driver = "org.postgresql.Driver"
)
</code>```

and I am getting the following error:

Any idea why is this happening?

Edit: I am trying to run the code locally in my computer.

答:
It is necesary copy postgresql-42.1.4.jar in all nodes... for my case, I did copy in the path /opt/spark-2.2.0-bin-hadoop2.7/jars

Also, i set classpath in ~/.bashrc (export SPARK_CLASSPATH="/opt/spark-2.2.0-bin-hadoop2.7/jars" )

and work fine in pyspark console and jupyter

Title: Using pyspark to connect to PostgreSQL

Body:
I am trying to connect to a database with pyspark and I am using the following code:

sqlctx = SQLContext(sc)
df = sqlctx.load(
    url = "jdbc:postgresql://[hostname]/[database]",
    dbtable = "(SELECT * FROM talent LIMIT 1000) as blah",
    password = "MichaelJordan",
    user =  "ScottyPippen",
    source = "jdbc",
    driver = "org.postgresql.Driver"
)

and I am getting the following error:

Any idea why is this happening?

Edit: I am trying to run the code locally in my computer.


问:
setInterval that takes into account function time of run
I need function that execute some payload functions once in a while but takes into account that

a) payload function can takes some time to finish (like axaj request with timeout)

b) payload function can be Promise

c) I might wanna stop it some time later

答:
With a great appreciation to https://www.thecodeship.com/web-development/alternative-to-javascript-evil-setinterval/ and small improvements by me I'm posting this solution, feel free to correct me.

function interval(func, wait, times) {
  var _interval = function () {
    if (typeof times === "undefined" || times-- > 0) {
      try {
        Promise.resolve(func())
          .then(() => { window.setTimeout(_interval, wait) });
      }
      catch (e) {
        times = 0;
        throw e.toString();
      }
    }
  };

  _interval();

  return { stop: () => { times = 0 } };
};
```

<p><code>interval()</code> returns object with <code>stop</code> field so you can run it to stop timer like:</p>

<pre class="lang-js prettyprint-override"><code>let timer = interval(func, 1000, 10);
...
timer.stop();
</code>```

Body:
With a great appreciation to https://www.thecodeship.com/web-development/alternative-to-javascript-evil-setinterval/ and small improvements by me I'm posting this solution, feel free to correct me.

function interval(func, wait, times) {
  var _interval = function () {
    if (typeof times === "undefined" || times-- > 0) {
      try {
        Promise.resolve(func())
          .then(() => { window.setTimeout(_interval, wait) });
      }
      catch (e) {
        times = 0;
        throw e.toString();
      }
    }
  };

  _interval();

  return { stop: () => { times = 0 } };
};

interval() returns object with stop field so you can run it to stop timer like:

let timer = interval(func, 1000, 10);
...
timer.stop();


问:
How to verify that an object transfer is complete
I want to send a message (a serializable object) from a java instance to another instance over a network. I would like to verify that the whole object has been sent correctly.

I suppose my first step is to calculate the checksum of the object. Then I include that checksum in the object OR build a container object for the message and its checksum.

Then my second step should be to verify the checksum against the object on the other side.

My third step would be for the receiver to send a confirmation message saying that the object in question was received and that the checksum has passed (or not). If I receive a failed checksum warning, I try to resend it a few times.

After a little while, if I never received a confirmation, I try to resend it a few times as well.

Questions :

Does my protocol sounds right to verify that an object was transferred correctly ?

I would also like to know how am I supposed to implement this in java ? Do I use the CRC32 class to generate the checksum ?

Bonus question : If I were to compress each message, do I generate the checksum before of after the compression, and how do I compress an object in java ?

答:
For compression, I would like to recommend the Apache Zip Utilities:
http://commons.apache.org/compress/apidocs/org/apache/commons/compress/archivers/zip/package-summary.html

If you are compressing then you can skip the checksum.  Compression algorithms are quite sensitive to data damage.  If the object fails to decompress on the other end, then you lost some information during transmission.


问:
ngrx - chain two store.select slices
In my Todo Cmp I have this code

```<code>this.todoListGroup$ = this.ngrx.select(fromRoot.getTodos)
    .flatMap((todos: Todo[]) => {
        console.log(todos)
        this.todos = todos
        this.ngrx.select(fromRoot.getLastChangedTodo);
    })
    .map(lastTodo =>{{
        console.log(lastTodo)
        doSomething(this.todos, lastTodo)
    })
</code>```

When I subscribe to it I get one more console.log(lastTodo) each time todo changes. I figure that with flatmap and ngrx.select, I'm subscribing to a new Observable each time?

with which operator can I chain two store slices?

EDIT:

As long as the view is in the DOM, I want to stay subscribed to todoListGroup$ since it should keep updating my view.

My solution so far is to define a new slice in the reducer which returns the two desired properties. However, I'm still interested in which operator can effectively chain ngrx single property slices.

Thanks!

答:
Would something like this work:

```<code>this.todoListGroup$ =
    Observable.combineLatest(
        this.ngrx.select(fromRoot.getTodos),
        this.ngrx.select(fromRoot.getLastChangedTodo)
    )
    .do(([todos, lastToDo]) => console.log(todos, lastToDo));
</code>```

The do would execute each time either one of getTodos or getLastChangedTodo is updated and would take the latest known values from each of them at the time of the update. The caveat here is the order of when each of those updates are fired may not always be the same. So, if you wanted more of a chained (or cascaded) update then you could do this:

```<code>this.todoListGroup$ =
    this.ngrx.select(fromRoot.getTodos)
    .withLatestFrom(this.ngrx.select(fromRoot.getLastChangedTodo))
    .do(([todos, lastToDo]) => console.log(todos, lastToDo));
</code>```

That will execute each time getToDos is updated and would take the latest value from getLastChangedTodo. Hence the chained (or cascaded) updated idiom.

edit for rxjs 5+ syntax:

```<code>this.todoListGroup$ =
    combineLatest(
        this.ngrx.select(fromRoot.getTodos),
        this.ngrx.select(fromRoot.getLastChangedTodo)
    )
    .pipe(tap(([todos, lastToDo]) => console.log(todos, lastToDo)));

this.todoListGroup$ =
    this.ngrx.select(fromRoot.getTodos).pipe(
      withLatestFrom(this.ngrx.select(fromRoot.getLastChangedTodo)),
      tap(([todos, lastToDo]) => console.log(todos, lastToDo))
    );
</code>```

Title: ngrx - chain two store.select slices

Body:
In my Todo Cmp I have this code

this.todoListGroup$ = this.ngrx.select(fromRoot.getTodos)
    .flatMap((todos: Todo[]) => {
        console.log(todos)
        this.todos = todos
        this.ngrx.select(fromRoot.getLastChangedTodo);
    })
    .map(lastTodo =>{{
        console.log(lastTodo)
        doSomething(this.todos, lastTodo)
    })

When I subscribe to it I get one more console.log(lastTodo) each time todo changes. I figure that with flatmap and ngrx.select, I'm subscribing to a new Observable each time?

with which operator can I chain two store slices?

EDIT:

As long as the view is in the DOM, I want to stay subscribed to todoListGroup$ since it should keep updating my view.

My solution so far is to define a new slice in the reducer which returns the two desired properties. However, I'm still interested in which operator can effectively chain ngrx single property slices.

Thanks!

Body:
Would something like this work:

this.todoListGroup$ =
    Observable.combineLatest(
        this.ngrx.select(fromRoot.getTodos),
        this.ngrx.select(fromRoot.getLastChangedTodo)
    )
    .do(([todos, lastToDo]) => console.log(todos, lastToDo));

The do would execute each time either one of getTodos or getLastChangedTodo is updated and would take the latest known values from each of them at the time of the update. The caveat here is the order of when each of those updates are fired may not always be the same. So, if you wanted more of a chained (or cascaded) update then you could do this:

this.todoListGroup$ =
    this.ngrx.select(fromRoot.getTodos)
    .withLatestFrom(this.ngrx.select(fromRoot.getLastChangedTodo))
    .do(([todos, lastToDo]) => console.log(todos, lastToDo));

That will execute each time getToDos is updated and would take the latest value from getLastChangedTodo. Hence the chained (or cascaded) updated idiom.

edit for rxjs 5+ syntax:

this.todoListGroup$ =
    combineLatest(
        this.ngrx.select(fromRoot.getTodos),
        this.ngrx.select(fromRoot.getLastChangedTodo)
    )
    .pipe(tap(([todos, lastToDo]) => console.log(todos, lastToDo)));

this.todoListGroup$ =
    this.ngrx.select(fromRoot.getTodos).pipe(
      withLatestFrom(this.ngrx.select(fromRoot.getLastChangedTodo)),
      tap(([todos, lastToDo]) => console.log(todos, lastToDo))
    );


问:
How to normalize the spectrum of a numpy (real) fourier transform so that parcevals theorem applies?
Currently, I'm considering taking an image and its spectrum. Now Parceval's theorem says that both should have equal energy. However when I try to test this on some images, this doesn't seem to be the case for the numpy real FFT function.

This is the code I'm using for my test:

```<code>import numpy as np
from PIL import Image

im = np.array(Image.open('/images/building.jpeg'))
spectral_im = np.fft.rfft2(im, axes = (0,1), norm = 'ortho')

def getNorm(im):
    return np.sum(np.abs(im))

print('Norm of the image: %d' % getNorm(im))
print('Norm of the spectrum of the image: %f' % getNorm(spectral_im))
print('Difference between norms: %f' % (getNorm(im) - getNorm(spectral_im)))
</code>```

I expected that the difference between the norms would be (approximately) 0 for every image, however it differs by an order of magnitude for every image I have tried. Can anyone see what I'm doing wrong?

With the help from the answers, here is the corrected code (note the extra cast to float64, otherwise they still aren't equal):

```<code>import numpy as np
from PIL import Image

im = np.array(Image.open('/images/building.jpeg')).astype('float64')
spectral_im = np.fft.fft2(im, axes = (0,1), norm = 'ortho')

def getNorm(im):
    return np.sum(np.abs(im) ** 2)

print('Norm of the image: %d' % getNorm(im))
print('Norm of the spectrum of the image: %f' % getNorm(spectral_im))
print('Difference between norms: %f' % (getNorm(im) - getNorm(spectral_im)))
</code>```

答:
Parceval's Theorem states that the integral over the square of the signal and the fourier transform are the same. So the getNorm function should be defined as

```<code>def getNorm(im):
    return np.sum(np.abs(im)**2)
</code>```

Then there is the FFT normalization issue. You need to normalize the FFT by the image area (product of dimensions):

```<code>x = np.random.rand(321, 456)
f = np.fft.fft2(x) / np.sqrt(321 * 456)
print(np.sum(np.abs(x)**2))  # 48654.563992061871
print(np.sum(np.abs(f)**2))  # 48654.563992061878
</code>```

Finally, don't use rfft to verify Parceval's theorem. The problem with rfft is that it knows the spectrum is symmetric so it skips the negative half. However, this half is missing in the integral (sum). This makes it sound like it should be off by a factor of 2, but this is not the case since the DC (mean) component is retained fully by the rfft (More details can be found here). Better use the normal FFT (fft2) and save you some trouble.

Body:
Currently, I'm considering taking an image and its spectrum. Now Parceval's theorem says that both should have equal energy. However when I try to test this on some images, this doesn't seem to be the case for the numpy real FFT function.

This is the code I'm using for my test:

import numpy as np
from PIL import Image

im = np.array(Image.open('/images/building.jpeg'))
spectral_im = np.fft.rfft2(im, axes = (0,1), norm = 'ortho')

def getNorm(im):
    return np.sum(np.abs(im))

print('Norm of the image: %d' % getNorm(im))
print('Norm of the spectrum of the image: %f' % getNorm(spectral_im))
print('Difference between norms: %f' % (getNorm(im) - getNorm(spectral_im)))

I expected that the difference between the norms would be (approximately) 0 for every image, however it differs by an order of magnitude for every image I have tried. Can anyone see what I'm doing wrong?

With the help from the answers, here is the corrected code (note the extra cast to float64, otherwise they still aren't equal):

import numpy as np
from PIL import Image

im = np.array(Image.open('/images/building.jpeg')).astype('float64')
spectral_im = np.fft.fft2(im, axes = (0,1), norm = 'ortho')

def getNorm(im):
    return np.sum(np.abs(im) ** 2)

print('Norm of the image: %d' % getNorm(im))
print('Norm of the spectrum of the image: %f' % getNorm(spectral_im))
print('Difference between norms: %f' % (getNorm(im) - getNorm(spectral_im)))

Body:
Parceval's Theorem states that the integral over the square of the signal and the fourier transform are the same. So the getNorm function should be defined as

def getNorm(im):
    return np.sum(np.abs(im)**2)

Then there is the FFT normalization issue. You need to normalize the FFT by the image area (product of dimensions):

x = np.random.rand(321, 456)
f = np.fft.fft2(x) / np.sqrt(321 * 456)
print(np.sum(np.abs(x)**2))  # 48654.563992061871
print(np.sum(np.abs(f)**2))  # 48654.563992061878

Finally, don't use rfft to verify Parceval's theorem. The problem with rfft is that it knows the spectrum is symmetric so it skips the negative half. However, this half is missing in the integral (sum). This makes it sound like it should be off by a factor of 2, but this is not the case since the DC (mean) component is retained fully by the rfft (More details can be found here). Better use the normal FFT (fft2) and save you some trouble.


答:
The standard forward FFT has an extra factor of sqrt(N) in it compared to the form used in Parceval's theorem. Taking that into account makes things work as expected:

```<code>x = np.random.rand(200, 100)
f = np.fft.fft2(x)
np.allclose(np.sum(x ** 2),
            np.sum(abs(f) ** 2 / x.size))
# True
</code>```

Title: How to normalize the spectrum of a numpy (real) fourier transform so that parcevals theorem applies?

Body:
The standard forward FFT has an extra factor of sqrt(N) in it compared to the form used in Parceval's theorem. Taking that into account makes things work as expected:

x = np.random.rand(200, 100)
f = np.fft.fft2(x)
np.allclose(np.sum(x ** 2),
            np.sum(abs(f) ** 2 / x.size))
# True


问:
create HDInsight Hadoop Cluster with Data Lake Store
I am new user of azure,i want to connect a data lake with HDinsight,  I followed the instructions on azure documentation, but when i try to chose to connect a created data lake with HDinsight, i have this error Invalid emplacement.
Can you help me please ?

Error hdinsight

答:
Note: Azure HDInsight cluster and the dependent storage(Blob or Data Lake Store) accounts must be in the same Azure location.

For example: If you have Azure HDInsight cluster in East US and Data Lake Store in East US 2, then you will receive Invalid emplacement error.

This article explains how to use the Azure portal to create a HDInsight cluster with an Azure Data Lake Store account as the default storage or an additional storage.


问:
EGit Library on GitHub
I'm really lost on how to be sure that some one uses the correct credentials when logging into GitHub.

https://github.com/eclipse/egit-github/tree/master/org.eclipse.egit.github.core

This is the library I'm trying to use, but when I try to use the .setCredentials() method, it never checks to see if the entered credentials are valid. You can enter a username with any password and allow you through.

My question is, how can I make sure the users password and username match to their GitHub account?

答:
The input credentials will be authenticated only when you make a request to the server. The server will reject the request if the authentication failed, and that will cause a ReqestException "401" at the client.  So, make a query and check the exception, and you will know if the input credentials are correct. For example,

```<code>try {
    GitHubClient client = new GitHubClient().setCredentials(login, password);
    UserService userService = new UserService(client);
    User user = userService.getUser(login);
    ...
} catch (RequestException re) {
    if (re.getMessage().endsWith("Bad credentials (401)")) {
        // input login/password incorrect...
    } else {
        // some other reason...
    }
}
</code>```

Title: EGit Library on GitHub

Body:
The input credentials will be authenticated only when you make a request to the server. The server will reject the request if the authentication failed, and that will cause a ReqestException "401" at the client.  So, make a query and check the exception, and you will know if the input credentials are correct. For example,

try {
    GitHubClient client = new GitHubClient().setCredentials(login, password);
    UserService userService = new UserService(client);
    User user = userService.getUser(login);
    ...
} catch (RequestException re) {
    if (re.getMessage().endsWith("Bad credentials (401)")) {
        // input login/password incorrect...
    } else {
        // some other reason...
    }
}


问:
C# WPF - DragMove window and Click Event
I am building a borderless application. What i need to achieve is to move the window by simply click and drag on an image it contains but i also want to do something when clicked.

Just a button, i have functionality for left and right clicks but can't figure how to implement drag now.
This is what my code looks like

```<code>private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if(e.LeftButton == MouseButtonState.Released)
        {
            toggle();
        }
        else if(e.LeftButton == MouseButtonState.Pressed)
        {
            DragMove();
        }
    }
</code>```

Right now only drag works, If i rearrange their occurrence then only left click would work. Right click functionality is working as expected right now.

答:
Do your thing once the DragMove() method has returned, i.e. when the mouse capture has been released:

```<code>private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        DragMove();
        System.Diagnostics.Debug.Write("some action...");
    }
}
</code>```

Or, if you want to do something before the mouse is captured, you could use a boolean flag:

```<code>private bool _capture;
private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        if (_capture)
        {
            DragMove();
            _capture = false;
        }
        else
        {
            System.Diagnostics.Debug.Write("some action...");

            _capture = true;
            btnHome.RaiseEvent(new MouseButtonEventArgs(e.MouseDevice, e.Timestamp, MouseButton.Left)
            {
                RoutedEvent = MouseDownEvent
            });
        }
    }
}
</code>```

Body:
I am building a borderless application. What i need to achieve is to move the window by simply click and drag on an image it contains but i also want to do something when clicked.

Just a button, i have functionality for left and right clicks but can't figure how to implement drag now.
This is what my code looks like

private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if(e.LeftButton == MouseButtonState.Released)
        {
            toggle();
        }
        else if(e.LeftButton == MouseButtonState.Pressed)
        {
            DragMove();
        }
    }

Right now only drag works, If i rearrange their occurrence then only left click would work. Right click functionality is working as expected right now.

Body:
Do your thing once the DragMove() method has returned, i.e. when the mouse capture has been released:

private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        DragMove();
        System.Diagnostics.Debug.Write("some action...");
    }
}

Or, if you want to do something before the mouse is captured, you could use a boolean flag:

private bool _capture;
private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        if (_capture)
        {
            DragMove();
            _capture = false;
        }
        else
        {
            System.Diagnostics.Debug.Write("some action...");

            _capture = true;
            btnHome.RaiseEvent(new MouseButtonEventArgs(e.MouseDevice, e.Timestamp, MouseButton.Left)
            {
                RoutedEvent = MouseDownEvent
            });
        }
    }
}


答:
Try this:</p>

```<code>this.todoListGroup$ = this.ngrx.select(fromRoot.getTodos)
.flatMap((todos: Todo[]) => {
    console.log(todos)
    this.todos = todos
    this.ngrx.select(fromRoot.getLastChangedTodo);
})
.take(1)
.map(lastTodo =>{{
    console.log(lastTodo)
    doSomething(this.todos, lastTodo)
})
</code>```

Title: ngrx - chain two store.select slices

Body:
Try this:

this.todoListGroup$ = this.ngrx.select(fromRoot.getTodos)
.flatMap((todos: Todo[]) => {
    console.log(todos)
    this.todos = todos
    this.ngrx.select(fromRoot.getLastChangedTodo);
})
.take(1)
.map(lastTodo =>{{
    console.log(lastTodo)
    doSomething(this.todos, lastTodo)
})


问:
TensorFlow : How do i find my output node in my Tensorflow trained model?
I am quite new in using Tensorflow, this is a sample of code that i found while googling. I tried to freeze the graph but it said that i need to input the correct output node. Since i am new to this, i am having a hard time to understand it. How do i find my output node in this code or do i need to freeze the whole graph?</p>

```<code>import tensorflow as tf
import numpy as np
import sys

class Seq2Seq(object):

    def __init__(self, xseq_len, yseq_len,
            xvocab_size, yvocab_size,
            emb_dim, num_layers, ckpt_path,
            lr=0.0001,
            epochs=200, model_name='seq2seq_model'):
        # attach these arguments to self
        self.xseq_len = xseq_len
        self.yseq_len = yseq_len
        self.ckpt_path = ckpt_path
        self.epochs = epochs
        self.model_name = model_name

        # build thy graph
        #  attach any part of the graph that needs to be exposed, to the self
        def __graph__():

            # placeholders
            tf.reset_default_graph()
            #  encoder inputs : list of indices of length xseq_len
            self.enc_ip = [ tf.placeholder(shape=[None,],
                            dtype=tf.int64,
                            name='ei_{}'.format(t)) for t in range(xseq_len) ]

            #  labels that represent the real outputs

            self.labels = [ tf.placeholder(shape=[None,],
                            dtype=tf.int64,
                            name='ei_{}'.format(t)) for t in range(yseq_len) ]

            #  decoder inputs : 'GO' + [ y1, y2, ... y_t-1 ]
            self.dec_ip = [ tf.zeros_like(self.enc_ip[0], dtype=tf.int64, name='GO') ] + self.labels[:-1]

            # Basic LSTM cell wrapped in Dropout Wrapper
            self.keep_prob = tf.placeholder(tf.float32)
            # define the basic cell
            basic_cell = tf.contrib.rnn.core_rnn_cell.DropoutWrapper(
                    tf.contrib.rnn.core_rnn_cell.BasicLSTMCell(emb_dim, state_is_tuple=True),
                    output_keep_prob=self.keep_prob)
            # stack cells together : n layered model
            stacked_lstm = tf.contrib.rnn.core_rnn_cell.MultiRNNCell([basic_cell]*num_layers, state_is_tuple=True)

            # for parameter sharing between training model
            #  and testing model
            with tf.variable_scope('decoder') as scope:
                # build the seq2seq model
                #  inputs : encoder, decoder inputs, LSTM cell type, vocabulary sizes, embedding dimensions
                self.decode_outputs, self.decode_states = tf.contrib.legacy_seq2seq.embedding_rnn_seq2seq(self.enc_ip,self.dec_ip, stacked_lstm,
                                                    xvocab_size, yvocab_size, emb_dim)
                # share parameters
                scope.reuse_variables()
                # testing model, where output of previous timestep is fed as input
                #  to the next timestep
                self.decode_outputs_test, self.decode_states_test = tf.contrib.legacy_seq2seq.embedding_rnn_seq2seq(
                    self.enc_ip, self.dec_ip, stacked_lstm, xvocab_size, yvocab_size,emb_dim,
                    feed_previous=True)

            # now, for training,
            #  build loss function

            # weighted loss
            #  TODO : add parameter hint
            loss_weights = [ tf.ones_like(label, dtype=tf.float32) for label in self.labels ]
            self.loss = tf.contrib.legacy_seq2seq.sequence_loss(self.decode_outputs, self.labels, loss_weights, yvocab_size)
            # train op to minimize the loss
            self.train_op = tf.train.AdamOptimizer(learning_rate=lr).minimize(self.loss)

        sys.stdout.write('<log> Building Graph ')
        # build comput graph
        __graph__()
        sys.stdout.write('</log>')

    '''
        Training and Evaluation

    '''

    # get the feed dictionary
    def get_feed(self, X, Y, keep_prob):
        feed_dict = {self.enc_ip[t]: X[t] for t in range(self.xseq_len)}
        feed_dict.update({self.labels[t]: Y[t] for t in range(self.yseq_len)})
        feed_dict[self.keep_prob] = keep_prob # dropout prob
        return feed_dict

    # run one batch for training
    def train_batch(self, sess, train_batch_gen):
        # get batches
        batchX, batchY = train_batch_gen.__next__()
        # build feed
        feed_dict = self.get_feed(batchX, batchY, keep_prob=0.5)
        _, loss_v = sess.run([self.train_op, self.loss], feed_dict)
        return loss_v

    def eval_step(self, sess, eval_batch_gen):
        # get batches
        batchX, batchY = eval_batch_gen.__next__()
        # build feed
        feed_dict = self.get_feed(batchX, batchY, keep_prob=1.)
        loss_v, dec_op_v = sess.run([self.loss, self.decode_outputs_test], feed_dict)
        # dec_op_v is a list; also need to transpose 0,1 indices
        #  (interchange batch_size and timesteps dimensions
        dec_op_v = np.array(dec_op_v).transpose([1,0,2])
        return loss_v, dec_op_v, batchX, batchY

    # evaluate 'num_batches' batches
    def eval_batches(self, sess, eval_batch_gen, num_batches):
        losses = []
        for i in range(num_batches):
            loss_v, dec_op_v, batchX, batchY = self.eval_step(sess, eval_batch_gen)
            losses.append(loss_v)
        return np.mean(losses)

    # finally the train function that
    #  runs the train_op in a session
    #   evaluates on valid set periodically
    #    prints statistics
    def train(self, train_set, valid_set, sess=None ):

        # we need to save the model periodically
        saver = tf.train.Saver()

        # if no session is given
        if not sess:
            # create a session
            sess = tf.Session()
            # init all variables
            sess.run(tf.global_variables_initializer())

        sys.stdout.write('\n<log> Training started </log>\n')
        # run M epochs
        for i in range(self.epochs):
            try:
                self.train_batch(sess, train_set)
                if i and i% (self.epochs//5) == 0: # TODO : make this tunable by the user
                    # save model to disk
                    saver.save(sess, self.ckpt_path + self.model_name + '.ckpt', global_step=i)
                    # evaluate to get validation loss
                    val_loss = self.eval_batches(sess, valid_set, 16) # TODO : and this
                    # print stats
                    print('\nModel saved to disk at iteration #{}'.format(i))
                    print('val   loss : {0:.6f}'.format(val_loss))
                    sys.stdout.flush()
            except KeyboardInterrupt: # this will most definitely happen, so handle it
                print('Interrupted by user at iteration {}'.format(i))
                self.session = sess
                return sess

    def restore_last_session(self):
        saver = tf.train.Saver()
        # create a session
        sess = tf.Session()
        # get checkpoint state
        ckpt = tf.train.get_checkpoint_state(self.ckpt_path)
        # restore session
        if ckpt and ckpt.model_checkpoint_path:
            saver.restore(sess, ckpt.model_checkpoint_path)
        # return to user
        return sess

    # prediction
    def predict(self, sess, X):
        feed_dict = {self.enc_ip[t]: X[t] for t in range(self.xseq_len)}
        feed_dict[self.keep_prob] = 1.
        dec_op_v = sess.run(self.decode_outputs_test, feed_dict)
        # dec_op_v is a list; also need to transpose 0,1 indices
        #  (interchange batch_size and timesteps dimensions
        dec_op_v = np.array(dec_op_v).transpose([1,0,2])
        # return the index of item with highest probability
        return np.argmax(dec_op_v, axis=2)
</code>```

答:
You first need to read/load your already frozen graph.

```<code>def load_graph(frozen_graph_filename):
    # We load the protobuf file from the disk and parse it to retrieve the
    # unserialized graph_def
    with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())

    # Then, we import the graph_def into a new Graph and return it
    with tf.Graph().as_default() as graph:
        # The name var will prefix every op/nodes in your graph
        # Since we load everything in a new graph, this is not needed
        tf.import_graph_def(graph_def, name="prefix")
    return graph
</code>```

Once you have loaded your already frozen graph, you can print all the operators in your graph like this:

```<code>for op in graph.get_operations():
    print(op.name, op.outputs)
</code>```

Ref: The above code snippet is based on this tutorial.

You can find your output node in the printed output. It should be similar to what was initially set in the tutorial you are following. Once you have found your output node name, you can actually get the tensor like this:

```<code># This line is from my graph where the operator's name is "y_" and the value is ":0 "
y = graph.get_tensor_by_name('prefix/y_:0')
</code>```

Note 1: Variable names in your code might be different from those mentioned here.

Note 2: Working with TensorFlow in the beginning can be overwhelming with all the different methods and properties to take care of. I suggest starting small to get the understanding of TensorFlow and then go ahead with a long example like the one you are following. You might want to go through the tutorial referenced in this answer, try to understand that, and then draw parallels with the sample code you are following.

Body:
I am quite new in using Tensorflow, this is a sample of code that i found while googling. I tried to freeze the graph but it said that i need to input the correct output node. Since i am new to this, i am having a hard time to understand it. How do i find my output node in this code or do i need to freeze the whole graph?

import tensorflow as tf
import numpy as np
import sys

class Seq2Seq(object):

    def __init__(self, xseq_len, yseq_len,
            xvocab_size, yvocab_size,
            emb_dim, num_layers, ckpt_path,
            lr=0.0001,
            epochs=200, model_name='seq2seq_model'):
        # attach these arguments to self
        self.xseq_len = xseq_len
        self.yseq_len = yseq_len
        self.ckpt_path = ckpt_path
        self.epochs = epochs
        self.model_name = model_name

        # build thy graph
        #  attach any part of the graph that needs to be exposed, to the self
        def __graph__():

            # placeholders
            tf.reset_default_graph()
            #  encoder inputs : list of indices of length xseq_len
            self.enc_ip = [ tf.placeholder(shape=[None,],
                            dtype=tf.int64,
                            name='ei_{}'.format(t)) for t in range(xseq_len) ]

            #  labels that represent the real outputs

            self.labels = [ tf.placeholder(shape=[None,],
                            dtype=tf.int64,
                            name='ei_{}'.format(t)) for t in range(yseq_len) ]

            #  decoder inputs : 'GO' + [ y1, y2, ... y_t-1 ]
            self.dec_ip = [ tf.zeros_like(self.enc_ip[0], dtype=tf.int64, name='GO') ] + self.labels[:-1]

            # Basic LSTM cell wrapped in Dropout Wrapper
            self.keep_prob = tf.placeholder(tf.float32)
            # define the basic cell
            basic_cell = tf.contrib.rnn.core_rnn_cell.DropoutWrapper(
                    tf.contrib.rnn.core_rnn_cell.BasicLSTMCell(emb_dim, state_is_tuple=True),
                    output_keep_prob=self.keep_prob)
            # stack cells together : n layered model
            stacked_lstm = tf.contrib.rnn.core_rnn_cell.MultiRNNCell([basic_cell]*num_layers, state_is_tuple=True)

            # for parameter sharing between training model
            #  and testing model
            with tf.variable_scope('decoder') as scope:
                # build the seq2seq model
                #  inputs : encoder, decoder inputs, LSTM cell type, vocabulary sizes, embedding dimensions
                self.decode_outputs, self.decode_states = tf.contrib.legacy_seq2seq.embedding_rnn_seq2seq(self.enc_ip,self.dec_ip, stacked_lstm,
                                                    xvocab_size, yvocab_size, emb_dim)
                # share parameters
                scope.reuse_variables()
                # testing model, where output of previous timestep is fed as input
                #  to the next timestep
                self.decode_outputs_test, self.decode_states_test = tf.contrib.legacy_seq2seq.embedding_rnn_seq2seq(
                    self.enc_ip, self.dec_ip, stacked_lstm, xvocab_size, yvocab_size,emb_dim,
                    feed_previous=True)

            # now, for training,
            #  build loss function

            # weighted loss
            #  TODO : add parameter hint
            loss_weights = [ tf.ones_like(label, dtype=tf.float32) for label in self.labels ]
            self.loss = tf.contrib.legacy_seq2seq.sequence_loss(self.decode_outputs, self.labels, loss_weights, yvocab_size)
            # train op to minimize the loss
            self.train_op = tf.train.AdamOptimizer(learning_rate=lr).minimize(self.loss)

        sys.stdout.write('<log> Building Graph ')
        # build comput graph
        __graph__()
        sys.stdout.write('</log>')

    '''
        Training and Evaluation

    '''

    # get the feed dictionary
    def get_feed(self, X, Y, keep_prob):
        feed_dict = {self.enc_ip[t]: X[t] for t in range(self.xseq_len)}
        feed_dict.update({self.labels[t]: Y[t] for t in range(self.yseq_len)})
        feed_dict[self.keep_prob] = keep_prob # dropout prob
        return feed_dict

    # run one batch for training
    def train_batch(self, sess, train_batch_gen):
        # get batches
        batchX, batchY = train_batch_gen.__next__()
        # build feed
        feed_dict = self.get_feed(batchX, batchY, keep_prob=0.5)
        _, loss_v = sess.run([self.train_op, self.loss], feed_dict)
        return loss_v

    def eval_step(self, sess, eval_batch_gen):
        # get batches
        batchX, batchY = eval_batch_gen.__next__()
        # build feed
        feed_dict = self.get_feed(batchX, batchY, keep_prob=1.)
        loss_v, dec_op_v = sess.run([self.loss, self.decode_outputs_test], feed_dict)
        # dec_op_v is a list; also need to transpose 0,1 indices
        #  (interchange batch_size and timesteps dimensions
        dec_op_v = np.array(dec_op_v).transpose([1,0,2])
        return loss_v, dec_op_v, batchX, batchY

    # evaluate 'num_batches' batches
    def eval_batches(self, sess, eval_batch_gen, num_batches):
        losses = []
        for i in range(num_batches):
            loss_v, dec_op_v, batchX, batchY = self.eval_step(sess, eval_batch_gen)
            losses.append(loss_v)
        return np.mean(losses)

    # finally the train function that
    #  runs the train_op in a session
    #   evaluates on valid set periodically
    #    prints statistics
    def train(self, train_set, valid_set, sess=None ):

        # we need to save the model periodically
        saver = tf.train.Saver()

        # if no session is given
        if not sess:
            # create a session
            sess = tf.Session()
            # init all variables
            sess.run(tf.global_variables_initializer())

        sys.stdout.write('\n<log> Training started </log>\n')
        # run M epochs
        for i in range(self.epochs):
            try:
                self.train_batch(sess, train_set)
                if i and i% (self.epochs//5) == 0: # TODO : make this tunable by the user
                    # save model to disk
                    saver.save(sess, self.ckpt_path + self.model_name + '.ckpt', global_step=i)
                    # evaluate to get validation loss
                    val_loss = self.eval_batches(sess, valid_set, 16) # TODO : and this
                    # print stats
                    print('\nModel saved to disk at iteration #{}'.format(i))
                    print('val   loss : {0:.6f}'.format(val_loss))
                    sys.stdout.flush()
            except KeyboardInterrupt: # this will most definitely happen, so handle it
                print('Interrupted by user at iteration {}'.format(i))
                self.session = sess
                return sess

    def restore_last_session(self):
        saver = tf.train.Saver()
        # create a session
        sess = tf.Session()
        # get checkpoint state
        ckpt = tf.train.get_checkpoint_state(self.ckpt_path)
        # restore session
        if ckpt and ckpt.model_checkpoint_path:
            saver.restore(sess, ckpt.model_checkpoint_path)
        # return to user
        return sess

    # prediction
    def predict(self, sess, X):
        feed_dict = {self.enc_ip[t]: X[t] for t in range(self.xseq_len)}
        feed_dict[self.keep_prob] = 1.
        dec_op_v = sess.run(self.decode_outputs_test, feed_dict)
        # dec_op_v is a list; also need to transpose 0,1 indices
        #  (interchange batch_size and timesteps dimensions
        dec_op_v = np.array(dec_op_v).transpose([1,0,2])
        # return the index of item with highest probability
        return np.argmax(dec_op_v, axis=2)

Body:
You first need to read/load your already frozen graph.

def load_graph(frozen_graph_filename):
    # We load the protobuf file from the disk and parse it to retrieve the
    # unserialized graph_def
    with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())

    # Then, we import the graph_def into a new Graph and return it
    with tf.Graph().as_default() as graph:
        # The name var will prefix every op/nodes in your graph
        # Since we load everything in a new graph, this is not needed
        tf.import_graph_def(graph_def, name="prefix")
    return graph

Once you have loaded your already frozen graph, you can print all the operators in your graph like this:

for op in graph.get_operations():
    print(op.name, op.outputs)

Ref: The above code snippet is based on this tutorial.

You can find your output node in the printed output. It should be similar to what was initially set in the tutorial you are following. Once you have found your output node name, you can actually get the tensor like this:

# This line is from my graph where the operator's name is "y_" and the value is ":0 "
y = graph.get_tensor_by_name('prefix/y_:0')

Note 1: Variable names in your code might be different from those mentioned here.

Note 2: Working with TensorFlow in the beginning can be overwhelming with all the different methods and properties to take care of. I suggest starting small to get the understanding of TensorFlow and then go ahead with a long example like the one you are following. You might want to go through the tutorial referenced in this answer, try to understand that, and then draw parallels with the sample code you are following.


问:
Ruby on Rails call an action I created
I have in my User view Index page a button_to tag as follows:

<%= button_to "Make Admin", :action => :make_admin :user => user %>

In the User controller i have:

def make_admin

    @user = User.find(params[:id])

    @changed_user.role = 3

    @changed_user.save

end

I get a message about bad routing, but since I'm not interested in changing the view until after the action I don't know how to route this action. Where have i gone wrong?

答:
You need to name the path in your routes:

```<code># routes.rb
get 'your_path' => 'user#make_admin, :as => 'make_admin' # can use post too
</code>```

```<code># controller
def make_admin
  # logic to make an admin
  redirect_to(some_other_path, :notice => 'User was made an admin')
end
</code>```

then, in your view,

```<code>button_to 'make admin', make_admin_path
</code>```

You might also want to make the call remotely, but you'll need to post another question with more information in that sense

Title: Ruby on Rails call an action I created

Body:
You need to name the path in your routes:

# routes.rb
get 'your_path' => 'user#make_admin, :as => 'make_admin' # can use post too

# controller
def make_admin
  # logic to make an admin
  redirect_to(some_other_path, :notice => 'User was made an admin')
end

then, in your view,

button_to 'make admin', make_admin_path

You might also want to make the call remotely, but you'll need to post another question with more information in that sense


问:
Is it possible to add border and background to post grids? [Wordpress]
I would like to add some border and background to my post grids to which they will be fit to my website look. Is that possible? The default one is;

Default

And
I want to make like this

Thanks!

My website is; BattlegroundsTurkiye.com

答: You could inspect the element and add custom CSS.


问:
Why is the Twitch API giving me an undocumented HTTP 404 error on Check User Subscription By Channel?
When trying to check whether a user is subscribed to a particular channel using the Twitch API v5, I'm getting an HTTP 404 response from the twitch server. According to the documentation  that should not happen in v5. v3 used to respond with an http 404 if the user wasn't subscribed but v5 should always respond with a json payload. If the user is not subscribed said payload would have a "status" field with value 404.

I am using the URL provided by twitch's documentation: https://api.twitch.tv/kraken/users/012345678/subscriptions/876543210

I am correctly connectiong to twitch since the API requests performed immediately before this one to get authorization from the user and their userid all work.

I have tested this both with users that are and users that aren't subscribed to the channel in question; both cause the same reaction.

The access token used to authorize the operation has scopes user_subscription and user_read.

In which situations does the twitch API respond like this?

Below is the code that is producing this problem:

```<code>twitchRequest = WebRequest.Create("https://api.twitch.tv/kraken/users/" + userId + "/subscriptions/" + DB.GetCode("TwitchChannelId"));
twitchRequest.Method = "GET";
twitchRequest.Headers.Add("Authorization: OAuth " + accessToken);
twitchRequest.Headers.Add("Client-ID: " + DB.GetCode("TwitchClientId"))
//this throws a System.Net.WebException
//The remote server returned an error: (404) Not Found.
twitchResponse = twitchRequest.GetResponse();
</code>```

答:
You're requesting the default v3 of the API, which uses usernames instead of IDs. To use v5, add</p>

```<code>twitchRequest.Headers.Add("Accept: application/vnd.twitchtv.v5+json");
</code>```

Body:
When trying to check whether a user is subscribed to a particular channel using the Twitch API v5, I'm getting an HTTP 404 response from the twitch server. According to the documentation  that should not happen in v5. v3 used to respond with an http 404 if the user wasn't subscribed but v5 should always respond with a json payload. If the user is not subscribed said payload would have a "status" field with value 404.

I am using the URL provided by twitch's documentation: https://api.twitch.tv/kraken/users/012345678/subscriptions/876543210

I am correctly connectiong to twitch since the API requests performed immediately before this one to get authorization from the user and their userid all work.

I have tested this both with users that are and users that aren't subscribed to the channel in question; both cause the same reaction.

The access token used to authorize the operation has scopes user_subscription and user_read.

In which situations does the twitch API respond like this?

Below is the code that is producing this problem:

twitchRequest = WebRequest.Create("https://api.twitch.tv/kraken/users/" + userId + "/subscriptions/" + DB.GetCode("TwitchChannelId"));
twitchRequest.Method = "GET";
twitchRequest.Headers.Add("Authorization: OAuth " + accessToken);
twitchRequest.Headers.Add("Client-ID: " + DB.GetCode("TwitchClientId"))
//this throws a System.Net.WebException
//The remote server returned an error: (404) Not Found.
twitchResponse = twitchRequest.GetResponse();

Body:
You're requesting the default v3 of the API, which uses usernames instead of IDs. To use v5, add

twitchRequest.Headers.Add("Accept: application/vnd.twitchtv.v5+json");


问:
read external coordinates of a converged force directed graph in d3.js v4
I am using Mike Bostock's example here: https://bl.ocks.org/mbostock/4062045

The html was modified to export the nodes and links in a json file. Unfortunately I cannot upload the whole file but here are some example lines:

```<code>{"nodes":[
{"id":"Myriel","group":1,"index":0,"x":791.0400812247225, "y":533.3621312414037,vy":-2.3537711995332984,"vx":-4.361299434636218},
{"id":"Napoleon","group":1,"index":1,"x":761.1221752922569, "y":563.7517203508193,"vy":-2.3317798484016428,"vx":-4.346736342960801},
.
.
.
"links":[{
  "source":
    {"id":"Napoleon","group":1,"index":1,"x":761.1221752922569, "y":563.7517203508193,"vy":-2.3317798484016428,"vx":-4.346736342960801},
  "target":
    {"id":"Myriel","group":1,"index":0,"x":791.0400812247225, "y":533.3621312414037,"vy":-2.3537711995332984,"vx":-4.361299434636218},
  "value":1,"index":0},
    .
    .
    .
</code>```

What I would like to do is read the nodes and links in another html file and just display it.

I thought this should be rather straight forward by replacing the input file miserables.json file with xy_miserables.json. The first thing I noted is that the nodes are not connected to the links, the second thing was that the nodes drifted apart but the links remained fixed. I was able to change the simulation parameters so the nodes stay close to their original position. But how am I going to connect the links to their nodes?
Here is the html content:

```<code><script>
 var svg = d3.select("svg"),
  width = +svg.attr("width"),
  height = +svg.attr("height");

  var color = d3.scaleOrdinal(d3.schemeCategory20);

  var simulation = d3.forceSimulation()
      .force("link", d3.forceLink().id(function(d) { return d.id; }));
    //.force("charge", d3.forceManyBody())
    //.force("center", d3.forceCenter(width / 2, height / 2));

d3.json("./xy_miserables.json", function(error, graph) {
   if (error) throw error;

   link = svg.append("g")
        .attr("class", "links")
        .selectAll("line")
        .data(graph.links)
        .enter().append("line")
        .attr("stroke-width", function(d) { return Math.sqrt(d.value); });

   node = svg.append("g")
      .attr("class", "nodes")
      .selectAll("circle")
      .data(graph.nodes)
      .enter().append("circle")
        .attr("r", 5)
        .attr("fill", function(d) { return color(d.group); })
        .attr("x", function(d) {return d.x})
        .attr("y", function(d) {return d.y});

console.log(graph.links)

simulation.force("link")
  .links(graph.links);

simulation
  .nodes(graph.nodes)
  .on("tick", ticked);

 function ticked() {
   link
    .attr("x1", function(d) { return d.source.x; })
    .attr("y1", function(d) { return d.source.y; })
    .attr("x2", function(d) { return d.target.x; })
    .attr("y2", function(d) { return d.target.y; });

   node
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; });
 }
});
</script>
</code>```

I confirmed that the links have the proper source ids and target ids defined. I compared the link info with the original data and it seems fine.
What am I forgetting here?

Thank you very much in advance,
Markus

答:
After some testing I realized that the issue lies with my exported xyz file I am trying to read in. I started out with the miserables.json file and added systematically node and link properties. As it turns out none of the link properties are required. This is the final solution to my json file:

```<code>{
  "nodes": [
    {"id": "1", "property1": "propert1", "property2": "property2", "property3": "property3", "x": "999.772419601515",  "y": "597.0467800520148",  "vx": "0",  "vy": "0",  "fx": "999.772419601515",  "fy": "597.0467800520148"},
    {"id": "2", "property1": "propert1", "property2": "property2", "property3": "property3", "x": "999.772419601515",  "y": "597.0467800520148",  "vx": "0",  "vy": "0",  "fx": "999.772419601515",  "fy": "597.0467800520148"},....],
"links": [
    {"source": "1", "target": "2, "value": 1},
    {"source": "1", "target": "3", "value": 1},....]
}
</code>```

Now my links are connected to the nodes.
Cheers,
Markus

Body:
I am using Mike Bostock's example here: https://bl.ocks.org/mbostock/4062045

The html was modified to export the nodes and links in a json file. Unfortunately I cannot upload the whole file but here are some example lines:

{"nodes":[
{"id":"Myriel","group":1,"index":0,"x":791.0400812247225, "y":533.3621312414037,vy":-2.3537711995332984,"vx":-4.361299434636218},
{"id":"Napoleon","group":1,"index":1,"x":761.1221752922569, "y":563.7517203508193,"vy":-2.3317798484016428,"vx":-4.346736342960801},
.
.
.
"links":[{
  "source":
    {"id":"Napoleon","group":1,"index":1,"x":761.1221752922569, "y":563.7517203508193,"vy":-2.3317798484016428,"vx":-4.346736342960801},
  "target":
    {"id":"Myriel","group":1,"index":0,"x":791.0400812247225, "y":533.3621312414037,"vy":-2.3537711995332984,"vx":-4.361299434636218},
  "value":1,"index":0},
    .
    .
    .

What I would like to do is read the nodes and links in another html file and just display it.

I thought this should be rather straight forward by replacing the input file miserables.json file with xy_miserables.json. The first thing I noted is that the nodes are not connected to the links, the second thing was that the nodes drifted apart but the links remained fixed. I was able to change the simulation parameters so the nodes stay close to their original position. But how am I going to connect the links to their nodes?
Here is the html content:

I confirmed that the links have the proper source ids and target ids defined. I compared the link info with the original data and it seems fine.
What am I forgetting here?

Thank you very much in advance,
Markus

Body:
After some testing I realized that the issue lies with my exported xyz file I am trying to read in. I started out with the miserables.json file and added systematically node and link properties. As it turns out none of the link properties are required. This is the final solution to my json file:

{
  "nodes": [
    {"id": "1", "property1": "propert1", "property2": "property2", "property3": "property3", "x": "999.772419601515",  "y": "597.0467800520148",  "vx": "0",  "vy": "0",  "fx": "999.772419601515",  "fy": "597.0467800520148"},
    {"id": "2", "property1": "propert1", "property2": "property2", "property3": "property3", "x": "999.772419601515",  "y": "597.0467800520148",  "vx": "0",  "vy": "0",  "fx": "999.772419601515",  "fy": "597.0467800520148"},....],
"links": [
    {"source": "1", "target": "2, "value": 1},
    {"source": "1", "target": "3", "value": 1},....]
}

Now my links are connected to the nodes.
Cheers,
Markus


答:
Separate the child and parent divs so they're both positioned relative to a common "container" then update your logic to position the child accordingly and set the z-index property of each.

.container {
  position:relative;
  background-color:grey;
  width: 500px;
  height: 500px;
}

.parent {
  background-color:blue;
  position:absolute;
  top: 50px;
  left: 10px;
  height: 100px;
  width: 100px;
  border-radius: 100%;
  z-index:2;
}
.child {
  position:absolute;
  top:50px;
  left: 90px;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  background-color:red;
  z-index:1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="parent">
  </div>
  <div class="child">
  </div>
</div></code>```

Title: Make absolute positioned parent appear on top of absolute positioned child

Body:
I'm trying to make an absolute positioned child appear behind its absolute positioned parent. The blue parent should appear above red child.

I tried setting z-index: -1 on the child, but that makes red child not visible.

.container {
  position:relative;
  background-color:grey;
  width: 500px;
  height: 500px;
}
.parent {
  background-color:blue;
  position:absolute;
  top: 50px;
  left: 10px;
  height: 100px;
  width: 100px;
  border-radius: 100%;
}
.child {
  position:absolute;
  top:-5px;
  right: 0px;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  background-color:red;
}

https://jsfiddle.net/dwil30/mh3qw64x/

Body:
Separate the child and parent divs so they're both positioned relative to a common "container" then update your logic to position the child accordingly and set the z-index property of each.

.container {
  position:relative;
  background-color:grey;
  width: 500px;
  height: 500px;
}

.parent {
  background-color:blue;
  position:absolute;
  top: 50px;
  left: 10px;
  height: 100px;
  width: 100px;
  border-radius: 100%;
  z-index:2;
}
.child {
  position:absolute;
  top:50px;
  left: 90px;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  background-color:red;
  z-index:1;
}

<div class="container">
  <div class="parent">
  </div>
  <div class="child">
  </div>
</div>


问:
setTimeout pass parameter in for loop
I created an array. I want to send ajax request with settimeout. But I can't get parameter in settimeout. When I print console log variable i is undefined. How can I solve this problem?

Console Log result

```<code>i undefined
</code>```

Javascript Code

```<code>$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (var i = 0; i < $scope.type.length; i++) {
    setTimeout(function (i) {
        console.log("i", i);
        $scope.params = {
            lat: $scope.lat,
            lng: $scope.lng,
            time: $scope.time,
            type: $scope.type[i]
        }
        console.log("params", $scope.params);
        return;
        $.ajax({
            type: 'post',
            url: "bz.php",
            dataType: 'json',
            async: true,
            cache: false,
            data: $scope.params,
            success: function (data) {
                if (data.response) {
                    console.log("data.response", data.response);
                    return;
                    if (!$scope.$$phase) $scope.$apply();
                } else if (data.response == null) {

                } else if (data.error) {

                }
            },
            error: function (data) {
            }
        });
    }.bind(this), i * 2000);
}
</code>```

答:
Add i as the third argument of setTimeout to encapsulate it:</p>

```<code>setTimeout(function(i){ // <--  ... and retrieved here again
   console.log(i);
}, i * 2000, i);// <--- i is stored here ...
</code>```

Title: setTimeout pass parameter in for loop

Body:
I created an array. I want to send ajax request with settimeout. But I can't get parameter in settimeout. When I print console log variable i is undefined. How can I solve this problem?

Console Log result

i undefined

Javascript Code

$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (var i = 0; i < $scope.type.length; i++) {
    setTimeout(function (i) {
        console.log("i", i);
        $scope.params = {
            lat: $scope.lat,
            lng: $scope.lng,
            time: $scope.time,
            type: $scope.type[i]
        }
        console.log("params", $scope.params);
        return;
        $.ajax({
            type: 'post',
            url: "bz.php",
            dataType: 'json',
            async: true,
            cache: false,
            data: $scope.params,
            success: function (data) {
                if (data.response) {
                    console.log("data.response", data.response);
                    return;
                    if (!$scope.$$phase) $scope.$apply();
                } else if (data.response == null) {

                } else if (data.error) {

                }
            },
            error: function (data) {
            }
        });
    }.bind(this), i * 2000);
}

Body:
Add i as the third argument of setTimeout to encapsulate it:

setTimeout(function(i){ // <--  ... and retrieved here again
   console.log(i);
}, i * 2000, i);// <--- i is stored here ...


问:
aws lambda js unit testing
I've been looking into aws lambda. How are people testing the harness for api gateway requests responses? In Java I have a lambda that's a bit like this.

```<code>import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
...
@Test
void turnsBarToFooTest() {

    TestContext ctx = new TestContext(); //implements  com.amazonaws.services.lambda.runtime.Context

    Fooer handler = new Fooer();

    APIGatewayProxyRequestEvent request = new APIGatewayProxyRequestEvent();
    Map<String, String> params = HashMap.of("thing_to_foo", "bar");
    request.setPathParameters(params.toJavaMap());

    APIGatewayProxyResponseEvent response = handler.handleRequest(request, ctx);
    assertEquals(200, response.getStatusCode().intValue());
    assertEquals("foo", response.getBody());
}
</code>```

I'd love to do something really simple with Jest and ES6 to replicate the above. Are there similar known events objects to use? How can I wire them up with jest.

答:
I made function for adding security headers based on Host header in Lambda for CloudFront. For testing I used JEST and basically mocked objects in AWS like this.

google.test.js:

```<code>const handler = require('../../src/functions/google').handler;
const testEventGenerator = require('./cloudfront-event-template-generator');

test('it adds xss protection', () => {
  const event = testEventGenerator();
  const callback = jest.fn();
  handler(event, {}, callback);
  expect(event.Records[0].cf.response.headers['x-xss-protection'][0].key).toBe('X-XSS-Protection');
  expect(event.Records[0].cf.response.headers['x-xss-protection'][0].value).toBe('1; mode=block');
  expect(callback.mock.calls.length).toBe(1);
});
</code>```

cloudfront-event-template-generator.js:

```<code>module.exports = () => ({
  Records: [
    {
      cf: {
        config: {
          distributionId: 'EXAMPLE'
        },
        request: {
          headers: {
            host: [
              {
                key: 'host',
                value: 'www.google.com'
              }
            ]
          }
        },
        response: {
          status: 200,
          headers: {
            'last-modified': [
              {
                key: 'Last-Modified',
                value: '2016-11-25'
              }
            ],
            vary: [
              {
                key: 'Vary',
                value: '*'
              }
            ],
            'x-amz-meta-last-modified': [
              {
                key: 'X-Amz-Meta-Last-Modified',
                value: '2016-01-01'
              }
            ]
          },
          statusDescription: 'OK'
        }
      }
    }
  ]
});
</code>```

Title: aws lambda js unit testing

Body:
I've been looking into aws lambda. How are people testing the harness for api gateway requests responses? In Java I have a lambda that's a bit like this.

import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
...
@Test
void turnsBarToFooTest() {

    TestContext ctx = new TestContext(); //implements  com.amazonaws.services.lambda.runtime.Context

    Fooer handler = new Fooer();

    APIGatewayProxyRequestEvent request = new APIGatewayProxyRequestEvent();
    Map<String, String> params = HashMap.of("thing_to_foo", "bar");
    request.setPathParameters(params.toJavaMap());

    APIGatewayProxyResponseEvent response = handler.handleRequest(request, ctx);
    assertEquals(200, response.getStatusCode().intValue());
    assertEquals("foo", response.getBody());
}

I'd love to do something really simple with Jest and ES6 to replicate the above. Are there similar known events objects to use? How can I wire them up with jest.

Body:
I made function for adding security headers based on Host header in Lambda for CloudFront. For testing I used JEST and basically mocked objects in AWS like this.

google.test.js:

const handler = require('../../src/functions/google').handler;
const testEventGenerator = require('./cloudfront-event-template-generator');

test('it adds xss protection', () => {
  const event = testEventGenerator();
  const callback = jest.fn();
  handler(event, {}, callback);
  expect(event.Records[0].cf.response.headers['x-xss-protection'][0].key).toBe('X-XSS-Protection');
  expect(event.Records[0].cf.response.headers['x-xss-protection'][0].value).toBe('1; mode=block');
  expect(callback.mock.calls.length).toBe(1);
});

cloudfront-event-template-generator.js:

module.exports = () => ({
  Records: [
    {
      cf: {
        config: {
          distributionId: 'EXAMPLE'
        },
        request: {
          headers: {
            host: [
              {
                key: 'host',
                value: 'www.google.com'
              }
            ]
          }
        },
        response: {
          status: 200,
          headers: {
            'last-modified': [
              {
                key: 'Last-Modified',
                value: '2016-11-25'
              }
            ],
            vary: [
              {
                key: 'Vary',
                value: '*'
              }
            ],
            'x-amz-meta-last-modified': [
              {
                key: 'X-Amz-Meta-Last-Modified',
                value: '2016-01-01'
              }
            ]
          },
          statusDescription: 'OK'
        }
      }
    }
  ]
});


问:
Date picker and time picker not working properly (https://material-ui-next.com/demos/pickers/)
Date picker and time picker not working properly. On desktop the calendar pop up won't show at all, work only in mobile. on Firefox, not show anything.

https://material-ui-next.com/demos/pickers/

Material-UI 1.0 beta.18

答: This pickers are native browser implementation, so for the any os, any device it would be different, somewhere they doesnt implemented at all. So I suggest you use some libriry that implements that pickers for you. One of them (really awesome one) is material-ui-pickers</p>