问:
Converting hex into a string using 'sprintf'
I am trying to convert an array into hex and then put it into a string variable. In the following loop the printf works fine, but I can not use sprintf properly. How can I stuff the hex values into the array as ASCII?</p>

```<code>static unsigned char  digest[16];
static unsigned char hex_tmp[16];

for (i = 0; i < 16; i++) {
  printf("%02x",digest[i]);  <--- WORKS
  sprintf(&hex_tmp[i], "%02x", digest[i]);  <--- DOES NOT WORK!
}
</code>```

答:
Perhaps you need:

```<code>&hex_tmp[i * 2]
</code>```

And also a bigger array.

Body:
I am trying to convert an array into hex and then put it into a string variable. In the following loop the printf works fine, but I can not use sprintf properly. How can I stuff the hex values into the array as ASCII?

static unsigned char  digest[16];
static unsigned char hex_tmp[16];

for (i = 0; i < 16; i++) {
  printf("%02x",digest[i]);  <--- WORKS
  sprintf(&hex_tmp[i], "%02x", digest[i]);  <--- DOES NOT WORK!
}

Body:
Perhaps you need:

&hex_tmp[i * 2]

And also a bigger array.


来源: stackexchange

问:
Trouble changing css `top` value to fixed element with js
Trying to move a position:fixed div on scroll by changing the top: css value in javascript. The div won't move though, not sure why.

html:

```<code><div id="red">
  <div id="blue"></div>
</div>
</code>```

css:

```<code>#red {
  position: relative;
  float: left;
  width: 100%;
  height: 1000px;
  background: rgba(255, 0, 0, 0.2);
  border: solid 2px #f0f;
}

#blue {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 50vh;
  background: rgba(0, 0, 255, 0.2);
  border: solid 2px #0ff;
}
</code>```

js:

```<code>window.addEventListener('scroll', function() {
  var yPos = -(Math.floor(document.body.scrollTop / 10));
  //console.log("yPos = " + yPos); //output is correct
  document.getElementById('blue').style.top = yPos + 'px';
  //document.getElementById('blue').setAttribute('top',yPos); //also tried this
});
</code>```

https://jsfiddle.net/akzx43yL/

Why isn't the top css value changing and how can I get it to do so? No jquery please.

答:
Two things:

Instead of document.documentElement.scrollTop, you should use window.pageYOffset (scrollTop doesn't play nicely in Chrome).

You need to add a unit of measurement after you update top; values other than 0 should have px appened to them.

This can be seen in the following:

window.addEventListener('scroll', function() {
  var yPos = -(Math.floor(window.pageYOffset / 10));
  document.getElementById('blue').style.top = yPos + "px";

  // Optionally log the `top` value
  //console.log(document.getElementById('blue').style.top);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#red {
  position: relative;
  float: left;
  width: 100%;
  height: 1000px;
  background: rgba(255, 0, 0, 0.2);
  border: solid 2px #f0f;
}

#blue {
  position: absolute;
  top: -10px;
  left: 0;
  width: 100vw;
  height: 50vh;
  background: rgba(0, 0, 255, 0.2);
  border: solid 2px #0ff;
}</code>```

```

Hope this helps! :)

ContentLicense: CC BY-SA 3.0

Body:
Trying to move a position:fixed div on scroll by changing the top: css value in javascript. The div won't move though, not sure why.

html:

css:

#red {
  position: relative;
  float: left;
  width: 100%;
  height: 1000px;
  background: rgba(255, 0, 0, 0.2);
  border: solid 2px #f0f;
}

#blue {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 50vh;
  background: rgba(0, 0, 255, 0.2);
  border: solid 2px #0ff;
}

js:

window.addEventListener('scroll', function() {
  var yPos = -(Math.floor(document.body.scrollTop / 10));
  //console.log("yPos = " + yPos); //output is correct
  document.getElementById('blue').style.top = yPos + 'px';
  //document.getElementById('blue').setAttribute('top',yPos); //also tried this
});

https://jsfiddle.net/akzx43yL/

Why isn't the top css value changing and how can I get it to do so? No jquery please.

Body:
Two things:

Instead of document.documentElement.scrollTop, you should use window.pageYOffset (scrollTop doesn't play nicely in Chrome).

You need to add a unit of measurement after you update top; values other than 0 should have px appened to them.

This can be seen in the following:

window.addEventListener('scroll', function() {
  var yPos = -(Math.floor(window.pageYOffset / 10));
  document.getElementById('blue').style.top = yPos + "px";

  // Optionally log the `top` value
  //console.log(document.getElementById('blue').style.top);
});

#red {
  position: relative;
  float: left;
  width: 100%;
  height: 1000px;
  background: rgba(255, 0, 0, 0.2);
  border: solid 2px #f0f;
}

#blue {
  position: absolute;
  top: -10px;
  left: 0;
  width: 100vw;
  height: 50vh;
  background: rgba(0, 0, 255, 0.2);
  border: solid 2px #0ff;
}

<div id="red">
  <div id="blue"></div>
</div>

Hope this helps! :)


问:
Formatting printed code with TypeScript compiler API
I have a TypeScript code generation scenario, where I construct an AST and then print it and save to a file. The printed class declaration elements, for example, are clustered together. How could one achieve the type of pretty printing that would insert newlines after new method/constructor declarations and perhaps could stack extension methods in new lines?

```<code>private baseUrl = "api/students";
constructor(private http: Http) { }
list(): Promise<Student[]> {
    return this.http.get(this.baseUrl + "/").toPromise().then((response: Response) => response.json()).catch(this.handleError);
}
get(id: number): Promise<Student> {
    return this.http.get(this.baseUrl + ("/" + id)).toPromise().then((response: Response) => response.json()).catch(this.handleError);
}
</code>```

Any existing API`s can suffice or is there a way to manually insert some trailing trivia after declarations?

答:
The formatting API will help with this:

```<code>const languageService: ts.LanguageService = ...;
const sourceFile: ts.SourceFile = ...;
const filePath: string = ...;

const textChanges = languageService.getFormattingEditsForDocument(filePath, {
    convertTabsToSpaces: true,
    insertSpaceAfterCommaDelimiter: true,
    insertSpaceAfterKeywordsInControlFlowStatements: true,
    insertSpaceBeforeAndAfterBinaryOperators: true,
    newLineCharacter: "\n",
    indentStyle: ts.IndentStyle.Smart,
    indentSize: 4,
    tabSize: 4
});

let finalText = sourceFile.getFullText();

for (const textChange in textChanges.sort((a, b) => b.span.start - a.span.start)) {
    const {span} = textChange;
    finalText = finalText.slice(0, span.start) + textChange.newText
        + finalText.slice(span.start + span.length);
}

// finalText contains the formatted text
</code>```

That said, you might want to check out tsfmt which will do this for you.

Body:
I have a TypeScript code generation scenario, where I construct an AST and then print it and save to a file. The printed class declaration elements, for example, are clustered together. How could one achieve the type of pretty printing that would insert newlines after new method/constructor declarations and perhaps could stack extension methods in new lines?

private baseUrl = "api/students";
constructor(private http: Http) { }
list(): Promise<Student[]> {
    return this.http.get(this.baseUrl + "/").toPromise().then((response: Response) => response.json()).catch(this.handleError);
}
get(id: number): Promise<Student> {
    return this.http.get(this.baseUrl + ("/" + id)).toPromise().then((response: Response) => response.json()).catch(this.handleError);
}

Any existing API`s can suffice or is there a way to manually insert some trailing trivia after declarations?

Body:
The formatting API will help with this:

const languageService: ts.LanguageService = ...;
const sourceFile: ts.SourceFile = ...;
const filePath: string = ...;

const textChanges = languageService.getFormattingEditsForDocument(filePath, {
    convertTabsToSpaces: true,
    insertSpaceAfterCommaDelimiter: true,
    insertSpaceAfterKeywordsInControlFlowStatements: true,
    insertSpaceBeforeAndAfterBinaryOperators: true,
    newLineCharacter: "\n",
    indentStyle: ts.IndentStyle.Smart,
    indentSize: 4,
    tabSize: 4
});

let finalText = sourceFile.getFullText();

for (const textChange in textChanges.sort((a, b) => b.span.start - a.span.start)) {
    const {span} = textChange;
    finalText = finalText.slice(0, span.start) + textChange.newText
        + finalText.slice(span.start + span.length);
}

// finalText contains the formatted text

That said, you might want to check out tsfmt which will do this for you.


问:
Vue js: Computed property not updating when changing route
I have a dashboard page that when I refresh the page it works fine, I retrieved my data. However, when I go to other links and move back to my dashboard page (previous page) it doesn't update my computed giveaways property, it doesn't return the data anymore but in my response It still work fine it just not rendering because of my computed property. I'm using axios in my vuex, I tried also the this.$forceUpdate but I don't know where's the right place to do this. What I trying to make is like everytime they go that dashboard.vue page whether its via refresh or vue-route it should reupdate the computed property because I reevaluate the data from my serverside.

Here is my Dashboard.vue script

```<code>import {mapState} from 'vuex'
import { mapGetters } from 'vuex'

export default{
    ready(){
        this.loaded =false;

    },
    data: () => ({
        cards: [

        ],
        cards_offender:[

        ],
        //giveaways: '',

        loaded: true
    }),
    computed:{
        ...mapState({
            Giveaway: state => state.Threshold.giveaways
        }),
        ...mapGetters({
            //done : 'doneGiveaways',
            //Done : getter => getters.Threshold.doneGiveaways
        }),
        giveaways(){
            //this.$foreceUpdate();
            //this.$store.dispatch('getGiveAways');
            return this.$store.getters.doneGiveaways
        },
        testing(){
            return this.$store.getters.loadTesting
        }
    },
    watch:{
        giveaways(newVal, oldVal){
            console.log(newVal + 'test');
        },
        testing(newVal, oldval){
            console.log(newVal)
        },
        deep: true
    },
    created(){

    },
    methods:{

    },
    mounted(){
        this.$store.dispatch('getGiveAways');
        this.cards[2].result_val = this.$store.getters.doneGiveaways;
        if(this.$store.getters.doneGiveaways > 0){
            this.cards[2].background_color = 'orange';
            console.log('wew');
        }
        /*if(this.$store.state.Threshold.giveaways === null){
            this.$store.dispatch('getGiveAways');
        }else{}*/
    }
}
</code>```

And here is my Threshold.js vuex

```<code>import Vue from 'vue';
import VueAxios from 'vue-axios';
import axios from 'axios';
Vue.use(VueAxios, axios);

const state = {
    giveaways: null,
    testing: ['wew']
}

const actions = {
    getGiveAways : ({commit}) =>{
        axios({
            url : '/prod/api/thresholds_settings',
            method: 'post',
            data : {
            },
            config: 'JOSN'
        })
        .then(response=>{
            if(response.status == 200){
                //console.log(response.data.total_giveaways);
                commit('SET_GIVEAWAYS', response.data.total_giveaways)
                //dispatch('getGiveAways');
            }
        })
        .catch(error=>{
            if(error.response){
                console.log('something happened')
            }
        });
    }
}

const mutations = {
    SET_GIVEAWAYS : (state, obj)=>{
        state.giveaways = obj
    }

}

const getters = {
    doneGiveaways(state){
        return state.giveaways
    },
    loadTesting(state){
        return state.testing
    }
}

export default {
    state, mutations, actions, getters
}
</code>```

答:
Try changing your match option to this:

```<code>watch:{
    giveaways(newVal, oldVal){
        console.log(newVal + 'test');
    },
    testing(newVal, oldval){
        console.log(newVal)
    },
    deep: true,
    $route: this.giveaways
},
</code>```

or add this to the router file (requires another dependency - vuex-router-store )

```<code>import { sync } from 'vuex-router-sync'
import store from './vuex/store' // vuex store instance
import router from './router' // vue-router instance
</code>```

Body:
I have a dashboard page that when I refresh the page it works fine, I retrieved my data. However, when I go to other links and move back to my dashboard page (previous page) it doesn't update my computed giveaways property, it doesn't return the data anymore but in my response It still work fine it just not rendering because of my computed property. I'm using axios in my vuex, I tried also the this.$forceUpdate but I don't know where's the right place to do this. What I trying to make is like everytime they go that dashboard.vue page whether its via refresh or vue-route it should reupdate the computed property because I reevaluate the data from my serverside.

Here is my Dashboard.vue script

import {mapState} from 'vuex'
import { mapGetters } from 'vuex'

export default{
    ready(){
        this.loaded =false;

    },
    data: () => ({
        cards: [

        ],
        cards_offender:[

        ],
        //giveaways: '',

        loaded: true
    }),
    computed:{
        ...mapState({
            Giveaway: state => state.Threshold.giveaways
        }),
        ...mapGetters({
            //done : 'doneGiveaways',
            //Done : getter => getters.Threshold.doneGiveaways
        }),
        giveaways(){
            //this.$foreceUpdate();
            //this.$store.dispatch('getGiveAways');
            return this.$store.getters.doneGiveaways
        },
        testing(){
            return this.$store.getters.loadTesting
        }
    },
    watch:{
        giveaways(newVal, oldVal){
            console.log(newVal + 'test');
        },
        testing(newVal, oldval){
            console.log(newVal)
        },
        deep: true
    },
    created(){

    },
    methods:{

    },
    mounted(){
        this.$store.dispatch('getGiveAways');
        this.cards[2].result_val = this.$store.getters.doneGiveaways;
        if(this.$store.getters.doneGiveaways > 0){
            this.cards[2].background_color = 'orange';
            console.log('wew');
        }
        /*if(this.$store.state.Threshold.giveaways === null){
            this.$store.dispatch('getGiveAways');
        }else{}*/
    }
}

And here is my Threshold.js vuex

import Vue from 'vue';
import VueAxios from 'vue-axios';
import axios from 'axios';
Vue.use(VueAxios, axios);

const state = {
    giveaways: null,
    testing: ['wew']
}

const actions = {
    getGiveAways : ({commit}) =>{
        axios({
            url : '/prod/api/thresholds_settings',
            method: 'post',
            data : {
            },
            config: 'JOSN'
        })
        .then(response=>{
            if(response.status == 200){
                //console.log(response.data.total_giveaways);
                commit('SET_GIVEAWAYS', response.data.total_giveaways)
                //dispatch('getGiveAways');
            }
        })
        .catch(error=>{
            if(error.response){
                console.log('something happened')
            }
        });
    }
}

const mutations = {
    SET_GIVEAWAYS : (state, obj)=>{
        state.giveaways = obj
    }

}

const getters = {
    doneGiveaways(state){
        return state.giveaways
    },
    loadTesting(state){
        return state.testing
    }
}

export default {
    state, mutations, actions, getters
}

Body:
Try changing your match option to this:

watch:{
    giveaways(newVal, oldVal){
        console.log(newVal + 'test');
    },
    testing(newVal, oldval){
        console.log(newVal)
    },
    deep: true,
    $route: this.giveaways
},

or add this to the router file (requires another dependency - vuex-router-store )

import { sync } from 'vuex-router-sync'
import store from './vuex/store' // vuex store instance
import router from './router' // vue-router instance


问:
Spring webflow Value of second parameter is not passed to subflow

Hi, I am using spring webflow2.4.4 with spring4.1.3.
 I am trying to pass values between two flows as below.
sending value from flow first xml

```<code><action-state id="submit">
        <evaluate expression="someMethod(form)" result="flowScope.saveStatus" />
        <set name="flowScope.value1" value="form.value1" />
        <set name="flowScope.value2" value="form.value2" />
        <transition on="success" to="view" />
    </action-state>

    <subflow-state id="view" subflow="flow/path/view">
        <input name="value1" value="value1" />
        <input name="value2" value="value2" />
        ...
    </subflow-state>
</code>```

reeving data in flow second view xml

```<code><input name="value1" type="string" />
    <input name="value2" type="string" />
</code>```

now in view xml I am able to receive value for "value1" what I passed from first flow but getting value for 'value2' is null.

I tried switching the position in first flow as below

```<code><action-state id="submit">
        <evaluate expression="someMethod(form)" result="flowScope.saveStatus" />
        <set name="flowScope.value2" value="form.value2" />
        <set name="flowScope.value1" value="form.value1" />
        <transition on="success" to="view" />
    </action-state>

    <subflow-state id="view" subflow="flow/path/view">
        <input name="value2" value="value2" />
        <input name="value1" value="value1" />
        ...
    </subflow-state>
</code>```

Now I am able to see value of 'value2' but value for 'value1' receiving is null.

What is wrong here? see below debug logs for both example

1st trial

DEBUG SubflowState - Calling subflow 'flow/path/view' with input map['value1' -> 'ABCDF', 'value2' -> [null]]

2nd trial

DEBUG SubflowState - Calling subflow 'flow/path/view' with input map['value2' -> 'ABCDF', 'value1' -> [null]]

I want to pass both thew values to second flow but it second parameter is getting skipped somehow.

答:
this is a very common mistake. the action state is transitioning when it gets a success and stops evaluating the rest of the commands.

you need to use <on-entry> to separate the two:

the commands you want to set or evaluate (value1 & value2)

the command that will be evaluated for the transition, here someMethod(form))

use this instead:

```<code><action-state id="submit">
    <on-entry>
        <set name="flowScope.value2" value="form.value2" />
        <set name="flowScope.value1" value="form.value1" />
    </on-entry>
    <evaluate expression="someMethod(form)" result="flowScope.saveStatus" />
    <transition on="success" to="view" />
</action-state>
</code>```

Body:
Hi, I am using spring webflow2.4.4 with spring4.1.3.
 I am trying to pass values between two flows as below.
sending value from flow first xml

<action-state id="submit">
        <evaluate expression="someMethod(form)" result="flowScope.saveStatus" />
        <set name="flowScope.value1" value="form.value1" />
        <set name="flowScope.value2" value="form.value2" />
        <transition on="success" to="view" />
    </action-state>

    <subflow-state id="view" subflow="flow/path/view">
        <input name="value1" value="value1" />
        <input name="value2" value="value2" />
        ...
    </subflow-state>

reeving data in flow second view xml

<input name="value1" type="string" />
    <input name="value2" type="string" />

now in view xml I am able to receive value for "value1" what I passed from first flow but getting value for 'value2' is null.

I tried switching the position in first flow as below

<action-state id="submit">
        <evaluate expression="someMethod(form)" result="flowScope.saveStatus" />
        <set name="flowScope.value2" value="form.value2" />
        <set name="flowScope.value1" value="form.value1" />
        <transition on="success" to="view" />
    </action-state>

    <subflow-state id="view" subflow="flow/path/view">
        <input name="value2" value="value2" />
        <input name="value1" value="value1" />
        ...
    </subflow-state>

Now I am able to see value of 'value2' but value for 'value1' receiving is null.

What is wrong here? see below debug logs for both example

1st trial

DEBUG SubflowState - Calling subflow 'flow/path/view' with input map['value1' -> 'ABCDF', 'value2' -> [null]]

2nd trial

DEBUG SubflowState - Calling subflow 'flow/path/view' with input map['value2' -> 'ABCDF', 'value1' -> [null]]

I want to pass both thew values to second flow but it second parameter is getting skipped somehow.

Body:
this is a very common mistake. the action state is transitioning when it gets a success and stops evaluating the rest of the commands.

you need to use <on-entry> to separate the two:

the commands you want to set or evaluate (value1 & value2)

the command that will be evaluated for the transition, here someMethod(form))

use this instead:

<action-state id="submit">
    <on-entry>
        <set name="flowScope.value2" value="form.value2" />
        <set name="flowScope.value1" value="form.value1" />
    </on-entry>
    <evaluate expression="someMethod(form)" result="flowScope.saveStatus" />
    <transition on="success" to="view" />
</action-state>


问:
Using MSTest within a TFS 2015 Release Definition to run a webtest
I have a *.webtest that I'm building as part of a TFS 2015 Release Definition.  I'd like to run this test as part of the release.

I believe this requires mstest.exe however the mstest command is not recognized when running within the Command Line component, unlike other commands like dotnet publish.

Do I need to include the MSTest.exe executable within my test project or is there a more "out of the box" way to go about running webtests within a TFS 2015 Release Definition?

答:
You can run WebTests through MSBuild tool, you can call MSBuild tool through PowerShell.

Add PowerShell task

Code:

```<code>        param (
        $tool = "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\MSTest.exe",
         $path ,
         $include = "*.webtest",
         $results ,
        $testsettings)
            $web_tests = get-ChildItem -Path $paths -Recurse -Include $include

foreach ($item in $web_tests)
     {

     $args += "/TestContainer:$item "

    }

    & $tool $args /resultsfile:$Results /testsettings:$testsettings
</code>```

Add Publish Test Results task

More information, you can refer to this article: Running WebTests as part of a VSTS VNext Release pipeline

Body:
You can run WebTests through MSBuild tool, you can call MSBuild tool through PowerShell.

Add PowerShell task

Code:

        param (
        $tool = "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\MSTest.exe",
         $path ,
         $include = "*.webtest",
         $results ,
        $testsettings)
            $web_tests = get-ChildItem -Path $paths -Recurse -Include $include

foreach ($item in $web_tests)
     {

     $args += "/TestContainer:$item "

    }

    & $tool $args /resultsfile:$Results /testsettings:$testsettings

Add Publish Test Results task

More information, you can refer to this article: Running WebTests as part of a VSTS VNext Release pipeline


问:
jquery event once all images are loaded (including cached images)?
I have the following function which is for ajaxing in a page and the showing it only once all the images are loaded:

```<code>$.get('target-page.php', function(data){
    var $live = $('#preview_temp_holder').html(data);
    var imgCount = $live.find('img').length;
    $('img',$live).load(function(){
        imgCount--;
        if (imgCount==0){
            //DO STUFF HERE ONCE ALL IMAGES ARE LOADED
            $('#preview_pane').html($live.children()).fadeIn(800);
            $live.children().remove();
        }
    });
});
</code>```

The problem comes with cached images not firing the .load() event and thus not decrementing the imgCount.

I know i need to implement Nick Craver's solution but am not sure how. Can anyone help me?

答:
I spent a long time looking for solutions for this. The plugin suggested on the jQuery API page (https://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js) did not work in firefox.

My solution was to loop through each image and only add the load event if it was not already loaded (i.e. cached by the browser). The code below includes a counter that I was using to check that load events were only firing for images not already in the cache:

```<code>$(document).ready(function () {

    var images = $("img.lazy");
    $(".image-wrapper").addClass("loading");

    var loadedCount = 0;
    images
        .hide()
        .each(function () {
            if (!this.complete) {
                $(this).load(function () {
                    loadedCount++;
                    console.log(loadedCount);
                    displayImage(this);
                });
            }
            else {
                displayImage(this);
            }
        });
});

function displayImage(img) {
    $(img).fadeIn(300, function () {
        $(this).parents(".image_wrapper").removeClass("loading");
    });
}
</code>```

I'm no javascript expert so if you spot any problems with this solution please do let me know. As I say, it works in IE8, Chrome and Firefox (not sure about older versions of IE).

ContentLicense: CC BY-SA 2.5

Body:
I have the following function which is for ajaxing in a page and the showing it only once all the images are loaded:

$.get('target-page.php', function(data){
    var $live = $('#preview_temp_holder').html(data);
    var imgCount = $live.find('img').length;
    $('img',$live).load(function(){
        imgCount--;
        if (imgCount==0){
            //DO STUFF HERE ONCE ALL IMAGES ARE LOADED
            $('#preview_pane').html($live.children()).fadeIn(800);
            $live.children().remove();
        }
    });
});

The problem comes with cached images not firing the .load() event and thus not decrementing the imgCount.

I know i need to implement Nick Craver's solution but am not sure how. Can anyone help me?

Body:
I spent a long time looking for solutions for this. The plugin suggested on the jQuery API page (https://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js) did not work in firefox.

My solution was to loop through each image and only add the load event if it was not already loaded (i.e. cached by the browser). The code below includes a counter that I was using to check that load events were only firing for images not already in the cache:

$(document).ready(function () {

    var images = $("img.lazy");
    $(".image-wrapper").addClass("loading");

    var loadedCount = 0;
    images
        .hide()
        .each(function () {
            if (!this.complete) {
                $(this).load(function () {
                    loadedCount++;
                    console.log(loadedCount);
                    displayImage(this);
                });
            }
            else {
                displayImage(this);
            }
        });
});

function displayImage(img) {
    $(img).fadeIn(300, function () {
        $(this).parents(".image_wrapper").removeClass("loading");
    });
}

I'm no javascript expert so if you spot any problems with this solution please do let me know. As I say, it works in IE8, Chrome and Firefox (not sure about older versions of IE).


问:
Keep this countdown from restart on browser refresh and remove mouse click during countdown
I have a countdown that needs to not reset on page refreshes. Could anyone show me what would suit best for my current code? I also would like some input if it's possible to disable any kind of mouseclick or if another apporach is the way to go to make the user unable to go somewhere else on the page during countdown. Any help is appreciated thanks!

Mine is not a duplicate since it includes remove of mouse click during countdown and my goal os a lot different from that post.

var time = 30;
function countdown()
{
  if(time==0)
  {
    window.location.reload();
  }
  else
  {
    tmptime = time;
    dayTime = 24*60*60;
    hourTime = 60*60;
    minutesTime = 60;

    days = Math.floor(tmptime/dayTime);
    tmptime = tmptime - days*dayTime;

    hours = Math.floor(tmptime/hourTime);
    tmptime = tmptime - hours*hourTime;

    minutes = Math.floor(tmptime/minutesTime);
    tmptime = tmptime - minutes*minutesTime;

    seconds = tmptime;
    tidtext="";
    if(days>0)
      tidtext = days+ hours + " hours " + minutes + " minutes " + seconds + " seconds";
    else if(hours>0)
      tidtext = hours + " hours " + minutes + " minutes " + seconds + " seconds";
    else
      tidtext =  minutes + " minutes " + seconds + " seconds";

      document.getElementById('timer').innerHTML = tidtext;
    document.getElementById('timer').classList.add('timer');
    time--;
    setTimeout("countdown()", 1000);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td data-th="Workout"><input type="submit" onclick="countdown();" value="Bench Press"></td>
<div id="timer"></div></code>```

答:
You can use localStorage.

```<code>localStorage.setItem("time", time);
</code>```

will set the value of time into localStorage. You could do this in every iteration of the loop. Then, on page load you could do

```<code>time = localStorage.getItem("time");
</code>```

to retrieve the value of time from localStorage.

Body:
I have a countdown that needs to not reset on page refreshes. Could anyone show me what would suit best for my current code? I also would like some input if it's possible to disable any kind of mouseclick or if another apporach is the way to go to make the user unable to go somewhere else on the page during countdown. Any help is appreciated thanks!

Mine is not a duplicate since it includes remove of mouse click during countdown and my goal os a lot different from that post.

var time = 30;
function countdown()
{
  if(time==0)
  {
    window.location.reload();
  }
  else
  {
    tmptime = time;
    dayTime = 24*60*60;
    hourTime = 60*60;
    minutesTime = 60;

    days = Math.floor(tmptime/dayTime);
    tmptime = tmptime - days*dayTime;

    hours = Math.floor(tmptime/hourTime);
    tmptime = tmptime - hours*hourTime;

    minutes = Math.floor(tmptime/minutesTime);
    tmptime = tmptime - minutes*minutesTime;

    seconds = tmptime;
    tidtext="";
    if(days>0)
      tidtext = days+ hours + " hours " + minutes + " minutes " + seconds + " seconds";
    else if(hours>0)
      tidtext = hours + " hours " + minutes + " minutes " + seconds + " seconds";
    else
      tidtext =  minutes + " minutes " + seconds + " seconds";

      document.getElementById('timer').innerHTML = tidtext;
    document.getElementById('timer').classList.add('timer');
    time--;
    setTimeout("countdown()", 1000);
  }
}

<input type="submit" onclick="countdown();" value="Bench Press">

Body:
You can use localStorage.

localStorage.setItem("time", time);

will set the value of time into localStorage. You could do this in every iteration of the loop. Then, on page load you could do

time = localStorage.getItem("time");

to retrieve the value of time from localStorage.


问:
How do I run Katalon test suite in Jenkins inside Docker
I have a Katalon test suite setup and it runs great in the UI and from the CLI on the machine where I have Katalon studio installed.

I have Jenkins CI server running in a docker container, and I would like to setup a job to run my test suite on that Jenkins server.

What runtime do I need on the Jenkins server so it can run a Katalon job?  Is there a runtime or a plugin for Jenkins for this?

If not, is there a docker container for Katalon that I can use to remotely run the job via jenkins, like the SonarQube stuff?

答:
You can find it here and on Docker Hub. But I don't like that it need to be activated by email/password. So it make the build slow down. I intend to make my own docker image including my activated Katalon studio.
They seems not support CI really well.

https://github.com/katalon-studio/katalon-studio-docker


问:
putExtra from activity then getExtra in fragment
i tried to put and get extra from activity to fragment . but something is wrong! anybody have idea? my case is diffrent because i wanna do it in fragment

myActivity :

```<code>if(email.matches(users.user1)&&password.matches(users.pass1)){
        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
        Intent i = new Intent(LoginActivity.this,ProfileFragment.class);
        i.putExtra("pn", users.pn1);
        i.putExtra("name", users.name1);
        i.putExtra("family", users.family1);
        i.putExtra("rank", users.rank1);
        startActivity(intent);
        finish();
    }
</code>```

myfragment

```<code>@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_profile2, container, false);

    final TextView pn =getActivity().findViewById(R.id.pn);
    final TextView name =getActivity().findViewById(R.id.name);
    final TextView family =getActivity().findViewById(R.id.family);
    final TextView user =getActivity().findViewById(R.id.user);
    final TextView rank =getActivity().findViewById(R.id.rank);

    String pnget = getActivity().getIntent().getStringExtra("pn");
    String nameget = getActivity().getIntent().getStringExtra("name");
    String familyget = getActivity().getIntent().getStringExtra("family");
    String userget = getActivity().getIntent().getStringExtra("user");
    String rankget = getActivity().getIntent().getStringExtra("rank");

    pn.setText(pnget);
    name.setText(nameget);
    family.setText(familyget);
    user.setText(userget);
    rank.setText(rankget);
}
</code>```

Hi . i tried to put and get extra from activity to fragment . but something is wrong! anybody have idea?

答:
You can send data with the bundle, that is recommended

To Pass Data from Activity

```<code>fragment = new YourFragment();

if (fragment != null) {
    FragmentManager fragmentManager = getFragmentManager();

    Bundle bundle = new Bundle();
    bundle.putString("key", "value");

    fragment.setArguments(bundle);

    fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
}
</code>```

To receive data from Fragment

```<code>  String var = getArguments().getString("value");
</code>```

Body:
i tried to put and get extra from activity to fragment . but something is wrong! anybody have idea? my case is diffrent because i wanna do it in fragment

myActivity :

if(email.matches(users.user1)&&password.matches(users.pass1)){
        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
        Intent i = new Intent(LoginActivity.this,ProfileFragment.class);
        i.putExtra("pn", users.pn1);
        i.putExtra("name", users.name1);
        i.putExtra("family", users.family1);
        i.putExtra("rank", users.rank1);
        startActivity(intent);
        finish();
    }

myfragment

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_profile2, container, false);

    final TextView pn =getActivity().findViewById(R.id.pn);
    final TextView name =getActivity().findViewById(R.id.name);
    final TextView family =getActivity().findViewById(R.id.family);
    final TextView user =getActivity().findViewById(R.id.user);
    final TextView rank =getActivity().findViewById(R.id.rank);

    String pnget = getActivity().getIntent().getStringExtra("pn");
    String nameget = getActivity().getIntent().getStringExtra("name");
    String familyget = getActivity().getIntent().getStringExtra("family");
    String userget = getActivity().getIntent().getStringExtra("user");
    String rankget = getActivity().getIntent().getStringExtra("rank");

    pn.setText(pnget);
    name.setText(nameget);
    family.setText(familyget);
    user.setText(userget);
    rank.setText(rankget);
}

Hi . i tried to put and get extra from activity to fragment . but something is wrong! anybody have idea?

Body:
You can send data with the bundle, that is recommended

To Pass Data from Activity

fragment = new YourFragment();

if (fragment != null) {
    FragmentManager fragmentManager = getFragmentManager();

    Bundle bundle = new Bundle();
    bundle.putString("key", "value");

    fragment.setArguments(bundle);

    fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
}

To receive data from Fragment

  String var = getArguments().getString("value");


问:
Warning when passing arguments to a GUIDE GUI
I am trying to pass arguments to a GUIDE generated GUI.  This works but throws a Warning.

```<code>inputTest('Passed In String')
</code>```

Warning: The input to STR2FUNC "Passed In String" is not a valid
  function name. This will generate an error in a future release.

I know I have passed arguments to GUIDE GUIs in the past and I don't recall ever seeing this warning message before.  However, I am relatively new to Matlab 2016b so something may have changed that I am not aware of.  I didn't find anything in the documentation.

The warning occurs in the "initialization code - DO NOT EDIT" auto generated section and only happens when passing in an optional argument.

Is this a bug in 2016b or have I missed something?

Minimal Example below.  It is a simple GUI with only a single Edit box.

```<code>function varargout = inputTest(varargin)
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @inputTest_OpeningFcn, ...
                   'gui_OutputFcn',  @inputTest_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1}); % WARNING OCCURS HERE
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

function inputTest_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
% Fill the box if the string is passed in.
if nargin == 4
    handles.edit1.String = varargin{1};
else
    handles.edit1.String = 'Nothing Passed In';
end
guidata(hObject, handles);

function varargout = inputTest_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;

function edit1_Callback(hObject, eventdata, handles)
function edit1_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
</code>```

答:
The default GUIDE GUI behavior is explained in the autogenerated inline documentation:

```<code>% ASDF MATLAB code for asdf.fig
%      ASDF, by itself, creates a new ASDF or raises the existing
%      singleton*.
%
%      H = ASDF returns the handle to a new ASDF or the handle to
%      the existing singleton*.
%
%      ASDF('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in ASDF.M with the given input arguments.
%
%      ASDF('Property','Value',...) creates a new ASDF or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before asdf_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to asdf_OpeningFcn via varargin.
</code>```

The syntax you're attempting to use is the syntax reserved for calling callbacks that are local to your GUI, which is why it's using a str2func call on the first input. Either remove the str2func call or change your input syntax to accept a separate output than what GUIDE is designed for.

Body:
I am trying to pass arguments to a GUIDE generated GUI.  This works but throws a Warning.

inputTest('Passed In String')

Warning: The input to STR2FUNC "Passed In String" is not a valid
  function name. This will generate an error in a future release.

I know I have passed arguments to GUIDE GUIs in the past and I don't recall ever seeing this warning message before.  However, I am relatively new to Matlab 2016b so something may have changed that I am not aware of.  I didn't find anything in the documentation.

The warning occurs in the "initialization code - DO NOT EDIT" auto generated section and only happens when passing in an optional argument.

Is this a bug in 2016b or have I missed something?

Minimal Example below.  It is a simple GUI with only a single Edit box.

function varargout = inputTest(varargin)
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @inputTest_OpeningFcn, ...
                   'gui_OutputFcn',  @inputTest_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1}); % WARNING OCCURS HERE
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

function inputTest_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
% Fill the box if the string is passed in.
if nargin == 4
    handles.edit1.String = varargin{1};
else
    handles.edit1.String = 'Nothing Passed In';
end
guidata(hObject, handles);

function varargout = inputTest_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;

function edit1_Callback(hObject, eventdata, handles)
function edit1_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

Body:
The default GUIDE GUI behavior is explained in the autogenerated inline documentation:

% ASDF MATLAB code for asdf.fig
%      ASDF, by itself, creates a new ASDF or raises the existing
%      singleton*.
%
%      H = ASDF returns the handle to a new ASDF or the handle to
%      the existing singleton*.
%
%      ASDF('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in ASDF.M with the given input arguments.
%
%      ASDF('Property','Value',...) creates a new ASDF or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before asdf_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to asdf_OpeningFcn via varargin.

The syntax you're attempting to use is the syntax reserved for calling callbacks that are local to your GUI, which is why it's using a str2func call on the first input. Either remove the str2func call or change your input syntax to accept a separate output than what GUIDE is designed for.


问:
trivial Scala filter isn't trivial
Okay, this should be a trivial problem, but I've been trying to make it work for hours.

I have a List(Tuple2(String,Int) ... ), with, for example, this data:

```<code>('PAUL ANKA',0)
('PAUL ANKA',0)
('P. ANKA /G. HAMILTON /J. NASH',0)
('PAUL ANKA',0)
('PAUL ANKA',0)
('PAUL ANKA',1)
('PAUL ANKA',0)
('PAUL ANKA',0)
('PAUL ANKA',0)
('PAUL ANKA',0)
</code>```

I want to filter it for only the tuples with the second element == 1.

It seems trivial:

```<code>mylist.filter(_._2 == 1)
</code>```

but no. So I tried

```<code>mylist.filter(x => x._2 == 0)
</code>```

No joy. Each of these examples should result in a List(('Paul Anka', 1)) but instead the list is empty.

This:

```<code>mylist.filter(x => true)
</code>```

works as expected, ie, it's an identity.

I am tearing my hair on this.

Update:

Okay, this is interesting. The example list above is output from scala.

Using prayagupta's answer, I get

```<code>@ val data = List(("Charlie Martin", 99), ("prayagupd", 100), ("PAUL ANKA", 1))
data: List[(String, Int)] = List(("Charlie Martin", 99), ("prayagupd", 100), ("PAUL ANKA", 1))

@ println(data)
List((Charlie Martin,99), (prayagupd,100), (PAUL ANKA,1))
</code>```

Observe that my example prints those strings (or putative strings) in single-quotes.

答:
Works just fine for me

```<code>val listOfTuples = List(("PAUL ANKA",0),
("PAUL ANKA",0),
("P. ANKA /G. HAMILTON /J. NASH",0),
("PAUL ANKA",0),
("PAUL ANKA",0),
("PAUL ANKA",1),
("PAUL ANKA",0),
("PAUL ANKA",0),
("PAUL ANKA",0),
("PAUL ANKA",0))

println(listOfTuples.filter(_._2 == 1))
</code>```

https://scalafiddle.io/sf/uHxkL8C/0

Make sure your actual data isn't single quoting things.

Title: trivial Scala filter isn't trivial

Body:
Okay, this should be a trivial problem, but I've been trying to make it work for hours.

I have a List(Tuple2(String,Int) ... ), with, for example, this data:

('PAUL ANKA',0)
('PAUL ANKA',0)
('P. ANKA /G. HAMILTON /J. NASH',0)
('PAUL ANKA',0)
('PAUL ANKA',0)
('PAUL ANKA',1)
('PAUL ANKA',0)
('PAUL ANKA',0)
('PAUL ANKA',0)
('PAUL ANKA',0)

I want to filter it for only the tuples with the second element == 1.

It seems trivial:

mylist.filter(_._2 == 1)

but no. So I tried

mylist.filter(x => x._2 == 0)

No joy. Each of these examples should result in a List(('Paul Anka', 1)) but instead the list is empty.

This:

mylist.filter(x => true)

works as expected, ie, it's an identity.

I am tearing my hair on this.

Update:

Okay, this is interesting. The example list above is output from scala.

Using prayagupta's answer, I get

@ val data = List(("Charlie Martin", 99), ("prayagupd", 100), ("PAUL ANKA", 1))
data: List[(String, Int)] = List(("Charlie Martin", 99), ("prayagupd", 100), ("PAUL ANKA", 1))

@ println(data)
List((Charlie Martin,99), (prayagupd,100), (PAUL ANKA,1))

Observe that my example prints those strings (or putative strings) in single-quotes.

Body:
Works just fine for me

val listOfTuples = List(("PAUL ANKA",0),
("PAUL ANKA",0),
("P. ANKA /G. HAMILTON /J. NASH",0),
("PAUL ANKA",0),
("PAUL ANKA",0),
("PAUL ANKA",1),
("PAUL ANKA",0),
("PAUL ANKA",0),
("PAUL ANKA",0),
("PAUL ANKA",0))

println(listOfTuples.filter(_._2 == 1))

https://scalafiddle.io/sf/uHxkL8C/0

Make sure your actual data isn't single quoting things.


答:
Your code looks correct but make sure your initial data is correct and is of type List[Tuple2[String, Int]],

Try in scala REPL,

```<code>scala> val data = List(("Charlie Martin", 99), ("prayagupd", 100), ("PAUL ANKA", 1))
data: List[(String, Int)] = List((Charlie Martin,99), (prayagupd,100), (PAUL ANKA,1))

scala> data.filter{case (name, age) => age == 1 }
res1: List[(String, Int)] = List((PAUL ANKA,1))
</code>```

alternative way,

```<code>scala> data.filter{_._2 == 1 }
res2: List[(String, Int)] = List((PAUL ANKA,1))
</code>```

If you read the data from file or so, probably your data-structure is List[(String, String)] where "1" == 1 is false,

```<code>scala> val data = List(("Charlie Martin", "99"), ("prayagupd", "100"), ("PAUL ANKA", "1"))
data: List[(String, String)] = List((Charlie Martin,99), (prayagupd,100), (PAUL ANKA,1))

scala> data.filter{_._2 == 1 }
res4: List[(String, String)] = List()
</code>```

Title: trivial Scala filter isn't trivial

Body:
Your code looks correct but make sure your initial data is correct and is of type List[Tuple2[String, Int]],

Try in scala REPL,

scala> val data = List(("Charlie Martin", 99), ("prayagupd", 100), ("PAUL ANKA", 1))
data: List[(String, Int)] = List((Charlie Martin,99), (prayagupd,100), (PAUL ANKA,1))

scala> data.filter{case (name, age) => age == 1 }
res1: List[(String, Int)] = List((PAUL ANKA,1))

alternative way,

scala> data.filter{_._2 == 1 }
res2: List[(String, Int)] = List((PAUL ANKA,1))

If you read the data from file or so, probably your data-structure is List[(String, String)] where "1" == 1 is false,

scala> val data = List(("Charlie Martin", "99"), ("prayagupd", "100"), ("PAUL ANKA", "1"))
data: List[(String, String)] = List((Charlie Martin,99), (prayagupd,100), (PAUL ANKA,1))

scala> data.filter{_._2 == 1 }
res4: List[(String, String)] = List()


问:
CoreBluetooth re-subscribe to characteristic while reconnecting
In my app, I am able to successfully connect to a BLE peripheral and subscribe to a characteristic, so that the app gets notified whenever there is a change in the characteristic value. But the app is not notified upon changes in characteristic value after the central manager is reinitialized during state restoration. Below is what I do during state restoration:

In didFinishLaunchingWithOptions: I re-instantiate central manager
object with the restoration identifier.

Then in centralManager:willRestoreState: method, I retrieve
previously    connected peripherals and reconnect to them using

CBCentralManagerRestoredStatePeripheralsKey.

Will simply reconnecting to the peripherals will do the characteristics subscription internally or finding services and subscribing to characteristic to be done explicitly as it is done during first launch ?

答: I wouldn't be surprised if this is buggy, so a robust solution would be to subscribe to the notifying characteristic when your app resumes. </p>


问:
reg expression replace not replacing space-dash-space
I am trying to strip out any non-alphanumeric characters and also replace any whitespace with an underscore.

myString = myString.replace(/[^a-zA-Z 0-9]+/g, '').replace(" ", "_");

This almost it, but it still fails in one case:

```<code>12th Madison - 100
</code>```

Becomes

```<code>12th_Madison  100
</code>```

What I would like is this:

```<code>12th_Madison_100
</code>```

答:
Did you mean to include the space in

/[^a-zA-Z 0-9]+/g

?

Body:
I am trying to strip out any non-alphanumeric characters and also replace any whitespace with an underscore.

myString = myString.replace(/[^a-zA-Z 0-9]+/g, '').replace(" ", "_");

This almost it, but it still fails in one case:

12th Madison - 100

Becomes

12th_Madison  100

What I would like is this:

12th_Madison_100


问:
create submit form with jquery
i want to make a submit action, so when i click submit the page will not refresh and data i input in div1 will send to kanjiconverter.php and display it to div2 by <?php echo $newkanji ?>. i have 3 form in these page.

here my kanjiconverter.php. i save a submit code here.

```<code><?php
  if(isset($_POST['submit1'])){
        $kanji = ($_POST['convertkanji']);

        $replacements = [
        'class="rt">' => "",
        ];
        $newkanji = strtr($kanji, $replacements);
  }
?>
</code>```

and my form code is here. submit button was in div1 but im using input tag not button tag.

```<code><form id="convertkanji" method="post" action="kanjiconverter.php"></form>
        <form>
          <div class="form-row">

            <!-- START DIV1 HERE -->
          <div id="div1" class="form-group col-md-6">
            <label for="convertkanji">Kanji Convert</label>
            <textarea id="convertkanji1" name="convertkanji" rows="10" form="convertkanji"></textarea>
            <input type="submit" name="submit1" class="btn btn-default" form="convertkanji" value="Convert" style="width: 100%; margin-top: 6px;" />
          </div>
          <!-- Ended DIV1 HERE -->

          <!-- START DIV2 HERE -->
            <div id="div2" class="form-group col-md-6" style="display: none;">
      <label for="kanji">New Kanji</label>
      <textarea id="kanji" name="kanji" rows="12" form="tambahposting"><?php echo $newkanji ?></textarea>
    </div>
          <!-- Ended DIV2 HERE -->
    </form>
</code>```

and heres my jquery script. im place it above  tag.

```<code>    <script>
        $(function() {
  $('#div1').show();
  $('#div2').hide();

  $('input[name="submit1"]').on('click', function(e) {
    e.preventDefault();

    $('#div1').hide();
    $('#div2').show();

    $.post('kanjiconverter.php', $('form').serialize(), function(response) {
      //Your response from the server-side
    })
  });
});
      </script>
</code>```

i make div2 hide for first and div1 show. but when i click submit div1 will hide and div2 will show.

and i place  between  and  tag.

the problem is, when i click submit the data i input not showing. only hide and show who was working. i think the data is not send.

答:
The button it's not submiting the form because of the  e.preventDefault(); because if this method is called, the default action of the event will not be triggered, so the button will not do what it suppose to do that is to submit the form with the data inside. So to fix it you most add this after show and hide:

    $( "#convertkanji" ).submit();

Title: create submit form with jquery

Body:
i want to make a submit action, so when i click submit the page will not refresh and data i input in div1 will send to kanjiconverter.php and display it to div2 by <?php echo $newkanji ?>. i have 3 form in these page.

here my kanjiconverter.php. i save a submit code here.

<?php
  if(isset($_POST['submit1'])){
        $kanji = ($_POST['convertkanji']);

        $replacements = [
        'class="rt">' => "",
        ];
        $newkanji = strtr($kanji, $replacements);
  }
?>

and my form code is here. submit button was in div1 but im using input tag not button tag.

<form id="convertkanji" method="post" action="kanjiconverter.php"></form>
        <form>

            Kanji Convert
            <textarea id="convertkanji1" name="convertkanji" rows="10" form="convertkanji"></textarea>
            <input type="submit" name="submit1" class="btn btn-default" form="convertkanji" value="Convert" style="width: 100%; margin-top: 6px;" />

      New Kanji
      <textarea id="kanji" name="kanji" rows="12" form="tambahposting"><?php echo $newkanji ?></textarea>

    </form>

and heres my jquery script. im place it above  tag.

i make div2 hide for first and div1 show. but when i click submit div1 will hide and div2 will show.

and i place  between  and  tag.

the problem is, when i click submit the data i input not showing. only hide and show who was working. i think the data is not send.


问:
What does this symbol mean in C++? "~"
If we use ~ before a function like this: ~func();, what does this mean?

Thanks.

答:
It's the bitwise complement operator.

(Actually, no, it's probably not a destructor. Destructor of a class named func??)

It takes the returned integer from func() and bitwise-complements it; that is, it flips all of its bits.

Title: What does this symbol mean in C++? "~"


问:
Adding a counter to a loop
On a broad question that I haven't been able to find for R:

I'm trying to add a counter at the beginning of a loop.
So that when I run the loop sim = 1000:

```<code>if(hours$week1 > 1 and hours$week1 < 48) add 1 to the counter
ifelse add 0
</code>```

I have came across counter tutorials that print a sentence to let you know where you are (if something goes wrong):
e.g

```<code>For (i in 1:1000) {
    if (i%%100==0) print(paste("No work", i))
}
</code>```

But the purpose of my counter is to generate a value output, measuring how many of the 1000 runs in the loop fall inside a specified range.

答:
How about this?

count = 0

for (i in 1:1000) {

  count = ifelse(i %in% 1:100, count + 1, count)

}

count

#> [1] 100
```

Title: Adding a counter to a loop

Body:
On a broad question that I haven't been able to find for R:

I'm trying to add a counter at the beginning of a loop.
So that when I run the loop sim = 1000:

if(hours$week1 > 1 and hours$week1 < 48) add 1 to the counter
ifelse add 0

I have came across counter tutorials that print a sentence to let you know where you are (if something goes wrong):
e.g

For (i in 1:1000) {
    if (i%%100==0) print(paste("No work", i))
}

But the purpose of my counter is to generate a value output, measuring how many of the 1000 runs in the loop fall inside a specified range.


答:
You can't create a Fragment with startActivity. You need to create the fragment with bundle like this:

```<code>ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();

args.putString("name", users.name1);
args.putString("family", users.family1);
fragment.setArguments(args);

// then tell the FragmentManager to attach the fragment
// to the activity
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.your_placeholder, fragment);
ft.commit();
</code>```

Then in your onCreateView get them with:

```<code>String name = getArguments().getString("name", "");
String family = getArguments().getString("family", "");
</code>```

Please remember that you need to move the return code to the last of onCreateView method and change your code to something like this:

```<code>@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
   View view = inflater.inflate(R.layout.fragment_profile2, container, false);

   TextView pn =view.findViewById(R.id.pn);
   ...

   return view;
}
</code>```

Title: putExtra from activity then getExtra in fragment

Body:
You can't create a Fragment with startActivity. You need to create the fragment with bundle like this:

ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();

args.putString("name", users.name1);
args.putString("family", users.family1);
fragment.setArguments(args);

// then tell the FragmentManager to attach the fragment
// to the activity
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.your_placeholder, fragment);
ft.commit();

Then in your onCreateView get them with:

String name = getArguments().getString("name", "");
String family = getArguments().getString("family", "");

Please remember that you need to move the return code to the last of onCreateView method and change your code to something like this:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
   View view = inflater.inflate(R.layout.fragment_profile2, container, false);

   TextView pn =view.findViewById(R.id.pn);
   ...

   return view;
}


问:
S3 Error: The difference between the request time and the current time is too large
I have error The difference between the request time and the current time is too large when call method amazons3.ListObjects

```<code>ListObjectsRequest request = new ListObjectsRequest() {
    BucketName = BucketName, Prefix = fullKey
};
using (ListObjectsResponse response = s3Client.ListObjects(request))
{
    bool result = response.S3Objects.Count > 0;

    return result;
}
</code>```

What it could be?

答: The time on your local box is out of sync with the current time.  Sync up your system clock and the problem will go away.</p>

Body:
I have error The difference between the request time and the current time is too large when call method amazons3.ListObjects

ListObjectsRequest request = new ListObjectsRequest() {
    BucketName = BucketName, Prefix = fullKey
};
using (ListObjectsResponse response = s3Client.ListObjects(request))
{
    bool result = response.S3Objects.Count > 0;

    return result;
}

What it could be?


问:
How to mocking a http request with route params using axios-mock-adapter
How to mock http request with route params?</p>

```<code>var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');

// This sets the mock adapter on the default instance
var mock = new MockAdapter(axios);
mock.onGet('/api/colleges/:collegeId/branches/:branchesId').reply(200);
</code>```

答:
Convert your placeholders to wildcards and the path to a RegExp:

```<code>function route (path = '') {
  return typeof path === 'string'
    ? new RegExp(path.replace(/:\w+/g, '[^/]+'))
    : path
}
</code>```

Use like this:

```<code>mock.onGet(route('/api/colleges/:collegeId/branches/:branchesId')).reply(200);
</code>```

Body:
How to mock http request with route params?

var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');

// This sets the mock adapter on the default instance
var mock = new MockAdapter(axios);
mock.onGet('/api/colleges/:collegeId/branches/:branchesId').reply(200);

Body:
Convert your placeholders to wildcards and the path to a RegExp:

function route (path = '') {
  return typeof path === 'string'
    ? new RegExp(path.replace(/:\w+/g, '[^/]+'))
    : path
}

Use like this:

mock.onGet(route('/api/colleges/:collegeId/branches/:branchesId')).reply(200);


问:
Quicksort Algorithm in a doubly linked list
I want to sort a list by last names with the algorithm of Quicksort but when exchanging the elements it does not work, it leaves them as they were

In this part the values of the chains are exchanged

```<code>void swap(string* a, string* b){

cout<<"A and B are "<<*a<<" - "<<*b<<endl;

string t = *a;
*a = *b;
cout<<" A is ->"<<*a<<endl;

*b= t;
cout<<"B is ->"<<*b<<endl;

}
</code>```

This is where the partition is made. I have noticed that when * i and * j take values they are exactly the same names and therefore can not be compared later. It seems strange to me that this list works if it is a number but when it is strings this error occurs.

```<code>User *i = lower;
</code>```

But this did not work at the end because the program crashed, but if you change the value of the string

```<code>User* partition(User *lower, User *high){

cout<<"Lower ->  "<<lower->lastname<<endl;
cout<<"High ->  "<<high->lastname<<endl;
string  pivot = high->lastname;
User *i = bajo->prev;
 for (User *j = lower; j != high; j = j->next)
{
    if (j->lastname.compare(pivot)< 0)
    {
        i = (i == NULL)? lower : i->next;
        cout<<"Atention J e I valen ->"<<i->lastname<<" - "<<j->lastname<<endl;
        swap(&(i->lastname), &(j->lastname));
    }
}
i = (i == NULL)? lower : i->lastname; // Similar to i++
swap(&(i->lastname), &(alto->lastname));
return i;
}
</code>```

What am I failing? How can I make it really take the desired value.

EDITED:

This is the source code

```<code>#include <iostream>
#include<iomanip>
#include <string>
#include<cstdlib>

using namespace std;

class User
{

public :
    string lastname;
    User *next;
    User *prev;
    User()
    {
        lastname= "";
        next=NULL;
        prev=NULL;

    }
    int empty(User *listt)
    {

        if(listt ==  NULL)
        {

            return 1;
        }
        else
        {

            return 0;
        }

    }

    User *Insert(User *listt, string lastName)
    {

        User *temp = new User();

        if(empty(listt))
        {

            temp->lastname=lastName;
            listt = temp;

        }
        else
        {

            temp->lastname=lastName;
            listt->prev=temp;
            temp->next=listt;
            listt=temp;

        }
        return listt;
    }
    void swap(string* a, string* b)
    {

        string t = *a;
        *a = *b;

        *b= t;

    }
    User* partition(User* lower, User* high)
    {

        cout<<"Lower ->  "<<lower->lastname<<endl;
        cout<<"High ->  "<<high->lastname<<endl;
        string  pivot = high->lastname;
        User *i = lower->prev;
        for (User *j = lower; j != high; j = j->next)
        {
            if (j->lastname.compare(pivot)< 0)
            {
                i = (i == NULL)? lower : i->next;
                swap(&(i->lastname), &(j->lastname));
            }
        }
        i = (i == NULL)? lower : i->next; // Similar to i++
        swap(&(i->lastname), &(high->lastname));
        return i;
    }
    User *Last(User *listt)
    {
        User *temp = listt;

        while(temp && temp ->next)
            temp=temp->next;
        return temp;

    }
    void _quickSort( User* lower, User* high)
    {

        if(high != NULL && lower != high&&lower!= high->next)
        {
            User *p = partition(lower,high);
            _quickSort(lower,p->next); //I change this part
            _quickSort(p->next,high);

        }

    }
    void quickSort(User *listt)
    {
        User *h = Last(listt);

        _quickSort(listt, h);

    }
    User *Display(User *listt)
    {

        if(empty(listt))
        {

            cout<<"List empty"<<endl;

        }
        else
        {

            User *temp = new User();
            temp = listt;
            while(temp!= NULL)
            {

                cout<<"The last name is -> "<<temp->lastname<<endl;
                temp=temp->next;
            }

        }
        return listt;

    }
};

int main()
{

    User *listt = NULL;
    User y;
    bool exit = false;
    int opc;
    string lastName;
    while(!exit)
    {

        cout<<"1.-Insert an element"<<endl;
        cout<<"2.-Sort element-(Quicksort)"<<endl;
        cout<<"3.-Show elements"<<endl;
        cout<<"4.-Exitt"<<endl;
        cin>>opc;
        switch(opc)
        {
        case 1:
            cout<<"Inser your last name"<<endl;
            cin>>lastName;
            listt=y.Insert(listt,lastName);
            system("pause");
            system("cls");
            break;
        case 2:
            cout<<"Sorting...."<<endl;
            y.quickSort(listt);
            system("pause");
            system("cls");
            break;
        case 3:
            cout<<"Display..."<<endl;
            y.Display(listt);
            system("pause");
            system("cls");
            break;
        case 4:
            exit = true;
            break;

        }

    }

}
</code>```

答:
Actually your swap function seems working but string t = *a; usage is kind of weird because *a is considered as an int value so you should not assign it to a string although the compiler can handle it either way. On the other hand I guess what you mentioned is to copy the value of "a" into a temporary string and it should be done as string* t = a;  and then you can do b = t;  but instead of that passing by reference is a better practice such as

```<code>void swap(string &a, string &b){
    string t = a;
    a = b;
    b= t;
}
</code>```

and you may want to check your Quick-sort implementation, see the reference on this page

Body:
I want to sort a list by last names with the algorithm of Quicksort but when exchanging the elements it does not work, it leaves them as they were

In this part the values of the chains are exchanged

void swap(string* a, string* b){

cout<<"A and B are "<<*a<<" - "<<*b<<endl;

string t = *a;
*a = *b;
cout<<" A is ->"<<*a<<endl;

*b= t;
cout<<"B is ->"<<*b<<endl;

}

This is where the partition is made. I have noticed that when * i and * j take values they are exactly the same names and therefore can not be compared later. It seems strange to me that this list works if it is a number but when it is strings this error occurs.

User *i = lower;

But this did not work at the end because the program crashed, but if you change the value of the string

User* partition(User *lower, User *high){

cout<<"Lower ->  "<<lower->lastname<<endl;
cout<<"High ->  "<<high->lastname<<endl;
string  pivot = high->lastname;
User *i = bajo->prev;
 for (User *j = lower; j != high; j = j->next)
{
    if (j->lastname.compare(pivot)< 0)
    {
        i = (i == NULL)? lower : i->next;
        cout<<"Atention J e I valen ->"<lastname<<" - "<<j->lastname<<endl;
        swap(&(i->lastname), &(j->lastname));
    }
}
i = (i == NULL)? lower : i->lastname; // Similar to i++
swap(&(i->lastname), &(alto->lastname));
return i;
}

What am I failing? How can I make it really take the desired value.

EDITED:

This is the source code

#include <iostream>
#include<iomanip>
#include <string>
#include<cstdlib>

using namespace std;

class User
{

public :
    string lastname;
    User *next;
    User *prev;
    User()
    {
        lastname= "";
        next=NULL;
        prev=NULL;

    }
    int empty(User *listt)
    {

        if(listt ==  NULL)
        {

            return 1;
        }
        else
        {

            return 0;
        }

    }

    User *Insert(User *listt, string lastName)
    {

        User *temp = new User();

        if(empty(listt))
        {

            temp->lastname=lastName;
            listt = temp;

        }
        else
        {

            temp->lastname=lastName;
            listt->prev=temp;
            temp->next=listt;
            listt=temp;

        }
        return listt;
    }
    void swap(string* a, string* b)
    {

        string t = *a;
        *a = *b;

        *b= t;

    }
    User* partition(User* lower, User* high)
    {

        cout<<"Lower ->  "<<lower->lastname<<endl;
        cout<<"High ->  "<<high->lastname<<endl;
        string  pivot = high->lastname;
        User *i = lower->prev;
        for (User *j = lower; j != high; j = j->next)
        {
            if (j->lastname.compare(pivot)< 0)
            {
                i = (i == NULL)? lower : i->next;
                swap(&(i->lastname), &(j->lastname));
            }
        }
        i = (i == NULL)? lower : i->next; // Similar to i++
        swap(&(i->lastname), &(high->lastname));
        return i;
    }
    User *Last(User *listt)
    {
        User *temp = listt;

        while(temp && temp ->next)
            temp=temp->next;
        return temp;

    }
    void _quickSort( User* lower, User* high)
    {

        if(high != NULL && lower != high&&lower!= high->next)
        {
            User *p = partition(lower,high);
            _quickSort(lower,p->next); //I change this part
            _quickSort(p->next,high);

        }

    }
    void quickSort(User *listt)
    {
        User *h = Last(listt);

        _quickSort(listt, h);

    }
    User *Display(User *listt)
    {

        if(empty(listt))
        {

            cout<<"List empty"<<endl;

        }
        else
        {

            User *temp = new User();
            temp = listt;
            while(temp!= NULL)
            {

                cout<<"The last name is -> "<<temp->lastname<<endl;
                temp=temp->next;
            }

        }
        return listt;

    }
};

int main()
{

    User *listt = NULL;
    User y;
    bool exit = false;
    int opc;
    string lastName;
    while(!exit)
    {

        cout<<"1.-Insert an element"<<endl;
        cout<<"2.-Sort element-(Quicksort)"<<endl;
        cout<<"3.-Show elements"<<endl;
        cout<<"4.-Exitt"<<endl;
        cin>>opc;
        switch(opc)
        {
        case 1:
            cout<<"Inser your last name"<<endl;
            cin>>lastName;
            listt=y.Insert(listt,lastName);
            system("pause");
            system("cls");
            break;
        case 2:
            cout<<"Sorting...."<<endl;
            y.quickSort(listt);
            system("pause");
            system("cls");
            break;
        case 3:
            cout<<"Display..."<<endl;
            y.Display(listt);
            system("pause");
            system("cls");
            break;
        case 4:
            exit = true;
            break;

        }

    }

}

Body:
Actually your swap function seems working but string t = *a; usage is kind of weird because *a is considered as an int value so you should not assign it to a string although the compiler can handle it either way. On the other hand I guess what you mentioned is to copy the value of "a" into a temporary string and it should be done as string* t = a;  and then you can do b = t;  but instead of that passing by reference is a better practice such as

void swap(string &a, string &b){
    string t = a;
    a = b;
    b= t;
}

and you may want to check your Quick-sort implementation, see the reference on this page


问:
Render conflicts with my view in Rails
I'm starting in Ruby on Rails and I searched for in Stack Overflow and Google and I couldn't find the solution for my problem. Actually what is happening is that I have my default view application.html.erb and I limited the access to some partials verifying

What I'm trying to do is put the validates method in the model company.rb and when the user mistakes, my companies_controller.rb to render the actual action for the user fixes.

But when I do that, my validations in the application.html.erb doesn't recognises the rendered action as part of the companies_controller.rb

application.html.erb

```<code><body>
    <% if user_signed_in? %>
    <%= render 'shared/navbar' unless (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "edit")  %>
    <%= render 'shared/sidebar' unless current_page?(root_path) || current_page?(edit_user_registration_path) || (controller.controller_name == "companies" && controller.action_name == "index") || (controller.controller_name == "companies" && controller.action_name == "new") || current_page?(new_company_path) || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "messages" && controller.action_name == "edit") %>
    <% end %>
    <%= yield %>
</body>
</code>```

create method from companies_controller.rb

```<code>def create
    @company = current_user.companies.new(company_params)

    respond_to do |format|
      if @company.save
        current_user.companies << @company
        format.html { redirect_to @company, notice: 'Company was successfully created.' }
        format.json { render :show, status: :created, location: @company }
      else
        format.html { render :new }
        format.json { render json: @company.errors, status: :unprocessable_entity }
      end
    end
  end
</code>```

_form.html.erb

```<code><%= form_with(model: company, local: true) do |form| %>
  <% if company.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(company.errors.count, "error") %> prohibited this company from being saved:</h2>

      <ul>
      <% company.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name, id: :company_name, class: "form-control" %>
  </div>

  <div class="field">
    <%= form.label :phone %>
    <%= form.text_field :phone, id: :company_phone, class: "form-control" %>
  </div>

  <div class="field">
    <%= form.label :category %>
    <%= form.text_field :category, id: :company_category, class: "form-control" %>
  </div>

  <div class="field">
    <%= form.label :active %>
    <%= form.check_box :active %>
  </div>

  <div class="actions">
    <%= form.submit "Save", class: "btn btn-primary" %>
    <%= link_to 'Back', companies_path, class: "btn btn-default" %>
  </div>
<% end %>
</code>```

company.rb

```<code>class Company < ApplicationRecord
    validates :name, uniqueness: true, presence: true

    has_many :folders, :dependent => :destroy
    has_many :analytics, :dependent => :destroy
    has_many :leads, :dependent => :destroy
    has_many :messages, :dependent => :destroy
    has_many :links, :dependent => :destroy

    has_many :user_companies, :dependent => :destroy
    has_many :users, :through => :user_companies
end
</code>```

And the error is ActionController::UrlGenerationError in Companies#create

Can someone help with that? Sorry for my english.

Thank you!

Update December, 08.

My routes.rb

```<code>scope '/dashboard' do
    resources :companies do
      resources :users
      resources :user_companies
      resources :folder_links
      resources :folders
      resources :analytics
      resources :leads
      resources :links
      resources :messages

      get 'user_companies/new/search', to: "user_companies#search"
    end
  end
</code>```

答:
I fixed the error adding another validation. What was happening is that I was missing one more validation on application.html.erb:

```<code><%= render 'shared/navbar' unless (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "edit")  %>
<%= render 'shared/sidebar' unless current_page?(root_path) || current_page?(edit_user_registration_path) || (controller.controller_name == "companies" && controller.action_name == "index") || (controller.controller_name == "companies" && controller.action_name == "new") || current_page?(new_company_path) || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "messages" && controller.action_name == "edit") %>
</code>```

I just added the condition to when the current action is create:

```<code><%= render 'shared/navbar' unless (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "edit")  %>
<%= render 'shared/sidebar' unless current_page?(root_path) || current_page?(edit_user_registration_path) || (controller.controller_name == "companies" && controller.action_name == "index") || (controller.controller_name == "companies" && controller.action_name == "create") || (controller.controller_name == "companies" && controller.action_name == "new") || current_page?(new_company_path) || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "messages" && controller.action_name == "edit") %>
</code>```

Sorry for waste your time.

Thank you for trying to help, guys!

Title: Render conflicts with my view in Rails

Body:
I'm starting in Ruby on Rails and I searched for in Stack Overflow and Google and I couldn't find the solution for my problem. Actually what is happening is that I have my default view application.html.erb and I limited the access to some partials verifying

What I'm trying to do is put the validates method in the model company.rb and when the user mistakes, my companies_controller.rb to render the actual action for the user fixes.

But when I do that, my validations in the application.html.erb doesn't recognises the rendered action as part of the companies_controller.rb

application.html.erb

    <% if user_signed_in? %>
    <%= render 'shared/navbar' unless (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "edit")  %>
    <%= render 'shared/sidebar' unless current_page?(root_path) || current_page?(edit_user_registration_path) || (controller.controller_name == "companies" && controller.action_name == "index") || (controller.controller_name == "companies" && controller.action_name == "new") || current_page?(new_company_path) || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "messages" && controller.action_name == "edit") %>
    <% end %>
    <%= yield %>

create method from companies_controller.rb

def create
    @company = current_user.companies.new(company_params)

    respond_to do |format|
      if @company.save
        current_user.companies << @company
        format.html { redirect_to @company, notice: 'Company was successfully created.' }
        format.json { render :show, status: :created, location: @company }
      else
        format.html { render :new }
        format.json { render json: @company.errors, status: :unprocessable_entity }
      end
    end
  end

_form.html.erb

<%= form_with(model: company, local: true) do |form| %>
  <% if company.errors.any? %>

<%= pluralize(company.errors.count, "error") %> prohibited this company from being saved:

      <% company.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= form.label :name %>
    <%= form.text_field :name, id: :company_name, class: "form-control" %>

    <%= form.label :phone %>
    <%= form.text_field :phone, id: :company_phone, class: "form-control" %>

    <%= form.label :category %>
    <%= form.text_field :category, id: :company_category, class: "form-control" %>

    <%= form.label :active %>
    <%= form.check_box :active %>

    <%= form.submit "Save", class: "btn btn-primary" %>
    <%= link_to 'Back', companies_path, class: "btn btn-default" %>

<% end %>

company.rb

class Company < ApplicationRecord
    validates :name, uniqueness: true, presence: true

    has_many :folders, :dependent => :destroy
    has_many :analytics, :dependent => :destroy
    has_many :leads, :dependent => :destroy
    has_many :messages, :dependent => :destroy
    has_many :links, :dependent => :destroy

    has_many :user_companies, :dependent => :destroy
    has_many :users, :through => :user_companies
end

And the error is ActionController::UrlGenerationError in Companies#create

Can someone help with that? Sorry for my english.

Thank you!

Update December, 08.

My routes.rb

scope '/dashboard' do
    resources :companies do
      resources :users
      resources :user_companies
      resources :folder_links
      resources :folders
      resources :analytics
      resources :leads
      resources :links
      resources :messages

      get 'user_companies/new/search', to: "user_companies#search"
    end
  end

Body:
I fixed the error adding another validation. What was happening is that I was missing one more validation on application.html.erb:

<%= render 'shared/navbar' unless (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "edit")  %>
<%= render 'shared/sidebar' unless current_page?(root_path) || current_page?(edit_user_registration_path) || (controller.controller_name == "companies" && controller.action_name == "index") || (controller.controller_name == "companies" && controller.action_name == "new") || current_page?(new_company_path) || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "messages" && controller.action_name == "edit") %>

I just added the condition to when the current action is create:

<%= render 'shared/navbar' unless (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "edit")  %>
<%= render 'shared/sidebar' unless current_page?(root_path) || current_page?(edit_user_registration_path) || (controller.controller_name == "companies" && controller.action_name == "index") || (controller.controller_name == "companies" && controller.action_name == "create") || (controller.controller_name == "companies" && controller.action_name == "new") || current_page?(new_company_path) || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "messages" && controller.action_name == "edit") %>

Sorry for waste your time.

Thank you for trying to help, guys!


问:
Valgrind not showing line numbers when compiled with cmake
I am compiling my project with the command cmake .. -G "CodeBlocks - Ninja, which works fine, but when I run valgrind it does not display any lines numbers.
This is the valgrind command I am using: valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes  --log-file="log.txt" ./pony_gpExe.

Here is an example of the output:

```<code>==5402== Use of uninitialised value of size 8
==5402==    at 0x40447B: get_double_arr_length (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x405184: get_test_and_train_data (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x4027B3: setup (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x402861: main (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==  Uninitialised value was created by a stack allocation
==5402==    at 0x405149: get_test_and_train_data (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
</code>```

Not sure if this is helpful but here is my main CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.4.3)
project (pony_gp)
set(DIR ${pony_gp_SOURCE_DIR})

file(GLOB_RECURSE pony_gp_SOURCES "${DIR}/src/*.c")
file(GLOB_RECURSE pony_gp_HEADERS "${DIR}/include/*.h")

foreach (_headerFile ${pony_gp_HEADERS})
    get_filename_component(_dir ${_headerFile} PATH)
    list (APPEND pony_gp_INCLUDE_DIRS ${_dir})
endforeach()
list(REMOVE_DUPLICATES pony_gp_INCLUDE_DIRS)

include("${DIR}/include/CMakeLists.txt")
include_directories(${pony_gp_INCLUDE_DIRS})
add_executable (pony_gpExe ${pony_gp_SOURCES})

if (CMAKE_COMPILER_IS_GNUCC)

    target_link_libraries(pony_gpExe m)

    find_program(MEMORYCHECK_COMMAND valgrind)
    set(MEMORYCHECK_COMMAND_OPTIONS "--trace-children=yes --leak-check=full")
    set(MEMORYCHECK_SUPPRESSIONS_FILE "${DIR}/valgrind_suppress.txt")
endif()

include(CTest)
add_test(test pony_gpExe)
</code>```

答:
I hope you compiled your code with -g and assume you running code in Ubuntu or Mac OS

Try to run valgrind like this which does the trick in Ubuntu

```<code>valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --dsymutil=yes --log-file="log.txt" ./pony_gpExe.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am compiling my project with the command cmake .. -G "CodeBlocks - Ninja, which works fine, but when I run valgrind it does not display any lines numbers.
This is the valgrind command I am using: valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes  --log-file="log.txt" ./pony_gpExe.

Here is an example of the output:

==5402== Use of uninitialised value of size 8
==5402==    at 0x40447B: get_double_arr_length (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x405184: get_test_and_train_data (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x4027B3: setup (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x402861: main (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==  Uninitialised value was created by a stack allocation
==5402==    at 0x405149: get_test_and_train_data (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)

Not sure if this is helpful but here is my main CMakeLists.txt:

cmake_minimum_required(VERSION 3.4.3)
project (pony_gp)
set(DIR ${pony_gp_SOURCE_DIR})

file(GLOB_RECURSE pony_gp_SOURCES "${DIR}/src/*.c")
file(GLOB_RECURSE pony_gp_HEADERS "${DIR}/include/*.h")

foreach (_headerFile ${pony_gp_HEADERS})
    get_filename_component(_dir ${_headerFile} PATH)
    list (APPEND pony_gp_INCLUDE_DIRS ${_dir})
endforeach()
list(REMOVE_DUPLICATES pony_gp_INCLUDE_DIRS)

include("${DIR}/include/CMakeLists.txt")
include_directories(${pony_gp_INCLUDE_DIRS})
add_executable (pony_gpExe ${pony_gp_SOURCES})

if (CMAKE_COMPILER_IS_GNUCC)

    target_link_libraries(pony_gpExe m)

    find_program(MEMORYCHECK_COMMAND valgrind)
    set(MEMORYCHECK_COMMAND_OPTIONS "--trace-children=yes --leak-check=full")
    set(MEMORYCHECK_SUPPRESSIONS_FILE "${DIR}/valgrind_suppress.txt")
endif()

include(CTest)
add_test(test pony_gpExe)

Body:
I hope you compiled your code with -g and assume you running code in Ubuntu or Mac OS

Try to run valgrind like this which does the trick in Ubuntu

valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --dsymutil=yes --log-file="log.txt" ./pony_gpExe.


问:
Mongoose query find() returns nothing
I'm querying db with 2 conditions, keyword and user id, both returns correctly in console log but returns nothing, not null, or [], just blank. Something is wrong with the syntax?

```<code>app.get("/api/client?", function (req, res) {

console.log("Search > " + JSON.stringify(req.query));
//Search > {"keyword":"emily","filterby":"5a25f3d1d4b3e30792dd53ca"}

var keyword = req.query.keyword;
var user_id = req.query.id;

Client.find({
  $and: [{
      "firstname": new RegExp('^' + keyword + '$', "i")
    },
    {
      userid: user_id
    }
  ]
}, (err, result) => {
  if (err) {
    console.log(err);
  }
  res.status(200).json(result);
  console.log("Result is... " + result)
  //Result is

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

Alternatively, I tried without query, just search all based on user id and it works, it returns all records in db

```<code>app.get("/client", function (req, res) {
var user_id = req.query.id;

Client.find({
  userid: user_id
}, (err, result) => {
  if (err) {
    console.log(err);
  }
  res.status(200).json(result);

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

答:
Found the solution! Noob mistake, I was caught up with what was working in search all, var user_id = req.query.id but in fact when I passed in "filterby", based on </p>

```<code>console.log {"keyword":"emily","filterby":"5a25f3d1d4b3e30792dd53ca"}
</code>```

<p>so it should be </p>

```<code>var keyword = req.query.keyword;
var **filterby** = req.query.id;

Client.find({
   $and: [{
       "firstname": new RegExp('^' + keyword + '$', "i")
       },
       {
       userid: **filterby**
       }
     ]
   }
</code>```

Title: Mongoose query find() returns nothing

Body:
I'm querying db with 2 conditions, keyword and user id, both returns correctly in console log but returns nothing, not null, or [], just blank. Something is wrong with the syntax?

app.get("/api/client?", function (req, res) {

console.log("Search > " + JSON.stringify(req.query));
//Search > {"keyword":"emily","filterby":"5a25f3d1d4b3e30792dd53ca"}

var keyword = req.query.keyword;
var user_id = req.query.id;

Client.find({
  $and: [{
      "firstname": new RegExp('^' + keyword + '$', "i")
    },
    {
      userid: user_id
    }
  ]
}, (err, result) => {
  if (err) {
    console.log(err);
  }
  res.status(200).json(result);
  console.log("Result is... " + result)
  //Result is

});
});

Alternatively, I tried without query, just search all based on user id and it works, it returns all records in db

app.get("/client", function (req, res) {
var user_id = req.query.id;

Client.find({
  userid: user_id
}, (err, result) => {
  if (err) {
    console.log(err);
  }
  res.status(200).json(result);

});
});

Body:
Found the solution! Noob mistake, I was caught up with what was working in search all, var user_id = req.query.id but in fact when I passed in "filterby", based on

console.log {"keyword":"emily","filterby":"5a25f3d1d4b3e30792dd53ca"}

so it should be

var keyword = req.query.keyword;
var **filterby** = req.query.id;

Client.find({
   $and: [{
       "firstname": new RegExp('^' + keyword + '$', "i")
       },
       {
       userid: **filterby**
       }
     ]
   }


问:
Setting getSheetbyName according to cell value
I'm not much of a programmer but managed to cobbled together a script and can't seem to get the last part working. I want to pass activelog string into log and feel like it's a simple syntax issue I'm overlooking:

```<code>var activelog = e.source.getSheetByName("SHEET1").getRange("A1").getValue();
var log = e.source.getSheetByName(activelog);
</code>```

Activelog gets the value of dropdown menu cell A1 on Sheet1 that contains list of all the relevant sheets. The script then copies down a formula in column C of whichever sheet is selected if something is typed in B1 of Sheet1. Right now specifying the sheetname "LOG" works fine:

```<code>function onEdit(e) {
    var activelog = e.source.getSheetByName("SHEET1").getRange("A1").getValue();
    var log = e.source.getSheetByName("LOG");
    var lr = log.getLastRow();
    var fdr = log.getRange(1,23,lr);
    var formula = "";

    if (e.source.getActiveSheet().getName() !== "SHEET1" || e.range.rowStart != 1 || e.range.columnStart != 2 ) return
    log.getRange("C1").setFormula(formula);log.getRange("C1").copyTo(fdr);
}
</code>```

答:
If the sheet is empty then var lr = log.getLastRow() will return a 0. Then when the log.getRange(1,23,lr) tries to getRange(1,23,0) it will error as it is an invalid range.

Add log.getLastRow() || 1; to set lr to 1, if the sheet is empty.

```<code>function onEdit(e) {
  var activelog = e.source.getSheetByName("SHEET1").getRange("A1").getValue();
  var log = e.source.getSheetByName(activelog);

  // If getLastRow() returns 0, set 1
  var lr = log.getLastRow() || 1;
  var fdr = log.getRange(1,23,lr);

  var formula = "=SUM(1+2)"; // for testing

  if (e.source.getActiveSheet().getName() !== "SHEET1" || e.range.rowStart != 1 || e.range.columnStart != 2 ) return
  log.getRange("C1").setFormula(formula);log.getRange("C1").copyTo(fdr);
}
</code>```

Body:
I'm not much of a programmer but managed to cobbled together a script and can't seem to get the last part working. I want to pass activelog string into log and feel like it's a simple syntax issue I'm overlooking:

var activelog = e.source.getSheetByName("SHEET1").getRange("A1").getValue();
var log = e.source.getSheetByName(activelog);

Activelog gets the value of dropdown menu cell A1 on Sheet1 that contains list of all the relevant sheets. The script then copies down a formula in column C of whichever sheet is selected if something is typed in B1 of Sheet1. Right now specifying the sheetname "LOG" works fine:

function onEdit(e) {
    var activelog = e.source.getSheetByName("SHEET1").getRange("A1").getValue();
    var log = e.source.getSheetByName("LOG");
    var lr = log.getLastRow();
    var fdr = log.getRange(1,23,lr);
    var formula = "";

    if (e.source.getActiveSheet().getName() !== "SHEET1" || e.range.rowStart != 1 || e.range.columnStart != 2 ) return
    log.getRange("C1").setFormula(formula);log.getRange("C1").copyTo(fdr);
}

Body:
If the sheet is empty then var lr = log.getLastRow() will return a 0. Then when the log.getRange(1,23,lr) tries to getRange(1,23,0) it will error as it is an invalid range.

Add log.getLastRow() || 1; to set lr to 1, if the sheet is empty.

function onEdit(e) {
  var activelog = e.source.getSheetByName("SHEET1").getRange("A1").getValue();
  var log = e.source.getSheetByName(activelog);

  // If getLastRow() returns 0, set 1
  var lr = log.getLastRow() || 1;
  var fdr = log.getRange(1,23,lr);

  var formula = "=SUM(1+2)"; // for testing

  if (e.source.getActiveSheet().getName() !== "SHEET1" || e.range.rowStart != 1 || e.range.columnStart != 2 ) return
  log.getRange("C1").setFormula(formula);log.getRange("C1").copyTo(fdr);
}


问:
How to only import _(value)?
I'm reducing non-used import in my web project.

According to lodash.com, I can cherry-pick the methods I use, which is good.

ex:

```<code>var at = require('lodash/at');
</code>```

But I don't know how to only import _(value).

I tried the following which doesn't work

```<code>const seq = require("lodash/seq");
</code>```

Anyone can help?

答:
Probably you can import chain method. But I'm not sure if it works properly with cherry-picking.

```<code>const chain = require('lodash/chain');
</code>```

P.s. check out the interesting article Why using _.chain is a mistake. and methods flow and flowRight

Title: How to only import _(value)?

Body:
I'm reducing non-used import in my web project.

According to lodash.com, I can cherry-pick the methods I use, which is good.

ex:

var at = require('lodash/at');

But I don't know how to only import _(value).

I tried the following which doesn't work

const seq = require("lodash/seq");

Anyone can help?

Body:
Probably you can import chain method. But I'm not sure if it works properly with cherry-picking.

const chain = require('lodash/chain');

P.s. check out the interesting article Why using _.chain is a mistake. and methods flow and flowRight