问:
Wait for signal, then continue execution
I am trying to make a program that suspends its execution until a signal arrives. Then, after the signal arrives I just want my code to continue its execution from where it was. I don't want it to execute a function handler or whatsoever. Is there a simple way of doing this? I have been struggling for a week or so, reading here and there, and didn't manage to get a fully operative code.

In particular, I want the main program to create a thread that waits for some particular event to happen (e.g., a user has input some data to stdin). Meanwhile, the main program is doing something but at some point it suspends its execution until it receives a signal.

The signal may come from the thread because it has detected the event or it may be due to a timeout because I don't want it to wait for ever.

I have made some code but it does not work as expected...

```<code>/*
 * This code SHOULD start a thread that gets messages from stdin.
 *  If the message is a "quit", the thread exits. Otherwise it raises
 *  a signal that should be caught by the main program.
 *  The main program simply waits for the message unless a timer of
 *  5.5 seconds expires before receiving the signal from the thread.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/time.h>
#include <signal.h>

#define BSIZE 100   /* Buffer size */

sigset_t mask;
pthread_t tid;
//struct itimerval timervalue;

int milisec = 5500; /* Timeout: 5,5 seconds */
int end = 0;

char buffer[BSIZE];

//Function prototypes
void init(void);
void * thread_job(void *);
void message_rcvd(void);
void wait_for_message_or_timeout(void);
int start_timer(struct itimerval, int);
int stop_timer(struct itimerval);
void on_signal(int);

// MAIN: Wait for message or timeout
int main(int argc, char ** argv) {

    init();

    while(!end){
        wait_for_message_or_timeout();
        if(!end)
            printf("Message received [%s]\n", buffer);
    }

    return 0;
}

// INIT: Initializes the signals that the program will wait for
//       and creates a thread that will eventually generate a signal
void init()
{

    /* Init the signals I want to wait for with sigwait() */
    sigemptyset(&mask);
    sigaddset(&mask, SIGUSR1);
    sigaddset(&mask, SIGALRM);
    sigprocmask(SIG_BLOCK, &mask, NULL);

    //signal(SIGUSR1, SIG_IGN);
    signal(SIGUSR1, on_signal);

    /* Create the thread and put it to work */
    pthread_t tid;
    pthread_create(&tid, NULL, thread_job, NULL);

}

void on_signal(int signum){
    printf("on_signal\n");
}

// THREAD CODE -------------
// THREAD JOB: When the user inputs a message, it passes the message
//              to the main thread by invoking message_rcvd()
void * thread_job(){

    int end = 0;

    while(!end){
        printf("Input message:");
        if (fgets(buffer, BSIZE, stdin) != NULL)
            message_rcvd();
    }
}

// MESSAGE RECEIVED: If message is not equal to "quit" raise a signal
void message_rcvd(){

    if(strcmp(buffer, "quit") == 0){
        exit(0);
    }else{
        printf("Going to raise SIGUSR1...");
        if(raise(SIGUSR1) == 0)
            printf("raised!\n");
    }

}

// WAIT: Should wait for signal SIGUSR1 for some time
void wait_for_message_or_timeout(){

    int sigid;
    struct itimerval t;

    /* Set a timer to prevent waiting for ever*/
    printf("Setting timer...\n");
    start_timer(t, milisec);

    /* Put the process to wait until signal arrives */
    sigwait(&mask, &sigid);

    switch(sigid){
        case SIGUSR1:
                printf("Received SIGUSR1: Message avaible!\n");
                break;
        case SIGALRM:
                printf("Received SIGALRM: Timeout\n");
                end = 1;
                break;
        default:
                printf("Unknown signal received\n");
                break;
    }

    printf("Stopping timer...\n");
    /* Stop timer */
    stop_timer(t);
}

// START TIMER: I don't want the timer to cause the execution
//              of a handler function
int start_timer(struct itimerval timervalue, int msec)
//int start_timer(int msec)
{

  timervalue.it_interval.tv_sec = msec / 1000;
  timervalue.it_interval.tv_usec = (msec % 1000) * 1000;
  timervalue.it_value.tv_sec = msec / 1000;
  timervalue.it_value.tv_usec = (msec % 1000) * 1000;

  if(setitimer(ITIMER_REAL, &timervalue, NULL))
  {
    printf("\nsetitimer() error\n");
    return(-1);
  }
  return(0);
}

// STOP TIMER:
int stop_timer(struct itimerval timervalue)
//int stop_timer()
{
  timervalue.it_interval.tv_sec = 0;
  timervalue.it_interval.tv_usec = 0;
  timervalue.it_value.tv_sec = 0;
  timervalue.it_value.tv_usec = 0;

  if(setitimer(ITIMER_REAL, &timervalue, NULL))
  {
    printf("\nsetitimer() error\n");
    return(-1);
  }
  return(0);

}
</code>```

Here is a typical execution of this code.

```<code>./signaltest
Setting timer...
Input message:hello
Going to raise SIGUSR1...raised!
Input message:friend
Going to raise SIGUSR1...raised!
Input message:Received SIGALRM: Timeout
Stopping timer...
</code>```

As you can see, the signal SIGUSR1 is being raised and sigwait is being unblocked. However, the code seems does not continue after the signal has been raised. (Note that I don't need a signal handler but I just added for the debugging purposes. I have blocked its execution with sigprocmask)

Why is SIGUSR1 unblocking sigwait but the execution does not continue from there? Is there a way to make it continue after unblocking? This seems to work for SIGALRM but why not for SIGUSR1?

As I said, I have been looking at tons of stackoverflow questions, online howto's, tried with different system calls (e.g., pause, sigsuspend), ... but couldn't find a way to solve this :-(

If you are wondering why I am not doing this code much simpler by not using a thread is because this is not actually the code I am implementing but just a simpler example to make my question more clear. I am actually trying to implement a network protocol API, similar to the sockets API for my own protocol.

Thanks in advance

答:
The SIGUSR1 signal isn't going where you think it is.

In a multithreaded program, the raise function sends a signal to the current thread, which is the thread_job thread in this case.  So the main thread never sees the signal.

You need to save off thread ID of the main thread, then use pthread_kill to send a signal to that thread.

Add a new global:

```<code>pthread_t main_tid;
</code>```

Then populate it in your init function before starting the new thread:

```<code>void init()
{
    main_tid = pthread_self();
    ...
</code>```

Then in message_rcvd, use pthread_kill:

```<code>    if(pthread_kill(main_tid, SIGUSR1) == 0)
        printf("raised!\n");
</code>```

Also, remove the definition of end in thread_job, and remove the definition of tid in init.  These definitions mask the global variables of the same name.

Sample output:

Setting timer...
Input message:hello
Going to raise SIGUSR1...raised!
Input message:Received SIGUSR1: Message avaible!
Stopping timer...
Message received [hello
]
Setting timer...
test
Going to raise SIGUSR1...raised!
Input message:Received SIGUSR1: Message avaible!
Stopping timer...
Message received [test
]
Setting timer...
Received SIGALRM: Timeout
Stopping timer...
```

Body:
I am trying to make a program that suspends its execution until a signal arrives. Then, after the signal arrives I just want my code to continue its execution from where it was. I don't want it to execute a function handler or whatsoever. Is there a simple way of doing this? I have been struggling for a week or so, reading here and there, and didn't manage to get a fully operative code.

In particular, I want the main program to create a thread that waits for some particular event to happen (e.g., a user has input some data to stdin). Meanwhile, the main program is doing something but at some point it suspends its execution until it receives a signal.

The signal may come from the thread because it has detected the event or it may be due to a timeout because I don't want it to wait for ever.

I have made some code but it does not work as expected...

/*
 * This code SHOULD start a thread that gets messages from stdin.
 *  If the message is a "quit", the thread exits. Otherwise it raises
 *  a signal that should be caught by the main program.
 *  The main program simply waits for the message unless a timer of
 *  5.5 seconds expires before receiving the signal from the thread.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/time.h>
#include <signal.h>

#define BSIZE 100   /* Buffer size */

sigset_t mask;
pthread_t tid;
//struct itimerval timervalue;

int milisec = 5500; /* Timeout: 5,5 seconds */
int end = 0;

char buffer[BSIZE];

//Function prototypes
void init(void);
void * thread_job(void *);
void message_rcvd(void);
void wait_for_message_or_timeout(void);
int start_timer(struct itimerval, int);
int stop_timer(struct itimerval);
void on_signal(int);

// MAIN: Wait for message or timeout
int main(int argc, char ** argv) {

    init();

    while(!end){
        wait_for_message_or_timeout();
        if(!end)
            printf("Message received [%s]\n", buffer);
    }

    return 0;
}

// INIT: Initializes the signals that the program will wait for
//       and creates a thread that will eventually generate a signal
void init()
{

    /* Init the signals I want to wait for with sigwait() */
    sigemptyset(&mask);
    sigaddset(&mask, SIGUSR1);
    sigaddset(&mask, SIGALRM);
    sigprocmask(SIG_BLOCK, &mask, NULL);

    //signal(SIGUSR1, SIG_IGN);
    signal(SIGUSR1, on_signal);

    /* Create the thread and put it to work */
    pthread_t tid;
    pthread_create(&tid, NULL, thread_job, NULL);

}

void on_signal(int signum){
    printf("on_signal\n");
}

// THREAD CODE -------------
// THREAD JOB: When the user inputs a message, it passes the message
//              to the main thread by invoking message_rcvd()
void * thread_job(){

    int end = 0;

    while(!end){
        printf("Input message:");
        if (fgets(buffer, BSIZE, stdin) != NULL)
            message_rcvd();
    }
}

// MESSAGE RECEIVED: If message is not equal to "quit" raise a signal
void message_rcvd(){

    if(strcmp(buffer, "quit") == 0){
        exit(0);
    }else{
        printf("Going to raise SIGUSR1...");
        if(raise(SIGUSR1) == 0)
            printf("raised!\n");
    }

}

// WAIT: Should wait for signal SIGUSR1 for some time
void wait_for_message_or_timeout(){

    int sigid;
    struct itimerval t;

    /* Set a timer to prevent waiting for ever*/
    printf("Setting timer...\n");
    start_timer(t, milisec);

    /* Put the process to wait until signal arrives */
    sigwait(&mask, &sigid);

    switch(sigid){
        case SIGUSR1:
                printf("Received SIGUSR1: Message avaible!\n");
                break;
        case SIGALRM:
                printf("Received SIGALRM: Timeout\n");
                end = 1;
                break;
        default:
                printf("Unknown signal received\n");
                break;
    }

    printf("Stopping timer...\n");
    /* Stop timer */
    stop_timer(t);
}

// START TIMER: I don't want the timer to cause the execution
//              of a handler function
int start_timer(struct itimerval timervalue, int msec)
//int start_timer(int msec)
{

  timervalue.it_interval.tv_sec = msec / 1000;
  timervalue.it_interval.tv_usec = (msec % 1000) * 1000;
  timervalue.it_value.tv_sec = msec / 1000;
  timervalue.it_value.tv_usec = (msec % 1000) * 1000;

  if(setitimer(ITIMER_REAL, &timervalue, NULL))
  {
    printf("\nsetitimer() error\n");
    return(-1);
  }
  return(0);
}

// STOP TIMER:
int stop_timer(struct itimerval timervalue)
//int stop_timer()
{
  timervalue.it_interval.tv_sec = 0;
  timervalue.it_interval.tv_usec = 0;
  timervalue.it_value.tv_sec = 0;
  timervalue.it_value.tv_usec = 0;

  if(setitimer(ITIMER_REAL, &timervalue, NULL))
  {
    printf("\nsetitimer() error\n");
    return(-1);
  }
  return(0);

}

Here is a typical execution of this code.

./signaltest
Setting timer...
Input message:hello
Going to raise SIGUSR1...raised!
Input message:friend
Going to raise SIGUSR1...raised!
Input message:Received SIGALRM: Timeout
Stopping timer...

As you can see, the signal SIGUSR1 is being raised and sigwait is being unblocked. However, the code seems does not continue after the signal has been raised. (Note that I don't need a signal handler but I just added for the debugging purposes. I have blocked its execution with sigprocmask)

Why is SIGUSR1 unblocking sigwait but the execution does not continue from there? Is there a way to make it continue after unblocking? This seems to work for SIGALRM but why not for SIGUSR1?

As I said, I have been looking at tons of stackoverflow questions, online howto's, tried with different system calls (e.g., pause, sigsuspend), ... but couldn't find a way to solve this :-(

If you are wondering why I am not doing this code much simpler by not using a thread is because this is not actually the code I am implementing but just a simpler example to make my question more clear. I am actually trying to implement a network protocol API, similar to the sockets API for my own protocol.

Thanks in advance

Body:
The SIGUSR1 signal isn't going where you think it is.

In a multithreaded program, the raise function sends a signal to the current thread, which is the thread_job thread in this case.  So the main thread never sees the signal.

You need to save off thread ID of the main thread, then use pthread_kill to send a signal to that thread.

Add a new global:

pthread_t main_tid;

Then populate it in your init function before starting the new thread:

void init()
{
    main_tid = pthread_self();
    ...

Then in message_rcvd, use pthread_kill:

    if(pthread_kill(main_tid, SIGUSR1) == 0)
        printf("raised!\n");

Also, remove the definition of end in thread_job, and remove the definition of tid in init.  These definitions mask the global variables of the same name.

Sample output:

Setting timer...
Input message:hello
Going to raise SIGUSR1...raised!
Input message:Received SIGUSR1: Message avaible!
Stopping timer...
Message received [hello
]
Setting timer...
test
Going to raise SIGUSR1...raised!
Input message:Received SIGUSR1: Message avaible!
Stopping timer...
Message received [test
]
Setting timer...
Received SIGALRM: Timeout
Stopping timer...


来源: stackexchange

问:
Making a button do the cmd + h command
Hey, I was wondering if it's possible to make a button do the cmd + h command?

This is how I was thinking.
The app will get the information as the force quit does (Apple Logo > Force Quit)
The user selected the app the user would like to hide and instead of having a force quit button I was thinking about having a hide button that does the cmd + h.

Would this be possible?

答: Do you mean hide the application you are running in, or hide a different application on the system? To hide the application you are in, attach the button to either the application's or first responder's hide: method. If you want to hide a different application, you have to send a hide apple event to the application.</p>

ContentLicense: CC BY-SA 2.5

Title: Making a button do the cmd + h command


问:
Does ReactJS reuse imported packages?
Does ReactJS reuse imported packages?

Let's say I have a file called DisplayItems.js and EditItem.js. They are both imported into App.js.

If I import a package (like axios) at the top of my DisplayItem.js file (import axios from 'axios';), and I also import it in my EditItem.js file, does my Application grow by 13kb or 26kb (assuming axios is 13kb)?

答:
In response to jhpratt, I did think of testing it on my own, but I knew it would take some time (about 34 mins).

Here's the test results.

Importing jQuery

2742120 (the control) - with jquery imported once

2742353 - with jquery imported twice (233 byte difference, .2kb)

2741887 - with jquery not being imported (233 byte difference, .2kb)

Importing modal-vanilla

2742120 (the control) - with modal-vanilla being imported once

2742406 - with modal-vanilla being import twice (286 byte difference, .3kb)

2712501 - with modal-vanilla not being imported (29386 byte difference, 29.3kb)

I'm not sure what was going on with jQuery (maybe I added it somewhere else in my project?), but it does look like packages are reused (at least in this instance).

Just in case anyone's wondering, I am using Laravel's React setup.

ContentLicense: CC BY-SA 3.0

Title: Does ReactJS reuse imported packages?


问:
What tsc command does Visual Studio run when I save a Typescript file?
I have a project in Visual Studio 2017 that uses Typescript.  I've set up the project so that when I save a *.ts file, Visual Studio compiles it (the default setting).  What command does Visual Studio actually run to compile the saved file?  I need to know because I want to run a similar command when I build my code on my build server.

Does Visual Studio just run tsc <filename>.ts for every saved file in my project?  Is there a command I can run that compiles all *.ts at once?

答:
You can see the exact command that is executed by MSBuild.

Change MSBuild to Detailed. Go to Tools->Options-> Project and Solution -> Build and Run. In the MSBuild project build output verbosity drop down select Detailed.

After you rebuild your project search the output window for tsc.exe (Ctrl + F works fine) And you will find the exact command executed.


问:
Webpack/node.js build, is it possible for webpack-dev-server to serve files to my public directory?
I currently have a node/express app that runs at localhost:8080, I have a webpack build that compiles stuff to my 'public' directories in that project correctly.

I would like to use webpack-dev-server to automagically watch and compile files on the fly for me, instead of using the 'watch' property of webpack.

When I start the dev server is starts at:

```<code>localhost:8081
</code>```

and my node app is at:

```<code>localhost:8080
</code>```

my assets for the node app are pulled from:

```<code>localhost:8080/public/css/main.css
localhost:8080/public/js/main.build.js
</code>```

I want to know whether its possible for the webpack-dev-server to server files from here instead? At the moment I can get to:

```<code>localhost:8081/public/js/main.css
</code>```

but this isn't where my express server reads assets from...help, much appreciated.

EDIT: webpack.config.js below, nothing too special here hopefully

```<code>const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const extractSass = new ExtractTextPlugin({
    filename: "./../sql-app/public/css/main.css",
    disable: process.env.NODE_ENV === "development"
});

module.exports = {
    entry: ['./src/js/app.js','./src/scss/main.scss'],
    output: {
        filename: './../sql-app/public/js/build.min.js',
        sourceMapFilename: '[file].map'
    },
    devtool: 'source-map',
    watch: (process.env.NODE_ENV !== 'staging' && process.env.NODE_ENV !== 'production') ? true : false,
    module: {
        loaders: [{
            test: /\.js[x]?$/,
            loaders: ['babel-loader?presets[]=es2015'],
            exclude: /(node_modules|bower_components)/
        }, {
            test: /\.woff$/,
            loader: "url-loader?limit=10000&mimetype=application/font-woff&name=[path][name].[ext]"
        }, {
            test: /\.woff2$/,
            loader: "url-loader?limit=10000&mimetype=application/font-woff2&name=[path][name].[ext]"
        }, {
            test: /\.(eot|ttf|svg|gif|png)$/,
            loader: "file-loader"
        }],
        rules: [{
            test: /\.scss$/,
            use: extractSass.extract({
                use: [{
                    loader: "css-loader"
                }, {
                    loader: "sass-loader"
                }],
                // use style-loader in development
                fallback: "style-loader"
            })
        }]
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            'jQuery': 'jquery',
            'window.jQuery': 'jquery',
            'global.jQuery': 'jquery'
        }),
        extractSass
    ],
    resolve: {
        alias: {
            'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
        }
    }
};
</code>```

答:
You can add the below similar code in your webpack.config.js

```<code>entry: './src/entry.js',
output: {
    path: path.join(__dirname, 'src/dist'),
    filename: 'bundle.js',
    publicPath: '/'
},
devServer: {
    contentBase: path.join(__dirname, 'src/dist'),
}
</code>```

As I can see one problem in your code [It will work, but not the right approach]

filename: './../sql-app/public/js/build.min.js'

It should be just a file name instead of any relative/absolute path.
It needs to be fixed to get the correct configuration which watches any changes & reloads the browser automatically.

Here is the link for your reference: https://stackoverflow.com/a/47658586/1681972

Body:
I currently have a node/express app that runs at localhost:8080, I have a webpack build that compiles stuff to my 'public' directories in that project correctly.

I would like to use webpack-dev-server to automagically watch and compile files on the fly for me, instead of using the 'watch' property of webpack.

When I start the dev server is starts at:

localhost:8081

and my node app is at:

localhost:8080

my assets for the node app are pulled from:

localhost:8080/public/css/main.css
localhost:8080/public/js/main.build.js

I want to know whether its possible for the webpack-dev-server to server files from here instead? At the moment I can get to:

localhost:8081/public/js/main.css

but this isn't where my express server reads assets from...help, much appreciated.

EDIT: webpack.config.js below, nothing too special here hopefully

const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const extractSass = new ExtractTextPlugin({
    filename: "./../sql-app/public/css/main.css",
    disable: process.env.NODE_ENV === "development"
});

module.exports = {
    entry: ['./src/js/app.js','./src/scss/main.scss'],
    output: {
        filename: './../sql-app/public/js/build.min.js',
        sourceMapFilename: '[file].map'
    },
    devtool: 'source-map',
    watch: (process.env.NODE_ENV !== 'staging' && process.env.NODE_ENV !== 'production') ? true : false,
    module: {
        loaders: [{
            test: /\.js[x]?$/,
            loaders: ['babel-loader?presets[]=es2015'],
            exclude: /(node_modules|bower_components)/
        }, {
            test: /\.woff$/,
            loader: "url-loader?limit=10000&mimetype=application/font-woff&name=[path][name].[ext]"
        }, {
            test: /\.woff2$/,
            loader: "url-loader?limit=10000&mimetype=application/font-woff2&name=[path][name].[ext]"
        }, {
            test: /\.(eot|ttf|svg|gif|png)$/,
            loader: "file-loader"
        }],
        rules: [{
            test: /\.scss$/,
            use: extractSass.extract({
                use: [{
                    loader: "css-loader"
                }, {
                    loader: "sass-loader"
                }],
                // use style-loader in development
                fallback: "style-loader"
            })
        }]
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            'jQuery': 'jquery',
            'window.jQuery': 'jquery',
            'global.jQuery': 'jquery'
        }),
        extractSass
    ],
    resolve: {
        alias: {
            'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
        }
    }
};

Body:
You can add the below similar code in your webpack.config.js

entry: './src/entry.js',
output: {
    path: path.join(__dirname, 'src/dist'),
    filename: 'bundle.js',
    publicPath: '/'
},
devServer: {
    contentBase: path.join(__dirname, 'src/dist'),
}

As I can see one problem in your code [It will work, but not the right approach]

filename: './../sql-app/public/js/build.min.js'

It should be just a file name instead of any relative/absolute path.
It needs to be fixed to get the correct configuration which watches any changes & reloads the browser automatically.

Here is the link for your reference: https://stackoverflow.com/a/47658586/1681972


问:
getting drop after dragleave in html5
I'm registered to HTML5 DnD events in order to get drop files from the desktop.
The problem that i see is that i always get dragleave event just before drop event.
In the specification there is no mention about something like this - and if you use the dragleave as an indicator that no drop happened then it mess-up the logic.

```<code>var dropbox = document.getElementById("dropzone");
dropbox.addEventListener("dragenter", dragEnter, false);
dropbox.addEventListener("dragleave", dragLeave, false);
dropbox.addEventListener("dragover", dragOver, false);
dropbox.addEventListener("drop", drop, false);

function dragEnter(e){
    console.log("dragEnter ",e);
    dropbox.style.backgroundColor = "red";
    e.stopPropagation();
    e.preventDefault();
}

function dragLeave(e){
    console.log("dragleave");
    dropbox.style.backgroundColor = "white";
    e.stopPropagation();
    e.preventDefault();
}

function dragOver(e){
    console.log("dragOver ",e);
    e.stopPropagation();
    e.preventDefault();
}

function drop(e){
     console.log("drop ",e);
     var files = e.dataTransfer.files;
     var count = files.length;
     e.stopPropagation();
     e.preventDefault();
}
</code>```

is this working as design or i'm missing something?

答:
This seems like a good reference:  http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/

Basically, dragLeave is not an indicator that no drop happened.  It is an indicator that a draggable object was dragged out of another object.

You don't need it.

[Edit:  Basically, dragleave is firing because the item you're dragging is from your desktop.  The object it is in before you drop it is basically your desktop.  If you drag any file from your desktop over any droptarget, it will fire the dragleave to indicate it's no longer "in" the previous object (your desktop), and now is in the new object ("dropzone").  If you had several dropzones, each time you dragged it over, then out of one of these, the dragleave would fire.  You should just use the drop event to tell if a drop happened.]

Title: getting drop after dragleave in html5

Body:
I'm registered to HTML5 DnD events in order to get drop files from the desktop.
The problem that i see is that i always get dragleave event just before drop event.
In the specification there is no mention about something like this - and if you use the dragleave as an indicator that no drop happened then it mess-up the logic.

var dropbox = document.getElementById("dropzone");
dropbox.addEventListener("dragenter", dragEnter, false);
dropbox.addEventListener("dragleave", dragLeave, false);
dropbox.addEventListener("dragover", dragOver, false);
dropbox.addEventListener("drop", drop, false);

function dragEnter(e){
    console.log("dragEnter ",e);
    dropbox.style.backgroundColor = "red";
    e.stopPropagation();
    e.preventDefault();
}

function dragLeave(e){
    console.log("dragleave");
    dropbox.style.backgroundColor = "white";
    e.stopPropagation();
    e.preventDefault();
}

function dragOver(e){
    console.log("dragOver ",e);
    e.stopPropagation();
    e.preventDefault();
}

function drop(e){
     console.log("drop ",e);
     var files = e.dataTransfer.files;
     var count = files.length;
     e.stopPropagation();
     e.preventDefault();
}

is this working as design or i'm missing something?


问:
java - object initialization syntax: someVar = (SomeClass[]) Object[aVariable]
In the following code snippet from https://introcs.cs.princeton.edu/java/44st/BinarySearchST.java.html
what does keys = (Key[]) new Comparable[initCapacity]; do?

```<code>public class BinarySearchST<Key extends Comparable<Key>, Value> {
    private static final int INIT_SIZE = 8;

    private Value[] vals;    // symbol table values
    private Key[] keys;      // symbol table keys
    private int n = 0;       // number of elements

    public BinarySearchST() {
        this(INIT_SIZE);
    }

    public BinarySearchST(int initCapacity) {
        vals = (Value[]) new Object[initCapacity];
        keys = (Key[]) new Comparable[initCapacity];
    } ...
</code>```

答:
In this case Key is a generic type. and specifically it is some type that extends Comparable.

Since you can't create an array of a generic type because of type erasure, you need to create an array of a supertype/interface of that generic type. In this case we know that Comparable is an interface of the generic type Key, so an array of Comparables is created in memory, then cast to the generic type Key

Here's more examples (also implement comparable):

```<code>static <T extends Comparable> T[] genericMethod(T someObj) {
    T[] arrayOfTypeT = (T[]) new Comparable[1];
    arrayOfTypeT[0] = someObj;
    return arrayOfTypeT;
}

// String extends Comparable
public static void main(String[] args) {
    String[] arrayOfString = genericMethod("A string");
    Integer[] arrayOfInt = genericMethod(new Integer(1));

    // this one doesn't compile, because it doesn't extend Comparable
    Object[] arrayOfObject = genericMethod(new Object());
}
</code>```

Body:
In the following code snippet from https://introcs.cs.princeton.edu/java/44st/BinarySearchST.java.html
what does keys = (Key[]) new Comparable[initCapacity]; do?

public class BinarySearchST<Key extends Comparable<Key>, Value> {
    private static final int INIT_SIZE = 8;

    private Value[] vals;    // symbol table values
    private Key[] keys;      // symbol table keys
    private int n = 0;       // number of elements

    public BinarySearchST() {
        this(INIT_SIZE);
    }

    public BinarySearchST(int initCapacity) {
        vals = (Value[]) new Object[initCapacity];
        keys = (Key[]) new Comparable[initCapacity];
    } ...

Body:
In this case Key is a generic type. and specifically it is some type that extends Comparable.

Since you can't create an array of a generic type because of type erasure, you need to create an array of a supertype/interface of that generic type. In this case we know that Comparable is an interface of the generic type Key, so an array of Comparables is created in memory, then cast to the generic type Key

Here's more examples (also implement comparable):

static <T extends Comparable> T[] genericMethod(T someObj) {
    T[] arrayOfTypeT = (T[]) new Comparable[1];
    arrayOfTypeT[0] = someObj;
    return arrayOfTypeT;
}

// String extends Comparable
public static void main(String[] args) {
    String[] arrayOfString = genericMethod("A string");
    Integer[] arrayOfInt = genericMethod(new Integer(1));

    // this one doesn't compile, because it doesn't extend Comparable
    Object[] arrayOfObject = genericMethod(new Object());
}


问:
Return Object Array from Invoke-Command
Powershell script is only returning one value from Invoke-Command not all the objects I would expect.

I am adding a property to an existing object on a remote server then returning it back.

$inventory contains application objects that look like this:

```<code>Name         : Centinel-Dev-AmazonServer
Platform     : Centinel
Type         : Windows Service
Tier         : APP
Status       : Running

Name         : Portal-QA-Walmart
Platform     : Portal
Type         : Windows Service
Tier         : APP
Status       : Running
</code>```

There are many more application objects similiar to the two given when I run my script it only returns the first object not all.

```<code>function verify_workingDir {
    param($server)
    $inventory = GetInventory -Server $server
    $return_object = @()
    $return_object += Invoke-Command -ComputerName $server -ScriptBlock {
        $inventory = $args[0]

        $return_object = @()
        foreach ($Application in $inventory) {

            $applicationParamters = Get-ItemProperty -Path x:\x\x\x\$($Application.Name)\Parameters

            $verify_object = [pscustomobject] @{
                WorkingDirectory = $applicationParamters.ServiceWorkingDir
            }

            $ExpandVerifyObject = $verify_object | Select-Object -Property @{
                Name       = "MyProperties"
                Expression = {$_.WorkingDirectory }
            } | Select-Object -ExpandProperty MyProperties

            Add-Member -MemberType NoteProperty -Name WorkingDirectory -InputObject $Application -TypeName PSObject -Value $ExpandVerifyObject
            $return_object += $Application
        }

        return $return_object

    } -ArgumentList ($inventory) #| Select Name, Platform, Type, Tier, Status, ServerName, WorkingDirectory

    return $return_object
}
</code>```

```<code>Answer:
  $inventory = $args[0] ---> $inventory = $args
</code>```

答:
Try $inventory = $args instead of $inventory = $args[0].

Passing arrays to script blocks is not the easiest thing because $args flattens everything to a single array.  If you pass -ArgumentList @(1,2,3), 4, then $Args will be a single array @(1,2,3,4) and $Args[0] will be 1.

If you ever need to pass complex arguments with -ArgumentList, pass them all as a single HashTable:  -ArgumentList @{FirstArg = @(1,2,3); SecondArg = 4}.

Title: Return Object Array from Invoke-Command

Body:
Powershell script is only returning one value from Invoke-Command not all the objects I would expect.

I am adding a property to an existing object on a remote server then returning it back.

$inventory contains application objects that look like this:

Name         : Centinel-Dev-AmazonServer
Platform     : Centinel
Type         : Windows Service
Tier         : APP
Status       : Running

Name         : Portal-QA-Walmart
Platform     : Portal
Type         : Windows Service
Tier         : APP
Status       : Running

There are many more application objects similiar to the two given when I run my script it only returns the first object not all.

function verify_workingDir {
    param($server)
    $inventory = GetInventory -Server $server
    $return_object = @()
    $return_object += Invoke-Command -ComputerName $server -ScriptBlock {
        $inventory = $args[0]

        $return_object = @()
        foreach ($Application in $inventory) {

            $applicationParamters = Get-ItemProperty -Path x:\x\x\x\$($Application.Name)\Parameters

            $verify_object = [pscustomobject] @{
                WorkingDirectory = $applicationParamters.ServiceWorkingDir
            }

            $ExpandVerifyObject = $verify_object | Select-Object -Property @{
                Name       = "MyProperties"
                Expression = {$_.WorkingDirectory }
            } | Select-Object -ExpandProperty MyProperties

            Add-Member -MemberType NoteProperty -Name WorkingDirectory -InputObject $Application -TypeName PSObject -Value $ExpandVerifyObject
            $return_object += $Application
        }

        return $return_object

    } -ArgumentList ($inventory) #| Select Name, Platform, Type, Tier, Status, ServerName, WorkingDirectory

    return $return_object
}

Answer:
  $inventory = $args[0] ---> $inventory = $args


问:
Getting an Uncaught TypeError: RulesModule.ruleModals is not a function
In an effort to write some neat and clean JavaScript, I am trying my hand at Modules. I created this Rules Module:

```<code>//RulesModule.js
var RulesModule = (function () {

    return {

        checkModal: function () {
            var checkModalContents = // string contents

            return checkModalContents;
        },

        ruleModals: function (modalType) {
            switch (modalType) {
                case "CheckDateRule":
                    return checkModal();
                default:
                    return "UNKNOWN MODAL";
            }
        }
    }
});
</code>```

I then hook into the event of a dropdown element and when an option is selected we pass that option to the RulesModule.ruleModals method, to get the correct modal.

```<code>//EventSubscriptions.js
    var go = false;//switch off
    $('#rules').on('click', function () {//on click
    if (go) {//if go
            var selectedRule = $("#rules").find(":selected").val();

            var contents = RulesModule.ruleModals(selectedRule); // this line throws the error

            console.log(contents);
            $("#modalContents").empty(); // clear up contents
            $("#modalContents").append(contents);
            $("#myModal").css("display", "block");

        go = false;//switch off
    } else { go = true; }//if !go, switch on
}).on('blur', function () { go = false; });//switch off on blur
</code>```

In my HTML, I load the two javascript files in my header:

```<code><head>
   <meta charset="utf-8" />
   <title></title>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script src="~/JavaScript/Modules/RulesModule.js"></script>
   <script src="~/JavaScript/EventSubscriptions.js"></script>
</head>
</code>```

答:
The return from RulesModule is an object and checkModal & ruleModals are two method to it,so try calling checkModal by this.checkModal

var RulesModule = (function() {
  return {
    checkModal: function() {
      var checkModalContents = ''; // string contents
      console.log('Check Modal called')
      return checkModalContents;
    },
    ruleModals: function(modalType) {
      switch (modalType) {
        case "CheckDateRule":
          return this.checkModal();
        default:
          return "UNKNOWN MODAL";
      }
    }
  }
}());

console.log(RulesModule.ruleModals('CheckDateRule'))```

Body:
In an effort to write some neat and clean JavaScript, I am trying my hand at Modules. I created this Rules Module:

//RulesModule.js
var RulesModule = (function () {

    return {

        checkModal: function () {
            var checkModalContents = // string contents

            return checkModalContents;
        },

        ruleModals: function (modalType) {
            switch (modalType) {
                case "CheckDateRule":
                    return checkModal();
                default:
                    return "UNKNOWN MODAL";
            }
        }
    }
});

I then hook into the event of a dropdown element and when an option is selected we pass that option to the RulesModule.ruleModals method, to get the correct modal.

//EventSubscriptions.js
    var go = false;//switch off
    $('#rules').on('click', function () {//on click
    if (go) {//if go
            var selectedRule = $("#rules").find(":selected").val();

            var contents = RulesModule.ruleModals(selectedRule); // this line throws the error

            console.log(contents);
            $("#modalContents").empty(); // clear up contents
            $("#modalContents").append(contents);
            $("#myModal").css("display", "block");

        go = false;//switch off
    } else { go = true; }//if !go, switch on
}).on('blur', function () { go = false; });//switch off on blur

In my HTML, I load the two javascript files in my header:

   <meta charset="utf-8" />
   <title></title>


问:
SQL Remove row when other rows are subset, keep row when no subset
I have a data set of 300,000 rows, looking at harvested acreage in the United States. Some, but not all of my data is double counted and I am trying to remove the double counting. The data looks like this:

```<code>Year  | State  | Crop | Practice | Acres Harvested | Acres
-------------------------------------------------------------
2008      1      1       1         1000 or more       40
2008      1      1       1         1000 to 1999       10
2008      1      1       1         2000 to 2999       30
2008      2      1       1         1000 or more       87
2008      3      2       2         1.0 to 14.9        15
2008      3      2       2         1.0 to 4.9          5
2008      3      2       2         5.0 to 14.9        10
</code>```

Some of the rows are subsets for other rows in the [Acres Harvested] column (rows 2 and 3 are a subset of row 1 and rows 6 and 7 are a subset of row 5). In situations where I have more detailed information for [Acres Harvested] (rows 2 and 3 provide more detail than row 1), I would like to keep the detailed information (row 2 and 3) and omit the general information (row 1). In other scenarios, I only have the general information (row 4), so that is what I will keep.

I am having trouble writing the code to omit the general information when the detailed information is present, but to keep the general information when the more detailed information does not exist.

I've been trying to write an "inner join" to join my table back with itself, but am unsure of how to omit rows when certain conditions are met. What I have:

```<code>SELECT *
FROM A
INNER JOIN (SELECT *
            FROM A
            GROUP BY [YEAR], [STATE], [CROP], [PRACTICE]
            HAVING COUNT (*) > 1) AS B

ON  A.Year     =    B.Year
AND A.State    =    B.State
AND A.Crop     =    B.Crop
AND A.Practice =    B.Practice
</code>```

And now I'm stuck...

Results should look like:

```<code>    Year  | State  | Crop | Practice | Acres Harvested | Acres
    -------------------------------------------------------------
    2008      1      1       1         1000 to 1999       10
    2008      1      1       1         2000 to 2999       30
    2008      2      1       1         1000 or more       87
    2008      3      2       2         1.0 to 4.9          5
    2008      3      2       2         5.0 to 14.9        10
</code>```

Appreciate any help!

答:
Your question is a bit vague.  This will return the result set you've specified for the input data you've specified:</p>

```<code>select a.*
from a
where a.acres_harvested not like '% or more' or
      not exists (select 1
                  from a a2
                  where a2.year = a.year and a2.state = a.state and a2.crop = a.crop and
                        a2.acres_harvested like '[0-9]%to%[0-9]'
                 );
</code>```

Body:
I have a data set of 300,000 rows, looking at harvested acreage in the United States. Some, but not all of my data is double counted and I am trying to remove the double counting. The data looks like this:

Year  | State  | Crop | Practice | Acres Harvested | Acres
-------------------------------------------------------------
2008      1      1       1         1000 or more       40
2008      1      1       1         1000 to 1999       10
2008      1      1       1         2000 to 2999       30
2008      2      1       1         1000 or more       87
2008      3      2       2         1.0 to 14.9        15
2008      3      2       2         1.0 to 4.9          5
2008      3      2       2         5.0 to 14.9        10

Some of the rows are subsets for other rows in the [Acres Harvested] column (rows 2 and 3 are a subset of row 1 and rows 6 and 7 are a subset of row 5). In situations where I have more detailed information for [Acres Harvested] (rows 2 and 3 provide more detail than row 1), I would like to keep the detailed information (row 2 and 3) and omit the general information (row 1). In other scenarios, I only have the general information (row 4), so that is what I will keep.

I am having trouble writing the code to omit the general information when the detailed information is present, but to keep the general information when the more detailed information does not exist.

I've been trying to write an "inner join" to join my table back with itself, but am unsure of how to omit rows when certain conditions are met. What I have:

SELECT *
FROM A
INNER JOIN (SELECT *
            FROM A
            GROUP BY [YEAR], [STATE], [CROP], [PRACTICE]
            HAVING COUNT (*) > 1) AS B

ON  A.Year     =    B.Year
AND A.State    =    B.State
AND A.Crop     =    B.Crop
AND A.Practice =    B.Practice

And now I'm stuck...

Results should look like:

    Year  | State  | Crop | Practice | Acres Harvested | Acres
    -------------------------------------------------------------
    2008      1      1       1         1000 to 1999       10
    2008      1      1       1         2000 to 2999       30
    2008      2      1       1         1000 or more       87
    2008      3      2       2         1.0 to 4.9          5
    2008      3      2       2         5.0 to 14.9        10

Appreciate any help!

Body:
Your question is a bit vague.  This will return the result set you've specified for the input data you've specified:

select a.*
from a
where a.acres_harvested not like '% or more' or
      not exists (select 1
                  from a a2
                  where a2.year = a.year and a2.state = a.state and a2.crop = a.crop and
                        a2.acres_harvested like '[0-9]%to%[0-9]'
                 );


问:
How to replace an item by another in a list in DrScheme when given paramters are two items and a list?
How to replace an item by another in a list in DrScheme when given paramters are two items and a list?</p>

答:
```<code>; replace first occurrence of b with a in list ls, q? is used for comparison
(define (replace q? a b ls)
  (cond ((null? ls) '())
    ((q? (car ls) b) (cons a (cdr ls)))
    (else (cons (car ls) (replace a b (cdr ls))))))
</code>```


问:
Nested and flatten dictionary from JSON by using recursion
I have the following .json file:

```<code>{
    "level1_one":"1",
    "level1_two":{
        "level2_one":"2",
        "level2_two":{
            "level3_one":"bottom"
        }
    }
}
</code>```

I need to give it nested and flatten representation like so:

```<code>{
    "level1_two": {
        "level2_two": {
            "level3_one": "bottom"
        },
        "level2_one": "2"
    },
    "level1_one": "1"
}
</code>```

and

```<code>{
    "level2_one": "2",
    "level3_one": "bottom",
    "level1_one": "1"
}
</code>```

I know I can easily achieve the nested form by simply doing this:

```<code>def json_parser(filename):
    data = json.load(open(filename))
    print(data)
</code>```

The problem is it needs to be done by using recursion for both cases. I tried almost everything I could find around here but without much success. How I can do this?

答:
Something like this

```<code>def flatten_dict(d):
    def items():
        for key, value in d.items():
            if isinstance(value, dict):
               for subkey, subvalue in flatten_dict(value).items():
                    yield subkey, subvalue
            else:
                yield key, value

    return dict(items())
</code>```

this returns

```<code>{'level1_one': '1', 'level2_one': '2', 'level3_one': 'bottom'}
</code>```

for the example you posted

Body:
I have the following .json file:

{
    "level1_one":"1",
    "level1_two":{
        "level2_one":"2",
        "level2_two":{
            "level3_one":"bottom"
        }
    }
}

I need to give it nested and flatten representation like so:

{
    "level1_two": {
        "level2_two": {
            "level3_one": "bottom"
        },
        "level2_one": "2"
    },
    "level1_one": "1"
}

and

{
    "level2_one": "2",
    "level3_one": "bottom",
    "level1_one": "1"
}

I know I can easily achieve the nested form by simply doing this:

def json_parser(filename):
    data = json.load(open(filename))
    print(data)

The problem is it needs to be done by using recursion for both cases. I tried almost everything I could find around here but without much success. How I can do this?

Body:
Something like this

def flatten_dict(d):
    def items():
        for key, value in d.items():
            if isinstance(value, dict):
               for subkey, subvalue in flatten_dict(value).items():
                    yield subkey, subvalue
            else:
                yield key, value

    return dict(items())

this returns

{'level1_one': '1', 'level2_one': '2', 'level3_one': 'bottom'}

for the example you posted


问:
How to load Table View in Main View Controller before segueing
Working on Swift 3 Xcode 9.1

I have two view controllers (one MainView and one Table View)

Problem: The Table View loads data from an API and displays it, however it take too long. I'm trying to have the load occur on the Main Controller.

I tried creating a custom method How to instantiate and load a view controller before segueing to it using swift

However the Table View has too many functions and I'm not sure how to call it.

Table View Code:

```<code>public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return array.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return cell
}

func loadData(){
 //loads data
 DispatchQueue.main.sync(execute:{
    self.tableView.reloadData()
}
</code>```

Question: Is creating a custom method the best way or is there another way? Please note I'm trying to do all this is the Main View Controller so the data can load once I segue to the Table View.

答:
Thank you all for your help!

I actually incorporated FryAnEgg's comment and created a Global Variable in my Main VC to load in the API.

Main VC:

```<code>var Global X

class Main VC: UIViewController {
   loadDataFunc(){
      GlobalX.append(data)
     }
 }
</code>```

TableView:

```<code>public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return GlobalX.count //calling Global Variable
  }
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  return cell
  }
</code>```

I then called the Global Variable in the Table View Controller and it worked !

Thanks again everyone

Body:
Working on Swift 3 Xcode 9.1

I have two view controllers (one MainView and one Table View)

Problem: The Table View loads data from an API and displays it, however it take too long. I'm trying to have the load occur on the Main Controller.

I tried creating a custom method How to instantiate and load a view controller before segueing to it using swift

However the Table View has too many functions and I'm not sure how to call it.

Table View Code:

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return array.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return cell
}

func loadData(){
 //loads data
 DispatchQueue.main.sync(execute:{
    self.tableView.reloadData()
}

Question: Is creating a custom method the best way or is there another way? Please note I'm trying to do all this is the Main View Controller so the data can load once I segue to the Table View.

Body:
Thank you all for your help!

I actually incorporated FryAnEgg's comment and created a Global Variable in my Main VC to load in the API.

Main VC:

var Global X

class Main VC: UIViewController {
   loadDataFunc(){
      GlobalX.append(data)
     }
 }

TableView:

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return GlobalX.count //calling Global Variable
  }
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  return cell
  }

I then called the Global Variable in the Table View Controller and it worked !

Thanks again everyone


问:
How to add triggers for a AWS Lambda function created using a CloudFormation template?
I am trying to create a lambda function from a CloudFormation template based on this example:

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-lambda.html

As can be seen from this link:

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html

there is no way to add a trigger for the lambda function (like a S3 upload trigger).

Is there a workaround to specify the trigger while writing the template?

答:
You need to add a NotificationConfiguration to the S3 bucket definition. However, this will lead to a circular dependency where the S3 bucket refers to the Lambda function and the Lambda function refers to the S3 bucket.

To avoid this circular dependency, create all resources (including the S3 bucket and the Lambda function) without specifying the notification configuration. Then, after you have created your stack, update the template with a notification configuration and then update the stack.


问:
SASS Mixins to Animate Dropdown Opening
I have a series of Nav dropdowns.  When the user hovers over one of them, I want it to open using an animation.  So my HTML looks something like this:

```<code><div class="nav-dropdown-contents short-dropdown">
  <div>Item 1</div>
  <div>Item 2</div>
</div>

<div class="nav-dropdown-contents medium-dropdown">
  <div>Item A</div>
  <div>Item B</div>
  <div>Item C</div>
  <div>Item D</div>
</div>
</code>```

So short dropdown has 2 items, and medium dropdown has 4.

Here is my SCSS for the short dropdown:

```<code>.short-dropdown {
    &.open {
        animation-name: shortDropdownOpenAnimation;
        animation-duration: 400ms;
    }

    &.closed {
        animation-name: shortDropdownCloseAnimation;
        animation-duration: 400ms;
    }
}
</code>```

And I have the two animations defined thusly:

```<code>@keyframes shortDropdownOpenAnimation {
from {
    height: 0px;
}

to {
    height: 50px;
}
</code>```

}

```<code>@keyframes ShortDropdownCloseAnimation {
from {
    height: 50px;
}

to {
    height: 0px;
}
</code>```

}

So this works great, but now I also have to define keyframes for my medium dropdown.  And as I get more dropdowns with different numbers of items, it would be nice to be able to factor all of these mixins out into just one, that takes a height property that I can pass in.

I've seen numerous examples of how to use mixins with animations, but they are all kind of verbose, and allow you to animate any properties.  I just need to animate height.  That's it.  I'm looking for the simplest possible way to do that.

Thanks.

Aaron

答:
Use an inner wrapper and apply any animations to that:

https://jsfiddle.net/v3act47k/1/

```<code>.dropdown {
   transition: all ease 1s;

  .inner-wrap {
    transform: translate3d(0, -100%, 0);
    visibility: hidden;
    animation-duration: 1s;
    animation-fill-mode: forwards;
  }
  &:hover {
    .inner-wrap {
      animation-name: slideInDown;
        animation-duration: 400ms;
    }
  }
}

@keyframes slideInDown {
  from {
    transform: translate3d(0, -100%, 0);
  }

  to {
    transform: translate3d(0, 0, 0);
    visibility: visible;
  }
}
</code>```

Title: SASS Mixins to Animate Dropdown Opening

Body:
I have a series of Nav dropdowns.  When the user hovers over one of them, I want it to open using an animation.  So my HTML looks something like this:

Item 1

Item 2

Item A

Item B

Item C

Item D

So short dropdown has 2 items, and medium dropdown has 4.

Here is my SCSS for the short dropdown:

.short-dropdown {
    &.open {
        animation-name: shortDropdownOpenAnimation;
        animation-duration: 400ms;
    }

    &.closed {
        animation-name: shortDropdownCloseAnimation;
        animation-duration: 400ms;
    }
}

And I have the two animations defined thusly:

@keyframes shortDropdownOpenAnimation {
from {
    height: 0px;
}

to {
    height: 50px;
}

}

@keyframes ShortDropdownCloseAnimation {
from {
    height: 50px;
}

to {
    height: 0px;
}

}

So this works great, but now I also have to define keyframes for my medium dropdown.  And as I get more dropdowns with different numbers of items, it would be nice to be able to factor all of these mixins out into just one, that takes a height property that I can pass in.

I've seen numerous examples of how to use mixins with animations, but they are all kind of verbose, and allow you to animate any properties.  I just need to animate height.  That's it.  I'm looking for the simplest possible way to do that.

Thanks.

Aaron

Body:
Use an inner wrapper and apply any animations to that:

https://jsfiddle.net/v3act47k/1/

.dropdown {
   transition: all ease 1s;

  .inner-wrap {
    transform: translate3d(0, -100%, 0);
    visibility: hidden;
    animation-duration: 1s;
    animation-fill-mode: forwards;
  }
  &:hover {
    .inner-wrap {
      animation-name: slideInDown;
        animation-duration: 400ms;
    }
  }
}

@keyframes slideInDown {
  from {
    transform: translate3d(0, -100%, 0);
  }

  to {
    transform: translate3d(0, 0, 0);
    visibility: visible;
  }
}


问:
Reformatting Table Multiple Separators Per Entry
I am working on a mac and would prefer to do this reformatting task with Bash, R, or python 3.

Here is a small example of the table that I am working with.  The table is thousands of rows long and each row has variable numbers of columns. Additionally the example contains 12 comma separated values beginning after the Isofrorm_ however i have reduced this to 4 for readability.

```<code>ENSMUSG0000001234 2.0 Isoform1_0.9,0.0,0.6,1.3 Isoform2_0.1,0.0,0.0,0.5
ENSMUSG0000005555 1.0 Isoform1_0.5,0.1,0.4,1.0 Isoform2_0.7,0.3,0.0,0.1 Isoform3_0.3,9.9,2.0,3.0
</code>```

I would like to be able to search for and reformat a row of interest to the following. To extract the row of interest i can use

```<code>grep "ENSMUSG0000001234" ./filename
</code>```

But i dont have enough experience to know how to pull out values by position and various separators and organize the output properly.  I think python is probably the best tool for this but i am a python novice.

I need the reformatted entry to look like the following

```<code>0.9 0.0 0.6 1.3
0.1 0.0 0.0 0.5
</code>```

For clarity the rownames and column names for this are

```<code>IsoformID Cell1 Cell2 Cell3 Cell4
Isoform1 0.9 0.0 0.6 1.3
Isoform2 0.1 0.0 0.0 0.5
</code>```

Any help is much appreciated.

答:
I saw that your preferred solution would be Bash, R or Python 3 but here is a quick solution for your problem that I could provide You in php.

You can save the following script into a file eg.: reformat.php

```<code><?php

$infile = $argv[1];

$handle = fopen($infile, "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $data = explode(' ', trim($line));
        print $data[0] . '-' . $data[1] . "\n";
        foreach (array_slice($data, 2) as $row) {
            print str_replace(['_', ','], ' ' , $row) . "\n";
        }
    }
    fclose($handle);
} else {
    exit("Unable to open file ($finfile)");
}
</code>```

Then run it from the command line in the following way:

```<code>php reformat.php your_data_file
</code>```

The script reads and process your file line by line. I am using the first two space separated fields as a block identifier. After then I process the remaining fields (array_slice($data, 2)) in the row.

Output:

```<code>ENSMUSG0000001234-2.0
Isoform1 0.9 0.0 0.6 1.3
Isoform2 0.1 0.0 0.0 0.5
ENSMUSG0000005555-1.0
Isoform1 0.5 0.1 0.4 1.0
Isoform2 0.7 0.3 0.0 0.1
Isoform3 0.3 9.9 2.0 3.0
</code>```

UPDATE:

I tried to figure out how to achive the goal using python. I came up with the following solution.

```<code>#!/usr/bin/python

with open("input.txt") as f:
    for line in f:
        row = line.strip().split(' ')
        print row[0] + '-' + row[1]
        for data in row[2:]:
            print data.replace('_', ' ').replace(',', ' ')
</code>```

This will produce identical output as showed above.

Body:
I am working on a mac and would prefer to do this reformatting task with Bash, R, or python 3.

Here is a small example of the table that I am working with.  The table is thousands of rows long and each row has variable numbers of columns. Additionally the example contains 12 comma separated values beginning after the Isofrorm_ however i have reduced this to 4 for readability.

ENSMUSG0000001234 2.0 Isoform1_0.9,0.0,0.6,1.3 Isoform2_0.1,0.0,0.0,0.5
ENSMUSG0000005555 1.0 Isoform1_0.5,0.1,0.4,1.0 Isoform2_0.7,0.3,0.0,0.1 Isoform3_0.3,9.9,2.0,3.0

I would like to be able to search for and reformat a row of interest to the following. To extract the row of interest i can use

grep "ENSMUSG0000001234" ./filename

But i dont have enough experience to know how to pull out values by position and various separators and organize the output properly.  I think python is probably the best tool for this but i am a python novice.

I need the reformatted entry to look like the following

0.9 0.0 0.6 1.3
0.1 0.0 0.0 0.5

For clarity the rownames and column names for this are

IsoformID Cell1 Cell2 Cell3 Cell4
Isoform1 0.9 0.0 0.6 1.3
Isoform2 0.1 0.0 0.0 0.5

Any help is much appreciated.

Body:
I saw that your preferred solution would be Bash, R or Python 3 but here is a quick solution for your problem that I could provide You in php.

You can save the following script into a file eg.: reformat.php

<?php

$infile = $argv[1];

$handle = fopen($infile, "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $data = explode(' ', trim($line));
        print $data[0] . '-' . $data[1] . "\n";
        foreach (array_slice($data, 2) as $row) {
            print str_replace(['_', ','], ' ' , $row) . "\n";
        }
    }
    fclose($handle);
} else {
    exit("Unable to open file ($finfile)");
}

Then run it from the command line in the following way:

php reformat.php your_data_file

The script reads and process your file line by line. I am using the first two space separated fields as a block identifier. After then I process the remaining fields (array_slice($data, 2)) in the row.

Output:

ENSMUSG0000001234-2.0
Isoform1 0.9 0.0 0.6 1.3
Isoform2 0.1 0.0 0.0 0.5
ENSMUSG0000005555-1.0
Isoform1 0.5 0.1 0.4 1.0
Isoform2 0.7 0.3 0.0 0.1
Isoform3 0.3 9.9 2.0 3.0

UPDATE:

I tried to figure out how to achive the goal using python. I came up with the following solution.

#!/usr/bin/python

with open("input.txt") as f:
    for line in f:
        row = line.strip().split(' ')
        print row[0] + '-' + row[1]
        for data in row[2:]:
            print data.replace('_', ' ').replace(',', ' ')

This will produce identical output as showed above.

ContentLicense: CC BY-SA 4.0


问:
Replace tf.squeeze using as tf.reshape
I need to train a mobile net using tensorflow. The tf.squeeze layer is not supported. Can I replace it with the tf.reshape?

Is the operation:

```<code>tf.squeeze(net, [1, 2], name='squeeze')
</code>```

the same as:

```<code>tf.reshape(net, [50,1000], name='reshape')
</code>```

where net has the shape [50,1,1,1000].

答: Why do you say tf.squeeze is not supported? In order to remove 1 dimensional axis from tensor, tf.squeeze is the correct operation. But you can achieve your desired work with tf.reshape as well though I will suggest you to make use of tf.squeeze.

Title: Replace tf.squeeze using as tf.reshape

Body:
I need to train a mobile net using tensorflow. The tf.squeeze layer is not supported. Can I replace it with the tf.reshape?

Is the operation:

tf.squeeze(net, [1, 2], name='squeeze')

the same as:

tf.reshape(net, [50,1000], name='reshape')

where net has the shape [50,1,1,1000].


答:
You can try this:

```<code>s = {
"level1_one":"1",
"level1_two":{
    "level2_one":"2",
    "level2_two":{
        "level3_one":"bottom"
    }
  }
}
def flatten(s):
   for i in s:
      if not isinstance(s[i], dict):
          yield (i, s[i])
      else:
           for b in flatten(s[i]):
              yield b

new_data = dict(list(flatten(s)))
</code>```

Output:

```<code>{'level2_one': '2', 'level3_one': 'bottom', 'level1_one': '1'}
</code>```

Title: Nested and flatten dictionary from JSON by using recursion

Body:
You can try this:

s = {
"level1_one":"1",
"level1_two":{
    "level2_one":"2",
    "level2_two":{
        "level3_one":"bottom"
    }
  }
}
def flatten(s):
   for i in s:
      if not isinstance(s[i], dict):
          yield (i, s[i])
      else:
           for b in flatten(s[i]):
              yield b

new_data = dict(list(flatten(s)))

Output:

{'level2_one': '2', 'level3_one': 'bottom', 'level1_one': '1'}


问:
Opening, edit/rewrite string, save back to a new or same file
I want to open a file, decode the format of data (from base64 to ASCII), rewrite or save the decoded string, either back to the same file, or new one.

I have it opening, reading, decoding (and printing as a test) the decoded base64 string into readable format (ASCII I believe)

My goal is to now save this output to: either a "newfile.txt" document or back to the original "test.mcz" file ready for the next steps of my mission...

I know there are great online base64 decoders and they do work well for what I am doing - I use them often, but my goal is to write my own program as a learning exercise more than anything (also when my internet plays up I need an offline program)

Here's where I am so far (the original file is .mcz format it is a game save)

```<code># PYTHON 3
import base64

f = open('test.mcz', 'r')
f_read = f.read()
# print(f_read) # was just as a test

new_f_read = base64.b64decode(f_read)
print (new_f_read)
</code>```

This prints a butt-load of readable code that is what I need, but I don't want to have to just copy and paste this output from the Python shell into another editor, I want to save it to a file...for convenience.

Either back into the same test.mcz (I will be re-encoding to base64 again later on anyway) or to a new file - thus leaving my original as it was.

problem arises when I want to save/write this decoded output that is stored within the new_f_read variable...it's just been a headache, before I started I could visualise how it needed to be written, I got tripped up when I had to switch it all over to Python3 for some reason (Don't ask...) and I have tried so many variations from online examples - I wouldn't know where to start explaining what I've tried so far. I can't open the original file as both "r" AND "w" together so once Ive opened and decoded I cant reopen the original file as "w" because it just wipes the contents (which are still encoded anyway) -

I think I need to write functions to handle:
1. Open, read, save string to a variable
2. Manipulate string - decode
3. Write the new string to new or existing file

Sounds easy I know, but I am stuck...so here I am. If anyone shows examples, please take the time to explain what is going on, it seems pointless to me having code I don't understand. Apologies if this seems like a simple thing, help would be appreciated..Thanks

答:
First, you can absolutely open a file for both reading and writing without truncating the contents.  That's what the r+ mode is for (see https://docs.python.org/3/library/functions.html#open).  If you do this, the model is (a) open the file, (b) read it, (c) seek back to the beginning with e.g. f.seek(0), (d) write it.

Secondly, you can simply open the file, read it, then close the file, and then reopen it, write it, and close it again, like this:

```<code># open the file for reading, read the data, then close the file
with open('test.mcz', 'rb') as f:
    f_read = f.read()

new_f_read = base64.b64decode(f_read)

# open the file for writing, write the data, then close the file
with open('test.mcz', 'wb') as f:
    f.write(new_f_read)
</code>```

This is probably the easiest solution.

Body:
I want to open a file, decode the format of data (from base64 to ASCII), rewrite or save the decoded string, either back to the same file, or new one.

I have it opening, reading, decoding (and printing as a test) the decoded base64 string into readable format (ASCII I believe)

My goal is to now save this output to: either a "newfile.txt" document or back to the original "test.mcz" file ready for the next steps of my mission...

I know there are great online base64 decoders and they do work well for what I am doing - I use them often, but my goal is to write my own program as a learning exercise more than anything (also when my internet plays up I need an offline program)

Here's where I am so far (the original file is .mcz format it is a game save)

# PYTHON 3
import base64

f = open('test.mcz', 'r')
f_read = f.read()
# print(f_read) # was just as a test

new_f_read = base64.b64decode(f_read)
print (new_f_read)

This prints a butt-load of readable code that is what I need, but I don't want to have to just copy and paste this output from the Python shell into another editor, I want to save it to a file...for convenience.

Either back into the same test.mcz (I will be re-encoding to base64 again later on anyway) or to a new file - thus leaving my original as it was.

problem arises when I want to save/write this decoded output that is stored within the new_f_read variable...it's just been a headache, before I started I could visualise how it needed to be written, I got tripped up when I had to switch it all over to Python3 for some reason (Don't ask...) and I have tried so many variations from online examples - I wouldn't know where to start explaining what I've tried so far. I can't open the original file as both "r" AND "w" together so once Ive opened and decoded I cant reopen the original file as "w" because it just wipes the contents (which are still encoded anyway) -

I think I need to write functions to handle:
1. Open, read, save string to a variable
2. Manipulate string - decode
3. Write the new string to new or existing file

Sounds easy I know, but I am stuck...so here I am. If anyone shows examples, please take the time to explain what is going on, it seems pointless to me having code I don't understand. Apologies if this seems like a simple thing, help would be appreciated..Thanks

Body:
First, you can absolutely open a file for both reading and writing without truncating the contents.  That's what the r+ mode is for (see https://docs.python.org/3/library/functions.html#open).  If you do this, the model is (a) open the file, (b) read it, (c) seek back to the beginning with e.g. f.seek(0), (d) write it.

Secondly, you can simply open the file, read it, then close the file, and then reopen it, write it, and close it again, like this:

# open the file for reading, read the data, then close the file
with open('test.mcz', 'rb') as f:
    f_read = f.read()

new_f_read = base64.b64decode(f_read)

# open the file for writing, write the data, then close the file
with open('test.mcz', 'wb') as f:
    f.write(new_f_read)

This is probably the easiest solution.


问:
Implementation of Expression.Assign in .Net 3.5 with same signature?
Expression.Assign isn't available before .NET 4. I need to implementation under .NET 3.5 of this method with original signature:

```<code>public static BinaryExpression Assign(
    Expression left,
    Expression right
)
</code>```

Clarification: I'm not looking for a way to use this method in the some case. I need to implement the general case.

答:
Based on the splution of Konstantin Oznobihin here´s a slighty modified one which contains the MethodCallExpression instead of a BinaryExpression:

```<code>public class ExpressionEx
{
    public static Expression Assign(Expression left, Expression right)
    {
        var method = typeof(ExpressionEx).GetMethod("Assign", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(left.Type);
        return Expression.Call(method, left, right);
    }
    private static void Assign<T>(ref T left, T right)
    {
        left = right;
    }
}
</code>```

This will create a delegate to the Assign-method within ExpressionEx and can now easily be used like this:

```<code>var expr = ExpressionEx.Assign(myInstanceExpression, newValueExpression);
</code>```

Body:
Expression.Assign isn't available before .NET 4. I need to implementation under .NET 3.5 of this method with original signature:

public static BinaryExpression Assign(
    Expression left,
    Expression right
)

Clarification: I'm not looking for a way to use this method in the some case. I need to implement the general case.

Body:
Based on the splution of Konstantin Oznobihin here´s a slighty modified one which contains the MethodCallExpression instead of a BinaryExpression:

public class ExpressionEx
{
    public static Expression Assign(Expression left, Expression right)
    {
        var method = typeof(ExpressionEx).GetMethod("Assign", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(left.Type);
        return Expression.Call(method, left, right);
    }
    private static void Assign<T>(ref T left, T right)
    {
        left = right;
    }
}

This will create a delegate to the Assign-method within ExpressionEx and can now easily be used like this:

var expr = ExpressionEx.Assign(myInstanceExpression, newValueExpression);


问:
C++ standard library - when should I use it and when shouldn't I?
I was wondering how often people actually use much of the standard c++ library, particularly the stuff in the <algorithm> and <numeric> headers.  The text books seem to recommend them, but I haven't seen any of them used at all in various projects I've sifted through (coincidence?) and personally it seems easier to just write appropriate simple algorithms myself each time rather than memorize or consult a reference to these headers each time. Am just being lazy or stubborn?  Is there actually performance gains etc when using these libraries?

Thanks,

R

答:
You should use standard libraries in all languages, not only C++. That's pretty much a basic rule in programming these days.

Your impression is wrong; any good project will benefit from building upon known, tested, libraries. The amount of time and man-hours there's behind these libraries is just something that an individual can't achieve alone.

Lots of people have suffered, sweated, sweared and fought over the years in order to get those libraries properly running. The combined effort of writing, debugging and arguing over each particular implementation detail can probably be measured in decades. On top of that, uncountable machine cycles have been spent running test after test just to make sure that everything worked according to the specs.

Yet pretty much every programmer has now and then that thought. You know the one.

"I can do better in one evening".

I know. I understand. I have been there.

Go ahead. It's a good experience.

A long, sinuous path will extend before you. On the initial part of your journey, you will find little implementation pebbles here and there. Some of them will slip into your shoes, most won't.

Later on the path will stop being so straight; it'll start branching out. Soon you will find yourself trying lots of different paths and backtracking frequently. And occasionally you will encounter a profound chasms of algorithmic uncertainty or a tiresome refactoring mountain.

All that while you watch your peers speeding on the clean, straight, maintained Standard Libraries Highway.

Gradually you will realize that refusing to use standard libraries and isn't just lazy or stubborn, but foolish. And terribly inefficient!

In conclusion - if you want to reach somewhere, no matter how fast you can run, driving a car will get you there faster and more safely (unless you are going to the store downstairs for some milk)


问:
Raising to a square with TensorFlow with a Dataset class
I want to write a neural network which look for a x^2 distribution without a predefined model. Precisely, it is given some points in [-1,1] with their squares to train, and then it would have to reproduce and predict similar for e.g. [-10,10].
I've more or less done it - without datasets. But then I tried to modify it in order to use datasets and learn how to use it. Now, I succeded in making the program run, but the output is worse then before, mainly it's constant 0.

Previous version was like x^2 in [-1,1] with linear prolongation, which was better.. Previous output
with a blue line being flat now. And the goal would be to coincide with a red one..

Here, comments are in Polish, sorry for that.

```<code># square2.py - drugie podejscie do trenowania sieci za pomocą Tensorflow
# cel: nauczyć sieć rozpoznawać rozkład x**2
# analiza skryptu z:
# https://stackoverflow.com/questions/43140591/neural-network-to-predict-nth-square

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.python.framework.ops import reset_default_graph

# def. danych do trenowania sieci
# x_train = (np.random.rand(10**3)*4-2).reshape(-1,1)
# y_train = x_train**2
square2_dane = np.load("square2_dane.npz")
x_train = square2_dane['x_tren'].reshape(-1,1)
y_train = square2_dane['y_tren'].reshape(-1,1)

# zoptymalizować dzielenie danych
# x_train = square2_dane['x_tren'].reshape(-1,1)
# ds_x = tf.data.Dataset.from_tensor_slices(x_train)
# batch_x = ds_x.batch(rozm_paczki)
# iterator = ds_x.make_one_shot_iterator()

# określenie parametrów sieci
wymiary = [50,50,50,1]
epoki = 500
rozm_paczki = 200

reset_default_graph()
X = tf.placeholder(tf.float32, shape=[None,1])
Y = tf.placeholder(tf.float32, shape=[None,1])

weights = []
biases = []
n_inputs = 1

# inicjalizacja zmiennych
for i,n_outputs in enumerate(wymiary):
    with tf.variable_scope("layer_{}".format(i)):
        w = tf.get_variable(name="W", shape=[n_inputs,n_outputs],initializer = tf.random_normal_initializer(mean=0.0,stddev=0.02,seed=42))
        b=tf.get_variable(name="b",shape=[n_outputs],initializer=tf.zeros_initializer)
        weights.append(w)
        biases.append(b)
        n_inputs=n_outputs

def forward_pass(X,weights,biases):
    h=X
    for i in range(len(weights)):
        h=tf.add(tf.matmul(h,weights[i]),biases[i])
        h=tf.nn.relu(h)
    return h

output_layer = forward_pass(X,weights,biases)
f_strat = tf.reduce_mean(tf.squared_difference(output_layer,Y),1)
f_strat = tf.reduce_sum(f_strat)
# alternatywna funkcja straty
#f_strat2 = tf.reduce_sum(tf.abs(Y-y_train)/y_train)
optimizer = tf.train.AdamOptimizer(learning_rate=0.003).minimize(f_strat)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # trenowanie
    dataset = tf.data.Dataset.from_tensor_slices((x_train,y_train))
    dataset = dataset.batch(rozm_paczki)
    dataset = dataset.repeat(epoki)
    iterator = dataset.make_one_shot_iterator()
    ds_x, ds_y = iterator.get_next()
    sess.run(optimizer, {X: sess.run(ds_x), Y: sess.run(ds_y)})
    saver = tf.train.Saver()
    save = saver.save(sess, "./model.ckpt")
    print("Model zapisano jako: %s" % save)

    # puszczenie sieci na danych
    x_test = np.linspace(-1,1,600)
    network_outputs = sess.run(output_layer,feed_dict = {X :x_test.reshape(-1,1)})

plt.plot(x_test,x_test**2,color='r',label='y=x^2')
plt.plot(x_test,network_outputs,color='b',label='sieć NN')
plt.legend(loc='right')
plt.show()
</code>```

I think that the problem is with input of training data
sess.run(optimizer, {X: sess.run(ds_x), Y: sess.run(ds_y)})
or with the definition of ds_x, ds_y. It's my first such a program..
So this was the output for the lines (insead of the 'sees' block)

```<code>with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # trenowanie
    for i in range(epoki):
        idx = np.arange(len(x_train))
        np.random.shuffle(idx)
        for j in range(len(x_train)//rozm_paczki):
            cur_idx = idx[rozm_paczki*j:(rozm_paczki+1)*j]
            sess.run(optimizer,feed_dict = {X:x_train[cur_idx],Y:y_train[cur_idx]})
    saver = tf.train.Saver()
    save = saver.save(sess, "./model.ckpt")
    print("Model zapisano jako: %s" % save)
</code>```

Thanks!

P.S.: I was highly inspired by Neural Network to predict nth square

答:
There are two problems that conspire to give your model poor accuracy, and both involve this line:

```<code>sess.run(optimizer, {X: sess.run(ds_x), Y: sess.run(ds_y)})
</code>```

Only one training step will execute because this code is not in a loop. Your original code ran len(x_train)//rozm_paczki steps, which ought to make more progress.

The two calls to sess.run(ds_x) and sess.run(ds_y) run in separate steps, which means they will contain values from different batches that are unrelated. Each call to sess.run(ds_x) or sess.run(ds_y) moves the Iterator on to the next batch, and discards any parts of the input element that you did not explicitly request in the sess.run() call. Essentially, you will get X from batch i and Y from batch i+1 (or vice versa), and the model will train on invalid data. If you want to get values from the same batch, you need to do it in a single sess.run([ds_x, ds_y]) call.

There are two further concerns that might impact efficiency:

The Dataset is not shuffled. Your original code calls np.random.shuffle() at the beginning of each epoch. You should include a dataset = dataset.shuffle(len(x_train)) before dataset = dataset.repeat().

It is inefficient to fetch the values from the the Iterator back to Python (e.g. when you do sess.run(ds_x)) and feed them back into the training step. It is more efficient to pass the output of the Iterator.get_next() operation directly into the feed-forward step as inputs.

Putting this all together, here's a rewritten version of your program that addresses these four points, and achieves the correct results. (Unfortunately my Polish isn't good enough to preserve the comments, so I've translated to English.)

```<code>import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

# Generate training data.
x_train = np.random.rand(10**3, 1).astype(np.float32) * 4 - 2
y_train = x_train ** 2

# Define hyperparameters.
DIMENSIONS = [50,50,50,1]
NUM_EPOCHS = 500
BATCH_SIZE = 200

dataset = tf.data.Dataset.from_tensor_slices((x_train,y_train))
dataset = dataset.shuffle(len(x_train))  # (Point 3.) Shuffle each epoch.
dataset = dataset.repeat(NUM_EPOCHS)
dataset = dataset.batch(BATCH_SIZE)
iterator = dataset.make_one_shot_iterator()

# (Point 2.) Ensure that `X` and `Y` correspond to the same batch of data.
# (Point 4.) Pass the tensors returned from `iterator.get_next()`
# directly as the input of the network.
X, Y = iterator.get_next()

# Initialize variables.
weights = []
biases = []
n_inputs = 1
for i, n_outputs in enumerate(DIMENSIONS):
  with tf.variable_scope("layer_{}".format(i)):
    w = tf.get_variable(name="W", shape=[n_inputs, n_outputs],
                        initializer=tf.random_normal_initializer(
                            mean=0.0, stddev=0.02, seed=42))
    b = tf.get_variable(name="b", shape=[n_outputs],
                        initializer=tf.zeros_initializer)
    weights.append(w)
    biases.append(b)
    n_inputs = n_outputs

def forward_pass(X,weights,biases):
  h = X
  for i in range(len(weights)):
    h=tf.add(tf.matmul(h, weights[i]), biases[i])
    h=tf.nn.relu(h)
  return h

output_layer = forward_pass(X, weights, biases)
loss = tf.reduce_sum(tf.reduce_mean(
    tf.squared_difference(output_layer, Y), 1))
optimizer = tf.train.AdamOptimizer(learning_rate=0.003).minimize(loss)
saver = tf.train.Saver()

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())

  # (Point 1.) Run the `optimizer` in a loop. Use try-while-except to iterate
  # until all elements in `dataset` have been consumed.
  try:
    while True:
      sess.run(optimizer)
  except tf.errors.OutOfRangeError:
    pass

  save = saver.save(sess, "./model.ckpt")
  print("Model saved to path: %s" % save)

  # Evaluate network.
  x_test = np.linspace(-1, 1, 600)
  network_outputs = sess.run(output_layer, feed_dict={X: x_test.reshape(-1, 1)})

plt.plot(x_test,x_test**2,color='r',label='y=x^2')
plt.plot(x_test,network_outputs,color='b',label='NN prediction')
plt.legend(loc='right')
plt.show()
</code>```

Body:
I want to write a neural network which look for a x^2 distribution without a predefined model. Precisely, it is given some points in [-1,1] with their squares to train, and then it would have to reproduce and predict similar for e.g. [-10,10].
I've more or less done it - without datasets. But then I tried to modify it in order to use datasets and learn how to use it. Now, I succeded in making the program run, but the output is worse then before, mainly it's constant 0.

Previous version was like x^2 in [-1,1] with linear prolongation, which was better.. Previous output
with a blue line being flat now. And the goal would be to coincide with a red one..

Here, comments are in Polish, sorry for that.

# square2.py - drugie podejscie do trenowania sieci za pomocą Tensorflow
# cel: nauczyć sieć rozpoznawać rozkład x**2
# analiza skryptu z:
# https://stackoverflow.com/questions/43140591/neural-network-to-predict-nth-square

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.python.framework.ops import reset_default_graph

# def. danych do trenowania sieci
# x_train = (np.random.rand(10**3)*4-2).reshape(-1,1)
# y_train = x_train**2
square2_dane = np.load("square2_dane.npz")
x_train = square2_dane['x_tren'].reshape(-1,1)
y_train = square2_dane['y_tren'].reshape(-1,1)

# zoptymalizować dzielenie danych
# x_train = square2_dane['x_tren'].reshape(-1,1)
# ds_x = tf.data.Dataset.from_tensor_slices(x_train)
# batch_x = ds_x.batch(rozm_paczki)
# iterator = ds_x.make_one_shot_iterator()

# określenie parametrów sieci
wymiary = [50,50,50,1]
epoki = 500
rozm_paczki = 200

reset_default_graph()
X = tf.placeholder(tf.float32, shape=[None,1])
Y = tf.placeholder(tf.float32, shape=[None,1])

weights = []
biases = []
n_inputs = 1

# inicjalizacja zmiennych
for i,n_outputs in enumerate(wymiary):
    with tf.variable_scope("layer_{}".format(i)):
        w = tf.get_variable(name="W", shape=[n_inputs,n_outputs],initializer = tf.random_normal_initializer(mean=0.0,stddev=0.02,seed=42))
        b=tf.get_variable(name="b",shape=[n_outputs],initializer=tf.zeros_initializer)
        weights.append(w)
        biases.append(b)
        n_inputs=n_outputs

def forward_pass(X,weights,biases):
    h=X
    for i in range(len(weights)):
        h=tf.add(tf.matmul(h,weights[i]),biases[i])
        h=tf.nn.relu(h)
    return h

output_layer = forward_pass(X,weights,biases)
f_strat = tf.reduce_mean(tf.squared_difference(output_layer,Y),1)
f_strat = tf.reduce_sum(f_strat)
# alternatywna funkcja straty
#f_strat2 = tf.reduce_sum(tf.abs(Y-y_train)/y_train)
optimizer = tf.train.AdamOptimizer(learning_rate=0.003).minimize(f_strat)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # trenowanie
    dataset = tf.data.Dataset.from_tensor_slices((x_train,y_train))
    dataset = dataset.batch(rozm_paczki)
    dataset = dataset.repeat(epoki)
    iterator = dataset.make_one_shot_iterator()
    ds_x, ds_y = iterator.get_next()
    sess.run(optimizer, {X: sess.run(ds_x), Y: sess.run(ds_y)})
    saver = tf.train.Saver()
    save = saver.save(sess, "./model.ckpt")
    print("Model zapisano jako: %s" % save)

    # puszczenie sieci na danych
    x_test = np.linspace(-1,1,600)
    network_outputs = sess.run(output_layer,feed_dict = {X :x_test.reshape(-1,1)})

plt.plot(x_test,x_test**2,color='r',label='y=x^2')
plt.plot(x_test,network_outputs,color='b',label='sieć NN')
plt.legend(loc='right')
plt.show()

I think that the problem is with input of training data
sess.run(optimizer, {X: sess.run(ds_x), Y: sess.run(ds_y)})
or with the definition of ds_x, ds_y. It's my first such a program..
So this was the output for the lines (insead of the 'sees' block)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # trenowanie
    for i in range(epoki):
        idx = np.arange(len(x_train))
        np.random.shuffle(idx)
        for j in range(len(x_train)//rozm_paczki):
            cur_idx = idx[rozm_paczki*j:(rozm_paczki+1)*j]
            sess.run(optimizer,feed_dict = {X:x_train[cur_idx],Y:y_train[cur_idx]})
    saver = tf.train.Saver()
    save = saver.save(sess, "./model.ckpt")
    print("Model zapisano jako: %s" % save)

Thanks!

P.S.: I was highly inspired by Neural Network to predict nth square

Body:
There are two problems that conspire to give your model poor accuracy, and both involve this line:

sess.run(optimizer, {X: sess.run(ds_x), Y: sess.run(ds_y)})

Only one training step will execute because this code is not in a loop. Your original code ran len(x_train)//rozm_paczki steps, which ought to make more progress.

The two calls to sess.run(ds_x) and sess.run(ds_y) run in separate steps, which means they will contain values from different batches that are unrelated. Each call to sess.run(ds_x) or sess.run(ds_y) moves the Iterator on to the next batch, and discards any parts of the input element that you did not explicitly request in the sess.run() call. Essentially, you will get X from batch i and Y from batch i+1 (or vice versa), and the model will train on invalid data. If you want to get values from the same batch, you need to do it in a single sess.run([ds_x, ds_y]) call.

There are two further concerns that might impact efficiency:

The Dataset is not shuffled. Your original code calls np.random.shuffle() at the beginning of each epoch. You should include a dataset = dataset.shuffle(len(x_train)) before dataset = dataset.repeat().

It is inefficient to fetch the values from the the Iterator back to Python (e.g. when you do sess.run(ds_x)) and feed them back into the training step. It is more efficient to pass the output of the Iterator.get_next() operation directly into the feed-forward step as inputs.

Putting this all together, here's a rewritten version of your program that addresses these four points, and achieves the correct results. (Unfortunately my Polish isn't good enough to preserve the comments, so I've translated to English.)

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

# Generate training data.
x_train = np.random.rand(10**3, 1).astype(np.float32) * 4 - 2
y_train = x_train ** 2

# Define hyperparameters.
DIMENSIONS = [50,50,50,1]
NUM_EPOCHS = 500
BATCH_SIZE = 200

dataset = tf.data.Dataset.from_tensor_slices((x_train,y_train))
dataset = dataset.shuffle(len(x_train))  # (Point 3.) Shuffle each epoch.
dataset = dataset.repeat(NUM_EPOCHS)
dataset = dataset.batch(BATCH_SIZE)
iterator = dataset.make_one_shot_iterator()

# (Point 2.) Ensure that `X` and `Y` correspond to the same batch of data.
# (Point 4.) Pass the tensors returned from `iterator.get_next()`
# directly as the input of the network.
X, Y = iterator.get_next()

# Initialize variables.
weights = []
biases = []
n_inputs = 1
for i, n_outputs in enumerate(DIMENSIONS):
  with tf.variable_scope("layer_{}".format(i)):
    w = tf.get_variable(name="W", shape=[n_inputs, n_outputs],
                        initializer=tf.random_normal_initializer(
                            mean=0.0, stddev=0.02, seed=42))
    b = tf.get_variable(name="b", shape=[n_outputs],
                        initializer=tf.zeros_initializer)
    weights.append(w)
    biases.append(b)
    n_inputs = n_outputs

def forward_pass(X,weights,biases):
  h = X
  for i in range(len(weights)):
    h=tf.add(tf.matmul(h, weights[i]), biases[i])
    h=tf.nn.relu(h)
  return h

output_layer = forward_pass(X, weights, biases)
loss = tf.reduce_sum(tf.reduce_mean(
    tf.squared_difference(output_layer, Y), 1))
optimizer = tf.train.AdamOptimizer(learning_rate=0.003).minimize(loss)
saver = tf.train.Saver()

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())

  # (Point 1.) Run the `optimizer` in a loop. Use try-while-except to iterate
  # until all elements in `dataset` have been consumed.
  try:
    while True:
      sess.run(optimizer)
  except tf.errors.OutOfRangeError:
    pass

  save = saver.save(sess, "./model.ckpt")
  print("Model saved to path: %s" % save)

  # Evaluate network.
  x_test = np.linspace(-1, 1, 600)
  network_outputs = sess.run(output_layer, feed_dict={X: x_test.reshape(-1, 1)})

plt.plot(x_test,x_test**2,color='r',label='y=x^2')
plt.plot(x_test,network_outputs,color='b',label='NN prediction')
plt.legend(loc='right')
plt.show()


问:
UITableView titleForHeaderInSection shows all caps
I am using titleForHeaderInSection to show a header for a UITableView section. It worked fine with the iOS6 SDK, but the iOS7 SDK shows the header in all CAPS.

I guess it's part of Apple's updated Human Interface Guidelines; all examples in there show headers in all caps. Also, all section headers in Settings on my iPhone are in all caps.

However, I wonder if there is a way around that. Normally, I wouldn't mind showing caps if that improves consistency, but when I need to show people's names in a section header, it's a bit awkward.

Anybody any idea how to get around to capitalization?

答:
In addition to @Animal451's post.
For swift 3 you can use

```<code>func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
  guard section == 0 ,
    let tableViewHeaderFooterView = view as? UITableViewHeaderFooterView
    else { return }

  tableViewHeaderFooterView.textLabel?.text = "Your awesome string"
 }
</code>```

And then ignore - titleForHeaderInSection:

Keep in mind that this code is for 1st section only. If you want to go through all of your sections, you'll need to add support for them

Body:
In addition to @Animal451's post.
For swift 3 you can use

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
  guard section == 0 ,
    let tableViewHeaderFooterView = view as? UITableViewHeaderFooterView
    else { return }

  tableViewHeaderFooterView.textLabel?.text = "Your awesome string"
 }

And then ignore - titleForHeaderInSection:

Keep in mind that this code is for 1st section only. If you want to go through all of your sections, you'll need to add support for them


问:
Overwriting array in dafny
I'm trying to overwrite an array inside a method. The compiler is giving me the error "Error: LHS of assignment must denote a mutable variable".

```<code>    method invalidSort(a : array<int>)
    modifies a;
    requires a != null;
    ensures sorted(a[..]);
    {
       a := new int[0];
    }
</code>```

Am I staring myself blind and missing something or why does Dafny not allow this?

答:
In Dafny, method parameters cannot be assigned to. You can use a local variable if you need to update the value internally.

For example,

```<code>var a' := new int[0];
</code>```

If you want this new array to be available to the caller, you'll also need to return it.

```<code>return a';
</code>```

All that said, if you're trying to write an in-place sorting method, then you don't need to do any of this. Just modify a in place.

```<code>a[0] := 0;
// ...
</code>```

Title: Overwriting array in dafny

Body:
I'm trying to overwrite an array inside a method. The compiler is giving me the error "Error: LHS of assignment must denote a mutable variable".

    method invalidSort(a : array<int>)
    modifies a;
    requires a != null;
    ensures sorted(a[..]);
    {
       a := new int[0];
    }

Am I staring myself blind and missing something or why does Dafny not allow this?

Body:
In Dafny, method parameters cannot be assigned to. You can use a local variable if you need to update the value internally.

For example,

var a' := new int[0];

If you want this new array to be available to the caller, you'll also need to return it.

return a';

All that said, if you're trying to write an in-place sorting method, then you don't need to do any of this. Just modify a in place.

a[0] := 0;
// ...


问:
How to scaffold Database in ASP.NET Core using Visual Studio Code
I have tried using the following command ( which works fine if I use Visual Studio) :

```<code>Scaffold-DbContext "Server=12.345.567.890;Database=ABC;Trusted_Connection=True;User Id=xyz;Password=12345;Integrated Security=false;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -f
</code>```

While trying the above command using Visual Studio code terminal, I get this error:

The term 'Scaffold-DbContext' is not recognized as the name of a cmdlet, function, script file, or
  operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
  again

答:
You may have to run the command line version of scaffolding. The command you have posted is for the Package Manager in Visual Studio

```<code>dotnet ef dbcontext scaffold "Server=12.345.567.890;Database=ABC;Trusted_Connection=True;User Id=xyz;Password=12345;Integrated Security=false;" Microsoft.EntityFrameworkCore.SqlServer -o Models
</code>```

Source
ASP.NET Core - Write Apps with Visual Studio Code and Entity Framework

Body:
I have tried using the following command ( which works fine if I use Visual Studio) :

Scaffold-DbContext "Server=12.345.567.890;Database=ABC;Trusted_Connection=True;User Id=xyz;Password=12345;Integrated Security=false;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -f

While trying the above command using Visual Studio code terminal, I get this error:

The term 'Scaffold-DbContext' is not recognized as the name of a cmdlet, function, script file, or
  operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
  again

Body:
You may have to run the command line version of scaffolding. The command you have posted is for the Package Manager in Visual Studio

dotnet ef dbcontext scaffold "Server=12.345.567.890;Database=ABC;Trusted_Connection=True;User Id=xyz;Password=12345;Integrated Security=false;" Microsoft.EntityFrameworkCore.SqlServer -o Models

Source
ASP.NET Core - Write Apps with Visual Studio Code and Entity Framework