问:
My sorting algorithm doesn't work
As homework, we were supposed to implement a few functions and then come up with a sorting algorithm potentially implementing those functions. first of all, these are the two needed functions:

```<code>remove :: (Ord a) => a -> [a] -> [a]
remove a (x:[]) = x:[]
remove a (x:xs) =
  if a == x
    then xs
    else x:(remove a xs)
</code>```

and:

```<code>smallest :: (Ord a) => [a] -> a
smallest (x:y:[]) =
  if x < y
    then x
    else y
smallest (x:y:xs) =
  if x < y
    then smallest (x:xs)
    else smallest (y:xs)
</code>```

My sorting Algorithm is just supposed to take the smallest element and put it at the beginning of the list:

```<code>sort :: (Integral a) => [a] -> [a]
sort [] = []
sort x = smallest x : sort (rest x)
      where
        rest = remove (smallest x) x
</code>```

The Error I get is

Couldn't match expected type ‘[a] -> [a]’ with actual type ‘[a]’

The function ‘rest’ is applied to one argument,
but its type ‘[a]’ has none
In the first argument of ‘sort’, namely ‘(rest x)’
In the second argument of ‘(:)’, namely ‘sort (rest x)’

I'm surely missing something obvious, but I can't figure out what it is. help me pls.

答:
First of all, your remove function will error on the empty list, and never remove an element from a list with one element. You probably want to write:

```<code>remove :: <b>Eq a</b> => a -> [a] -> [a]
remove a <b>[]</b> = <b>[]</b>
remove a (x:xs) <b>| a == x = xs
                | otherwise = x : remove a xs</b></code>```

Next your smallest behaves weird as well since it will not select the smallest from a list with one element (in that case the smallest element is that case). We can rewrite it like:

```<code>smallest :: Ord a => [a] -> a
smallest <b>[x]</b> = <b>x</b>
smallest (x:y:xs) <b>| x < y = smallest (x:xs)
                  | otherwise = smallest (y:xs)</b></code>```

Now that we have fixed these, we can focus on the real sorting function. I do not really see why you want to use a helper function here to remove the element, you can use a variable small to store the smallest element in the list, and then simply use recursion, like:

```<code>sort :: Ord a => [a] -> [a]
sort [] = []
sort x  = <b>small</b> : sort (<b>remove small x</b>)
    <b>where small = smallest x</b></code>```

Now with this sorting algorithm, we obtain:

```<code>*Main> sort [1,4,2,5]
[1,2,4,5]
*Main> sort [1,4,2,5,1,3,0,2]
[0,1,1,2,2,3,4,5]
</code>```

Title: My sorting algorithm doesn't work

Body:
As homework, we were supposed to implement a few functions and then come up with a sorting algorithm potentially implementing those functions. first of all, these are the two needed functions:

remove :: (Ord a) => a -> [a] -> [a]
remove a (x:[]) = x:[]
remove a (x:xs) =
  if a == x
    then xs
    else x:(remove a xs)

and:

smallest :: (Ord a) => [a] -> a
smallest (x:y:[]) =
  if x < y
    then x
    else y
smallest (x:y:xs) =
  if x < y
    then smallest (x:xs)
    else smallest (y:xs)

My sorting Algorithm is just supposed to take the smallest element and put it at the beginning of the list:

sort :: (Integral a) => [a] -> [a]
sort [] = []
sort x = smallest x : sort (rest x)
      where
        rest = remove (smallest x) x

The Error I get is

Couldn't match expected type ‘[a] -> [a]’ with actual type ‘[a]’

The function ‘rest’ is applied to one argument,
but its type ‘[a]’ has none
In the first argument of ‘sort’, namely ‘(rest x)’
In the second argument of ‘(:)’, namely ‘sort (rest x)’

I'm surely missing something obvious, but I can't figure out what it is. help me pls.

Body:
First of all, your remove function will error on the empty list, and never remove an element from a list with one element. You probably want to write:

remove :: Eq a => a -> [a] -> [a]
remove a [] = []
remove a (x:xs) | a == x = xs
                | otherwise = x : remove a xs

Next your smallest behaves weird as well since it will not select the smallest from a list with one element (in that case the smallest element is that case). We can rewrite it like:

smallest :: Ord a => [a] -> a
smallest [x] = x
smallest (x:y:xs) | x < y = smallest (x:xs)
                  | otherwise = smallest (y:xs)

Now that we have fixed these, we can focus on the real sorting function. I do not really see why you want to use a helper function here to remove the element, you can use a variable small to store the smallest element in the list, and then simply use recursion, like:

sort :: Ord a => [a] -> [a]
sort [] = []
sort x  = small : sort (remove small x)
    where small = smallest x

Now with this sorting algorithm, we obtain:

*Main> sort [1,4,2,5]
[1,2,4,5]
*Main> sort [1,4,2,5,1,3,0,2]
[0,1,1,2,2,3,4,5]


来源: stackexchange

问:
install couchbase php extension on xampp under windows 10
i've tried many times to install couchbase client using this tutorial : http://trondn.blogspot.ro/2013/04/couchbase-php-xampp-and-windows.html ,, but is not working,,

when i run composer update i get the following errors

```<code>PHP Warning:  PHP Startup: Unable to load dynamic library 'C:\xampp\php\ext\php_couchbase.dll' - The specified module could not be found.
 in Unknown on line 0

Warning: PHP Startup: Unable to load dynamic library 'C:\xampp\php\ext\php_couchbase.dll' - The specified module could not be found.
 in Unknown on line 0
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - ytake/laravel-couchbase 0.5.7 requires ext-couchbase ^2.2.2 -> the requested PHP extension couchbase is missing from your system.
    - ytake/laravel-couchbase 0.5.6 requires ext-couchbase >=2.2.0 -> the requested PHP extension couchbase is missing from your system.
    - ytake/laravel-couchbase 0.5.5 requires ext-couchbase >=2.2.0 -> the requested PHP extension couchbase is missing from your system.
    - ytake/laravel-couchbase 0.5.3 requires ext-couchbase >=2.2.0 -> the requested PHP extension couchbase is missing from your system.
    - ytake/laravel-couchbase 0.5.2 requires ext-couchbase >=2.2.0 -> the requested PHP extension couchbase is missing from your system.
    - ytake/laravel-couchbase 0.5.1 requires ext-couchbase >=2.2.0 -> the requested PHP extension couchbase is missing from your system.
    - Installation request for ytake/laravel-couchbase ^0.5 -> satisfiable by ytake/laravel-couchbase[0.5.1, 0.5.2, 0.5.3, 0.5.5, 0.5.6, 0.5.7].
</code>```

what should i do? please i need help

答:
Official PHP SDK binaries for Windows published on
https://developer.couchbase.com/server/other-products/release-notes-archives/php-sdk

Make sure you put php_couchbase.dll into your extensions directory, and libcouchbase.dll into your SAPI PATH (or process current directory).

ContentLicense: CC BY-SA 3.0

Body:
i've tried many times to install couchbase client using this tutorial : http://trondn.blogspot.ro/2013/04/couchbase-php-xampp-and-windows.html ,, but is not working,,

when i run composer update i get the following errors

PHP Warning:  PHP Startup: Unable to load dynamic library 'C:\xampp\php\ext\php_couchbase.dll' - The specified module could not be found.
 in Unknown on line 0

Warning: PHP Startup: Unable to load dynamic library 'C:\xampp\php\ext\php_couchbase.dll' - The specified module could not be found.
 in Unknown on line 0
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - ytake/laravel-couchbase 0.5.7 requires ext-couchbase ^2.2.2 -> the requested PHP extension couchbase is missing from your system.
    - ytake/laravel-couchbase 0.5.6 requires ext-couchbase >=2.2.0 -> the requested PHP extension couchbase is missing from your system.
    - ytake/laravel-couchbase 0.5.5 requires ext-couchbase >=2.2.0 -> the requested PHP extension couchbase is missing from your system.
    - ytake/laravel-couchbase 0.5.3 requires ext-couchbase >=2.2.0 -> the requested PHP extension couchbase is missing from your system.
    - ytake/laravel-couchbase 0.5.2 requires ext-couchbase >=2.2.0 -> the requested PHP extension couchbase is missing from your system.
    - ytake/laravel-couchbase 0.5.1 requires ext-couchbase >=2.2.0 -> the requested PHP extension couchbase is missing from your system.
    - Installation request for ytake/laravel-couchbase ^0.5 -> satisfiable by ytake/laravel-couchbase[0.5.1, 0.5.2, 0.5.3, 0.5.5, 0.5.6, 0.5.7].

what should i do? please i need help


问:
Best way to send HTML email to group of people in MySQL table?
I would like to know what the best way to email a list of people (>=2000) from a MySQL database is. I would like to send an HTML email to the people retrieved from a table in this MySQL database. I know that there are existing programs or "mass mailers" but I was told that using them might make my domain blacklisted. What if I wrote a small program and made that separate the email recipients in chunks of, say, 200, and loop through these blocks...would that be a better/safer way?

Thanks in advance,
Tim

答:
The art of getting UCE (Unsolicited Commercial Email) through the maze of spam filters changes daily. I have a couple of suggestions:

1) Make sure your content is legitimate and professional... people will be less likely to report your stuff as spam.

2) Use the SMTP server of your ISP to send the mail. Most ISPs do a lot of work to ensure that their servers are not blacklisted. One of the worst things you can do is send it from your own computer/workstation from a dynamic IP address (coffee shop, home cable modem), since that your computer is not in the family of known mail servers (mostly defined by special types of DNS records). Your ISP's mail server is likely able to handle a large volume of mail properly without causing issues with spam filtering/delivery.

This could of course bring you up against your ISP's terms of service, but if you're sending the mail as a legitimate business communication you should be fine. Check with their technical support before you send it to make sure you're doing it by the book.

ContentLicense: CC BY-SA 2.5


问:
c++ iterator error "does not refer to a value"
I am just trying to create an iterator for a list of class pointers. I searched around for a while and could not find anything regarding this issue. Everything works fine until I try and create the iterator.

Here is the compilation error message I'm getting:

```<code>ProcessList.cpp:28:7: error: 'Process' does not refer to a value
            list<Process*>::iterator i;
                 ^
    ./Process.h:3:7: note: declared here
    class Process
          ^
    ProcessList.cpp:28:15: error: expected expression
            list<Process*>::iterator i;
                         ^
    ProcessList.cpp:28:18: error: cannot refer to class template 'iterator' without a template argument list
            list<Process*>::iterator i;
                          ~~^
    /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/iterator:431:30: note: template is declared here
    struct _LIBCPP_TYPE_VIS_ONLY iterator
                                 ^
    3 errors generated.
</code>```

Here is my code. The error comes from the ProcessList.cpp code at the bottom:

```<code>//main.cpp
#include <iostream>
#include <list>
#include <random>
#include "ProcessList.h"
#include "Generator.h"
using namespace std;

int main()
{

    ProcessList processList(2);

    processList.getProcess(processList.getProcessList());

    return 0;
}
</code>```

```<code>//Process.h
class Process
{
    public:
        Process();

        void setPID(int PID);
        int getPID();

        int calculateNumberOfCycles();
        int getNumberOfCycles();

        int calculateMemorySize();
        int getMemorySize();

    private:
        static int number_of_processes;
        int PID;
        int number_of_cycles;
        int memory_size;

};
</code>```

```<code>//Process.cpp
#include <iostream>
#include "Process.h"
using namespace std;

int Process::number_of_processes = 0;//define static variable

//Constructor
Process::Process()
{
    cout << "Process Constructor" << endl;

    PID = number_of_processes;
    number_of_cycles = number_of_processes;
    memory_size = number_of_processes;
    number_of_processes++;

    //number_of_cycles = setNumberOfCycles;
    //memory_size = setMemorySize;

}

//PID Setter
void Process::setPID(int PID)
{

}

//PID Getter
int Process::getPID()
{
    return PID;
}

//Generates a random number of cycles based od the defined variables
int Process::calculateNumberOfCycles()
{
    return 0;
}

//Returns the number of cycles of the process
int Process::getNumberOfCycles()
{
    return number_of_cycles;
}

//Generates a random amount of memory based on the defined variables
int Process::calculateMemorySize()
{
    return 0;
}

//Returns the amount of memory for the process
int Process::getMemorySize()
{
    return memory_size;
}
</code>```

```<code>//ProcessList.h
#include <list>
#include "Process.h"
 using namespace std;

class ProcessList
{
    private:
        list<Process*> processList;

    public:
        ProcessList(int number_of_processes_to_create);
        list<Process*> getProcessList();
        Process* createProcess();
        void getProcess(list<Process*> list);

};
</code>```

```<code>//ProcessList.cpp
 #include <iostream>
 #include "ProcessList.h"
 using namespace std;

ProcessList::ProcessList(int number_of_processes_to_create)
{
    processList.push_back(createProcess());
}

Process* ProcessList::createProcess()
{
    Process *process = new Process();

    return process;
}

list<Process*> ProcessList::getProcessList()
{
    return processList;
}

void ProcessList::getProcess(list<Process*> list)
{

    list<Process*>::iterator i;

}
</code>```

答:
Look at this function closely:

```<code>void ProcessList::getProcess(list<Process*> list)
{
   list<Process*>::iterator i;
}
</code>```

What does list mean within the function body? It's not std::list here, because you've hidden that with your parameter name. That makes no sense to the compiler.

An easy way to express what you really mean is qualify it:

```<code>void ProcessList::getProcess(list<Process*> list)
{
    std::list<Process*>::iterator i;
}
</code>```

But you should really just do that everywhere and forget you ever heard of using namespace std;. And it's not a good idea to use list as your parameter name, since it tends to confuse the reader if not the compiler.

Body:
I am just trying to create an iterator for a list of class pointers. I searched around for a while and could not find anything regarding this issue. Everything works fine until I try and create the iterator.

Here is the compilation error message I'm getting:

ProcessList.cpp:28:7: error: 'Process' does not refer to a value
            list<Process*>::iterator i;
                 ^
    ./Process.h:3:7: note: declared here
    class Process
          ^
    ProcessList.cpp:28:15: error: expected expression
            list<Process*>::iterator i;
                         ^
    ProcessList.cpp:28:18: error: cannot refer to class template 'iterator' without a template argument list
            list<Process*>::iterator i;
                          ~~^
    /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/iterator:431:30: note: template is declared here
    struct _LIBCPP_TYPE_VIS_ONLY iterator
                                 ^
    3 errors generated.

Here is my code. The error comes from the ProcessList.cpp code at the bottom:

//main.cpp
#include <iostream>
#include <list>
#include <random>
#include "ProcessList.h"
#include "Generator.h"
using namespace std;

int main()
{

    ProcessList processList(2);

    processList.getProcess(processList.getProcessList());

    return 0;
}

//Process.h
class Process
{
    public:
        Process();

        void setPID(int PID);
        int getPID();

        int calculateNumberOfCycles();
        int getNumberOfCycles();

        int calculateMemorySize();
        int getMemorySize();

    private:
        static int number_of_processes;
        int PID;
        int number_of_cycles;
        int memory_size;

};

//Process.cpp
#include <iostream>
#include "Process.h"
using namespace std;

int Process::number_of_processes = 0;//define static variable

//Constructor
Process::Process()
{
    cout << "Process Constructor" << endl;

    PID = number_of_processes;
    number_of_cycles = number_of_processes;
    memory_size = number_of_processes;
    number_of_processes++;

    //number_of_cycles = setNumberOfCycles;
    //memory_size = setMemorySize;

}

//PID Setter
void Process::setPID(int PID)
{

}

//PID Getter
int Process::getPID()
{
    return PID;
}

//Generates a random number of cycles based od the defined variables
int Process::calculateNumberOfCycles()
{
    return 0;
}

//Returns the number of cycles of the process
int Process::getNumberOfCycles()
{
    return number_of_cycles;
}

//Generates a random amount of memory based on the defined variables
int Process::calculateMemorySize()
{
    return 0;
}

//Returns the amount of memory for the process
int Process::getMemorySize()
{
    return memory_size;
}

//ProcessList.h
#include <list>
#include "Process.h"
 using namespace std;

class ProcessList
{
    private:
        list<Process*> processList;

    public:
        ProcessList(int number_of_processes_to_create);
        list<Process*> getProcessList();
        Process* createProcess();
        void getProcess(list<Process*> list);

};

//ProcessList.cpp
 #include <iostream>
 #include "ProcessList.h"
 using namespace std;

ProcessList::ProcessList(int number_of_processes_to_create)
{
    processList.push_back(createProcess());
}

Process* ProcessList::createProcess()
{
    Process *process = new Process();

    return process;
}

list<Process*> ProcessList::getProcessList()
{
    return processList;
}

void ProcessList::getProcess(list<Process*> list)
{

    list<Process*>::iterator i;

}

Body:
Look at this function closely:

void ProcessList::getProcess(list<Process*> list)
{
   list<Process*>::iterator i;
}

What does list mean within the function body? It's not std::list here, because you've hidden that with your parameter name. That makes no sense to the compiler.

An easy way to express what you really mean is qualify it:

void ProcessList::getProcess(list<Process*> list)
{
    std::list<Process*>::iterator i;
}

But you should really just do that everywhere and forget you ever heard of using namespace std;. And it's not a good idea to use list as your parameter name, since it tends to confuse the reader if not the compiler.


问:
How to keep dynamically generated HTML upon validation failure
I have a page with various input field. Some additional fields can be added and they are generated with Javascript. The issue I am having is that upon validation failure the page is reloaded and the generated content input fields are lost. How would I go about it to preserve these input fields? Thanks</p>

答:
I see the laravel tag but I do not know if you use laravel, for those who use laravel, you can retrieve the form data after server-side validation as below: </p>

```<code><input type="text" id="name" name="name" value="{{ old('name') }}">
</code>```

Body:
I see the laravel tag but I do not know if you use laravel, for those who use laravel, you can retrieve the form data after server-side validation as below:

<input type="text" id="name" name="name" value="{{ old('name') }}">


问:
How to merge multiple dataframes
I have different dataframes and need to merge them together based on the date column. If I only had two dataframes, I could use df1.merge(df2, on='date'), to do it with three dataframes, I use df1.merge(df2.merge(df3, on='date'), on='date'), however it becomes really complex and unreadable to do it with multiple dataframes.

All dataframes have one column in common -date, but they don't have the same number of rows nor columns and I only need those rows in which each date is common to every dataframe.

So, I'm trying to write a recursion function that returns a dataframe with all data but it didn't work. How should I merge multiple dataframes then?

I tried different ways and got errors like out of range, keyerror 0/1/2/3 and can not merge DataFrame with instance of type <class 'NoneType'>.

This is the script I wrote:

```<code>dfs = [df1, df2, df3] # list of dataframes

def mergefiles(dfs, countfiles, i=0):
    if i == (countfiles - 2): # it gets to the second to last and merges it with the last
        return

    dfm = dfs[i].merge(mergefiles(dfs[i+1], countfiles, i=i+1), on='date')
    return dfm

print(mergefiles(dfs, len(dfs)))
</code>```

An example:
df_1:

```<code>May 19, 2017;1,200.00;0.1%
May 18, 2017;1,100.00;0.1%
May 17, 2017;1,000.00;0.1%
May 15, 2017;1,901.00;0.1%
</code>```

df_2:

```<code>May 20, 2017;2,200.00;1000000;0.2%
May 18, 2017;2,100.00;1590000;0.2%
May 16, 2017;2,000.00;1230000;0.2%
May 15, 2017;2,902.00;1000000;0.2%
</code>```

df_3:

```<code>May 21, 2017;3,200.00;2000000;0.3%
May 17, 2017;3,100.00;2590000;0.3%
May 16, 2017;3,000.00;2230000;0.3%
May 15, 2017;3,903.00;2000000;0.3%
</code>```

Expected merge result:

```<code>May 15, 2017;  1,901.00;0.1%;  2,902.00;1000000;0.2%;   3,903.00;2000000;0.3%
</code>```

答:
Thank you for your help @jezrael, @zipa and @everestial007, both answers are what I need. If I wanted to make a recursive, this would also work as intended:

```<code>def mergefiles(dfs=[], on=''):
    """Merge a list of files based on one column"""
    if len(dfs) == 1:
         return "List only have one element."

    elif len(dfs) == 2:
        df1 = dfs[0]
        df2 = dfs[1]
        df = df1.merge(df2, on=on)
        return df

    # Merge the first and second datafranes into new dataframe
    df1 = dfs[0]
    df2 = dfs[1]
    df = dfs[0].merge(dfs[1], on=on)

    # Create new list with merged dataframe
    dfl = []
    dfl.append(df)

    # Join lists
    dfl = dfl + dfs[2:]
    dfm = mergefiles(dfl, on)
    return dfm
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to merge multiple dataframes

Body:
I have different dataframes and need to merge them together based on the date column. If I only had two dataframes, I could use df1.merge(df2, on='date'), to do it with three dataframes, I use df1.merge(df2.merge(df3, on='date'), on='date'), however it becomes really complex and unreadable to do it with multiple dataframes.

All dataframes have one column in common -date, but they don't have the same number of rows nor columns and I only need those rows in which each date is common to every dataframe.

So, I'm trying to write a recursion function that returns a dataframe with all data but it didn't work. How should I merge multiple dataframes then?

I tried different ways and got errors like out of range, keyerror 0/1/2/3 and can not merge DataFrame with instance of type <class 'NoneType'>.

This is the script I wrote:

dfs = [df1, df2, df3] # list of dataframes

def mergefiles(dfs, countfiles, i=0):
    if i == (countfiles - 2): # it gets to the second to last and merges it with the last
        return

    dfm = dfs[i].merge(mergefiles(dfs[i+1], countfiles, i=i+1), on='date')
    return dfm

print(mergefiles(dfs, len(dfs)))

An example:
df_1:

May 19, 2017;1,200.00;0.1%
May 18, 2017;1,100.00;0.1%
May 17, 2017;1,000.00;0.1%
May 15, 2017;1,901.00;0.1%

df_2:

May 20, 2017;2,200.00;1000000;0.2%
May 18, 2017;2,100.00;1590000;0.2%
May 16, 2017;2,000.00;1230000;0.2%
May 15, 2017;2,902.00;1000000;0.2%

df_3:

May 21, 2017;3,200.00;2000000;0.3%
May 17, 2017;3,100.00;2590000;0.3%
May 16, 2017;3,000.00;2230000;0.3%
May 15, 2017;3,903.00;2000000;0.3%

Expected merge result:

May 15, 2017;  1,901.00;0.1%;  2,902.00;1000000;0.2%;   3,903.00;2000000;0.3%

Body:
Thank you for your help @jezrael, @zipa and @everestial007, both answers are what I need. If I wanted to make a recursive, this would also work as intended:

def mergefiles(dfs=[], on=''):
    """Merge a list of files based on one column"""
    if len(dfs) == 1:
         return "List only have one element."

    elif len(dfs) == 2:
        df1 = dfs[0]
        df2 = dfs[1]
        df = df1.merge(df2, on=on)
        return df

    # Merge the first and second datafranes into new dataframe
    df1 = dfs[0]
    df2 = dfs[1]
    df = dfs[0].merge(dfs[1], on=on)

    # Create new list with merged dataframe
    dfl = []
    dfl.append(df)

    # Join lists
    dfl = dfl + dfs[2:]
    dfm = mergefiles(dfl, on)
    return dfm


问:
Powershell force 5 digit format in a string pattern
So what I have now will (below) will search for XX-##-# and force it to XX-##-#0000.

How can I do this to return XX-##-0000#?

Is there a way to force 5 digits at the end, filling preceding 0s, to cover the other possibilities (XX-##-##, XX-##-###, XX-##-####)? As opposed to copying this 4 times, slightly adjusting for each.

```<code>$Pattern1 = '[a-zA-Z][a-zA-Z]-[0-9][0-9]-[0-9]'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse | ForEach {
     (Get-Content $_ |
     ForEach  { $_ -replace $Pattern1, ('$1'+'0000')}) |
     Set-Content $_
}
</code>```

Thanks.

EDIT: I would like to do the following

```<code>Search           Replacement
XX-##-#          XX-##-0000#
XX-##-##         XX-##-000##
XX-##-###        XX-##-00###
XX-##-####       XX-##-0####
</code>```

答:
Create capturing groups. Combine them while applying the formatting to the second.

Edit: Updated to remove the assumption that the line is only the matching string. Note, the assumption that there is only one match per line still exists.

```<code>$Pattern1 = '^(.*?)([a-zA-Z][a-zA-Z]-\d\d-)(\d+)(.*)$'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse |
    ForEach-Object {
        (Get-Content $_ |
            ForEach-Object {
                if ($_ -match $Pattern1) {
                     "{0}{1}{2:D5}{3}" -f $matches[1],$matches[2],[int]$matches[3],$matches[4]
                } else {
                    $_
                }
            }) | Set-Content -Path $_
    }
</code>```

Body:
So what I have now will (below) will search for XX-##-# and force it to XX-##-#0000.

How can I do this to return XX-##-0000#?

Is there a way to force 5 digits at the end, filling preceding 0s, to cover the other possibilities (XX-##-##, XX-##-###, XX-##-####)? As opposed to copying this 4 times, slightly adjusting for each.

$Pattern1 = '[a-zA-Z][a-zA-Z]-[0-9][0-9]-[0-9]'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse | ForEach {
     (Get-Content $_ |
     ForEach  { $_ -replace $Pattern1, ('$1'+'0000')}) |
     Set-Content $_
}

Thanks.

EDIT: I would like to do the following

Search           Replacement
XX-##-#          XX-##-0000#
XX-##-##         XX-##-000##
XX-##-###        XX-##-00###
XX-##-####       XX-##-0####

Body:
Create capturing groups. Combine them while applying the formatting to the second.

Edit: Updated to remove the assumption that the line is only the matching string. Note, the assumption that there is only one match per line still exists.

$Pattern1 = '^(.*?)([a-zA-Z][a-zA-Z]-\d\d-)(\d+)(.*)$'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse |
    ForEach-Object {
        (Get-Content $_ |
            ForEach-Object {
                if ($_ -match $Pattern1) {
                     "{0}{1}{2:D5}{3}" -f $matches[1],$matches[2],[int]$matches[3],$matches[4]
                } else {
                    $_
                }
            }) | Set-Content -Path $_
    }


问:
Start a Animation when I press a Button doesn't work
I have a beginning Animation which is called divanimated. Its a rectangel which comes in. Now I want to start a 2nd Animation on this div when I hit a button. I don't know why it isn't working.
Here is my code:

```<code>    <div class="div"> </div>
    <img src="/arrowright.png" class="arrowright">
    <script>
        $(".arrowright").click(function(){
            $(".div").toggleClass("divanimated");
        });
    </script>
</code>```

css:

```<code>.divanimated{
animation-name: divanimated;
-webkit-animation-name: divanimated;

animation-duration: 1.5s;
-webkit-animation-duration: 1.5s;

animation-timing-function: ease-out;
-webkit-animation-timing-function: ease-out;

transform-origin: 0% 0%;
-ms-transform-origin: 0% 0%;
-webkit-transform-origin: 0% 0%;

 background: #e74c3c;
z-index: 1;
width: 72.8vw;
height: 39vh;
margin-top: 136.5vh;
margin-left: 13.6vw;
position: absolute;
border-radius: 7vh;
display: none;
box-shadow:2px 2px 10px #333333;
}

@keyframes divanimated{
0% {
    transform: scaleX(0.3);
}
40% {
    transform: scaleX(1.02);
}
60% {
    transform: scaleX(0.98);
}
80% {
    transform: scaleX(1.01);
}
100% {
    transform: scaleX(0.98);
}
80% {
    transform: scaleX(1.01);
}
100% {
    transform: scaleX(1);
}
}

@-webkit-keyframes divanimated{
0% {
    -webkit-transform: scaleX(0.3);
}
40% {
    -webkit-transform: scaleX(1.02);
}
60% {
    -webkit-transform: scaleX(0.98);
}
80% {
    -webkit-transform: scaleX(1.01);
}
100% {
    -webkit-transform: scaleX(0.98);
}
80% {
    -webkit-transform: scaleX(1.01);
}
100% {
    -webkit-transform: scaleX(1);
}
}
.div{
animation-name: div;
-webkit-animation-name: div;

animation-duration: 1.6s;
-webkit-animation-duration: 1.6s;

animation-timing-function: ease-out;
-webkit-animation-timing-function: ease -out;

visibility: visible !important;

background: #e74c3c;
z-index: 1;
width: 72.8vw;
height: 39vh;
margin-top: 136.5vh;
margin-left: 13.6vw;
position: absolute;
border-radius: 7vh;
display: none;
box-shadow:2px 2px 10px #333333;
}

@keyframes div{
0% {
    transform: translateY(100%) scaleX(0.5);
}
30%{
    transform: translateY(-8%) scaleX(0.5);
}
40%{
    transform: translateY(2%) scaleX(0.5);
}
50%{
    transform: translateY(0%) scaleX(1.1);
}
60%{
    transform: translateY(0%) scaleX(0.9);
}
70% {
    transform: translateY(0%) scaleX(1.05);
}
80%{
    transform: translateY(0%) scaleX(0.95);
}
90% {
    transform: translateY(0%) scaleX(1.02);
}
100%{
    transform: translateY(0%) scaleX(1);
}
}

@-webkit-keyframes div{
0% {
    -webkit-transform: translateY(100%) scaleX(0.5);
}
30%{
    -webkit-transform: translateY(-8%) scaleX(0.5);
}
40%{
    -webkit-transform: translateY(2%) scaleX(0.5);
}
50%{
    -webkit-transform: translateY(0%) scaleX(1.1);
}
60%{
    -webkit-transform: translateY(0%) scaleX(0.9);
}
70% {
    -webkit-transform: translateY(0%) scaleX(1.05);
}
80%{
    -webkit-transform: translateY(0%) scaleX(0.95);
}
90% {
    -webkit-transform: translateY(0%) scaleX(1.02);
}
100%{
    -webkit-transform: translateY(0%) scaleX(1);
}
}
</code>```

Can someone help me ? Whats wrong with my code ?

Thanks for the help.

答:
Thanks to all which helped me :)
I got it and I am really happy about it. Thanks to all.</p>

Body:
I have a beginning Animation which is called divanimated. Its a rectangel which comes in. Now I want to start a 2nd Animation on this div when I hit a button. I don't know why it isn't working.
Here is my code:

css:

.divanimated{
animation-name: divanimated;
-webkit-animation-name: divanimated;

animation-duration: 1.5s;
-webkit-animation-duration: 1.5s;

animation-timing-function: ease-out;
-webkit-animation-timing-function: ease-out;

transform-origin: 0% 0%;
-ms-transform-origin: 0% 0%;
-webkit-transform-origin: 0% 0%;

 background: #e74c3c;
z-index: 1;
width: 72.8vw;
height: 39vh;
margin-top: 136.5vh;
margin-left: 13.6vw;
position: absolute;
border-radius: 7vh;
display: none;
box-shadow:2px 2px 10px #333333;
}

@keyframes divanimated{
0% {
    transform: scaleX(0.3);
}
40% {
    transform: scaleX(1.02);
}
60% {
    transform: scaleX(0.98);
}
80% {
    transform: scaleX(1.01);
}
100% {
    transform: scaleX(0.98);
}
80% {
    transform: scaleX(1.01);
}
100% {
    transform: scaleX(1);
}
}

@-webkit-keyframes divanimated{
0% {
    -webkit-transform: scaleX(0.3);
}
40% {
    -webkit-transform: scaleX(1.02);
}
60% {
    -webkit-transform: scaleX(0.98);
}
80% {
    -webkit-transform: scaleX(1.01);
}
100% {
    -webkit-transform: scaleX(0.98);
}
80% {
    -webkit-transform: scaleX(1.01);
}
100% {
    -webkit-transform: scaleX(1);
}
}
.div{
animation-name: div;
-webkit-animation-name: div;

animation-duration: 1.6s;
-webkit-animation-duration: 1.6s;

animation-timing-function: ease-out;
-webkit-animation-timing-function: ease -out;

visibility: visible !important;

background: #e74c3c;
z-index: 1;
width: 72.8vw;
height: 39vh;
margin-top: 136.5vh;
margin-left: 13.6vw;
position: absolute;
border-radius: 7vh;
display: none;
box-shadow:2px 2px 10px #333333;
}

@keyframes div{
0% {
    transform: translateY(100%) scaleX(0.5);
}
30%{
    transform: translateY(-8%) scaleX(0.5);
}
40%{
    transform: translateY(2%) scaleX(0.5);
}
50%{
    transform: translateY(0%) scaleX(1.1);
}
60%{
    transform: translateY(0%) scaleX(0.9);
}
70% {
    transform: translateY(0%) scaleX(1.05);
}
80%{
    transform: translateY(0%) scaleX(0.95);
}
90% {
    transform: translateY(0%) scaleX(1.02);
}
100%{
    transform: translateY(0%) scaleX(1);
}
}

@-webkit-keyframes div{
0% {
    -webkit-transform: translateY(100%) scaleX(0.5);
}
30%{
    -webkit-transform: translateY(-8%) scaleX(0.5);
}
40%{
    -webkit-transform: translateY(2%) scaleX(0.5);
}
50%{
    -webkit-transform: translateY(0%) scaleX(1.1);
}
60%{
    -webkit-transform: translateY(0%) scaleX(0.9);
}
70% {
    -webkit-transform: translateY(0%) scaleX(1.05);
}
80%{
    -webkit-transform: translateY(0%) scaleX(0.95);
}
90% {
    -webkit-transform: translateY(0%) scaleX(1.02);
}
100%{
    -webkit-transform: translateY(0%) scaleX(1);
}
}

Can someone help me ? Whats wrong with my code ?

Thanks for the help.


问:
How to get DistributedLDAModel in org.apache.spark.ml.clustering.LDA
I am trying to get the DistributedLDAModel for LDA ml library. I am seeing examples with mllib LDA and not ml LDA. Is there any sample code which I can follow?</p>

答:
To get a DistributedLDAModel instead of a LocalLDAModel, you need to use the Expectation-Maximization (EM) optimizer instead of the default Online Variational Bayes (online) one.

Concretely, use setOptimizer('em') on your LDA builder to get a distributed model:

```<code>val lda = new LDA().setOptimizer("em")
</code>```

Body:
To get a DistributedLDAModel instead of a LocalLDAModel, you need to use the Expectation-Maximization (EM) optimizer instead of the default Online Variational Bayes (online) one.

Concretely, use setOptimizer('em') on your LDA builder to get a distributed model:

val lda = new LDA().setOptimizer("em")


问:
How can I send stuff commands to a start-in-detached screen?
Any session that I start with "-d -m" doesn't accept "-X stuff [...]" commands unless I've attached to the screen at least once.  There is no error message, the commands just do not get through.

The problem is that I start the session from a cron job and am unable to attach to the screen from within cron.

Steps to repeat

```<code>$ screen -m -d -S mydaemon bash
$ screen -S mydaemon -X stuff "`printf "exit\\r"`"
$ screen -ls
        32456.mydaemon  (Detached)
$ screen -r -S mydaemon
$ ^a d
$ screen -S mydaemon -X stuff "`printf "exit\\r"`"
$ screen -ls
No Sockets found in /var/run/screen/S-user
</code>```

^a d indicates pressing Ctrl+a then pressing d.

Versions

```<code>CentOS release 5.5 (Final)
Screen version 4.00.03 (FAU) 23-Oct-06
</code>```

答:
Using the .screenrc file, you can set things to start;

```<code>screen -t <title> <window position> <command>
</code>```

So, if you wanted to start top in window 7, you'd do

```<code>screen -t window7top 7 top
</code>```

Body:
Any session that I start with "-d -m" doesn't accept "-X stuff [...]" commands unless I've attached to the screen at least once.  There is no error message, the commands just do not get through.

The problem is that I start the session from a cron job and am unable to attach to the screen from within cron.

Steps to repeat

$ screen -m -d -S mydaemon bash
$ screen -S mydaemon -X stuff "`printf "exit\\r"`"
$ screen -ls
        32456.mydaemon  (Detached)
$ screen -r -S mydaemon
$ ^a d
$ screen -S mydaemon -X stuff "`printf "exit\\r"`"
$ screen -ls
No Sockets found in /var/run/screen/S-user

^a d indicates pressing Ctrl+a then pressing d.

Versions

CentOS release 5.5 (Final)
Screen version 4.00.03 (FAU) 23-Oct-06

Body:
Using the .screenrc file, you can set things to start;

screen -t <title> <window position> <command>

So, if you wanted to start top in window 7, you'd do

screen -t window7top 7 top


问:
Search keywords with enter key - BUG
So, i'm developing a search feature in my website, and i want to redirect the user to a page with the keywords he is trying to search.

The following code works, but there is a bug: when i click enter in my homepage it works. The user is successfully redirected to my search page with the results. But when i'm in that page (or any other page) the enter key does not work! Only the button works all the time! It's a strange error and i dont know what to do...

This code is in my masterpage (.net 4.0) and it is the parent of all my webforms (including home). Can anyone help me?

<asp:TextBox ID="TBPesquisa" runat="server" placeholder="Pesquise produtos aqui" onkeypress="return runScript(event)"></asp:TextBox>

<button id="BTPesquisa" class="button-search" type="button" onClick="javascript:window.location.assign('/Pesquisa?val='+encodeURIComponent(document.getElementById('TBPesquisa').value));">Pesquisar</button>

```

答:
Probably, the reason is that the TBPesquia field wasn't found, as this is an asp.net textbox control, and the ID might not be what you expect it to be.

Now you could either go for setting the ClientID property, like:

```<code><asp:TextBox ID="TBPesquisa" ClientID="TBPesquisa" runat="server" placeholder="Pesquise produtos aqui" onkeypress="return runScript(event)"></asp:TextBox>
</code>```

or you could rewrite your handler slightly, by doing the following

```<code><asp:TextBox ID="TBPesquisa" runat="server" placeholder="Pesquise produtos aqui" onkeypress="runScript(event)"></asp:TextBox>
</code>```

and change the runscript to:

```<code> function runScript(e) {
   var source = e.target;
   if (e.keyCode === 13) {
     searchFor( source.value );
     e.preventDefault();
   }
 }

 function searchFor( textValue ) {
   window.location.assign('/Pesquisa?val=' + encodeURIComponent(textValue));
 }
</code>```

I would btw rather put the code for searching outside of the searchbutton itself, it only makes sense to have this outside of your html element

Title: Search keywords with enter key - BUG

Body:
Probably, the reason is that the TBPesquia field wasn't found, as this is an asp.net textbox control, and the ID might not be what you expect it to be.

Now you could either go for setting the ClientID property, like:

<asp:TextBox ID="TBPesquisa" ClientID="TBPesquisa" runat="server" placeholder="Pesquise produtos aqui" onkeypress="return runScript(event)"></asp:TextBox>

or you could rewrite your handler slightly, by doing the following

<asp:TextBox ID="TBPesquisa" runat="server" placeholder="Pesquise produtos aqui" onkeypress="runScript(event)"></asp:TextBox>

and change the runscript to:

 function runScript(e) {
   var source = e.target;
   if (e.keyCode === 13) {
     searchFor( source.value );
     e.preventDefault();
   }
 }

 function searchFor( textValue ) {
   window.location.assign('/Pesquisa?val=' + encodeURIComponent(textValue));
 }

I would btw rather put the code for searching outside of the searchbutton itself, it only makes sense to have this outside of your html element


问:
Standalone Java Application, no beans get created in the Spring Application Context? (IntelliJ, JavaConfig)
I am new to Spring so I've no doubt I've probably overlooked something simple. I am making a standalone application using Spring to aid with dependency injection and AOP.

The problem is none of the beans are available in the spring application context when I run the application. The bean I want to inject is of type: WatchKey. The application seems to run fine but when an event occurs in the "watched" folder I'll get NullPointerException saying the WatchKey variable is null.

These are the beans I'm declaring in my config file

```<code>@Configuration
public class FileManagerConfig
{
    @Bean
    public Path FTPPath ()
    {
        Path FTPDir = null;
        try {
            FTPDir = FileSystems.getDefault().getPath("PATH_TO_FOLDER");
        } catch (Exception e) {
        e.printStackTrace();
        }
        return FTPDir;
    }

    @Bean
    public WatchService getWatcher ()
    {
        WatchService watcher = null;
        try {
            watcher = FileSystems.getDefault().newWatchService();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return watcher;
    }

    @Bean
    public WatchKey getKey(Path path, WatchService FTPWatcher)
    {
        WatchKey key = null;
        try {
            key = path.register(FTPWatcher, ENTRY_CREATE);
            key = FTPWatcher.take();
        } catch (IOException | InterruptedException e) {
            System.out.println(e.getMessage());
        }
        return key;
    }
}
</code>```

The last bean is the one I want to autowire in the main application. The other beans are injected into the last bean.

Please note I have told IntelliJ about this configuration file in Project Structure > Facets.

Please also note when getKey is run, the key is NOT null (I put an if statement in the try block to check).

The following is the class that requires the WatchKey dependency:

```<code>public class FTPWatchZip extends Observable
{
    private boolean run;

    @Autowired
    private WatchKey key;

    public FTPWatchZip()
    {
        run = true;
        watch(key);
    }

    @Autowired
    private void watch(WatchKey key)
    {
        try {
            while(run)
            {
                for (WatchEvent<?> event : key.pollEvents())
                {
                    if (event.kind() == ENTRY_CREATE) {
                        System.out.println("New file detected in FTP Folder\nDownloading...");
                        TimeUnit.SECONDS.sleep(30);
                        System.out.println("Notify subscribers\n");
                    }
                }
                key.reset();
            }
        } catch(InterruptedException e) {
            System.out.println(e.getMessage());
        }
    }
}
</code>```

I have noticed IntelliJ tells me (when I hover over @Autowired):

Autowired members must be defined in valid Spring bean (@Component|@Servuce|...).

Which suggests to me the necessary beans are not being put into the Spring Application Context.

For completeness here is my main class, I have tried different versions of main in order to try and solve this issue but this is what it is at the moment:

```<code>public class DuckCreekMonitor
{
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(FileManagerConfig.class);
        new FTPWatchZip();
    }
}
</code>```

When I run the program the following is printed to the console:

Jun 07, 2017 5:01:25 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5ef04b5: startup date [Wed Jun 07 17:01:25 BST 2017]; root of context hierarchy

It then appears to "Watch" the folder for changes, anytime it detects a change in that directory I get a NullPointerException and a stacktrace.

Therefore I don't think the beans are being autowired into my function. Would anyone know anything I can try?

答:
How would Spring be aware of your FTPWatchZip class? you should annotate it with @Component or @Service, and this is what IntelliJ is telling you. or Make it a bean as you did for the others: </p>

```<code>    @Bean
    public FTPWatchZip getFTPWatch ()
    {

        return new FTPWatchZip();
    }
</code>```

Body:
I am new to Spring so I've no doubt I've probably overlooked something simple. I am making a standalone application using Spring to aid with dependency injection and AOP.

The problem is none of the beans are available in the spring application context when I run the application. The bean I want to inject is of type: WatchKey. The application seems to run fine but when an event occurs in the "watched" folder I'll get NullPointerException saying the WatchKey variable is null.

These are the beans I'm declaring in my config file

@Configuration
public class FileManagerConfig
{
    @Bean
    public Path FTPPath ()
    {
        Path FTPDir = null;
        try {
            FTPDir = FileSystems.getDefault().getPath("PATH_TO_FOLDER");
        } catch (Exception e) {
        e.printStackTrace();
        }
        return FTPDir;
    }

    @Bean
    public WatchService getWatcher ()
    {
        WatchService watcher = null;
        try {
            watcher = FileSystems.getDefault().newWatchService();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return watcher;
    }

    @Bean
    public WatchKey getKey(Path path, WatchService FTPWatcher)
    {
        WatchKey key = null;
        try {
            key = path.register(FTPWatcher, ENTRY_CREATE);
            key = FTPWatcher.take();
        } catch (IOException | InterruptedException e) {
            System.out.println(e.getMessage());
        }
        return key;
    }
}

The last bean is the one I want to autowire in the main application. The other beans are injected into the last bean.

Please note I have told IntelliJ about this configuration file in Project Structure > Facets.

Please also note when getKey is run, the key is NOT null (I put an if statement in the try block to check).

The following is the class that requires the WatchKey dependency:

public class FTPWatchZip extends Observable
{
    private boolean run;

    @Autowired
    private WatchKey key;

    public FTPWatchZip()
    {
        run = true;
        watch(key);
    }

    @Autowired
    private void watch(WatchKey key)
    {
        try {
            while(run)
            {
                for (WatchEvent<?> event : key.pollEvents())
                {
                    if (event.kind() == ENTRY_CREATE) {
                        System.out.println("New file detected in FTP Folder\nDownloading...");
                        TimeUnit.SECONDS.sleep(30);
                        System.out.println("Notify subscribers\n");
                    }
                }
                key.reset();
            }
        } catch(InterruptedException e) {
            System.out.println(e.getMessage());
        }
    }
}

I have noticed IntelliJ tells me (when I hover over @Autowired):

Autowired members must be defined in valid Spring bean (@Component|@Servuce|...).

Which suggests to me the necessary beans are not being put into the Spring Application Context.

For completeness here is my main class, I have tried different versions of main in order to try and solve this issue but this is what it is at the moment:

public class DuckCreekMonitor
{
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(FileManagerConfig.class);
        new FTPWatchZip();
    }
}

When I run the program the following is printed to the console:

Jun 07, 2017 5:01:25 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5ef04b5: startup date [Wed Jun 07 17:01:25 BST 2017]; root of context hierarchy

It then appears to "Watch" the folder for changes, anytime it detects a change in that directory I get a NullPointerException and a stacktrace.

Therefore I don't think the beans are being autowired into my function. Would anyone know anything I can try?

Body:
How would Spring be aware of your FTPWatchZip class? you should annotate it with @Component or @Service, and this is what IntelliJ is telling you. or Make it a bean as you did for the others:

    @Bean
    public FTPWatchZip getFTPWatch ()
    {

        return new FTPWatchZip();
    }


问:
Does it make sense to convert sub class to parent class this way?
```<code>class Student{
}

class CollegeStudent extends Student{
}
</code>```

I have a list of CollegeStudent, and I want to convert it to a list of Student:

```<code>List<CollegeStudent> collegeStudents = getStudents();
List<Student> students = new ArrayList<Student>();
for(CollegeStudent s : collegeStudents){
     students.add(s);
}
</code>```

Is this the appropriate way to achieve the purpose? Is the purpose sound? The reason I want to do this is I need to create another class, which takes a list of Student as parameters, not list of CollegeStduent.

答:
That's fine, but there are a few shorter ways:</p>

```<code>// Using the Collection<? extends E> constructor:
List<Student> studentsA = new ArrayList<>(collegeStudents);
// Using Collections.unmodifiableList which returns
// an unmodifiable view of the List<CollegeStudent>
// as a List<Student> without copying its elements:
List<Student> studentsB = Collections.unmodifiableList(collegeStudents);
// Older versions of Java might require a type
// witness for Collections.unmodifiableList:
List<Student> studentsC = Collections.<Student>unmodifiableList(collegeStudents);
</code>```

Body:
class Student{
}

class CollegeStudent extends Student{
}

I have a list of CollegeStudent, and I want to convert it to a list of Student:

List<CollegeStudent> collegeStudents = getStudents();
List<Student> students = new ArrayList<Student>();
for(CollegeStudent s : collegeStudents){
     students.add(s);
}

Is this the appropriate way to achieve the purpose? Is the purpose sound? The reason I want to do this is I need to create another class, which takes a list of Student as parameters, not list of CollegeStduent.

Body:
That's fine, but there are a few shorter ways:

// Using the Collection<? extends E> constructor:
List<Student> studentsA = new ArrayList<>(collegeStudents);
// Using Collections.unmodifiableList which returns
// an unmodifiable view of the List<CollegeStudent>
// as a List<Student> without copying its elements:
List<Student> studentsB = Collections.unmodifiableList(collegeStudents);
// Older versions of Java might require a type
// witness for Collections.unmodifiableList:
List<Student> studentsC = Collections.<Student>unmodifiableList(collegeStudents);


问:
Getting the binary value of a character string in Powershell
```<code>$getInput = Read-Host "ASCII or Binary? `n"
$getInput = $getInput.toLower()

if($getInput -eq "ascii"){

    ""

    #Write-Host "Type In Your ASCII" -backgroundcolor "black"
    $getAscii = Read-Host "Type In Your ASCII`n"
    ""
    ""
    $readAscii = @($getAscii)
    [byte[]]$outBytes = $readAscii

}
elseif($getInput -eq "binary"){

}
else{
    Write-Host "Wrong Input... [ASCII] or [BINARY]" -backgroundcolor "red" -foregroundcolor "white"
}
</code>```

I want to be able to get a users paragraph or whatever string they put in and convert it to binary. The [conver]::toString($getAscii,2) only works for integers.

答:
I recommend utilizing the Encoding library similarly to this user:

```<code>$stringToConvert = "Hello World"

    $test = [System.Text.Encoding]::UTF8.GetBytes($stringToConvert) | %{ [System.Convert]::ToString($_,2).PadLeft(8,'0') }

    $test
</code>```

Source: https://www.reddit.com/r/PowerShell/comments/3e82vk/convert_string_to_binary_and_back/

*Note: I believe the original poster of this method intended to assign $foo to the second conversion. I believe it will work either way because the return will be dumped to the variable below.

Body:
$getInput = Read-Host "ASCII or Binary? `n"
$getInput = $getInput.toLower()

if($getInput -eq "ascii"){

    ""

    #Write-Host "Type In Your ASCII" -backgroundcolor "black"
    $getAscii = Read-Host "Type In Your ASCII`n"
    ""
    ""
    $readAscii = @($getAscii)
    [byte[]]$outBytes = $readAscii

}
elseif($getInput -eq "binary"){

}
else{
    Write-Host "Wrong Input... [ASCII] or [BINARY]" -backgroundcolor "red" -foregroundcolor "white"
}

I want to be able to get a users paragraph or whatever string they put in and convert it to binary. The [conver]::toString($getAscii,2) only works for integers.

Body:
I recommend utilizing the Encoding library similarly to this user:

$stringToConvert = "Hello World"

    $test = [System.Text.Encoding]::UTF8.GetBytes($stringToConvert) | %{ [System.Convert]::ToString($_,2).PadLeft(8,'0') }

    $test

Source: https://www.reddit.com/r/PowerShell/comments/3e82vk/convert_string_to_binary_and_back/

*Note: I believe the original poster of this method intended to assign $foo to the second conversion. I believe it will work either way because the return will be dumped to the variable below.


问:
Idling thread between curl_multi_perform
I have an update thread which runs curl_multi_perform in a while loop in it. I want to make sure the thread doesn't just sit there and spin, so I'd like to throttle it to a few updates per second. This works fine, except for when doing file uploads or downloads on 10+ MB files, when curl_multi_perform has to be called pretty much continuously to get around the upload/download chunk limit.

Is there a way to poll if curl_multi_perform will need to be called right away again in the next update loop, or if it's okay to let the thread idle for ~100 ms? I thought curl_multi_wait would be used for this, but the thread seems to be spinning up the CPU while inside curl_multi_wait anyway, so that doesn't seem right.

答:
I recommend sleep_until instead of sleep_for for your application:

```<code>using namespace std::chrono;
auto next = steady_clock::now() + milliseconds{10};
while(runUpdateThread)
{
    curl_multi_perform(mCurlHandle, &handleCount);

    /* handle call results */

    std::this_thread::sleep_until( next );
    next += milliseconds{10};
}
</code>```

Now if the upload/download takes a long time, the sleep_until doesn't sleep at all.  This effectively gives you the auto throttling you are after.

Body:
I recommend sleep_until instead of sleep_for for your application:

using namespace std::chrono;
auto next = steady_clock::now() + milliseconds{10};
while(runUpdateThread)
{
    curl_multi_perform(mCurlHandle, &handleCount);

    /* handle call results */

    std::this_thread::sleep_until( next );
    next += milliseconds{10};
}

Now if the upload/download takes a long time, the sleep_until doesn't sleep at all.  This effectively gives you the auto throttling you are after.


问:
Combination and Multiplying Rows of array in matlab
I have a matrix (89x42) of 0's and 1's that I'd like to multiply combinations of rows together.

For example, for matrix

```<code>input = [1 0 1
         0 0 0
         1 1 0];
</code>```

and with 2 combinations, I want an output of

```<code>output = [0 0 0; % (row1*row2)
          1 0 0; % (row1*row3)
          0 0 0] % (row2*row3)
</code>```

Which rows to multiply is dictated by "n Choose 2" (nCk), or all possible combinations of the rows n taken k at a time. In this case k=2.

Currently I am using a loop and it works fine for the 89C2 combinations of rows, but when I run it with 89C3 it takes far too long too run.

What would be the most efficient way to do this program so I can do more than 2 combinations?

答:
Several things you can do:

Use logical ("binary") arrays (or even sparse logical arrays) instead of double arrays.

Use optimized combinatorical functions.

bitand or and instead of times (where applicable).

Vectorize:

```<code>function out = q44417404(I,k)

if nargin == 0
  rng(44417404);
  I = randi(2,89,42)-1 == 1;
  k = 3;
end

out = permute(prod(reshape(I(nchoosek(1:size(I,1),k).',:).',size(I,2),k,[]),2),[3,1,2]);
</code>```

Body:
I have a matrix (89x42) of 0's and 1's that I'd like to multiply combinations of rows together.

For example, for matrix

input = [1 0 1
         0 0 0
         1 1 0];

and with 2 combinations, I want an output of

output = [0 0 0; % (row1*row2)
          1 0 0; % (row1*row3)
          0 0 0] % (row2*row3)

Which rows to multiply is dictated by "n Choose 2" (nCk), or all possible combinations of the rows n taken k at a time. In this case k=2.

Currently I am using a loop and it works fine for the 89C2 combinations of rows, but when I run it with 89C3 it takes far too long too run.

What would be the most efficient way to do this program so I can do more than 2 combinations?

Body:
Several things you can do:

Use logical ("binary") arrays (or even sparse logical arrays) instead of double arrays.

Use optimized combinatorical functions.

bitand or and instead of times (where applicable).

Vectorize:

function out = q44417404(I,k)

if nargin == 0
  rng(44417404);
  I = randi(2,89,42)-1 == 1;
  k = 3;
end

out = permute(prod(reshape(I(nchoosek(1:size(I,1),k).',:).',size(I,2),k,[]),2),[3,1,2]);


问:
Python: condensing arbitrarily large dataframe query
I am using a pandas dataframe, and am iterating over all possible combinations of values in several columns.  I do this using itertools.combinations and pandas.Series.unique():

```<code>query_fields = ['direction','subj_id','speed']
query_items = [df_reps[k].unique() for k in query_fields]

for a in itertools.product(*query_items):
    df = df_reps[(df_reps['subj_id']==a[0]) & (df_reps['direction']==a[1]) & (df_reps['speed']==a[2])]
    #Do something with df
</code>```

I'm wondering if there is a more pythonic way of condensing my dataframe query.  If I had more possibly query fields then this approach would become increasingly unusable.  One possible method is to iterate over all the fields and apply each query individually (like a funnel) - could this be done with list comprehension, something like:

```<code>df = df_reps[(df_reps[qf]==a[i]) for qf,i in enumerate(query_fields)] #Doesn't work
</code>```

Does this functionality already exist in pandas?

EDIT

Input: A DataFrame and a list containing headers.

Output: A loop or similiar, selecting each unique combination of values in the columns specified by the header list.

答:
use pandas.DataFrame.drop_duplicates;

```<code>unique_df = df_reps.drop_duplicates(['direction','subj_id','speed'])
</code>```

You now have a new dataframe that you can continue to slice by other conditions, like;

```<code>unique_df[unique_df['direction'] == 'left']
</code>```

Body:
I am using a pandas dataframe, and am iterating over all possible combinations of values in several columns.  I do this using itertools.combinations and pandas.Series.unique():

query_fields = ['direction','subj_id','speed']
query_items = [df_reps[k].unique() for k in query_fields]

for a in itertools.product(*query_items):
    df = df_reps[(df_reps['subj_id']==a[0]) & (df_reps['direction']==a[1]) & (df_reps['speed']==a[2])]
    #Do something with df

I'm wondering if there is a more pythonic way of condensing my dataframe query.  If I had more possibly query fields then this approach would become increasingly unusable.  One possible method is to iterate over all the fields and apply each query individually (like a funnel) - could this be done with list comprehension, something like:

df = df_reps[(df_reps[qf]==a[i]) for qf,i in enumerate(query_fields)] #Doesn't work

Does this functionality already exist in pandas?

EDIT

Input: A DataFrame and a list containing headers.

Output: A loop or similiar, selecting each unique combination of values in the columns specified by the header list.

Body:
use pandas.DataFrame.drop_duplicates;

unique_df = df_reps.drop_duplicates(['direction','subj_id','speed'])

You now have a new dataframe that you can continue to slice by other conditions, like;

unique_df[unique_df['direction'] == 'left']


问:
VS2015 JavaScript language service has encountered an error and has been shut down
I ran into this issue and it refuses to go away.  Error popsup every time I load any project/solution.  I tried some solutions for VS 2013 but those didn't work for VS 2015.  I have update3 and .net core installed.  I've tried uninstalling all that but issue remains.  Any ideas? </p>

答:
I've tried a few other links to SO that don't work.

Near as I can tell because I've customized an ad blocker in Chrome and I do debugging in other Chrome windows by attaching to those processes that this might cause it but that's not proven.

However, if I've been to Fox News, which is what I have the .js snippet for and I've left the Chrome Tools window open, this error does occur.

I've saved the .js file, removed the folder from Chrome to see if this will handle it.


问:
Relational tables: a 3rd table with relations
I'm building a php page that will show an specific banner when the user enters his/her phone number in a form field.

So here's my logic for the database:

Table phones with fields: id, name of user and phone number.
Table banners with fields: id, banner's name/title and banner (path to the image).
Table relation with fields: here's where the phone number should be related to a banner and where I need your help :)

And here's my logic for the php page:

-form gets the phone number
-I query the data base
-I show the banner related to the phone number entered in the form.

Below is the code for the table creation so far .. as you'll see don't know how to advance.

Thanks a million

```<code>    CREATE TABLE phones(

id_phone INT NOT NULL AUTO_INCREMENT,

nombre VARCHAR(30),

number INT (9),

PRIMARY KEY (id_phone)

) TYPE = INNODB;

CREATE TABLE banners (

id_banners INT NOT NULL AUTO_INCREMENT,

id_phone INT NOT NULL,

name VARCHAR(250),

banner VARCHAR(250),

PRIMARY KEY(id_phone),

INDEX (id_phone),

FOREIGN KEY (id_phone) REFERENCES clientes(id_phone)

) TYPE = INNODB;
</code>```

答:
From your question, it seems that each phone number has only one banner associated with it. Therefore, delete the banners.id_banners field and add a phones.id_banners

Then to select the data, you can do a JOIN:

```<code>SELECT phones.id_phone, phones.nombre, phones.number,
banners.id_banners, banners.name, banners.banner
JOIN banners ON phones.id_banners = banners.id_banners
WHERE phone = '123-456-789'
</code>```

Body:
I'm building a php page that will show an specific banner when the user enters his/her phone number in a form field.

So here's my logic for the database:

Table phones with fields: id, name of user and phone number.
Table banners with fields: id, banner's name/title and banner (path to the image).
Table relation with fields: here's where the phone number should be related to a banner and where I need your help :)

And here's my logic for the php page:

-form gets the phone number
-I query the data base
-I show the banner related to the phone number entered in the form.

Below is the code for the table creation so far .. as you'll see don't know how to advance.

Thanks a million

    CREATE TABLE phones(

id_phone INT NOT NULL AUTO_INCREMENT,

nombre VARCHAR(30),

number INT (9),

PRIMARY KEY (id_phone)

) TYPE = INNODB;

CREATE TABLE banners (

id_banners INT NOT NULL AUTO_INCREMENT,

id_phone INT NOT NULL,

name VARCHAR(250),

banner VARCHAR(250),

PRIMARY KEY(id_phone),

INDEX (id_phone),

FOREIGN KEY (id_phone) REFERENCES clientes(id_phone)

) TYPE = INNODB;

Body:
From your question, it seems that each phone number has only one banner associated with it. Therefore, delete the banners.id_banners field and add a phones.id_banners

Then to select the data, you can do a JOIN:

SELECT phones.id_phone, phones.nombre, phones.number,
banners.id_banners, banners.name, banners.banner
JOIN banners ON phones.id_banners = banners.id_banners
WHERE phone = '123-456-789'


问:
how to run old code where print is used as keyword with python 3.x?
I know that in python 3 the keyword print became a function.
But is it possible to reuse my old code without replacing every

```<code>print "Error text"
</code>```

by:

```<code>print("Error text")
</code>```

per hand?

答: I would suggest you to read about Automated Python 2 to 3 code translation and see if it can be useful to you or not ?</p>

Body:
I know that in python 3 the keyword print became a function.
But is it possible to reuse my old code without replacing every

print "Error text"

by:

print("Error text")

per hand?


问:
Delphi DataSnap Rest
I'm running some Datasnap tests with REST and json.

There in Unit ServerMethods, which Delphi itself creates, has the "ReverseString" function, but well, how do I know who sent it?

I would like to keep a log of information from the clients who called this method.

I know it could be passed as a parameter, but it would be the responsibility of the client to pass this information to me, which I do not want, let's say the method would be public and several clients would be triggering this information. I can easily lose this control, if I do not get the information directly by the control of the server.

I found on the web, that in the ServerConteiner unit, has a "DSServer" object, this object has an event called "OnConnect", so it can get the following sa data:

```<code>Procedure TServerContainer1.DSServer1Connect (
  DSConnectEventObject: TDSConnectEventObject);
Begin
  DSConnectEventObject.ChannelInfo.ClientInfo.IpAddress;
  DSConnectEventObject.ChannelInfo.ClientInfo.ClientPort;
  DSConnectEventObject.ChannelInfo.ClientInfo.Protocol;
  DSConnectEventObject.ChannelInfo.ClientInfo.AppName;
End;
</code>```

But I am not able to find how there in ServerMethods.ReverseString I can get this data ...

I believe that the processing is in thread on the server, so I can not pass this value as global, because it can pick up information from other simultaneous connections.

In the method, ReverseString, I tried as follows:

```<code>Var
    ADSServerClass: TDSServerClass;
Begin
  ADSServerClass: = TDSServerClass (GetOwner);
  TDSServer (ADSServerClass.Server). ???
  // I got to the server, but I can not find it, and I do not know if it is this way to find the data of who is requesting me to execute the ReverseString
End;
</code>```

答:
A very dirty solution is to create thread global variables on your ServerContainer

```<code>threadvar
  IpAddress: string;
  ClientPort: integer;
  Protocol: string;
  AppName: string;
</code>```

So you can now use these variables and you will see an independent set of values per thread/connection.

The problem of threadvar variables is that there are not emptied when your connection finishes, potentially leading to memory leaks.

So to avoid those leaks you will neeed to clear them manually when your TMethods datamodule is destroyed.

```<code>procedure TMyMethods.DataModuleDestroy(Sender: TObject);
begin
  if DatabaseCn.Connected then DatabaseCn.Close;
  IpAddress := '';
  ClientPort := 0;
  Protocol := '';
  AppName := '';
end;
</code>```

I'm certain that they are far more elegant solutions, but you could use this alternative if no one else provides a better option.

Title: Delphi DataSnap Rest

Body:
I'm running some Datasnap tests with REST and json.

There in Unit ServerMethods, which Delphi itself creates, has the "ReverseString" function, but well, how do I know who sent it?

I would like to keep a log of information from the clients who called this method.

I know it could be passed as a parameter, but it would be the responsibility of the client to pass this information to me, which I do not want, let's say the method would be public and several clients would be triggering this information. I can easily lose this control, if I do not get the information directly by the control of the server.

I found on the web, that in the ServerConteiner unit, has a "DSServer" object, this object has an event called "OnConnect", so it can get the following sa data:

Procedure TServerContainer1.DSServer1Connect (
  DSConnectEventObject: TDSConnectEventObject);
Begin
  DSConnectEventObject.ChannelInfo.ClientInfo.IpAddress;
  DSConnectEventObject.ChannelInfo.ClientInfo.ClientPort;
  DSConnectEventObject.ChannelInfo.ClientInfo.Protocol;
  DSConnectEventObject.ChannelInfo.ClientInfo.AppName;
End;

But I am not able to find how there in ServerMethods.ReverseString I can get this data ...

I believe that the processing is in thread on the server, so I can not pass this value as global, because it can pick up information from other simultaneous connections.

In the method, ReverseString, I tried as follows:

Var
    ADSServerClass: TDSServerClass;
Begin
  ADSServerClass: = TDSServerClass (GetOwner);
  TDSServer (ADSServerClass.Server). ???
  // I got to the server, but I can not find it, and I do not know if it is this way to find the data of who is requesting me to execute the ReverseString
End;

Body:
A very dirty solution is to create thread global variables on your ServerContainer

threadvar
  IpAddress: string;
  ClientPort: integer;
  Protocol: string;
  AppName: string;

So you can now use these variables and you will see an independent set of values per thread/connection.

The problem of threadvar variables is that there are not emptied when your connection finishes, potentially leading to memory leaks.

So to avoid those leaks you will neeed to clear them manually when your TMethods datamodule is destroyed.

procedure TMyMethods.DataModuleDestroy(Sender: TObject);
begin
  if DatabaseCn.Connected then DatabaseCn.Close;
  IpAddress := '';
  ClientPort := 0;
  Protocol := '';
  AppName := '';
end;

I'm certain that they are far more elegant solutions, but you could use this alternative if no one else provides a better option.


问:
Consume a big data by Kafka and Spark
I have a stream data in Json that provides by Websocket that size is changing between 1MB and 60 MB per second.

I got to decode the data then parse it and finally write to mysql.

I thought 2 ideas:

1) To read data from Socket then decode the data and send to Consumer via Avro in Producer,
Then to get the data and write to mysql on Spark map, reduce in Consumer

2) To read data from Socket then send the data to Consumer in Producer,
Then to get the data in Consumer then decode on Spark and send the parsed data to Spark Job for writing to mysql.

Do you have any idea?

Producer

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tan;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.ProducerConfig;

import java.util.Properties;

import java.util.stream.Stream;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
 *
 * @author Tan
 */
public class MainKafkaProducer {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws InterruptedException {
        // TODO code application logic here
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //props.put("group.id", "mygroup");
        //props.put("max.partition.fetch.bytes", "100000000");
        //props.put("serializer.class", "kafka.serializer.StringEncoder");
        //props.put("partitioner.class","kafka.producer.DefaultPartitioner");
        //props.put("request.required.acks", "1");

         KafkaProducer<String, String> producer = new KafkaProducer<>(props);

         // Read the data from websocket and send it to consumer
         //for (int i = 0; i < 100; i++) {
            String fileName = "/Users/Tan/Desktop/feed.json";
            try{
                BufferedReader file = new BufferedReader(new FileReader(fileName));
                String st = file.readLine();
                for(int i = 0; i < 100; i++)
                {
                    ProducerRecord<String, String> record = new ProducerRecord<>("mytopic", st);
                    producer.send(record);
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        //}

        /*
        for(int i = 0; i < 100; i++)
        {
            ProducerRecord<String, String> record2 = new ProducerRecord<>("mytopic", "Hasan-" + i);
            producer.send(record2);
        }
        */

        producer.close();
    }

}
</code>```

Consumer

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tan;

import kafka.serializer.DefaultDecoder;
import kafka.serializer.StringDecoder;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.streaming.Duration;
import org.apache.spark.streaming.api.java.JavaPairInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.kafka.KafkaUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
 *
 * @author Tan
 */
public class MainKafkaConsumer {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        SparkConf conf = new SparkConf()
                .setAppName(MainKafkaConsumer.class.getName())
                .setMaster("local[*]");
        JavaSparkContext sc = new JavaSparkContext(conf);
        JavaStreamingContext ssc = new JavaStreamingContext(sc, new Duration(2000));

        Set<String> topics = Collections.singleton("mytopic");
        Map<String, String> kafkaParams = new HashMap<>();
        kafkaParams.put("metadata.broker.list", "localhost:9092");

        JavaPairInputDStream<String, String> directKafkaStream = KafkaUtils.createDirectStream(ssc,
                String.class, String.class,
                StringDecoder.class, StringDecoder.class,
                kafkaParams, topics);

        directKafkaStream.foreachRDD(rdd -> {

            rdd.foreach(records -> {

                System.out.println(records._2);

            });

        });
        /*
        directKafkaStream.foreachRDD(rdd -> {
            System.out.println("--- New RDD with " + rdd.partitions().size()
                    + " partitions and " + rdd.count() + " records");
            rdd.foreach(record -> {
                System.out.println(record._2);
            });
        });
        */

        ssc.start();
        ssc.awaitTermination();

    }

}
</code>```

答:
Your process is good, the point is just for the avro conversion. Your data is not that big, 1Mb to 60Mb.

Here I have a similar process, reading from an MQ, process the data, convert to avro, send to kafka, consume from kafka, parse the data and post in other MQ.

The Avro help a lot when our data is huge, like >= 1Gb. But in some cases our data is really small like < 10Mb. In this case Avro make our processing be a little bit slow, there is no gain in network transmission.

What I suggest to you, if your network is good enought to not convert to avro, better do it without avro. To improove performance in Spark Side configure the topic of kafka with a good number of partitions, because if you have just one partition, your spark will not do the parallization correctly. Check this text that can help you.

Title: Consume a big data by Kafka and Spark

Body:
I have a stream data in Json that provides by Websocket that size is changing between 1MB and 60 MB per second.

I got to decode the data then parse it and finally write to mysql.

I thought 2 ideas:

1) To read data from Socket then decode the data and send to Consumer via Avro in Producer,
Then to get the data and write to mysql on Spark map, reduce in Consumer

2) To read data from Socket then send the data to Consumer in Producer,
Then to get the data in Consumer then decode on Spark and send the parsed data to Spark Job for writing to mysql.

Do you have any idea?

Producer

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tan;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.ProducerConfig;

import java.util.Properties;

import java.util.stream.Stream;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
 *
 * @author Tan
 */
public class MainKafkaProducer {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws InterruptedException {
        // TODO code application logic here
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //props.put("group.id", "mygroup");
        //props.put("max.partition.fetch.bytes", "100000000");
        //props.put("serializer.class", "kafka.serializer.StringEncoder");
        //props.put("partitioner.class","kafka.producer.DefaultPartitioner");
        //props.put("request.required.acks", "1");

         KafkaProducer<String, String> producer = new KafkaProducer<>(props);

         // Read the data from websocket and send it to consumer
         //for (int i = 0; i < 100; i++) {
            String fileName = "/Users/Tan/Desktop/feed.json";
            try{
                BufferedReader file = new BufferedReader(new FileReader(fileName));
                String st = file.readLine();
                for(int i = 0; i < 100; i++)
                {
                    ProducerRecord<String, String> record = new ProducerRecord<>("mytopic", st);
                    producer.send(record);
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        //}

        /*
        for(int i = 0; i < 100; i++)
        {
            ProducerRecord<String, String> record2 = new ProducerRecord<>("mytopic", "Hasan-" + i);
            producer.send(record2);
        }
        */

        producer.close();
    }

}

Consumer

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tan;

import kafka.serializer.DefaultDecoder;
import kafka.serializer.StringDecoder;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.streaming.Duration;
import org.apache.spark.streaming.api.java.JavaPairInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.kafka.KafkaUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
 *
 * @author Tan
 */
public class MainKafkaConsumer {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        SparkConf conf = new SparkConf()
                .setAppName(MainKafkaConsumer.class.getName())
                .setMaster("local[*]");
        JavaSparkContext sc = new JavaSparkContext(conf);
        JavaStreamingContext ssc = new JavaStreamingContext(sc, new Duration(2000));

        Set<String> topics = Collections.singleton("mytopic");
        Map<String, String> kafkaParams = new HashMap<>();
        kafkaParams.put("metadata.broker.list", "localhost:9092");

        JavaPairInputDStream<String, String> directKafkaStream = KafkaUtils.createDirectStream(ssc,
                String.class, String.class,
                StringDecoder.class, StringDecoder.class,
                kafkaParams, topics);

        directKafkaStream.foreachRDD(rdd -> {

            rdd.foreach(records -> {

                System.out.println(records._2);

            });

        });
        /*
        directKafkaStream.foreachRDD(rdd -> {
            System.out.println("--- New RDD with " + rdd.partitions().size()
                    + " partitions and " + rdd.count() + " records");
            rdd.foreach(record -> {
                System.out.println(record._2);
            });
        });
        */

        ssc.start();
        ssc.awaitTermination();

    }

}


问:
Resize Image without distorting or cropping it
Users upload an image of any size and we need to resize it so it becomes a square without distorting or cropping the image. Basically, it should do something similar to the "Aspect Fit" content mode in an image view. So if we have a 200x100px png image, I want to make it 200x200px and have the extra 100px in the height be transparent space. It should not crop the image to 200x200.

I tried to use this image processor but it does not do what I want. https://github.com/gavinbunney/Toucan. It only crops the image.

How would I do this in swift and is there a framework that is better than the one I mentioned above to make doing this easier. Basically, I am looking for the simplest way to do this.

答:
Posting this as an answer, along with example usage...

The scaling code is not mine, it's from: https://gist.github.com/tomasbasham/10533743#gistcomment-1988471

Here is code you can run in a playground to test:

```<code>import UIKit
import PlaygroundSupport

let container = UIView(frame: CGRect(x: 0, y: 0, width: 800, height: 800))

container.backgroundColor = UIColor.blue

PlaygroundPage.current.liveView = container

// MARK: - Image Scaling.
extension UIImage {

    /// Represents a scaling mode
    enum ScalingMode {
        case aspectFill
        case aspectFit

        /// Calculates the aspect ratio between two sizes
        ///
        /// - parameters:
        ///     - size:      the first size used to calculate the ratio
        ///     - otherSize: the second size used to calculate the ratio
        ///
        /// - return: the aspect ratio between the two sizes
        func aspectRatio(between size: CGSize, and otherSize: CGSize) -> CGFloat {
            let aspectWidth  = size.width/otherSize.width
            let aspectHeight = size.height/otherSize.height

            switch self {
            case .aspectFill:
                return max(aspectWidth, aspectHeight)
            case .aspectFit:
                return min(aspectWidth, aspectHeight)
            }
        }
    }

    /// Scales an image to fit within a bounds with a size governed by the passed size. Also keeps the aspect ratio.
    ///
    /// - parameter:
    ///     - newSize:     the size of the bounds the image must fit within.
    ///     - scalingMode: the desired scaling mode
    ///
    /// - returns: a new scaled image.
    func scaled(to newSize: CGSize, scalingMode: UIImage.ScalingMode = .aspectFill) -> UIImage {

        let aspectRatio = scalingMode.aspectRatio(between: newSize, and: size)

        /* Build the rectangle representing the area to be drawn */
        var scaledImageRect = CGRect.zero

        scaledImageRect.size.width  = size.width * aspectRatio
        scaledImageRect.size.height = size.height * aspectRatio
        scaledImageRect.origin.x    = (newSize.width - size.width * aspectRatio) / 2.0
        scaledImageRect.origin.y    = (newSize.height - size.height * aspectRatio) / 2.0

        /* Draw and retrieve the scaled image */
        UIGraphicsBeginImageContext(newSize)

        draw(in: scaledImageRect)
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return scaledImage!
    }
}

if let srcimg = UIImage(named: "flags") {

    let w = srcimg.size.width
    let h = srcimg.size.height

    // determine whether width or height is greater
    let longer = max(w, h)

    // create a Square size
    let sz = CGSize(width: longer, height: longer)

    // call scaling function to scale the image to the Square dimensions,
    // using "aspect fit"
    let newImage = srcimg.scaled(to: sz, scalingMode: .aspectFit)

    // create a UIImageView with the resulting image
    let v = UIImageView(image: newImage)
    v.backgroundColor = UIColor.white

    // add it to the container view
    container.addSubview(v)

}
</code>```

Body:
Posting this as an answer, along with example usage...

The scaling code is not mine, it's from: https://gist.github.com/tomasbasham/10533743#gistcomment-1988471

Here is code you can run in a playground to test:

import UIKit
import PlaygroundSupport

let container = UIView(frame: CGRect(x: 0, y: 0, width: 800, height: 800))

container.backgroundColor = UIColor.blue

PlaygroundPage.current.liveView = container

// MARK: - Image Scaling.
extension UIImage {

    /// Represents a scaling mode
    enum ScalingMode {
        case aspectFill
        case aspectFit

        /// Calculates the aspect ratio between two sizes
        ///
        /// - parameters:
        ///     - size:      the first size used to calculate the ratio
        ///     - otherSize: the second size used to calculate the ratio
        ///
        /// - return: the aspect ratio between the two sizes
        func aspectRatio(between size: CGSize, and otherSize: CGSize) -> CGFloat {
            let aspectWidth  = size.width/otherSize.width
            let aspectHeight = size.height/otherSize.height

            switch self {
            case .aspectFill:
                return max(aspectWidth, aspectHeight)
            case .aspectFit:
                return min(aspectWidth, aspectHeight)
            }
        }
    }

    /// Scales an image to fit within a bounds with a size governed by the passed size. Also keeps the aspect ratio.
    ///
    /// - parameter:
    ///     - newSize:     the size of the bounds the image must fit within.
    ///     - scalingMode: the desired scaling mode
    ///
    /// - returns: a new scaled image.
    func scaled(to newSize: CGSize, scalingMode: UIImage.ScalingMode = .aspectFill) -> UIImage {

        let aspectRatio = scalingMode.aspectRatio(between: newSize, and: size)

        /* Build the rectangle representing the area to be drawn */
        var scaledImageRect = CGRect.zero

        scaledImageRect.size.width  = size.width * aspectRatio
        scaledImageRect.size.height = size.height * aspectRatio
        scaledImageRect.origin.x    = (newSize.width - size.width * aspectRatio) / 2.0
        scaledImageRect.origin.y    = (newSize.height - size.height * aspectRatio) / 2.0

        /* Draw and retrieve the scaled image */
        UIGraphicsBeginImageContext(newSize)

        draw(in: scaledImageRect)
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return scaledImage!
    }
}

if let srcimg = UIImage(named: "flags") {

    let w = srcimg.size.width
    let h = srcimg.size.height

    // determine whether width or height is greater
    let longer = max(w, h)

    // create a Square size
    let sz = CGSize(width: longer, height: longer)

    // call scaling function to scale the image to the Square dimensions,
    // using "aspect fit"
    let newImage = srcimg.scaled(to: sz, scalingMode: .aspectFit)

    // create a UIImageView with the resulting image
    let v = UIImageView(image: newImage)
    v.backgroundColor = UIColor.white

    // add it to the container view
    container.addSubview(v)

}


问:
CSS3 loading animation component in Angular 2
I'm starting to learn how do do animations with CSS3, here's my first animation.

I have placed it between my <root> tag in my Angular4 application and it works !

But I wish to package it in an Angular component for reuse, can that be achieved? How can a loading component be loaded before anything else in order to... display a loading animation?

答:
I am assuming you want to show this when loading some async data. In that case, you can just add your HTML/CSS to a component and control its visibility with an input variable.

In this example, it will be shown by default, then you can hide it after your data is resolved.

```<code>import { Component, Input } from '@angular/core';

@Component({
  selector: 'spinner',
  templateUrl: './spinner.component.html',
  styleUrls: ['./spinner.component.scss']
})
export class ItemsListComponent {

  @Input() showSpinner: boolean = true;

  constructor() { }

}
</code>```

In your spinner.component.html

```<code><div *ngIf="showSpinner" class="lds-cube">
  <!-- the rest of your html -->
</div>
</code>```

Then you can show or hide the spinner from any parent component by passing it a boolean variable that you set to true after the data is loaded.

```<code><spinner [showSpinner]="yourBoolean"></spinner>
</code>```

Here's an article about using a spinner component for async data from Firebase, but would work same with any data stream.

Showing a Spinner Before the App has Loaded

Your app will not have access to its components at this point, so I think it's best to use plain CSS. Add a div with a loading class in index.html.

```<code><app-root></app-root>
<div class="loading">
  <h1>~$ loading app...</h1>
 <!-- your animation html -->
</div>
</code>```

Then in your main stylesheet, you can use the pseudo :empty selector to show the loading content when the app-root empty.

```<code>.loading {
    opacity: 0;
    position: fixed;
    height: 100%;
    width: 100%;
    background: #272c33;
    padding-top: 25vh;
    text-align: center;
    z-index: -1;
    transition: opacity .8s ease-out;
}
app-root:empty + .loading {
  opacity: 1;
  z-index: 99999;
}
</code>```

Body:
I am assuming you want to show this when loading some async data. In that case, you can just add your HTML/CSS to a component and control its visibility with an input variable.

In this example, it will be shown by default, then you can hide it after your data is resolved.

import { Component, Input } from '@angular/core';

@Component({
  selector: 'spinner',
  templateUrl: './spinner.component.html',
  styleUrls: ['./spinner.component.scss']
})
export class ItemsListComponent {

  @Input() showSpinner: boolean = true;

  constructor() { }

}

In your spinner.component.html

<div *ngIf="showSpinner" class="lds-cube">
  <!-- the rest of your html -->
</div>

Then you can show or hide the spinner from any parent component by passing it a boolean variable that you set to true after the data is loaded.

<spinner [showSpinner]="yourBoolean"></spinner>

Here's an article about using a spinner component for async data from Firebase, but would work same with any data stream.

Showing a Spinner Before the App has Loaded

Your app will not have access to its components at this point, so I think it's best to use plain CSS. Add a div with a loading class in index.html.

<app-root></app-root>
<div class="loading">
  <h1>~$ loading app...</h1>
 <!-- your animation html -->
</div>

Then in your main stylesheet, you can use the pseudo :empty selector to show the loading content when the app-root empty.

.loading {
    opacity: 0;
    position: fixed;
    height: 100%;
    width: 100%;
    background: #272c33;
    padding-top: 25vh;
    text-align: center;
    z-index: -1;
    transition: opacity .8s ease-out;
}
app-root:empty + .loading {
  opacity: 1;
  z-index: 99999;
}


问:
Application Logic (Proper place for Authentication/Authorization)
I am developing a CMS like application using MVC 3 (RC2) and I am in crossroads at this point. I am unable to convince myself if my proposed approach is appropriate or not. I guess it is because I am aware that I am trying to cut some corners which will cost me heavily later down the line.

I will get right down to describing my problem:

1) I have a resource (lets call it A) which has to be made editable.

2) I have a custom permission system implemented which has 2 (of many) permissions:

Can Edit Own Resource

Can Edit Other Resource

3) Creator of resource A is free to edit it if they have 'Can Edit Own Resource' permission.

4) A separate user can only edit A if they have permission 'Can Edit Other Resource'

Now that the requirement is described, let me tell you my approach so far:

1) I have a controller called 'ResourceController'

2) I have a action called 'Edit'

3) The action has a attribute on it: [CustomerAuthorize(Perm.CanEditOwnResource, Perm.CanEditOtherResource, Any = true)]

4) I have a service class which takes care of domain validation.

So a user get call the action method if they have either the 'Can Edit Own Resource' or 'Can Edit Other Resource' permission.

How do I decide (and where should this decision be made) on whether the user has the right permission or not (depending on whether they own the resource?) Should it be in the controller action, in the resource service class, in a separate service class?

Waiting to hear different views...

答:
One way to approach it is to have 2 actions, instead only "Edit", you have "EditOwnResource" and "EditOtherResource". You can then place a single permission on each of these.

Then if you are using the MVVM pattern you can bind the availability of these actions to wether it is an ownResource or otherResource. The setting of these values is done in the view model.


问:
EXCEL Summing values YTD based on Criteria (Offset Index Match)
Let's say...

I have Jan - Dec data, say columns B : K.

Then I have the row labels in column A (Sales, COGS, Travel Expenses, etc...).

Then on a summary screen, I have a data validation list where the user can choose the month for a Year-to-Date calculation.

I swore I've been able to calculate YTD based off a data validation list in the past using SUMIF(Column A, (Criteria), Offset (Jan) : Index(match) the column # based off of the month selection)

So Mar would move the range from Jan to Mar, and so on.

答:
instead of SUMIF use just SUM with INDEX and MATCH like:

```<code>=SUM(INDEX(B:B,MATCH([criteria],A:A,0)):INDEX(B:K,MATCH([criteria],A:A,0),[count of month]))
</code>```

for [count of month] use 6 for January to June.
the only you can not do is summing up multiple rows at once.

Body:
instead of SUMIF use just SUM with INDEX and MATCH like:

=SUM(INDEX(B:B,MATCH([criteria],A:A,0)):INDEX(B:K,MATCH([criteria],A:A,0),[count of month]))

for [count of month] use 6 for January to June.
the only you can not do is summing up multiple rows at once.


问:
Excel counter for when a Cell with streaming data increases?
I have a single cell that streams live data.  I'm trying to add a counter to another cell, such that each time the single streaming data cell changes, the counter increases.  (The data coming in is only increasing, so each time it increases, the counter should increase).

Any way to do this w/o a VBA macro?  Otherwise VBA code will help.  thanks

答:
Put this in your sheet under Microsoft Excel Objects. Set the first cell to be the one that's changing, and the second cell to where you want the counter.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    'First cell
    If Target.Address = "$A$1" Then
        'Second cell
        ActiveWorkbook.Worksheets("Sheet1").Range("B1").Value = ActiveWorkbook.Worksheets("Sheet1").Range("B1").Value + 1
    End If
End Sub
</code>```

EDIT: For if C1 equals D1 on change. If it doesn't equal it, the counter doesn't go up.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$C$1" Then
        If ActiveWorkbook.Worksheets("Sheet1").Range("C1").Value = ActiveWorkbook.Worksheets("Sheet1").Range("D1").Value Then
            ActiveWorkbook.Worksheets("Sheet1").Range("D2").Value = ActiveWorkbook.Worksheets("Sheet1").Range("D2").Value + 1
        End If
    End If
End Sub
</code>```

Body:
Put this in your sheet under Microsoft Excel Objects. Set the first cell to be the one that's changing, and the second cell to where you want the counter.

Private Sub Worksheet_Change(ByVal Target As Range)
    'First cell
    If Target.Address = "$A$1" Then
        'Second cell
        ActiveWorkbook.Worksheets("Sheet1").Range("B1").Value = ActiveWorkbook.Worksheets("Sheet1").Range("B1").Value + 1
    End If
End Sub

EDIT: For if C1 equals D1 on change. If it doesn't equal it, the counter doesn't go up.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$C$1" Then
        If ActiveWorkbook.Worksheets("Sheet1").Range("C1").Value = ActiveWorkbook.Worksheets("Sheet1").Range("D1").Value Then
            ActiveWorkbook.Worksheets("Sheet1").Range("D2").Value = ActiveWorkbook.Worksheets("Sheet1").Range("D2").Value + 1
        End If
    End If
End Sub