问:
jQuery click events firing multiple times
I'm attempting to write a video poker game in Javascript as a way of getting the basics of it down, and I've run into a problem where the jQuery click event handlers are firing multiple times.

They're attached to buttons for placing a bet, and it works fine for placing a bet on the first hand during a game (firing only once); but in betting for the second hand, it fires the click event twice each time a bet or place bet button is pressed (so twice the correct amount is bet for each press).  Overall, it follows this pattern for number of times the click event is fired when pressing a bet button once--where the ith term of the sequence is for the betting of the ith hand from the beginning of the game: 1, 2, 4, 7, 11, 16, 22, 29, 37, 46, which appears to be n(n+1)/2 + 1 for whatever that's worth--and I wasn't smart enough to figure that out, I used OEIS. :)

Here's the function with the click event handlers that are acting up; hopefully it's easy to understand (let me know if not, I want to get better at that as well):

```<code>/** The following function keeps track of bet buttons that are pressed, until place button is pressed to place bet. **/
function pushingBetButtons() {
    $("#money").text("Money left: $" + player.money); // displays money player has left

    $(".bet").click(function() {
        var amount = 0; // holds the amount of money the player bet on this click
        if($(this).attr("id") == "bet1") { // the player just bet $1
            amount = 1;
        } else if($(this).attr("id") == "bet5") { // etc.
            amount = 5;
        } else if($(this).attr("id") == "bet25") {
            amount = 25;
        } else if($(this).attr("id") == "bet100") {
            amount = 100;
        } else if($(this).attr("id") == "bet500") {
            amount = 500;
        } else if($(this).attr("id") == "bet1000") {
            amount = 1000;
        }
        if(player.money >= amount) { // check whether the player has this much to bet
            player.bet += amount; // add what was just bet by clicking that button to the total bet on this hand
            player.money -= amount; // and, of course, subtract it from player's current pot
            $("#money").text("Money left: $" + player.money); // then redisplay what the player has left
        } else {
            alert("You don't have $" + amount + " to bet.");
        }
    });

    $("#place").click(function() {
        if(player.bet == 0) { // player didn't bet anything on this hand
            alert("Please place a bet first.");
        } else {
            $("#card_para").css("display", "block"); // now show the cards
            $(".card").bind("click", cardClicked); // and set up the event handler for the cards
            $("#bet_buttons_para").css("display", "none"); // hide the bet buttons and place bet button
            $("#redraw").css("display", "block"); // and reshow the button for redrawing the hand
            player.bet = 0; // reset the bet for betting on the next hand
            drawNewHand(); // draw the cards
        }
    });
}
</code>```

Please let me know if you have any ideas or suggestions, or if the solution to my problem is similar to a solution to another problem on here (I've looked at many similarly titled threads and had no luck in finding a solution that could work for me).

答:
The below code worked for me in my chat application to handle multiple mouse click triggering events more than once.
if (!e.originalEvent.detail || e.originalEvent.detail == 1)
{ // Your code logic }

Body:
I'm attempting to write a video poker game in Javascript as a way of getting the basics of it down, and I've run into a problem where the jQuery click event handlers are firing multiple times.

They're attached to buttons for placing a bet, and it works fine for placing a bet on the first hand during a game (firing only once); but in betting for the second hand, it fires the click event twice each time a bet or place bet button is pressed (so twice the correct amount is bet for each press).  Overall, it follows this pattern for number of times the click event is fired when pressing a bet button once--where the ith term of the sequence is for the betting of the ith hand from the beginning of the game: 1, 2, 4, 7, 11, 16, 22, 29, 37, 46, which appears to be n(n+1)/2 + 1 for whatever that's worth--and I wasn't smart enough to figure that out, I used OEIS. :)

Here's the function with the click event handlers that are acting up; hopefully it's easy to understand (let me know if not, I want to get better at that as well):

/** The following function keeps track of bet buttons that are pressed, until place button is pressed to place bet. **/
function pushingBetButtons() {
    $("#money").text("Money left: $" + player.money); // displays money player has left

    $(".bet").click(function() {
        var amount = 0; // holds the amount of money the player bet on this click
        if($(this).attr("id") == "bet1") { // the player just bet $1
            amount = 1;
        } else if($(this).attr("id") == "bet5") { // etc.
            amount = 5;
        } else if($(this).attr("id") == "bet25") {
            amount = 25;
        } else if($(this).attr("id") == "bet100") {
            amount = 100;
        } else if($(this).attr("id") == "bet500") {
            amount = 500;
        } else if($(this).attr("id") == "bet1000") {
            amount = 1000;
        }
        if(player.money >= amount) { // check whether the player has this much to bet
            player.bet += amount; // add what was just bet by clicking that button to the total bet on this hand
            player.money -= amount; // and, of course, subtract it from player's current pot
            $("#money").text("Money left: $" + player.money); // then redisplay what the player has left
        } else {
            alert("You don't have $" + amount + " to bet.");
        }
    });

    $("#place").click(function() {
        if(player.bet == 0) { // player didn't bet anything on this hand
            alert("Please place a bet first.");
        } else {
            $("#card_para").css("display", "block"); // now show the cards
            $(".card").bind("click", cardClicked); // and set up the event handler for the cards
            $("#bet_buttons_para").css("display", "none"); // hide the bet buttons and place bet button
            $("#redraw").css("display", "block"); // and reshow the button for redrawing the hand
            player.bet = 0; // reset the bet for betting on the next hand
            drawNewHand(); // draw the cards
        }
    });
}

Please let me know if you have any ideas or suggestions, or if the solution to my problem is similar to a solution to another problem on here (I've looked at many similarly titled threads and had no luck in finding a solution that could work for me).


来源: stackexchange

问:
How to show ProgressBar in centre of screen regardless layout types
I wonder if there is any way to show a ProgressBar at the middle of the screen programatically regardless the type of layout of the current Activity like a toast can be shown like,

```<code>Toast toast = Toast.makeText(Activity.this,"Sample toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
</code>```

答:
Thanks ADM and Reddy for guidance. Finally I was able to show a progressBar using dialog,</p>

```<code>var loadingDialog: Dialog? = null

fun showLoadingDialog() {

    loadingDialog = Dialog(this)

    loadingDialog?.window?.requestFeature(Window.FEATURE_NO_TITLE)
    loadingDialog?.setCancelable(true)

    val relativeLayout = RelativeLayout(this)
    relativeLayout.layoutParams = RelativeLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)

    val progressBar = ProgressBar(this, null, android.R.attr.progressBarStyleLarge)
    val params = RelativeLayout.LayoutParams(150, 150)
    params.addRule(RelativeLayout.CENTER_IN_PARENT)

    relativeLayout.addView(progressBar, params)

    loadingDialog?.window?.setContentView(relativeLayout, relativeLayout.layoutParams)
        loadingDialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        loadingDialog?.show()
}

fun hideLoadingDialog(){

    loadingDialog?.hide()
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wonder if there is any way to show a ProgressBar at the middle of the screen programatically regardless the type of layout of the current Activity like a toast can be shown like,

Toast toast = Toast.makeText(Activity.this,"Sample toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

Body:
Thanks ADM and Reddy for guidance. Finally I was able to show a progressBar using dialog,

var loadingDialog: Dialog? = null

fun showLoadingDialog() {

    loadingDialog = Dialog(this)

    loadingDialog?.window?.requestFeature(Window.FEATURE_NO_TITLE)
    loadingDialog?.setCancelable(true)

    val relativeLayout = RelativeLayout(this)
    relativeLayout.layoutParams = RelativeLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)

    val progressBar = ProgressBar(this, null, android.R.attr.progressBarStyleLarge)
    val params = RelativeLayout.LayoutParams(150, 150)
    params.addRule(RelativeLayout.CENTER_IN_PARENT)

    relativeLayout.addView(progressBar, params)

    loadingDialog?.window?.setContentView(relativeLayout, relativeLayout.layoutParams)
        loadingDialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        loadingDialog?.show()
}

fun hideLoadingDialog(){

    loadingDialog?.hide()
}


问:
How to perform multiple updates in single merge statement
I need to update multiple columns in a single merge statement with two differ conditions like
1. row_ind = N; update some columns

2. row_ind = Y; update some columns

How i will achieves this one in sqlserver / oracle

```<code>WHEN MATCHED THEN
UPDATE SET TARGET.NodeId = SOURCE.StartNodeId,
           TARGET.LinkId = SOURCE.Id where row_ind ='Y'

UPDATE SET TARGET.NodeId = SOURCE.EndNodeId,
           TARGET.LinkId = SOURCE.Id where row_ind = 'N';
</code>```

答:
You can use "CASE..WHEN" to achieve the same in Oracle as follows:

```<code>WHEN MATCHED THEN UPDATE SET TARGET.NODEID = CASE ROW_IND
    WHEN 'Y'   THEN SOURCE.STARTNODEID
    WHEN 'N'   THEN SOURCE.ENDNODEID
END,
TARGET.LINKID = SOURCE.ID;
</code>```

Thanks

Body:
I need to update multiple columns in a single merge statement with two differ conditions like
1. row_ind = N; update some columns

2. row_ind = Y; update some columns

How i will achieves this one in sqlserver / oracle

WHEN MATCHED THEN
UPDATE SET TARGET.NodeId = SOURCE.StartNodeId,
           TARGET.LinkId = SOURCE.Id where row_ind ='Y'

UPDATE SET TARGET.NodeId = SOURCE.EndNodeId,
           TARGET.LinkId = SOURCE.Id where row_ind = 'N';

Body:
You can use "CASE..WHEN" to achieve the same in Oracle as follows:

WHEN MATCHED THEN UPDATE SET TARGET.NODEID = CASE ROW_IND
    WHEN 'Y'   THEN SOURCE.STARTNODEID
    WHEN 'N'   THEN SOURCE.ENDNODEID
END,
TARGET.LINKID = SOURCE.ID;

Thanks


问:
The access token is from the wrong issuer 'https://sts.windows.net'
I am using  'azure-arm-resource' for get all resources in azure for my node js project.

https://www.npmjs.com/package/azure-arm-resource

But using this I get some error,

```<code> msRestAzure.interactiveLogin().then(credentials => {
  const azureResources = new resourceManagement.ResourceManagementClient(credentials, subscriptionId);

  azureResources.resources
    .list()
    .then(res => {
      if (filter) {
        return res.filter(r => r.kind === filter);
      } else {
        return res;
      }
    })
    .then(d => {
      console.log('Done Resources');
    });
});
console.log('Pulling...');
 }
</code>```

Error,

```<code> Uncaught (in promise) Error: The access token is from the wrong issuer
'https://sts.windows.net/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx/'.
 It must match the tenant 'https://sts.windows.net/xxxx-xxx-xxxx-xxxx-
 c3xxx4xxffd57xx7/'
 associated with this subscription. Please use the authority (URL)
 'https://login.windows.net/xxxx-xxxx-xxx-xxxx-xxxxxxxx' to get the token.
  Note, if the subscription is transferred to another tenant there is no
 impact to the services, but information about new tenant could take time to
  propagate (up to an hour). If you just transferred your subscription and
  this error message, please try back later.
</code>```

Device Token Credentials undefined in azure interactive login

答:
When you login on the portal ,when using an org id something@yourcompany-name.com , it will work, but when use a live id something@gmail.com, we need to pass TenantId.

Primary purpose is to make the login experience simple for the user. Hence we start with minimal required parameters. For interactiveLogin(), I thought it was zero. But that is incorrect. TenantId or domain must be provided when using liveID.

Body:
I am using  'azure-arm-resource' for get all resources in azure for my node js project.

https://www.npmjs.com/package/azure-arm-resource

But using this I get some error,

 msRestAzure.interactiveLogin().then(credentials => {
  const azureResources = new resourceManagement.ResourceManagementClient(credentials, subscriptionId);

  azureResources.resources
    .list()
    .then(res => {
      if (filter) {
        return res.filter(r => r.kind === filter);
      } else {
        return res;
      }
    })
    .then(d => {
      console.log('Done Resources');
    });
});
console.log('Pulling...');
 }

Error,

 Uncaught (in promise) Error: The access token is from the wrong issuer
'https://sts.windows.net/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx/'.
 It must match the tenant 'https://sts.windows.net/xxxx-xxx-xxxx-xxxx-
 c3xxx4xxffd57xx7/'
 associated with this subscription. Please use the authority (URL)
 'https://login.windows.net/xxxx-xxxx-xxx-xxxx-xxxxxxxx' to get the token.
  Note, if the subscription is transferred to another tenant there is no
 impact to the services, but information about new tenant could take time to
  propagate (up to an hour). If you just transferred your subscription and
  this error message, please try back later.

Device Token Credentials undefined in azure interactive login


问:
How to pass variables from 1 method to another inside controller
i Want to get all these variables at one place so that i can add them into DB using a model.
Thank you in advance.

```<code>          public function web_login()
    {
            $data['user'] = array();

            if ($this->facebook->is_authenticated())
            {

                $user = $this->facebook->request('get', '/me?fields=id,name,email');
                if (!isset($user['error']))
                {
                    $data['user'] = $user; // ***WANNA PASS THIS VARIABLE FROM HERE***

                    $this->load->view('user/header');
                    $this->load->view('user/fbpass');
                    $this->load->view('user/footer');

            }
            else {
                $this->load->view('user/register');
            }
        }
}
</code>```

SECOND METHOD________________________________________________

```<code>                public function getpass(){
                $this->load->model('user_model', 'auth');
                $this->load->view('user/header');
                $this->load->library('form_validation');
                $this->form_validation->set_rules('password', 'Password', 'required');
                $this->form_validation->set_rules('passwordagain', 'Password Confirmation', 'required|matches[password]');

                if ($this->form_validation->run() == FALSE)
                {
                        $this->load->view('user/fbpass');
                }
                else
                {
                        $password=$this->input->post('password');

                       ***//WANNA GET THAT VARIABLE HERE***
                }

        }
</code>```

答:
```<code>class ClassName{
    public $var;
    function one(){
        $this->var = 'value';
    }

    function two(){
        return $this->var; // if you call function one then call function two you will get value
    }
}
</code>```

but if you need to call them not the same time you can use session

```<code>$_SESSION['var'] = 'value';
</code>```

Body:
i Want to get all these variables at one place so that i can add them into DB using a model.
Thank you in advance.

          public function web_login()
    {
            $data['user'] = array();

            if ($this->facebook->is_authenticated())
            {

                $user = $this->facebook->request('get', '/me?fields=id,name,email');
                if (!isset($user['error']))
                {
                    $data['user'] = $user; // ***WANNA PASS THIS VARIABLE FROM HERE***

                    $this->load->view('user/header');
                    $this->load->view('user/fbpass');
                    $this->load->view('user/footer');

            }
            else {
                $this->load->view('user/register');
            }
        }
}

SECOND METHOD________________________________________________

                public function getpass(){
                $this->load->model('user_model', 'auth');
                $this->load->view('user/header');
                $this->load->library('form_validation');
                $this->form_validation->set_rules('password', 'Password', 'required');
                $this->form_validation->set_rules('passwordagain', 'Password Confirmation', 'required|matches[password]');

                if ($this->form_validation->run() == FALSE)
                {
                        $this->load->view('user/fbpass');
                }
                else
                {
                        $password=$this->input->post('password');

                       ***//WANNA GET THAT VARIABLE HERE***
                }

        }

Body:
class ClassName{
    public $var;
    function one(){
        $this->var = 'value';
    }

    function two(){
        return $this->var; // if you call function one then call function two you will get value
    }
}

but if you need to call them not the same time you can use session

$_SESSION['var'] = 'value';


问:
Ramdajs, group array with arguments
List to group:

```<code>const arr = [
  {
    "Global Id": "1231",
    "TypeID": "FD1",
    "Size": 160,
    "Flöde": 55,
  },
  {
    "Global Id": "5433",
    "TypeID": "FD1",
    "Size": 160,
    "Flöde": 100,
  },
  {
    "Global Id": "50433",
    "TypeID": "FD1",
    "Size": 120,
    "Flöde": 100,
  },
 {
    "Global Id": "452",
    "TypeID": "FD2",
    "Size": 120,
    "Flöde": 100,
  },
]
</code>```

Input to function which specifies what keys to group:

```<code>const columns = [
    {
      "dataField": "TypeID",
      "summarize": false,
    },
    {
      "dataField": "Size",
      "summarize": false,
    },
    {
      "dataField": "Flöde",
      "summarize": true,
    },
]
</code>```

Expected output:

```<code>const output = [
    {
      "TypeID": "FD1",
      "Size": 160,
      "Flöde": 155 // 55 + 100
      "nrOfItems": 2
    },
    {
       "TypeID": "FD1",
       "Size": 120,
       "Flöde": 100,
       "nrOfItems": 1
    },
    {
       "TypeID": "FD2",
       "Size": 120,
       "Flöde": 100,
       "nrOfItems": 1
    }
  ]

  // nrOfItems adds up 4. 2 + 1 +1. The totalt nr of items.
</code>```

Function:

```<code>const groupArr = (columns) => R.pipe(...);
</code>```

The "summarize" property tells if the property should summarize or not.

The dataset is very large, +100k items. So I don't want to iterate more than necessary.

I've looked at the R.group but I'm not sure it can be applied here?

Maybe something with R.reduce? Store the group in the accumulator, summarize values and add to count if the group already exists? Need to find the group fast so maybe store the group as a key?

Or is it better to use vanilla javascript in this case?

答:
Here's an answer in vanilla javascipt first, because I'm not super familiar with the Ramda API. I'm pretty sure the approach is the quite similar with Ramda.

The code has comments explaining every step. I'll try to follow up with a rewrite to Ramda.

const arr=[{"Global Id":"1231",TypeID:"FD1",Size:160,"Flöde":55},{"Global Id":"5433",TypeID:"FD1",Size:160,"Flöde":100},{"Global Id":"50433",TypeID:"FD1",Size:120,"Flöde":100},{"Global Id":"452",TypeID:"FD2",Size:120,"Flöde":100}],columns=[{dataField:"TypeID",summarize:!1},{dataField:"Size",summarize:!1},{dataField:"Flöde",summarize:!0}];

// The columns that don't summarize
// give us the keys we need to group on
const groupKeys = columns
  .filter(c => c.summarize === false)
  .map(g => g.dataField);

// We compose a hash function that create
// a hash out of all the items' properties
// that are in our groupKeys
const groupHash = groupKeys
  .map(k => x => x[k])
  .reduce(
    (f, g) => x => `${f(x)}___${g(x)}`,
    () => "GROUPKEY"
  );

// The columns that summarize tell us which
// properties to sum for the items within the
// same group
const sumKeys = columns
  .filter(c => c.summarize === true)
  .map(c => c.dataField);

// Again, we compose in to a single function.
// This function concats two items, taking the
// "last" item with only applying the sum
// logic for keys in concatKeys
const concats = sumKeys
  .reduce(
    (f, k) => (a, b) => Object.assign(f(a, b), {
      [k]: (a[k] || 0) + b[k]
    }),
    (a, b) => Object.assign({}, a, b)
  )

// Now, we take our data and group by the groupHash
const groups = arr.reduce(
  (groups, x) => {
    const k = groupHash(x);
    if (!groups[k]) groups[k] = [x];
    else groups[k].push(x);
    return groups;
  },
  {}
);

// These are the keys we want our final objects to have...
const allKeys = ["nrTotal"]
  .concat(groupKeys)
  .concat(sumKeys);

// ...baked in to a helper to remove other keys
const cleanKeys = obj => Object.assign(
  ...allKeys.map(k => ({ [k]: obj[k] }))
);

// With the items neatly grouped, we can reduce each
// group using the composed concatenator
const items = Object
  .values(groups)
  .flatMap(
    xs => cleanKeys(
      xs.reduce(concats, { nrTotal: xs.length })
    ),
  );

console.log(items);```
</div>
</div>
</p>

<p>Here's an attempt at porting to Ramda, but I didn't get much further than replacing the vanilla js methods with the Ramda equivalents. Curious to see which cool utilities and functional concepts I missed! I'm sure somebody more knowledgable on the Ramda specifics will chime in!</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr=[{"Global Id":"1231",TypeID:"FD1",Size:160,"Flöde":55},{"Global Id":"5433",TypeID:"FD1",Size:160,"Flöde":100},{"Global Id":"50433",TypeID:"FD1",Size:120,"Flöde":100},{"Global Id":"452",TypeID:"FD2",Size:120,"Flöde":100}],columns=[{dataField:"TypeID",summarize:!1},{dataField:"Size",summarize:!1},{dataField:"Flöde",summarize:!0}];

const [ sumCols, groupCols ] = R.partition(
  R.prop("summarize"),
  columns
);

const groupKeys = R.pluck("dataField", groupCols);
const sumKeys = R.pluck("dataField", sumCols);

const grouper = R.reduce(
  (f, g) => x => `${f(x)}___${g(x)}`,
  R.always("GROUPKEY"),
  R.map(R.prop, groupKeys)
);

const reducer = R.reduce(
  (f, k) => (a, b) => R.mergeRight(
    f(a, b),
    { [k]: (a[k] || 0) + b[k] }
  ),
  R.mergeRight,
  sumKeys
);

const allowedKeys = new Set(
  [ "nrTotal" ].concat(sumKeys).concat(groupKeys)
);

const cleanKeys = R.pipe(
  R.toPairs,
  R.filter(([k, v]) => allowedKeys.has(k)),
  R.fromPairs
);

const items = R.flatten(
  R.values(
    R.map(
      xs => cleanKeys(
        R.reduce(
          reducer,
          { nrTotal: xs.length },
          xs
        )
      ),
      R.groupBy(grouper, arr)
    )
  )
);

console.log(items);</code>```

```

Title: Ramdajs, group array with arguments

Body:
List to group:

const arr = [
  {
    "Global Id": "1231",
    "TypeID": "FD1",
    "Size": 160,
    "Flöde": 55,
  },
  {
    "Global Id": "5433",
    "TypeID": "FD1",
    "Size": 160,
    "Flöde": 100,
  },
  {
    "Global Id": "50433",
    "TypeID": "FD1",
    "Size": 120,
    "Flöde": 100,
  },
 {
    "Global Id": "452",
    "TypeID": "FD2",
    "Size": 120,
    "Flöde": 100,
  },
]

Input to function which specifies what keys to group:

const columns = [
    {
      "dataField": "TypeID",
      "summarize": false,
    },
    {
      "dataField": "Size",
      "summarize": false,
    },
    {
      "dataField": "Flöde",
      "summarize": true,
    },
]

Expected output:

const output = [
    {
      "TypeID": "FD1",
      "Size": 160,
      "Flöde": 155 // 55 + 100
      "nrOfItems": 2
    },
    {
       "TypeID": "FD1",
       "Size": 120,
       "Flöde": 100,
       "nrOfItems": 1
    },
    {
       "TypeID": "FD2",
       "Size": 120,
       "Flöde": 100,
       "nrOfItems": 1
    }
  ]

  // nrOfItems adds up 4. 2 + 1 +1. The totalt nr of items.

Function:

const groupArr = (columns) => R.pipe(...);

The "summarize" property tells if the property should summarize or not.

The dataset is very large, +100k items. So I don't want to iterate more than necessary.

I've looked at the R.group but I'm not sure it can be applied here?

Maybe something with R.reduce? Store the group in the accumulator, summarize values and add to count if the group already exists? Need to find the group fast so maybe store the group as a key?

Or is it better to use vanilla javascript in this case?

Body:
Here's an answer in vanilla javascipt first, because I'm not super familiar with the Ramda API. I'm pretty sure the approach is the quite similar with Ramda.

The code has comments explaining every step. I'll try to follow up with a rewrite to Ramda.

const arr=[{"Global Id":"1231",TypeID:"FD1",Size:160,"Flöde":55},{"Global Id":"5433",TypeID:"FD1",Size:160,"Flöde":100},{"Global Id":"50433",TypeID:"FD1",Size:120,"Flöde":100},{"Global Id":"452",TypeID:"FD2",Size:120,"Flöde":100}],columns=[{dataField:"TypeID",summarize:!1},{dataField:"Size",summarize:!1},{dataField:"Flöde",summarize:!0}];

// The columns that don't summarize
// give us the keys we need to group on
const groupKeys = columns
  .filter(c => c.summarize === false)
  .map(g => g.dataField);

// We compose a hash function that create
// a hash out of all the items' properties
// that are in our groupKeys
const groupHash = groupKeys
  .map(k => x => x[k])
  .reduce(
    (f, g) => x => `${f(x)}___${g(x)}`,
    () => "GROUPKEY"
  );

// The columns that summarize tell us which
// properties to sum for the items within the
// same group
const sumKeys = columns
  .filter(c => c.summarize === true)
  .map(c => c.dataField);

// Again, we compose in to a single function.
// This function concats two items, taking the
// "last" item with only applying the sum
// logic for keys in concatKeys
const concats = sumKeys
  .reduce(
    (f, k) => (a, b) => Object.assign(f(a, b), {
      [k]: (a[k] || 0) + b[k]
    }),
    (a, b) => Object.assign({}, a, b)
  )

// Now, we take our data and group by the groupHash
const groups = arr.reduce(
  (groups, x) => {
    const k = groupHash(x);
    if (!groups[k]) groups[k] = [x];
    else groups[k].push(x);
    return groups;
  },
  {}
);

// These are the keys we want our final objects to have...
const allKeys = ["nrTotal"]
  .concat(groupKeys)
  .concat(sumKeys);

// ...baked in to a helper to remove other keys
const cleanKeys = obj => Object.assign(
  ...allKeys.map(k => ({ [k]: obj[k] }))
);

// With the items neatly grouped, we can reduce each
// group using the composed concatenator
const items = Object
  .values(groups)
  .flatMap(
    xs => cleanKeys(
      xs.reduce(concats, { nrTotal: xs.length })
    ),
  );

console.log(items);

Here's an attempt at porting to Ramda, but I didn't get much further than replacing the vanilla js methods with the Ramda equivalents. Curious to see which cool utilities and functional concepts I missed! I'm sure somebody more knowledgable on the Ramda specifics will chime in!

const arr=[{"Global Id":"1231",TypeID:"FD1",Size:160,"Flöde":55},{"Global Id":"5433",TypeID:"FD1",Size:160,"Flöde":100},{"Global Id":"50433",TypeID:"FD1",Size:120,"Flöde":100},{"Global Id":"452",TypeID:"FD2",Size:120,"Flöde":100}],columns=[{dataField:"TypeID",summarize:!1},{dataField:"Size",summarize:!1},{dataField:"Flöde",summarize:!0}];

const [ sumCols, groupCols ] = R.partition(
  R.prop("summarize"),
  columns
);

const groupKeys = R.pluck("dataField", groupCols);
const sumKeys = R.pluck("dataField", sumCols);

const grouper = R.reduce(
  (f, g) => x => `${f(x)}___${g(x)}`,
  R.always("GROUPKEY"),
  R.map(R.prop, groupKeys)
);

const reducer = R.reduce(
  (f, k) => (a, b) => R.mergeRight(
    f(a, b),
    { [k]: (a[k] || 0) + b[k] }
  ),
  R.mergeRight,
  sumKeys
);

const allowedKeys = new Set(
  [ "nrTotal" ].concat(sumKeys).concat(groupKeys)
);

const cleanKeys = R.pipe(
  R.toPairs,
  R.filter(([k, v]) => allowedKeys.has(k)),
  R.fromPairs
);

const items = R.flatten(
  R.values(
    R.map(
      xs => cleanKeys(
        R.reduce(
          reducer,
          { nrTotal: xs.length },
          xs
        )
      ),
      R.groupBy(grouper, arr)
    )
  )
);

console.log(items);

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>


问:
Eclipse CDT crash randomly under Windows 7 x64?
I use the last JRE, Eclipse C++ package and Mingw. I can compile but Eclipse crash randomly in few minutes after it starts.

Log file :

```<code>eclipse.buildId=M20110210-1200
java.version=1.6.0_24
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=fr_FR
Framework arguments:  -product org.eclipse.epp.package.cpp.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.cpp.product

!ENTRY org.eclipse.core.resources 2 10035 2011-03-11 20:08:04.087
!MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes.

!ENTRY org.eclipse.cdt.core 4 0 2011-03-11 20:19:20.164
!MESSAGE Error while parsing /TD1_Seq/src/main.cpp.
!STACK 0
java.lang.NullPointerException
at     org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTemplateId.accept(CPPASTTemplateId.java:162)
at org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTCompositeTypeSpecifier.accept(CPPASTCompositeTypeSpecifier.java:153)
at org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclaration.accept(CPPASTSimpleDeclaration.java:89)
at org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTemplateSpecialization.accept(CPPASTTemplateSpecialization.java:73)
at org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTNamespaceDefinition.accept(CPPASTNamespaceDefinition.java:116)
at org.eclipse.cdt.internal.core.dom.parser.ASTTranslationUnit.accept(ASTTranslationUnit.java:268)
at org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTranslationUnit.resolveAmbiguities(CPPASTTranslationUnit.java:173)
at org.eclipse.cdt.internal.core.dom.parser.AbstractGNUSourceCodeParser.resolveAmbiguities(AbstractGNUSourceCodeParser.java:664)
at org.eclipse.cdt.internal.core.dom.parser.AbstractGNUSourceCodeParser.parse(AbstractGNUSourceCodeParser.java:651)
at org.eclipse.cdt.core.dom.parser.AbstractCLikeLanguage.getASTTranslationUnit(AbstractCLikeLanguage.java:143)
at org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask.createAST(AbstractIndexerTask.java:285)
at org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask.createAST(AbstractIndexerTask.java:258)
at org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask.parseFile(AbstractIndexerTask.java:754)
at org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask.parseLinkage(AbstractIndexerTask.java:637)
at org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask.runTask(AbstractIndexerTask.java:344)
at org.eclipse.cdt.internal.core.pdom.indexer.PDOMIndexerTask.run(PDOMIndexerTask.java:127)
at org.eclipse.cdt.internal.core.pdom.PDOMIndexerJob.run(PDOMIndexerJob.java:137)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
</code>```

I try to use option :
    -vm "C:\Programs Files\java\bin\"
but eclipse still crash and no error is report in log file.

log file : http://pastebin.com/zEgQjmPq

答: Try to use JVM update 22, it resolved the problem.</p>

ContentLicense: CC BY-SA 2.5

Body:
I use the last JRE, Eclipse C++ package and Mingw. I can compile but Eclipse crash randomly in few minutes after it starts.

Log file :

eclipse.buildId=M20110210-1200
java.version=1.6.0_24
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=fr_FR
Framework arguments:  -product org.eclipse.epp.package.cpp.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.cpp.product

!ENTRY org.eclipse.core.resources 2 10035 2011-03-11 20:08:04.087
!MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes.

!ENTRY org.eclipse.cdt.core 4 0 2011-03-11 20:19:20.164
!MESSAGE Error while parsing /TD1_Seq/src/main.cpp.
!STACK 0
java.lang.NullPointerException
at     org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTemplateId.accept(CPPASTTemplateId.java:162)
at org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTCompositeTypeSpecifier.accept(CPPASTCompositeTypeSpecifier.java:153)
at org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclaration.accept(CPPASTSimpleDeclaration.java:89)
at org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTemplateSpecialization.accept(CPPASTTemplateSpecialization.java:73)
at org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTNamespaceDefinition.accept(CPPASTNamespaceDefinition.java:116)
at org.eclipse.cdt.internal.core.dom.parser.ASTTranslationUnit.accept(ASTTranslationUnit.java:268)
at org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTranslationUnit.resolveAmbiguities(CPPASTTranslationUnit.java:173)
at org.eclipse.cdt.internal.core.dom.parser.AbstractGNUSourceCodeParser.resolveAmbiguities(AbstractGNUSourceCodeParser.java:664)
at org.eclipse.cdt.internal.core.dom.parser.AbstractGNUSourceCodeParser.parse(AbstractGNUSourceCodeParser.java:651)
at org.eclipse.cdt.core.dom.parser.AbstractCLikeLanguage.getASTTranslationUnit(AbstractCLikeLanguage.java:143)
at org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask.createAST(AbstractIndexerTask.java:285)
at org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask.createAST(AbstractIndexerTask.java:258)
at org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask.parseFile(AbstractIndexerTask.java:754)
at org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask.parseLinkage(AbstractIndexerTask.java:637)
at org.eclipse.cdt.internal.core.pdom.AbstractIndexerTask.runTask(AbstractIndexerTask.java:344)
at org.eclipse.cdt.internal.core.pdom.indexer.PDOMIndexerTask.run(PDOMIndexerTask.java:127)
at org.eclipse.cdt.internal.core.pdom.PDOMIndexerJob.run(PDOMIndexerJob.java:137)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

I try to use option :
    -vm "C:\Programs Files\java\bin\"
but eclipse still crash and no error is report in log file.

log file : http://pastebin.com/zEgQjmPq

ContentLicense: CC BY-SA 3.0


答:
```<code>class TestClass extends Controller {
    function test_mehtod($param) {
        //do something
       echo $param."<br>";
       echo "hi, you are in same controller";
    }

    function test_mehtod2() {
        //do something-else
        $this->test_mehtod("param value");
        // and we called the other method here!
    }
}
</code>```

Title: How to pass variables from 1 method to another inside controller


问:
Unzoomable element
I want to make div with size equal to 1 screen pixel regardless current browser zoom.

It's important for me that this element will be as small as possible, but will cause line break if the next element tries to get same size as container or larger.

I used 1px but when page zoom is less then 100% it gets unstable - sometimes it works, but sometimes Chrome shrinks element to 0 and does not wrap the next element. So I hoped to enlarge element on other zooms, but I don't know how to detect it.

Seems like on my computer next snippet works fine, but in the real code similar thing works unstable if browser zoom is less than 100%. In this example I want red div to take 1px of the screen width regardless current zoom. Is that possible?

~function () {
  var s = "When silver div gets too wide it should jump down..."
  var i = s.length
  var div = document.querySelector(".content");

  setInterval(function () {
    div.textContent = s.slice(0, i = ++i % (s.length + 1))
  }, 100)
}()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
  width: 15em;
  height: 2em;
  line-height: 2em;
  border: 1px solid;
}

div {
  display: inline-block;
  vertical-align: top;
  height: 100%;
}

.narrow {
  width: 1px;
  background: red;
  margin-bottom: 1px;
}

.content {
  background: silver;
  white-space: nowrap;
}</code>```

```

答:
For webkit it's possible with media queries:

~function () {
  var s = "When silver div gets too wide it should jump down..."
  var i = s.length
  var div = document.querySelector(".content");

  setInterval(function () {
    div.textContent = s.slice(0, i = ++i % (s.length + 1))
  }, 100)
}()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
  width: 15em;
  height: 2em;
  line-height: 2em;
  border: 1px solid;
}

div {
  display: inline-block;
  vertical-align: top;
  height: 100%;
}

.narrow {
  width: 1px;
  background: red;
  margin-bottom: 1px;
}

@media (-webkit-min-device-pixel-ratio: .1 )   { .narrow { width: 10px; } }
@media (-webkit-min-device-pixel-ratio: .25)   { .narrow { width:  4px; } }
@media (-webkit-min-device-pixel-ratio: .3 )   { .narrow { width:  3px; } }
@media (-webkit-min-device-pixel-ratio: .5 )   { .narrow { width:  2px; } }
@media (-webkit-min-device-pixel-ratio: 1  )   { .narrow { width:  1px; } }

.content {
  background: silver;
  white-space: nowrap;
}</code>```

```

Title: Unzoomable element

Body:
I want to make div with size equal to 1 screen pixel regardless current browser zoom.

It's important for me that this element will be as small as possible, but will cause line break if the next element tries to get same size as container or larger.

I used 1px but when page zoom is less then 100% it gets unstable - sometimes it works, but sometimes Chrome shrinks element to 0 and does not wrap the next element. So I hoped to enlarge element on other zooms, but I don't know how to detect it.

Seems like on my computer next snippet works fine, but in the real code similar thing works unstable if browser zoom is less than 100%. In this example I want red div to take 1px of the screen width regardless current zoom. Is that possible?

~function () {
  var s = "When silver div gets too wide it should jump down..."
  var i = s.length
  var div = document.querySelector(".content");

  setInterval(function () {
    div.textContent = s.slice(0, i = ++i % (s.length + 1))
  }, 100)
}()

section {
  width: 15em;
  height: 2em;
  line-height: 2em;
  border: 1px solid;
}

div {
  display: inline-block;
  vertical-align: top;
  height: 100%;
}

.narrow {
  width: 1px;
  background: red;
  margin-bottom: 1px;
}

.content {
  background: silver;
  white-space: nowrap;
}

Body:
For webkit it's possible with media queries:

~function () {
  var s = "When silver div gets too wide it should jump down..."
  var i = s.length
  var div = document.querySelector(".content");

  setInterval(function () {
    div.textContent = s.slice(0, i = ++i % (s.length + 1))
  }, 100)
}()

section {
  width: 15em;
  height: 2em;
  line-height: 2em;
  border: 1px solid;
}

div {
  display: inline-block;
  vertical-align: top;
  height: 100%;
}

.narrow {
  width: 1px;
  background: red;
  margin-bottom: 1px;
}

@media (-webkit-min-device-pixel-ratio: .1 )   { .narrow { width: 10px; } }
@media (-webkit-min-device-pixel-ratio: .25)   { .narrow { width:  4px; } }
@media (-webkit-min-device-pixel-ratio: .3 )   { .narrow { width:  3px; } }
@media (-webkit-min-device-pixel-ratio: .5 )   { .narrow { width:  2px; } }
@media (-webkit-min-device-pixel-ratio: 1  )   { .narrow { width:  1px; } }

.content {
  background: silver;
  white-space: nowrap;
}

<section><div class=narrow></div><div class=content></div></section>


问:
Scrolling parent div overflow based on position of div within parent
I have 3 sections of the page:

```<code><div class="container" id="main-container">
    <div class="section" id="profile">
      Hello World
    </div>
    <div class="section" id="projects">
      Hello World 2
    </div>
    <div class="section" id="contact">
      Hello World 3
    </div>
  </div>
</code>```

I have 3 links in my navigation:

```<code><body onresize="scroll()">
  <div class="nav">
    <div class="nav-link" id="profile">
      <a>
        Profile
      </a>
    </div>
    <div class="nav-link" id="projects">
      <a>
        Projects
      </a>
    </div>
    <div class="nav-link" id="contact">
      <a>
        Contact
      </a>
    </div>
  </div>
</code>```

#main-container has overflow scroll and each of the sections takes up 100% width and height of the page.

I tried to make it so that when one of them links are clicked, it animates the scrolling effect to that section:

```<code>$(document).ready(function () {
  $('.nav-link').on('click', function () {
    if ($(window).width() < 768) {
      let section = $(".section#"+$(this).attr('id')).position();
      $('#main-container').animate({
          scrollTop: section.top
      }, 500);
    }
  });
});
</code>```

But this doesn't work, the value of position() changes based on where the user is scrolled to. How do i get the scroll position of a section of $main-container based on the #main-container? And how to do animate the scroll to it?

答:
```<code>let section = $(".section#"+$(this).attr('id')).offset();
  let scrollTop = $('#main-container').scrollTop() + section.top
  console.log(scrollTop);
  $('#main-container').animate({
      scrollTop: scrollTop
  }, 500);
</code>```

This is what i changed to get it working

Body:
I have 3 sections of the page:

      Hello World

      Hello World 2

      Hello World 3

I have 3 links in my navigation:

        Profile

        Projects

        Contact

#main-container has overflow scroll and each of the sections takes up 100% width and height of the page.

I tried to make it so that when one of them links are clicked, it animates the scrolling effect to that section:

$(document).ready(function () {
  $('.nav-link').on('click', function () {
    if ($(window).width() < 768) {
      let section = $(".section#"+$(this).attr('id')).position();
      $('#main-container').animate({
          scrollTop: section.top
      }, 500);
    }
  });
});

But this doesn't work, the value of position() changes based on where the user is scrolled to. How do i get the scroll position of a section of $main-container based on the #main-container? And how to do animate the scroll to it?

Body:
let section = $(".section#"+$(this).attr('id')).offset();
  let scrollTop = $('#main-container').scrollTop() + section.top
  console.log(scrollTop);
  $('#main-container').animate({
      scrollTop: scrollTop
  }, 500);

This is what i changed to get it working


问:
Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier
```<code>DataTable distinctTable = dTable.DefaultView.ToTable(true,"ITEM_NO","ITEM_STOCK");
DataTable dtSummerized = new DataTable("SummerizedResult");

dtSummerized.Columns.Add("ITEM_NO",typeof(string));
dtSummerized.Columns.Add("ITEM_STOCK",typeof(double));

int count=0;

foreach(DataRow dRow in distinctTable.Rows)
{
  count++;
  //string itemNo = Convert.ToString(dRow[0]);
  double TotalItem = Convert.ToDouble(dRow[1]);

  string TotalStock = dTable.Compute("sum(" + TotalItem + ")", "ITEM_NO=" + dRow["ITEM_NO"].ToString()).ToString();
  dtSummerized.Rows.Add(count,dRow["ITEM_NO"],TotalStock);
}
</code>```

Error Message: Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier.

Do anyone can help me out?

Thanks.

答:
You want to write:

```<code>dTable.Compute("sum(CONVERT(ITEM_STOCK, 'System.Double'))",
               "ITEM_NO='" + dRow["ITEM_NO"].ToString() + "'")
</code>```

instead of:

```<code>dTable.Compute("sum(" + TotalItem + ")", "ITEM_NO="...
</code>```

because it will translate to dTable.Compute("sum(value_of_TotalItem), "ITEM_NO="..., value_of_TotalItem is a double and is not a column name.

See DataTable.Compute

UPDATE:

try this:

```<code>DataTable distinctTable = dTable.Clone();
dTable.Columns.Add("ITEM_STOCK_D", typeof(Decimal),
                   "CONVERT(ITEM_STOCK, 'System.Decimal')");
foreach (DataRow dRow in dTable.Rows)
{
    String itemNo = dRow["ITEM_NO"].ToString();
    if(distinctTable.Select(String.Format("ITEM_NO = '{0}'",itemNo)).Length == 0)
    {
        double totalStock = Convert.ToDouble(dTable.Compute("SUM(ITEM_STOCK_D)",
                                     String.Format("ITEM_NO = '{0}'", itemNo)));
        distinctTable.Rows.Add(itemNo, totalStock.ToString());
    }
}
dTable.Columns.Remove("ITEM_STOCK_D");
</code>```

Body:
DataTable distinctTable = dTable.DefaultView.ToTable(true,"ITEM_NO","ITEM_STOCK");
DataTable dtSummerized = new DataTable("SummerizedResult");

dtSummerized.Columns.Add("ITEM_NO",typeof(string));
dtSummerized.Columns.Add("ITEM_STOCK",typeof(double));

int count=0;

foreach(DataRow dRow in distinctTable.Rows)
{
  count++;
  //string itemNo = Convert.ToString(dRow[0]);
  double TotalItem = Convert.ToDouble(dRow[1]);

  string TotalStock = dTable.Compute("sum(" + TotalItem + ")", "ITEM_NO=" + dRow["ITEM_NO"].ToString()).ToString();
  dtSummerized.Rows.Add(count,dRow["ITEM_NO"],TotalStock);
}

Error Message: Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier.

Do anyone can help me out?

Thanks.

Body:
You want to write:

dTable.Compute("sum(CONVERT(ITEM_STOCK, 'System.Double'))",
               "ITEM_NO='" + dRow["ITEM_NO"].ToString() + "'")

instead of:

dTable.Compute("sum(" + TotalItem + ")", "ITEM_NO="...

because it will translate to dTable.Compute("sum(value_of_TotalItem), "ITEM_NO="..., value_of_TotalItem is a double and is not a column name.

See DataTable.Compute

UPDATE:

try this:

DataTable distinctTable = dTable.Clone();
dTable.Columns.Add("ITEM_STOCK_D", typeof(Decimal),
                   "CONVERT(ITEM_STOCK, 'System.Decimal')");
foreach (DataRow dRow in dTable.Rows)
{
    String itemNo = dRow["ITEM_NO"].ToString();
    if(distinctTable.Select(String.Format("ITEM_NO = '{0}'",itemNo)).Length == 0)
    {
        double totalStock = Convert.ToDouble(dTable.Compute("SUM(ITEM_STOCK_D)",
                                     String.Format("ITEM_NO = '{0}'", itemNo)));
        distinctTable.Rows.Add(itemNo, totalStock.ToString());
    }
}
dTable.Columns.Remove("ITEM_STOCK_D");


问:
How to access to a cell into a dataframe
Issue trying to get a value from a DataFrame

I'm using pyspark in Databricks, I'm trying to get the amount of rows as a value to do some calculation

What I did:

```<code>f=sqlContext.sql('SELECT COUNT(*) AS COUNTF FROM SOOMLA')
#It´s a dataframe
</code>```

Now I want to get this number into the DataFrame as a value to make calculation, I tried already:

```<code>f['COUNTF'].iloc[0]
</code>```

but I got:

```<code>Out[158]: Column<b'COUNTF[iloc][0]'>
</code>```

How can I get this 439016392 as a value?

答:
You can run collect() and extract the first item into a variables. Here is example:

```<code>f = sqlContext.sql('SELECT COUNT(*) AS COUNTF FROM SOOMLA').collect()[0][0]

print(f)
#3

type(f)
#int
</code>```

collect() returns list of Rows.  So collect()[0] will return first row from list and collect()[0][0] will return first element of first row from list.

Here we are running COUNT(*) and it will return one record/row. So in this case collect() is returning one list with one row only and we need to extract first element from first row so collect()[0][0] will work.

I hope this explanation helps!

Body:
Issue trying to get a value from a DataFrame

I'm using pyspark in Databricks, I'm trying to get the amount of rows as a value to do some calculation

What I did:

f=sqlContext.sql('SELECT COUNT(*) AS COUNTF FROM SOOMLA')
#It´s a dataframe

Now I want to get this number into the DataFrame as a value to make calculation, I tried already:

f['COUNTF'].iloc[0]

but I got:

Out[158]: Column

How can I get this 439016392 as a value?

Body:
You can run collect() and extract the first item into a variables. Here is example:

f = sqlContext.sql('SELECT COUNT(*) AS COUNTF FROM SOOMLA').collect()[0][0]

print(f)
#3

type(f)
#int

collect() returns list of Rows.  So collect()[0] will return first row from list and collect()[0][0] will return first element of first row from list.

Here we are running COUNT(*) and it will return one record/row. So in this case collect() is returning one list with one row only and we need to extract first element from first row so collect()[0][0] will work.

I hope this explanation helps!


问:
Simple Query to Grab Max Value for each ID
OK I have a table like this:

```<code>ID     Signal    Station    OwnerID
111     -120      Home       1
111     -130      Car        1
111     -135      Work       2
222     -98       Home       2
222     -95       Work       1
222     -103      Work       2
</code>```

This is all for the same day. I just need the Query to return the max signal for each ID:

```<code>ID    Signal    Station    OwnerID
111   -120      Home        1
222   -95       Work        1
</code>```

I tried using MAX() and the aggregation messes up with the Station and OwnerID being different for each record. Do I need to do a JOIN?

答:
select
 id,
 max_signal,
 owner,
 ownerId
FROM (
  select * , rank() over(partition by id order by signal desc) as max_signal from table
)
where max_signal = 1;</p>

Body:
OK I have a table like this:

ID     Signal    Station    OwnerID
111     -120      Home       1
111     -130      Car        1
111     -135      Work       2
222     -98       Home       2
222     -95       Work       1
222     -103      Work       2

This is all for the same day. I just need the Query to return the max signal for each ID:

ID    Signal    Station    OwnerID
111   -120      Home        1
222   -95       Work        1

I tried using MAX() and the aggregation messes up with the Station and OwnerID being different for each record. Do I need to do a JOIN?


问:
How to wait on a error/close event for a socket with asyncio?
I am using a networking library who provides a wrapper for using its coroutine functions with asyncio. When I wrote a test that randomly closes the connection (to see if my program is resilient under bad conditions), I found that it hangs indefinitely.

It seemed like a bug in the wrapper provided by the library I was using, because the program hangs waiting on the callback from either loop.add_reader() or loop.add_writer(), but then I could not find how to be notified when the socket is closed.

This is a minimal program that shows what is happening with my program:

```<code>import asyncio
import socket

async def kill_later(c):
    await asyncio.sleep(0.1)
    c.close()

async def main():
    loop = asyncio.get_running_loop()

    c = socket.create_connection(('www.google.com', 80))
    c.setblocking(0)

    ev = asyncio.Event()
    loop.add_reader(c, ev.set)

    # Closes the socket after 0.1 ms:
    asyncio.create_task(kill_later(c))

    print("waiting...")

    #### ↓ THIS WAITS FOREVER ↓ ####
    await ev.wait()

asyncio.run(main())
</code>```

My question: how to be notified a socket is closed by the asyncio loop?

EDIT: due to popular demand, made the socket non-blocking, but it makes no difference, because add_reader() doesn't try to perform any IO on the socket, merely watches for when it is ready.

答:
Your test program is flawed. A call to c.close() doesn't emulate the socket being closed by the other end, it closes your own file descriptor and makes it inaccessible. You can think of close(fd) as breaking the link between the number fd and the underlying OS resource. After that reading and polling fd becomes meaningless because the number no longer refers to anything. As a result, epoll() can't and won't report a closed file descriptor as "readable".

The way to test the condition you want to test is by having the other end close the connection. The easiest way to do that is by spawning another process or thread as a mock server. For example:

```<code>import asyncio, threading, socket, time

def start_mock_server():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('localhost', 10000))
    s.listen(1)
    def serve():
        conn, addr = s.accept()
        time.sleep(1)
        conn.close()
        s.close()
    threading.Thread(target=serve).start()

async def main():
    loop = asyncio.get_running_loop()
    start_mock_server()

    c = socket.create_connection(('localhost', 10000))
    c.setblocking(0)

    ev = asyncio.Event()
    loop.add_reader(c.fileno(), ev.set)

    print("waiting...")
    await ev.wait()
    print("done")

asyncio.run(main())
</code>```

Body:
I am using a networking library who provides a wrapper for using its coroutine functions with asyncio. When I wrote a test that randomly closes the connection (to see if my program is resilient under bad conditions), I found that it hangs indefinitely.

It seemed like a bug in the wrapper provided by the library I was using, because the program hangs waiting on the callback from either loop.add_reader() or loop.add_writer(), but then I could not find how to be notified when the socket is closed.

This is a minimal program that shows what is happening with my program:

import asyncio
import socket

async def kill_later(c):
    await asyncio.sleep(0.1)
    c.close()

async def main():
    loop = asyncio.get_running_loop()

    c = socket.create_connection(('www.google.com', 80))
    c.setblocking(0)

    ev = asyncio.Event()
    loop.add_reader(c, ev.set)

    # Closes the socket after 0.1 ms:
    asyncio.create_task(kill_later(c))

    print("waiting...")

    #### ↓ THIS WAITS FOREVER ↓ ####
    await ev.wait()

asyncio.run(main())

My question: how to be notified a socket is closed by the asyncio loop?

EDIT: due to popular demand, made the socket non-blocking, but it makes no difference, because add_reader() doesn't try to perform any IO on the socket, merely watches for when it is ready.

Body:
Your test program is flawed. A call to c.close() doesn't emulate the socket being closed by the other end, it closes your own file descriptor and makes it inaccessible. You can think of close(fd) as breaking the link between the number fd and the underlying OS resource. After that reading and polling fd becomes meaningless because the number no longer refers to anything. As a result, epoll() can't and won't report a closed file descriptor as "readable".

The way to test the condition you want to test is by having the other end close the connection. The easiest way to do that is by spawning another process or thread as a mock server. For example:

import asyncio, threading, socket, time

def start_mock_server():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('localhost', 10000))
    s.listen(1)
    def serve():
        conn, addr = s.accept()
        time.sleep(1)
        conn.close()
        s.close()
    threading.Thread(target=serve).start()

async def main():
    loop = asyncio.get_running_loop()
    start_mock_server()

    c = socket.create_connection(('localhost', 10000))
    c.setblocking(0)

    ev = asyncio.Event()
    loop.add_reader(c.fileno(), ev.set)

    print("waiting...")
    await ev.wait()
    print("done")

asyncio.run(main())


问:
How to avoid multiple button click at same time in android?
I'm using two button in view. While clicking two button simultaneously it will goes to different activity at a time. How to avoid this?

I have tried like this, But its not working please save....

```<code>public class MenuPricipalScreen extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.menu_principal_layout);

    findViewById(R.id.imageView2).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            disable(findViewById(R.id.imageView3));

            Intent intent = new Intent(MenuPricipalScreen.this,
                    SelectYourLanguageVideo.class);
            startActivity(intent);
        }
    });
    findViewById(R.id.imageView3).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            disable(findViewById(R.id.imageView2));

            Intent intent = new Intent(MenuPricipalScreen.this,
                    CategoryScreen.class);
            intent.putExtra("request", "false");
            startActivity(intent);
        }
    });

}

 @Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    ((ImageView) findViewById(R.id.imageView3)).setEnabled(true);
    ((ImageView) findViewById(R.id.imageView2)).setEnabled(true);
    ((ImageView) findViewById(R.id.imageView3)).setClickable(true);
    ((ImageView) findViewById(R.id.imageView2)).setClickable(true);
    ((ImageView) findViewById(R.id.imageView3)).setFocusable(true);
    ((ImageView) findViewById(R.id.imageView2)).setFocusable(true);
}

 private void disable(View v) {
    Log.d("TAG", "TAG" + v.getId());
    v.setEnabled(false);
    v.setClickable(false);
    v.setFocusable(false);
}
}
</code>```

Thanks,

答:
The simple way to do it in Kotlin is to use:</p>

```<code>//When you need to disable the button
  btn.isEnabled = false

//When you need to enable the button again
  btn.isEnabled = true
</code>```

Body:
I'm using two button in view. While clicking two button simultaneously it will goes to different activity at a time. How to avoid this?

I have tried like this, But its not working please save....

public class MenuPricipalScreen extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.menu_principal_layout);

    findViewById(R.id.imageView2).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            disable(findViewById(R.id.imageView3));

            Intent intent = new Intent(MenuPricipalScreen.this,
                    SelectYourLanguageVideo.class);
            startActivity(intent);
        }
    });
    findViewById(R.id.imageView3).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            disable(findViewById(R.id.imageView2));

            Intent intent = new Intent(MenuPricipalScreen.this,
                    CategoryScreen.class);
            intent.putExtra("request", "false");
            startActivity(intent);
        }
    });

}

 @Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    ((ImageView) findViewById(R.id.imageView3)).setEnabled(true);
    ((ImageView) findViewById(R.id.imageView2)).setEnabled(true);
    ((ImageView) findViewById(R.id.imageView3)).setClickable(true);
    ((ImageView) findViewById(R.id.imageView2)).setClickable(true);
    ((ImageView) findViewById(R.id.imageView3)).setFocusable(true);
    ((ImageView) findViewById(R.id.imageView2)).setFocusable(true);
}

 private void disable(View v) {
    Log.d("TAG", "TAG" + v.getId());
    v.setEnabled(false);
    v.setClickable(false);
    v.setFocusable(false);
}
}

Thanks,

Body:
The simple way to do it in Kotlin is to use:

//When you need to disable the button
  btn.isEnabled = false

//When you need to enable the button again
  btn.isEnabled = true


问:
Google Cloud SDK fails to install on Windows 10
Having Python27 installed on a Windows 10 I'm failing to install Google's Cloud SDK.

Its install fails with:

```<code>ImportError: cannot import name _remove_dead_weakref
Failed to install.
</code>```

On its way to this failure it suggests:

```<code>Please verify that the following is the path to a working Python 2.7 executable:
C:\Users\c\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\bundledpython\python.exe
If it is not, please set the CLOUDSDK_PYTHON environment variable to point to a working Python 2.7 executable.
</code>```

A working Python 2.7 is indeed in the desired place. Setting CLOUDSDK_PYTHON doesn't fix its problem

答: I removed the environment variable PYTHONHOME and the Google Cloud SDK installed successfully.

Body:
Having Python27 installed on a Windows 10 I'm failing to install Google's Cloud SDK.

Its install fails with:

ImportError: cannot import name _remove_dead_weakref
Failed to install.

On its way to this failure it suggests:

Please verify that the following is the path to a working Python 2.7 executable:
C:\Users\c\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\bundledpython\python.exe
If it is not, please set the CLOUDSDK_PYTHON environment variable to point to a working Python 2.7 executable.

A working Python 2.7 is indeed in the desired place. Setting CLOUDSDK_PYTHON doesn't fix its problem


问:
Why the compiler is reading first the internal term and then going out?
lets assume I've done return something1(something2(something3)); then the PC is first doing the internal term and then going to the next term which is something2 and then going to the next term which is something1, my question why he's going in that way and not going opposite, like this : doing first something1, then something2 , then something3?</p>

答:
Actually it does. It wants to evaluate (execute) something1. This has one parameter that it wants to pass. But that parameter is a function call, so it first has to call that function in order to get a result. So it calls something2. But this function has 1 parameter that it must pass, so it evaluates the parameter something3.

Now everything is fine: it can call something2 with the evaluated parameter and then has this function's return value that it passes to something1.

So it does your "first something1, then something2, then something3". Except that it can't do the first without first doing the second, without first doing the third. QED.


问:
Convert date format from dd/mm/yyyy to yyyy-mm-dd using xsl
First time I am using XSLT.
I need to convert date from dd/mm/yyyy  to yyyy-mm-dd .
Below are my codes.

```<code><xsl:element name="transactionDate">
                                <xsl:value-of select="concat(substring(col26,5,5), '-', substring(col26,3,1), '-', substring(col26,1,1))"/>
            </xsl:element>
</code>```

In above code I am able to convert the date from dd/mm/yyyy  to yyyy-mm-dd  but when the date came as double digit then its not working.

Can somebody please suggest.

Thank in advanced.

答:
If col26 contains a date in dd/mm/yyyy format, then your expression should be:

```<code><xsl:value-of select="concat(substring(col26, 7, 4), '-', substring(col26, 4, 2), '-', substring(col26, 1, 2))"/>
</code>```

Not sure what you mean by "when the date came as double digit". The above assumes that the days and months in the input are zero-padded to 2 digits each. Otherwise the format is not dd/mm/yyyy.

Added:

if the date is coming as 2/4/2019 then its (my code )working fine

If the date can be 2/4/2019 then your format is d/m/y, not dd/mm/yyyy. To convert it to yyyy-mm-dd, try:

```<code><transactionDate>
    <xsl:variable name="d" select="substring-before(col26, '/')" />
    <xsl:variable name="m" select="substring-before(substring-after(col26, '/'), '/')" />
    <xsl:variable name="y" select="substring-after(substring-after(col26, '/'), '/')" />

    <xsl:value-of select="format-number($y, '0000')" />
    <xsl:value-of select="format-number($m, '-00')" />
    <xsl:value-of select="format-number($d, '-00')" />
</transactionDate>
</code>```

Added #2:

sorry to inform you that in date field the value is "20/12/2019 9:24:00 AM" ,time is also coming in csv

It is indeed regrettable that you did not reveal this information sooner.

If your input format is d/m/y h:mm:ss xm, then use:

```<code><transactionDate>
    <xsl:variable name="date" select="substring-before(col26, ' ')" />

    <xsl:variable name="d" select="substring-before($date, '/')" />
    <xsl:variable name="m" select="substring-before(substring-after($date, '/'), '/')" />
    <xsl:variable name="y" select="substring-after(substring-after($date, '/'), '/')" />

    <xsl:value-of select="format-number($y, '0000')" />
    <xsl:value-of select="format-number($m, '-00')" />
    <xsl:value-of select="format-number($d, '-00')" />
</transactionDate>
</code>```

Demo: https://xsltfiddle.liberty-development.net/pPzifpU

Body:
First time I am using XSLT.
I need to convert date from dd/mm/yyyy  to yyyy-mm-dd .
Below are my codes.

<xsl:element name="transactionDate">
                                <xsl:value-of select="concat(substring(col26,5,5), '-', substring(col26,3,1), '-', substring(col26,1,1))"/>
            </xsl:element>

In above code I am able to convert the date from dd/mm/yyyy  to yyyy-mm-dd  but when the date came as double digit then its not working.

Can somebody please suggest.

Thank in advanced.

Body:
If col26 contains a date in dd/mm/yyyy format, then your expression should be:

<xsl:value-of select="concat(substring(col26, 7, 4), '-', substring(col26, 4, 2), '-', substring(col26, 1, 2))"/>

Not sure what you mean by "when the date came as double digit". The above assumes that the days and months in the input are zero-padded to 2 digits each. Otherwise the format is not dd/mm/yyyy.

Added:

if the date is coming as 2/4/2019 then its (my code )working fine

If the date can be 2/4/2019 then your format is d/m/y, not dd/mm/yyyy. To convert it to yyyy-mm-dd, try:

<transactionDate>
    <xsl:variable name="d" select="substring-before(col26, '/')" />
    <xsl:variable name="m" select="substring-before(substring-after(col26, '/'), '/')" />
    <xsl:variable name="y" select="substring-after(substring-after(col26, '/'), '/')" />

    <xsl:value-of select="format-number($y, '0000')" />
    <xsl:value-of select="format-number($m, '-00')" />
    <xsl:value-of select="format-number($d, '-00')" />
</transactionDate>

Added #2:

sorry to inform you that in date field the value is "20/12/2019 9:24:00 AM" ,time is also coming in csv

It is indeed regrettable that you did not reveal this information sooner.

If your input format is d/m/y h:mm:ss xm, then use:

<transactionDate>
    <xsl:variable name="date" select="substring-before(col26, ' ')" />

    <xsl:variable name="d" select="substring-before($date, '/')" />
    <xsl:variable name="m" select="substring-before(substring-after($date, '/'), '/')" />
    <xsl:variable name="y" select="substring-after(substring-after($date, '/'), '/')" />

    <xsl:value-of select="format-number($y, '0000')" />
    <xsl:value-of select="format-number($m, '-00')" />
    <xsl:value-of select="format-number($d, '-00')" />
</transactionDate>

Demo: https://xsltfiddle.liberty-development.net/pPzifpU


问:
Can torchtext's BucketIterator pad all batches to the same length?
I recently started using torchtext to replace my glue code and I'm running into an issue where I'd like to use an attention layer in my architecture. In order to do this, I need to know the maximum sequence length of my training data.

The problem is that torchtext.data.BucketIterator does padding on a per-batch basis:

```<code># All 4 examples in the batch will be padded to maxlen in the batch
train_iter = torchtext.data.BucketIterator(dataset=train, batch_size=4)
</code>```

Is there some way to ensure that all training examples are padded to the same length; i.e., the maxlen in training?

答: When instantiating a torchtext.data.Field, there's an optional keyword argument called fix_length which, when set, defines the length to which all samples will be padded; by default it is not set which implies flexible padding.

Body:
I recently started using torchtext to replace my glue code and I'm running into an issue where I'd like to use an attention layer in my architecture. In order to do this, I need to know the maximum sequence length of my training data.

The problem is that torchtext.data.BucketIterator does padding on a per-batch basis:

# All 4 examples in the batch will be padded to maxlen in the batch
train_iter = torchtext.data.BucketIterator(dataset=train, batch_size=4)

Is there some way to ensure that all training examples are padded to the same length; i.e., the maxlen in training?


问:
VBConsole - Transfer Result from Query to Batch Script and Run the batch file
I have a loader to load data automatically which run using script (the loader containing the script named was batchautoload.cmd).

```<code>cd C:\file\loader\
C:\file\loader\load.exe /appID=1234 /username=admin /process="load" /initialDate=T1 /finalDate=T2
</code>```

I have a query to determine in which there is no data loaded using above process due to failure or etc as below.

declare @initdate as varchar(20)
declare @lastdate as varchar(20)
declare @location as varchar(20)

set @initdate = CONVERT(date,GETDATE()-1);
set @lastdate = CONVERT(date,GETDATE());
set @location = 'xxxx%'

;with q(a, c) as
(
    select MIN(date), MAX(date)
    from Table_Loader
    where nameplace like @location
    and date >= @initdate
    and date <= @lastdate
    union all
    select DATEADD(hour,1,a), c
    from q
    where a < c
)
select *
from q
where a not in
(
    select date
    from Table_Loader
    where nameplace like @location
    and date >= @initdate
    and date <= @lastdate
)
order by a asc
OPTION (MAXRECURSION 0)
"
```

<p>Now, my question is, is it possible to somehow transfer results from query to script where the script "/initialdate=queryresulttime /finaldate=queryresulttime+1"?</p>

<p>I have some general idea on using VB console, where:</p>

<ol>
<li>my console will run query from DB</li>
<li>transfer result query to script (stuck in here)</li>
<li>will automatically run the script created from step #2.</li>
</ol>

<p>Step #1</p>

<pre class="lang-vb prettyprint-override"><code>Module Module1
    Dim sqCon As New SqlClient.SqlConnection("Server=10.10.111.11;Database=DataBaseMain1;Connection Timeout=50;Trusted_Connection=Yes;")
    Dim sqCmd As New SqlClient.SqlCommand
    Dim sdrRow As SqlClient.SqlDataReader

    Sub Main()
        sqCmd.Connection = sqCon
        sqCmd.CommandText =
            "
            declare @initdate as varchar(20)
            declare @lastdate as varchar(20)
            declare @location as varchar(20)

            set @initdate = CONVERT(date,GETDATE()-1);
            set @lastdate = CONVERT(date,GETDATE());
            set @location = 'xxxx%'

            ;with q(a, c) as
            (
            select MIN(date), MAX(date)
            from Table_Loader
            where nameplace like @location
            and date >= @initdate
            and date <= @lastdate
            union all
            select DATEADD(hour,1,a), c
            from q
            where a < c
            )
            select *
            from q
            where a not in
            (
                select date
                from Table_Loader
                where nameplace like @location
                and date >= @initdate
                and date <= @lastdate
            )
            order by a asc
            OPTION (MAXRECURSION 0)
            "
        sqCon.Open()
        sqCmd.ExecuteNonQuery()
        sdrRow = sqCmd.ExecuteReader()

        For Each itm In sdrRow
            Dim column0 As String = sdrRow.GetValue(0)
            MsgBox(column0)
        Next

        sdrRow.Close()
        sqCon.Close()
    End Sub

End Module
</code>```

Now I can generate the process #1 but not #2 and #3. Since the data will be used in script, I am thinking of creating temporary file of batch (appear when only this console running, deleted after the console finished process). Since I don't want to create many file from the console.

I am new in VB console thus limit my idea to get this solved. I heard about "pipe" but I do not know on how to do that. I am still thinking on continuing For Each loop or For loop, but am stuck on this. Please advise me. Just to inform, I am planning to implement this console to run on daily-basis.

答:
Can you adapt the export/import process like this:

Application A exports data more or less reliably every hour and writes it into a folder resp. file share somewhere on your network, lets say \\srvApplicationA\ExportForApplicationB.

Optimally application A writes it to a file with the date and time in it and a temporary extension that is renamed when finished, e.g. Export20190530_132255.part during the write operation and Export20190530_132255.xml (or whatever final extension is needed) when finished.

Application B loops every 5 minutes through all the export files in \\srvApplicationA\ExportForApplicationB that have the final extension (usually none but if the service was down for some time there could be many), and for each tries to move it to folder \\srvApplicationA\ExportForApplicationB\InProgress and if successful, tries to import it (otherwise the error is silently ignored, the import application might have been started more than once and therefore a race condition occurred. Simply pick the next file in the loop).

If the import succeeds, the file is move from \\srvApplicationA\ExportForApplicationB\InProgress to folder \\srvApplicationA\ExportForApplicationB\Success, if it fails to folder \\srvApplicationA\ExportForApplicationB\Error.

In VB.NET you make an application, say ImportFromAtoB.exe, that does all the logic mentionned above and that can be started in a silent mode without user interaction.

In VB.NET you make also a simple self-installing/deinstalling windows service, say ImportFromAtoBService.exe containing no logic but calling ImportFromAtoB.exe every 5 minutes (it needs to be a service as windows scheduled tasks are not reliable).

Install the service as autostart on one of the servers or another machine that is always running and from now on the import is reliably done forever.

This dedicated service/application setup has the advantage that you can easily debug the import logic interactivly in Visual Studio, and what I also find quite refreshing during development periods is, that one can simply copy the new import binaries over the old ones without stopping the service (that saves interactive logging on to the server through a terminal server session, stopping the service, uninstalling it, copying the files, reinstalling it, starting the service and logging off - sometimes even a reboot is needed after too many deinstalls and reinstalls of the same (modified) service).

The only manual tasks now is to check the folder \\srvApplicationA\ExportForApplicationB\Error from time to time and analyze, why a certain file could not be imported (and to delete/archive the old import files in \\srvApplicationA\ExportForApplicationB\Success once in a while).

Body:
I have a loader to load data automatically which run using script (the loader containing the script named was batchautoload.cmd).

cd C:\file\loader\
C:\file\loader\load.exe /appID=1234 /username=admin /process="load" /initialDate=T1 /finalDate=T2

I have a query to determine in which there is no data loaded using above process due to failure or etc as below.

declare @initdate as varchar(20)
declare @lastdate as varchar(20)
declare @location as varchar(20)

set @initdate = CONVERT(date,GETDATE()-1);
set @lastdate = CONVERT(date,GETDATE());
set @location = 'xxxx%'

;with q(a, c) as
(
    select MIN(date), MAX(date)
    from Table_Loader
    where nameplace like @location
    and date >= @initdate
    and date <= @lastdate
    union all
    select DATEADD(hour,1,a), c
    from q
    where a < c
)
select *
from q
where a not in
(
    select date
    from Table_Loader
    where nameplace like @location
    and date >= @initdate
    and date <= @lastdate
)
order by a asc
OPTION (MAXRECURSION 0)
"

Now, my question is, is it possible to somehow transfer results from query to script where the script "/initialdate=queryresulttime /finaldate=queryresulttime+1"?

I have some general idea on using VB console, where:

my console will run query from DB

transfer result query to script (stuck in here)

will automatically run the script created from step #2.

Step #1

Module Module1
    Dim sqCon As New SqlClient.SqlConnection("Server=10.10.111.11;Database=DataBaseMain1;Connection Timeout=50;Trusted_Connection=Yes;")
    Dim sqCmd As New SqlClient.SqlCommand
    Dim sdrRow As SqlClient.SqlDataReader

    Sub Main()
        sqCmd.Connection = sqCon
        sqCmd.CommandText =
            "
            declare @initdate as varchar(20)
            declare @lastdate as varchar(20)
            declare @location as varchar(20)

            set @initdate = CONVERT(date,GETDATE()-1);
            set @lastdate = CONVERT(date,GETDATE());
            set @location = 'xxxx%'

            ;with q(a, c) as
            (
            select MIN(date), MAX(date)
            from Table_Loader
            where nameplace like @location
            and date >= @initdate
            and date <= @lastdate
            union all
            select DATEADD(hour,1,a), c
            from q
            where a < c
            )
            select *
            from q
            where a not in
            (
                select date
                from Table_Loader
                where nameplace like @location
                and date >= @initdate
                and date <= @lastdate
            )
            order by a asc
            OPTION (MAXRECURSION 0)
            "
        sqCon.Open()
        sqCmd.ExecuteNonQuery()
        sdrRow = sqCmd.ExecuteReader()

        For Each itm In sdrRow
            Dim column0 As String = sdrRow.GetValue(0)
            MsgBox(column0)
        Next

        sdrRow.Close()
        sqCon.Close()
    End Sub

End Module

Now I can generate the process #1 but not #2 and #3. Since the data will be used in script, I am thinking of creating temporary file of batch (appear when only this console running, deleted after the console finished process). Since I don't want to create many file from the console.

I am new in VB console thus limit my idea to get this solved. I heard about "pipe" but I do not know on how to do that. I am still thinking on continuing For Each loop or For loop, but am stuck on this. Please advise me. Just to inform, I am planning to implement this console to run on daily-basis.


问:
how to implement sub select with where condition in sequelize
I have these tables:

products

stores

produuctProperties

with this structure

[
  "products" :
    {
        "id": 1,
        "orginalName": "146153-0100 ",
        "title": null,
        "stores": [
            {
                "id": 1,
                "stock": 100,
                "minOQ": 1,
                "maxOQ": 0
            },
            {
                "id": 2,
                "stock": 100,
                "minOQ": 1,
                "maxOQ": 0,

            }
        ],
        "productproperties": [
            {
                "id": 1,
                "productId": 1,
                "propertyId": 8,
                "propertyOptionId": 5
            },
            {
                "id": 2,
                "productId": 1,
                "propertyId": 9,
                "propertyOptionId": 11
            },
            {
                "id": 3,
                "productId": 1,
                "propertyId": 10,
                "propertyOptionId": 9
            }
        ]
    }
]```
</div>
</div>
</p>

<p>I want filter my products by selected options , Suppose the selected options are 11 and 9</p>

<p>how to implement below sql query in Sequelize 5.6 with findAll , where and... : </p>

```select * from products as p
inner join stores as sr on sr.productId = p.id
where (select count(*) from productProperties where propertyOptionId in (11,9) and productId = p.id) >= 2
```

答:
I've found that using query builder in sequelize is really confusing,
so if you're good with raw sql you could just run them on as below

if Student is you're model
then
const students = Student.query('Select *  from students');

Body:
I have these tables:

products

stores

produuctProperties

with this structure

[
  "products" :
    {
        "id": 1,
        "orginalName": "146153-0100 ",
        "title": null,
        "stores": [
            {
                "id": 1,
                "stock": 100,
                "minOQ": 1,
                "maxOQ": 0
            },
            {
                "id": 2,
                "stock": 100,
                "minOQ": 1,
                "maxOQ": 0,

            }
        ],
        "productproperties": [
            {
                "id": 1,
                "productId": 1,
                "propertyId": 8,
                "propertyOptionId": 5
            },
            {
                "id": 2,
                "productId": 1,
                "propertyId": 9,
                "propertyOptionId": 11
            },
            {
                "id": 3,
                "productId": 1,
                "propertyId": 10,
                "propertyOptionId": 9
            }
        ]
    }
]

I want filter my products by selected options , Suppose the selected options are 11 and 9

how to implement below sql query in Sequelize 5.6 with findAll , where and... :

select * from products as p
inner join stores as sr on sr.productId = p.id
where (select count(*) from productProperties where propertyOptionId in (11,9) and productId = p.id) >= 2


问:
How to convert date format "dd/mm/yy" to "yy/mm/dd" for mysql database inserting?
When I insert a date from a file that has it formatted "dd/mm/yy" into my database table with the date formatted "yy/mm/dd" the date is wrong:

Instead of getting 2019:04:11 I get 2011:04:19.

I want to keep the database format ("yy/mm/dd")

I have tried:

actualdate = DATE_FORMAT(j[0], '%y-%m-%d')

cursor.execute(actualdate)

but it tells me error: name 'DATE_FORMAT' is not defined

```<code>import mysql.connector
sql = mysql.connector.connect(host='',user='',password='',db='')

cursor = sql.cursor()
f = open("C:\Cumulus\data\Apr19log.txt","r")

st=[i.strip().split(',') for i in f.readlines()]

actualdate = DATE_FORMAT(j[0], '%y-%m-%d')
cursor.execute(actualdate)

sqllist = "INSERT INTO station_fenelon (variable, date, time,
outside_temp, outside_humidity) VALUES (%s, %s, %s, %s, %s)"
record = [(i+1, j[0], j[1], j[2], j[3]) for i, j in enumerate(st)]
cursor.executemany(sqllist, record)
sql.commit()
</code>```

error: name 'DATE_FORMAT' is not defined

答:
DATE_FORMAT() is a MySQL function and you call it directly in your python script so you get an error message that is not defined.You should remove this line.

You could use STR_TO_DATE to convert your string to a date

```<code>sqllist = "INSERT INTO station_fenelon (variable, date, time,
outside_temp, outside_humidity) VALUES (%s, STR_TO_DATE(%s,'%d/%m/%Y'), %s, %s, %s)"
</code>```

Body:
When I insert a date from a file that has it formatted "dd/mm/yy" into my database table with the date formatted "yy/mm/dd" the date is wrong:

Instead of getting 2019:04:11 I get 2011:04:19.

I want to keep the database format ("yy/mm/dd")

I have tried:

actualdate = DATE_FORMAT(j[0], '%y-%m-%d')

cursor.execute(actualdate)

but it tells me error: name 'DATE_FORMAT' is not defined

import mysql.connector
sql = mysql.connector.connect(host='',user='',password='',db='')

cursor = sql.cursor()
f = open("C:\Cumulus\data\Apr19log.txt","r")

st=[i.strip().split(',') for i in f.readlines()]

actualdate = DATE_FORMAT(j[0], '%y-%m-%d')
cursor.execute(actualdate)

sqllist = "INSERT INTO station_fenelon (variable, date, time,
outside_temp, outside_humidity) VALUES (%s, %s, %s, %s, %s)"
record = [(i+1, j[0], j[1], j[2], j[3]) for i, j in enumerate(st)]
cursor.executemany(sqllist, record)
sql.commit()

error: name 'DATE_FORMAT' is not defined

Body:
DATE_FORMAT() is a MySQL function and you call it directly in your python script so you get an error message that is not defined.You should remove this line.

You could use STR_TO_DATE to convert your string to a date

sqllist = "INSERT INTO station_fenelon (variable, date, time,
outside_temp, outside_humidity) VALUES (%s, STR_TO_DATE(%s,'%d/%m/%Y'), %s, %s, %s)"


问:
Killing child process in node.js/electron
I am opening a child process in node.js to start an RTSP stream using VLC. I then want to kill the process once a command has been sent from the electron application.

Here is the code I  have written. Is there anything I am doing wrong because the child process doesn't get killed even though the code is run through. I have checked that cam is not undefined, it actually enters that code block.

```<code>const { dialog, ipcMain, BrowserWindow} = require('electron');
const {url} = require('url');
var net = require('net');
var spawn = require('child_process').exec;
var cam;

class streamHandler {
    constructor(){
        this.sendAndReceiveMessageListener();
    }

    sendAndReceiveMessageListener(){
        ipcMain.on('http-request', (event)=>{
            let message = "Starting the video stream";
            cam = spawn('"C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe" --qt-start-minimized  rtsp://192.168.0.75/live --sout "#transcode{acodec=vorb, vcodec=theo}:standard{access=http, mux=ogg, dst=localhost:8090/}"', function(error, stdout, stderr){});
            event.sender.send('http-response', (message));
        });

        ipcMain.on('http-end-stream-request', (event)=>{
            let message = "Video stream ended.";
            if (typeof cam !== 'undefined' && cam !== null){
                cam.kill('');
            }

            event.sender.send('http-end-stream-response', (message));

        });
    }

    spawnVLC(){
        console.log()
    }
}

module.exports = new streamHandler();
</code>```

答:
One of the reasons this might be happening is because the child process that you spawned (RTSP stream using VLC - let's called this child process 'A'), is creating other child processes ('B', 'C' etc.) which will not be killed when you try to kill child process 'A'.

When the child thread finishes executing and deletes, the grandchild thread becomes the zombie process, and process.kill() cannot delete it.

You can use the following approach:

Spawn the child process in detached mode so that you can kill all the child processes.

```<code>    var spawn = require('child_process').spawn;
    var child = spawn('my-command', {detached: true});
    process.kill(-child.pid);
</code>```

Please note - before pid. This converts a pid to a group of pids for process kill() method.

Related links:

[How to] https://azimi.me/2014/12/31/kill-child_process-node-js.html

[Related Issue] https://github.com/nodejs/help/issues/1389

[Documentation] https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal

Body:
I am opening a child process in node.js to start an RTSP stream using VLC. I then want to kill the process once a command has been sent from the electron application.

Here is the code I  have written. Is there anything I am doing wrong because the child process doesn't get killed even though the code is run through. I have checked that cam is not undefined, it actually enters that code block.

const { dialog, ipcMain, BrowserWindow} = require('electron');
const {url} = require('url');
var net = require('net');
var spawn = require('child_process').exec;
var cam;

class streamHandler {
    constructor(){
        this.sendAndReceiveMessageListener();
    }

    sendAndReceiveMessageListener(){
        ipcMain.on('http-request', (event)=>{
            let message = "Starting the video stream";
            cam = spawn('"C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe" --qt-start-minimized  rtsp://192.168.0.75/live --sout "#transcode{acodec=vorb, vcodec=theo}:standard{access=http, mux=ogg, dst=localhost:8090/}"', function(error, stdout, stderr){});
            event.sender.send('http-response', (message));
        });

        ipcMain.on('http-end-stream-request', (event)=>{
            let message = "Video stream ended.";
            if (typeof cam !== 'undefined' && cam !== null){
                cam.kill('');
            }

            event.sender.send('http-end-stream-response', (message));

        });
    }

    spawnVLC(){
        console.log()
    }
}

module.exports = new streamHandler();

Body:
One of the reasons this might be happening is because the child process that you spawned (RTSP stream using VLC - let's called this child process 'A'), is creating other child processes ('B', 'C' etc.) which will not be killed when you try to kill child process 'A'.

When the child thread finishes executing and deletes, the grandchild thread becomes the zombie process, and process.kill() cannot delete it.

You can use the following approach:

Spawn the child process in detached mode so that you can kill all the child processes.

    var spawn = require('child_process').spawn;
    var child = spawn('my-command', {detached: true});
    process.kill(-child.pid);

Please note - before pid. This converts a pid to a group of pids for process kill() method.

Related links:

[How to] https://azimi.me/2014/12/31/kill-child_process-node-js.html

[Related Issue] https://github.com/nodejs/help/issues/1389

[Documentation] https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal


问:
xml error code file
we are thinking use xml file to store our error codes for our C# application. for the following two structures, which one is better?

```<code><error>
<code>0x00000001</code>
<description>Error PIB: Clamp</description>
<reaction>Display</reaction>
</error>
</code>```

or

```<code><error code=0x00000001 >
<description>Error PIB: Clamp</description>
<reaction>Display</reaction>
</error>
</code>```

or your better suggestion?

seems the second one save some space and easiler for lookup through it?

I need to get the description and reaction string by lookup the error code. do you have an effective way to lookup through file?

答:
If you were after space-saving techniques, I would suggest not using XML in the first place :)

Personally I prefer the second approach over the first, but both will work. If this is really just for lookup, I'd suggest that when you load the file, you convert it to a Dictionary<String, ErrorInformation> or something similar. (You could make the key value a numeric type instead, but that would require parsing the value of course.)

LINQ to XML makes it really easy to do this sort of conversion:

```<code>XDocument xml = XDocument.Load("errorcodes.xml");
var dictionary = xml.Descendants("error")
                    .ToDictionary(element => (string) element.Attribute("code"),
                                  element => new ErrorInformation(
                                      (string) element.Element("description"),
                                      (string) element.Element("reaction")));
</code>```

Title: xml error code file

Body:
we are thinking use xml file to store our error codes for our C# application. for the following two structures, which one is better?

<error>
0x00000001
<description>Error PIB: Clamp</description>
<reaction>Display</reaction>
</error>

or

<error code=0x00000001 >
<description>Error PIB: Clamp</description>
<reaction>Display</reaction>
</error>

or your better suggestion?

seems the second one save some space and easiler for lookup through it?

I need to get the description and reaction string by lookup the error code. do you have an effective way to lookup through file?

Body:
If you were after space-saving techniques, I would suggest not using XML in the first place :)

Personally I prefer the second approach over the first, but both will work. If this is really just for lookup, I'd suggest that when you load the file, you convert it to a Dictionary<String, ErrorInformation> or something similar. (You could make the key value a numeric type instead, but that would require parsing the value of course.)

LINQ to XML makes it really easy to do this sort of conversion:

XDocument xml = XDocument.Load("errorcodes.xml");
var dictionary = xml.Descendants("error")
                    .ToDictionary(element => (string) element.Attribute("code"),
                                  element => new ErrorInformation(
                                      (string) element.Element("description"),
                                      (string) element.Element("reaction")));


问:
What can I do if I have 2 equal average?
I have a list of students and some notes, and I have to find the average of each student's grades and show them the following way(if the average is greater than or equal to 6.0):

[student name, average] (in descending order of the average).

I did this, but the problem is that I have 2 equal averages and I can not correspond with the name of the student, he takes my first student with the average '6.0' in both cases.

My lists look like this:

```<code>info = [['Frank Morgan', '7.89', '3.19', '6.90', '9.90'], ['Jesse Lawrence', '6', '6', '6', '6'], ['Mark Porter', '9.00', '7.87', '9.12', '10.00'], ['Philip Sanchez', '6', '6', '6', '6']]

average= [6.970000000000001, 6.0, 8.9975, 6.0]
</code>```

I want to create the following:

```<code>result = [['Frank Morgan', 6.970000000000001], ['Jesse Lawrence', 6.0],['Mark Porter', 8.9975], ['Philip Sanchez', 6.0]]
</code>```

I tried in the following way:

```<code>result = []
for i in average:
    if i >= 6.0:
        result.append([info[average.index(i)][0], i])
print result
</code>```

But I got:

```<code>result = [['Frank Morgan', 6.970000000000001], ['Jesse Lawrence', 6.0],['Mark Porter', 8.9975], ['Jesse Lawrence', 6.0]]
</code>```

'Jesse Lawrence' instead of 'Philip Sanchez'

Please help me to find another solution for this matching problem.

答:
With help of numpy and itertools.groupby you can do it like this:

```<code>[[k, np.mean(np.array(list(g)[0][1:], dtype='float'))] for k, g in itertools.groupby(sorted(a, key=lambda x: x[0]), lambda x: x[0])]
</code>```

And get:

```<code>[['Frank Morgan', 6.970000000000001],
 ['Jesse Lawrence', 6.0],
 ['Mark Porter', 8.9975],
 ['Philip Sanchez', 6.0]]
</code>```

Body:
I have a list of students and some notes, and I have to find the average of each student's grades and show them the following way(if the average is greater than or equal to 6.0):

[student name, average] (in descending order of the average).

I did this, but the problem is that I have 2 equal averages and I can not correspond with the name of the student, he takes my first student with the average '6.0' in both cases.

My lists look like this:

info = [['Frank Morgan', '7.89', '3.19', '6.90', '9.90'], ['Jesse Lawrence', '6', '6', '6', '6'], ['Mark Porter', '9.00', '7.87', '9.12', '10.00'], ['Philip Sanchez', '6', '6', '6', '6']]

average= [6.970000000000001, 6.0, 8.9975, 6.0]

I want to create the following:

result = [['Frank Morgan', 6.970000000000001], ['Jesse Lawrence', 6.0],['Mark Porter', 8.9975], ['Philip Sanchez', 6.0]]

I tried in the following way:

result = []
for i in average:
    if i >= 6.0:
        result.append([info[average.index(i)][0], i])
print result

But I got:

result = [['Frank Morgan', 6.970000000000001], ['Jesse Lawrence', 6.0],['Mark Porter', 8.9975], ['Jesse Lawrence', 6.0]]

'Jesse Lawrence' instead of 'Philip Sanchez'

Please help me to find another solution for this matching problem.

Body:
With help of numpy and itertools.groupby you can do it like this:

[[k, np.mean(np.array(list(g)[0][1:], dtype='float'))] for k, g in itertools.groupby(sorted(a, key=lambda x: x[0]), lambda x: x[0])]

And get:

[['Frank Morgan', 6.970000000000001],
 ['Jesse Lawrence', 6.0],
 ['Mark Porter', 8.9975],
 ['Philip Sanchez', 6.0]]


问:
Sort List in reverse in order
I have List list1 in direct order. List<String> list = Ordering.natural().sortedCopy(asu2);

How to change order. And I don't know how to rewrite methods from extends class, please write with examples or speak clearly.

答:
How I would do it is:

```<code>personsList.sort(Comparator.comparing(Person::getAge, Comparator.reverseOrder()));
</code>```

And happy coding :)

Title: Sort List in reverse in order

Body:
How I would do it is:

personsList.sort(Comparator.comparing(Person::getAge, Comparator.reverseOrder()));

And happy coding :)