问:
For comma-separated
I'm new to RegEx and JavaScript and I was wondering if anyone knew what the RegEx would be for detecting whether or not an input field contained the following type of format:

At least one alphanumeric tag which can contain spaces (e.g. "Test Tag" but not "Test@Tag")

Each tag separated by a single comma (e.g. "Cars, Vehicle, Large Dog, Bed" but not "Cars, Vehicle, Tiger)

An example of what I mean is this, these would be valid tags:

```<code>boy, man,girl, woman,tyrannosaurus rex, lion
</code>```

And these would be invalid tags:

```<code>hat, cat, rat, c3po, @gmail
</code>```

Because there are invalid characters in "@gmail".

It should also be able to accept just a single tag, as long as the characters are alphanumeric.

答:
Assuming that underscores (_) are not invalid:

```<code>/^(\w+\s?[\w\s]*)(,\s*\w+\s?[\w\s]*)*$/

Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match the regular expression below and capture its match into backreference number 1 «(\w+\s?[\w\s]*)»
   Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s?»
      Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
   Match a single character present in the list below «[\w\s]*»
      Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
      A word character (letters, digits, and underscores) «\w»
      A whitespace character (spaces, tabs, and line breaks) «\s»
Match the regular expression below and capture its match into backreference number 2 «(,\s*\w+\s?[\w\s]*)*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
   Note: You repeated the capturing group itself.
   The group will capture only the last iteration.
   Put a capturing group around the repeated group to capture all iterations. «*»
   Match the character “,” literally «,»
   Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s*»
      Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
   Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s?»
      Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
   Match a single character present in the list below «[\w\s]*»
      Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
      A word character (letters, digits, and underscores) «\w»
      A whitespace character (spaces, tabs, and line breaks) «\s»
Assert position at the end of a line (at the end of the string or before a line break character) «$»

Created with RegexBuddy
</code>```

Title: For comma-separated

Body:
I'm new to RegEx and JavaScript and I was wondering if anyone knew what the RegEx would be for detecting whether or not an input field contained the following type of format:

At least one alphanumeric tag which can contain spaces (e.g. "Test Tag" but not "Test@Tag")

Each tag separated by a single comma (e.g. "Cars, Vehicle, Large Dog, Bed" but not "Cars, Vehicle, Tiger)

An example of what I mean is this, these would be valid tags:

boy, man,girl, woman,tyrannosaurus rex, lion

And these would be invalid tags:

hat, cat, rat, c3po, @gmail

Because there are invalid characters in "@gmail".

It should also be able to accept just a single tag, as long as the characters are alphanumeric.

Body:
Assuming that underscores (_) are not invalid:

/^(\w+\s?[\w\s]*)(,\s*\w+\s?[\w\s]*)*$/

Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match the regular expression below and capture its match into backreference number 1 «(\w+\s?[\w\s]*)»
   Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s?»
      Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
   Match a single character present in the list below «[\w\s]*»
      Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
      A word character (letters, digits, and underscores) «\w»
      A whitespace character (spaces, tabs, and line breaks) «\s»
Match the regular expression below and capture its match into backreference number 2 «(,\s*\w+\s?[\w\s]*)*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
   Note: You repeated the capturing group itself.
   The group will capture only the last iteration.
   Put a capturing group around the repeated group to capture all iterations. «*»
   Match the character “,” literally «,»
   Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s*»
      Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
   Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s?»
      Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
   Match a single character present in the list below «[\w\s]*»
      Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
      A word character (letters, digits, and underscores) «\w»
      A whitespace character (spaces, tabs, and line breaks) «\s»
Assert position at the end of a line (at the end of the string or before a line break character) «$»

Created with RegexBuddy


来源: stackexchange

问:
Create new element in cheerio
What is the best way to create a new element in cheerio?

May be:

```<code>cheerio.load('<li>something in here!</li>')
</code>```

or

```<code>$('li', '<li>bla, bla, bla, ...</li>')
</code>```

答:
Neither load nor the context string actually create HTML. They serve as a starting point for creating a virtual DOM.

Refer to the Manipulation section in the documentation for methods of injecting into the DOM. Namely, the following methods are provided for injection:

append

appendTo

prepend

prependTo

after

insertAfter

before

insertBefore

replaceWith

html

wrap

ContentLicense: CC BY-SA 3.0

Title: Create new element in cheerio

Body:
What is the best way to create a new element in cheerio?

May be:

cheerio.load('
something in here!
')

or

$('li', '
bla, bla, bla, ...
')

ContentLicense: CC BY-SA 4.0


问:
c# WCF REST DATETIME displayed as /Date(1462399200000+0200)
I have a .mdf database which looks like this:
Table kosarica:

[datum_zakljucenega_nakupa] DATETIME NULL,
and other values which are not important right now.

In my model I have a :

```<code>[DataMember]
public DateTime datum_zakljucenega_nakupa{get;set;}
</code>```

This is in my Service1.SVC

```<code> public List<Kosarica> Kosarica()
        {
            using (SqlConnection myConn = new SqlConnection(connection))
            {
                myConn.Open();

                SqlCommand cmd = new SqlCommand("SELECT * FROM Kosarica;", myConn);
                SqlDataReader rdr = cmd.ExecuteReader();
                List<Kosarica> kosarice = new List<Kosarica>();

                while (rdr.Read())
                {
                    Kosarica k = new Kosarica();
                    k.Id = (int)rdr["Id"];

                   k.datum_zakljucenega_nakupa = (DateTime)rdr["datum_zakljucenega_nakupa"];

                    kosarice.Add(k);
                }
                myConn.Close();
                return kosarice;

            }

        }
</code>```

There are other values in here which are not important right now. When I run Postman all other values display correctly except for the datetime which shows:
/Date(1462399200000+0200)

I have tried parsing it with various ways, but it didn't work. The "datetime" which postman returns is in milliseconds.

答:
Send the DateTime as a formatted string, you need to edit your model:

Example:

```<code>k.datum_zakljucenega_nakupa = ((DateTime)rdr["datum_zakljucenega_nakupa"]).toString("dd-MM-YYYY");
</code>```

Body:
I have a .mdf database which looks like this:
Table kosarica:

[datum_zakljucenega_nakupa] DATETIME NULL,
and other values which are not important right now.

In my model I have a :

[DataMember]
public DateTime datum_zakljucenega_nakupa{get;set;}

This is in my Service1.SVC

 public List<Kosarica> Kosarica()
        {
            using (SqlConnection myConn = new SqlConnection(connection))
            {
                myConn.Open();

                SqlCommand cmd = new SqlCommand("SELECT * FROM Kosarica;", myConn);
                SqlDataReader rdr = cmd.ExecuteReader();
                List<Kosarica> kosarice = new List<Kosarica>();

                while (rdr.Read())
                {
                    Kosarica k = new Kosarica();
                    k.Id = (int)rdr["Id"];

                   k.datum_zakljucenega_nakupa = (DateTime)rdr["datum_zakljucenega_nakupa"];

                    kosarice.Add(k);
                }
                myConn.Close();
                return kosarice;

            }

        }

There are other values in here which are not important right now. When I run Postman all other values display correctly except for the datetime which shows:
/Date(1462399200000+0200)

I have tried parsing it with various ways, but it didn't work. The "datetime" which postman returns is in milliseconds.

Body:
Send the DateTime as a formatted string, you need to edit your model:

Example:

k.datum_zakljucenega_nakupa = ((DateTime)rdr["datum_zakljucenega_nakupa"]).toString("dd-MM-YYYY");


问:
Send file via cURL from form POST in PHP
I'm writing an API and I'm wanting to handle file uploads from a form POST. The markup for the form is nothing too complex:

```<code><form action="" method="post" enctype="multipart/form-data">
  <fieldset>
    <input type="file" name="image" id="image" />
    <input type="submit" name="upload" value="Upload" />
  </fieldset>
</form>
</code>```

However, I'm having difficulties understanding how to handle this server-side and send along with a cURL request.

I'm familiar with sending POST requests with cURL with a data array, and resources I've read on uploading files tell me to prefix the filename with an @ symbol. But these same resources have a hard-coded file name, e.g.

```<code>$post = array(
    'image' => '@/path/to/myfile.jpg',
    ...
);
</code>```

Well which file path is this? Where would I find it? Would it be something like $_FILES['image']['tmp_name'], in which case my $post array should look like this:

```<code>$post = array(
    'image' => '@' . $_FILES['image']['tmp_name'],
    ...
);
</code>```

Or am I going about this the wrong way? Any advice would be most appreciated.

EDIT: If someone could give me a code snippet of where I would go with the following code snippets then I'd be most grateful. I'm mainly after what I would send as cURL parameters, and a sample of how to use those parameters with the receiving script (let's call it curl_receiver.php for argument's sake).

I have this web form:

```<code><form action="script.php" method="post" enctype="multipart/form-data">
  <fieldset>
    <input type="file" name="image />
    <input type="submit" name="upload" value="Upload" />
  </fieldset>
</form>
</code>```

And this would be script.php:

```<code>if (isset($_POST['upload'])) {
    // cURL call would go here
    // my tmp. file would be $_FILES['image']['tmp_name'], and
    // the filename would be $_FILES['image']['name']
}
</code>```

答:
Here is some production code that sends the file to an ftp (may be a good solution for you):</p>

```<code>// This is the entire file that was uploaded to a temp location.
$localFile = $_FILES[$fileKey]['tmp_name'];

$fp = fopen($localFile, 'r');

// Connecting to website.
$ch = curl_init();

curl_setopt($ch, CURLOPT_USERPWD, "email@email.org:password");
curl_setopt($ch, CURLOPT_URL, 'ftp://@ftp.website.net/audio/' . $strFileName);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 86400); // 1 Day Timeout
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'CURL_callback');
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localFile));
curl_exec ($ch);

if (curl_errno($ch)) {

    $msg = curl_error($ch);
}
else {

    $msg = 'File uploaded successfully.';
}

curl_close ($ch);

$return = array('msg' => $msg);

echo json_encode($return);
</code>```

Body:
I'm writing an API and I'm wanting to handle file uploads from a form POST. The markup for the form is nothing too complex:

<form action="" method="post" enctype="multipart/form-data">
  <fieldset>
    <input type="file" name="image" id="image" />
    <input type="submit" name="upload" value="Upload" />
  </fieldset>
</form>

However, I'm having difficulties understanding how to handle this server-side and send along with a cURL request.

I'm familiar with sending POST requests with cURL with a data array, and resources I've read on uploading files tell me to prefix the filename with an @ symbol. But these same resources have a hard-coded file name, e.g.

$post = array(
    'image' => '@/path/to/myfile.jpg',
    ...
);

Well which file path is this? Where would I find it? Would it be something like $_FILES['image']['tmp_name'], in which case my $post array should look like this:

$post = array(
    'image' => '@' . $_FILES['image']['tmp_name'],
    ...
);

Or am I going about this the wrong way? Any advice would be most appreciated.

EDIT: If someone could give me a code snippet of where I would go with the following code snippets then I'd be most grateful. I'm mainly after what I would send as cURL parameters, and a sample of how to use those parameters with the receiving script (let's call it curl_receiver.php for argument's sake).

I have this web form:

<form action="script.php" method="post" enctype="multipart/form-data">
  <fieldset>
    <input type="file" name="image />
    <input type="submit" name="upload" value="Upload" />
  </fieldset>
</form>

And this would be script.php:

if (isset($_POST['upload'])) {
    // cURL call would go here
    // my tmp. file would be $_FILES['image']['tmp_name'], and
    // the filename would be $_FILES['image']['name']
}

Body:
Here is some production code that sends the file to an ftp (may be a good solution for you):

// This is the entire file that was uploaded to a temp location.
$localFile = $_FILES[$fileKey]['tmp_name'];

$fp = fopen($localFile, 'r');

// Connecting to website.
$ch = curl_init();

curl_setopt($ch, CURLOPT_USERPWD, "email@email.org:password");
curl_setopt($ch, CURLOPT_URL, 'ftp://@ftp.website.net/audio/' . $strFileName);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 86400); // 1 Day Timeout
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'CURL_callback');
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localFile));
curl_exec ($ch);

if (curl_errno($ch)) {

    $msg = curl_error($ch);
}
else {

    $msg = 'File uploaded successfully.';
}

curl_close ($ch);

$return = array('msg' => $msg);

echo json_encode($return);


问:
How to convert day,month,year into date format?
I have been trying to run a python script that converts day,month,year into date format.

I have attempted the following script;

```<code># dateconvert2.py
# Converts day month and year numbers into two date formats

def main():
    # get the day month and year
    day, month, year = eval(input("Please enter day, month, year numbers: "))

    date1 = str(month)+"/"+str(day)+"/"+str(year)

    months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Novemeber", "December"]
    monthStr = months[month-1]
    date2 = monthStr+" " + str(day) + ", " + str(year)

    print("The date is", date1, "or", date2+ ".")
main()
</code>```

The result should look like;

```<code>>>> Please enter day, month,  and year numbers: 24, 5, 2003
The date is 5/24/2003 or May 24, 2003.
</code>```

As I ran the program, an error appeared saying that the line;

```<code>    monthStr = months[month-1]
</code>```

had an index error.

What can I do to improve this? Please help

答:
```<code>day, month, year = eval(input("Please enter day, month, year numbers: "))
</code>```

eval() is unnecessary here, assuming your user knows to separate with commas you can just use:

```<code>day, month, year = input("Please enter comma seperated day, month, year numbers: ")
</code>```

may only work in 2.x see comments below, sorry for confusion

then regarding inputs you should validate your data:

```<code>if 1 <= month <= 12:
    if (month in [1,3,5,7,8,10,12]) and (day != 31):
        print 'error'
    elif (month in [4,6,9,11]) and (day != 30):
        print 'error'
    elif (month==2) and (day not in [28,29]):
        print 'error'
else:
    print 'error'
</code>```

Body:
I have been trying to run a python script that converts day,month,year into date format.

I have attempted the following script;

# dateconvert2.py
# Converts day month and year numbers into two date formats

def main():
    # get the day month and year
    day, month, year = eval(input("Please enter day, month, year numbers: "))

    date1 = str(month)+"/"+str(day)+"/"+str(year)

    months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Novemeber", "December"]
    monthStr = months[month-1]
    date2 = monthStr+" " + str(day) + ", " + str(year)

    print("The date is", date1, "or", date2+ ".")
main()

The result should look like;

>>> Please enter day, month,  and year numbers: 24, 5, 2003
The date is 5/24/2003 or May 24, 2003.

As I ran the program, an error appeared saying that the line;

    monthStr = months[month-1]

had an index error.

What can I do to improve this? Please help

Body:
day, month, year = eval(input("Please enter day, month, year numbers: "))

eval() is unnecessary here, assuming your user knows to separate with commas you can just use:

day, month, year = input("Please enter comma seperated day, month, year numbers: ")

may only work in 2.x see comments below, sorry for confusion

then regarding inputs you should validate your data:

if 1 <= month <= 12:
    if (month in [1,3,5,7,8,10,12]) and (day != 31):
        print 'error'
    elif (month in [4,6,9,11]) and (day != 30):
        print 'error'
    elif (month==2) and (day not in [28,29]):
        print 'error'
else:
    print 'error'


问:
javascript how to use same random value in array
var myName = ['Beth', 'Chris', 'Carl', 'April', 'Cinnamon','Ethan'];

I want to be able to pick a number or name from an array and use that same value again? I am using javascript

答:
You can use random Math function. If your array has 6 elements. you can use the below JavaScript.</p>

```<code>myName[Math.floor(Math.random()*6)]
</code>```

Body:
You can use random Math function. If your array has 6 elements. you can use the below JavaScript.

myName[Math.floor(Math.random()*6)]


问:
HTA as a Command Line GUI
I'm in a bit of a bind...
I'm trying to use HTA as a GUI to run some command line utilities in a more modern way...except it's not quite going as I'd hoped.

So far I've tried a few tricks to get what I want done, but each one is falling a bit short of what I'm aiming for.

My goal is to have my script run an exe that executes as a command line tool and capture the output in realtime, parse each line as it happens, and show something in the HTA window to indicate what the tool is doing behind the scenes, such as a progress bar or some kind of fancy formatted log output, rather than the console text of the cmd window.

The trouble is, the only way I've seen to get HTA to run another program is either the .Run or .Exec functions of WScript.Shell.  Each has its own headache attached that keeps my GUI from doing its job.
.Exec seemed to be what I wanted at first, since my intention is to capture the stdout from the command line and parse each line as it prints, but when I tried to use it, I noticed a big blank CMD window appearing and blocking most of the screen until the exe finished running.  Yes, the HTA captured the output and responded as I was hoping, but that blank CMD window kinda defeats the purpose of making a GUI.
I tried .Run, but while that lets me run the exe in a hidden window, I can't capture the stdout in realtime and at best I can only dump it into a txt file and try to read it after the fact.

Needless to say, neither is quite what I'm looking for...

As a real world(ish) example of what I'd be looking to create, imagine running an HTA that runs ping with like 10 pings. I want to show a progress bar to show how many pings have completed, with some text showing an average total of each ping as they're happening, like how many pings were successful vs timed out, what the average ms per hit was, and so on.  Then when the ping tool finishes running, the HTA would remove the progress bar and show the final totals for the ping test.
With .Exec, this technically works, but the entire time I have a command window sitting somewhere on the screen, which is annoying and usually blocks the HTA.
With .Run, the HTA just appears to hang while the 10 pings run, and only gets the returned error code of 0, and then I have to load up a text file to see what happened before finally showing the results in the HTA...definitely not the ideal result.

I feel like I'm missing something important... how can I get an HTA to run a command line executable in a hidden window while still being able to capture the output line by line in realtime? (I don't mind semi-realtime with JScript setTimeout or similar) I want to avoid having the command prompt window appearing at all, and I want to be able to show the output in the GUI as it's happening, rather than having to wait for it to complete and waste time writing a file, reading it, then deleting it.

答:
If you start a Exec operation from a cscript running inside a hidden console, the started process will be also hidden. But this does not happen from .hta, the Exec method creates a console attached to the process executed and there is no way to hide it without third party code.

So, the usual way to deal with command output parsing is to redirect the output to a file and then read the file, of course losing the option to write into the StdIn stream of the started process.

To redirect the output of a process to a file, the first idea is to use something like

```<code>>"outputFile" command
</code>```

but the problem is that trying to execute this directly will not work. This redirection is not part of the OS, but an operator of cmd.exe, so, we need to run something like

```<code>cmd /c" >"outputFile" command "
</code>```

We will also need a way to know if the process has ended and no more data will be available. We can use the Wait argument of the Run method, but this will leave the .hta interface freezed, blocked by the Run method.

Without been able to use the Wait argument, we have to start the process, get its process id and wait for it to end and read all its data or periodically retrieve the output until the process has ended.

You have a basic class (ProcessOutputMonitor) that implements this approach in this test .hta

<title>pingMonitor</title>
<HTA:APPLICATION
    ID="pingMonitor"
    APPLICATIONNAME="pingMonitorHTA"
    MINIMIZEBUTTON="no"
    MAXIMIZEBUTTON="no"
    SINGLEINSTANCE="no"
    SysMenu="no"
    BORDER="thin"
/>

    <input id="checkButton" type="button" value="EXIT" name="run_button" onClick="ExitProgram" align="right">

microsoft	google

```

This will simply start two ping processes, and using  window.setInterval will retrieve each 500ms the output of the two processes and append it (the bad way, just test code) to the output until both processes have ended.

Title: HTA as a Command Line GUI

Body:
If you start a Exec operation from a cscript running inside a hidden console, the started process will be also hidden. But this does not happen from .hta, the Exec method creates a console attached to the process executed and there is no way to hide it without third party code.

So, the usual way to deal with command output parsing is to redirect the output to a file and then read the file, of course losing the option to write into the StdIn stream of the started process.

To redirect the output of a process to a file, the first idea is to use something like

>"outputFile" command

but the problem is that trying to execute this directly will not work. This redirection is not part of the OS, but an operator of cmd.exe, so, we need to run something like

cmd /c" >"outputFile" command "

We will also need a way to know if the process has ended and no more data will be available. We can use the Wait argument of the Run method, but this will leave the .hta interface freezed, blocked by the Run method.

Without been able to use the Wait argument, we have to start the process, get its process id and wait for it to end and read all its data or periodically retrieve the output until the process has ended.

You have a basic class (ProcessOutputMonitor) that implements this approach in this test .hta

<html>
<head>
<title>pingMonitor</title>
<HTA:APPLICATION
    ID="pingMonitor"
    APPLICATIONNAME="pingMonitorHTA"
    MINIMIZEBUTTON="no"
    MAXIMIZEBUTTON="no"
    SINGLEINSTANCE="no"
    SysMenu="no"
    BORDER="thin"
/>
<script type="text/vbscript" >

Class ProcessOutputMonitor

    Dim shell, fso, wmi
    Dim processID, retCode, processQuery
    Dim outputFile, inputFile

    Private Sub Class_Initialize
        Set fso     = CreateObject("Scripting.FileSystemObject")
        Set shell   = CreateObject("WScript.Shell")
        Set wmi     = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
        Set inputFile = Nothing
    End Sub

    Private Sub Class_Terminate
        freeResources
    End Sub

    Public Default Function Start( ByVal commandLine )
    Const SW_HIDE = 0
    Const SW_NORMAL = 1
    Const TemporaryFolder = 2
    Dim startUp

        Start = False
        If Not IsEmpty( processID ) Then Exit Function

        outputFile  = fso.BuildPath( _
            fso.GetSpecialFolder(TemporaryFolder) _
            , Left(CreateObject("Scriptlet.TypeLib").GUID,38) & ".tmp" _
        )

        ' "%comspec%" /c">"outputFile" command arguments "
        commandLine = Join( _
            Array( _
                quote(shell.ExpandEnvironmentStrings("%comspec%")) _
                , "/c"">" & quote(outputFile) _
                , commandLine _
                , """" _
            ) _
            , " " _
        )

        ' https://msdn.microsoft.com/en-us/library/aa394375%28v=vs.85%29.aspx
        Set startUp = wmi.Get("Win32_ProcessStartup").SpawnInstance_
        startUp.ShowWindow = SW_HIDE

        retCode = wmi.Get("Win32_Process").Create( commandLine , Null, startUp, processID )
        If retCode <> 0 Then
            freeResources
            Exit Function
        End If

        processQuery = "SELECT ProcessID From Win32_Process WHERE ProcessID=" & processID

        Start = True
    End Function

    Public Property Get StartReturnCode
        StartReturnCode = retCode
    End Property

    Public Property Get WasStarted
    End Property

    Public Property Get PID
        PID = processID
    End Property

    Public Property Get IsRunning()
        IsRunning = False
        If Not IsEmpty( processID ) Then
            If getWMIProcess() Is Nothing Then
                processID = Empty
                freeResources
            Else
                IsRunning = True
            End If
        End If
    End Property

    Public Property Get NextLine
        NextLine = getFromInputFile("line")
    End Property

    Public Property Get NextData
        NextData = getFromInputFile("all")
    End Property

    Private Function getFromInputFile( what )
    Const ForReading = 1
        getFromInputFile = Empty
        If Not IsEmpty( processID ) Then
            If inputFile Is Nothing Then
                If fso.FileExists( outputFile ) Then
                    Set inputFile = fso.GetFile( outputFile ).OpenAsTextStream( ForReading )
                End If
            End If
            If Not ( inputFile Is Nothing ) Then
                If Not inputFile.AtEndOfStream Then
                    Select Case what
                        Case "line" :   getFromInputFile = inputFile.ReadLine()
                        Case "all"  :   getFromInputFile = inputFile.ReadAll()
                    End Select
                End If
            End If
        End If
    End Function

    Private Function quote( text )
        quote = """" & text & """"
    End Function

    Private Function getWMIProcess()
    Const wbemFlagForwardOnly = 32
    Dim process
        Set getWMIProcess = Nothing
        If Not IsEmpty( processID ) Then
            For Each process In wmi.ExecQuery( processQuery, "WQL", wbemFlagForwardOnly )
                Set getWMIProcess = process
            Next
        End If
    End Function

    Private Sub freeResources()
    Dim process
        Set process = getWMIProcess()
        If Not ( process Is Nothing ) Then
            process.Terminate
        End If
        processID = Empty
        processQuery = Empty
        If Not ( inputFile Is Nothing ) Then
            inputFile.Close
            Set inputFile = Nothing
            fso.DeleteFile outputFile
        End If
    End Sub

End Class

</script>

<SCRIPT LANGUAGE="VBScript">

Dim timerID
Dim monitorGoogle, monitorMicrosoft

Sub Window_onLoad
    window.resizeTo 1024,400
    Set monitorGoogle = New ProcessOutputMonitor
        monitorGoogle.Start "ping -4 www.google.com"
    Set monitorMicrosoft = New ProcessOutputMonitor
        monitorMicrosoft.Start "ping -4 www.microsoft.com"

    timerID = window.setInterval(GetRef("monitorPings"), 500)
End Sub

Sub monitorPings
Dim buffer, keepRunning
    keepRunning = False

    buffer = monitorGoogle.NextData
    If Not IsEmpty( buffer ) Then
        google.innerHTML = google.innerHTML & Replace( buffer, vbCrLf, "<br>" )
        keepRunning = True
    Else
        keepRunning = CBool( keepRunning Or monitorGoogle.IsRunning )
    End If

    buffer = monitorMicrosoft.NextData
    If Not IsEmpty( buffer ) Then
        microsoft.innerHTML = microsoft.innerHTML & Replace( buffer, vbCrLf, "<br>" )
        keepRunning = True
    Else
        keepRunning = CBool( keepRunning Or monitorMicrosoft.IsRunning )
    End If

    If Not keepRunning Then
        window.clearInterval( timerID )
        timerID = Empty
        alert("Done")
    End If

End Sub

Sub ExitProgram
    If Not IsEmpty(timerID) Then window.clearInterval(timerID)
    window.close()
End Sub

</SCRIPT>

</head>

<body>
    <input id="checkButton" type="button" value="EXIT" name="run_button" onClick="ExitProgram" align="right">
<br><br>
    <span id="CurrentTime"></span>
<br><br>
    <table style="width:100%">
        <tr><th style="width:50%;">microsoft</th><th style="width:50%">google</th></tr>
        <tr>
            <td id="microsoft" style="font-family=courier;font-size:0.6em;vertical-align:top;"></td>
            <td id="google" style="font-family=courier;font-size:0.6em;vertical-align:top;"></td>
        </tr>
    </table>

</body>
</html>

This will simply start two ping processes, and using  window.setInterval will retrieve each 500ms the output of the two processes and append it (the bad way, just test code) to the output until both processes have ended.


问:
legend ordering and factor ordering in ggplot2
I have produced the following code:

```<code>#library(tidyverse)
#library(ggplot2)
#library(forcats)

    temp<-tribble(
 ~kt, ~yes, ~'no', ~'NA',
 "Berne", 47,33, 0,
 "Basel", 60,45,0,
 "Geneva", 64,61,0,
 "Zurich", 19,107,3
)

temp2 <- gather(temp, ' ', val, -kt)
ggplot(temp2, aes(kt, val, fill = ` `)) +
  geom_col(position = 'fill', color='darkgrey') +
  geom_text(aes(label = val), position = position_fill(vjust = 0.5), size=3) +
  scale_y_continuous(labels = scales::percent_format())+
  theme_bw()+
  labs(x='Jurisdiction', y='Percentage') +
  coord_flip()+ scale_fill_grey(start = 0.9, end = .5) +
  guides(fill=guide_legend(title="Witnesses heard"))
</code>```

Now I have the following difficulties and would appreciate it if someone could help me:

How can I change the ordering of the legend? The ordering should be just reversed (but the ordering of the barplot is fine).

Obviously the y-Axis (jurisdiction) seems to be ordered alphabetically, but I'd rather have this to be ordered manually (as in the tibble). Unfortunately I did not manage to get this fixed.

Thank you for any advices!

答:
```<code>temp2 <- gather(temp, ' ', val, -kt)
temp2[,2] <- as.factor(temp2[[2]])
temp2[,2] <- factor(temp2$` `, levels = rev(levels(temp2$` `)))

temp2[,1] <- as.factor(temp2[[1]])
temp2[,1] <- factor(temp2$kt, levels = rev(levels(temp2$kt)))

ggplot(temp2, aes(kt, val, fill = ` `)) +
  geom_col(position = 'fill', color='darkgrey') +
  geom_text(aes(label = val), position = position_fill(vjust = 0.5), size=3) +
  scale_y_continuous(labels = scales::percent_format())+theme_bw()+
  labs(x='Jurisdiction', y='Percentage')+coord_flip()+ scale_fill_grey(start = 0.9, end = .5)+
  guides(fill=guide_legend(title="Witnesses heard"))
</code>```

Body:
I have produced the following code:

#library(tidyverse)
#library(ggplot2)
#library(forcats)

    temp<-tribble(
 ~kt, ~yes, ~'no', ~'NA',
 "Berne", 47,33, 0,
 "Basel", 60,45,0,
 "Geneva", 64,61,0,
 "Zurich", 19,107,3
)

temp2 <- gather(temp, ' ', val, -kt)
ggplot(temp2, aes(kt, val, fill = ` `)) +
  geom_col(position = 'fill', color='darkgrey') +
  geom_text(aes(label = val), position = position_fill(vjust = 0.5), size=3) +
  scale_y_continuous(labels = scales::percent_format())+
  theme_bw()+
  labs(x='Jurisdiction', y='Percentage') +
  coord_flip()+ scale_fill_grey(start = 0.9, end = .5) +
  guides(fill=guide_legend(title="Witnesses heard"))

Now I have the following difficulties and would appreciate it if someone could help me:

How can I change the ordering of the legend? The ordering should be just reversed (but the ordering of the barplot is fine).

Obviously the y-Axis (jurisdiction) seems to be ordered alphabetically, but I'd rather have this to be ordered manually (as in the tibble). Unfortunately I did not manage to get this fixed.

Thank you for any advices!


问:
How do I match an element but avoid failing validation if attributes are present?
I have the xml:

```<code><video contenttype="asf" fileextension=".wmv" hascontent="no" lang="en-GB" length="1800" pid="3678738364972" sid="">
  <title>A vid with Pete</title>
  <description>Petes vid</description>
  <contributor>Pete</contributor>
  <subject>Cat 2</subject>
</video>
</code>```

And I want to validate the video element is present using an xsd schema but I really dont care what attributes it has (in fact I want to ignore the attributes). All I care about is the video element being present. Is it possible to do this with xsd?

Currently the xsd is:

```<code><?xml version="1.0" encoding="utf-8"?>

<xs:schema id="UploadXSD"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/UploadXSD.xsd"
    xmlns:mstns="http://tempuri.org/UploadXSD.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="video">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="title" minOccurs="1" type="xs:string"></xs:element>
        <xs:element name="description" type="xs:string"></xs:element>
        <xs:element name="contributor" type="xs:string"></xs:element>
        <xs:element name="subject" type="xs:string"></xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>
</code>```

答: Yes, just specify xs:anyAttribute in your complexType element, after the sequence: here's a link.

Body:
I have the xml:

<video contenttype="asf" fileextension=".wmv" hascontent="no" lang="en-GB" length="1800" pid="3678738364972" sid="">
  <title>A vid with Pete</title>
  <description>Petes vid</description>
  <contributor>Pete</contributor>
  <subject>Cat 2</subject>
</video>

And I want to validate the video element is present using an xsd schema but I really dont care what attributes it has (in fact I want to ignore the attributes). All I care about is the video element being present. Is it possible to do this with xsd?

Currently the xsd is:

<?xml version="1.0" encoding="utf-8"?>

<xs:schema id="UploadXSD"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/UploadXSD.xsd"
    xmlns:mstns="http://tempuri.org/UploadXSD.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="video">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="title" minOccurs="1" type="xs:string"></xs:element>
        <xs:element name="description" type="xs:string"></xs:element>
        <xs:element name="contributor" type="xs:string"></xs:element>
        <xs:element name="subject" type="xs:string"></xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>

ContentLicense: CC BY-SA 2.5


答:
Why would something simple such as this not work. Up  to your to explore the truly "random" aspect of this but likely OK for most things.  Note that arrays are 0 based thus the 0,myName.length-1 parameters.

function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
var myName = ['Beth', 'Chris', 'Carl', 'April', 'Cinnamon','Ethan'];
var randomName = myName[randomIntFromInterval(0,myName.length-1)];
console.log(randomName);```

Title: javascript how to use same random value in array

Body:
var myName = ['Beth', 'Chris', 'Carl', 'April', 'Cinnamon','Ethan'];

I want to be able to pick a number or name from an array and use that same value again? I am using javascript


问:
foreach loop inside variable
Here is a situation I need to display values from array through foreach loop inside variable and than echo that variable inside  HTML table. Thanks in Advance. . I have checked all related links in stackoverflow  some links are given  below.

PHP  simple foreach loop with HTML [closed]

My  question is about store looping array inside a variable.. And their is no similarity in another and my question

I want my output to be this way below

I'm getting this error image given below

php filename: foreachloop.php

```<code>    <?php
$arr = array("Apple","orange","strawberry");
$abc = '<table border="2">
            <tr>
                <th>Names</th>
            </tr>
            foreach($arr as $key){
            <tr>
                <td>'.$key.'</td>
            </tr>
        }
        </table>';

echo $abc;
?>
</code>```

答:
Because, you are messing php and html code

```<code>$arr = array("Apple","orange","strawberry");
$abc = '<table border="2">
            <tr>
                <th>Names</th>
            </tr>';
            foreach($arr as $key){
            $abc.='<tr>
                <td>'.$key.'</td>
            </tr>';
        }
        $abc.='</table>';

echo $abc;
</code>```

Demo

Title: foreach loop inside variable

Body:
Here is a situation I need to display values from array through foreach loop inside variable and than echo that variable inside  HTML table. Thanks in Advance. . I have checked all related links in stackoverflow  some links are given  below.

PHP  simple foreach loop with HTML [closed]

My  question is about store looping array inside a variable.. And their is no similarity in another and my question

I want my output to be this way below

I'm getting this error image given below

php filename: foreachloop.php

    <?php
$arr = array("Apple","orange","strawberry");
$abc = '

                Names

            foreach($arr as $key){

                '.$key.'

        }

';

echo $abc;
?>

Body:
Because, you are messing php and html code

$arr = array("Apple","orange","strawberry");
$abc = '<table border="2">
            <tr>
                <th>Names</th>
            </tr>';
            foreach($arr as $key){
            $abc.='<tr>
                <td>'.$key.'</td>
            </tr>';
        }
        $abc.='</table>';

echo $abc;

Demo


问:
XSLT Generating multiple output
I have an xml document. from that xml I need to generate multiple xml using xslt.
for example.

```<code><Class>
<Student>
<name>First</name>
<age></age>
</Student>
<Student>
<name>Second</name>
<age></age>
</Student>
</Class>.
</code>```

From this xml I need to generate one xml with First student and another with Second student.

答:
You can use this spiltter</p>

```<code><xsl:template match="Class">
        <xsl:for-each select="Student">
                <xsl:result-document href="{position()}.xml" method="xml">
                        <Class>
                                <xsl:copy-of select="."></xsl:copy-of>
                        </Class>
                </xsl:result-document>
        </xsl:for-each>
</xsl:template>
</code>```

Title: XSLT Generating multiple output

Body:
I have an xml document. from that xml I need to generate multiple xml using xslt.
for example.

<Class>
<Student>
<name>First</name>
<age></age>
</Student>
<Student>
<name>Second</name>
<age></age>
</Student>
</Class>.

From this xml I need to generate one xml with First student and another with Second student.

Body:
You can use this spiltter

<xsl:template match="Class">
        <xsl:for-each select="Student">
                <xsl:result-document href="{position()}.xml" method="xml">
                        <Class>
                                <xsl:copy-of select="."></xsl:copy-of>
                        </Class>
                </xsl:result-document>
        </xsl:for-each>
</xsl:template>


问:
JS import - VueJs Router - having trouble refactoring a watch object
This question is specific to vuejs router, however may simply be a misunderstanding of importing js objects and assigning to the window object.

I am watching for url changes on a page which works fine with the watcher code in the component file. I need to use the same watcher code for multiple components so I extracted it to its own file, assigned it to the global scope, and cannot get it to work. Here are the details:

Working code in with the watcher in the component:

```<code> watch:{
            $route () {
                console.log('route changed')
                //was it a reset?

                console.log( this.$route.query.sort)

                if(this.$route.query.sort === undefined){
                    if(this.$route.meta.reset){
                        //reset was pressed... actually do nothing here
                        this.$route.meta['reset'] = false;
                    }
                    else{
                        this.loading = true;
                        this.searchableTable.removeResultsTable();
                        this.searchableTable.options.search_query = this.$route.fullPath;
                        this.searchableTable.updateSearchPage();
                    }

                }
                else
                {
                    //sort change just update the table view
                }

            }
        }
</code>```

So then I extracted the watch to a file routeWatcher.js:

```<code>export default  {
    $route () {
        console.log('route changed')
        //was it a reset?

        console.log(this.$route.query.sort)

        if (this.$route.query.sort === undefined) {
            if (this.$route.meta.reset) {
                //reset was pressed... actually do nothing here
                this.$route.meta['reset'] = false;
            }
            else {
                this.loading = true;
                this.searchableTable.removeResultsTable();
                this.searchableTable.options.search_query = this.$route.fullPath;
                this.searchableTable.updateSearchPage();
            }

        }
        else {
            //sort change just update the table view
        }

    }

}
</code>```

then I import and use, which works fine....

```<code>import searchableTableRouteWatcher from '../../controllers/routeWatcher'
</code>```

...

```<code>watch:searchableTableRouteWatcher
</code>```

again works fine.

Now the problem -  I want to avoid the import in multiple files, so I thought I could put it on the window as a global

in my main.js file:

```<code>import searchableTableRouteWatcher from './controllers/routeWatcher'
window.searchableTableRouteWatcher = searchableTableRouteWatcher;
</code>```

Then in my component:

```<code>watch:searchableTableRouteWatcher
</code>```

results in searchableTableRouteWatcher is not defined

```<code>watch:window.searchableTableRouteWatcher
</code>```

results in no errors, but the code is not being called

I have a feeling it has to do with this and there is confusion on $route()

答:
For your purpose there are 'Mixins' in Vue.js: documentation

What you can do:

create a file, say mixins/index.js:

```<code>export const routeWatcher = {
   watch: {... your watcher code pasted here ... }
};
</code>```

import into your component:

```<code>import { routeWatcher } from 'path/to/mixins/index';
</code>```

add mixin to your component properties and methods:

```<code><script>
   export default {
       mixins: [routeWatcher];
       data () ...... all your original component's script content
   }
</code>```

Mixin's content will be merged with component's original properties and act if it was hardcoded there.

Addition after your comment:

You can also declare Mixin globally, like this:

above 'new Vue' declaration put this code:

```<code>Vue.mixin({
   watch: {....}
});
</code>```

This mixin will appear in every component.

Body:
This question is specific to vuejs router, however may simply be a misunderstanding of importing js objects and assigning to the window object.

I am watching for url changes on a page which works fine with the watcher code in the component file. I need to use the same watcher code for multiple components so I extracted it to its own file, assigned it to the global scope, and cannot get it to work. Here are the details:

Working code in with the watcher in the component:

 watch:{
            $route () {
                console.log('route changed')
                //was it a reset?

                console.log( this.$route.query.sort)

                if(this.$route.query.sort === undefined){
                    if(this.$route.meta.reset){
                        //reset was pressed... actually do nothing here
                        this.$route.meta['reset'] = false;
                    }
                    else{
                        this.loading = true;
                        this.searchableTable.removeResultsTable();
                        this.searchableTable.options.search_query = this.$route.fullPath;
                        this.searchableTable.updateSearchPage();
                    }

                }
                else
                {
                    //sort change just update the table view
                }

            }
        }

So then I extracted the watch to a file routeWatcher.js:

export default  {
    $route () {
        console.log('route changed')
        //was it a reset?

        console.log(this.$route.query.sort)

        if (this.$route.query.sort === undefined) {
            if (this.$route.meta.reset) {
                //reset was pressed... actually do nothing here
                this.$route.meta['reset'] = false;
            }
            else {
                this.loading = true;
                this.searchableTable.removeResultsTable();
                this.searchableTable.options.search_query = this.$route.fullPath;
                this.searchableTable.updateSearchPage();
            }

        }
        else {
            //sort change just update the table view
        }

    }

}

then I import and use, which works fine....

import searchableTableRouteWatcher from '../../controllers/routeWatcher'

...

watch:searchableTableRouteWatcher

again works fine.

Now the problem -  I want to avoid the import in multiple files, so I thought I could put it on the window as a global

in my main.js file:

import searchableTableRouteWatcher from './controllers/routeWatcher'
window.searchableTableRouteWatcher = searchableTableRouteWatcher;

Then in my component:

watch:searchableTableRouteWatcher

results in searchableTableRouteWatcher is not defined

watch:window.searchableTableRouteWatcher

results in no errors, but the code is not being called

I have a feeling it has to do with this and there is confusion on $route()

Body:
For your purpose there are 'Mixins' in Vue.js: documentation

What you can do:

create a file, say mixins/index.js:

export const routeWatcher = {
   watch: {... your watcher code pasted here ... }
};

import into your component:

import { routeWatcher } from 'path/to/mixins/index';

add mixin to your component properties and methods:

<script>
   export default {
       mixins: [routeWatcher];
       data () ...... all your original component's script content
   }

Mixin's content will be merged with component's original properties and act if it was hardcoded there.

Addition after your comment:

You can also declare Mixin globally, like this:

above 'new Vue' declaration put this code:

Vue.mixin({
   watch: {....}
});

This mixin will appear in every component.


问:
Unable to Stream Screen using VLCJ
I wanted to stream the screen using VLCJ through HTTP. I am able to do the video streaming with the webcam but when I tried stream my screen It gives me following output and the application stops:

Java Result: -1073741676

This is the code which I am using:

```<code>public class StreamHttp extends VlcjTest {
static MediaPlayerFactory mediaPlayerFactory;
    public static void main(String[] args) throws Exception {
        new NativeDiscovery().discover();

        String options = formatHttpStream("127.0.0.1", 5555);

        mediaPlayerFactory = new MediaPlayerFactory(args);
        HeadlessMediaPlayer mediaPlayer = mediaPlayerFactory.newHeadlessMediaPlayer();
        mediaPlayer.playMedia("screen://", options);

        Thread.currentThread().join();
    }

    private static String formatHttpStream(String serverAddress, int serverPort) {
        StringBuilder sb = new StringBuilder(60);
        sb.append(":sout=#transcode{vcodec=mp4v,vb=800,scale=0,acodec=mpga,ab=128,channels=2,samplerate=44100}:duplicate{dst=std{access=http,mux=ts,");
        sb.append("dst=");
        sb.append(serverAddress);
        sb.append(':');
        sb.append(serverPort);
        sb.append("}}");
        return sb.toString();
    }
}
</code>```

Kinldy help!!

答: Okay so after some struggle and searching I found that there was an issue with VLC player 2.2.4 which is the latest release. I switched to VLC 2.1.3 and everything was perfect. Got to know that they are working to fix it. So no issue with the code.</p>

Title: Unable to Stream Screen using VLCJ

Body:
I wanted to stream the screen using VLCJ through HTTP. I am able to do the video streaming with the webcam but when I tried stream my screen It gives me following output and the application stops:

Java Result: -1073741676

This is the code which I am using:

public class StreamHttp extends VlcjTest {
static MediaPlayerFactory mediaPlayerFactory;
    public static void main(String[] args) throws Exception {
        new NativeDiscovery().discover();

        String options = formatHttpStream("127.0.0.1", 5555);

        mediaPlayerFactory = new MediaPlayerFactory(args);
        HeadlessMediaPlayer mediaPlayer = mediaPlayerFactory.newHeadlessMediaPlayer();
        mediaPlayer.playMedia("screen://", options);

        Thread.currentThread().join();
    }

    private static String formatHttpStream(String serverAddress, int serverPort) {
        StringBuilder sb = new StringBuilder(60);
        sb.append(":sout=#transcode{vcodec=mp4v,vb=800,scale=0,acodec=mpga,ab=128,channels=2,samplerate=44100}:duplicate{dst=std{access=http,mux=ts,");
        sb.append("dst=");
        sb.append(serverAddress);
        sb.append(':');
        sb.append(serverPort);
        sb.append("}}");
        return sb.toString();
    }
}

Kinldy help!!


问:
get the value of another table
The first table is like this:-

```<code>LocalityID | LocalityName | StateID | LocalityChamp

 1         |     anyName  |    1    |  AnYOne
</code>```

The second table is like this :-

```<code>StateID | StateName

  1     |   anyState
</code>```

I want to return the values like this

```<code>1    anyName      anyState    AnYOne
</code>```

in codeignitor

答:
Assuming that first table name is locality and second table name is state. Use the following query

```<code>SELECT Locality.LocalityID , Locality.LocalityName, State.StateName from locality
inner join State on State.StateID=Locality.StateID
</code>```

or use Active Records .

Edit

In your model create a function like this;

```<code>function getChamps() {
 $this->db->select('Locality.LocalityID , Locality.LocalityName, State.StateName');
 $this->db->from('Locality');
 $this->db->join('State', 'State.StateID = Locality.StateID');
 $query = $this->db->get();
 return $query->result_array();
}
</code>```

In your controller

```<code>function index()
{
 $data['Champs']=$this->Model_name->getChamps();
 $this->load->view('path/to/view',$data);
}
</code>```

Title: get the value of another table

Body:
The first table is like this:-

LocalityID | LocalityName | StateID | LocalityChamp

 1         |     anyName  |    1    |  AnYOne

The second table is like this :-

StateID | StateName

  1     |   anyState

I want to return the values like this

1    anyName      anyState    AnYOne

in codeignitor

Body:
Assuming that first table name is locality and second table name is state. Use the following query

SELECT Locality.LocalityID , Locality.LocalityName, State.StateName from locality
inner join State on State.StateID=Locality.StateID

or use Active Records .

Edit

In your model create a function like this;

function getChamps() {
 $this->db->select('Locality.LocalityID , Locality.LocalityName, State.StateName');
 $this->db->from('Locality');
 $this->db->join('State', 'State.StateID = Locality.StateID');
 $query = $this->db->get();
 return $query->result_array();
}

In your controller

function index()
{
 $data['Champs']=$this->Model_name->getChamps();
 $this->load->view('path/to/view',$data);
}


问:
405 Method not allowed error in angularjs http Post request with IIS 8.5
I m getting "405 Method Not Allowed" error for my angularjs application running on PHP over iis 8.5

These are my header request...

```<code>Access-Control-Allow-Headers:Content-Type, Accept
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Allow:GET, HEAD, OPTIONS, TRACE
</code>```

What i can see is that post is missing in "Allow:GET, HEAD, OPTIONS, TRACE"

Can any one guide me how to enable POST request in IIS 8.5.

SOLVED

```<code>i finally solve this.... I guess the issue was in MY URL - api/login which is called in POST... i changes that URL with api/login/checklogin.php and executed POST request.... it works.......

SUPER THANKS TO LIN for his guidance and
http://stackoverflow.com always gives you the best.... THANKS ALL..
</code>```

答:
CORS do not effect the HTTP Status code > HTTP status codes effect cors. Taken from this answer you should allow all the HTTP-Request types in IIS
you need.

For  IIS 8.x try:

You could follow up this guide or make the following change in your applicationhost.configfile for your instance:

```<code><system.webServer>
    <handlers>
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <remove name="OPTIONSVerbHandler" />
        <remove name="TRACEVerbHandler" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>
</code>```

Also ensure you removed WebDAV module from web.config (if installed and enabled):

```<code><system.webServer>
  <modules>
    <remove name="WebDAVModule"/>
  </modules>
  <handlers>
    <remove name="WebDAV"/>
  </handlers>
</system.webServer>
</code>```

Body:
I m getting "405 Method Not Allowed" error for my angularjs application running on PHP over iis 8.5

These are my header request...

Access-Control-Allow-Headers:Content-Type, Accept
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Allow:GET, HEAD, OPTIONS, TRACE

What i can see is that post is missing in "Allow:GET, HEAD, OPTIONS, TRACE"

Can any one guide me how to enable POST request in IIS 8.5.

SOLVED

i finally solve this.... I guess the issue was in MY URL - api/login which is called in POST... i changes that URL with api/login/checklogin.php and executed POST request.... it works.......

SUPER THANKS TO LIN for his guidance and
http://stackoverflow.com always gives you the best.... THANKS ALL..

Body:
CORS do not effect the HTTP Status code > HTTP status codes effect cors. Taken from this answer you should allow all the HTTP-Request types in IIS
you need.

For  IIS 8.x try:

You could follow up this guide or make the following change in your applicationhost.configfile for your instance:

<system.webServer>
    <handlers>
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <remove name="OPTIONSVerbHandler" />
        <remove name="TRACEVerbHandler" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>

Also ensure you removed WebDAV module from web.config (if installed and enabled):

<system.webServer>
  <modules>
    <remove name="WebDAVModule"/>
  </modules>
  <handlers>
    <remove name="WebDAV"/>
  </handlers>
</system.webServer>


问:
How do I access individual words after splitting a string?
```<code>std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token[0] << "\n";
</code>```

This is printing individual letters. How do I get the complete words?

Updated to add:

I need to access them as words for doing something like this...

```<code>if (word[0] == "something")
   do_this();
else
   do_that();
</code>```

答:
```<code>std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token << "\n";
</code>```

To store all the tokens:

```<code>std::vector<std::string> tokens;
while (getline(iss, token, ' '))
    tokens.push_back(token);
</code>```

or just:

```<code>std::vector<std::string> tokens;
while (iss >> token)
    tokens.push_back(token);
</code>```

Now tokens[i] is the ith token.

Body:
std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token[0] << "\n";

This is printing individual letters. How do I get the complete words?

Updated to add:

I need to access them as words for doing something like this...

if (word[0] == "something")
   do_this();
else
   do_that();

Body:
std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token << "\n";

To store all the tokens:

std::vector<std::string> tokens;
while (getline(iss, token, ' '))
    tokens.push_back(token);

or just:

std::vector<std::string> tokens;
while (iss >> token)
    tokens.push_back(token);

Now tokens[i] is the ith token.


问:
How can I bind the html <title> content in vuejs?
I'm trying a demo on vuejs. Now I want the html title to bind a vm field.

The below is what I tried:

index.html

```<code><!DOCTYPE html>
<html id="html">
<head>
    <title>{{ hello }}</title>
    <script src="lib/requirejs/require.min.js" data-main="app"></script>
</head>
<body>
{{ hello }}
<input v-model="hello" title="hello" />
</body>
</html>
</code>```

app.js

```<code>define([
    'jquery', 'vue'
], function ($, Vue) {
    var vm = new Vue({
        el: 'html',
        data: {
            hello: 'Hello world'
        }
    });
});
</code>```

But the title seemed not bounded, how to make it work?

答:
Title and meta tags can be edited and updated asynchronously.

You can use state management, create a store for SEO using vuex and update each part accordingly.

Or you can update the element by yourself easily

```<code>created: function() {

  ajax().then(function(data){
     document.title = data.title
     document.head.querySelector('meta[name=description]').content = data.description
  })

}
</code>```

Body:
I'm trying a demo on vuejs. Now I want the html title to bind a vm field.

The below is what I tried:

index.html

<!DOCTYPE html>

    <title>{{ hello }}</title>

{{ hello }}
<input v-model="hello" title="hello" />

app.js

define([
    'jquery', 'vue'
], function ($, Vue) {
    var vm = new Vue({
        el: 'html',
        data: {
            hello: 'Hello world'
        }
    });
});

But the title seemed not bounded, how to make it work?

Body:
Title and meta tags can be edited and updated asynchronously.

You can use state management, create a store for SEO using vuex and update each part accordingly.

Or you can update the element by yourself easily

created: function() {

  ajax().then(function(data){
     document.title = data.title
     document.head.querySelector('meta[name=description]').content = data.description
  })

}


问:
Regex multiline replacement failing to strip anything
I have a large text file with the following example of text in it. There are many "CHARTS" blocks, probably 200+ in total.

```<code>CHARTS
  Color=14671839
  Layer=7
  [0] Font=MS SAN SERIF,10,0,F,F,
'''other lines'''
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

CHARTS
 Color=14671839
  Layer=4
  [0] Font=MS SAN SERIF,10,0,F,F,
...other lines...
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
</code>```

I am trying to strip all blocks where "Layer=7" meaning the above text would end up as

```<code>CHARTS
 Color=14671839

  Layer=4
  [0] Font=MS SAN SERIF,10,0,F,F,
...other lines...
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
</code>```

I have used the following:

```<code>$contents =~ s/CHARTS(?s)Layer\=7(?s).*?\[28\]\=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,//g;
</code>```

I am not getting any errors BUT nothing is being stripped.

I have spent the last hour playing around with it but am getting nowhere. Can someone point me in the right direction?

Many thanks

答:
Assuming the files are fairly regular (for instance, there are never any spaces around = in Layer=7, and CHARTS is always alone at the beginning of a line) this Perl one-line command will print the filtered output to stdout. I trust you know how to redirect it to a new file?

```<code>perl -0777 -ne '/Layer=7\b/ or print for split /^(?=CHARTS)/m' myfile
</code>```

output

```<code>CHARTS
 Color=14671839
  Layer=4
  [0] Font=MS SAN SERIF,10,0,F,F,
...other lines...
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
</code>```

,

Body:
I have a large text file with the following example of text in it. There are many "CHARTS" blocks, probably 200+ in total.

CHARTS
  Color=14671839
  Layer=7
  [0] Font=MS SAN SERIF,10,0,F,F,
'''other lines'''
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

CHARTS
 Color=14671839
  Layer=4
  [0] Font=MS SAN SERIF,10,0,F,F,
...other lines...
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

I am trying to strip all blocks where "Layer=7" meaning the above text would end up as

CHARTS
 Color=14671839

  Layer=4
  [0] Font=MS SAN SERIF,10,0,F,F,
...other lines...
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

I have used the following:

$contents =~ s/CHARTS(?s)Layer\=7(?s).*?\[28\]\=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,//g;

I am not getting any errors BUT nothing is being stripped.

I have spent the last hour playing around with it but am getting nowhere. Can someone point me in the right direction?

Many thanks

Body:
Assuming the files are fairly regular (for instance, there are never any spaces around = in Layer=7, and CHARTS is always alone at the beginning of a line) this Perl one-line command will print the filtered output to stdout. I trust you know how to redirect it to a new file?

perl -0777 -ne '/Layer=7\b/ or print for split /^(?=CHARTS)/m' myfile

output

CHARTS
 Color=14671839
  Layer=4
  [0] Font=MS SAN SERIF,10,0,F,F,
...other lines...
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

,


问:
DRF setting fields with non string
lest say we have a code like this.

```<code>class UserProfileDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('userThumbnail', 'point')
</code>```

what i want to do is not using ('userThumbnail', 'point')

but something like this (nameof(UserProfile.userThumbnail), nameof(UserProfile.point))

so i don't have to rewrite those fields everytime i rename those.

how can i do something like that?

答:
Yes you can.</p>

```<code>def nameof(field):
    return field.field_name

class User(models.Model):
    git = models.CharField(max_length = 10)

>>> nameof(User.git)
'git'
</code>```

Title: DRF setting fields with non string

Body:
lest say we have a code like this.

class UserProfileDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('userThumbnail', 'point')

what i want to do is not using ('userThumbnail', 'point')

but something like this (nameof(UserProfile.userThumbnail), nameof(UserProfile.point))

so i don't have to rewrite those fields everytime i rename those.

how can i do something like that?

Body:
Yes you can.

def nameof(field):
    return field.field_name

class User(models.Model):
    git = models.CharField(max_length = 10)

>>> nameof(User.git)
'git'


问:
Separate pages for blog posts
I'm currently working on my private CMS, mostly just to learn PHP. For now I have very simple way to show post, using GET with ID, for example www.mypage.com/post.php?id=1 and then loading results from DB. But I see that almost all blogs are using other way, which looks like this www.mypage.com/post/lorem-ipsum. I know about removing file extensions but the rest is mystery. Does wordpress and other blog CMS are somehow creating separate files? PHP is huge, and it's hard to find an answer if you don't know it well, so If someone can point me in the right direction, I'll be obliged.</p>

答: It is possible to rewrite the URL using an .htaccess file: see here

Title: Separate pages for blog posts


问:
Difference in uses between malloc and calloc
```<code>gcc 4.5.1 c89
</code>```

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions.

```<code>dev = malloc(number * sizeof *devices);
</code>```

is equal to this calloc. I am not concerned about clearing the memory.

```<code>dev = calloc(number, sizeof *devices);
</code>```

What is that exactly, compared to doing this 5 times in a while loop:

```<code>dev = malloc(sizeof *devices);
</code>```

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

My program illustrates this 3 different methods compiled and ran with valgrind --leak-check=full.

Many thanks for any advice.

```<code>#include <stdio.h>
#include <stdlib.h>

struct Devices {
#define MAX_NAME_SIZE 80
    size_t id;
    char name[MAX_NAME_SIZE];
};

struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);

int main(void)
{
    size_t num_devices = 5;
    size_t i = 0;
    struct Devices *device = NULL;
    struct Devices *dev_malloc = NULL;
    struct Devices *dev_calloc = NULL;

    for(i = 0; i < num_devices; i++) {
        device = create_device(device);
        /* Assign values */
        device->id = i + 1;
        sprintf(device->name, "Device%zu", device->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", device->id);
        printf("Name --- [ %s ]\n", device->name);
        /* Test free */
        destroy_device(device);
    }

    printf("\n");
    dev_malloc = malloc(num_devices * sizeof *dev_malloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_malloc->id = i + 1;
        sprintf(dev_malloc->name, "dev_malloc%zu", dev_malloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_malloc->id);
        printf("Name --- [ %s ]\n", dev_malloc->name);
    }
    /* Test free */
    destroy_device(dev_malloc);

    printf("\n");
    dev_calloc = calloc(num_devices, sizeof *dev_calloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_calloc->id = i + 1;
        sprintf(dev_calloc->name, "dev_calloc%zu", dev_calloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_calloc->id);
        printf("Name --- [ %s ]\n", dev_calloc->name);
    }
    /* Test free */
    destroy_device(dev_calloc);

    return 0;
}

struct Devices* create_device(struct Devices *dev)
{
    /* Not checking for memory error - just simple test */
    return dev = malloc(sizeof *dev);
}

void destroy_device(struct Devices *dev)
{
    if(dev != NULL) {
        free(dev);
    }
}
</code>```

答:
All three loops in your program use only one struct Devices object at a time.  The later ones allocate extra memory as though they are going to use multiple objects, but then keep overwriting the beginning of that memory.  If you tried to use the object with ID 1 after setting up the object with ID 2, you would find there is no longer any object with ID 1.

Instead, you could do something like this to treat the allocated memory as an array of structs:

```<code>dev_malloc = malloc(num_devices * sizeof *dev_malloc);
for (i=0; i<num_devices; i++) {
    /* Assign values */
    dev_malloc[i].id = i + 1;
    sprintf(dev_malloc[i].name, "dev_malloc%zu", dev_malloc[i].id);
    /* Print values */
    printf("ID ----- [ %zu ]\n", dev_malloc[i].id);
    printf("Name --- [ %s ]\n", dev_malloc[i].name);
}
free(dev_malloc);
</code>```

Body:
gcc 4.5.1 c89

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions.

dev = malloc(number * sizeof *devices);

is equal to this calloc. I am not concerned about clearing the memory.

dev = calloc(number, sizeof *devices);

What is that exactly, compared to doing this 5 times in a while loop:

dev = malloc(sizeof *devices);

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

My program illustrates this 3 different methods compiled and ran with valgrind --leak-check=full.

Many thanks for any advice.

#include <stdio.h>
#include <stdlib.h>

struct Devices {
#define MAX_NAME_SIZE 80
    size_t id;
    char name[MAX_NAME_SIZE];
};

struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);

int main(void)
{
    size_t num_devices = 5;
    size_t i = 0;
    struct Devices *device = NULL;
    struct Devices *dev_malloc = NULL;
    struct Devices *dev_calloc = NULL;

    for(i = 0; i < num_devices; i++) {
        device = create_device(device);
        /* Assign values */
        device->id = i + 1;
        sprintf(device->name, "Device%zu", device->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", device->id);
        printf("Name --- [ %s ]\n", device->name);
        /* Test free */
        destroy_device(device);
    }

    printf("\n");
    dev_malloc = malloc(num_devices * sizeof *dev_malloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_malloc->id = i + 1;
        sprintf(dev_malloc->name, "dev_malloc%zu", dev_malloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_malloc->id);
        printf("Name --- [ %s ]\n", dev_malloc->name);
    }
    /* Test free */
    destroy_device(dev_malloc);

    printf("\n");
    dev_calloc = calloc(num_devices, sizeof *dev_calloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_calloc->id = i + 1;
        sprintf(dev_calloc->name, "dev_calloc%zu", dev_calloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_calloc->id);
        printf("Name --- [ %s ]\n", dev_calloc->name);
    }
    /* Test free */
    destroy_device(dev_calloc);

    return 0;
}

struct Devices* create_device(struct Devices *dev)
{
    /* Not checking for memory error - just simple test */
    return dev = malloc(sizeof *dev);
}

void destroy_device(struct Devices *dev)
{
    if(dev != NULL) {
        free(dev);
    }
}

Body:
All three loops in your program use only one struct Devices object at a time.  The later ones allocate extra memory as though they are going to use multiple objects, but then keep overwriting the beginning of that memory.  If you tried to use the object with ID 1 after setting up the object with ID 2, you would find there is no longer any object with ID 1.

Instead, you could do something like this to treat the allocated memory as an array of structs:

dev_malloc = malloc(num_devices * sizeof *dev_malloc);
for (i=0; i<num_devices; i++) {
    /* Assign values */
    dev_malloc[i].id = i + 1;
    sprintf(dev_malloc[i].name, "dev_malloc%zu", dev_malloc[i].id);
    /* Print values */
    printf("ID ----- [ %zu ]\n", dev_malloc[i].id);
    printf("Name --- [ %s ]\n", dev_malloc[i].name);
}
free(dev_malloc);


问:
Best approach to listen to a dynamic array of refs generated for Firebase?
Here's the scenario: I get an initial payload from Firebase (eg. 5 objects) from firebaseRef_1 (using a .once callback). I then transform each received object into a new Firebase ref. That newly generated ref looks like this:

```<code> "data/ccccyyyyotKKiWC2xaV1WZ7H3/things/-KgXo121225H9_Nks1O"
</code>```

If for example I have 5 incoming objects on that .once call, then I'll create 5 refs (see code snippet below).

Once I've created/generated the ref(s) I want to:

a) Create a .on listener to each of those 5 refs.

b) If (lets say) some time later 1 'row' of new data arrives to firebaseRef_1, I want to generate a new ref, and then create a listener - but now, just for that newly added item. Otherwise if I try to loop through all of the (now 6) elements Firebase throws a promise error telling me that the original 5  elements (refs) already have a listener attached.

The reason that I was thinking to use a .once call initially, is so that I can get the whole payload "all at .once" (pun intended!) which makes populating a ListView (react native) faster. I tried using a .child_added approach but on the initial load (of those 5 rows) the .child_added gets called 5 times and so you can see the rows appear one by one in the ListView which I dont like.

How should I best structure this in code to achieve what I've described above? Should I just have a .once call like this:

```<code>generateTheRefs() {
  firebase.database()
    .ref('data/' + firebaseUID + '/initialPath')
    .once('value', (snapshot) => {

     snapshot.forEach(childSnapshot => {
        var childData = childSnapshot.val();
        let path = `data/${childData.item1}/things/${childData.item2}`;

        //now create a .on listener
        firebase.database()
        .ref(path)
        .on('value', (snapshot) => {
             //....
        });
    });
  });
 }
</code>```

答:
It sounds like what you are after is to use all of the results at the same time so they don't dribble in over time. You can use an array of promises and Promise.all() to wait for them all to arrive before using them, something like:</p>

```<code>function generateTheRefs() {
  firebase.database()
      .ref('data/' + firebaseUID + '/initialPath')
      .once('value', (snapshot) => {

        let promises = [];

        snapshot.forEach(childSnapshot => {
          var childData = childSnapshot.val();
          let path = `data/${childData.item1}/things/${childData.item2}`;

          //now create a .on listener
          promises.push(firebase.database()
              .ref(path)
              .once('value'));
        });

        Promise.all(promises).then(snaps => {
          snaps.forEach(snap => {
            // ...
            console.log(snap.val());
          })
        });
      });
}
</code>```

Body:
Here's the scenario: I get an initial payload from Firebase (eg. 5 objects) from firebaseRef_1 (using a .once callback). I then transform each received object into a new Firebase ref. That newly generated ref looks like this:

 "data/ccccyyyyotKKiWC2xaV1WZ7H3/things/-KgXo121225H9_Nks1O"

If for example I have 5 incoming objects on that .once call, then I'll create 5 refs (see code snippet below).

Once I've created/generated the ref(s) I want to:

a) Create a .on listener to each of those 5 refs.

b) If (lets say) some time later 1 'row' of new data arrives to firebaseRef_1, I want to generate a new ref, and then create a listener - but now, just for that newly added item. Otherwise if I try to loop through all of the (now 6) elements Firebase throws a promise error telling me that the original 5  elements (refs) already have a listener attached.

The reason that I was thinking to use a .once call initially, is so that I can get the whole payload "all at .once" (pun intended!) which makes populating a ListView (react native) faster. I tried using a .child_added approach but on the initial load (of those 5 rows) the .child_added gets called 5 times and so you can see the rows appear one by one in the ListView which I dont like.

How should I best structure this in code to achieve what I've described above? Should I just have a .once call like this:

generateTheRefs() {
  firebase.database()
    .ref('data/' + firebaseUID + '/initialPath')
    .once('value', (snapshot) => {

     snapshot.forEach(childSnapshot => {
        var childData = childSnapshot.val();
        let path = `data/${childData.item1}/things/${childData.item2}`;

        //now create a .on listener
        firebase.database()
        .ref(path)
        .on('value', (snapshot) => {
             //....
        });
    });
  });
 }

Body:
It sounds like what you are after is to use all of the results at the same time so they don't dribble in over time. You can use an array of promises and Promise.all() to wait for them all to arrive before using them, something like:

function generateTheRefs() {
  firebase.database()
      .ref('data/' + firebaseUID + '/initialPath')
      .once('value', (snapshot) => {

        let promises = [];

        snapshot.forEach(childSnapshot => {
          var childData = childSnapshot.val();
          let path = `data/${childData.item1}/things/${childData.item2}`;

          //now create a .on listener
          promises.push(firebase.database()
              .ref(path)
              .once('value'));
        });

        Promise.all(promises).then(snaps => {
          snaps.forEach(snap => {
            // ...
            console.log(snap.val());
          })
        });
      });
}


问:
CollapsingToolbarLayout - Dim/Blur the background image
I've got a collapsing toolbar with an imageview. When extended, it looks like this:

When collapsed, it looks like this:

I know that according to the guidelines, the toolbar should be of the primary color while collapsed, but i like the way i've set it up, and would like to keep it like that.

However, obviously, the toolbar title won't be visible if the image has a lot of white in it. So, is there a way i can blur/dim the background so that the toolbar title is visible at all times?

Edit: The image in question, is loaded from the internet using Picasso.

答:
My not optimal solution to this problem was to overlap two images, the normal and the blurred one, and change the alpha of the blurred one. When expanded, the alpha is 0. When collapsed its alpha is one. I used

```<code>AppBarLayout.addOnOffsetChangedListener
</code>```

to get the scroll event. In my case

```<code> appBarLayout.addOnOffsetChangedListener((view, verticalOffset) -> {
        if (mScrollRange == 0) {
              mScrollRange = appBarLayout.getTotalScrollRange();
        }
        ViewCompat.setAlpha(mBlurredImage,
                (float) (1 - Math.pow(((mScrollRange + verticalOffset) / (float) mScrollRange), 4)));
 });
</code>```

It is not ideal but it does its work

Body:
My not optimal solution to this problem was to overlap two images, the normal and the blurred one, and change the alpha of the blurred one. When expanded, the alpha is 0. When collapsed its alpha is one. I used

AppBarLayout.addOnOffsetChangedListener

to get the scroll event. In my case

 appBarLayout.addOnOffsetChangedListener((view, verticalOffset) -> {
        if (mScrollRange == 0) {
              mScrollRange = appBarLayout.getTotalScrollRange();
        }
        ViewCompat.setAlpha(mBlurredImage,
                (float) (1 - Math.pow(((mScrollRange + verticalOffset) / (float) mScrollRange), 4)));
 });

It is not ideal but it does its work


问:
How to regex string that includes html
I have this string which is part of a larger string with multiple occurrences of "content" and "/content": I want to capture the whole string between "content ..." and "/content".

<content type="xhtml">

RATING: ★★★★

TAGS: Fiction, General, Science Fiction

SERIES: 20 SienceFiction Greats [19]

SUMMARY:
Luna is an open colony and the regime is a harsh one....

    </content>```
</div>
</div>

I want to capture all between "content type="xhtml"" and "/content"
I tried this code:</p>

```let regexPattern = "<content type=\"xhtml\">.*</content>"
let result:[String] = matches(for: regexPattern, in: dataString)
```

but it returns an empty array.

答:
Well I found a solution as the .* pattern captures everything from the first occurrence of "content" to the last occurrence of "/content".

so this is my solution: get an array of "content" occurrences and an array of "/content" occurrences, from these arrays I can calculate the ranges I need from the string

```<code>private func getXHTMLContentFromDataString(dataString: String) -> [String] {
    var contentStringArray: [String] = []
    let startString: String = "<content type=\"xhtml\">"
    let endString: String = "</content>"
    var isFound = true
    var currentString = dataString
    while isFound == true && currentString.characters.count > 0 {
        if let contentStartRange = currentString.range(of: startString), let contentEndRange = currentString.range(of: endString) {
            isFound = true
            let contentStr: String = currentString[contentStartRange.upperBound .. < contentEndRange.lowerBound]
            contentStringArray.append(contentStr)
            currentString = currentString[contentEndRange.upperBound .. <currentString.endIndex]
        } else {

            isFound = false
        }
    }
    return contentStringArray
}
</code>```

Title: How to regex string that includes html

Body:
I have this string which is part of a larger string with multiple occurrences of "content" and "/content": I want to capture the whole string between "content ..." and "/content".

<content type="xhtml">

RATING: ★★★★

TAGS: Fiction, General, Science Fiction

SERIES: 20 SienceFiction Greats [19]

SUMMARY:
Luna is an open colony and the regime is a harsh one....

    </content>

I want to capture all between "content type="xhtml"" and "/content"
I tried this code:

let regexPattern = "<content type=\"xhtml\">.*</content>"
let result:[String] = matches(for: regexPattern, in: dataString)

but it returns an empty array.

Body:
Well I found a solution as the .* pattern captures everything from the first occurrence of "content" to the last occurrence of "/content".

so this is my solution: get an array of "content" occurrences and an array of "/content" occurrences, from these arrays I can calculate the ranges I need from the string

private func getXHTMLContentFromDataString(dataString: String) -> [String] {
    var contentStringArray: [String] = []
    let startString: String = "<content type=\"xhtml\">"
    let endString: String = "</content>"
    var isFound = true
    var currentString = dataString
    while isFound == true && currentString.characters.count > 0 {
        if let contentStartRange = currentString.range(of: startString), let contentEndRange = currentString.range(of: endString) {
            isFound = true
            let contentStr: String = currentString[contentStartRange.upperBound .. < contentEndRange.lowerBound]
            contentStringArray.append(contentStr)
            currentString = currentString[contentEndRange.upperBound .. <currentString.endIndex]
        } else {

            isFound = false
        }
    }
    return contentStringArray
}


问:
Let in Javascript. Confusion
I am really confused about this code

var box = document.getElementsByClassName('box-value');

for(let i = 0; i < box.length; i++){
    box[i].onclick = function(){
        console.log(i);
    }
    console.log("End loop. i:" + i);
}

let i = 0;
box[i].onclick = function(){
    console.log(i);
}
i = 9;

box[0].onclick();```

In the first block, i is 0

But in the second block, i is 9.

I really don't understand why?

答:
Because your first i is in a block and doesn't get changed afterwards, while your second i (is not in a block) and does get set to 9 before the click handler is run. You can emulate the behaviour from the loop by doing

```<code>{
    let i = 0; // one variable that stays constant
    box[i].onclick = function(){
        console.log(i);
    };
}
let i = 9; // a different variable
</code>```

and you can also emulate the altering behaviour of the assignment by putting the scope around the loop:

```<code>let i = 0;
for(; i < box.length; i++) {
    box[i].onclick = function() {
        console.log(i);
    };
    console.log("End loop. i:" + i);
}
</code>```

Title: Let in Javascript. Confusion

Body:
I am really confused about this code

var box = document.getElementsByClassName('box-value');

for(let i = 0; i < box.length; i++){
    box[i].onclick = function(){
        console.log(i);
    }
    console.log("End loop. i:" + i);
}

let i = 0;
box[i].onclick = function(){
    console.log(i);
}
i = 9;

box[0].onclick();

In the first block, i is 0

But in the second block, i is 9.

I really don't understand why?

Body:
Because your first i is in a block and doesn't get changed afterwards, while your second i (is not in a block) and does get set to 9 before the click handler is run. You can emulate the behaviour from the loop by doing

{
    let i = 0; // one variable that stays constant
    box[i].onclick = function(){
        console.log(i);
    };
}
let i = 9; // a different variable

and you can also emulate the altering behaviour of the assignment by putting the scope around the loop:

let i = 0;
for(; i < box.length; i++) {
    box[i].onclick = function() {
        console.log(i);
    };
    console.log("End loop. i:" + i);
}


问:
CSS: 3 divs - Resizing 2 outer divs automatically based on width of inner div/text
My problem is best outlined with this schematic/image which outlines how I want it to look:

!

I have a background image and 2 divs for text over the top of it (headline, and intro-text). I also have 2 divs on either side of the headline - these are for the white horizontal stripes.

My issue is that the headline is changeable in a CMS, and I want the horizontal white stripes to automatically fill up the space to the left and to the right of it, regardless of the headline's width.

I can't figure out how to make those 2 horizontal white stripes resize automatically.

Here's my HTML:

```<code><div id="masthead">
<div id="headline-container">
    <div id="left-stripe"> </div><div id="headline">{headline}</div><div id="right-stripe"> </div>
</div>
<div class="clear-both"> </div>
<div id="intro-text">{intro_text}</div>
</div>
</code>```

And here's my CSS - ignore the widths specified for the left-stripe and right-stripe - they're just placeholders:

```<code>#masthead {
    height: 260px;
}

div#headline-container {
    width:960px;
    padding:none;
}
div#left-stripe{
    float: left;
    background-color:#fff;
    height: 3px;
    width:500px;
    display: inline;
}
div#right-stripe{
    float: right;
    background-color:#fff;
    height: 3px;
    width:100px;
    display: inline;
}
div#headline {
    text-align:right;
    color: #fff;
    font-size: 200%;
    float: left;
    display: inline;
}
div#intro-text {
    text-align: left;
    float: right;
    width: 300px;
    color: #fff;
}
</code>```

Ideas? Please let me know if I can provide more detail.

答:
I'm a bit too busy to actually test this, but this might give you some direction.  i'm not sure the exact effect you're trying to achieve (see comment about finding a live demo someone made).

Regardless, this kind of fluid layout is a bit difficult to achieve reliably with straight CSS.  To make it easier I would suggest making the right-stripe a static width.

This CSS solution MIGHT work... no promises.

markup

```<code><div class="container">
  <div class="headline-container">
   <div class="left-stripe"></div>
   <div class="headline">Headline goes here</div>
   <div class="right-stripe></div>
  </div>
  <div class="content"></div>
</div>
</code>```

CSS

```<code>//static width for right stripe
.right-stripe { width: 20px; }
.headline { width: auto; }
.left-stripe { width: auto; }
</code>```

Using javascript would make it really easy though... here's how i would do it with jQuery. Again, I would make the right-stripe a static width to achieve this effect.

(same markup...)

..

js

```<code>var totalWidth = $("#container").width();
var leftWidth = totalWidth - ($("headline").width() + $("right-stripe").width());
$("left-stripe").width(leftWidth);
</code>```

Body:
My problem is best outlined with this schematic/image which outlines how I want it to look:

!

I have a background image and 2 divs for text over the top of it (headline, and intro-text). I also have 2 divs on either side of the headline - these are for the white horizontal stripes.

My issue is that the headline is changeable in a CMS, and I want the horizontal white stripes to automatically fill up the space to the left and to the right of it, regardless of the headline's width.

I can't figure out how to make those 2 horizontal white stripes resize automatically.

Here's my HTML:

{headline}

{intro_text}

And here's my CSS - ignore the widths specified for the left-stripe and right-stripe - they're just placeholders:

#masthead {
    height: 260px;
}

div#headline-container {
    width:960px;
    padding:none;
}
div#left-stripe{
    float: left;
    background-color:#fff;
    height: 3px;
    width:500px;
    display: inline;
}
div#right-stripe{
    float: right;
    background-color:#fff;
    height: 3px;
    width:100px;
    display: inline;
}
div#headline {
    text-align:right;
    color: #fff;
    font-size: 200%;
    float: left;
    display: inline;
}
div#intro-text {
    text-align: left;
    float: right;
    width: 300px;
    color: #fff;
}

Ideas? Please let me know if I can provide more detail.

Body:
I'm a bit too busy to actually test this, but this might give you some direction.  i'm not sure the exact effect you're trying to achieve (see comment about finding a live demo someone made).

Regardless, this kind of fluid layout is a bit difficult to achieve reliably with straight CSS.  To make it easier I would suggest making the right-stripe a static width.

This CSS solution MIGHT work... no promises.

markup

<div class="container">
  <div class="headline-container">
   <div class="left-stripe"></div>
   <div class="headline">Headline goes here</div>
   <div class="right-stripe></div>
  </div>
  <div class="content"></div>
</div>

CSS

//static width for right stripe
.right-stripe { width: 20px; }
.headline { width: auto; }
.left-stripe { width: auto; }

Using javascript would make it really easy though... here's how i would do it with jQuery. Again, I would make the right-stripe a static width to achieve this effect.

(same markup...)

..

js

var totalWidth = $("#container").width();
var leftWidth = totalWidth - ($("headline").width() + $("right-stripe").width());
$("left-stripe").width(leftWidth);


问:
"exclude" property of tsconfig.json is not being respected
I am working with the excellent Express/Node/Typescript example code found here. It transpiles the .ts code with the following command from run.sh:

./node_modules/.bin/tsc --sourcemap --module commonjs ./bin/www.ts

This works as advertised, but I would prefer to use a tsconfig.json file and tsc -p . However, when I run that command I get a raft of TS2300: Duplicate identifier 'foo' errorswhen tsc(erroneously?) tries to walk the ./node_modules and ./typings directories. Below is the tsconfig.json I am using:

```<code>{
  "compilerOptions": {
    "target": "ES5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings"
  ]
}
</code>```

Any ideas? I am using tsc 1.7.3 FWIW.

答:
04/02/0217 (april 2) - I was going through this same thing, spent almost a full weekend on it. Finally I found this website (which I have never seen linked from any stackoverflow post): https://angular.io/docs/ts/latest/guide/typescript-configuration.html

In it, I found this line, right in the compilerOptions:

```<code>"lib": [ "es2015", "dom" ]
</code>```

I have no idea what it does, and at this point I don't care, but ALL of my node_modules errors went away.

As for include/exclude not working, I believe it is because of "dependencies." Even if you exclude a folder, if an imported file (like Component or NgModule) has some dependency on a file in node_modules, tsc is going to try to compile that file.

Body:
I am working with the excellent Express/Node/Typescript example code found here. It transpiles the .ts code with the following command from run.sh:

./node_modules/.bin/tsc --sourcemap --module commonjs ./bin/www.ts

This works as advertised, but I would prefer to use a tsconfig.json file and tsc -p . However, when I run that command I get a raft of TS2300: Duplicate identifier 'foo' errorswhen tsc(erroneously?) tries to walk the ./node_modules and ./typings directories. Below is the tsconfig.json I am using:

{
  "compilerOptions": {
    "target": "ES5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings"
  ]
}

Any ideas? I am using tsc 1.7.3 FWIW.

Body:
04/02/0217 (april 2) - I was going through this same thing, spent almost a full weekend on it. Finally I found this website (which I have never seen linked from any stackoverflow post): https://angular.io/docs/ts/latest/guide/typescript-configuration.html

In it, I found this line, right in the compilerOptions:

"lib": [ "es2015", "dom" ]

I have no idea what it does, and at this point I don't care, but ALL of my node_modules errors went away.

As for include/exclude not working, I believe it is because of "dependencies." Even if you exclude a folder, if an imported file (like Component or NgModule) has some dependency on a file in node_modules, tsc is going to try to compile that file.