问:
Apache virtual server and hardcoded mysql connectors using ip addresses
xampp distribution 5.6.15 with Apache 2.4.17 MariaDB 10.1.10 running on w7-64,

I've recreated a copy of a production website on my local box using virtual hosting.  Works great except for the hard coded mysql connectors distributed all about the code.

Modifying these files is not an option at this time.  Question is, is there a way to setup Apache, or mysql, to allow these connections to work?

Here's an example (older technology):

```<code>mysql_connect('123.123.123.123', DB_USER, DB_PASSWORD);
</code>```

The mysql database is running outside of this xampp port. It is an identical mysql/MariaDB release. The database connects when the host is properly named.

Thank you.  (please leave the php tag - these guys know a lot.)

MORE INFO - Edit

I've modified two files trying to remap the ip address.

\Windows\System32\drivers\etc\hosts
and
\xampp2\apache\conf\extra\httpd-vhosts.conf

With host names it worked find. Here are the additional entries I made. If you can think of a permutation, I've probably tried it. I'm wonder now it this isn't some mysql config problem. Again, take away the ip address, use a name, and everything is fine: (it's the entries with the ip addresses that fail. After any change in either of these two files, I cycled Apache and flushed the dns. Error message from connect attempt is:

mysql_connect(): A socket operation was attempted to an unreachable host

======================================================================

```<code><VirtualHost *:80>
DocumentRoot "C:/xampp2/htdocs"
ServerName www.production.com
</VirtualHost>

<VirtualHost 123.123.123.123>
DocumentRoot "C:/xampp2/htdocs"
ServerName www.production.com
</VirtualHost>
</code>```

====================================================================

```<code>127.0.0.1 localhost
127.0.0.1 www.mspfound.com # second server
123.123.123.123 localhost
</code>```

or

```<code>127.0.0.1 localhost
127.0.0.1 www.mspfound.com # second server
123.123.123.123 www.mspfound.com
</code>```

答:
You can not override an ip address locally, what you can do is reroute connections through a proxy server and/or some iptables changes, but that's not really my area, another idea would be setting up a local or virtual network where the mysql server can use the same ip as the existing production server,I usually did this using couple of virtual boxes connected to the same virtual network and using the same subnet as the server in question.

but that's all quick fixing and patching, what you should really be doing (I hope you've done it already, it's been 3 months!) is to replace all ip addresses in code with either a config variable that can be changed centrally or a virtual host name that can be changed in your hosts file, also you probably need to replace the deprecated mysql_* functions.

Best of luck.

Body:
xampp distribution 5.6.15 with Apache 2.4.17 MariaDB 10.1.10 running on w7-64,

I've recreated a copy of a production website on my local box using virtual hosting.  Works great except for the hard coded mysql connectors distributed all about the code.

Modifying these files is not an option at this time.  Question is, is there a way to setup Apache, or mysql, to allow these connections to work?

Here's an example (older technology):

mysql_connect('123.123.123.123', DB_USER, DB_PASSWORD);

The mysql database is running outside of this xampp port. It is an identical mysql/MariaDB release. The database connects when the host is properly named.

Thank you.  (please leave the php tag - these guys know a lot.)

MORE INFO - Edit

I've modified two files trying to remap the ip address.

\Windows\System32\drivers\etc\hosts
and
\xampp2\apache\conf\extra\httpd-vhosts.conf

With host names it worked find. Here are the additional entries I made. If you can think of a permutation, I've probably tried it. I'm wonder now it this isn't some mysql config problem. Again, take away the ip address, use a name, and everything is fine: (it's the entries with the ip addresses that fail. After any change in either of these two files, I cycled Apache and flushed the dns. Error message from connect attempt is:

mysql_connect(): A socket operation was attempted to an unreachable host

======================================================================

<VirtualHost *:80>
DocumentRoot "C:/xampp2/htdocs"
ServerName www.production.com
</VirtualHost>

<VirtualHost 123.123.123.123>
DocumentRoot "C:/xampp2/htdocs"
ServerName www.production.com
</VirtualHost>

====================================================================

127.0.0.1 localhost
127.0.0.1 www.mspfound.com # second server
123.123.123.123 localhost

or

127.0.0.1 localhost
127.0.0.1 www.mspfound.com # second server
123.123.123.123 www.mspfound.com


来源: stackexchange

问:
Silverlight 3.0 - How to access a MainPage control value from an UserControl
I need to retrieve some control values from the MainPage to an UserControl.
In this UserControl I need to be able to get the Frame.ActualWidth & Frame.ActualHeight values (in this case, the Frame element is in the MainPage and the UserControl is loaded inside a MainPage's Grid via xaml).
Does someone have a sample?
Thank you

Josimari Martarelli
ESL Sistemas Logísticos
Silverlight UI Design

jmartarelli@logfacil.com.br

答:
First I created a static method in the App class that walks up the hierarchy of parents until it finds a match based on name.  This can be used for more than just MainPage. Everything in the hierarchy should be derived from the FrameworkElement class.

```<code>    public static FrameworkElement GetParentByName(FrameworkElement currentPage,
string ParentName)
    {

        FrameworkElement fe = (FrameworkElement)currentPage.Parent;

        // Walk your way up the chain of Parents until we get a match
        while(fe.GetType().Name != ParentName)
            fe = (FrameworkElement)fe.Parent;

        return fe;

    }
</code>```

Then to use this I just call something like:

MainPage m = (MainPage)App.GetParentByName(this, "MainPage");

ContentLicense: CC BY-SA 2.5

Body:
First I created a static method in the App class that walks up the hierarchy of parents until it finds a match based on name.  This can be used for more than just MainPage. Everything in the hierarchy should be derived from the FrameworkElement class.

    public static FrameworkElement GetParentByName(FrameworkElement currentPage,
string ParentName)
    {

        FrameworkElement fe = (FrameworkElement)currentPage.Parent;

        // Walk your way up the chain of Parents until we get a match
        while(fe.GetType().Name != ParentName)
            fe = (FrameworkElement)fe.Parent;

        return fe;

    }

Then to use this I just call something like:

MainPage m = (MainPage)App.GetParentByName(this, "MainPage");


问:
Binding pivot table with Laravel Form Builders using checkbox group
I'd like to bind my checkbox group Form::checkbox('services[]') with data from my pivot table but I'm having trouble doing so, I think this is because no key is being returned with service_id.

My data model is as follows:

Business

Service

Business_Service table to store many to many link.

Blade Template

```<code>@foreach($service as $service)
{!! Form::checkbox('services[]', $service->id, (in_array($service->id, $selected_services) ? true : false)) !!}
@endforeach
</code>```

Controller

```<code>$service = Service::all();
$selected_services = Auth::user()->business->services()->get();

return view('signup.step2', compact('service', 'selected_services'));
</code>```

When I return $selected_services I can see the following:

[{"id":2,"name":"Service
  1","image":"picture.png","created_at":"2017-03-31
  00:31:20","updated_at":"2017-03-31
  00:31:20","pivot":{"business_id":103,"service_id":2}},{"id":3,"name":"Service
  2","image":"picture.png","created_at":"2017-03-31
  00:31:23","updated_at":"2017-03-31
  00:31:23","pivot":{"business_id":103,"service_id":3}}]

I have tried changing $selected_services like this:

```<code>$selected_services = Auth::user()->business->services()->keyBy('service_id');
</code>```

But this only returns one row and doesn't associate a key to the row as expected.

答:
I can prepare another array instead of using the collection Eloquent returns but I was hoping there was some built-in function by Laravel I could use.</p>

```<code>$service = Service::all();
$business_services = Auth::user()->business->services()->get();

$selected_services = [];
foreach ($business_services as $ss) {
    $selected_services[] = $ss->pivot->service_id;
}

return view('signup.step2', compact('service', 'selected_services'));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'd like to bind my checkbox group Form::checkbox('services[]') with data from my pivot table but I'm having trouble doing so, I think this is because no key is being returned with service_id.

My data model is as follows:

Business

Service

Business_Service table to store many to many link.

Blade Template

@foreach($service as $service)
{!! Form::checkbox('services[]', $service->id, (in_array($service->id, $selected_services) ? true : false)) !!}
@endforeach

Controller

$service = Service::all();
$selected_services = Auth::user()->business->services()->get();

return view('signup.step2', compact('service', 'selected_services'));

When I return $selected_services I can see the following:

[{"id":2,"name":"Service
  1","image":"picture.png","created_at":"2017-03-31
  00:31:20","updated_at":"2017-03-31
  00:31:20","pivot":{"business_id":103,"service_id":2}},{"id":3,"name":"Service
  2","image":"picture.png","created_at":"2017-03-31
  00:31:23","updated_at":"2017-03-31
  00:31:23","pivot":{"business_id":103,"service_id":3}}]

I have tried changing $selected_services like this:

$selected_services = Auth::user()->business->services()->keyBy('service_id');

But this only returns one row and doesn't associate a key to the row as expected.

Body:
I can prepare another array instead of using the collection Eloquent returns but I was hoping there was some built-in function by Laravel I could use.

$service = Service::all();
$business_services = Auth::user()->business->services()->get();

$selected_services = [];
foreach ($business_services as $ss) {
    $selected_services[] = $ss->pivot->service_id;
}

return view('signup.step2', compact('service', 'selected_services'));


问:
Xcode 8.3 does not ask for an user input
enter image description here

I just install Xcode 8.3 from App Store and try to run those codes (from the photo) in C++ but it doesn't ask me to input a value to test the codes out. Please help me out?

答:
I'm having the same problem. It looks like you need to add a new line character for it to appear in the console. That is

std::cout << "Enter amount: $";

would not print, while

std::cout << "Enter amount: $\n";

will


问:
Adding Values to playing cards in Python
So I'm trying to add Values to the cards so i can calculate each players scores.
I would like the scoring system to work like this: 2 has a value of 2 counting up to ace which has a value of 14, ace being highest 2 being lowest. Each suit has another value to it spades = 1, hearts = 2, diamonds = 3, clubs = 2. I think i can do the scoring part myself after i know how to add the values to each card and suit but I have no idea how to add the values so can someone please give me some ideas or hints?

Please no straight up code answers because id like to learn how its done rather than just copy pasting your code.

the deck code is

```<code>CardList= ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"]
SuitList= ["Diamonds", "Clubs", "hearts", "Spades"]
Deck= ["%s of %s" %(X, Y) for X in ValueList for Y in SuitList]
</code>```

答:
I changed your deck and suitlist to a dictionary that way I can tie values to cards and suits.  It's simple, hearts are worth 2 extra points, so "Hearts":2.  Then I used the .items() function to grab all the item's keys, values from the suits list, I stored the value as v.  Then, I used enumerate to loop over the CardList, so I could get both a variable i (which is the index of the card in the array) and the name of the card, X.   Then I added 2, since arrays start counting at 0.  Finally, I implemented pprint in order to make my output look cleaner, you can remove this in the final version.

```<code>import pprint
CardList= ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"]
SuitList= {"Spades":1, "Hearts":2, "Diamonds":3, "Clubs":2}
Deck = [["%s of %s" % (X, Y), i + 2 + v] for i, X in enumerate(CardList) for Y, v in SuitList.items()]
pprint.PrettyPrinter(indent=4).pprint(Deck)
</code>```

Output:

```<code>[   ['2 of Hearts', 4],
        ['2 of Clubs', 4],
        ['2 of Spades', 3],
        ['2 of Diamonds', 5],
        ['3 of Hearts', 5],
        ['3 of Clubs', 5],
        ['3 of Spades', 4],
        ['3 of Diamonds', 6],
        ['4 of Hearts', 6],
        ['4 of Clubs', 6],
        ['4 of Spades', 5],
        ['4 of Diamonds', 7],
        ['5 of Hearts', 7],
        ['5 of Clubs', 7],
        ['5 of Spades', 6],
        ['5 of Diamonds', 8],
        ['6 of Hearts', 8],
        ['6 of Clubs', 8],
        ['6 of Spades', 7],
        ['6 of Diamonds', 9],
        ['7 of Hearts', 9],
        ['7 of Clubs', 9],
        ['7 of Spades', 8],
        ['7 of Diamonds', 10],
        ['8 of Hearts', 10],
        ['8 of Clubs', 10],
        ['8 of Spades', 9],
        ['8 of Diamonds', 11],
        ['9 of Hearts', 11],
        ['9 of Clubs', 11],
        ['9 of Spades', 10],
        ['9 of Diamonds', 12],
        ['10 of Hearts', 12],
        ['10 of Clubs', 12],
        ['10 of Spades', 11],
        ['10 of Diamonds', 13],
        ['Jack of Hearts', 13],
        ['Jack of Clubs', 13],
        ['Jack of Spades', 12],
        ['Jack of Diamonds', 14],
        ['Queen of Hearts', 14],
        ['Queen of Clubs', 14],
        ['Queen of Spades', 13],
        ['Queen of Diamonds', 15],
        ['King of Hearts', 15],
        ['King of Clubs', 15],
        ['King of Spades', 14],
        ['King of Diamonds', 16],
        ['Ace of Hearts', 16],
        ['Ace of Clubs', 16],
        ['Ace of Spades', 15],
        ['Ace of Diamonds', 17]]
</code>```

Body:
So I'm trying to add Values to the cards so i can calculate each players scores.
I would like the scoring system to work like this: 2 has a value of 2 counting up to ace which has a value of 14, ace being highest 2 being lowest. Each suit has another value to it spades = 1, hearts = 2, diamonds = 3, clubs = 2. I think i can do the scoring part myself after i know how to add the values to each card and suit but I have no idea how to add the values so can someone please give me some ideas or hints?

Please no straight up code answers because id like to learn how its done rather than just copy pasting your code.

the deck code is

CardList= ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"]
SuitList= ["Diamonds", "Clubs", "hearts", "Spades"]
Deck= ["%s of %s" %(X, Y) for X in ValueList for Y in SuitList]

Body:
I changed your deck and suitlist to a dictionary that way I can tie values to cards and suits.  It's simple, hearts are worth 2 extra points, so "Hearts":2.  Then I used the .items() function to grab all the item's keys, values from the suits list, I stored the value as v.  Then, I used enumerate to loop over the CardList, so I could get both a variable i (which is the index of the card in the array) and the name of the card, X.   Then I added 2, since arrays start counting at 0.  Finally, I implemented pprint in order to make my output look cleaner, you can remove this in the final version.

import pprint
CardList= ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"]
SuitList= {"Spades":1, "Hearts":2, "Diamonds":3, "Clubs":2}
Deck = [["%s of %s" % (X, Y), i + 2 + v] for i, X in enumerate(CardList) for Y, v in SuitList.items()]
pprint.PrettyPrinter(indent=4).pprint(Deck)

Output:

[   ['2 of Hearts', 4],
        ['2 of Clubs', 4],
        ['2 of Spades', 3],
        ['2 of Diamonds', 5],
        ['3 of Hearts', 5],
        ['3 of Clubs', 5],
        ['3 of Spades', 4],
        ['3 of Diamonds', 6],
        ['4 of Hearts', 6],
        ['4 of Clubs', 6],
        ['4 of Spades', 5],
        ['4 of Diamonds', 7],
        ['5 of Hearts', 7],
        ['5 of Clubs', 7],
        ['5 of Spades', 6],
        ['5 of Diamonds', 8],
        ['6 of Hearts', 8],
        ['6 of Clubs', 8],
        ['6 of Spades', 7],
        ['6 of Diamonds', 9],
        ['7 of Hearts', 9],
        ['7 of Clubs', 9],
        ['7 of Spades', 8],
        ['7 of Diamonds', 10],
        ['8 of Hearts', 10],
        ['8 of Clubs', 10],
        ['8 of Spades', 9],
        ['8 of Diamonds', 11],
        ['9 of Hearts', 11],
        ['9 of Clubs', 11],
        ['9 of Spades', 10],
        ['9 of Diamonds', 12],
        ['10 of Hearts', 12],
        ['10 of Clubs', 12],
        ['10 of Spades', 11],
        ['10 of Diamonds', 13],
        ['Jack of Hearts', 13],
        ['Jack of Clubs', 13],
        ['Jack of Spades', 12],
        ['Jack of Diamonds', 14],
        ['Queen of Hearts', 14],
        ['Queen of Clubs', 14],
        ['Queen of Spades', 13],
        ['Queen of Diamonds', 15],
        ['King of Hearts', 15],
        ['King of Clubs', 15],
        ['King of Spades', 14],
        ['King of Diamonds', 16],
        ['Ace of Hearts', 16],
        ['Ace of Clubs', 16],
        ['Ace of Spades', 15],
        ['Ace of Diamonds', 17]]


问:
How to break a string in C with /
I have a string with the following pattern :

```<code>char *str = "ai/aj/module_mat.mod";
</code>```

and I want to select module_mat as my final string for the further logic. I have tried to used rindex() so that I can get the final part of the string. But I am not able to do this in C. What am I doing wrong?

The code I am trying is -

```<code>char *first = rindex(str, "/");
char *first = strtok(first, ".");
</code>```

答:
First off, the string literal is immutable, so it is very dangerous to bind it to a mutable char pointer. First fix your code:

```<code>const char* str = "ai/aj/module_mat.mod";
</code>```

Next, use strchr:

```<code>#include <string.h>

const char* p = strchr(str, '/');
if (p != NULL) {
  ++p;
  printf("Last part: %s\n", p);
} else {
  printf("No '/' found in string %s.\n", str);
}
</code>```

If a / is found in the string, p will point to it, and hence p can be used as the suffix substring of the original string, and there's no need to modify the original string. We advance p by one to skip past the / and are left with the final part of the string.

Title: How to break a string in C with /

Body:
I have a string with the following pattern :

char *str = "ai/aj/module_mat.mod";

and I want to select module_mat as my final string for the further logic. I have tried to used rindex() so that I can get the final part of the string. But I am not able to do this in C. What am I doing wrong?

The code I am trying is -

char *first = rindex(str, "/");
char *first = strtok(first, ".");

Body:
First off, the string literal is immutable, so it is very dangerous to bind it to a mutable char pointer. First fix your code:

const char* str = "ai/aj/module_mat.mod";

Next, use strchr:

#include <string.h>

const char* p = strchr(str, '/');
if (p != NULL) {
  ++p;
  printf("Last part: %s\n", p);
} else {
  printf("No '/' found in string %s.\n", str);
}

If a / is found in the string, p will point to it, and hence p can be used as the suffix substring of the original string, and there's no need to modify the original string. We advance p by one to skip past the / and are left with the final part of the string.


问:
Python subprocess; Can't read stdout
I have about 500,000+ txt file for about 7+ gigs of data total.  I am using python to put them into a sqlite database. I am creating 2 tables, 1. is the pK and the hyperlink to the file.
For the other table I am using an entity extractor that was devloped in perl by a coworker.

To accomplish this I am using subprocess.Popen(). T  Prior to this method I was opening the perl at every iteration of my loop, but it was simply to expensive to be useful.

I need the perl to be dynamic, I need to be able to send data back and fourth from it and the process not terminate untilI tell it to do so.  The perl was modified so it perl accepts the full string of a file as a stdin, and gives me a stdout when it gets a \n. But I am having trouble reading data...

If I use communicate, at the next iteration in my loop my subprocess is terminated, I get an I/O error. If I try and use readline() or read(), it locks up.  Here are some examples of the differant behavior I am experiancing.

This deadlocks my system and I need to force close python to continue.

```<code>numberExtractor = subprocess.Popen(["C:\\Perl\\bin\\perl5.10.0.exe","D:\\MyDataExtractor\\extractSerialNumbers.pl"], stdout=subprocess.PIPE, stdin= subprocess.PIPE)
for infile in glob.glob(self.dirfilename + '\\*\\*.txt'):
   f = open(infile)
   reportString = f.read()
   f.close()

   reportString = reportString.replace('\n',' ')
   reportString = reportString.replace('\r',' ')
   reportString = reportString +'\n'

   numberExtractor.stdin.write(reportString)
   x = numberExtractor.stdout.read()        #I can not see the STDOUT, python freezes and does not run past here.

   print x
</code>```

This cancels the subprocess and I get an I/O error at the next iteration of my loop.

```<code>numberExtractor = subprocess.Popen(["C:\\Perl\\bin\\perl5.10.0.exe","D:\\MyDataExtractor\\extractSerialNumbers.pl"], stdout=subprocess.PIPE, stdin= subprocess.PIPE)
for infile in glob.glob(self.dirfilename + '\\*\\*.txt'):

   f = open(infile)
   reportString = f.read()
   f.close()

   reportString = reportString.replace('\n',' ')
   reportString = reportString.replace('\r',' ')
   reportString = reportString +'\n'
   numberExtractor.stdin.write(reportString)
   x = numberExtractor.communicate()   #Works good, I can see my STDOUT from perl but the process terminates and will not run on the next iteration

   print x
</code>```

If I just run it like this, It runs through all the code fine. the print line is ', mode 'rb' at 0x015dbf08> for each item in my folder.

```<code>numberExtractor = subprocess.Popen(["C:\\Perl\\bin\\perl5.10.0.exe","D:\\MyDataExtractor\\extractSerialNumbers.pl"], stdout=subprocess.PIPE, stdin= subprocess.PIPE)
for infile in glob.glob(self.dirfilename + '\\*\\*.txt'):
   f = open(infile)
   reportString = f.read()
   f.close()

   reportString = reportString.replace('\n',' ')
   reportString = reportString.replace('\r',' ')
   reportString = reportString +'\n'

   numberExtractor.stdin.write(reportString)
   x = numberExtractor.stdout                #I can not get the value of the object, but it runs through all my files fine.

   print x
</code>```

Hopefully I am making a simple mistake, but is there some way I can just send a file to my perll (stdin), get the stdout, and then repeat without having to reopen my subprocess for every file in my loop?

答:
Consider using the shell.  Life is simpler.

```<code>perl extractSerialNumbers.pl *.txt | python load_database.py
</code>```

Don't mess around with having Python start perl and all that.  Just read the results from perl and process those results in Python.

Since both processes run concurrently, this tends to be pretty fast and use a lot of CPU resources without much programming on your part.

In the Python program (load_database.py) you can simply use fileinput module to read the entire file provided on stdin.

```<code>import fileinput
for line in fileinput.input():
    load the row into the database
</code>```

That's about all you need in the Python program if you make the shell do the dirty work of setting up the pipeline.

Title: Python subprocess; Can't read stdout

Body:
I have about 500,000+ txt file for about 7+ gigs of data total.  I am using python to put them into a sqlite database. I am creating 2 tables, 1. is the pK and the hyperlink to the file.
For the other table I am using an entity extractor that was devloped in perl by a coworker.

To accomplish this I am using subprocess.Popen(). T  Prior to this method I was opening the perl at every iteration of my loop, but it was simply to expensive to be useful.

I need the perl to be dynamic, I need to be able to send data back and fourth from it and the process not terminate untilI tell it to do so.  The perl was modified so it perl accepts the full string of a file as a stdin, and gives me a stdout when it gets a \n. But I am having trouble reading data...

If I use communicate, at the next iteration in my loop my subprocess is terminated, I get an I/O error. If I try and use readline() or read(), it locks up.  Here are some examples of the differant behavior I am experiancing.

This deadlocks my system and I need to force close python to continue.

numberExtractor = subprocess.Popen(["C:\\Perl\\bin\\perl5.10.0.exe","D:\\MyDataExtractor\\extractSerialNumbers.pl"], stdout=subprocess.PIPE, stdin= subprocess.PIPE)
for infile in glob.glob(self.dirfilename + '\\*\\*.txt'):
   f = open(infile)
   reportString = f.read()
   f.close()

   reportString = reportString.replace('\n',' ')
   reportString = reportString.replace('\r',' ')
   reportString = reportString +'\n'

   numberExtractor.stdin.write(reportString)
   x = numberExtractor.stdout.read()        #I can not see the STDOUT, python freezes and does not run past here.

   print x

This cancels the subprocess and I get an I/O error at the next iteration of my loop.

numberExtractor = subprocess.Popen(["C:\\Perl\\bin\\perl5.10.0.exe","D:\\MyDataExtractor\\extractSerialNumbers.pl"], stdout=subprocess.PIPE, stdin= subprocess.PIPE)
for infile in glob.glob(self.dirfilename + '\\*\\*.txt'):

   f = open(infile)
   reportString = f.read()
   f.close()

   reportString = reportString.replace('\n',' ')
   reportString = reportString.replace('\r',' ')
   reportString = reportString +'\n'
   numberExtractor.stdin.write(reportString)
   x = numberExtractor.communicate()   #Works good, I can see my STDOUT from perl but the process terminates and will not run on the next iteration

   print x

If I just run it like this, It runs through all the code fine. the print line is ', mode 'rb' at 0x015dbf08> for each item in my folder.

numberExtractor = subprocess.Popen(["C:\\Perl\\bin\\perl5.10.0.exe","D:\\MyDataExtractor\\extractSerialNumbers.pl"], stdout=subprocess.PIPE, stdin= subprocess.PIPE)
for infile in glob.glob(self.dirfilename + '\\*\\*.txt'):
   f = open(infile)
   reportString = f.read()
   f.close()

   reportString = reportString.replace('\n',' ')
   reportString = reportString.replace('\r',' ')
   reportString = reportString +'\n'

   numberExtractor.stdin.write(reportString)
   x = numberExtractor.stdout                #I can not get the value of the object, but it runs through all my files fine.

   print x

Hopefully I am making a simple mistake, but is there some way I can just send a file to my perll (stdin), get the stdout, and then repeat without having to reopen my subprocess for every file in my loop?

Body:
Consider using the shell.  Life is simpler.

perl extractSerialNumbers.pl *.txt | python load_database.py

Don't mess around with having Python start perl and all that.  Just read the results from perl and process those results in Python.

Since both processes run concurrently, this tends to be pretty fast and use a lot of CPU resources without much programming on your part.

In the Python program (load_database.py) you can simply use fileinput module to read the entire file provided on stdin.

import fileinput
for line in fileinput.input():
    load the row into the database

That's about all you need in the Python program if you make the shell do the dirty work of setting up the pipeline.


问:
How is Spring's basePackages scan retrieving my classes from a different Maven module?
I'm getting confused now with packages. It's broken down like this: Simple Maven multi module project. One parent POM, two sibling module children (one is a service module, one is a web module to be ran in Tomcat).

Below is my Spring Annotation Config for Dispatcher Servlet. Here is where I am confused. At first I didn't think basePackages was going to be able to scan for packages in a totally separate module (which is the service module). However, it somehow worked, exactly as written below. 'Entities' and 'Services' are the two packages from the Service module, while 'Controllers' comes from THIS web module. Let it be known that I have in fact added the Service module as a dependency into my web module. Nothing crazy going on there. Simple dependency so I can have access to my Service classes.

```<code>@EnableWebMvc
@Configuration
@ComponentScan(basePackages={"entities", "services", "controllers"})
public class DispatcherConfig {

}
</code>```

What I don't understand is how the packaging is working. It's all spaghetti'd in my mind now. When Spring gets to the line @ComponentScan and sees "entities", and "services", what is the structure it is looking on to get these classes?

My package structure is very simple. In the Service module I simply have src/main/java/entities and src/main/java/services

Something is happening behind the scenes here that I don't understand. How come Spring is smart enough to know this? I didn't even have to list the full package, i.e. myproject/src/main/java/entities or something like that?

Thanks

答:
suppose @ComponentScan uses string array, like this:

```<code>@ComponentScan({"com.package.first","com.my.package.second"})
</code>```

When you provide multiple package names in only one string, Spring interprets this as one package name.

This post might be helpful.

Body:
I'm getting confused now with packages. It's broken down like this: Simple Maven multi module project. One parent POM, two sibling module children (one is a service module, one is a web module to be ran in Tomcat).

Below is my Spring Annotation Config for Dispatcher Servlet. Here is where I am confused. At first I didn't think basePackages was going to be able to scan for packages in a totally separate module (which is the service module). However, it somehow worked, exactly as written below. 'Entities' and 'Services' are the two packages from the Service module, while 'Controllers' comes from THIS web module. Let it be known that I have in fact added the Service module as a dependency into my web module. Nothing crazy going on there. Simple dependency so I can have access to my Service classes.

@EnableWebMvc
@Configuration
@ComponentScan(basePackages={"entities", "services", "controllers"})
public class DispatcherConfig {

}

What I don't understand is how the packaging is working. It's all spaghetti'd in my mind now. When Spring gets to the line @ComponentScan and sees "entities", and "services", what is the structure it is looking on to get these classes?

My package structure is very simple. In the Service module I simply have src/main/java/entities and src/main/java/services

Something is happening behind the scenes here that I don't understand. How come Spring is smart enough to know this? I didn't even have to list the full package, i.e. myproject/src/main/java/entities or something like that?

Thanks

Body:
suppose @ComponentScan uses string array, like this:

@ComponentScan({"com.package.first","com.my.package.second"})

When you provide multiple package names in only one string, Spring interprets this as one package name.

This post might be helpful.


问:
Download generated zip from servlet
I know this is a very basic question but there are so many implementations out there and I can't get them to work.

So in my project if the user clicks a button, I'm generating a zip file on a servlet (which is called through an AJAX POST). Naturally, I want that file to get downloaded to the user.

Here's my code for the request:

```<code><button type="button" class="btn btn-info btn-lg" onclick="getZip();">
    <span class="glyphicon glyphicon-download"></span> Download clusters (.zip)
</button>
</code>```

Here's the AJAX for the POST:

```<code>function getzip() {
    $.ajax({
        url:'GetZipServlet',
        type:'GET',
    });
}
</code>```

And this is my code for the download:

```<code>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("Downloading clusters.zip");

        /* Generate the directory on the server, then zip it. */
        ClinicoGenomic.getInstance().clustersToFiles();
        ClinicoGenomic.getInstance().zipClusters();
        System.out.println("Done generating the .zip");

        String parent_dir = System.getProperty("catalina.base");
        String filename = "clusters.zip";

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + filename);
        ZipOutputStream zipStream = new ZipOutputStream( response.getOutputStream() );

        ZipInputStream fi = new ZipInputStream(new FileInputStream(parent_dir + "/" + filename));
        int i;
        while ((i = fi.read())!=-1)
            zipStream.write(i);

        zipStream.close();
        fi.close();
        System.out.println(".zip file downloaded at client successfully");
    }
</code>```

I get the correct messages in my console, up to the .zip file downloaded at client successfully. But the download doesn't start. what could be wrong here???

答:
if you are correctly sending the response you should just simply handle it after your ajax call, like this:</p>

```<code>$.ajax({
  url:'GetZipServlet',
  type:'GET',
  success: function (response) {
     //handle the response here
  }
});
</code>```

Title: Download generated zip from servlet

Body:
I know this is a very basic question but there are so many implementations out there and I can't get them to work.

So in my project if the user clicks a button, I'm generating a zip file on a servlet (which is called through an AJAX POST). Naturally, I want that file to get downloaded to the user.

Here's my code for the request:

<button type="button" class="btn btn-info btn-lg" onclick="getZip();">
     Download clusters (.zip)
</button>

Here's the AJAX for the POST:

function getzip() {
    $.ajax({
        url:'GetZipServlet',
        type:'GET',
    });
}

And this is my code for the download:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("Downloading clusters.zip");

        /* Generate the directory on the server, then zip it. */
        ClinicoGenomic.getInstance().clustersToFiles();
        ClinicoGenomic.getInstance().zipClusters();
        System.out.println("Done generating the .zip");

        String parent_dir = System.getProperty("catalina.base");
        String filename = "clusters.zip";

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + filename);
        ZipOutputStream zipStream = new ZipOutputStream( response.getOutputStream() );

        ZipInputStream fi = new ZipInputStream(new FileInputStream(parent_dir + "/" + filename));
        int i;
        while ((i = fi.read())!=-1)
            zipStream.write(i);

        zipStream.close();
        fi.close();
        System.out.println(".zip file downloaded at client successfully");
    }

I get the correct messages in my console, up to the .zip file downloaded at client successfully. But the download doesn't start. what could be wrong here???

Body:
if you are correctly sending the response you should just simply handle it after your ajax call, like this:

$.ajax({
  url:'GetZipServlet',
  type:'GET',
  success: function (response) {
     //handle the response here
  }
});


问:
SELECT * FROM table WHERE field IN(array) - H2 Database
We are trying to select all rows from a table where a specific field has a value that is contained inside an array of values - e.g.

```<code>SELECT * FROM table WHERE field IN(array)
</code>```

The specific use is seeing if the field contains a specific User Group from an array of provided User Groups that the user currently belongs to - e.g.

```<code>SELECT * FROM Gadgets WHERE Visibility IN("Everyone", "Registered User", "Site Owner", "Accountant")
</code>```

Coming up blank on all our searches, so would love some help on this one.

答:
something like this may work.</p>

```<code>SELECT * FROM Gadgets g WHERE exists (
select 1 from usergroup u where u.visibility = g.visibility
)
</code>```

Body:
We are trying to select all rows from a table where a specific field has a value that is contained inside an array of values - e.g.

SELECT * FROM table WHERE field IN(array)

The specific use is seeing if the field contains a specific User Group from an array of provided User Groups that the user currently belongs to - e.g.

SELECT * FROM Gadgets WHERE Visibility IN("Everyone", "Registered User", "Site Owner", "Accountant")

Coming up blank on all our searches, so would love some help on this one.

Body:
something like this may work.

SELECT * FROM Gadgets g WHERE exists (
select 1 from usergroup u where u.visibility = g.visibility
)


问:
Twitter Streaming API: output has data without tweet text
I am using the code given in this tutorial:
http://adilmoujahid.com/posts/2014/07/twitter-analytics/

The purpose is to gather data using the Twitter Streaming API, store the data in JSON format, and then obtain tweets from this data. At step two of the tutorial, it uses this code to obtain the tweets:

```<code>tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
    try:
        tweet = json.loads(line)
        tweets_data.append(tweet)
    except:
        continue

tweets = pd.DataFrame()
tweets['text'] = map(lambda tweet: tweet['text'], tweets_data[0:2377])
</code>```

I am using a subset of tweets_data in the DataFrame tweets. However, at index 2376 of tweets_data, instead of containing data about a tweet and its text, it has:

```<code>{u'limit': {u'track': 4, u'timestamp_ms': u'1491153253907'}
</code>```

Thus, using tweets_data[0:2377] returns KeyError: 'text'. The dictionary element at index 2376 does not have u'text' like the other elements do; using any subset below index 2376 works. However, I can't just skip 2376 because there are more elements like it in my JSON data. Using tweets_data[0:2377] + tweets_data[2377:len(tweets_data)]  also returns KeyError: 'text'.

So what's going on at element 2376? Before creating the 'text' column in the dataframe, should I just filter out elements without u'text' in them? Or is there a better way?

答:
That element looks like log data for the api call.

Just check for text before storing each line, like this:

```<code>if 'text' in tweet:
    tweets_data.append(tweet)
</code>```

Body:
I am using the code given in this tutorial:
http://adilmoujahid.com/posts/2014/07/twitter-analytics/

The purpose is to gather data using the Twitter Streaming API, store the data in JSON format, and then obtain tweets from this data. At step two of the tutorial, it uses this code to obtain the tweets:

tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
    try:
        tweet = json.loads(line)
        tweets_data.append(tweet)
    except:
        continue

tweets = pd.DataFrame()
tweets['text'] = map(lambda tweet: tweet['text'], tweets_data[0:2377])

I am using a subset of tweets_data in the DataFrame tweets. However, at index 2376 of tweets_data, instead of containing data about a tweet and its text, it has:

{u'limit': {u'track': 4, u'timestamp_ms': u'1491153253907'}

Thus, using tweets_data[0:2377] returns KeyError: 'text'. The dictionary element at index 2376 does not have u'text' like the other elements do; using any subset below index 2376 works. However, I can't just skip 2376 because there are more elements like it in my JSON data. Using tweets_data[0:2377] + tweets_data[2377:len(tweets_data)]  also returns KeyError: 'text'.

So what's going on at element 2376? Before creating the 'text' column in the dataframe, should I just filter out elements without u'text' in them? Or is there a better way?

Body:
That element looks like log data for the api call.

Just check for text before storing each line, like this:

if 'text' in tweet:
    tweets_data.append(tweet)


问:
Returning the Key in a Map<String,List<Pair<Integer,String>>>
I have defined a collection using the type TreeMap< String, List < Pair < Integer, String >>> in which pair is a class that I defined: </p>

```<code>public class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r) {
        this.l = l;
        this.r = r;
    }
public L getL() {return l;}
public R getR() {return r;}
public void setL(L l){this.l = l;}
public void setR(R r){this.r = r;}

}
</code>```

<p>I want to return the string (TreeMap key) that is paired with a list that contains a given String value. For example, I have a String "bob" that is stored in one of the pairs in the list, and I want to return the key (string) of the Treemap that is associated with that list of pairs that "bob" is in. How would I go about doing this? </p>

答:
This essentially is a reverse lookup. You have a map of keys associated to values and you want to find that key for which the associated value satisfies some condition. Note that this, in the worse case, will result in the entire table lookup which can be very expensive because you may end up accessing every entry in the map.

For starters, I'd do something very straightforward like below. I have taken liberty to modify the Pair class a little bit. The following prints the key key2 as per your requirements:

```<code>public class ReverseLookup {
    static class Pair<L,R> {
        private L l;
        private R r;
        public Pair(L l, R r) {
            this.l = l;
            this.r = r;
        }
        public L getL() {return l;}
        public R getR() {return r;}
        public void setL(L l){this.l = l;}
        public void setR(R r){this.r = r;}

        public static <L, R> Pair<L, R> right(List<Pair<L, R>> pairs, R rVal) {
            for (Pair<L, R> pair : pairs) {
                if (rVal != null && rVal.equals(pair.getR()))
                    return pair;
            }
            return null;
        }
    }

    public static void main(String[] args) {
        String lookFor = "bob";
        Map<String, List<Pair <Integer, String>>> listOfPairs = new TreeMap<>();
        listOfPairs.put(
            "key1", Arrays.asList(new Pair("2", "carol"), new Pair(4, "david"))
            );
        listOfPairs.put(
        "key2", Arrays.asList(new Pair("0", "alice"), new Pair(1, "bob"))
        );
        for (Map.Entry<String, List<Pair<Integer, String>>> entry : listOfPairs.entrySet()) {
            // entry is a mapping from string -> list of pairs Integer, String
            List<Pair<Integer, String>> pairs = entry.getValue();
            if (Pair.right(pairs, lookFor) != null) {
                System.out.println(entry.getKey());
            }
        }
    }
}
</code>```

Body:
I have defined a collection using the type TreeMap< String, List < Pair < Integer, String >>> in which pair is a class that I defined:

public class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r) {
        this.l = l;
        this.r = r;
    }
public L getL() {return l;}
public R getR() {return r;}
public void setL(L l){this.l = l;}
public void setR(R r){this.r = r;}

}

I want to return the string (TreeMap key) that is paired with a list that contains a given String value. For example, I have a String "bob" that is stored in one of the pairs in the list, and I want to return the key (string) of the Treemap that is associated with that list of pairs that "bob" is in. How would I go about doing this?

Body:
This essentially is a reverse lookup. You have a map of keys associated to values and you want to find that key for which the associated value satisfies some condition. Note that this, in the worse case, will result in the entire table lookup which can be very expensive because you may end up accessing every entry in the map.

For starters, I'd do something very straightforward like below. I have taken liberty to modify the Pair class a little bit. The following prints the key key2 as per your requirements:

public class ReverseLookup {
    static class Pair<L,R> {
        private L l;
        private R r;
        public Pair(L l, R r) {
            this.l = l;
            this.r = r;
        }
        public L getL() {return l;}
        public R getR() {return r;}
        public void setL(L l){this.l = l;}
        public void setR(R r){this.r = r;}

        public static <L, R> Pair<L, R> right(List<Pair<L, R>> pairs, R rVal) {
            for (Pair<L, R> pair : pairs) {
                if (rVal != null && rVal.equals(pair.getR()))
                    return pair;
            }
            return null;
        }
    }

    public static void main(String[] args) {
        String lookFor = "bob";
        Map<String, List<Pair <Integer, String>>> listOfPairs = new TreeMap<>();
        listOfPairs.put(
            "key1", Arrays.asList(new Pair("2", "carol"), new Pair(4, "david"))
            );
        listOfPairs.put(
        "key2", Arrays.asList(new Pair("0", "alice"), new Pair(1, "bob"))
        );
        for (Map.Entry<String, List<Pair<Integer, String>>> entry : listOfPairs.entrySet()) {
            // entry is a mapping from string -> list of pairs Integer, String
            List<Pair<Integer, String>> pairs = entry.getValue();
            if (Pair.right(pairs, lookFor) != null) {
                System.out.println(entry.getKey());
            }
        }
    }
}


问:
avoiding nested for loops python
I have a function which takes in expressions and replaces the variables with all the permutations of the values that I am using as inputs. This is my code that I have tested and works, however after looking through SO, people have said that nested for loops are a bad idea however I am unsure as to how to make this more efficient. Could somebody help? Thanks. </p>

```<code>def replaceVar(expression):

    eval_list = list()

    a = [1, 8, 12, 13]
    b = [1, 2, 3, 4]
    c = [5, 9, 2, 7]

    for i in expression:
        first_eval = [i.replace("a", str(j)) for j in a]
        tmp = list()
        for k in first_eval:
            snd_eval = [k.replace("b", str(l)) for l in b]
            tmp2 = list()
            for m in snd_eval:
                trd_eval = [m.replace("c", str(n)) for n in c]
                tmp2.append(trd_eval)
            tmp.append(tmp2)
        eval_list.append(tmp)
    print(eval_list)
    return eval_list

print(replaceVar(['b-16+(c-(a+11))', 'a-(c-5)+a-b-10']))
</code>```

答:
"The problem" with nested loops is basically just that the number of levels is hard coded.  You wrote nesting for 3 variables.  What if you only have 2?  What if it jumps to 5?  Then you need non-trivial surgery on the code.  That's why itertools.product() is recommended.

Relatedly, all suggestions so far hard-code the number of replace() calls.  Same "problem":  if you don't have exactly 3 variables, the replacement code has to be modified.

Instead of doing that, think about a cleaner way to do the replacements.  For example, suppose your input string were:

```<code>s = '{b}-16+({c}-({a}+11))'
</code>```

instead of:

```<code>'b-16+(c-(a+11))'
</code>```

That is, the variables to be replaced are enclosed in curly braces.  Then Python can do all the substitutions "at once" for you:

```<code>>>> s.format(a=333, b=444, c=555)
'444-16+(555-(333+11))'
</code>```

That hard-codes the names and number of names too, but the same thing can be accomplished with a dict:

```<code>>>> d = dict(zip(["a", "b", "c"], (333, 444, 555)))
>>> s.format(**d)
'444-16+(555-(333+11))'
</code>```

Now nothing about the number of variables, or their names, is hard-coded in the format() call.

The tuple of values ((333, 444, 555)) is exactly the kind of thing itertools.product() returns.  The list of variable names (["a", "b", "c"]) can be created just once at the top, or even passed in to the function.

You just need a bit of code to transform your input expressions to enclose the variable names in curly braces.

Title: avoiding nested for loops python

Body:
I have a function which takes in expressions and replaces the variables with all the permutations of the values that I am using as inputs. This is my code that I have tested and works, however after looking through SO, people have said that nested for loops are a bad idea however I am unsure as to how to make this more efficient. Could somebody help? Thanks.

def replaceVar(expression):

    eval_list = list()

    a = [1, 8, 12, 13]
    b = [1, 2, 3, 4]
    c = [5, 9, 2, 7]

    for i in expression:
        first_eval = [i.replace("a", str(j)) for j in a]
        tmp = list()
        for k in first_eval:
            snd_eval = [k.replace("b", str(l)) for l in b]
            tmp2 = list()
            for m in snd_eval:
                trd_eval = [m.replace("c", str(n)) for n in c]
                tmp2.append(trd_eval)
            tmp.append(tmp2)
        eval_list.append(tmp)
    print(eval_list)
    return eval_list

print(replaceVar(['b-16+(c-(a+11))', 'a-(c-5)+a-b-10']))

Body:
"The problem" with nested loops is basically just that the number of levels is hard coded.  You wrote nesting for 3 variables.  What if you only have 2?  What if it jumps to 5?  Then you need non-trivial surgery on the code.  That's why itertools.product() is recommended.

Relatedly, all suggestions so far hard-code the number of replace() calls.  Same "problem":  if you don't have exactly 3 variables, the replacement code has to be modified.

Instead of doing that, think about a cleaner way to do the replacements.  For example, suppose your input string were:

s = '{b}-16+({c}-({a}+11))'

instead of:

'b-16+(c-(a+11))'

That is, the variables to be replaced are enclosed in curly braces.  Then Python can do all the substitutions "at once" for you:

>>> s.format(a=333, b=444, c=555)
'444-16+(555-(333+11))'

That hard-codes the names and number of names too, but the same thing can be accomplished with a dict:

>>> d = dict(zip(["a", "b", "c"], (333, 444, 555)))
>>> s.format(**d)
'444-16+(555-(333+11))'

Now nothing about the number of variables, or their names, is hard-coded in the format() call.

The tuple of values ((333, 444, 555)) is exactly the kind of thing itertools.product() returns.  The list of variable names (["a", "b", "c"]) can be created just once at the top, or even passed in to the function.

You just need a bit of code to transform your input expressions to enclose the variable names in curly braces.


问:
I am trying to check if an array is increasing in both rows and columns, how do i do this? I know you need to compare the previous to the current
I am trying to check if an array is increasing in both rows and columns

```<code>  public static boolean increasingArray(int[][] a) {

        for (var i = 0; i < a.length; i++) {
         for(int row = 0; row< a.length row > previous)
         for(int col= 0; col< a.length col > previous)
          return true;
        }
</code>```

This is what I have so far.

答:
You can use "if" statement and just enter the statement you want.
If I understand correctly you want something like this :

```<code>    1 2
    3 4
</code>```

So if you want to compare 1 and 2 use j and j + 1 if you want to compare
1 and 3 use i and i + 1. Make sure control the last row and column, you can pass the limit of array.

```<code>    public static boolean increasingArray(int[][] array) {
    boolean result = true;
    int n = array.length;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (j != n - 1 && array[i][j] >= array[i][j + 1])
                result = false;
            else if (i != n - 1 && array[i][j] >= array[i + 1][j])
                result = false;
            else
                result = true;
        }

    }
    return result;
}
</code>```

Body:
I am trying to check if an array is increasing in both rows and columns

  public static boolean increasingArray(int[][] a) {

        for (var i = 0; i < a.length; i++) {
         for(int row = 0; row previous)
         for(int col= 0; col previous)
          return true;
        }

This is what I have so far.

Body:
You can use "if" statement and just enter the statement you want.
If I understand correctly you want something like this :

    1 2
    3 4

So if you want to compare 1 and 2 use j and j + 1 if you want to compare
1 and 3 use i and i + 1. Make sure control the last row and column, you can pass the limit of array.

    public static boolean increasingArray(int[][] array) {
    boolean result = true;
    int n = array.length;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (j != n - 1 && array[i][j] >= array[i][j + 1])
                result = false;
            else if (i != n - 1 && array[i][j] >= array[i + 1][j])
                result = false;
            else
                result = true;
        }

    }
    return result;
}


问:
restore consumable inapp purchases using webservice
we are using a backend service for the products in the app and a mapping scheme of in-app consumables for the dynamic content (added in the backend and synced to the app) so that a new content added to the backend can be matched with a fixed price of a consumable in app purchase, this way we dont have add a new object with itunes connect when a new item in the backend is added. but how can the restoration of a product be done (since its required by apple)? is it possible to send the receipt of a transaction to the backend and use it for restoring? anyone here who has experience with a similiar solution?</p>

答:
Apple does not require you to have restoration for consumable in-app purchases. In fact the StoreKit API and App Receipt does not contain any record of consumable purchases after the transaction has been finished.

See this doc and search for 'Calling the payment queue’s restoreCompletedTransactions method does not restore any products in my application' for more info.


问:
Why initializing data at global scope by passing it to some function is not possible?
I've been wondering for a while why initializing any data by passing it to some function is not permitted despite the fact that constructors that are a kind of function anyway can be called at global scope, so if we have something like an array at global scope it can't be initialized by any function but if it was in an object of a structure at global scope then it could be initialized using a constructor at the scope:</p>

```<code>//global scope

    char charArray[100];//can't be initialized using any function at global scope but in other scopes it could by being passed to some function

    struct Test{
     public:
      Test(){
       //initialization
      }
      char charArray[100];
    };
    Test obj();//now charArray can be initialized using constructor at global scope
</code>```

答:
Actually you can call functions at global scope.

```<code>int foo()
{
    return 5;
}

int bar = foo();
</code>```

It's just the way that C was designed years ago that you can't have functions run on their own at global scope. All program code starts at main.

In general, the less you depend on global initialization (avoid it if possible), the less you'll have to worry about weird static-init errors and such problems randomly cropping up.

Arrays are a different case because you can never assign the result of a function call to an array - the only way to initialize it in this case is inside a constructor as you observed.

EDIT: Somewhat evil approach to initialize an array inspired by a comment:

```<code>bool do_init(int a[50])
{
    // Do whatever to init the array here.
    return true;
}

int array[50];
bool init_array = do_init(array);
</code>```

This only works since within a translation unit the order of creation/initialization of globals is guaranteed to be the order they appear in the file.

Body:
I've been wondering for a while why initializing any data by passing it to some function is not permitted despite the fact that constructors that are a kind of function anyway can be called at global scope, so if we have something like an array at global scope it can't be initialized by any function but if it was in an object of a structure at global scope then it could be initialized using a constructor at the scope:

//global scope

    char charArray[100];//can't be initialized using any function at global scope but in other scopes it could by being passed to some function

    struct Test{
     public:
      Test(){
       //initialization
      }
      char charArray[100];
    };
    Test obj();//now charArray can be initialized using constructor at global scope

Body:
Actually you can call functions at global scope.

int foo()
{
    return 5;
}

int bar = foo();

It's just the way that C was designed years ago that you can't have functions run on their own at global scope. All program code starts at main.

In general, the less you depend on global initialization (avoid it if possible), the less you'll have to worry about weird static-init errors and such problems randomly cropping up.

Arrays are a different case because you can never assign the result of a function call to an array - the only way to initialize it in this case is inside a constructor as you observed.

EDIT: Somewhat evil approach to initialize an array inspired by a comment:

bool do_init(int a[50])
{
    // Do whatever to init the array here.
    return true;
}

int array[50];
bool init_array = do_init(array);

This only works since within a translation unit the order of creation/initialization of globals is guaranteed to be the order they appear in the file.


问:
No Operator error code
I am completing a hotel reservation form using C++ language. I keep getting no operator error for fin !=0. How can I address this error? Here is the actual coding...</p>

```<code>void Hotel::show_room_record()
{
    cout << "R.Num" << setw(10) << "R.Stat" << setw(10) << "Category" << setw(10) << "Rent\n";
    ifstream fin("room.dat", ios::in);
    for (int p = 0; fin != 0; p = p + 15)
    {
        fin.seekg(p);
        fin >> room_no;
        fin >> room_status;
        fin >> category;
        fin >> rent;
        cout << room_no << setw(10) << room_status << setw(10) << category << setw(10) << rent << "\n";
    }
    fin.close();
}
</code>```

答:
You can't compare fin with 0, fin wont return the next input.
First store the input in a variable, then compare it.

For your case, you probably want to check if the next character is a '0', or even a '\0'.
Try using this:
http://www.cplusplus.com/reference/istream/istream/peek/

Your condition becomes (assuming you want '\0'):

```<code>fin.peek() != 0
</code>```

Title: No Operator error code

Body:
I am completing a hotel reservation form using C++ language. I keep getting no operator error for fin !=0. How can I address this error? Here is the actual coding...

void Hotel::show_room_record()
{
    cout << "R.Num" << setw(10) << "R.Stat" << setw(10) << "Category" << setw(10) << "Rent\n";
    ifstream fin("room.dat", ios::in);
    for (int p = 0; fin != 0; p = p + 15)
    {
        fin.seekg(p);
        fin >> room_no;
        fin >> room_status;
        fin >> category;
        fin >> rent;
        cout << room_no << setw(10) << room_status << setw(10) << category << setw(10) << rent << "\n";
    }
    fin.close();
}

Body:
You can't compare fin with 0, fin wont return the next input.
First store the input in a variable, then compare it.

For your case, you probably want to check if the next character is a '0', or even a '\0'.
Try using this:
http://www.cplusplus.com/reference/istream/istream/peek/

Your condition becomes (assuming you want '\0'):

fin.peek() != 0


问:
Exception in thread "main" java.io.IOException: java.lang.reflect.InvocationTargetException
I am writing a spark program which will just put a record to hbase.
Spark version 1.3.1
HBase 1.0.0-cdh5.4.2
The program is as follows.

```<code>import org.apache.hadoop.hbase.client.{HBaseAdmin, HTable, Put}
import org.apache.hadoop.hbase.mapreduce.TableOutputFormat
import org.apache.hadoop.hbase.util.Bytes
import org.apache.hadoop.hbase.{HBaseConfiguration, HColumnDescriptor, HTableDescriptor}

object Employee {
  def main(args: Array[String]) {
    if (args.length != 1) {
      System.err.println("In correct number of arguments " + args.length)
      System.out.println("Please provide correct arguments.")
      System.exit(1)
    }
    val hbaseConf = HBaseConfiguration.create()
    val tableName = "employee"
    hbaseConf.set(TableOutputFormat.OUTPUT_TABLE, tableName)
    hbaseConf.set("hbase.zookeeper.quorum","quickstart.cloudera")
    hbaseConf.set("hbase.zookeeper.property.client.port","2181")
    val admin = new HBaseAdmin(hbaseConf)
    val cfProfessionalData = Bytes.toBytes("professional_data")
    val cfPersonalData = Bytes.toBytes("personal_data")
    if (!admin.isTableAvailable(tableName)) {
      val tableDesc = new HTableDescriptor(tableName)
      tableDesc.addFamily(new HColumnDescriptor(cfProfessionalData))
      tableDesc.addFamily(new HColumnDescriptor(cfPersonalData))
    }
    val hTable = new HTable(hbaseConf,tableName)
    //val records = sc.textFile(args(0))
    val put = new Put(Bytes.toBytes("e_1"))
    val eId = Bytes.toBytes("Emp_id")
    val name = Bytes.toBytes("Name")
    val dsgtn = Bytes.toBytes("Designation")
    val doj = Bytes.toBytes("DOJ")
    val addr = Bytes.toBytes("Address")
    val phn = Bytes.toBytes("Phone")
    val dob = Bytes.toBytes("DOB")
    put.add(cfProfessionalData, eId, Bytes.toBytes(1))
    put.add(cfProfessionalData, name, Bytes.toBytes("Mridul Gohain"))
    put.add(cfProfessionalData, dsgtn, Bytes.toBytes("SE"))
    put.add(cfProfessionalData, doj, Bytes.toBytes("15-07-2015"))
    put.add(cfPersonalData, addr, Bytes.toBytes("Chabua"))
    put.add(cfPersonalData, phn, Bytes.toBytes("9859559606"))
    put.add(cfPersonalData, dob, Bytes.toBytes("04-10-1991"))
    hTable.put(put)
    hTable.close()
  }
}
</code>```

but when I execute the code, I get the below exception

```<code>16/08/03 04:09:00 INFO zookeeper.ZooKeeper: Client environment:user.home=/home/cloudera
16/08/03 04:09:00 INFO zookeeper.ZooKeeper: Client environment:user.dir=/home/cloudera/tars
16/08/03 04:09:00 INFO zookeeper.ZooKeeper: Initiating client connection, connectString=quickstart.cloudera:2181 sessionTimeout=90000 watcher=hconnection-0x3fa7e1a80x0, quorum=quickstart.cloudera:2181, baseZNode=/hbase
Exception in thread "main" java.io.IOException: java.lang.reflect.InvocationTargetException
        at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:240)
        at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:414)
        at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:407)
        at org.apache.hadoop.hbase.client.ConnectionManager.getConnectionInternal(ConnectionManager.java:285)
        at org.apache.hadoop.hbase.client.HBaseAdmin.<init>(HBaseAdmin.java:207)
        at com.zaloni.mgohain.sparkHbaseIntegration.services.Employee$.main(Employee.scala:20)
        at com.zaloni.mgohain.sparkHbaseIntegration.services.Employee.main(Employee.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:569)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:166)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:189)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:110)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:238)
        ... 15 more
Caused by: java.lang.NoClassDefFoundError: org/apache/htrace/Trace
        at org.apache.hadoop.hbase.zookeeper.RecoverableZooKeeper.exists(RecoverableZooKeeper.java:218)
        at org.apache.hadoop.hbase.zookeeper.ZKUtil.checkExists(ZKUtil.java:481)
        at org.apache.hadoop.hbase.zookeeper.ZKClusterId.readClusterIdZNode(ZKClusterId.java:65)
        at org.apache.hadoop.hbase.client.ZooKeeperRegistry.getClusterId(ZooKeeperRegistry.java:86)
        at org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation.retrieveClusterId(ConnectionManager.java:850)
        at org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation.<init>(ConnectionManager.java:635)
        ... 20 more
Caused by: java.lang.ClassNotFoundException: org.apache.htrace.Trace
        at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        ... 26 more
16/08/03 04:09:00 INFO zookeeper.ClientCnxn: Opening socket connection to server quickstart.cloudera/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
</code>```

Can you give some light here?

答:
Be aware about the HBase version you are trying to access. Specially related with the htrace version that your hbase client is going to use. I set my pom.xml file to:

```<code>    <!-- https://mvnrepository.com/artifact/org.apache.htrace/htrace-core -->
    <dependency>
        <groupId>org.apache.htrace</groupId>
        <artifactId>htrace-core</artifactId>
        <version>3.1.0-incubating</version>
    </dependency>
</code>```

and it worked rightful.

Body:
I am writing a spark program which will just put a record to hbase.
Spark version 1.3.1
HBase 1.0.0-cdh5.4.2
The program is as follows.

import org.apache.hadoop.hbase.client.{HBaseAdmin, HTable, Put}
import org.apache.hadoop.hbase.mapreduce.TableOutputFormat
import org.apache.hadoop.hbase.util.Bytes
import org.apache.hadoop.hbase.{HBaseConfiguration, HColumnDescriptor, HTableDescriptor}

object Employee {
  def main(args: Array[String]) {
    if (args.length != 1) {
      System.err.println("In correct number of arguments " + args.length)
      System.out.println("Please provide correct arguments.")
      System.exit(1)
    }
    val hbaseConf = HBaseConfiguration.create()
    val tableName = "employee"
    hbaseConf.set(TableOutputFormat.OUTPUT_TABLE, tableName)
    hbaseConf.set("hbase.zookeeper.quorum","quickstart.cloudera")
    hbaseConf.set("hbase.zookeeper.property.client.port","2181")
    val admin = new HBaseAdmin(hbaseConf)
    val cfProfessionalData = Bytes.toBytes("professional_data")
    val cfPersonalData = Bytes.toBytes("personal_data")
    if (!admin.isTableAvailable(tableName)) {
      val tableDesc = new HTableDescriptor(tableName)
      tableDesc.addFamily(new HColumnDescriptor(cfProfessionalData))
      tableDesc.addFamily(new HColumnDescriptor(cfPersonalData))
    }
    val hTable = new HTable(hbaseConf,tableName)
    //val records = sc.textFile(args(0))
    val put = new Put(Bytes.toBytes("e_1"))
    val eId = Bytes.toBytes("Emp_id")
    val name = Bytes.toBytes("Name")
    val dsgtn = Bytes.toBytes("Designation")
    val doj = Bytes.toBytes("DOJ")
    val addr = Bytes.toBytes("Address")
    val phn = Bytes.toBytes("Phone")
    val dob = Bytes.toBytes("DOB")
    put.add(cfProfessionalData, eId, Bytes.toBytes(1))
    put.add(cfProfessionalData, name, Bytes.toBytes("Mridul Gohain"))
    put.add(cfProfessionalData, dsgtn, Bytes.toBytes("SE"))
    put.add(cfProfessionalData, doj, Bytes.toBytes("15-07-2015"))
    put.add(cfPersonalData, addr, Bytes.toBytes("Chabua"))
    put.add(cfPersonalData, phn, Bytes.toBytes("9859559606"))
    put.add(cfPersonalData, dob, Bytes.toBytes("04-10-1991"))
    hTable.put(put)
    hTable.close()
  }
}

but when I execute the code, I get the below exception

16/08/03 04:09:00 INFO zookeeper.ZooKeeper: Client environment:user.home=/home/cloudera
16/08/03 04:09:00 INFO zookeeper.ZooKeeper: Client environment:user.dir=/home/cloudera/tars
16/08/03 04:09:00 INFO zookeeper.ZooKeeper: Initiating client connection, connectString=quickstart.cloudera:2181 sessionTimeout=90000 watcher=hconnection-0x3fa7e1a80x0, quorum=quickstart.cloudera:2181, baseZNode=/hbase
Exception in thread "main" java.io.IOException: java.lang.reflect.InvocationTargetException
        at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:240)
        at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:414)
        at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:407)
        at org.apache.hadoop.hbase.client.ConnectionManager.getConnectionInternal(ConnectionManager.java:285)
        at org.apache.hadoop.hbase.client.HBaseAdmin.<init>(HBaseAdmin.java:207)
        at com.zaloni.mgohain.sparkHbaseIntegration.services.Employee$.main(Employee.scala:20)
        at com.zaloni.mgohain.sparkHbaseIntegration.services.Employee.main(Employee.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:569)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:166)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:189)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:110)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:238)
        ... 15 more
Caused by: java.lang.NoClassDefFoundError: org/apache/htrace/Trace
        at org.apache.hadoop.hbase.zookeeper.RecoverableZooKeeper.exists(RecoverableZooKeeper.java:218)
        at org.apache.hadoop.hbase.zookeeper.ZKUtil.checkExists(ZKUtil.java:481)
        at org.apache.hadoop.hbase.zookeeper.ZKClusterId.readClusterIdZNode(ZKClusterId.java:65)
        at org.apache.hadoop.hbase.client.ZooKeeperRegistry.getClusterId(ZooKeeperRegistry.java:86)
        at org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation.retrieveClusterId(ConnectionManager.java:850)
        at org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation.<init>(ConnectionManager.java:635)
        ... 20 more
Caused by: java.lang.ClassNotFoundException: org.apache.htrace.Trace
        at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        ... 26 more
16/08/03 04:09:00 INFO zookeeper.ClientCnxn: Opening socket connection to server quickstart.cloudera/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)

Can you give some light here?

Body:
Be aware about the HBase version you are trying to access. Specially related with the htrace version that your hbase client is going to use. I set my pom.xml file to:

    <!-- https://mvnrepository.com/artifact/org.apache.htrace/htrace-core -->
    <dependency>
        <groupId>org.apache.htrace</groupId>
        <artifactId>htrace-core</artifactId>
        <version>3.1.0-incubating</version>
    </dependency>

and it worked rightful.


答:
One way to approach the problem would be to sort by the values and slice the first two items:

```<code>In [1]: data = {('F2', 'F1'): 0.9154929577464789,
    ...:        ('F2', 'F3'): 0.8285714285714286,
    ...:        ('F4', 'F1'): 0.8285714285714286,
    ...:        ('F4', 'F3'): 0.9130434782608695}

In [2]: from operator import itemgetter

In [3]: dict(sorted(data.items(), key=itemgetter(1))[2:])
Out[3]: {('F2', 'F1'): 0.9154929577464789, ('F4', 'F3'): 0.9130434782608695}
</code>```

One potential problem could be that, if you would have more than 2 items with the same lowest value, we'll slice only 2 of them, not all of them.

Or, we can use heapq (implements the "minimum heap" data structure) to find the n smallest items and filter them from our dictionary:

```<code>In [4]: import heapq

In [5]: smallest = set(heapq.nsmallest(2, data, key=data.get))

In [6]: {key: value for key, value in data.items() if key not in smallest}
Out[7]: {('F2', 'F1'): 0.9154929577464789, ('F4', 'F3'): 0.9130434782608695}
</code>```

Title: Drop dict entries with the lowest values

Body:
In the following dict how can I drop the two entries with the lowest values?

{('F2', 'F1'): 0.9154929577464789,
 ('F2', 'F3'): 0.8285714285714286,
 ('F4', 'F1'): 0.8285714285714286,
 ('F4', 'F3'): 0.9130434782608695}

Body:
One way to approach the problem would be to sort by the values and slice the first two items:

In [1]: data = {('F2', 'F1'): 0.9154929577464789,
    ...:        ('F2', 'F3'): 0.8285714285714286,
    ...:        ('F4', 'F1'): 0.8285714285714286,
    ...:        ('F4', 'F3'): 0.9130434782608695}

In [2]: from operator import itemgetter

In [3]: dict(sorted(data.items(), key=itemgetter(1))[2:])
Out[3]: {('F2', 'F1'): 0.9154929577464789, ('F4', 'F3'): 0.9130434782608695}

One potential problem could be that, if you would have more than 2 items with the same lowest value, we'll slice only 2 of them, not all of them.

Or, we can use heapq (implements the "minimum heap" data structure) to find the n smallest items and filter them from our dictionary:

In [4]: import heapq

In [5]: smallest = set(heapq.nsmallest(2, data, key=data.get))

In [6]: {key: value for key, value in data.items() if key not in smallest}
Out[7]: {('F2', 'F1'): 0.9154929577464789, ('F4', 'F3'): 0.9130434782608695}


答:
If you want to use inbuilt Laravel functions, then you could use the Collection::pluck function.

```<code>$businessServices = Auth::user()->business->services->pluck('id');
</code>```

Title: Binding pivot table with Laravel Form Builders using checkbox group

Body:
I'd like to bind my checkbox group Form::checkbox('services[]') with data from my pivot table but I'm having trouble doing so, I think this is because no key is being returned with service_id.

My data model is as follows:

Business

Service

Business_Service table to store many to many link.

Blade Template

@foreach($service as $service)
{!! Form::checkbox('services[]', $service->id, (in_array($service->id, $selected_services) ? true : false)) !!}
@endforeach

Controller

$service = Service::all();
$selected_services = Auth::user()->business->services()->get();

return view('signup.step2', compact('service', 'selected_services'));

When I return $selected_services I can see the following:

[{"id":2,"name":"Service
  1","image":"picture.png","created_at":"2017-03-31
  00:31:20","updated_at":"2017-03-31
  00:31:20","pivot":{"business_id":103,"service_id":2}},{"id":3,"name":"Service
  2","image":"picture.png","created_at":"2017-03-31
  00:31:23","updated_at":"2017-03-31
  00:31:23","pivot":{"business_id":103,"service_id":3}}]

I have tried changing $selected_services like this:

$selected_services = Auth::user()->business->services()->keyBy('service_id');

But this only returns one row and doesn't associate a key to the row as expected.

Body:
If you want to use inbuilt Laravel functions, then you could use the Collection::pluck function.

$businessServices = Auth::user()->business->services->pluck('id');


问:
Alamofire Extra argument 'method' in call - with custom ParameterEncoding
I'm trying to upload an array of objects in jsonSerialization and gzip. I wrote a struct as described in github.

```<code>struct JSONDocumentArrayEncoding: ParameterEncoding {
private let array: [Document]
init(array:[Document]) {
    self.array = array
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
    var urlRequest = urlRequest.urlRequest

    let data = try JSONSerialization.data(withJSONObject: array, options: [])

    if urlRequest!.value(forHTTPHeaderField: "Content-Type") == nil {
        urlRequest!.setValue("application/json", forHTTPHeaderField: "Content-Type")
    }

    urlRequest!.httpBody = data

    return urlRequest!
}
</code>```

}

Then in the request

```<code>request = customAlamofireManager.request(
        ServerURL ,
        method: .post,
        parameters: [objects],
        encoding: JSONDocumentArrayEncoding,
        headers: headers
    )
</code>```

error is "extra argument method in call". This issue was discussed in github1508 here But I cannot see a solution. Since the parameter is defined as [string:object], cannot pass in an array. Therefore even with customized struct for encoding, there's no way to pass in this body data. I'm thinking a work around maybe add a dummy key to the array and modify server api to catch the value of the dictionary. But there's no ideal.

答:
Answer my own question: Find a work around without using the default request method: </p>

```<code>    func uploadBatchDocumentsWithDocs(_ documents: [Any]) {
        let headers = NetworkManager.sharedInstance.headers
         var urlRequest = URLRequest(url: URL(string: (ServerURL + Api))!)
         urlRequest.httpMethod = "post"
         urlRequest.allHTTPHeaderFields = headers
         let jsonArrayencoding = JSONDocumentArrayEncoding(array: documents)
         let jsonAryEncodedRequest = try? jsonArrayencoding.encode(urlRequest, with: nil)

        var request: Alamofire.DataRequest? = customAlamofireManager.request(jsonAryEncodedRequest!)
        request?.validate{request, response, data in
            return .success
            }
            .responseJSON {
...
}
</code>```

<p>}
Instead of using request(url,method, parameters,encoding, headers), make the encodedRequest manually first, then using it init alamofire's datarequest. </p>

Body:
I'm trying to upload an array of objects in jsonSerialization and gzip. I wrote a struct as described in github.

struct JSONDocumentArrayEncoding: ParameterEncoding {
private let array: [Document]
init(array:[Document]) {
    self.array = array
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
    var urlRequest = urlRequest.urlRequest

    let data = try JSONSerialization.data(withJSONObject: array, options: [])

    if urlRequest!.value(forHTTPHeaderField: "Content-Type") == nil {
        urlRequest!.setValue("application/json", forHTTPHeaderField: "Content-Type")
    }

    urlRequest!.httpBody = data

    return urlRequest!
}

}

Then in the request

request = customAlamofireManager.request(
        ServerURL ,
        method: .post,
        parameters: [objects],
        encoding: JSONDocumentArrayEncoding,
        headers: headers
    )

error is "extra argument method in call". This issue was discussed in github1508 here But I cannot see a solution. Since the parameter is defined as [string:object], cannot pass in an array. Therefore even with customized struct for encoding, there's no way to pass in this body data. I'm thinking a work around maybe add a dummy key to the array and modify server api to catch the value of the dictionary. But there's no ideal.

Body:
Answer my own question: Find a work around without using the default request method:

    func uploadBatchDocumentsWithDocs(_ documents: [Any]) {
        let headers = NetworkManager.sharedInstance.headers
         var urlRequest = URLRequest(url: URL(string: (ServerURL + Api))!)
         urlRequest.httpMethod = "post"
         urlRequest.allHTTPHeaderFields = headers
         let jsonArrayencoding = JSONDocumentArrayEncoding(array: documents)
         let jsonAryEncodedRequest = try? jsonArrayencoding.encode(urlRequest, with: nil)

        var request: Alamofire.DataRequest? = customAlamofireManager.request(jsonAryEncodedRequest!)
        request?.validate{request, response, data in
            return .success
            }
            .responseJSON {
...
}

}
Instead of using request(url,method, parameters,encoding, headers), make the encodedRequest manually first, then using it init alamofire's datarequest.


问:
C Socket recv()ing weird characters
So i've stuck mainly to MAC/Linux with sockets and it all works fine so i've tried to somewhat of base my windows sockets off that maybe i am wrong for doing that and that's the whole issue, but the issue i am trying to fix right now is the console printing random characters after the actual string sent by the server.
Server.c

```<code>#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include "stdafx.h"
#include <conio.h>
#include <io.h>
#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
#pragma comment(lib,"ws2_32.lib") //Winsock Library

char message[4040];
int main()
{
    WSADATA wsa;
    SOCKET sock, newsock;
    int c;
    struct sockaddr_in server, client;
    char smesg[155];
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        return 1;
    }

    printf("Initialised.\n");

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("Could not create socket! Error: %d", WSAGetLastError());
        return 1;
    }
    //textcolor(2);
    printf("Socket Created!\n");

    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(3939);

    //bind
    if (bind(sock, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) {
        printf("Bind failed! Error Code: %d", WSAGetLastError());
    }
    puts("Binded!");
    printf("\nNow Listening...\n");
    listen(sock, 1);
    //Accept!
    c = sizeof(struct sockaddr_in);
    newsock = accept(sock, (struct sockaddr *)&client, &c);
    if (newsock == INVALID_SOCKET) {
        printf("Couldn't Accept connection!");
    }
    printf("Accepted Connection!\n");
        //char *client_ip = inet_ntoa(client.sin_addr);
        //int client_port = ntohs(client.sin_port);
        while (1) {
            printf("Command: ");
            fgets(smesg, 4040, stdin);
            send(newsock, smesg, strlen(smesg), 0);
            bzero(smesg, sizeof(smesg));
            //memset(0, smesg, 4040);
        }
    return 0;
}
</code>```

Client.c

```<code>#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include "stdafx.h"
#include <conio.h>
#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
#pragma comment(lib,"ws2_32.lib") //Winsock Library

int main(int argc, char *argv[])
{
    int reader;
    WSADATA wsa;
    SOCKET sock;
    struct sockaddr_in server;
    char message[2000];
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        return 1;
    }

    printf("Initialised.\n");

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("Could not create socket! Error: %d", WSAGetLastError());
        return 1;
    }
    //textcolor(2);
    printf("Socket Created!\n");

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    server.sin_port = htons(3939);

    //Connect
    if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
        puts("Connect Error");
        return 1;
    }
    puts("Connected\n");
    while (1) {
        //memset(0, message, 4040);
        reader = recv(sock, message, 2000, 0);
        fprintf(stdout, "%s", message);
        bzero(message, 2000);
    }
    return 0;
}
</code>```

I type "Hello" into the server console and the client console recv()s/Prints
Due to the fact i can't C&P from console ill just have a picture of it instead
Console Output

Update to the question the null terminator as posted by many what i did to fix it was switch

```<code>        printf("Command: ");
        fgets(smesg, 155, stdin);
</code>```

In server.c to

```<code>        bzero(smesg, sizeof(smesg));
        printf("Command: ");
        fgets(smesg, 155, stdin);
        strcat(smesg, "\0");
</code>```

答:
Usual problem. You are ignoring the value returned by recv():

```<code>reader = recv(sock, message, 2000, 0);
fprintf(stdout, "%s", message)
</code>```

should be

```<code>reader = recv(sock, message, 2000, 0);
if (reader == -1)  // error
{
    perror("recv)"); // at least
    break; // out of the read loop and close the socket
}
else if (reader == 0) // EOS: peer has closed the connection
    break;
else
    fprintf(stdout, "%.*s", reader, message);
</code>```

Title: C Socket recv()ing weird characters

Body:
So i've stuck mainly to MAC/Linux with sockets and it all works fine so i've tried to somewhat of base my windows sockets off that maybe i am wrong for doing that and that's the whole issue, but the issue i am trying to fix right now is the console printing random characters after the actual string sent by the server.
Server.c

#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include "stdafx.h"
#include <conio.h>
#include <io.h>
#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
#pragma comment(lib,"ws2_32.lib") //Winsock Library

char message[4040];
int main()
{
    WSADATA wsa;
    SOCKET sock, newsock;
    int c;
    struct sockaddr_in server, client;
    char smesg[155];
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        return 1;
    }

    printf("Initialised.\n");

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("Could not create socket! Error: %d", WSAGetLastError());
        return 1;
    }
    //textcolor(2);
    printf("Socket Created!\n");

    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(3939);

    //bind
    if (bind(sock, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) {
        printf("Bind failed! Error Code: %d", WSAGetLastError());
    }
    puts("Binded!");
    printf("\nNow Listening...\n");
    listen(sock, 1);
    //Accept!
    c = sizeof(struct sockaddr_in);
    newsock = accept(sock, (struct sockaddr *)&client, &c);
    if (newsock == INVALID_SOCKET) {
        printf("Couldn't Accept connection!");
    }
    printf("Accepted Connection!\n");
        //char *client_ip = inet_ntoa(client.sin_addr);
        //int client_port = ntohs(client.sin_port);
        while (1) {
            printf("Command: ");
            fgets(smesg, 4040, stdin);
            send(newsock, smesg, strlen(smesg), 0);
            bzero(smesg, sizeof(smesg));
            //memset(0, smesg, 4040);
        }
    return 0;
}

Client.c

#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include "stdafx.h"
#include <conio.h>
#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
#pragma comment(lib,"ws2_32.lib") //Winsock Library

int main(int argc, char *argv[])
{
    int reader;
    WSADATA wsa;
    SOCKET sock;
    struct sockaddr_in server;
    char message[2000];
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        return 1;
    }

    printf("Initialised.\n");

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("Could not create socket! Error: %d", WSAGetLastError());
        return 1;
    }
    //textcolor(2);
    printf("Socket Created!\n");

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    server.sin_port = htons(3939);

    //Connect
    if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
        puts("Connect Error");
        return 1;
    }
    puts("Connected\n");
    while (1) {
        //memset(0, message, 4040);
        reader = recv(sock, message, 2000, 0);
        fprintf(stdout, "%s", message);
        bzero(message, 2000);
    }
    return 0;
}

I type "Hello" into the server console and the client console recv()s/Prints
Due to the fact i can't C&P from console ill just have a picture of it instead
Console Output

Update to the question the null terminator as posted by many what i did to fix it was switch

        printf("Command: ");
        fgets(smesg, 155, stdin);

In server.c to

        bzero(smesg, sizeof(smesg));
        printf("Command: ");
        fgets(smesg, 155, stdin);
        strcat(smesg, "\0");

Body:
Usual problem. You are ignoring the value returned by recv():

reader = recv(sock, message, 2000, 0);
fprintf(stdout, "%s", message)

should be

reader = recv(sock, message, 2000, 0);
if (reader == -1)  // error
{
    perror("recv)"); // at least
    break; // out of the read loop and close the socket
}
else if (reader == 0) // EOS: peer has closed the connection
    break;
else
    fprintf(stdout, "%.*s", reader, message);


问:
jQuery/Javascript: variable NOT updating after GET call
I'm trying to read from a text file and put the information inside it into an Array. However, it seems I am doing something wrong.

```<code>var Level = function(ctx) {
    this.ctx = ctx;
    this.lvlWidth = 0;
    this.lvlHeight = 0;

    this.map = [];

    this.loadLevel = function(){
    var start = 0;
    var end = 0;
    this.lvlHeight = 25;
    this.lvlWidth = 21;

    $.get("1.txt", function(data){
        start = data.indexOf("0");
        end = data.lastIndexOf("#");
        this.map = data.slice(start, end - 2).split(" ");
    }, "text");

    console.log(this.map);
   };
}; // end Level
</code>```

On console, it says that my variable this.map is an EMPTY ARRAY. It doesn't modify itself, and I don't know why. I checked other answers and people said that this problem happens if you don't declare your variable (in my case map) outside the function, but you can clearly see that I did. Ironically enough, this.lvlWidth and this.lvlHeight DO change to 21 and 25 respectively. Can anyone tell me why does map doesn't update?

Here is the info of 1.txt (which is on the same folder as this file):

```<code># startleveldata
0 0 0 0 0 0 0 0 0 113 21 113 0 0 0 0 0 0 0 0 0
0 107 100 100 100 100 100 100 100 106 0 105 100 100 100 100 100 100 100 108 0
0 101 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 101 0
0 101 3 120 2 113 2 111 100 108 2 107 100 112 2 113 2 120 3 101 0
0 101 2 2 2 101 2 2 2 101 2 101 2 2 2 101 2 2 2 101 0
0 101 2 111 100 106 2 113 2 110 2 110 2 113 2 105 100 112 2 101 0
0 101 2 2 2 2 2 101 2 2 2 2 2 101 2 2 2 2 2 101 0
0 101 2 120 2 111 100 130 100 112 2 111 100 130 100 112 2 120 2 101 0
0 101 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 101 0
0 105 100 108 2 113 2 111 100 100 100 100 100 112 2 113 2 107 100 106 0
0 0 0 101 2 101 2 2 0 0 10 0 0 2 2 101 2 101 0 0 0
111 100 100 106 2 105 112 2 107 112 1 111 108 2 111 106 2 105 100 100 112
20 0 0 0 2 0 0 2 101 11 12 13 101 2 0 0 2 0 0 0 20
111 133 100 112 2 111 112 2 105 100 100 100 106 2 111 112 2 111 100 133 112
0 101 2 2 2 0 0 2 0 0 0 0 0 2 0 0 2 2 2 101 0
0 101 2 120 2 107 112 2 111 100 100 100 112 2 111 108 2 120 2 101 0
0 101 2 2 2 101 2 2 0 0 4 0 0 2 2 101 2 2 2 101 0
0 105 133 112 2 110 2 111 100 100 133 100 100 112 2 110 2 111 133 106 0
0 0 101 2 2 2 2 2 2 2 101 2 2 2 2 2 2 2 101 0 0
0 0 101 2 111 112 2 111 108 2 101 2 107 112 2 111 112 2 101 0 0
107 100 106 2 2 2 2 2 101 2 101 2 101 2 2 2 2 2 105 100 108
101 2 2 2 111 100 112 2 110 2 110 2 110 2 111 100 112 2 2 2 101
101 3 120 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 120 3 101
101 2 2 2 107 100 100 100 100 108 0 107 100 100 100 100 108 2 2 2 101
105 100 100 100 106 0 0 0 0 110 21 110 0 0 0 0 105 100 100 100 106
# endleveldata
</code>```

EDIT: I made it work guys! Problem is I needed to call a callback function that would call this function again. Following user @ACOMIT001 advice, I used the .then() function after my $.get(). I extracted the $get function, put it on my main program, and on the .then() function I called loadLevel(), and it works. I can't really explain why but this works for me now. Thanks everyone for your help/

答:
I think it's because the scope of your this is changing.
try this:

```<code>var that = this;
....
 $.get("1.txt", function(data){
    start = data.indexOf("0");
    end = data.lastIndexOf("#");
    that.map = data.slice(start, end - 2).split(" ");
}, "text");

console.log(that.map);
</code>```

http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/

Body:
I'm trying to read from a text file and put the information inside it into an Array. However, it seems I am doing something wrong.

var Level = function(ctx) {
    this.ctx = ctx;
    this.lvlWidth = 0;
    this.lvlHeight = 0;

    this.map = [];

    this.loadLevel = function(){
    var start = 0;
    var end = 0;
    this.lvlHeight = 25;
    this.lvlWidth = 21;

    $.get("1.txt", function(data){
        start = data.indexOf("0");
        end = data.lastIndexOf("#");
        this.map = data.slice(start, end - 2).split(" ");
    }, "text");

    console.log(this.map);
   };
}; // end Level

On console, it says that my variable this.map is an EMPTY ARRAY. It doesn't modify itself, and I don't know why. I checked other answers and people said that this problem happens if you don't declare your variable (in my case map) outside the function, but you can clearly see that I did. Ironically enough, this.lvlWidth and this.lvlHeight DO change to 21 and 25 respectively. Can anyone tell me why does map doesn't update?

Here is the info of 1.txt (which is on the same folder as this file):

# startleveldata
0 0 0 0 0 0 0 0 0 113 21 113 0 0 0 0 0 0 0 0 0
0 107 100 100 100 100 100 100 100 106 0 105 100 100 100 100 100 100 100 108 0
0 101 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 101 0
0 101 3 120 2 113 2 111 100 108 2 107 100 112 2 113 2 120 3 101 0
0 101 2 2 2 101 2 2 2 101 2 101 2 2 2 101 2 2 2 101 0
0 101 2 111 100 106 2 113 2 110 2 110 2 113 2 105 100 112 2 101 0
0 101 2 2 2 2 2 101 2 2 2 2 2 101 2 2 2 2 2 101 0
0 101 2 120 2 111 100 130 100 112 2 111 100 130 100 112 2 120 2 101 0
0 101 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 101 0
0 105 100 108 2 113 2 111 100 100 100 100 100 112 2 113 2 107 100 106 0
0 0 0 101 2 101 2 2 0 0 10 0 0 2 2 101 2 101 0 0 0
111 100 100 106 2 105 112 2 107 112 1 111 108 2 111 106 2 105 100 100 112
20 0 0 0 2 0 0 2 101 11 12 13 101 2 0 0 2 0 0 0 20
111 133 100 112 2 111 112 2 105 100 100 100 106 2 111 112 2 111 100 133 112
0 101 2 2 2 0 0 2 0 0 0 0 0 2 0 0 2 2 2 101 0
0 101 2 120 2 107 112 2 111 100 100 100 112 2 111 108 2 120 2 101 0
0 101 2 2 2 101 2 2 0 0 4 0 0 2 2 101 2 2 2 101 0
0 105 133 112 2 110 2 111 100 100 133 100 100 112 2 110 2 111 133 106 0
0 0 101 2 2 2 2 2 2 2 101 2 2 2 2 2 2 2 101 0 0
0 0 101 2 111 112 2 111 108 2 101 2 107 112 2 111 112 2 101 0 0
107 100 106 2 2 2 2 2 101 2 101 2 101 2 2 2 2 2 105 100 108
101 2 2 2 111 100 112 2 110 2 110 2 110 2 111 100 112 2 2 2 101
101 3 120 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 120 3 101
101 2 2 2 107 100 100 100 100 108 0 107 100 100 100 100 108 2 2 2 101
105 100 100 100 106 0 0 0 0 110 21 110 0 0 0 0 105 100 100 100 106
# endleveldata

EDIT: I made it work guys! Problem is I needed to call a callback function that would call this function again. Following user @ACOMIT001 advice, I used the .then() function after my $.get(). I extracted the $get function, put it on my main program, and on the .then() function I called loadLevel(), and it works. I can't really explain why but this works for me now. Thanks everyone for your help/

Body:
I think it's because the scope of your this is changing.
try this:

var that = this;
....
 $.get("1.txt", function(data){
    start = data.indexOf("0");
    end = data.lastIndexOf("#");
    that.map = data.slice(start, end - 2).split(" ");
}, "text");

console.log(that.map);

http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/