问:
How can I center the loading div before load() with jQuery?
I have this code:

```<code>$("#result").html('<div class="loading">Loading results...</div>');
$("#result").load('<?php bloginfo('template_directory'); ?>/GetResults.php?' + $.cookie('nw-query'));
</code>```

It shows the loading div until the load is done. What I want to do here, I want the loading div exactly in the center of the page/document?

That's extra but could be nice - can I also fade the document until the load is done so that the loading div stands out?

Any jquery/css suggestions are welcome.

Thank you :)

答: This might be a bit over-kill but the jQuery UI dialog plugin could achieve those effects (you would just not be using it for a dialog...). Check out the modal option and example. If you are using jQuery ui already, might be worth it...</p>

Body:
I have this code:

$("#result").html('
Loading results...
');
$("#result").load('<?php bloginfo('template_directory'); ?>/GetResults.php?' + $.cookie('nw-query'));

It shows the loading div until the load is done. What I want to do here, I want the loading div exactly in the center of the page/document?

That's extra but could be nice - can I also fade the document until the load is done so that the loading div stands out?

Any jquery/css suggestions are welcome.

Thank you :)


来源: stackexchange

问:
Node readline 'line' event not firing
I am creating a this program which finds the common words of 2 word files and then creates a new file with just the common words.
I'm using the readline module to read each word of first word file and then store that word in a Trie. After that has been completed, I'm trying to read the words from the other word file and if it is in trie, I'm writing to file.

I'm using promises to make sure that the events happen in sequence but the second time the 'line' event is not triggered.

```<code>'use strict'
const readLine = require('readline');
const fs = require('fs');

const wordList = require('./Trie.js');

function createTrie(reader, trie) {
  return new Promise((resolve, reject) => {
    if(typeof reader === 'undefined' || reader === null)
      reject('Failed')

    reader.on('line', line => trie.add(line))
    reader.on('close', () => {
      console.log('done')
      resolve(trie)
    })
  })
}

function findCommon(reader, trie) {
  return new Promise((resolve, reject) => {
    if(typeof reader === 'undefined' || reader === null) {
      console.log('failed')
      reject('Failed')
    }

    let commonWords = ''

    console.log('we are here')

    reader.on('line', (line) => {
      console.log(line) // This does not output
      if(line.length > 2 && trie.search(line)) {
        let word = line + '\n'
        commonWords += word
      }
    })
    reader.on('close', () => {
      fs.writeFile('wordlist.txt', commonWords, (err) => {
        if(err) {
          console.log(err)
          reject('error')
        }
        console.log('written')
        resolve('Success')
      })
    })
  })
}

let reader_1 = readLine.createInterface({
  input: fs.createReadStream('words/enable2k.txt')
})
let reader_2 = readLine.createInterface({
  input: fs.createReadStream('words/engmix.txt')
})

createTrie(reader_1, wordList)
  .then((trie) => findCommon(reader_2, trie))
  .then((data) => console.log(data))
</code>```

The above code gives the below output

```<code>done
we are here
</code>```

The 'line' event is not triggered. It seems like I'm not using readline correctly but I'm not sure.

Any help is appreciated!

答:
You can avoid promises and callbacks altogether and just execute the logic sequentially using nsynjs. Logic will transform as follows:

```<code>var nsynjs = require('nsynjs');
var textFile = require('./wrappers/nodeReadline').textFile; // this file is part of nsynjs

function process(textFile) {

    var fh = new textFile();
    fh.open('path/to/file1');
    var s, dict={};
    while (typeof(s = fh.readLine(nsynjsCtx).data) != 'undefined')
        dict[s] = true;
    fh.close();

    fh = new textFile();
    fh.open('path/to/file2');
    while (typeof(s = fh.readLine(nsynjsCtx).data) != 'undefined')
        if(dict[s])
            console.log(s);
    fh.close();

}

var ctx = nsynjs.run(process,{},textFile,function () {
    console.log('done');
});
</code>```

Code above is based on this example:  https://github.com/amaksr/nsynjs/blob/master/examples/node-readline/index.js

ContentLicense: CC BY-SA 3.0

Title: Node readline 'line' event not firing

Body:
I am creating a this program which finds the common words of 2 word files and then creates a new file with just the common words.
I'm using the readline module to read each word of first word file and then store that word in a Trie. After that has been completed, I'm trying to read the words from the other word file and if it is in trie, I'm writing to file.

I'm using promises to make sure that the events happen in sequence but the second time the 'line' event is not triggered.

'use strict'
const readLine = require('readline');
const fs = require('fs');

const wordList = require('./Trie.js');

function createTrie(reader, trie) {
  return new Promise((resolve, reject) => {
    if(typeof reader === 'undefined' || reader === null)
      reject('Failed')

    reader.on('line', line => trie.add(line))
    reader.on('close', () => {
      console.log('done')
      resolve(trie)
    })
  })
}

function findCommon(reader, trie) {
  return new Promise((resolve, reject) => {
    if(typeof reader === 'undefined' || reader === null) {
      console.log('failed')
      reject('Failed')
    }

    let commonWords = ''

    console.log('we are here')

    reader.on('line', (line) => {
      console.log(line) // This does not output
      if(line.length > 2 && trie.search(line)) {
        let word = line + '\n'
        commonWords += word
      }
    })
    reader.on('close', () => {
      fs.writeFile('wordlist.txt', commonWords, (err) => {
        if(err) {
          console.log(err)
          reject('error')
        }
        console.log('written')
        resolve('Success')
      })
    })
  })
}

let reader_1 = readLine.createInterface({
  input: fs.createReadStream('words/enable2k.txt')
})
let reader_2 = readLine.createInterface({
  input: fs.createReadStream('words/engmix.txt')
})

createTrie(reader_1, wordList)
  .then((trie) => findCommon(reader_2, trie))
  .then((data) => console.log(data))

The above code gives the below output

done
we are here

The 'line' event is not triggered. It seems like I'm not using readline correctly but I'm not sure.

Any help is appreciated!

Body:
You can avoid promises and callbacks altogether and just execute the logic sequentially using nsynjs. Logic will transform as follows:

var nsynjs = require('nsynjs');
var textFile = require('./wrappers/nodeReadline').textFile; // this file is part of nsynjs

function process(textFile) {

    var fh = new textFile();
    fh.open('path/to/file1');
    var s, dict={};
    while (typeof(s = fh.readLine(nsynjsCtx).data) != 'undefined')
        dict[s] = true;
    fh.close();

    fh = new textFile();
    fh.open('path/to/file2');
    while (typeof(s = fh.readLine(nsynjsCtx).data) != 'undefined')
        if(dict[s])
            console.log(s);
    fh.close();

}

var ctx = nsynjs.run(process,{},textFile,function () {
    console.log('done');
});

Code above is based on this example:  https://github.com/amaksr/nsynjs/blob/master/examples/node-readline/index.js


问:
Syncing .emacs.d folder using personal git server
Requirements:

Install git and emacs on OpenBSD 6.1 server (DONE)

Put entire .emacs.d folder under git version control

Clone a "working" repo on server (so that files are visible/usable for server local emacs instance, not just the VC files)

Clone .emacs.d to all devices

Actions so far:

On Server:

pkg_add git

pkg_add emacs

mkdir ~/.emacs.d

cd ~/.emacs.d

git --bare init

On Laptop (with working .emacs.d config)

mv ~/.emacs.d .emacs.dbk

rm -rf .emacs.d

git clone test@000.000.000.000:~/.emacs.d

copied everything from .emacs.dbk to .emacs.d

git add .

git commit

git push origin master

Success

Back on Server

ls -a ~/.emacs.d

HEAD         config       hooks        objects      refs
branches     description  info         packed-refs

I'm pretty sure this is good.

Issues:

I'm not sure how to get a "working" view of my repo. I know the above is the "version control" view (server).

I tried to git clone test@000.000.000.000:~/.emacs.d on my other devices and I get SHA 1 errors

Did I miss a step on the server for folder permissions?
Anyone else see mistakes?

Thanks

答: In the bare repo at the server: git ls-tree HEAD


问:
Javascript toggle class on element
Say I have this HTML structure

```<code><div class="sType_click">
    <div class="Switcher">
      <span class="customText">Custom text</span>
    </div>
</div>

<div class="sType_click">
    <div class="Switcher">
      <span class="customText">Custom text</span>
    </div>
</div>

<div class="sType_click">
    <div class="Switcher">
      <span class="customText">Custom text</span>
    </div>
</div>
</code>```

How do I use JavaScript to toggle class on sType_click div with the customText span BUT without adding it on other sType_click divs?

For example if I click on one of the customText class I want to toggle class on its parent sType_click div and not adding on any others.

I currently use this

```<code>var sType_click = document.querySelector(".sType_click"),
customText = document.querySelector(".customText"),
if (null !== document.querySelector(".customText")) {
    customText.onclick = function() {
        sType_click.classList.toggle("sOpen");
    };
}
</code>```

But this toggles all sType_click divs on the page
I'm okay with jQuery but i prefer pure javascript,
Thanks in advance.

答:
I think you use jQuery because it requires less code as compare to javascript.

Check below snippet:

$(document).on('click', '.customText', function() {
  $(this).closest(".sType_click").toggleClass("selected");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected {
  color: red;
}</code>```

    Custom text

    Custom text

    Custom text

```

Title: Javascript toggle class on element

Body:
Say I have this HTML structure

      Custom text

      Custom text

      Custom text

How do I use JavaScript to toggle class on sType_click div with the customText span BUT without adding it on other sType_click divs?

For example if I click on one of the customText class I want to toggle class on its parent sType_click div and not adding on any others.

I currently use this

var sType_click = document.querySelector(".sType_click"),
customText = document.querySelector(".customText"),
if (null !== document.querySelector(".customText")) {
    customText.onclick = function() {
        sType_click.classList.toggle("sOpen");
    };
}

But this toggles all sType_click divs on the page
I'm okay with jQuery but i prefer pure javascript,
Thanks in advance.

Body:
I think you use jQuery because it requires less code as compare to javascript.

Check below snippet:

$(document).on('click', '.customText', function() {
  $(this).closest(".sType_click").toggleClass("selected");
});

.selected {
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sType_click">
  <div class="Switcher">
    <span class="customText">Custom text</span>
  </div>
</div>

<div class="sType_click">
  <div class="Switcher">
    <span class="customText">Custom text</span>
  </div>
</div>

<div class="sType_click">
  <div class="Switcher">
    <span class="customText">Custom text</span>
  </div>
</div>


问:
Users seeing inconsistent representation of unicode text across request cycle in Spring 3 MVC
While testing my app, I noticed the following issue where a string containing a unicode character, when passed to the controller and then back to the page, becomes garbled - or at least is not represented consistently - from the user's perspective.

```<code>1. Xáeso
2. Xßeso
3. X%E1eso
</code>```

Text that I pass as a RequestParam from the page to the controller.

How that is output in the log file immediately after reading it from the RequestParam in the controller

The text passed from the controller back to the client after the request handler exits.

This is the only valid representation of the text as far as what the user would expect to see:

```<code>1. Xáeso
</code>```

How can I ensure that the unicode character in position 2 of this string is represented consistently to the client-side user of the app?

答:
My guess is that part of the problem is that the web server (e.g. Tomcat) is using the wrong character set when translating the request parameters into UTF-16.

If you are using Tomcat, read the Character Encoding FAQ, and check each of the issues listed.  (Pay particular attention to the bit that talks about the effects of filters and valves ...)

ContentLicense: CC BY-SA 2.5

Body:
While testing my app, I noticed the following issue where a string containing a unicode character, when passed to the controller and then back to the page, becomes garbled - or at least is not represented consistently - from the user's perspective.

1. Xáeso
2. Xßeso
3. X%E1eso

Text that I pass as a RequestParam from the page to the controller.

How that is output in the log file immediately after reading it from the RequestParam in the controller

The text passed from the controller back to the client after the request handler exits.

This is the only valid representation of the text as far as what the user would expect to see:

1. Xáeso

How can I ensure that the unicode character in position 2 of this string is represented consistently to the client-side user of the app?


问:
MS SQL Server Trigger if else insert
I'm trying to write a trigger but I need help. How can I write this type of trigger?
If data coming null insert into this parameter?
There is my codes

```<code>CREATE TRIGGER AddDayOn ON Control
INSTEAD OF INSERT
AS
DECLARE @first DATETIME,@second DATETIME,@name NVARCHAR(11),@birth DATETIME
SELECT @first = First,
       @second = Second,
       @name = Name,
       @birth = Birth
FROM inserted
INSERT INTO Control(
Name,
First,
Birth,
Second,
Prob
)
VALUES
( @name,
@first,
@birth,
DATEADD(DAY,220,@first),
DATEADD(DAY 250,@first))
</code>```

I need to chance this trigger with if-else.Because i have 3 more parameters(Four,Five,Six). I'm try to write something like that

```<code> If @first not null DATEADD..
 If @four not null DATEADD.. like that
</code>```

答:
you can use exists in your statement like this:</p>

```<code>insert into table1(col1,col2)
select col1,col2 from inserted as i
where not exists(select 0 from table1 where relatedkey=i.relatedkey)
</code>```

Title: MS SQL Server Trigger if else insert

Body:
I'm trying to write a trigger but I need help. How can I write this type of trigger?
If data coming null insert into this parameter?
There is my codes

CREATE TRIGGER AddDayOn ON Control
INSTEAD OF INSERT
AS
DECLARE @first DATETIME,@second DATETIME,@name NVARCHAR(11),@birth DATETIME
SELECT @first = First,
       @second = Second,
       @name = Name,
       @birth = Birth
FROM inserted
INSERT INTO Control(
Name,
First,
Birth,
Second,
Prob
)
VALUES
( @name,
@first,
@birth,
DATEADD(DAY,220,@first),
DATEADD(DAY 250,@first))

I need to chance this trigger with if-else.Because i have 3 more parameters(Four,Five,Six). I'm try to write something like that

 If @first not null DATEADD..
 If @four not null DATEADD.. like that

Body:
you can use exists in your statement like this:

insert into table1(col1,col2)
select col1,col2 from inserted as i
where not exists(select 0 from table1 where relatedkey=i.relatedkey)


问:
Python - Random sample from a range whilst avoiding certain values
I have been reading up about the random.sample() function in the random module and have not seen anything that solves my problem.

I know that using random.sample(range(1,100),5) would give me 5 unique samples from the 'population'...

I would like to get a random number in range(0,999). I could use random.sample(range(0,999),1) but why then am I thinking about using random.sample() ?

I need the random number in that range to not match any number in a separate array (Say, [443,122,738])

Is there a relatively easy way I could go about doing this?

Also, I am pretty new to python and am definitely a beginner -- If you would like me to update the question with any information I may have missed then I will.

EDIT:
Accidentally said random.range() once. Whoops.

答:
There are two main ways:

```<code>import random

def method1(lower, upper, exclude):
    choices = set(range(lower, upper + 1)) - set(exclude)
    return random.choice(list(choices))

def method2(lower, upper, exclude):
    exclude = set(exclude)
    while True:
        val = random.randint(lower, upper)
        if val not in exclude:
            return val
</code>```

Example usage:

```<code>for method in method1, method2:
    for i in range(10):
        print(method(1, 5, [2, 4]))
    print('----')
</code>```

Output:

```<code>1
1
5
3
1
1
3
5
5
1
----
5
3
5
1
5
3
5
3
1
3
----
</code>```

The first is better for a smaller range or a larger list exclude (so the choices list won't be too big), the second is better for the opposite (so it doesn't loop too many times looking for an appropriate option).

Body:
There are two main ways:

import random

def method1(lower, upper, exclude):
    choices = set(range(lower, upper + 1)) - set(exclude)
    return random.choice(list(choices))

def method2(lower, upper, exclude):
    exclude = set(exclude)
    while True:
        val = random.randint(lower, upper)
        if val not in exclude:
            return val

Example usage:

for method in method1, method2:
    for i in range(10):
        print(method(1, 5, [2, 4]))
    print('----')

Output:

1
1
5
3
1
1
3
5
5
1
----
5
3
5
1
5
3
5
3
1
3
----

The first is better for a smaller range or a larger list exclude (so the choices list won't be too big), the second is better for the opposite (so it doesn't loop too many times looking for an appropriate option).


问:
get colsum of every possible row combination
Hello I have a problem of how to sum up every possible combination of rows.

Consider I have the matrix:

```<code>M<-replicate(5, rnorm(10))
</code>```

now I want a universal solution to get colSums vectors saved in a list or data frame of all possible row combination: eg some examples :

colsum of row 1 + row 2

colsum of row 1 + row 3
..

row 2 + row 3

row 2 + row 4
..

row 1 + row 2 + row 3
..

row 4 + row 7 + row 10
...

row 1 + row 2 + row 3 + row 4 + row 5 + row6 + row 7 + row 8 +row 9 + row 10

does anyone know a solution for that?
Many thanks

Body:
Hello I have a problem of how to sum up every possible combination of rows.

Consider I have the matrix:

M<-replicate(5, rnorm(10))

now I want a universal solution to get colSums vectors saved in a list or data frame of all possible row combination: eg some examples :

colsum of row 1 + row 2

colsum of row 1 + row 3
..

row 2 + row 3

row 2 + row 4
..

row 1 + row 2 + row 3
..

row 4 + row 7 + row 10
...

row 1 + row 2 + row 3 + row 4 + row 5 + row6 + row 7 + row 8 +row 9 + row 10

does anyone know a solution for that?
Many thanks

Body:
set.seed(101)
M <- replicate(5, rnorm(10))

A function to get the vector of column sums of a specified set of rows (and label which rows are summed)

cs <- function(cc) colSums(M[cc,])

Test it out with rows 1 and 2:

cs(c(1,2))
##         1         2
##  2.450401 -4.396749

This will get all N-way combinations:

csN <- function(N) {
     cc <- combn(1:nrow(M),N,FUN=cs,simplify=FALSE)
     names(cc) <- combn(1:nrow(M),N,FUN=paste,collapse=",")
     return(cc)
}

This makes a list of all of the combinations and sticks them together ...

do.call("c",lapply(2:nrow(M),csN))
## quote function name for safety (fails if a vble called c exists)

## $`1,2`
## [1]  0.2264254 -0.2683963  0.5447664  1.1740892  1.2406726
##
## $`1,3`
## [1] -1.0009803  1.9542036 -0.4317362  1.9028030 -1.8368686
##
## ...
##
## $`2,3,4,5,6,7,8,9,10`
## [1]  2.7764374 -4.9231973 -0.3762125 -0.4554264 -4.6341908
##
## $`1,2,3,4,5,6,7,8,9,10`
## [1]  2.4504010 -4.3967492 -0.5399682  0.4395108 -4.1517320


问:
how to distribute items in number of lists?
Question: How to distribute items in number of lists? following are examples:

Imagine I have a 8 lists, and 5 items. in this case list 1 to 5 will have 1 item.  rest of lists remain empty.

Now If I have 8 lists and 16 items each list will have 2 items.

If I have 8 lists and 11 items, list 1 to 3 will have two items. rest of the lists will have 1 item.

```<code>var items = new List<object>();
var containers = new List<List<object>>();

int c = -1; // indexer for container.

for(int i = 0; i < items.Count; i++)
{
    // disturbute items to containers

    if (i % (items.Count/containers.Count) == 0) c++; // this is wrong. when to increment?

    containers[c].Add(items[i]);
}
</code>```

I'm pretty sure only if statement is wrong. Its getting confusing how to handle i.

答:
Try this:</p>

```<code>    static void Main(string[] args)
    {
        var items = new List<object>() {1, 2, 3, 4, 5, 6};
        var containers = new List<List<object>>() { new List<object>(), new List<object>(),  new List<object>()};

        int c = 0; // indexer for container.
        int containerCount = containers.Count;

        for (int i = 0; i < items.Count; i++, c++)
        {
            c = c % containerCount;
            containers[c].Add(items[i]);
        }
    }
</code>```

Body:
Question: How to distribute items in number of lists? following are examples:

Imagine I have a 8 lists, and 5 items. in this case list 1 to 5 will have 1 item.  rest of lists remain empty.

Now If I have 8 lists and 16 items each list will have 2 items.

If I have 8 lists and 11 items, list 1 to 3 will have two items. rest of the lists will have 1 item.

var items = new List<object>();
var containers = new List<List<object>>();

int c = -1; // indexer for container.

for(int i = 0; i < items.Count; i++)
{
    // disturbute items to containers

    if (i % (items.Count/containers.Count) == 0) c++; // this is wrong. when to increment?

    containers[c].Add(items[i]);
}

I'm pretty sure only if statement is wrong. Its getting confusing how to handle i.

Body:
Try this:

    static void Main(string[] args)
    {
        var items = new List<object>() {1, 2, 3, 4, 5, 6};
        var containers = new List<List<object>>() { new List<object>(), new List<object>(),  new List<object>()};

        int c = 0; // indexer for container.
        int containerCount = containers.Count;

        for (int i = 0; i < items.Count; i++, c++)
        {
            c = c % containerCount;
            containers[c].Add(items[i]);
        }
    }


问:
Guitar Chord Recognition Algorithm?
Whats a good digital signal processing algorithm that is good on guitar chords? Since Fast Fourier Transform I think only is accurate on single notes played on the guitar but not notes that are played simultaenously (i.e. chords).

Thanks!

答:
The short answer is that you need much more than one algorithm. Good chord recognition methods could more aptly be described as "systems", but usually they are indeed based on an initial transform to the frequency domain (most often DFT).

If you want a chord representaton of the song similar to this

```<code>C G Am F7 F6 C ...
</code>```

then this is actually a problem that is slightly removed from recognising the notes in a piece of audio. In fact, there are two problems (roughly speaking):

finding which pitches are present at any time

grouping these pitches over time so as to be able to assign a chord label to a time interval.

It turns out that the way you transform from the time domain (normal audio) to the frequency domain (spectral representation) is only of limited importance. It's very important what you do afterwards, and often sophisticated probabilistic models (similar to those in speech recognition: HMMs, DBNs, ...) are used to tackle this problem.

Try google scholar "chord transcription", or "chord detection", or "chord labelling" for advanced research in this area.

Most of these approaches use a discrete Fourier transform (DFT) to create the initial spectrogram. During further processing, too, they tend to differ only slightly, though different time-series smoothing techniques have been used: hidden Markov models, dynamic Bayesian networks, support vector machines (SVMstruct), and conditional random fields -- among others.
The most advanced transcribers use automatic tuning, key information, bass note information, and information of the metric position to improve the results. My thesis (Chapter 2) gives a nice overview.

Open source chord detection algorithms:

Chordino at http://isophonics.net/nnls-chroma

Chordata at http://clam-project.org/

LabROSA Chord Recognition http://labrosa.ee.columbia.edu/projects/chords/

Hope this helps.

Title: Guitar Chord Recognition Algorithm?

Body:
The short answer is that you need much more than one algorithm. Good chord recognition methods could more aptly be described as "systems", but usually they are indeed based on an initial transform to the frequency domain (most often DFT).

If you want a chord representaton of the song similar to this

C G Am F7 F6 C ...

then this is actually a problem that is slightly removed from recognising the notes in a piece of audio. In fact, there are two problems (roughly speaking):

finding which pitches are present at any time

grouping these pitches over time so as to be able to assign a chord label to a time interval.

It turns out that the way you transform from the time domain (normal audio) to the frequency domain (spectral representation) is only of limited importance. It's very important what you do afterwards, and often sophisticated probabilistic models (similar to those in speech recognition: HMMs, DBNs, ...) are used to tackle this problem.

Try google scholar "chord transcription", or "chord detection", or "chord labelling" for advanced research in this area.

Most of these approaches use a discrete Fourier transform (DFT) to create the initial spectrogram. During further processing, too, they tend to differ only slightly, though different time-series smoothing techniques have been used: hidden Markov models, dynamic Bayesian networks, support vector machines (SVMstruct), and conditional random fields -- among others.
The most advanced transcribers use automatic tuning, key information, bass note information, and information of the metric position to improve the results. My thesis (Chapter 2) gives a nice overview.

Open source chord detection algorithms:

Chordino at http://isophonics.net/nnls-chroma

Chordata at http://clam-project.org/

LabROSA Chord Recognition http://labrosa.ee.columbia.edu/projects/chords/

Hope this helps.


问:
SSTable multiple directories
I have recently started working on Cassandra everything was well documented and easy to understand so far.

However I am unable to find any answer to the following question:

Why do Cassandra data directory (/var/lib/cassandra/data/ks) have multiple subdirectories for the same SSTable?
At why what point is the new directory is created?

[centos@cs1 2017-06-03--19-46-14 cassandra $] ls -l /var/lib/cassandra/data/ks
total 8
drwxr-xr-x. 3 root root 4096 Jun  3 19:46 events-4f35e2c0482911e79119511599d22fe7
drwxr-xr-x. 3 root root 4096 Jun  3 19:41 events-7a34c34047f411e7aee3b9dc2549db1c

[centos@cs1 2017-06-03--19-46-10 cassandra $] tree
.
├── events-4f35e2c0482911e79119511599d22fe7
│   ├── ks-events-ka-4-CompressionInfo.db
│   ├── ks-events-ka-4-Data.db
│   ├── ks-events-ka-4-Digest.sha1
│   ├── ks-events-ka-4-Filter.db
│   ├── ks-events-ka-4-Index.db
│   ├── ks-events-ka-4-Statistics.db
│   ├── ks-events-ka-4-Summary.db
│   ├── ks-events-ka-4-TOC.txt
│   └── snapshots
└── events-7a34c34047f411e7aee3b9dc2549db1c
    └── snapshots
        └── 1496472654574-device_log
            └── manifest.json

5 directories, 9 files```

I noticed that flushing or compacting does not create new directory. It Simply adds/compacts the most recent SSTable directory

答:
When you drop a table, by default Cassandra takes a snapshot to prevent data-loss if it was unintended. In your case, the events-7a34c34047f411e7aee3b9dc2549db1c is the older table and it has only snapshot directory in it.

The Cassandra.yaml parameter responsible for that action is as follows

auto_snapshot  (Default: true) Enable or disable whether a snapshot
  is taken of the data before keyspace truncation or dropping of tables.
  To prevent data loss, using the default setting is strongly advised.
  If you set to false, you will lose data on truncation or drop.

Remember to clean up the older table snapshots in production like environments, otherwise it could easily pile up on the data directory size.

Title: SSTable multiple directories

Body:
I have recently started working on Cassandra everything was well documented and easy to understand so far.

However I am unable to find any answer to the following question:

Why do Cassandra data directory (/var/lib/cassandra/data/ks) have multiple subdirectories for the same SSTable?
At why what point is the new directory is created?

[centos@cs1 2017-06-03--19-46-14 cassandra $] ls -l /var/lib/cassandra/data/ks
total 8
drwxr-xr-x. 3 root root 4096 Jun  3 19:46 events-4f35e2c0482911e79119511599d22fe7
drwxr-xr-x. 3 root root 4096 Jun  3 19:41 events-7a34c34047f411e7aee3b9dc2549db1c

[centos@cs1 2017-06-03--19-46-10 cassandra $] tree
.
├── events-4f35e2c0482911e79119511599d22fe7
│   ├── ks-events-ka-4-CompressionInfo.db
│   ├── ks-events-ka-4-Data.db
│   ├── ks-events-ka-4-Digest.sha1
│   ├── ks-events-ka-4-Filter.db
│   ├── ks-events-ka-4-Index.db
│   ├── ks-events-ka-4-Statistics.db
│   ├── ks-events-ka-4-Summary.db
│   ├── ks-events-ka-4-TOC.txt
│   └── snapshots
└── events-7a34c34047f411e7aee3b9dc2549db1c
    └── snapshots
        └── 1496472654574-device_log
            └── manifest.json

5 directories, 9 files

I noticed that flushing or compacting does not create new directory. It Simply adds/compacts the most recent SSTable directory


问:
Calling converted string from UIDataPicker date
Now I am learning Swift and making a typical ToDo app.
I found a function to convert date data from UIDatePicker to String, here is my ViewController chunk of code:

```<code>@IBAction func dateToString(sender: UIDatePicker) {
            var dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
            var strDate = dateFormatter.stringFromDate(myDatePicker.date)
            return ()
        }
</code>```

But the problem is that I can not access the string results from this function, in my app
i have 2 labels in every tableViewCell, one simple label text data, and another is date data from date picker (also should be a string):

```<code>@IBOutlet weak var saveButton: UIBarButtonItem!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if saveButton === sender {
        let name = nameTextField.text ?? ""
        let date =
        item = Item (name: name, date: date)
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    if let item = item {
        nameTextField.text = item.name
                           = item.date

}
</code>```

}

please help, what should I write in

```<code>let date =
</code>```

and

```<code>= item.date
</code>```

to define a date?
I've tried to call a function let date = dateToString; but it doesn't work for me.
Greatly appreciate any help here!

答:
You could change your function like </p>

```<code>var strDate:String = String()

@IBAction func dateToString(sender: UIDatePicker) {
        var dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        strDate = dateFormatter.stringFromDate(myDatePicker.date)
    }
</code>```

<p>Then you can use </p>

```<code>let date = strDate
</code>```

Body:
Now I am learning Swift and making a typical ToDo app.
I found a function to convert date data from UIDatePicker to String, here is my ViewController chunk of code:

@IBAction func dateToString(sender: UIDatePicker) {
            var dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
            var strDate = dateFormatter.stringFromDate(myDatePicker.date)
            return ()
        }

But the problem is that I can not access the string results from this function, in my app
i have 2 labels in every tableViewCell, one simple label text data, and another is date data from date picker (also should be a string):

@IBOutlet weak var saveButton: UIBarButtonItem!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if saveButton === sender {
        let name = nameTextField.text ?? ""
        let date =
        item = Item (name: name, date: date)
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    if let item = item {
        nameTextField.text = item.name
                           = item.date

}

}

please help, what should I write in

let date =

and

= item.date

to define a date?
I've tried to call a function let date = dateToString; but it doesn't work for me.
Greatly appreciate any help here!

Body:
You could change your function like

var strDate:String = String()

@IBAction func dateToString(sender: UIDatePicker) {
        var dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        strDate = dateFormatter.stringFromDate(myDatePicker.date)
    }

Then you can use

let date = strDate


问:
Text file apostrophe trouble
I'm attempting to read from a Project Gutenberg text file and count the total number of words. I'm currently overshooting because words with apostrophes are double counted. However the apostrophe character from the text file doesn't match the ASCII character 39, i.e. '\'', so my is_word function is working incorrectly. Any suggestion as to what that character actually is?

Note: When I go through and manually replace the apostrophes in vim, the word counter works fine.

link to text file: http://www.gutenberg.org/ebooks/1342

答:
This isn't a complete answer, but if you do

```<code>#include <wchar.h>
#include <locale.h>
</code>```

and then

```<code>setlocale(LC_ALL, "en_US.UTF-8");
</code>```

and then call getwchar() or getwc(fp) instead of getchar/getc, and then check for the value 8217 as well as '\'', you might be able to get it all to work.

(It works for me.  YMMV.  Depending on your OS, you might have to use a locale string other than "en_US.UTF-8".)

(And if this does work, welcome to the wonderful world of internationalization.  Having gone down this road, there are several other issues you'll have to pay attention to if you want your code to work properly under all circumstances and in all locales.)

Title: Text file apostrophe trouble

Body:
This isn't a complete answer, but if you do

#include <wchar.h>
#include <locale.h>

and then

setlocale(LC_ALL, "en_US.UTF-8");

and then call getwchar() or getwc(fp) instead of getchar/getc, and then check for the value 8217 as well as '\'', you might be able to get it all to work.

(It works for me.  YMMV.  Depending on your OS, you might have to use a locale string other than "en_US.UTF-8".)

(And if this does work, welcome to the wonderful world of internationalization.  Having gone down this road, there are several other issues you'll have to pay attention to if you want your code to work properly under all circumstances and in all locales.)


问:
How to set parameters to score function in sklearn SelectKBest ()
I'm using the SelectKBest() class for feature selection in sklearn. SelectKBest() can take a callable score function as an input. In this case I would like to use mutual_info_regression as the score function. mutual_info_regression can take a few parameters which I would like to set myself. For example, I would like to set the random_state = 0. The problem is I'm not sure how to pass parameters into the score function since the score function is itself a parameter in SelectKBest(). Obviously something like SelectKBest(score_func = mutual_info_classif(random_state=0)) won't work because the mutal_info_classif function would be called directly. I feel like this is probably a very basic question about python classes but I can't seem to find anything addressing what I'm looking for. Thanks in advance for your time!

答:
You can create another function which calls mutual_info_regression and pass it instead:

```<code>def my_score(X, y):
    return mutual_info_regression(X, y, random_state=0)

SelectKBest(score_func=my_score)
</code>```

Python standard library provides an useful helper for creating such functions - it is called functools.partial. It allows to create functions with some parameters pre-set; instead of "manual" my_score definition you can write

```<code>from functools import partial
my_score = partial(mutual_info_regression, random_state=0)
SelectKBest(score_func=my_score)
</code>```

Of course, you can also pass partial directly, which gets you very close to your example:

```<code>from functools import partial
SelectKBest(score_func=partial(mutual_info_classif, random_state=0))
</code>```

Body:
You can create another function which calls mutual_info_regression and pass it instead:

def my_score(X, y):
    return mutual_info_regression(X, y, random_state=0)

SelectKBest(score_func=my_score)

Python standard library provides an useful helper for creating such functions - it is called functools.partial. It allows to create functions with some parameters pre-set; instead of "manual" my_score definition you can write

from functools import partial
my_score = partial(mutual_info_regression, random_state=0)
SelectKBest(score_func=my_score)

Of course, you can also pass partial directly, which gets you very close to your example:

from functools import partial
SelectKBest(score_func=partial(mutual_info_classif, random_state=0))


问:
Ruby on rails: unexpected end-of-input, expecting keyword_end
i have a problem like the subject in the controller. I've got error of expecting end of function. But as you can see I've got every end of the function. I'm a beginner in RoR.</p>

```<code>class UsersController < ApplicationController
before_filter :authenticate_user!

  def show
    @user = User.find(params[:id])
    @user_catalogs = @user.catalogs
    @hash = Gmaps4rails.build_markers(@user.locations) do |location, marker|
    marker.lat location.latitude
    marker.lng location.longitude
    marker.infowindow location.address
  end

  def index
       @users = User.where.not("id = ?",current_user.id).order("created_at DESC")
       @conversations = Conversation.involving(current_user).order("created_at DESC")
  end
end
</code>```

答:
You missed end in show method. Try this:

```<code>  def show
    @user = User.find(params[:id])
    @user_catalogs = @user.catalogs
    @hash = Gmaps4rails.build_markers(@user.locations) do |location, marker|
      marker.lat location.latitude
      marker.lng location.longitude
      marker.infowindow location.address
    end
  end
</code>```

Body:
i have a problem like the subject in the controller. I've got error of expecting end of function. But as you can see I've got every end of the function. I'm a beginner in RoR.

class UsersController < ApplicationController
before_filter :authenticate_user!

  def show
    @user = User.find(params[:id])
    @user_catalogs = @user.catalogs
    @hash = Gmaps4rails.build_markers(@user.locations) do |location, marker|
    marker.lat location.latitude
    marker.lng location.longitude
    marker.infowindow location.address
  end

  def index
       @users = User.where.not("id = ?",current_user.id).order("created_at DESC")
       @conversations = Conversation.involving(current_user).order("created_at DESC")
  end
end

Body:
You missed end in show method. Try this:

  def show
    @user = User.find(params[:id])
    @user_catalogs = @user.catalogs
    @hash = Gmaps4rails.build_markers(@user.locations) do |location, marker|
      marker.lat location.latitude
      marker.lng location.longitude
      marker.infowindow location.address
    end
  end


问:
Make bold text inside element (jQuery)
I'm trying to make text (fat) bold. Curretly I managed to do this whit code below:

```<code>Movie <b>fat</b> was been added
</code>```

But this bold tags won't work. Now the question is how to enable html for only (fat), to be bold like this: Movie fat was been added

My code so far:

```<code>var boldy = (Movie[0].title)
var fat = boldy.bold()

$("div.container div:first").text("Movie " + (fat) + " was been added")
</code>```

I also tried whit this:

```<code>$("div.container div:first").html("Hello <b>"+(boldy)+"</b>")
</code>```

答:
var world = 'world';
$("div").html(`Hello <b>${world}</b>`);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  Movie fat was been added
</div></code>```

Title: Make bold text inside element (jQuery)

Body:
I'm trying to make text (fat) bold. Curretly I managed to do this whit code below:

Movie fat was been added

But this bold tags won't work. Now the question is how to enable html for only (fat), to be bold like this: Movie fat was been added

My code so far:

var boldy = (Movie[0].title)
var fat = boldy.bold()

$("div.container div:first").text("Movie " + (fat) + " was been added")

I also tried whit this:

$("div.container div:first").html("Hello "+(boldy)+"")

Body:
var world = 'world';
$("div").html(`Hello <b>${world}</b>`);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  Movie fat was been added
</div>


问:
Do testCompile and androidTestCompile dependencies go into the built apk?
By default are testCompile and androidTestCompile dependencies along with any test cases written get packaged into the debug or release apk? If so, do we need to add some Proguard rules and or remove test cases before building release apk?

答: No, they are not. Or, more accurately, they are not included in any regular builds (e.g., debug, release). That is why the code is isolated in separate source sets and why the dependencies have the specific prefixes (test, androidTest).


答:
var word ="fat"
$("div:first").html("Movie "+word+" was been added")```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div></code>```

Title: Make bold text inside element (jQuery)

Body:
var word ="fat"
$("div:first").html("Movie <b>"+word+"</b> was been added")

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>


答:
Found it </p>

```<code>  def show
    @user = User.find(params[:id])
    @user_catalogs = @user.catalogs
    @hash = Gmaps4rails.build_markers(@user.locations) do |location, marker|
    marker.lat location.latitude
    marker.lng location.longitude
    marker.infowindow location.address
    end <<<<< here!
  end
</code>```

Title: Ruby on rails: unexpected end-of-input, expecting keyword_end

Body:
Found it

  def show
    @user = User.find(params[:id])
    @user_catalogs = @user.catalogs
    @hash = Gmaps4rails.build_markers(@user.locations) do |location, marker|
    marker.lat location.latitude
    marker.lng location.longitude
    marker.infowindow location.address
    end <<<<< here!
  end


问:
Java boolean equations as parametar of function
Lets take a look at my program. That have some imaginary .txt file with car models.

```<code>public class Car {
    private String model;

    public String getModel() {
        return this.model;
    }
}

public class Main {
    public static void Main(String[] args) {
        ArrayList<Car> cars = loadCars(path); //imaginary func and file
        String someModel = generateSomeModel(); //imaginart func

        for (Car c : cars)
            if (c.getModel.equals(someModel))
                System.out.println("Hit!");

        for (Car c : cars)
            if (!c.getModel.equals(someModel))
                System.out.println("Hit!");

    }
}
</code>```

Lets suppose that I have to go through my cars list a 100 times and compare them in if statement for some different attributes every time, that means I  will have to write 100 different for loops that will be 90% same. Is there a way to write a function that will take as a parametar Boolean equation? Something like this.

```<code>public static void printCars(Boolean equation) {
    for (Car c : cars)
        if (Boolean equation)
            System.out.println("Hit!");
}
</code>```

答:
You can use Predicate interface to pass a function (or lambda) as parameter to your function:

https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html

With a predicate you can rewrite your function in a following way:

```<code>public static void printCars(Predicate<Car> filter) {
    for (Car c : cars)
        if (filter.test(car))
            System.out.println("Hit!");
}
</code>```

And then pass required function in the following way:

printCars(c -> c.getModel().equals("bmw"));

Body:
Lets take a look at my program. That have some imaginary .txt file with car models.

public class Car {
    private String model;

    public String getModel() {
        return this.model;
    }
}

public class Main {
    public static void Main(String[] args) {
        ArrayList<Car> cars = loadCars(path); //imaginary func and file
        String someModel = generateSomeModel(); //imaginart func

        for (Car c : cars)
            if (c.getModel.equals(someModel))
                System.out.println("Hit!");

        for (Car c : cars)
            if (!c.getModel.equals(someModel))
                System.out.println("Hit!");

    }
}

Lets suppose that I have to go through my cars list a 100 times and compare them in if statement for some different attributes every time, that means I  will have to write 100 different for loops that will be 90% same. Is there a way to write a function that will take as a parametar Boolean equation? Something like this.

public static void printCars(Boolean equation) {
    for (Car c : cars)
        if (Boolean equation)
            System.out.println("Hit!");
}

Body:
You can use Predicate interface to pass a function (or lambda) as parameter to your function:

https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html

With a predicate you can rewrite your function in a following way:

public static void printCars(Predicate<Car> filter) {
    for (Car c : cars)
        if (filter.test(car))
            System.out.println("Hit!");
}

And then pass required function in the following way:

printCars(c -> c.getModel().equals("bmw"));


问:
Override standard CSS for hidden input tags
For HTML tags such as <input type="hidden"> when I look at the browser's standard CSS, I see:

```<code>input[type="hidden" i] {
    display: none;
}
</code>```

So I added this to my CSS:

```<code>input[type="hidden" i] {
    display: block !important;
}
</code>```

And for HTML I have <input name=countrycode type=hidden value=US>

When I open up the developer tools I can see that the old display:none is ignored, however, the field never shows up in the page and is still hidden!

Why doesn't  the browser follow my CSS rules, is there another way to force it to do so?  If I add width: 200;height:200;background: black this should make it appear in the page, right?

The reason I want to do this is because I have a lot of hidden inputs in many pages that now I want them to be visible (to get input from user) so I decided to do it fast with CSS. I know this can be easily done with JavaScript, but just curious why CSS is not working or maybe it will work on other browsers but not Google Chrome?

答:
The reason that your input[type=hidden] is hidden, is because it doesn't have a control type to show the user it's value, so your display: block; should work, but the browser'll have nothing to render. Your hidden input could be a checkbox, a text field or a number.

More info: https://www.w3.org/wiki/HTML/Elements/input

Body:
For HTML tags such as <input type="hidden"> when I look at the browser's standard CSS, I see:

input[type="hidden" i] {
    display: none;
}

So I added this to my CSS:

input[type="hidden" i] {
    display: block !important;
}

And for HTML I have <input name=countrycode type=hidden value=US>

When I open up the developer tools I can see that the old display:none is ignored, however, the field never shows up in the page and is still hidden!

Why doesn't  the browser follow my CSS rules, is there another way to force it to do so?  If I add width: 200;height:200;background: black this should make it appear in the page, right?

The reason I want to do this is because I have a lot of hidden inputs in many pages that now I want them to be visible (to get input from user) so I decided to do it fast with CSS. I know this can be easily done with JavaScript, but just curious why CSS is not working or maybe it will work on other browsers but not Google Chrome?


问:
rsync with ssh without using credentials stored in ~/.ssh/config
I have a script that transfers files. Everytime I run it It needs to connect to a different host. That's why I'm adding the host as parameter.

The script is executed as: ./transfer.sh <hostname>

```<code>#!/bin/bash -evx

SSH="ssh \
-o UseRoaming=no \
-o UserKnownHostsFile=/dev/null \
-o StrictHostKeyChecking=no \
-i ~/.ssh/privateKey.pem \
-l ec2-user \
${1}"

files=(
  file1
  file2
)

files="${files[@]}"

# this works
$SSH

# this does not work
rsync -avzh --stats --progress $files -e $SSH:/home/ec2-user/

# also this does not work
rsync -avzh --stats --progress $files -e $SSH ec2-user@$1:/home/ec2-user/
</code>```

I can properly connect with the ssh connection stored in $SSH, but the rsync connection attempts fails because of the wrong key:

```<code>Permission denied (publickey).
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: unexplained error (code 255) at io.c(226) [sender=3.1.2]
</code>```

What would be the correct syntax for the rsync connection?

答:
My solution after Jakuje pointed me in the right direction:</p>

```<code>#!/bin/bash -evx

host=$1

SSH="ssh \
-o UseRoaming=no \
-o UserKnownHostsFile=/dev/null \
-o StrictHostKeyChecking=no \
-i ~/.ssh/privateKey.pem \
-l ec2-user"

files=(
  file1
  file2
)

files="${files[@]}"

# transfer all in one rsync connection
rsync -avzh --stats --progress $files -e "$SSH" $host:/home/ec2-user/

# launch setup script
$SSH $host ./setup.sh
</code>```

Body:
I have a script that transfers files. Everytime I run it It needs to connect to a different host. That's why I'm adding the host as parameter.

The script is executed as: ./transfer.sh <hostname>

#!/bin/bash -evx

SSH="ssh \
-o UseRoaming=no \
-o UserKnownHostsFile=/dev/null \
-o StrictHostKeyChecking=no \
-i ~/.ssh/privateKey.pem \
-l ec2-user \
${1}"

files=(
  file1
  file2
)

files="${files[@]}"

# this works
$SSH

# this does not work
rsync -avzh --stats --progress $files -e $SSH:/home/ec2-user/

# also this does not work
rsync -avzh --stats --progress $files -e $SSH ec2-user@$1:/home/ec2-user/

I can properly connect with the ssh connection stored in $SSH, but the rsync connection attempts fails because of the wrong key:

Permission denied (publickey).
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: unexplained error (code 255) at io.c(226) [sender=3.1.2]

What would be the correct syntax for the rsync connection?

Body:
My solution after Jakuje pointed me in the right direction:

#!/bin/bash -evx

host=$1

SSH="ssh \
-o UseRoaming=no \
-o UserKnownHostsFile=/dev/null \
-o StrictHostKeyChecking=no \
-i ~/.ssh/privateKey.pem \
-l ec2-user"

files=(
  file1
  file2
)

files="${files[@]}"

# transfer all in one rsync connection
rsync -avzh --stats --progress $files -e "$SSH" $host:/home/ec2-user/

# launch setup script
$SSH $host ./setup.sh


问:
Django: How to filter for keyword in multiple fields on a model?
I have Article model with title and body fields. I'm building a search functionality and need to filter for articles that have keywords either in title or body fields.

I have two Articles. One has "candy" in the title and the other has "candy" in the body. So my result filter should have both articles. I'm trying below query but it's bringing me the first article only

```<code>Article.objects.filter(title__icontains='candy').filter(body__icontains='candy')
</code>```

Thx

答:
You need to use Q objects.</p>

```<code>Article.objects.filter(Q(title__icontains='candy')|Q(body__icontains='candy'))
</code>```

Body:
I have Article model with title and body fields. I'm building a search functionality and need to filter for articles that have keywords either in title or body fields.

I have two Articles. One has "candy" in the title and the other has "candy" in the body. So my result filter should have both articles. I'm trying below query but it's bringing me the first article only

Article.objects.filter(title__icontains='candy').filter(body__icontains='candy')

Thx

Body:
You need to use Q objects.

Article.objects.filter(Q(title__icontains='candy')|Q(body__icontains='candy'))


问:
How to compute the "15% of the time" randomness?
I'm looking for a decent, elegant method of calculating this simple logic.

Right now I can't think of one, it's spinning my head.

I am required to do some action only 15% of the time.

I'm used to "50% of the time" where I just mod the milliseconds of the current time and see if it's odd or even, but I don't think that's elegant.

How would I elegantly calculate "15% of the time"?  Random number generator maybe?

Pseudo-code or any language are welcome.

Hope this is not subjective, since I'm looking for the "smartest" short-hand method of doing that.

Thanks.

答:
Solution 1 (double)

get a random double between 0 and 1 (whatever language you use, there must be such a function)

do the action only if it is smaller than 0.15

Solution 2 (int)

You can also achieve this by creating a random int and see if it is dividable to 6 or 7. UPDATE --> This is not optimal.


问:
How to get values from table valued function in C#
I have a program where i have to display

The Event Description (OpisDogodka)

Location (Lokacija)

Time (ura)
My table valued function:

```<code>     [dbo].[DobiDogodek](
     @Ime nvarchar(100), @Datum date)
     RETURNS TABLE AS RETURN (SELECT OpisDogodka AS 'Opisdogodka',Lokacija, Ura FROM Dogodek WHERE Ime=@Ime AND Datum=@Datum)
</code>```

My method to connect to the server:

```<code> public string Dobi_dogodek(string ime,string datum)
{
    string a="";
    cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(@Ime,@Datum)",povezava); //povezava = connectio and it succeeds to connect to the server.

    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@Ime", ime);
    cmd.Parameters.AddWithValue("@Datum", datum); //how to pass date only?
    try
    {
        SqlDataReader Reader = cmd.ExecuteReader();
        while(Reader.Read())
        {

            a = Reader.GetString(0)+" "+Reader.GetString(1)+" "+Reader.GetString(3).ToString(); // get what?

                }
            Uspeh = true;
    }
    catch (Exception e)
    {
        ex = e;
    }
    finally
    {
        povezava.Close();
    }

    return a;
}
</code>```

I tried also using Datatable and datarow. I am also unsure how to work with Date. I know how to work with DateTime, but I need Date and Time separate. What I am doing wrong?

4.6.2017 (11.40 am CET)Update:
It seems I get the desired result

```<code>  public List<string> Dobi_dogodek(string ime,string datum)
{
    s = new List<string>();
    cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(@Ime,@Datum)",povezava);

    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@Ime", ime);
    cmd.Parameters.AddWithValue("@Datum", Convert.ToDateTime(datum));
    dt = new DataTable();
    da = new SqlDataAdapter(cmd);
    da.Fill(dt);

    try
    {
        foreach (DataRow dr in dt.Rows)
        {
            s.Add(dr["Opis dogodka"].ToString() + "\\" + dr["Lokacija"].ToString() + "\\" + dr["Ura"].ToString());
        }

        Uspeh = true;
    }
    catch (Exception e)
    {
        ex = e;
    }
    finally
    {
        povezava.Close();
    }

    return s;
}
</code>```

Now I just need to split the strings according to my requirements, but is the a better (not necessarily an easy) way?

答:
Try this:

cmd.Parameters.AddWithValue("@Datum", Convert.ToDateTime(datum));

See also https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx .

ContentLicense: CC BY-SA 4.0

Body:
I have a program where i have to display

The Event Description (OpisDogodka)

Location (Lokacija)

Time (ura)
My table valued function:

     [dbo].[DobiDogodek](
     @Ime nvarchar(100), @Datum date)
     RETURNS TABLE AS RETURN (SELECT OpisDogodka AS 'Opisdogodka',Lokacija, Ura FROM Dogodek WHERE Ime=@Ime AND Datum=@Datum)

My method to connect to the server:

 public string Dobi_dogodek(string ime,string datum)
{
    string a="";
    cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(@Ime,@Datum)",povezava); //povezava = connectio and it succeeds to connect to the server.

    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@Ime", ime);
    cmd.Parameters.AddWithValue("@Datum", datum); //how to pass date only?
    try
    {
        SqlDataReader Reader = cmd.ExecuteReader();
        while(Reader.Read())
        {

            a = Reader.GetString(0)+" "+Reader.GetString(1)+" "+Reader.GetString(3).ToString(); // get what?

                }
            Uspeh = true;
    }
    catch (Exception e)
    {
        ex = e;
    }
    finally
    {
        povezava.Close();
    }

    return a;
}

I tried also using Datatable and datarow. I am also unsure how to work with Date. I know how to work with DateTime, but I need Date and Time separate. What I am doing wrong?

4.6.2017 (11.40 am CET)Update:
It seems I get the desired result

  public List<string> Dobi_dogodek(string ime,string datum)
{
    s = new List<string>();
    cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(@Ime,@Datum)",povezava);

    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@Ime", ime);
    cmd.Parameters.AddWithValue("@Datum", Convert.ToDateTime(datum));
    dt = new DataTable();
    da = new SqlDataAdapter(cmd);
    da.Fill(dt);

    try
    {
        foreach (DataRow dr in dt.Rows)
        {
            s.Add(dr["Opis dogodka"].ToString() + "\\" + dr["Lokacija"].ToString() + "\\" + dr["Ura"].ToString());
        }

        Uspeh = true;
    }
    catch (Exception e)
    {
        ex = e;
    }
    finally
    {
        povezava.Close();
    }

    return s;
}

Now I just need to split the strings according to my requirements, but is the a better (not necessarily an easy) way?


问:
how to use hostname variable in single quoted?
In the bash file named "input_data"

```<code>LA=$1
curl -H 'Content-Type: application/x-ndjson' -XPOST '"'$LA'":9200/human_flow/human_flow/_bulk?pretty' --data-binary @$2.json
</code>```

When running command

```<code> ./input_data localhost human_flow
</code>```

give error message

```<code>bash-3.2$ ./input_data localhost human_flow
curl: (6) Could not resolve host: "localhost"
</code>```

localhost can be resolved

```<code>bash-3.2$ ping localhost
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.156 ms
</code>```

use 127.0.0.1 instead of localhost

```<code>bash-3.2$ ./input_data 127.0.0.1 human_flow
curl: (6) Could not resolve host: "127.0.0.1"
</code>```

答:
Correct usage would look like:

```<code>curl \
  -H 'Content-Type: application/x-ndjson' \
  -XPOST \
  --data-binary "@$2.json" \
  "$LA:9200/human_flow/human_flow/_bulk?pretty"
</code>```

All expansions are in double quotes -- neither in single quotes (which prevents them from being expanded) nor unquoted.

Double quotes must not be inside single quotes if they are expected to have semantic meaning.

By POSIX convention, positional arguments should be specified after all optional arguments. Applications following GNU conventions don't strictly require this, but following it across-the-board avoids surprises.

Body:
In the bash file named "input_data"

LA=$1
curl -H 'Content-Type: application/x-ndjson' -XPOST '"'$LA'":9200/human_flow/human_flow/_bulk?pretty' --data-binary @$2.json

When running command

 ./input_data localhost human_flow

give error message

bash-3.2$ ./input_data localhost human_flow
curl: (6) Could not resolve host: "localhost"

localhost can be resolved

bash-3.2$ ping localhost
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.156 ms

use 127.0.0.1 instead of localhost

bash-3.2$ ./input_data 127.0.0.1 human_flow
curl: (6) Could not resolve host: "127.0.0.1"

Body:
Correct usage would look like:

curl \
  -H 'Content-Type: application/x-ndjson' \
  -XPOST \
  --data-binary "@$2.json" \
  "$LA:9200/human_flow/human_flow/_bulk?pretty"

All expansions are in double quotes -- neither in single quotes (which prevents them from being expanded) nor unquoted.

Double quotes must not be inside single quotes if they are expected to have semantic meaning.

By POSIX convention, positional arguments should be specified after all optional arguments. Applications following GNU conventions don't strictly require this, but following it across-the-board avoids surprises.


问:
Automatically detect all map navigation applications installed
In iOS apple maps application, when selecting a destination, apple maps gives you options to use any of the installed mapping apps to get turn by turn directions.

How does apple maps do this? is there a way to implement similar feature in my own app?

One way is to get a list of most popular navigation apps, check that they support url schemes, and check if any of them are installed by using:

```<code>if ([[UIApplication sharedApplication] canOpenURL:url]) {
        // mapping app is installed ...
}
</code>```

However, this is not reliable as url schemes might change and also some of the mapping turn-by-turn apps do not support url schemes.

Thanks in advance.

答:
<s>Is this what you're looking for?</s>

Whoops, probably not what you were looking for, but this is how Apple Maps does it. Maybe somewhere in that documentation (or digging deep into it) you might find a way.

From Apple's docs:

iOS apps that are able to display point-to-point directions can register as routing apps and make those directions available to Maps and other apps.

https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/AddingCapabilities/AddingCapabilities.html#//apple_ref/doc/uid/TP40012582-CH26-SW9

Body:
In iOS apple maps application, when selecting a destination, apple maps gives you options to use any of the installed mapping apps to get turn by turn directions.

How does apple maps do this? is there a way to implement similar feature in my own app?

One way is to get a list of most popular navigation apps, check that they support url schemes, and check if any of them are installed by using:

if ([[UIApplication sharedApplication] canOpenURL:url]) {
        // mapping app is installed ...
}

However, this is not reliable as url schemes might change and also some of the mapping turn-by-turn apps do not support url schemes.

Thanks in advance.


答:
Just use a PRNG.  Like always, it's a performance v. accuracy trade-off.  I think making your own doing directly off the time is a waste of time (pun intended).  You'll probably get biasing effects even worse than a run of the mill linear congruential generator.

In Java, I would use nextInt:

```<code>myRNG.nextInt(100) < 15
</code>```

Or (mostly) equivalently:

```<code>myRNG.nextInt(20) < 3
</code>```

There are way to get a random integer in other languages (multiple ways actually, depending how accurate it has to be).

Title: How to compute the "15% of the time" randomness?

Body:
I'm looking for a decent, elegant method of calculating this simple logic.

Right now I can't think of one, it's spinning my head.

I am required to do some action only 15% of the time.

I'm used to "50% of the time" where I just mod the milliseconds of the current time and see if it's odd or even, but I don't think that's elegant.

How would I elegantly calculate "15% of the time"?  Random number generator maybe?

Pseudo-code or any language are welcome.

Hope this is not subjective, since I'm looking for the "smartest" short-hand method of doing that.

Thanks.

Body:
Just use a PRNG.  Like always, it's a performance v. accuracy trade-off.  I think making your own doing directly off the time is a waste of time (pun intended).  You'll probably get biasing effects even worse than a run of the mill linear congruential generator.

In Java, I would use nextInt:

myRNG.nextInt(100) < 15

Or (mostly) equivalently:

myRNG.nextInt(20) < 3

There are way to get a random integer in other languages (multiple ways actually, depending how accurate it has to be).


问:
How can i place 3 button horizontally and vertically aligned
I want these 3 buttons to be vertically and horizontally aligned but when I try to align them, the last button is falling down and I don't know why. This is the original code without alignment, some one can help me?

@import 'https://fonts.googleapis.com/css?family=Comfortaa:300,400,700&subset=cyrillic,cyrillic-ext,latin-ext';

body {
  background: url(https://wallpaperscraft.com/image/black_background_pattern_light_texture_55291_1920x1080.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
button {
  color:#454545;
  width: 200px;
  background:transparent;
  border-width:2px;
  border-style: solid;
  border-color: #454545;
  position:relative;
  margin:1em;
  display:inline-block;
  padding:0.5em 1em;
  transition:all 0.3s ease-in-out;
  text-align:center;
  font-family:comfortaa;
  font-weight:bold
}

button:before, button:after{
  content:'';
  display:block;
  position:absolute;
  border-color:#454545;
  box-sizing:border-box;
  border-style:solid;
  width:1em;height:1em;
  transition:all 0.3s ease-in-out
}

button:before {
  top:-6px;left:-6px;
  border-width:2px 0 0 2px;
  z-index:5;
}

button:after {
  bottom:-6px;
  right:-6px;
  border-width:0 2px 2px 0;
}

button:hover:before, button:hover:after {
  width:calc(100% + 12px);
  height:calc(100% + 12px);
  border-color:#fff
}

button:hover {
  color:#353535;
  background-color:#fff;
  border-color:#fff
}

.pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.rosso button {
  color:#ff0c0c;
  border-color:#ff0c0c
}

.rosso button:before, .rosso button:after  {
  border-color:#ff0c0c
}

.rosso button:hover:before, .rosso button:hover:after {
  border-color:#ff0c0c;
}

.rosso button:hover {
  color:#fff;
  background-color:#ff0c0c;
  border-color:#ff0c0c;
}

.rosso .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.bianco button {
  color:#e8e8e8;
  border-color:#e8e8e8
}

.bianco button:before, .bianco button:after  {
  border-color:#e8e8e8
}

.bianco button:hover:before, .bianco button:hover:after {
  border-color:#e8e8e8;
}

.bianco button:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.bianco .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.verde button {
  color:#e8e8e8;
  border-color:#e8e8e8
}

.verde button:before, .bianco button:after  {
  border-color:#e8e8e8
}

.verde button:hover:before, .bianco button:hover:after {
  border-color:#e8e8e8;
}

.verde button:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.verde .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <body>
 <div class="pannello rosso">
    <button>TS3</button>
 </div>

 <div class="pannello bianco">
    <button>FORUM</button>
 </div>

 <div class="pannello verde">
    <button>BUYCRAFT</button>
 </div>

 </body></code>```

Thanks!

PS: If you can post the fiddle

答:
I deliberately changed your markup and CSS a little, made it simpler and then changed your pannello rule like this

```<code>.pannello {
  text-align:center;
  position:relative;
  white-space: nowrap;                 /*  make buttons stay on 1 line  */
  left: 50%;                           /*  position its left edge in the middle  */
  top: 50vh;                           /*  position its top edge in the middle */
  transform: translate(-50%,-50%);     /*  move left/top back half its own width/height  */
}
</code>```

Note, since the rules .rosso .pannello, .bianco .pannello and .verde .pannello didn't apply to any element, I simply deleted them

Stack snippet

@import 'https://fonts.googleapis.com/css?family=Comfortaa:300,400,700&subset=cyrillic,cyrillic-ext,latin-ext';

body {
  background: url(https://wallpaperscraft.com/image/black_background_pattern_light_texture_55291_1920x1080.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
button {
  color:#454545;
  width: 200px;
  background:transparent;
  border: 2px solid #454545;
  position:relative;
  margin:1em;
  padding:0.5em 1em;
  transition:all 0.3s ease-in-out;
  font-family:comfortaa;
  font-weight:bold;
}

button:before, button:after{
  content:'';
  position:absolute;
  border-color:#454545;
  box-sizing:border-box;
  border-style:solid;
  width:1em;height:1em;
  transition:all 0.3s ease-in-out
}

button:before {
  top:-6px;left:-6px;
  border-width:2px 0 0 2px;
}

button:after {
  bottom:-6px;
  right:-6px;
  border-width:0 2px 2px 0;
}

button:hover:before, button:hover:after {
  width:calc(100% + 12px);
  height:calc(100% + 12px);
  border-color:#fff
}

button:hover {
  color:#353535;
  background-color:#fff;
  border-color:#fff
}

.pannello {
  position:relative;
  text-align:center;
  white-space: nowrap;                 /*  make buttons stay on 1 line  */
  left: 50%;                           /*  position its left edge in the middle  */
  top: 50vh;                           /*  position its top edge in the middle */
  transform: translate(-50%,-50%);     /*  move left/top back half its own width/height  */
}

.rosso {
  color:#ff0c0c;
  border-color:#ff0c0c
}
.rosso:before, .rosso:after  {
  border-color:#ff0c0c
}
.rosso:hover:before, .rosso:hover:after {
  border-color:#ff0c0c;
}
.rosso:hover {
  color:#fff;
  background-color:#ff0c0c;
  border-color:#ff0c0c;
}

.bianco {
  color:#e8e8e8;
  border-color:#e8e8e8
}
.bianco:before, .bianco:after  {
  border-color:#e8e8e8
}
.bianco:hover:before, .bianco:hover:after {
  border-color:#e8e8e8;
}
.bianco:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.verde {
  color:#e8e8e8;
  border-color:#e8e8e8
}
.verde:before, .bianco:after  {
  border-color:#e8e8e8
}
.verde:hover:before, .bianco:hover:after {
  border-color:#e8e8e8;
}
.verde:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="pannello">
    <button class="rosso">TS3</button>
    <button class="bianco">FORUM</button>
    <button class="verde">BUYCRAFT</button>
  </div>
</body></code>```

Body:
I want these 3 buttons to be vertically and horizontally aligned but when I try to align them, the last button is falling down and I don't know why. This is the original code without alignment, some one can help me?

@import 'https://fonts.googleapis.com/css?family=Comfortaa:300,400,700&subset=cyrillic,cyrillic-ext,latin-ext';

body {
  background: url(https://wallpaperscraft.com/image/black_background_pattern_light_texture_55291_1920x1080.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
button {
  color:#454545;
  width: 200px;
  background:transparent;
  border-width:2px;
  border-style: solid;
  border-color: #454545;
  position:relative;
  margin:1em;
  display:inline-block;
  padding:0.5em 1em;
  transition:all 0.3s ease-in-out;
  text-align:center;
  font-family:comfortaa;
  font-weight:bold
}

button:before, button:after{
  content:'';
  display:block;
  position:absolute;
  border-color:#454545;
  box-sizing:border-box;
  border-style:solid;
  width:1em;height:1em;
  transition:all 0.3s ease-in-out
}

button:before {
  top:-6px;left:-6px;
  border-width:2px 0 0 2px;
  z-index:5;
}

button:after {
  bottom:-6px;
  right:-6px;
  border-width:0 2px 2px 0;
}

button:hover:before, button:hover:after {
  width:calc(100% + 12px);
  height:calc(100% + 12px);
  border-color:#fff
}

button:hover {
  color:#353535;
  background-color:#fff;
  border-color:#fff
}

.pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.rosso button {
  color:#ff0c0c;
  border-color:#ff0c0c
}

.rosso button:before, .rosso button:after  {
  border-color:#ff0c0c
}

.rosso button:hover:before, .rosso button:hover:after {
  border-color:#ff0c0c;
}

.rosso button:hover {
  color:#fff;
  background-color:#ff0c0c;
  border-color:#ff0c0c;
}

.rosso .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.bianco button {
  color:#e8e8e8;
  border-color:#e8e8e8
}

.bianco button:before, .bianco button:after  {
  border-color:#e8e8e8
}

.bianco button:hover:before, .bianco button:hover:after {
  border-color:#e8e8e8;
}

.bianco button:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.bianco .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.verde button {
  color:#e8e8e8;
  border-color:#e8e8e8
}

.verde button:before, .bianco button:after  {
  border-color:#e8e8e8
}

.verde button:hover:before, .bianco button:hover:after {
  border-color:#e8e8e8;
}

.verde button:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.verde .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

    <button>TS3</button>

    <button>FORUM</button>

    <button>BUYCRAFT</button>

Thanks!

PS: If you can post the fiddle

Body:
I deliberately changed your markup and CSS a little, made it simpler and then changed your pannello rule like this

.pannello {
  text-align:center;
  position:relative;
  white-space: nowrap;                 /*  make buttons stay on 1 line  */
  left: 50%;                           /*  position its left edge in the middle  */
  top: 50vh;                           /*  position its top edge in the middle */
  transform: translate(-50%,-50%);     /*  move left/top back half its own width/height  */
}

Note, since the rules .rosso .pannello, .bianco .pannello and .verde .pannello didn't apply to any element, I simply deleted them

Stack snippet

@import 'https://fonts.googleapis.com/css?family=Comfortaa:300,400,700&subset=cyrillic,cyrillic-ext,latin-ext';

body {
  background: url(https://wallpaperscraft.com/image/black_background_pattern_light_texture_55291_1920x1080.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
button {
  color:#454545;
  width: 200px;
  background:transparent;
  border: 2px solid #454545;
  position:relative;
  margin:1em;
  padding:0.5em 1em;
  transition:all 0.3s ease-in-out;
  font-family:comfortaa;
  font-weight:bold;
}

button:before, button:after{
  content:'';
  position:absolute;
  border-color:#454545;
  box-sizing:border-box;
  border-style:solid;
  width:1em;height:1em;
  transition:all 0.3s ease-in-out
}

button:before {
  top:-6px;left:-6px;
  border-width:2px 0 0 2px;
}

button:after {
  bottom:-6px;
  right:-6px;
  border-width:0 2px 2px 0;
}

button:hover:before, button:hover:after {
  width:calc(100% + 12px);
  height:calc(100% + 12px);
  border-color:#fff
}

button:hover {
  color:#353535;
  background-color:#fff;
  border-color:#fff
}

.pannello {
  position:relative;
  text-align:center;
  white-space: nowrap;                 /*  make buttons stay on 1 line  */
  left: 50%;                           /*  position its left edge in the middle  */
  top: 50vh;                           /*  position its top edge in the middle */
  transform: translate(-50%,-50%);     /*  move left/top back half its own width/height  */
}

.rosso {
  color:#ff0c0c;
  border-color:#ff0c0c
}
.rosso:before, .rosso:after  {
  border-color:#ff0c0c
}
.rosso:hover:before, .rosso:hover:after {
  border-color:#ff0c0c;
}
.rosso:hover {
  color:#fff;
  background-color:#ff0c0c;
  border-color:#ff0c0c;
}

.bianco {
  color:#e8e8e8;
  border-color:#e8e8e8
}
.bianco:before, .bianco:after  {
  border-color:#e8e8e8
}
.bianco:hover:before, .bianco:hover:after {
  border-color:#e8e8e8;
}
.bianco:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.verde {
  color:#e8e8e8;
  border-color:#e8e8e8
}
.verde:before, .bianco:after  {
  border-color:#e8e8e8
}
.verde:hover:before, .bianco:hover:after {
  border-color:#e8e8e8;
}
.verde:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

<body>
  <div class="pannello">
    <button class="rosso">TS3</button>
    <button class="bianco">FORUM</button>
    <button class="verde">BUYCRAFT</button>
  </div>
</body>


问:
Putting image in table using innerHTML (Javascript / Html)
Alright, some information right off the bat, I have a table that is dynamically being created.
The table looks roughly like this :

|item__  | price | category | category | category | category | picture |

|chicken| $20   | _______ |_ ______        | _______        | _______        | 1000.png|

```<code>        var array = csvpls();
        var table = "<tr>";
        for (var i = 0; i < array.length; i++) {
            for (var j = 0; j < array[i].length; j++) {
                if (j == 6) {
                table += "<td>" + "<img src='CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";
                } else if {
                table += "<td>" + array[i][j];
                }
        table += "<tr>";
        table += "</tr>";
        }

    document.getElementById("Invtable").innerHTML = table;
</code>```

This is the code that I have at the moment, where array is a 2D array. And every (6th column in the row, I want it to be an image) When runned, this does not display any table whatsoever.

In the code below

```<code>        var array = csvpls();
        var table = "<tr>";
        for (var i = 0; i < array.length; i++) {
            for (var j = 0; j < array[i].length; j++) {
                table += "<td>" + array[i][j];
                }
        table += "<tr>";
        table += "</tr>";
        }

    document.getElementById("Invtable").innerHTML = table;
</code>```

Without the if statement and the additional img content, the table displays perfectly, but obviously 1000.png shows up instead of the actual image.
CSV_Photos is a folder where the image is stored at, essentially in the same folder. I don't know what is wrong, any help or leads are appreciated.

Edit: So the 2nd part of the code I have works perfectly, It generates a table for me. But at every 6th column of a row is a picture name (1000.png) and its in the folder CSV_Photo. I want it to no display as 1000.png, but instead the picture. The 1st section of code is my attempt to make it an image, but no table is created so I'm guessing there is something wrong with this line table += "" + <"img src= 'CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";

答:
Try:</p>

```<code>    var array = csvpls();
    var table = "<table>";
    for (var i = 0; i < array.length; i++) {
        table += "<tr>";

        for (var j = 0; j < array[i].length; j++) {
            table += "<td>" + array[i][j];
        }

        table += "</tr>";
    }
    table += "</table>";

    document.getElementById("Invtable").innerHTML = table;
</code>```

Body:
Alright, some information right off the bat, I have a table that is dynamically being created.
The table looks roughly like this :

|item__  | price | category | category | category | category | picture |

|chicken| $20   | _______ |_ ______        | _______        | _______        | 1000.png|

        var array = csvpls();
        var table = "
";
        for (var i = 0; i < array.length; i++) {
            for (var j = 0; j < array[i].length; j++) {
                if (j == 6) {
                table += "" + "";
                } else if {
                table += "" + array[i][j];
                }
        table += "
";
        table += "
";
        }

    document.getElementById("Invtable").innerHTML = table;

This is the code that I have at the moment, where array is a 2D array. And every (6th column in the row, I want it to be an image) When runned, this does not display any table whatsoever.

In the code below

        var array = csvpls();
        var table = "
";
        for (var i = 0; i < array.length; i++) {
            for (var j = 0; j < array[i].length; j++) {
                table += "" + array[i][j];
                }
        table += "
";
        table += "
";
        }

    document.getElementById("Invtable").innerHTML = table;

Without the if statement and the additional img content, the table displays perfectly, but obviously 1000.png shows up instead of the actual image.
CSV_Photos is a folder where the image is stored at, essentially in the same folder. I don't know what is wrong, any help or leads are appreciated.

Edit: So the 2nd part of the code I have works perfectly, It generates a table for me. But at every 6th column of a row is a picture name (1000.png) and its in the folder CSV_Photo. I want it to no display as 1000.png, but instead the picture. The 1st section of code is my attempt to make it an image, but no table is created so I'm guessing there is something wrong with this line table += "" + <"img src= 'CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";

Body:
Try:

    var array = csvpls();
    var table = "<table>";
    for (var i = 0; i < array.length; i++) {
        table += "<tr>";

        for (var j = 0; j < array[i].length; j++) {
            table += "<td>" + array[i][j];
        }

        table += "</tr>";
    }
    table += "</table>";

    document.getElementById("Invtable").innerHTML = table;


问:
Prolog - Subset
I'm kinda new to Prolog. I'm trying to write a function subset(Set, Subset) that determines if Subset is a subset of Set (duh). Also, if the second parameter is not instantiated, it should output every possible subset. Right now, it works when both parameters are instantiated, but when I'm trying to output all subsets, it runs into a problem with member/2. For example:

```<code>?- subset([1,2,3], S).
S = [];
S = [1];
S = [1, 1];
S = [1, 1, 1];
...
</code>```

Here is my code:

```<code>% subset/2
% subset(Set, Subset) iff Subset is a subset of Set
subset(_, []).
subset(Set, [H|T]) :-
  member(H, Set),
  subset(Set, T).
</code>```

How do I make it so that member doesn't keep picking the first option in Set?

答:
To enumerate subsets, I don't think its necessary to also generate permutations, after all a set shouldn't care about ordering. So the typical text book solution is:

```<code>% subset(-Set, +Set)
subset([X|L], [X|R]) :-
   subset(L, R).
subset(L, [_|R]) :-
   subset(L, R).
subset([], []).
</code>```

Compare this with the other solutions:

This solution:

```<code>?- subset(X, [1,2,3]), write(X), nl, fail; true.
[1,2,3]
[1,2]
[1,3]
[1]
[2,3]
[2]
[3]
[]
</code>```

The others capellis solution:

```<code>?- subset([1,2,3], X), write(X), nl, fail; true.
[]
[1]
[1,2]
[1,2,3]
[1,3]
[1,3,2]
[2]
[2,1]
[2,1,3]
[2,3]
[2,3,1]
[3]
[3,1]
[3,1,2]
[3,2]
[3,2,1]
</code>```

From set theory we know |P(A)|=2^|A|, so for 3 element long input subset should generate 8 subsets. This is what this solution does, but other solutions enumerate way to many redundant subsets.

Title: Prolog - Subset

Body:
I'm kinda new to Prolog. I'm trying to write a function subset(Set, Subset) that determines if Subset is a subset of Set (duh). Also, if the second parameter is not instantiated, it should output every possible subset. Right now, it works when both parameters are instantiated, but when I'm trying to output all subsets, it runs into a problem with member/2. For example:

?- subset([1,2,3], S).
S = [];
S = [1];
S = [1, 1];
S = [1, 1, 1];
...

Here is my code:

% subset/2
% subset(Set, Subset) iff Subset is a subset of Set
subset(_, []).
subset(Set, [H|T]) :-
  member(H, Set),
  subset(Set, T).

How do I make it so that member doesn't keep picking the first option in Set?

Body:
To enumerate subsets, I don't think its necessary to also generate permutations, after all a set shouldn't care about ordering. So the typical text book solution is:

% subset(-Set, +Set)
subset([X|L], [X|R]) :-
   subset(L, R).
subset(L, [_|R]) :-
   subset(L, R).
subset([], []).

Compare this with the other solutions:

This solution:

?- subset(X, [1,2,3]), write(X), nl, fail; true.
[1,2,3]
[1,2]
[1,3]
[1]
[2,3]
[2]
[3]
[]

The others capellis solution:

?- subset([1,2,3], X), write(X), nl, fail; true.
[]
[1]
[1,2]
[1,2,3]
[1,3]
[1,3,2]
[2]
[2,1]
[2,1,3]
[2,3]
[2,3,1]
[3]
[3,1]
[3,1,2]
[3,2]
[3,2,1]

From set theory we know |P(A)|=2^|A|, so for 3 element long input subset should generate 8 subsets. This is what this solution does, but other solutions enumerate way to many redundant subsets.


问:
Add items if equal to (XML feed reading)
i am reading an XML feed  and adding results like this:

```<code> XElement _xml;
        try
        {
            if (!e.Cancelled)
            {
                _xml = XElement.Parse(e.Result);
                Results.Items.Clear();
                foreach (XElement value in _xml.Elements("runner").Elements("rr_event"))
                {
                    FeedItem _item = new FeedItem();
                    _item.Title = value.Element("title").Value;
                    _item.Description = Regex.Replace(value.Element("description").Value,
                    @"<(.|\n)*?>", String.Empty);
                    _item.Sector = value.Element("sector").Value;

   Results.Items.Add(_item);

                }
            }
        }
</code>```

My aim is to only add to Results if the XML tag "Sector" text equals to "A"

Many thanks. Dan

答:
Totally agree with vortex, just add if("A".equals(_item.Sector)).

```<code> XElement _xml;
        try
        {
            if (!e.Cancelled)
            {
                _xml = XElement.Parse(e.Result);
                Results.Items.Clear();
                foreach (XElement value in _xml.Elements("runner").Elements("rr_event"))
                {
                    FeedItem _item = new FeedItem();
                    _item.Title = value.Element("title").Value;
                    _item.Description = Regex.Replace(value.Element("description").Value,
                    @"<(.|\n)*?>", String.Empty);
                    _item.Sector = value.Element("sector").Value;

                    if("A".equals(_item.Sector)) Results.Items.Add(_item);
                }
            }
        }
</code>```

This should do it.

Body:
i am reading an XML feed  and adding results like this:

 XElement _xml;
        try
        {
            if (!e.Cancelled)
            {
                _xml = XElement.Parse(e.Result);
                Results.Items.Clear();
                foreach (XElement value in _xml.Elements("runner").Elements("rr_event"))
                {
                    FeedItem _item = new FeedItem();
                    _item.Title = value.Element("title").Value;
                    _item.Description = Regex.Replace(value.Element("description").Value,
                    @"<(.|\n)*?>", String.Empty);
                    _item.Sector = value.Element("sector").Value;

   Results.Items.Add(_item);

                }
            }
        }

My aim is to only add to Results if the XML tag "Sector" text equals to "A"

Many thanks. Dan

Body:
Totally agree with vortex, just add if("A".equals(_item.Sector)).

 XElement _xml;
        try
        {
            if (!e.Cancelled)
            {
                _xml = XElement.Parse(e.Result);
                Results.Items.Clear();
                foreach (XElement value in _xml.Elements("runner").Elements("rr_event"))
                {
                    FeedItem _item = new FeedItem();
                    _item.Title = value.Element("title").Value;
                    _item.Description = Regex.Replace(value.Element("description").Value,
                    @"<(.|\n)*?>", String.Empty);
                    _item.Sector = value.Element("sector").Value;

                    if("A".equals(_item.Sector)) Results.Items.Add(_item);
                }
            }
        }

This should do it.


问:
how to distribute items in number of lists?
Question: How to distribute items in number of lists? following are examples:

Imagine I have a 8 lists, and 5 items. in this case list 1 to 5 will have 1 item.  rest of lists remain empty.

Now If I have 8 lists and 16 items each list will have 2 items.

If I have 8 lists and 11 items, list 1 to 3 will have two items. rest of the lists will have 1 item.

```<code>var items = new List<object>();
var containers = new List<List<object>>();

int c = -1; // indexer for container.

for(int i = 0; i < items.Count; i++)
{
    // disturbute items to containers

    if (i % (items.Count/containers.Count) == 0) c++; // this is wrong. when to increment?

    containers[c].Add(items[i]);
}
</code>```

I'm pretty sure only if statement is wrong. Its getting confusing how to handle i.

答:
Think about the algorithm. When inserting item, you insert it to a list and then move to next one. When reaching last list, start inserting back to the first. Code (written in notepad, so may not compile):

```<code>var items = new List<object>();
var containers = new List<List<object>>();

int c = 0;

for (int i = 0; i < items.Count; i++)
{
    c++; // move to next container

    // when reached to the end, insert again to first list
    if (c == containers.Count)
    {
        c = 0;
    }
    containers[c].Add(items[i]);
}
</code>```

This can be made a bit shorter:

```<code>var items = new List<object>();
var containers = new List<List<object>>();

int c = 0;
foreach (int item in items)
{
    c = (c == containers.Count - 1) ? 0 : c + 1;
    containers[c].Add(item);
}
</code>```

Body:
Question: How to distribute items in number of lists? following are examples:

Imagine I have a 8 lists, and 5 items. in this case list 1 to 5 will have 1 item.  rest of lists remain empty.

Now If I have 8 lists and 16 items each list will have 2 items.

If I have 8 lists and 11 items, list 1 to 3 will have two items. rest of the lists will have 1 item.

var items = new List<object>();
var containers = new List<List<object>>();

int c = -1; // indexer for container.

for(int i = 0; i < items.Count; i++)
{
    // disturbute items to containers

    if (i % (items.Count/containers.Count) == 0) c++; // this is wrong. when to increment?

    containers[c].Add(items[i]);
}

I'm pretty sure only if statement is wrong. Its getting confusing how to handle i.

Body:
Think about the algorithm. When inserting item, you insert it to a list and then move to next one. When reaching last list, start inserting back to the first. Code (written in notepad, so may not compile):

var items = new List<object>();
var containers = new List<List<object>>();

int c = 0;

for (int i = 0; i < items.Count; i++)
{
    c++; // move to next container

    // when reached to the end, insert again to first list
    if (c == containers.Count)
    {
        c = 0;
    }
    containers[c].Add(items[i]);
}

This can be made a bit shorter:

var items = new List<object>();
var containers = new List<List<object>>();

int c = 0;
foreach (int item in items)
{
    c = (c == containers.Count - 1) ? 0 : c + 1;
    containers[c].Add(item);
}


问:
SweetAlert: Missing title argument
I'm using sweet alert and i've got the following error when the error function is called from sweet alert. It works fine when the operation from the php files is successful. How can solve this problem? Many thanks

```<code>SweetAlert: Missing "title" argument!
</code>```

This is my javascript code

```<code>function DeletePost() {
    swal({
        title: "Sei Sicuro?",
        text: "Questa operazione non è reversibile ed eliminerà la comunicazione i commenti ad essa connessi dal database!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Si, elimina comunicazione!",
        cancelButtonClass: "btn btn-danger",
        cancelButtonText: "No, non procedere!",
        closeOnConfirm: false,
        closeOnCancel: false
    }, function(isConfirm) {
        if (isConfirm) {

            $.ajax({
                url: "../delete_all.php",
                method: "POST",
                dataType: 'json',

                success: function(response) {
                  // swal('Deleted!', response.message, response.status);
                    swal({

                      title: response.title,
                      text: response.message,
                      type: response.status

                    },

                    function(){

                      location.reload();

                    }

                  );

                },

                error: function(response) {

                  swal({

                      title: response.title,
                      text: response.message,
                      type: response.status

                    });

                }

            });

        } else {
            swal("Annulato!", "Operazione annullata con successo!", "error");
        }
    });
}
</code>```

And this is my php file

```<code>if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Prelevo l'id dell'amministratore e lo passo ad una variabile
    $userid = $_SESSION['user_id'];

    if($delete_inbox  = mysqli_prepare($conn, "DELETE FROM user_inbox where user_inbox_user=? AND user_inbox_status = 'trash'")){

           mysqli_stmt_bind_param($delete_inbox, 'i', $userid);
           mysqli_stmt_execute($delete_inbox);
           mysqli_stmt_close($delete_inbox);

    // Passo messaggio di risposta se l'operazione è andata a buon fine
    $response['title']  = 'Messaggi eliminati!';
    $response['message'] = 'Tutti i messaggi sono stati eliminati con successo.';
    $response['status']  = 'success';

    }else{

    // Passo messaggio di risposta se l'operazione non è andata a buon fine
    $response['title']  = 'Si è verificato un errore!';
    $response['message'] = 'Non è stato possibile eliminare i messaggi. Per favore contatta amministratore di sistema';
    $response['status']  = 'error';

    }

    echo json_encode($response);

}
</code>```

答:
You forgot to convert json's response to javascript object

So it should be all right

```<code> $.ajax({
      url: "../delete_all.php",
      method: "POST",
      dataType: 'json',
      success: function(response) {
         // swal('Deleted!', response.message, response.status);

         response= JSON.parse(response);

         swal({
            title: response.title,
                  ...
</code>```

I added this line

```<code>  response= JSON.parse(response);
</code>```

Title: SweetAlert: Missing title argument

Body:
I'm using sweet alert and i've got the following error when the error function is called from sweet alert. It works fine when the operation from the php files is successful. How can solve this problem? Many thanks

SweetAlert: Missing "title" argument!

This is my javascript code

function DeletePost() {
    swal({
        title: "Sei Sicuro?",
        text: "Questa operazione non è reversibile ed eliminerà la comunicazione i commenti ad essa connessi dal database!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Si, elimina comunicazione!",
        cancelButtonClass: "btn btn-danger",
        cancelButtonText: "No, non procedere!",
        closeOnConfirm: false,
        closeOnCancel: false
    }, function(isConfirm) {
        if (isConfirm) {

            $.ajax({
                url: "../delete_all.php",
                method: "POST",
                dataType: 'json',

                success: function(response) {
                  // swal('Deleted!', response.message, response.status);
                    swal({

                      title: response.title,
                      text: response.message,
                      type: response.status

                    },

                    function(){

                      location.reload();

                    }

                  );

                },

                error: function(response) {

                  swal({

                      title: response.title,
                      text: response.message,
                      type: response.status

                    });

                }

            });

        } else {
            swal("Annulato!", "Operazione annullata con successo!", "error");
        }
    });
}

And this is my php file

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Prelevo l'id dell'amministratore e lo passo ad una variabile
    $userid = $_SESSION['user_id'];

    if($delete_inbox  = mysqli_prepare($conn, "DELETE FROM user_inbox where user_inbox_user=? AND user_inbox_status = 'trash'")){

           mysqli_stmt_bind_param($delete_inbox, 'i', $userid);
           mysqli_stmt_execute($delete_inbox);
           mysqli_stmt_close($delete_inbox);

    // Passo messaggio di risposta se l'operazione è andata a buon fine
    $response['title']  = 'Messaggi eliminati!';
    $response['message'] = 'Tutti i messaggi sono stati eliminati con successo.';
    $response['status']  = 'success';

    }else{

    // Passo messaggio di risposta se l'operazione non è andata a buon fine
    $response['title']  = 'Si è verificato un errore!';
    $response['message'] = 'Non è stato possibile eliminare i messaggi. Per favore contatta amministratore di sistema';
    $response['status']  = 'error';

    }

    echo json_encode($response);

}

Body:
You forgot to convert json's response to javascript object

So it should be all right

 $.ajax({
      url: "../delete_all.php",
      method: "POST",
      dataType: 'json',
      success: function(response) {
         // swal('Deleted!', response.message, response.status);

         response= JSON.parse(response);

         swal({
            title: response.title,
                  ...

I added this line

  response= JSON.parse(response);