问:
jQuery not recognizing Symfony JSON?
I'm trying to get my JSON data from Symfony but it doesn't seem to be working right. Below is the snippet of symfony code:

```<code>$this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8');
return $this->renderPartial('listJsonResponse',
array('jsonSlots' => json_encode($this->jsonQuery)));
</code>```

The above works fine and hits the partial. All that is in my partial is this:

```<code><?php echo $jsonSlots ?>
</code>```

Now according to Firebug this gets populated properly. Below is a copy of the response

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

Note if I take out the Content/Type header it changes slightly. I get the same response tab as above but also an html tab with the above parsed into html. Which shows like this:

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

I know the JSON function is hitting, but it isn't parsing the success function and alerting me any sort of data. the JavasScript is shown below and is wrapped in a jquery ready tag

```<code>$.getJSON('/frontend_dev.php/module/listJSONSlots', function(data) {
    alert(data);
});
</code>```

Any ideas why I can't get to the alert?

答:
You do not need to render a template, you can skip that and directly return something from your action. Try this:</p>

```<code>return $this->renderText(json_encode($this->jsonQuery));
</code>```

Title: jQuery not recognizing Symfony JSON?

Body:
I'm trying to get my JSON data from Symfony but it doesn't seem to be working right. Below is the snippet of symfony code:

$this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8');
return $this->renderPartial('listJsonResponse',
array('jsonSlots' => json_encode($this->jsonQuery)));

The above works fine and hits the partial. All that is in my partial is this:

<?php echo $jsonSlots ?>

Now according to Firebug this gets populated properly. Below is a copy of the response

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

Note if I take out the Content/Type header it changes slightly. I get the same response tab as above but also an html tab with the above parsed into html. Which shows like this:

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

I know the JSON function is hitting, but it isn't parsing the success function and alerting me any sort of data. the JavasScript is shown below and is wrapped in a jquery ready tag

$.getJSON('/frontend_dev.php/module/listJSONSlots', function(data) {
    alert(data);
});

Any ideas why I can't get to the alert?

Body:
You do not need to render a template, you can skip that and directly return something from your action. Try this:

return $this->renderText(json_encode($this->jsonQuery));


来源: stackexchange

问:
Selenium standalone server fails in production mode - Grails
I have a web application written using Grails that's failing in production mode when trying to fire up Selenium standalone server.

Here's the error:

```<code> 2017-12-04 10:04:52,905 [http-bio-8080-exec-7] ERROR
 errors.GrailsExceptionResolver  - ClassNotFoundException occurred when
 processing request: [GET] /Diversotron-0.1/api/edit
 com.google.common.base.Function. Stacktrace follows:
 java.lang.ClassNotFoundException: com.google.common.base.Function
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2585)
    at java.lang.Class.getDeclaredConstructors(Class.java:1906)
    at org.codehaus.groovy.util.LazyReference.getLocked(LazyReference.java:46)
    at org.codehaus.groovy.util.LazyReference.get(LazyReference.java:33)
    at diversotron.PropotronService.setPropotron(PropotronService.groovy:29)
    at diversotron.ApiController.edit(ApiController.groovy:53)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
</code>```

Line 29 is this:

```<code> WebDriver driver = new RemoteWebDriver(new URL("http://123.456.78.910:4444/wd/hub"), capabilities)
</code>```

This works perfectly fine in debug mode. Anyone have any ideas? (IP address hidden for privacy)

答:
Use FirefoxOptions to merge the capabilities through org.openqa.selenium.MutableCapabilities as follows :

```<code>DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("...", true);
capabilities.setCapability("...", true);
FirefoxOptions options = new FirefoxOptions();
options.merge(capabilities);
WebDriver driver = new RemoteWebDriver(new URL("http://127.0.0.1:4444/wd/hub"), options);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a web application written using Grails that's failing in production mode when trying to fire up Selenium standalone server.

Here's the error:

 2017-12-04 10:04:52,905 [http-bio-8080-exec-7] ERROR
 errors.GrailsExceptionResolver  - ClassNotFoundException occurred when
 processing request: [GET] /Diversotron-0.1/api/edit
 com.google.common.base.Function. Stacktrace follows:
 java.lang.ClassNotFoundException: com.google.common.base.Function
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2585)
    at java.lang.Class.getDeclaredConstructors(Class.java:1906)
    at org.codehaus.groovy.util.LazyReference.getLocked(LazyReference.java:46)
    at org.codehaus.groovy.util.LazyReference.get(LazyReference.java:33)
    at diversotron.PropotronService.setPropotron(PropotronService.groovy:29)
    at diversotron.ApiController.edit(ApiController.groovy:53)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

Line 29 is this:

 WebDriver driver = new RemoteWebDriver(new URL("http://123.456.78.910:4444/wd/hub"), capabilities)

This works perfectly fine in debug mode. Anyone have any ideas? (IP address hidden for privacy)

Body:
Use FirefoxOptions to merge the capabilities through org.openqa.selenium.MutableCapabilities as follows :

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("...", true);
capabilities.setCapability("...", true);
FirefoxOptions options = new FirefoxOptions();
options.merge(capabilities);
WebDriver driver = new RemoteWebDriver(new URL("http://127.0.0.1:4444/wd/hub"), options);


问:
use compass framework and compile with something else
do I have to compile with compass in order to use it framework ?
is it possible to use compass framework and compile sass with an other tool like gulp ? </p>

答:
You can use gulp-compass to compile compass.

Main thing about compass vs sass is being able to use @include x(y); to get browser prefixes (at least from my experience). You could also use gulp-autoprefixer and gulp-sass to accomplish something similar.

I use .scss files (because I like semi-colons) but a sass builder with my gulp file:

```<code>gulp.task('sass', function() {
    return gulp.src(settings.sass.input)
        .pipe(sourcemaps.init())
            .pipe(sass(settings.sass.options).on('error', errorLog))
            .pipe(autoprefixer(settings.sass.autoprefixer).on('error', errorLog))
        .pipe(sourcemaps.write(settings.maps, {
            sourceMappingURL: file => {
                return file.relative + '.map';
            }
        }))
        .pipe(gulp.dest(settings.sass.output))
    .resume();
});
</code>```

I used to use compass, then it started taking 10-15 seconds to compile, and ended up switching back to just using sass (though with a .scss file type).

Body:
You can use gulp-compass to compile compass.

Main thing about compass vs sass is being able to use @include x(y); to get browser prefixes (at least from my experience). You could also use gulp-autoprefixer and gulp-sass to accomplish something similar.

I use .scss files (because I like semi-colons) but a sass builder with my gulp file:

gulp.task('sass', function() {
    return gulp.src(settings.sass.input)
        .pipe(sourcemaps.init())
            .pipe(sass(settings.sass.options).on('error', errorLog))
            .pipe(autoprefixer(settings.sass.autoprefixer).on('error', errorLog))
        .pipe(sourcemaps.write(settings.maps, {
            sourceMappingURL: file => {
                return file.relative + '.map';
            }
        }))
        .pipe(gulp.dest(settings.sass.output))
    .resume();
});

I used to use compass, then it started taking 10-15 seconds to compile, and ended up switching back to just using sass (though with a .scss file type).


问:
grep regex for file name with one separator but not two
So here's my problem, I have a script where I generate files like so (just an example):

animal

animal.dog

animal.dog.7

essentially this is a tree structure in files, each of which contain different information.

I'm trying to grab animal.dog but my regex .*\..*$ wants to grab both

animal.dog.7 and animal.dog

where I only want animal.dog.

Any help would be greatly appreciated!

答:
You can use this negated character class in grep -E  regex pattern:

```<code>^[^.]+\.[^.]+$
</code>```

This will match animal.dog but won't match animal.dog.7

RegEx Breakup:

^: Start

[^.]+: Match 1+ characters that is not a DOT

\.: Match a literal DOT

[^.]+: Match 1+ characters that is not a DOT

$: End

Body:
You can use this negated character class in grep -E  regex pattern:

^[^.]+\.[^.]+$

This will match animal.dog but won't match animal.dog.7

RegEx Breakup:

^: Start

[^.]+: Match 1+ characters that is not a DOT

\.: Match a literal DOT

[^.]+: Match 1+ characters that is not a DOT

$: End


问:
Run a shell file in java
In Java you can call a shell file like this:

```<code>public class Shell {
    private static Shell rootShell = null;
    private final Process proc;
    private final OutputStreamWriter writer;

    private Shell(String cmd) throws IOException {
        this.proc = new ProcessBuilder(cmd).redirectErrorStream(true).start();
        this.writer = new OutputStreamWriter(this.proc.getOutputStream(), "UTF-8");
    }

    public void cmd(String command)  {
        try {
            writer.write(command+'\n');
            writer.flush();
        } catch (IOException e) {   }
    }

    public void close() {
        try {
            if (writer != null) {
                writer.close();
                if(proc != null) {
                    proc.destroy();
                }
            }
        } catch (IOException ignore) {}
    }

    public static void exec(String command) {
        Shell.get().cmd(command);
    }

    public static Shell get() {
        if (Shell.rootShell == null) {
            while (Shell.rootShell == null) {
                try {
                    Shell.rootShell = new Shell("su"); //Open with Root Privileges
                } catch (IOException e) {   }
            }
        }
        return Shell.rootShell;
    }
}

Shell.exec("echo " + bt.getLevel() + " > "+ flashfile);
</code>```

right.

but I have a shell which giving an argument after executing it.

how can I pass that argument?  I don't want user type anything to run this shell file. in another word, I want to fully automate a shell file.

答:
Runtime.getRuntime().exec("src/[FILE LOCATION]");

I think this is the command you're looking for. Let me know if it works!

Title: Run a shell file in java

Body:
In Java you can call a shell file like this:

public class Shell {
    private static Shell rootShell = null;
    private final Process proc;
    private final OutputStreamWriter writer;

    private Shell(String cmd) throws IOException {
        this.proc = new ProcessBuilder(cmd).redirectErrorStream(true).start();
        this.writer = new OutputStreamWriter(this.proc.getOutputStream(), "UTF-8");
    }

    public void cmd(String command)  {
        try {
            writer.write(command+'\n');
            writer.flush();
        } catch (IOException e) {   }
    }

    public void close() {
        try {
            if (writer != null) {
                writer.close();
                if(proc != null) {
                    proc.destroy();
                }
            }
        } catch (IOException ignore) {}
    }

    public static void exec(String command) {
        Shell.get().cmd(command);
    }

    public static Shell get() {
        if (Shell.rootShell == null) {
            while (Shell.rootShell == null) {
                try {
                    Shell.rootShell = new Shell("su"); //Open with Root Privileges
                } catch (IOException e) {   }
            }
        }
        return Shell.rootShell;
    }
}

Shell.exec("echo " + bt.getLevel() + " > "+ flashfile);

right.

but I have a shell which giving an argument after executing it.

how can I pass that argument?  I don't want user type anything to run this shell file. in another word, I want to fully automate a shell file.


问:
Camera Intent - how to?
Sorry to bother you guys, but I am not able to get a solution where In we take picture using intents. I know the default behavior of native camera is to save the picture at default directory/place of O.S. The thing is I have some requirements where I do not want to save the picture when clicked using camera app. There has to be a solution of this issue, be it like once we take a picture we could delete it right away, or there should be an alternate by which we won't allow O.S to save Image, please help.

Here is a piece of code I tried, tried several ways by creating a directory and then deleting file, nothing works.

```<code> public void takeImageFromCamera() {

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_REQUEST);
    }

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

// Check for the integer request code originally supplied to startResolutionForResult().
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {

            if (isCameraPermissionGranted()) {
                bitmap= (Bitmap) data.getExtras().get("data");
              //  bitmap = processReuiredImage(picUri);
                getProfileDetailViaFace(encodeImageBitmapToString(bitmap));
                Log.d("path",String.valueOf(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES)));

              //  getApplicationContext().getContentResolver().delete(, "/storage/emulated/0/Pictures", null);
            //     mediaStorageDir.getPath().delete();

            } else {
                requestCameraPermission();
            }
        }

public void takeImageFromCamera() {

    File file = getOutputMediaFile(CAMERA_FILE_TYPE);

    if (Build.VERSION.SDK_INT >= 24) {
        try {

            Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
            m.invoke(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    picUri = Uri.fromFile(file);

    Intent takePictureIntent = new
   Intent(MediaStore.ACTION_IMAGE_CAPTURE_SECURE);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, CAMERA_REQUEST);
    }
    }

   private File getOutputMediaFile(int type) {
    mediaStorageDir  = new
     File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "peppercard");

    /**Create the storage directory if it does not exist*/
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            return null;
        }
    }

    /**Create a media file name*/
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

    if (type == CAMERA_FILE_TYPE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "IMG_" + timeStamp + ".jpeg");
    } else {
        return null;
    }
</code>```

}
        return mediaFile;

}

答:
```<code>There has to be a solution of this issue, be it like once we take
a picture we could delete it right away
</code>```

Indeed there is. You could specify a path (even using a file provider) where the camera app has to put the image in a file.

Then when the camera app is done you can get the image from that file and then delete the file.

Have a look at Intent.EXTRA_OUTPUT.

Pretty standard your question. You can find a lot of example code on this site.

Title: Camera Intent - how to?

Body:
Sorry to bother you guys, but I am not able to get a solution where In we take picture using intents. I know the default behavior of native camera is to save the picture at default directory/place of O.S. The thing is I have some requirements where I do not want to save the picture when clicked using camera app. There has to be a solution of this issue, be it like once we take a picture we could delete it right away, or there should be an alternate by which we won't allow O.S to save Image, please help.

Here is a piece of code I tried, tried several ways by creating a directory and then deleting file, nothing works.

 public void takeImageFromCamera() {

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_REQUEST);
    }

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

// Check for the integer request code originally supplied to startResolutionForResult().
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {

            if (isCameraPermissionGranted()) {
                bitmap= (Bitmap) data.getExtras().get("data");
              //  bitmap = processReuiredImage(picUri);
                getProfileDetailViaFace(encodeImageBitmapToString(bitmap));
                Log.d("path",String.valueOf(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES)));

              //  getApplicationContext().getContentResolver().delete(, "/storage/emulated/0/Pictures", null);
            //     mediaStorageDir.getPath().delete();

            } else {
                requestCameraPermission();
            }
        }

public void takeImageFromCamera() {

    File file = getOutputMediaFile(CAMERA_FILE_TYPE);

    if (Build.VERSION.SDK_INT >= 24) {
        try {

            Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
            m.invoke(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    picUri = Uri.fromFile(file);

    Intent takePictureIntent = new
   Intent(MediaStore.ACTION_IMAGE_CAPTURE_SECURE);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, CAMERA_REQUEST);
    }
    }

   private File getOutputMediaFile(int type) {
    mediaStorageDir  = new
     File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "peppercard");

    /**Create the storage directory if it does not exist*/
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            return null;
        }
    }

    /**Create a media file name*/
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

    if (type == CAMERA_FILE_TYPE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "IMG_" + timeStamp + ".jpeg");
    } else {
        return null;
    }

}
        return mediaFile;

}

Body:
There has to be a solution of this issue, be it like once we take
a picture we could delete it right away

Indeed there is. You could specify a path (even using a file provider) where the camera app has to put the image in a file.

Then when the camera app is done you can get the image from that file and then delete the file.

Have a look at Intent.EXTRA_OUTPUT.

Pretty standard your question. You can find a lot of example code on this site.


问:
Formatting data from an excel sheet (two criteria) in MATLAB
I have a question related to another one recently asked. I download my data as a csv.file. I then format it in MATLAB. I obtan formatted data such as:

I would like to format the data so that I obtain:

In other words, the date should be in the first column, while the two identifier should be in the first two rows, respectively.

I tried the code provided by @gnovice, yet I have problems to adjust for the second identifier. The code is:

```<code>A = accumarray([rowIndex colIndex], data(:, 4), [], @(x) x(1));
A = [NaN colVals; rowVals A];
</code>```

where data is equal to picture (1).

Therefore, I obtain a matrix A like:

```<code> A =
      NaN     1    2     3;
 20160101   100   80    90;
 20170101   150   90   200;
</code>```

How can I adjust my code in a way that the second identifier is taken care of and A becomes:

```<code> A =
      NaN     1    2     3;
      NaN    10   10    15;
 20160101   100   80    90;
 20170101   150   90   200;
</code>```

答:
The answer from albusSimba points in the right direction. You'll want to collect the columns containing your identifiers (i.e. data(:, [1 3])), pass that to unique with the 'rows' option to find the unique row combinations, then capture the third output to use as the index for aggregation by accumarray. Your final matrix formatting will then just have to be changed to account for the second identifier:

```<code>[rowVals, ~, rowIndex] = unique(data(:, 2));
[colVals, ~, colIndex] = unique(data(:, [1 3]), 'rows');
A = accumarray([rowIndex colIndex], data(:, 4), [], @(x) x(1));
A = [NaN colVals(:, 1).'; NaN colVals(:, 2).'; rowVals A];
</code>```

And the result for your sample data:

```<code>A =

         NaN           1           2           3
         NaN          10          10          15
    20160101         100          80         200
    20170101         150          90         200
</code>```

Body:
I have a question related to another one recently asked. I download my data as a csv.file. I then format it in MATLAB. I obtan formatted data such as:

I would like to format the data so that I obtain:

In other words, the date should be in the first column, while the two identifier should be in the first two rows, respectively.

I tried the code provided by @gnovice, yet I have problems to adjust for the second identifier. The code is:

A = accumarray([rowIndex colIndex], data(:, 4), [], @(x) x(1));
A = [NaN colVals; rowVals A];

where data is equal to picture (1).

Therefore, I obtain a matrix A like:

 A =
      NaN     1    2     3;
 20160101   100   80    90;
 20170101   150   90   200;

How can I adjust my code in a way that the second identifier is taken care of and A becomes:

 A =
      NaN     1    2     3;
      NaN    10   10    15;
 20160101   100   80    90;
 20170101   150   90   200;

Body:
The answer from albusSimba points in the right direction. You'll want to collect the columns containing your identifiers (i.e. data(:, [1 3])), pass that to unique with the 'rows' option to find the unique row combinations, then capture the third output to use as the index for aggregation by accumarray. Your final matrix formatting will then just have to be changed to account for the second identifier:

[rowVals, ~, rowIndex] = unique(data(:, 2));
[colVals, ~, colIndex] = unique(data(:, [1 3]), 'rows');
A = accumarray([rowIndex colIndex], data(:, 4), [], @(x) x(1));
A = [NaN colVals(:, 1).'; NaN colVals(:, 2).'; rowVals A];

And the result for your sample data:

A =

         NaN           1           2           3
         NaN          10          10          15
    20160101         100          80         200
    20170101         150          90         200


问:
Creating a self extracting bash script for linux using Ant on Windows
I'm trying to generate a self extracting script using the method discussed here: http://www.linuxjournal.com/node/1005818

Using ANT (on windows) I create the payload archive using TAR task(gzip compression), and concat the script and the tar using the following CONCAT task.

```<code><concat destfile="${output}/selfextract.bsx"
            append="true"
            eol="lf">
    <fileset file="${installer}/decompress"/>
    <fileset file="${output}/payload.tar.gz"/>
</concat>
</code>```

The file is being created, and appears to contain the archive data, but when run on our Red Hat machine gzip complains "invalid compressed data --format violated".

Has anyone succeeded in this before?

答:
Solved.

Higher in the ANT script, I was using the FixCRLF task with eol="unix" on decompress.sh.  By default this task adds an extra newline to the end of the file unless you add fixlast="false".

I also added the binary="yes" attribute to concat.

My mistake for not including the rest of the script, and thanks for the help.

Final Code:

```<code><concat destfile="${output}/selfextract.bsx"
        binary="yes">
    <fileset file="${installer}/decompress"/>
    <fileset file="${output}/payload.tar.gz"/>
</concat>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to generate a self extracting script using the method discussed here: http://www.linuxjournal.com/node/1005818

Using ANT (on windows) I create the payload archive using TAR task(gzip compression), and concat the script and the tar using the following CONCAT task.

<concat destfile="${output}/selfextract.bsx"
            append="true"
            eol="lf">
    <fileset file="${installer}/decompress"/>
    <fileset file="${output}/payload.tar.gz"/>
</concat>

The file is being created, and appears to contain the archive data, but when run on our Red Hat machine gzip complains "invalid compressed data --format violated".

Has anyone succeeded in this before?

Body:
Solved.

Higher in the ANT script, I was using the FixCRLF task with eol="unix" on decompress.sh.  By default this task adds an extra newline to the end of the file unless you add fixlast="false".

I also added the binary="yes" attribute to concat.

My mistake for not including the rest of the script, and thanks for the help.

Final Code:

<concat destfile="${output}/selfextract.bsx"
        binary="yes">
    <fileset file="${installer}/decompress"/>
    <fileset file="${output}/payload.tar.gz"/>
</concat>


问:
How to transfer folder from Amazon Web Services to ASP.NET Server remotely
I have a folder on Amazon Web services and I want to transfer it to ASP.NET Server.

The Folder has huge size and I have a limited internet capacity so I can't download it and re-upload it via ASP.NET Web Forms.

so is it possible ? and How could I do it ? or What I should search for this ?

P.S: as I searched all I found was the other way around and I didn't quite understand it.

答:
I found a service that do the exact thing I want via FTP.

As the user registers two FTPs and he can copy/migraine the files/folders you want from one to the other.

Multcloud: Manage, migrate, transfer, copy, and move files between any cloud storage services.


问:
How to remove/delete last character from printed list in python
I am creating simple program which finds the smallest multiplicators of a number (not sure if this is the right term). However, I can not find a way to delete last "*" from the listed result. What am I doing wrong? Please help.

```<code>num = int(input("write number: "))
print(num, end = "=")
div = 2
while num > 1:
    if num % div == 0:
        num = num / div
        print(div, end = "*")
    else:
        div += 1
</code>```

Result I got:

```<code>24=2*2*2*3*
</code>```

Result I want:

```<code>24=2*2*2*3
</code>```

I tried to use sep="" instead of end="", tried \b, [:-1] but this does not work or I am just doing it wrong.
Thank you.

答:
You can concatenate your results:

```<code>s += div + "*"
</code>```

And after just don't print last symbol:

```<code>print(s[:-1])
</code>```

But in my mind it's a bad decision because in python type string is immutable type --> and because of it every time "s += div + "*"" new variable "s" will be created.

Body:
I am creating simple program which finds the smallest multiplicators of a number (not sure if this is the right term). However, I can not find a way to delete last "*" from the listed result. What am I doing wrong? Please help.

num = int(input("write number: "))
print(num, end = "=")
div = 2
while num > 1:
    if num % div == 0:
        num = num / div
        print(div, end = "*")
    else:
        div += 1

Result I got:

24=2*2*2*3*

Result I want:

24=2*2*2*3

I tried to use sep="" instead of end="", tried \b, [:-1] but this does not work or I am just doing it wrong.
Thank you.

Body:
You can concatenate your results:

s += div + "*"

And after just don't print last symbol:

print(s[:-1])

But in my mind it's a bad decision because in python type string is immutable type --> and because of it every time "s += div + "*"" new variable "s" will be created.


问:
Implementing Okta in React Native and get: Response to preflight request doesn't pass access
I'm implementing the Okta signin widget with React Native

I get this:

Failed to load https://dev-827074.oktapreview.com/api/v1/sessions/me: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

After trying to login, I get the following:

UnsupportedBrowserError {name: "UNSUPPORTED_BROWSER_ERROR", message: "There was an error sending the request - have you enabled CORS?"}

答: You may need to add http://localhost:3000/implicit/callback to your app's Login Redirect URI's in the General Settings of your Okta app


问:
Change the color of a link over time (so that it doesn't begin a new cycle on refresh)
I'm trying to change the color of a link over time cycling through rainbow colors. When you refresh the color should still be the same it was a moment ago, not begin a new cycle (so CSS animations haven't worked for me yet either).

I am trying to apply the color of this calculation to the hover function of a link.

```<code>  var h = ( 60 * ( color[0] + time ) % 360 ) / 360;
  materials[i].color.setHSL( h, color[1], color[2] );
  var time = Date.now() * 0.00005;
</code>```

Any help would be greatly appreciated.

答:
Something like that?

var colors = [
  '#FF0000', // Red
  '#FF7F00', // Orange
  '#FFFF00', // Yellow
  '#00FF00', // Green
  '#0000FF', // Blue
  '#4B0082', // Indigo
  '#9400D3', // Violet
];

var link = document.getElementById('link');

function calculateColor() {
  var time = Math.floor(Date.now() / 1000);
  link.style.color = colors[time % colors.length];
}

calculateColor();
setInterval(calculateColor, 100);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Link</p></code>```

If you need another frequency instead of 1 second, you could keep the timestamp rounded until the next time interval... I don't know if I make myself clear, because I don't know how to explain it. It'd be something like:

var colors = [
  '#FF0000', // Red
  '#FF7F00', // Orange
  '#FFFF00', // Yellow
  '#00FF00', // Green
  '#0000FF', // Blue
  '#4B0082', // Indigo
  '#9400D3', // Violet
];

var link = document.getElementById('link');

var freq = 5; // seconds
var time = Math.floor(Date.now() / 1000);

function calculateColor() {
  var now = Math.floor(Date.now() / 1000);
  var offset = now - time;
  time = offset > freq ? now : time;
  link.style.color = colors[time % colors.length];
}

calculateColor();
setInterval(calculateColor, 100);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Link</p></code>```

Body:
I'm trying to change the color of a link over time cycling through rainbow colors. When you refresh the color should still be the same it was a moment ago, not begin a new cycle (so CSS animations haven't worked for me yet either).

I am trying to apply the color of this calculation to the hover function of a link.

  var h = ( 60 * ( color[0] + time ) % 360 ) / 360;
  materials[i].color.setHSL( h, color[1], color[2] );
  var time = Date.now() * 0.00005;

Any help would be greatly appreciated.

Body:
Something like that?

var colors = [
  '#FF0000', // Red
  '#FF7F00', // Orange
  '#FFFF00', // Yellow
  '#00FF00', // Green
  '#0000FF', // Blue
  '#4B0082', // Indigo
  '#9400D3', // Violet
];

var link = document.getElementById('link');

function calculateColor() {
  var time = Math.floor(Date.now() / 1000);
  link.style.color = colors[time % colors.length];
}

calculateColor();
setInterval(calculateColor, 100);

<p><a id="link" href="#">Link</a></p>

If you need another frequency instead of 1 second, you could keep the timestamp rounded until the next time interval... I don't know if I make myself clear, because I don't know how to explain it. It'd be something like:

var colors = [
  '#FF0000', // Red
  '#FF7F00', // Orange
  '#FFFF00', // Yellow
  '#00FF00', // Green
  '#0000FF', // Blue
  '#4B0082', // Indigo
  '#9400D3', // Violet
];

var link = document.getElementById('link');

var freq = 5; // seconds
var time = Math.floor(Date.now() / 1000);

function calculateColor() {
  var now = Math.floor(Date.now() / 1000);
  var offset = now - time;
  time = offset > freq ? now : time;
  link.style.color = colors[time % colors.length];
}

calculateColor();
setInterval(calculateColor, 100);

<p><a id="link" href="#">Link</a></p>


问:
Can DVD+R hold .iso files and boot up via to bios?
This seems like a stupid question, I know, but can I take a DVD+R and use that as a .iso image DVD and then boot a program from the bios with it? If not, what type of CD do I need?</p>

答: AFAIK, the type of medium the ISO file is on is irrelevant so long as it is a bootable ISO.</p>


问:
Python: Removing a specific item that has a duplicate only knowing its index in a list
What I want this program to do is to delete all the 1's that are in the list that follow by index all the 2's.

This is the code:

```<code>a = [3, 1, 2, 1]
a.remove(a[3])
print(a)
</code>```

I really put this program into the basics but the point is that I have only got the index of the 1 that follows the 2, tho when I do this the result is:

```<code>[3, 2, 1]
</code>```

This means that it doesn't delete the 1 I want but just the first 1 it finds. Tho this is really a problem in a real program situation where the first 1 is an important value.

How can I fix it? Thanks

答:
Using enumerate() and a list comprehension:

```<code>>>> a = [3, 1, 2, 1]
>>> [v for i, v in enumerate(a) if not i or not (v == 1 and a[i-1] == 2)]
[3, 1, 2]
</code>```

Body:
What I want this program to do is to delete all the 1's that are in the list that follow by index all the 2's.

This is the code:

a = [3, 1, 2, 1]
a.remove(a[3])
print(a)

I really put this program into the basics but the point is that I have only got the index of the 1 that follows the 2, tho when I do this the result is:

[3, 2, 1]

This means that it doesn't delete the 1 I want but just the first 1 it finds. Tho this is really a problem in a real program situation where the first 1 is an important value.

How can I fix it? Thanks

Body:
Using enumerate() and a list comprehension:

>>> a = [3, 1, 2, 1]
>>> [v for i, v in enumerate(a) if not i or not (v == 1 and a[i-1] == 2)]
[3, 1, 2]


问:
Portable docker daemon for deterministic CI builds
We are looking to make use of Docker to run integration tests within CI builds (with Bazel).
We need to support Debian as well as MacOS.

In order to guarantee build correctness, and ensure determinism and portability, we cannot rely on the host having a running docker daemon. The build needs to come with its own docker daemon.
What is the best way to achieve this? Is there a standard “portable” docker binary?
If not, what do you think would be the right approach to implement this?
In linux systems, I imagine this would be relatively simple, as we would just need to download the binaries and run.
In MacOS, I guess we would need to bundle it with hyperkit.

Would love to hear your thoughts on this.

答:
In terms of building Docker images, you should look at bazelbuild/rules_docker (disclaimer: I wrote/own them).  They implement the only properly deterministic Docker builds of which I'm aware (at least to Bazel's standard).

They do this by avoiding Dockerfile and the Docker daemon (which most other approaches use), as it is unclear these can produce deterministic artifacts.  This avoids the root requirement too, which is nice.

However, you specifically asked about testing, which tl;dr we have not solved.

@ittaiz is also interested in this and started this Github issue for discussing it.  Would you mind moving the discussion there?


问:
jHtmlArea creates really small editing area
I have a problem that I can't seem to figure out. I am using jHtmlArea 0.8 along with jQuery v3.2.1. I created a dialog with a TEXTAREA which I am using jHTMLArea to convert to an HTML editing area.

My problem is that the HTMLArea seems to be created but it doesn't really give me an editing area. I have searched to see if there is a way to control the height but, based on what I see in the source code, the height of the HTMLArea should match the size of the textarea. I have checked my css and I cannot find anything that might cause this.

I have posted a simplified version of the page online (all the custom code is inline) at http://issuesnj.com/sample/. Just click on the + button and you should see the issue. I would be grateful for any assistance on this.

The operative code here is the dialog HTML definition and the JavaScript. Here they are:

```<code><div id="divEdit">
    <table>
        <tr>
            <td>Page Name</td>
            <td><input name="pageName" id="pageName" style="width:400px" type="text"></td>
        </tr>
        <tr>
            <td>Page Title (shows on the tab)</td>
            <td><input name="pageTitle" id="pageTitle" style="width:400px" type="text"></td>
        </tr>
        <tr>
            <td>Page Caption</td>
            <td><input name="pageCaption" id="pageCaption" style="width:400px" type="text"></td>
        </tr>
        <tr>
            <td>After upload URL</td>
            <td><input name="afterProcView" id="afterProcView" style="width:400px" type="text"></td>
        </tr>
        <tr>
            <td colspan="2"><br>Page Text:</td>
        </tr>
        <tr>
            <td colspan="2"><textarea name="pageText" id="pageText" rows="20" style="width: 700px;"></textarea></td>
        </tr>
    </table>
</div>
</code>```

Here's the javascript for the dialog and the fnAdd function which has the htmlarea call...

```<code>$(document).ready(function(){
    $("#divEdit").dialog({
        "autoOpen": false,
        "width": "auto",
        "title": "Page Settings",
        "open": function (evt, ui) {
            $("#pageText").htmlarea();
        },
        "buttons":
        [
            {"text": "Save",
             "click": function(){$("#divEdit").dialog("close");}
            },
            {"text": "Cancel",
             "click": function(){$("#divEdit").dialog("close");}
            }
        ]
    });
});

function fnAdd(){
    $("#id").val("New");
    $("#pageName").val("");
    $("#pageTitle").val("");
    $("#pageCaption").val("");
    $("#pageText").htmlarea('html', '\b');
    $("#afterProcView").val("");
    $("#divEdit").dialog("open");
}
</code>```

Thanks in advance!

答:
OK. I have an answer to this one although I am left with a new question (which I guess I will post separately)...

The problem was that I only htmlarea() once (during the edit). I needed to initialize the htmlarea in the document ready function. So, the modified code would look like this:

```<code>$(document).ready(function(){
    $("#pageText").htmlarea();

    $("#divEdit").dialog({
        "autoOpen": false,
        "width": "auto",
        "title": "Page Settings",
        "open": function (evt, ui) {
            $("#pageText").htmlarea();
        },
        "buttons":
        [
            {"text": "Save",
             "click": function(){$("#divEdit").dialog("close");}
            },
            {"text": "Cancel",
             "click": function(){$("#divEdit").dialog("close");}
            }
        ]
    });
});
</code>```

Once I added that generic htmlalrea call, it sized properly. As for the rest, that will be the subject of another question.

Body:
I have a problem that I can't seem to figure out. I am using jHtmlArea 0.8 along with jQuery v3.2.1. I created a dialog with a TEXTAREA which I am using jHTMLArea to convert to an HTML editing area.

My problem is that the HTMLArea seems to be created but it doesn't really give me an editing area. I have searched to see if there is a way to control the height but, based on what I see in the source code, the height of the HTMLArea should match the size of the textarea. I have checked my css and I cannot find anything that might cause this.

I have posted a simplified version of the page online (all the custom code is inline) at http://issuesnj.com/sample/. Just click on the + button and you should see the issue. I would be grateful for any assistance on this.

The operative code here is the dialog HTML definition and the JavaScript. Here they are:

            Page Name
            <input name="pageName" id="pageName" style="width:400px" type="text">

            Page Title (shows on the tab)
            <input name="pageTitle" id="pageTitle" style="width:400px" type="text">

            Page Caption
            <input name="pageCaption" id="pageCaption" style="width:400px" type="text">

            After upload URL
            <input name="afterProcView" id="afterProcView" style="width:400px" type="text">

Page Text:

            <textarea name="pageText" id="pageText" rows="20" style="width: 700px;"></textarea>

Here's the javascript for the dialog and the fnAdd function which has the htmlarea call...

$(document).ready(function(){
    $("#divEdit").dialog({
        "autoOpen": false,
        "width": "auto",
        "title": "Page Settings",
        "open": function (evt, ui) {
            $("#pageText").htmlarea();
        },
        "buttons":
        [
            {"text": "Save",
             "click": function(){$("#divEdit").dialog("close");}
            },
            {"text": "Cancel",
             "click": function(){$("#divEdit").dialog("close");}
            }
        ]
    });
});

function fnAdd(){
    $("#id").val("New");
    $("#pageName").val("");
    $("#pageTitle").val("");
    $("#pageCaption").val("");
    $("#pageText").htmlarea('html', '\b');
    $("#afterProcView").val("");
    $("#divEdit").dialog("open");
}

Thanks in advance!

Body:
OK. I have an answer to this one although I am left with a new question (which I guess I will post separately)...

The problem was that I only htmlarea() once (during the edit). I needed to initialize the htmlarea in the document ready function. So, the modified code would look like this:

$(document).ready(function(){
    $("#pageText").htmlarea();

    $("#divEdit").dialog({
        "autoOpen": false,
        "width": "auto",
        "title": "Page Settings",
        "open": function (evt, ui) {
            $("#pageText").htmlarea();
        },
        "buttons":
        [
            {"text": "Save",
             "click": function(){$("#divEdit").dialog("close");}
            },
            {"text": "Cancel",
             "click": function(){$("#divEdit").dialog("close");}
            }
        ]
    });
});

Once I added that generic htmlalrea call, it sized properly. As for the rest, that will be the subject of another question.


问:
Why is xml declaration getting deleted while parsing?
I'm trying to modify some node value from one xml file to another using the below program which gets the value from the first node pub-title from a xml file in a folder called abc and then pastes the value to the first node publisher-name in another xml file in a folder named xyz.

NOTE: The escape_string method is implemented to not modify the UTF-8 entity values and keep them as they are.

```<code>var job_folders = Directory.EnumerateDirectories(textBox1.Text, "*", SearchOption.TopDirectoryOnly);
foreach (string job_folder in job_folders)
{
    var target_xml_file = Directory.GetFiles(job_folder, "*.xml", SearchOption.AllDirectories).Where(a => Path.GetFileName(Path.GetDirectoryName(x)).ToLower() == "abc").First();
    var target_meta_file = Directory.GetFiles(job_folder, "*.xml", SearchOption.AllDirectories).Where(a => Path.GetFileName(Path.GetDirectoryName(x)).ToLower() == "xyz").First();

    string path = Path.GetFullPath(target_meta_file);
    string file_content = escape_string(File.ReadAllText(path), 0);
    XDocument doc = XDocument.Parse(file_content, LoadOptions.PreserveWhitespace);
    var lbl=doc.Descendants("pub-title").First().Value;
    XDocument doc2 = XDocument.Parse(escape_string(File.ReadAllText(target_xml_file), 0), LoadOptions.PreserveWhitespace);
    doc2.DocumentType.InternalSubset = null;
    doc2.Descendants("publisher-name").First().Value=lbl;
    doc2.Save(target_xml_file);
    File.WriteAllText(target_xml_file, escape_string(doc2.ToString(), 1));
}

MessageBox.Show("Complete");

private static string escape_string(string input_string, int option)
{
    switch (option)
    {
        case 0:
            return input_string.Replace("&", "&").ToString();
        case 1:
            return input_string.Replace("&", "&").ToString();
        default:
            return null;
    }
}
</code>```

Everything goes fine but <?xml version="1.0" encoding="utf-8"?> is getting deleted from the file in target_xml_file.

How do I fix this?
File before modification

```<code><?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="jats-html.xsl"?>
<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD with OASIS Tables v1.0 20120330//EN" "JATS-journalpublishing-oasis-article1.dtd"[]>
<article article-type="proceedings" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:oasis="http://www.niso.org/standards/z39-96/ns/oasis-exchange/table">
<front>
<journal-meta>
<journal-id journal-id-type="publisher-id" />
<journal-title-group>
<journal-title>Eleventh & Tenth International Conference on Correlation Optics</journal-title>
</journal-title-group>
<issn pub-type="epub">0277-786X</issn>
<publisher>
<publisher-name>SPIE</publisher-name>
</publisher>
</journal-meta>
....
....
</code>```

File after

```<code><?xml-stylesheet type="text/xsl" href="jats-html.xsl"?>
<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD with OASIS Tables v1.0 20120330//EN" "JATS-journalpublishing-oasis-article1.dtd">
<article article-type="proceedings" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:oasis="http://www.niso.org/standards/z39-96/ns/oasis-exchange/table">
<front>
<journal-meta>
<journal-id journal-id-type="publisher-id" />
<journal-title-group>
<journal-title>Eleventh & Tenth International Conference on Correlation Optics</journal-title>
</journal-title-group>
<issn pub-type="epub">0277-786X</issn>
<publisher>
<publisher-name>a</publisher-name>
</publisher>
</journal-meta>
</code>```

答:
Following the answer to XDocument.ToString() drops XML Encoding Tag you should not use ToString method, use StringWriter instead:

```<code>using (var stream = new MemoryStream())
{
    using (var writer = new XmlTextWriter(stream, Encoding.UTF8))
    {
        doc2.Save(writer);
    }
    string xml = escape_string(Encoding.UTF8.GetString(stream.ToArray()), 1);
    File.WriteAllBytes(target_xml_file, Encoding.UTF8.GetBytes(xml));
}
</code>```

Body:
I'm trying to modify some node value from one xml file to another using the below program which gets the value from the first node pub-title from a xml file in a folder called abc and then pastes the value to the first node publisher-name in another xml file in a folder named xyz.

NOTE: The escape_string method is implemented to not modify the UTF-8 entity values and keep them as they are.

var job_folders = Directory.EnumerateDirectories(textBox1.Text, "*", SearchOption.TopDirectoryOnly);
foreach (string job_folder in job_folders)
{
    var target_xml_file = Directory.GetFiles(job_folder, "*.xml", SearchOption.AllDirectories).Where(a => Path.GetFileName(Path.GetDirectoryName(x)).ToLower() == "abc").First();
    var target_meta_file = Directory.GetFiles(job_folder, "*.xml", SearchOption.AllDirectories).Where(a => Path.GetFileName(Path.GetDirectoryName(x)).ToLower() == "xyz").First();

    string path = Path.GetFullPath(target_meta_file);
    string file_content = escape_string(File.ReadAllText(path), 0);
    XDocument doc = XDocument.Parse(file_content, LoadOptions.PreserveWhitespace);
    var lbl=doc.Descendants("pub-title").First().Value;
    XDocument doc2 = XDocument.Parse(escape_string(File.ReadAllText(target_xml_file), 0), LoadOptions.PreserveWhitespace);
    doc2.DocumentType.InternalSubset = null;
    doc2.Descendants("publisher-name").First().Value=lbl;
    doc2.Save(target_xml_file);
    File.WriteAllText(target_xml_file, escape_string(doc2.ToString(), 1));
}

MessageBox.Show("Complete");

private static string escape_string(string input_string, int option)
{
    switch (option)
    {
        case 0:
            return input_string.Replace("&", "&").ToString();
        case 1:
            return input_string.Replace("&", "&").ToString();
        default:
            return null;
    }
}

Everything goes fine but <?xml version="1.0" encoding="utf-8"?> is getting deleted from the file in target_xml_file.

How do I fix this?
File before modification

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="jats-html.xsl"?>
<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD with OASIS Tables v1.0 20120330//EN" "JATS-journalpublishing-oasis-article1.dtd"[]>

<front>
<journal-meta>
<journal-id journal-id-type="publisher-id" />
<journal-title-group>
<journal-title>Eleventh & Tenth International Conference on Correlation Optics</journal-title>
</journal-title-group>
<issn pub-type="epub">0277-786X</issn>
<publisher>
<publisher-name>SPIE</publisher-name>
</publisher>
</journal-meta>
....
....

File after

<?xml-stylesheet type="text/xsl" href="jats-html.xsl"?>
<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD with OASIS Tables v1.0 20120330//EN" "JATS-journalpublishing-oasis-article1.dtd">

<front>
<journal-meta>
<journal-id journal-id-type="publisher-id" />
<journal-title-group>
<journal-title>Eleventh & Tenth International Conference on Correlation Optics</journal-title>
</journal-title-group>
<issn pub-type="epub">0277-786X</issn>
<publisher>
<publisher-name>a</publisher-name>
</publisher>
</journal-meta>

Body:
Following the answer to XDocument.ToString() drops XML Encoding Tag you should not use ToString method, use StringWriter instead:

using (var stream = new MemoryStream())
{
    using (var writer = new XmlTextWriter(stream, Encoding.UTF8))
    {
        doc2.Save(writer);
    }
    string xml = escape_string(Encoding.UTF8.GetString(stream.ToArray()), 1);
    File.WriteAllBytes(target_xml_file, Encoding.UTF8.GetBytes(xml));
}


问:
SSIS Data Flow Task column data type float, ignore string values
I am setting up a simple data flow task to pull in multiple CSVs to a SQL Server DB table. A number of columns in the CSV are float but occasionally will say 'N/A*'. I want to keep these columns as floats and make any string in them convert to NULL.

By just ignoring the conversion failure in the flat file source settings, I can achieve this, but I don't think it's best practice to ignore failures. Is the solution just to do a Conditional Split on all these columns to say when 'N/A*' then NULL, else float?

答: You could use a Derived Column to replace the column with a Float column that replaces "N/A" with NULL.</p>


问:
Powershell - Filter scope of line of a CSV
As I am a newbie on powershell, I have tried a lot of thing, but I think I need realy help...

Here is my problem:
I want to filter a scope of line of a csv file to output the non filtered lines in powershell. Moreover, I want to filter the line who have the number "5" at their beginning.

Here is the csv example file when I do the Powershell commands:

```<code>FirstName      Name      PhoneNumber
A               AA            3366
B               BA            3356
C               CC            5898
D               DC            5316
E               EH            5623
F               FB            5963
</code>```

Here, I want to filter the line who beginning by "5" and have a powershell output like that:

```<code>FirstName      Name      PhoneNumber
A               AA            3366
B               BA            3356
</code>```

Here is my powershell code:

```<code>$i = "C:\my_csv_file.csv"
$colonne = "First Name" , "Name" , "PhoneNumber"
$test = Import-Csv -Encoding Default $i -Delimiter ";" | Select  $colonne
echo $test
</code>```

I think (but i'm not sure) that what I have to do to filter is to use a "if" command.

Actually I have tried a lot of "if" with some arguments, but nothing work!

Hope you can help me guys!

Sorry for my bad english, i've tried to write the better that i can. If you don't understand something, tell me, it will be a pleasure to argue more

答:
This will use regex to filter your PhoneNumber property:

```<code>$i = 'C:\my_csv_file.csv'
$colonne = @('First Name', 'Name', 'PhoneNumber')
$test = Import-Csv -Path $i -Encoding Default -Delimiter ';' |
    Where-Object { $_.PhoneNumber -notmatch '^5' } |
    Select-Object -Property $colonne
$test
</code>```

This (Where-Object) will look at the property and remove the phone numbers starting with 5 from the end result.

Body:
As I am a newbie on powershell, I have tried a lot of thing, but I think I need realy help...

Here is my problem:
I want to filter a scope of line of a csv file to output the non filtered lines in powershell. Moreover, I want to filter the line who have the number "5" at their beginning.

Here is the csv example file when I do the Powershell commands:

FirstName      Name      PhoneNumber
A               AA            3366
B               BA            3356
C               CC            5898
D               DC            5316
E               EH            5623
F               FB            5963

Here, I want to filter the line who beginning by "5" and have a powershell output like that:

FirstName      Name      PhoneNumber
A               AA            3366
B               BA            3356

Here is my powershell code:

$i = "C:\my_csv_file.csv"
$colonne = "First Name" , "Name" , "PhoneNumber"
$test = Import-Csv -Encoding Default $i -Delimiter ";" | Select  $colonne
echo $test

I think (but i'm not sure) that what I have to do to filter is to use a "if" command.

Actually I have tried a lot of "if" with some arguments, but nothing work!

Hope you can help me guys!

Sorry for my bad english, i've tried to write the better that i can. If you don't understand something, tell me, it will be a pleasure to argue more

Body:
This will use regex to filter your PhoneNumber property:

$i = 'C:\my_csv_file.csv'
$colonne = @('First Name', 'Name', 'PhoneNumber')
$test = Import-Csv -Path $i -Encoding Default -Delimiter ';' |
    Where-Object { $_.PhoneNumber -notmatch '^5' } |
    Select-Object -Property $colonne
$test

This (Where-Object) will look at the property and remove the phone numbers starting with 5 from the end result.


问:
Firebase Security Rules - Checking if data.hasChild and keeps failing
I have a security rule that looks like this:

```<code>"user_feeds": {
     "$userId": {
        ".indexOn": ["timestamp"],
        ".read": "auth != null",
         "$postId" : {
           ".write": "auth != null && newData.parent().hasChild(newData.child('band_id').val())"
           }
         }
       }
</code>```

in my $postId sub-tree, I'm trying to check to see if the parent has a node that corresponds to the band_id value of the data that is being inserted.

The data looks like:

```<code>{
   post_id: 1,
   band_id: '-L-tyesfsdf13434',
   timestamp: 34234234234
}
</code>```

And an actual tree that these rules would correspond to look like:

```<code>{
   "user_feeds": {
     "userId1": {
        "-L-tyesfsdf13434": true
     }
   }
}
</code>```

I am using Ionic/Angular and here is my function that's actually trying to do the write operation:

```<code>addPostToFollowers(bandId, postId) {

    // 1. Get the user's connections
    this._bands.getBandFollowers(bandId).take(1).subscribe(connections => {
      if(connections.$value !== null) {
        delete connections['$key'];
        delete connections['$exists'];

        let connectionKeys = Object.keys(connections);
        // 2. Go through those connections and add the post
        let bandFeeds = {};
        connectionKeys.forEach(connectionKey => {
          bandFeeds[`/user_feeds/${connectionKey}/${postId}`] = {
            post_id: postId,
            band_id: bandId,
            timestamp: -(+(new Date()))
          }
        })

        // 3. Update the social feeds
        this.db.object(`social`).update(bandFeeds);
      }
    })
  }
</code>```

However, when I try to run this, I get a permission denied and I have no idea why. Am I doing something wrong here?

答:
Try using root.child('user_feeds').child($userId) instead of newData.parent():

```<code>"user_feeds": {
 "$userId": {
    ".indexOn": ["timestamp"],
    ".read": "auth != null",
     "$postId" : {
       ".write": "auth != null && root.child('user_feeds').child($userId)
                    .hasChild(newData.child('band_id').val())"
       }
     }
   }
</code>```

I suspect the newData snapshot is limited to the data at that location and parent() cannot be used to fetch data at a location higher in the database tree.

Body:
I have a security rule that looks like this:

"user_feeds": {
     "$userId": {
        ".indexOn": ["timestamp"],
        ".read": "auth != null",
         "$postId" : {
           ".write": "auth != null && newData.parent().hasChild(newData.child('band_id').val())"
           }
         }
       }

in my $postId sub-tree, I'm trying to check to see if the parent has a node that corresponds to the band_id value of the data that is being inserted.

The data looks like:

{
   post_id: 1,
   band_id: '-L-tyesfsdf13434',
   timestamp: 34234234234
}

And an actual tree that these rules would correspond to look like:

{
   "user_feeds": {
     "userId1": {
        "-L-tyesfsdf13434": true
     }
   }
}

I am using Ionic/Angular and here is my function that's actually trying to do the write operation:

addPostToFollowers(bandId, postId) {

    // 1. Get the user's connections
    this._bands.getBandFollowers(bandId).take(1).subscribe(connections => {
      if(connections.$value !== null) {
        delete connections['$key'];
        delete connections['$exists'];

        let connectionKeys = Object.keys(connections);
        // 2. Go through those connections and add the post
        let bandFeeds = {};
        connectionKeys.forEach(connectionKey => {
          bandFeeds[`/user_feeds/${connectionKey}/${postId}`] = {
            post_id: postId,
            band_id: bandId,
            timestamp: -(+(new Date()))
          }
        })

        // 3. Update the social feeds
        this.db.object(`social`).update(bandFeeds);
      }
    })
  }

However, when I try to run this, I get a permission denied and I have no idea why. Am I doing something wrong here?

Body:
Try using root.child('user_feeds').child($userId) instead of newData.parent():

"user_feeds": {
 "$userId": {
    ".indexOn": ["timestamp"],
    ".read": "auth != null",
     "$postId" : {
       ".write": "auth != null && root.child('user_feeds').child($userId)
                    .hasChild(newData.child('band_id').val())"
       }
     }
   }

I suspect the newData snapshot is limited to the data at that location and parent() cannot be used to fetch data at a location higher in the database tree.


问:
Merge b/w two dask data frame giving MemoryError
Reading the parquet files

```<code>df_ss_parq = dd.read_parquet("trainSearchStream.parquet/")
df_ai_parq = dd.read_parquet("AdsInfo.parquet/")
</code>```

Merging the two datasets

```<code>df_train =(df_ss_parq.merge(df_ai,on="ad_id",how="left")
       ).compute()
</code>```

RAM: 16 GB

I have tried using an index on column "ad_id" which makes it faster but shows the same error.

trainSearchStream size = 17 GB

AdsInfo size = 17 GB

Anybody have any idea how to solve it?

答: I would suggest using a SQL engine like Impala or Drill to do the join, writing the result out to new Parquet files. The Python data stack is not very well-suited right now for handling joins between large tables in a memory-constrained environment. </p>

Body:
Reading the parquet files

df_ss_parq = dd.read_parquet("trainSearchStream.parquet/")
df_ai_parq = dd.read_parquet("AdsInfo.parquet/")

Merging the two datasets

df_train =(df_ss_parq.merge(df_ai,on="ad_id",how="left")
       ).compute()

RAM: 16 GB

I have tried using an index on column "ad_id" which makes it faster but shows the same error.

trainSearchStream size = 17 GB

AdsInfo size = 17 GB

Anybody have any idea how to solve it?


问:
Autolayout : Need constraints for y position or height
I am trying to satisfying the constraint form a long time but getting above error i.e. is "Need constraints for y position or height" for Yellow View and Green View. Basically I have 2 UILabel (dynamic height) within UIView and UIImageView of 4:3 ratio within a Cell.

And my applied constraint is

I am also including sample project here with above issue.

答: I am attaching two images, one is output and another one is the constraints of views (UILabel, UIImageView). For testing purpose, I put long texts in UILabel, after testing I reduced the text to 'Heading it is' and 'Sub heading it is'. Let me know, if its working of not.enter image description here


问:
In SQL Server, casting varchar to int converts the blank to 0, is there a way to avoid this?
```<code> sample0 <- paste("SELECT cast([Date] as Date) as Date values (NULL)
              ,[Major_Asset_Class] values (NULL)
              ,[Country] values (NULL)
              ,cast([CPI_Index] as float) as CPI_Index values (NULL)
              ,cast([GDP] as float) as GDP values (NULL)
              ,cast([",Local_Earning_Index,"] as float) as Local_Earning_Index values (NULL)
              ,cast([",Local_MARKET_CAP,"] as float) as Local_MARKET_CAP values (NULL)
              ,cast([",Local_NET_DVD,"] as float) as Local_NET_DVD values (NULL)
              ,cast([",Local_Price_Index,"] as float) as Local_Price_Index values (NULL)
              ,cast([",MSCI_Earning_Index,"] as float) as MSCI_Earning_Index values (NULL)
              ,cast([",MSCI_MARKET_CAP,"] as float) as MSCI_MARKET_CAP values (NULL)
              ,cast([",MSCI_NET_DVD,"] as float) as MSCI_NET_DVD values (NULL)
              ,cast([",MSCI_Price_Index,"] as float) as MSCI_Price_Index values (NULL)
              ,cast([",Volitility_Index,"] as FLOAT) as Volitility_Index values (NULL)
              ,cast([",Local_TtlGrs_Return,"] as float) as Local_TtlGrs_Return values (NULL)
              ,cast([",Local_TtlNet_Return,"] as float) as Local_TtlNet_Return into values (NULL)
              Last_Month_Data_1$
              FROM [Tableau].[dbo].[Last_Month_Data]",sep="")
</code>```

I don't want the blanks in each column to convert to 0s. How can i avoid that?

答:
You can wrap your cast in a isnull statement and tell sql server what you want null values to be set too:

```<code>isnull(filename,<New value>)
</code>```

where  can be 0, -1, or any other valid value, an int since you are casting to int. The final line with casting would be

```<code>cast(isnull(fieldname,'-1') as int)
</code>```

Assuming you want null's to be -1

If you want a blank, you'll need to use a case statement to determine if it is null, then return as a string, else return the value. See first answers link for example or as follows:

```<code>case when (isnull(fieldname,'') = '') then ''
     else cast(fieldname as int)
     end as fieldname
</code>```

First line checks if the fields value is null and returns '' as existing type (varchar in your case), else it does the cast to int.

Body:
 sample0 <- paste("SELECT cast([Date] as Date) as Date values (NULL)
              ,[Major_Asset_Class] values (NULL)
              ,[Country] values (NULL)
              ,cast([CPI_Index] as float) as CPI_Index values (NULL)
              ,cast([GDP] as float) as GDP values (NULL)
              ,cast([",Local_Earning_Index,"] as float) as Local_Earning_Index values (NULL)
              ,cast([",Local_MARKET_CAP,"] as float) as Local_MARKET_CAP values (NULL)
              ,cast([",Local_NET_DVD,"] as float) as Local_NET_DVD values (NULL)
              ,cast([",Local_Price_Index,"] as float) as Local_Price_Index values (NULL)
              ,cast([",MSCI_Earning_Index,"] as float) as MSCI_Earning_Index values (NULL)
              ,cast([",MSCI_MARKET_CAP,"] as float) as MSCI_MARKET_CAP values (NULL)
              ,cast([",MSCI_NET_DVD,"] as float) as MSCI_NET_DVD values (NULL)
              ,cast([",MSCI_Price_Index,"] as float) as MSCI_Price_Index values (NULL)
              ,cast([",Volitility_Index,"] as FLOAT) as Volitility_Index values (NULL)
              ,cast([",Local_TtlGrs_Return,"] as float) as Local_TtlGrs_Return values (NULL)
              ,cast([",Local_TtlNet_Return,"] as float) as Local_TtlNet_Return into values (NULL)
              Last_Month_Data_1$
              FROM [Tableau].[dbo].[Last_Month_Data]",sep="")

I don't want the blanks in each column to convert to 0s. How can i avoid that?

Body:
You can wrap your cast in a isnull statement and tell sql server what you want null values to be set too:

isnull(filename,<New value>)

where  can be 0, -1, or any other valid value, an int since you are casting to int. The final line with casting would be

cast(isnull(fieldname,'-1') as int)

Assuming you want null's to be -1

If you want a blank, you'll need to use a case statement to determine if it is null, then return as a string, else return the value. See first answers link for example or as follows:

case when (isnull(fieldname,'') = '') then ''
     else cast(fieldname as int)
     end as fieldname

First line checks if the fields value is null and returns '' as existing type (varchar in your case), else it does the cast to int.


问:
unable to run sql query from CRON
I need to add my script to cronjob. but it is not getting connected to sqlprompt and executing my query. Cron works fine for other commands which are not inside sqlprompt
    #!/bin/bash

```<code>sql=/instance_name/../product/12102 // ORACLE_HOME loc

connnect=$($sql -s "/ as sysdba" <<EOF
spool h1.txt
select file_name from dba_data_files where tablespace_name='RTSPACE';
spool off;
exit
EOF)
cat "h1.txt" | mail -s "test" xyz@yahoo.com
exit
</code>```

Problem I am facing is, script is not getting connected to sqlprompt.
I am currently getting mail. but the ouput of query is not getting read. so my body of the mail is blank.

答:
I Found the solution. just source ~./profile for any shell other than bash and source ~./bash_profile for bash shell. redirect both to >/dev/null incase of any error. this shud connect to your sql prompt. </p>

```<code>source ~./bash_profile >/dev/null
source ~./profile >/dev/null

sqlplus -s "/ as sysdba" <<EOF
spool h1.txt
select file_name from dba_data_files where tablespace_name='RTSPACE';
spool off;
exit
EOF)
cat "h1.txt" | mail -s "test" xyz@yahoo.com
exit
</code>```

Title: unable to run sql query from CRON

Body:
I need to add my script to cronjob. but it is not getting connected to sqlprompt and executing my query. Cron works fine for other commands which are not inside sqlprompt
    #!/bin/bash

sql=/instance_name/../product/12102 // ORACLE_HOME loc

connnect=$($sql -s "/ as sysdba" <<EOF
spool h1.txt
select file_name from dba_data_files where tablespace_name='RTSPACE';
spool off;
exit
EOF)
cat "h1.txt" | mail -s "test" xyz@yahoo.com
exit

Problem I am facing is, script is not getting connected to sqlprompt.
I am currently getting mail. but the ouput of query is not getting read. so my body of the mail is blank.

Body:
I Found the solution. just source ~./profile for any shell other than bash and source ~./bash_profile for bash shell. redirect both to >/dev/null incase of any error. this shud connect to your sql prompt.

source ~./bash_profile >/dev/null
source ~./profile >/dev/null

sqlplus -s "/ as sysdba" <<EOF
spool h1.txt
select file_name from dba_data_files where tablespace_name='RTSPACE';
spool off;
exit
EOF)
cat "h1.txt" | mail -s "test" xyz@yahoo.com
exit


问:
Angular/TypeScript - http post using a custom class' toString()
I am using Angular Reactive forms, I am getting form.value and sending it to asp.net web-api. The object named len in the code snipped below is a custom class that I wrote that is a very simple version of TimeSpan.

Here is my request;

```<code>{
  "id": "a7b06cf9-36a5-4c7a-99e5-8b9661469329",
  "minCapacity": 5,
  "maxCapacity": 10,
  "len": {
    "Days": 0,
    "Hours": 2,
    "Minutes": 0
  },
}
</code>```

By default .NET TimeSpan requires an input like this:

string.Format("{0}.{1}:{2}:{3}", len.Days, len.Hours, len.Minutes, len.Seconds)

And otherwise grabs the variable len as null.

Therefore, I have implemented an override toString() to my custom TimeSpan class. Yet when using the HTTP class in my Typescript code I still get the object in JSON format.

I have fiddled around SO for a couple hours, as well as google, yet I have failed to find an answer. I am hoping this is not a duplicate

Is there a way to override this at client side?

component.ts

```<code>saveItem(model: Room) {
    let selected = this.selected;
    this.roomService.createUpdateRoom(model).subscribe(
        response => {
            Helpers.setLoading(false);
            var result = response as ServiceResult<any>;
            if (result.hasError) {
                this.toaster.error(result.message, 'Error');
            }
            else {
                alert('ok');
                this.viewForm();
            }
        },
        error => {
            this.toaster.error(error.message, 'Error');
        });
}
</code>```

service.ts

```<code>createUpdateRoom(request) {
    return this.post('api/v1.0/room/createupdate', true, request);
}
</code>```

base.service.ts

```<code>post(apiAddress: string, isAuthorizeRequest: boolean, parameter: any): Observable<any> {
        return this.intercept(this.injector.get(AuthHttp).post(this.baseUrl + apiAddress, parameter).map(
            (response) => {
                let data = response.json();
                if (data) {
                    httpSuccess = data;
                }
                return httpSuccess;
            }
        ));
    }
</code>```

timespan.ts

```<code>export class TimeSpan {
day: number = 0;
hour: number = 0;
minute: number = 0;

toTimeString(): string {
    return this.hour +':' + this.minute;
}

toString = (): string => {

    return this.day + ':' + this.toTimeString() + ':00';
}
}
</code>```

room.ts

```<code>export class Room {
    id: string;
    minCapacity: number;
    maxCapacity: number;
    len: TimeSpan;
}
</code>```

答: I got a similar problem, when the form-model was different from the data-model on a specific property. What I ended up doing is specifying a pre-processing and post-processing step when converting from the form-model to the data-model and vice-versa. This might not be the best solution but by making it a clear pattern it was easy to manage.</p>

Body:
I am using Angular Reactive forms, I am getting form.value and sending it to asp.net web-api. The object named len in the code snipped below is a custom class that I wrote that is a very simple version of TimeSpan.

Here is my request;

{
  "id": "a7b06cf9-36a5-4c7a-99e5-8b9661469329",
  "minCapacity": 5,
  "maxCapacity": 10,
  "len": {
    "Days": 0,
    "Hours": 2,
    "Minutes": 0
  },
}

By default .NET TimeSpan requires an input like this:

string.Format("{0}.{1}:{2}:{3}", len.Days, len.Hours, len.Minutes, len.Seconds)

And otherwise grabs the variable len as null.

Therefore, I have implemented an override toString() to my custom TimeSpan class. Yet when using the HTTP class in my Typescript code I still get the object in JSON format.

I have fiddled around SO for a couple hours, as well as google, yet I have failed to find an answer. I am hoping this is not a duplicate

Is there a way to override this at client side?

component.ts

saveItem(model: Room) {
    let selected = this.selected;
    this.roomService.createUpdateRoom(model).subscribe(
        response => {
            Helpers.setLoading(false);
            var result = response as ServiceResult<any>;
            if (result.hasError) {
                this.toaster.error(result.message, 'Error');
            }
            else {
                alert('ok');
                this.viewForm();
            }
        },
        error => {
            this.toaster.error(error.message, 'Error');
        });
}

service.ts

createUpdateRoom(request) {
    return this.post('api/v1.0/room/createupdate', true, request);
}

base.service.ts

post(apiAddress: string, isAuthorizeRequest: boolean, parameter: any): Observable<any> {
        return this.intercept(this.injector.get(AuthHttp).post(this.baseUrl + apiAddress, parameter).map(
            (response) => {
                let data = response.json();
                if (data) {
                    httpSuccess = data;
                }
                return httpSuccess;
            }
        ));
    }

timespan.ts

export class TimeSpan {
day: number = 0;
hour: number = 0;
minute: number = 0;

toTimeString(): string {
    return this.hour +':' + this.minute;
}

toString = (): string => {

    return this.day + ':' + this.toTimeString() + ':00';
}
}

room.ts

export class Room {
    id: string;
    minCapacity: number;
    maxCapacity: number;
    len: TimeSpan;
}


问:
Bootstrap 3 multi level dropdown menu not working in mobile
Bootstrap 3 multi level dropdown menu not working on mobile devices. I checked many solution in StackOverflow. That solution for Desktop not for mobile. Below is the best solutions for multi lebel dropdown menu.

Bootstrap 3 dropdown sub menu missing

https://github.com/djokodonev/bootstrap-multilevel-dropdown

```<code>$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
  // Avoid following the href location when clicking
  event.preventDefault();
  // Avoid having the menu to close when clicking
  event.stopPropagation();
  // If a menu is already open we close it
  $('ul.dropdown-menu [data-toggle=dropdown]').parent().removeClass('open');
  // opening the one you clicked on
  $(this).parent().addClass('open');
});
</code>```

Above code is working well for desktop.

Live example: http://rahulmoral.com/portfolio/essanet/

Please view on mobile devices. Second level dropdown-menu will not work on mobile devices.

答:
i got it to working by adding this to my css

```<code>@media screen and (max-width: 767px){
.navbar-fixed-top .navbar-collapse{
    max-height:100%;
} }
</code>```

but instead of 100% you can also use none. i am using a fixed nav which is why i have navbar fixed top. u can change it to static or w.e. you are using.

Body:
Bootstrap 3 multi level dropdown menu not working on mobile devices. I checked many solution in StackOverflow. That solution for Desktop not for mobile. Below is the best solutions for multi lebel dropdown menu.

Bootstrap 3 dropdown sub menu missing

https://github.com/djokodonev/bootstrap-multilevel-dropdown

$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
  // Avoid following the href location when clicking
  event.preventDefault();
  // Avoid having the menu to close when clicking
  event.stopPropagation();
  // If a menu is already open we close it
  $('ul.dropdown-menu [data-toggle=dropdown]').parent().removeClass('open');
  // opening the one you clicked on
  $(this).parent().addClass('open');
});

Above code is working well for desktop.

Live example: http://rahulmoral.com/portfolio/essanet/

Please view on mobile devices. Second level dropdown-menu will not work on mobile devices.

Body:
i got it to working by adding this to my css

@media screen and (max-width: 767px){
.navbar-fixed-top .navbar-collapse{
    max-height:100%;
} }

but instead of 100% you can also use none. i am using a fixed nav which is why i have navbar fixed top. u can change it to static or w.e. you are using.


问:
Meteor MongoDB return single object
```<code>{
    "_id" : "R9zbu8oTWwgxT5eCR",
    "practiceSetup" : {
        "operatoriesSettings" : [
            {
                "name" : "Operatory 1",
                "description" : "Room 1",
                "status" : true
            },
                            {
                "name" : "Operatory 2",
                "description" : "Room B",
                "status" : true
            }
        ],

}
</code>```

I'm trying to lookup object that has name "Operatory 1" and only return that object.

Here is what I have tried,

```<code>Practice.findOne({ _id: 'R9zbu8oTWwgxT5eCR' }, { "$elemMatch": { "practiceSetup.operatoriesSettings": { "name": "Operatory 1" } } } );
</code>```

However this will return the whole document, not that particular object, not sure what I'm doing wrong here.

答:
I found that using "Projections" will return matched object off an array.

Query:

```<code>{ "_id": "R9zbu8oTWwgxT5eCR", "practiceSetup.operatoriesSettings": { $elemMatch: {'name': 'Operatory 1'} } }
</code>```

Projection

```<code>{"practiceSetup.operatoriesSettings.$.name": 1}
</code>```

Full Query:

```<code>db.Practice.findOne({
    "_id" : "R9zbu8oTWwgxT5eCR",
    "practiceSetup.operatoriesSettings" : {
        "$elemMatch" : {
            "name" : "Operatory 1"
        }
    }
}, {
    "practiceSetup.operatoriesSettings.$.name" : 1.0
});
</code>```

Returns

```<code>{
    "_id" : "R9zbu8oTWwgxT5eCR",
    "practiceSetup" : {
        "operatoriesSettings" : [
            {
                "name" : "Operatory 1",
                "description" : "Room 1",
                "status" : true
            }
        ]
    }
}
</code>```

Meteor

When using Meteor methods, you will need to use "fields" when using Projections.

```<code>   return Practice.findOne({
        "_id": "R9zbu8oTWwgxT5eCR",
        "practiceSetup.operatoriesSettings": {
          "$elemMatch": {
            "name": data
          }
        }
      },
        { fields: { 'practiceSetup.operatoriesSettings.$.name': 1, _id: 0 } }
       );
</code>```

Title: Meteor MongoDB return single object

Body:
{
    "_id" : "R9zbu8oTWwgxT5eCR",
    "practiceSetup" : {
        "operatoriesSettings" : [
            {
                "name" : "Operatory 1",
                "description" : "Room 1",
                "status" : true
            },
                            {
                "name" : "Operatory 2",
                "description" : "Room B",
                "status" : true
            }
        ],

}

I'm trying to lookup object that has name "Operatory 1" and only return that object.

Here is what I have tried,

Practice.findOne({ _id: 'R9zbu8oTWwgxT5eCR' }, { "$elemMatch": { "practiceSetup.operatoriesSettings": { "name": "Operatory 1" } } } );

However this will return the whole document, not that particular object, not sure what I'm doing wrong here.

Body:
I found that using "Projections" will return matched object off an array.

Query:

{ "_id": "R9zbu8oTWwgxT5eCR", "practiceSetup.operatoriesSettings": { $elemMatch: {'name': 'Operatory 1'} } }

Projection

{"practiceSetup.operatoriesSettings.$.name": 1}

Full Query:

db.Practice.findOne({
    "_id" : "R9zbu8oTWwgxT5eCR",
    "practiceSetup.operatoriesSettings" : {
        "$elemMatch" : {
            "name" : "Operatory 1"
        }
    }
}, {
    "practiceSetup.operatoriesSettings.$.name" : 1.0
});

Returns

{
    "_id" : "R9zbu8oTWwgxT5eCR",
    "practiceSetup" : {
        "operatoriesSettings" : [
            {
                "name" : "Operatory 1",
                "description" : "Room 1",
                "status" : true
            }
        ]
    }
}

Meteor

When using Meteor methods, you will need to use "fields" when using Projections.

   return Practice.findOne({
        "_id": "R9zbu8oTWwgxT5eCR",
        "practiceSetup.operatoriesSettings": {
          "$elemMatch": {
            "name": data
          }
        }
      },
        { fields: { 'practiceSetup.operatoriesSettings.$.name': 1, _id: 0 } }
       );


问:
How to hide form code from view code/inspect element browser?
I want to hide form code from view code/inspect element browser , how can i do that ?

This is my code, please see below:

```<code><div style=" text-align: center;  padding: 300px; font-family: lato; ">
     Please wait redirect page ......<br>
    <img src="http://maps.nrel.gov/sites/all/modules/custom_modules/hydra/assets/images/loading_bar.gif" border="0">
</div>

<form name="f1" action="payments.php" method="post">
<input type="hidden" name="id_crad" value="...">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="amount" value="12.99">
</form>

<script type="text/javascript">
setTimeout(function(){f1.submit();}, 3000);
</script>
</code>```

Please see picture

答:
Below JavaScript code worked for me to disable inspect element. </p>

```<code>// Disable inspect element
$(document).bind("contextmenu",function(e) {
 e.preventDefault();
});
$(document).keydown(function(e){
    if(e.which === 123){
       return false;
    }
});
</code>```

Body:
I want to hide form code from view code/inspect element browser , how can i do that ?

This is my code, please see below:

     Please wait redirect page ......

<form name="f1" action="payments.php" method="post">
<input type="hidden" name="id_crad" value="...">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="amount" value="12.99">
</form>

Please see picture

Body:
Below JavaScript code worked for me to disable inspect element.

// Disable inspect element
$(document).bind("contextmenu",function(e) {
 e.preventDefault();
});
$(document).keydown(function(e){
    if(e.which === 123){
       return false;
    }
});