问:
Nested NSArray into UITableView
i have looked everywhere for this, but i am unable to find the exact answer... all have slight variations.

Anyway, i call a json page that returns the following (from the NSLog):

```<code>{
    messages =         {
        1 =             {
            Body = "This is the body of message 1";
            Title = "Message 1";
        };
        2 =             {
            Body = "This is the body of message 2";
            Title = "Message 2";
        };
    };
}
</code>```

I then save the data into a NSDictionary (called messageArray). (the array is a NSMutableArray)

then i do:

```<code>// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    //put rowsarray into dictionary
    NSDictionary *dictionary = [messageArray objectAtIndex:indexPath.section];

    //new dictionary into array
    NSArray *messages = [dictionary objectForKey:@"messages"];

    NSLog(@"the message array = %@",messages );

    //this fails
    cell.textLabel.text = [messages objectAtIndex:indexPath.row];

return cell;
</code>```

the returned NSLog (so i am assuming my json array is working correctly):

```<code>the message array = {
1 =     {
    Body = "This is the body of message 1";
    Title = "Message 1";
};
2 =     {
    Body = "This is the body of message 2";
    Title = "Message 2";
};
</code>```

}

I understand that i am not labelling the textlabels.text correctly, but i am not sure how to go about looping through the "messages" array, to display all the "Title" values from the array, to display on my UITableView list.

i am certain i am missing something so simple... but it has eluded me until now. Any links welcome... i will keep searching myself....

答:
```<code>NSArray *messages = [dictionary objectForKey:@"messages"];
</code>```

what is the need of this line if you get your dictionary here

```<code>NSDictionary *dictionary = [messageArray objectAtIndex:indexPath.section];
</code>```

now, you know what are the keys for attaching data to dictionary.

then simply

```<code>cell.textLabel.text = [dictionary valueForKey:@"Title"];
cell.detailTextLabel.text= [dictionary valueForKey:@"Body"];
</code>```

Title: Nested NSArray into UITableView

Body:
i have looked everywhere for this, but i am unable to find the exact answer... all have slight variations.

Anyway, i call a json page that returns the following (from the NSLog):

{
    messages =         {
        1 =             {
            Body = "This is the body of message 1";
            Title = "Message 1";
        };
        2 =             {
            Body = "This is the body of message 2";
            Title = "Message 2";
        };
    };
}

I then save the data into a NSDictionary (called messageArray). (the array is a NSMutableArray)

then i do:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    //put rowsarray into dictionary
    NSDictionary *dictionary = [messageArray objectAtIndex:indexPath.section];

    //new dictionary into array
    NSArray *messages = [dictionary objectForKey:@"messages"];

    NSLog(@"the message array = %@",messages );

    //this fails
    cell.textLabel.text = [messages objectAtIndex:indexPath.row];

return cell;

the returned NSLog (so i am assuming my json array is working correctly):

the message array = {
1 =     {
    Body = "This is the body of message 1";
    Title = "Message 1";
};
2 =     {
    Body = "This is the body of message 2";
    Title = "Message 2";
};

}

I understand that i am not labelling the textlabels.text correctly, but i am not sure how to go about looping through the "messages" array, to display all the "Title" values from the array, to display on my UITableView list.

i am certain i am missing something so simple... but it has eluded me until now. Any links welcome... i will keep searching myself....

Body:
NSArray *messages = [dictionary objectForKey:@"messages"];

what is the need of this line if you get your dictionary here

NSDictionary *dictionary = [messageArray objectAtIndex:indexPath.section];

now, you know what are the keys for attaching data to dictionary.

then simply

cell.textLabel.text = [dictionary valueForKey:@"Title"];
cell.detailTextLabel.text= [dictionary valueForKey:@"Body"];


来源: stackexchange

问:
Ignite Transactional From DataStream Receiver not supported?
I am using igniteDataStreamer and would like to know if it is possible to use transactions from closures. </p>

<p>Unfortunately, when running from different IgniteDataStreamer threads for the same record to update in the cache(receive() method in StreamReceiver), Ignite does not throw any TransactionOptimisticException even though CacheConfiguration atomicityMode is TRANSACTIONAL. </p>

```<code>try (Transaction t = ignite.transactions().txStart(TransactionConcurrency.OPTIMISTIC, TransactionIsolation.SERIALIZABLE)) {
            try {
                cache.putAll(update);
                t.commit();
            catch (TransactionOptimisticException toe) {
                LOG.error("TransactionOptimisticException Could not put all the profiles",toe);
            }
        }
</code>```

答: Data streamer is not transactional. To execute updates in a single transaction, they must be initiated on the same node and by the same thread. For more details and examples read here: https://apacheignite.readme.io/docs/transactions</p>

ContentLicense: CC BY-SA 3.0

Body:
I am using igniteDataStreamer and would like to know if it is possible to use transactions from closures.

Unfortunately, when running from different IgniteDataStreamer threads for the same record to update in the cache(receive() method in StreamReceiver), Ignite does not throw any TransactionOptimisticException even though CacheConfiguration atomicityMode is TRANSACTIONAL.

try (Transaction t = ignite.transactions().txStart(TransactionConcurrency.OPTIMISTIC, TransactionIsolation.SERIALIZABLE)) {
            try {
                cache.putAll(update);
                t.commit();
            catch (TransactionOptimisticException toe) {
                LOG.error("TransactionOptimisticException Could not put all the profiles",toe);
            }
        }


问:
If I press one key and then another too fast, my pygame sprite stops moving
I'm new to pygame so my code is a bit messy but I hope you can help me. When I make a sprite move it works fine, but if I switch keys really fast, or if I press the jump button and let go, my sprite stops moving.</p>

```<code>import shelve
import sys, pygame, pygame.mixer
import time
from pygame.locals import *
import random
pygame.init()
shelfFile = shelve.open('save_game')

#screen
sise = width, hight = 700, 600
red = 30,30,30
screen = pygame.display.set_mode(sise)

pygame.display.set_caption('Thing')

#varuables
background = pygame.image.load('background.png')
player = pygame.image.load('you.png')
enemy1 = pygame.image.load('enemy1.png')
clock = pygame.time.Clock()
px = shelfFile['px']
py = shelfFile['py']
health = shelfFile['health']
x2 = 0

x = 0
y = 0
u = 0
d = 0
t = 0
r = 0

ex = 0
ey = 0

cutseane = shelfFile ['cutseane']
black = 255,255,255

Punch = False

color = 255,0,0
radius = 5

room = shelfFile['room']

ehealth = shelfFile['ehealth']

while True:
    pygame.event.get()
    if jump == 1:
        y = -20
    if py <= 200:
        jump = 2
    if jump == 2:
        y = +20
    if py >= 480:
        py = 480

                #The Wall
    if px <= 0:
        px = 0
    if px >= 630:
        px = 630
    pygame.display.flip()
    screen.blit(background,(1,1))
    screen.blit(player,(px,py))
    #if ehealth >= 1:
        #screen.blit(enemy1,(ex,ey))
    #else:
        #ex = 0
        #ey = 0
                px = px + x
    py = py + y
    clock.tick(30)
    for event in pygame.event.get():
        keys = pygame.key.get_pressed()

        if event.type == KEYDOWN and event.key == pygame.K_ESCAPE:
            shelfFile['px'] = px
            shelfFile['py'] = py
            shelfFile['health'] = health
            shelfFile['ehealth'] = ehealth
            shelfFile['cutseane'] = cutseane
            shelfFile['room'] = room
            shelfFile.close()
            pygame.quit(); sys.exit();

                    #Player Movement
        elif event.type == pygame.KEYDOWN:
            if keys [pygame.K_0]:
                health -= 1
                text = 1
                shelfFile['text'] = text
            elif event.key == pygame.K_RIGHT:
                x = -15
            elif event.key == pygame.K_LEFT:
                x = +15
            elif event.key == pygame.K_UP:
                y = +15
            elif event.key == pygame.K_DOWN:
                y = -15
        elif event.type == KEYUP:
            if event.key == pygame.K_LEFT and x > 0:
                x = 0
            elif event.key == pygame.K_RIGHT and x < 0:
                x = 0
            elif event.key == pygame.K_UP and x > 0:
                y = 0
            elif event.key == pygame.K_DOWN and x < 0:
                y = 0
</code>```

答:
I think the problem is that in some places, you wrote y = +20 instead of y += 20. If you want y to increase by 20 units, do y += 20, if you want y to be set to the value 20, do y = 20 (does the same thing as y = +20). I don't know what you are trying to do because I don't have your png files and I can't run the program to see what happens. Also, if it even is an unintentional mistake, you did the same thing for negatives and in other parts of the code.

This isn't really a mistake, it will work if not corrected but you also spelled some things wrong (if it was intentional, ignore this.)

sise should be size,
hight should be height,
cutseane should be cutscene...

There are other mistakes. If all of this works and they are not just typos, then you might be using some version of python that I am not aware of.

Body:
I'm new to pygame so my code is a bit messy but I hope you can help me. When I make a sprite move it works fine, but if I switch keys really fast, or if I press the jump button and let go, my sprite stops moving.

import shelve
import sys, pygame, pygame.mixer
import time
from pygame.locals import *
import random
pygame.init()
shelfFile = shelve.open('save_game')

#screen
sise = width, hight = 700, 600
red = 30,30,30
screen = pygame.display.set_mode(sise)

pygame.display.set_caption('Thing')

#varuables
background = pygame.image.load('background.png')
player = pygame.image.load('you.png')
enemy1 = pygame.image.load('enemy1.png')
clock = pygame.time.Clock()
px = shelfFile['px']
py = shelfFile['py']
health = shelfFile['health']
x2 = 0

x = 0
y = 0
u = 0
d = 0
t = 0
r = 0

ex = 0
ey = 0

cutseane = shelfFile ['cutseane']
black = 255,255,255

Punch = False

color = 255,0,0
radius = 5

room = shelfFile['room']

ehealth = shelfFile['ehealth']

while True:
    pygame.event.get()
    if jump == 1:
        y = -20
    if py <= 200:
        jump = 2
    if jump == 2:
        y = +20
    if py >= 480:
        py = 480

                #The Wall
    if px <= 0:
        px = 0
    if px >= 630:
        px = 630
    pygame.display.flip()
    screen.blit(background,(1,1))
    screen.blit(player,(px,py))
    #if ehealth >= 1:
        #screen.blit(enemy1,(ex,ey))
    #else:
        #ex = 0
        #ey = 0
                px = px + x
    py = py + y
    clock.tick(30)
    for event in pygame.event.get():
        keys = pygame.key.get_pressed()

        if event.type == KEYDOWN and event.key == pygame.K_ESCAPE:
            shelfFile['px'] = px
            shelfFile['py'] = py
            shelfFile['health'] = health
            shelfFile['ehealth'] = ehealth
            shelfFile['cutseane'] = cutseane
            shelfFile['room'] = room
            shelfFile.close()
            pygame.quit(); sys.exit();

                    #Player Movement
        elif event.type == pygame.KEYDOWN:
            if keys [pygame.K_0]:
                health -= 1
                text = 1
                shelfFile['text'] = text
            elif event.key == pygame.K_RIGHT:
                x = -15
            elif event.key == pygame.K_LEFT:
                x = +15
            elif event.key == pygame.K_UP:
                y = +15
            elif event.key == pygame.K_DOWN:
                y = -15
        elif event.type == KEYUP:
            if event.key == pygame.K_LEFT and x > 0:
                x = 0
            elif event.key == pygame.K_RIGHT and x < 0:
                x = 0
            elif event.key == pygame.K_UP and x > 0:
                y = 0
            elif event.key == pygame.K_DOWN and x < 0:
                y = 0


问:
Deploy with Laravel?
First Laravel Project.

I want to deploy my Laravel project to a Hoster. I have FTP access to it, but I don't want to tinker with filezilla everytime I change something. Plus my Development and 'Finished' projects has some differences (for example Debugbar and different DataBase authentication. What's the best method to deploy a Laravel Project?

答:
It can be done in many ways. So I am going to give a headstart.

Warning: This might not be everything you need to know. I recommend you to learn more about, deployment,ssh, version controlling, apache vhosts, etc , this is just a headstart

Here is how I do it on my Ubuntu server with apache, php and mysql.

I use Git for version controlling and bitbucket and github for managing repositories.

1 - make my project a git repository.

2 - push the repo to bitbucket.

3 - connect to the remote server through ssh and setup the apache vhosts, databases etc.

create a vhost /etc/apache/sites-available/somesite.com.conf file

add the entry to /etc/hosts file

4 - pull the repo from bitbucket to remote server, create and bring the required changes to the production .env file

5 - do a composer install

6 - run php artisan key:generate and php artisan migrate

7 - turn on the site

run sudo a2ensite somesite.com.conf

run sudo service apache2 reload

now the site its up and ready to go.

Title: Deploy with Laravel?


问:
String doesn't appear in class when using constructor
I have made monopoly game in C# for a month already and i finished everything, i have only one problem from start. There are 2 forms. First one is where you select how many players are playing and typing their names. Second is the game, and i have tested, it passes player names from form1 to form2, but it seems like it doesn't apply it when i use constructor for class Player.
It looks like this
Form 2:

```<code>    public static string PlayerName1;
    public static string PlayerName2;
    public static string PlayerName3;
    public static string PlayerName4;
    public static Player Player1 = new Player(0, PlayerName1, 1, 10000);
    public static Player Player2 = new Player(1, PlayerName2, 1, 10000);
    public static Player Player3 = new Player(2, PlayerName3, 1, 10000);
    public static Player Player4 = new Player(3, PlayerName4, 1, 10000);
</code>```

As i said, PlayerName (all of them) works perfectly in form2 i tested it in label and it shows it right, so it isn't problem passing it from form1

Now the Player class code:

```<code>    public int ID;
    public string Name;
    public int Field;
    public int Money;
    public Player(int id, string name, int field, int money)
    {
        ID = id;
        Name = name;
        Field = field;
        Money = money;
    }
</code>```

So now this is where i use those values in form2:

```<code> private void update()
    {
        switch (turn)
        {
            case 0: PlayerName.Text = Player1.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;

            case 1: PlayerName.Text = Player2.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;

            case 2: PlayerName.Text = Player3.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;

            case 3: PlayerName.Text = Player4.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;
        }
    }
</code>```

PlayerName and Money in form2 are labels, Money label works perfectly with every "update" but PlayerName label is always empty. It is visible and it has text "Name" in it when i open Form2 but after first "update" it is empty and stays like that until i restart program. I also use Player.PlayerName in message boxes when paying rent from one player to another and it also doesn't work there... Hopefully someone can help me, i have to finish this by tomorrow, it's not like i'll get lesser grade for this but i want to everything be perfectly :)

答:
As i said, PlayerName (all of them) works perfectly in form2

They surely do, when the form is created and its method invoked.

```<code>public static Player Player1 = new Player(0, PlayerName1, 1, 10000);
</code>```

This static initialization unfortunately takes place at the very beginning of the form's lifetime. At this moment, the PlayerName1 is empty yet. You possibly change it somewhere later but too late, the change isn't magically copied to the player object by itself.

The workaround is simple, make sure you updat the name property when the name is known.

```<code>// somewhere you somehow learn the name
PlayerName1 = ...

// update accordingly
Player1.Name = PlayerName1;
</code>```

Body:
I have made monopoly game in C# for a month already and i finished everything, i have only one problem from start. There are 2 forms. First one is where you select how many players are playing and typing their names. Second is the game, and i have tested, it passes player names from form1 to form2, but it seems like it doesn't apply it when i use constructor for class Player.
It looks like this
Form 2:

    public static string PlayerName1;
    public static string PlayerName2;
    public static string PlayerName3;
    public static string PlayerName4;
    public static Player Player1 = new Player(0, PlayerName1, 1, 10000);
    public static Player Player2 = new Player(1, PlayerName2, 1, 10000);
    public static Player Player3 = new Player(2, PlayerName3, 1, 10000);
    public static Player Player4 = new Player(3, PlayerName4, 1, 10000);

As i said, PlayerName (all of them) works perfectly in form2 i tested it in label and it shows it right, so it isn't problem passing it from form1

Now the Player class code:

    public int ID;
    public string Name;
    public int Field;
    public int Money;
    public Player(int id, string name, int field, int money)
    {
        ID = id;
        Name = name;
        Field = field;
        Money = money;
    }

So now this is where i use those values in form2:

 private void update()
    {
        switch (turn)
        {
            case 0: PlayerName.Text = Player1.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;

            case 1: PlayerName.Text = Player2.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;

            case 2: PlayerName.Text = Player3.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;

            case 3: PlayerName.Text = Player4.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;
        }
    }

PlayerName and Money in form2 are labels, Money label works perfectly with every "update" but PlayerName label is always empty. It is visible and it has text "Name" in it when i open Form2 but after first "update" it is empty and stays like that until i restart program. I also use Player.PlayerName in message boxes when paying rent from one player to another and it also doesn't work there... Hopefully someone can help me, i have to finish this by tomorrow, it's not like i'll get lesser grade for this but i want to everything be perfectly :)

Body:
As i said, PlayerName (all of them) works perfectly in form2

They surely do, when the form is created and its method invoked.

public static Player Player1 = new Player(0, PlayerName1, 1, 10000);

This static initialization unfortunately takes place at the very beginning of the form's lifetime. At this moment, the PlayerName1 is empty yet. You possibly change it somewhere later but too late, the change isn't magically copied to the player object by itself.

The workaround is simple, make sure you updat the name property when the name is known.

// somewhere you somehow learn the name
PlayerName1 = ...

// update accordingly
Player1.Name = PlayerName1;


问:
How do I access innerText of a specific XMLnode
Hi
I have the following XML fragment:

```<code>  <Customer AccountNumber="4">
    <CustomerInfo>
      <firstName>Andrew</firstName>
      <lastName>Walker</lastName>
    </CustomerInfo>
    <Transactions>
      <AccountBalance>595848584.4</AccountBalance>
    </Transactions>
  </Customer>
</code>```

from a bigger XML file. I want to access the <firsName> in C#.
Currently I am doing the following:

```<code>    foreach (XmlNode customer in root)
    {
        i++;
        if(_AccNumber== Convert.ToInt32(customer.Attributes[0].Value))
        {
            searchNode = CustNodes[(i - 1)];
            string _firstName = searchNode.FirstChild.FirstChild.InnerText;

        }
    }
</code>```

When I view searchNode in the debugger I can see in the results view element [0] which has a localName CustomerInfo as you expect. So in the debugger first name has the following path:

```<code>searchNode -> [0].[0].[0].value
</code>```

if that makes sense?

Is there any better way of doing this? (without LINQ)?
Apologies, if something isn't clear....its 2:30AM! Let me know and I'll explain myself better.
Thanks!!

答:
I think xpath is so much complex to understand , so better to use the GetElementsByTagName function</p>

```<code>XmlDocument doc = new XmlDocument();
        doc.Load(@"sample.xml");
        XmlNodeList firstNameNodes =  doc.GetElementsByTagName("firstName");
        foreach (XmlNode node in firstNameNodes)
        {
            string firstName =  node.InnerText;
        }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hi
I have the following XML fragment:

  <Customer AccountNumber="4">
    <CustomerInfo>
      <firstName>Andrew</firstName>
      <lastName>Walker</lastName>
    </CustomerInfo>
    <Transactions>
      <AccountBalance>595848584.4</AccountBalance>
    </Transactions>
  </Customer>

from a bigger XML file. I want to access the <firsName> in C#.
Currently I am doing the following:

    foreach (XmlNode customer in root)
    {
        i++;
        if(_AccNumber== Convert.ToInt32(customer.Attributes[0].Value))
        {
            searchNode = CustNodes[(i - 1)];
            string _firstName = searchNode.FirstChild.FirstChild.InnerText;

        }
    }

When I view searchNode in the debugger I can see in the results view element [0] which has a localName CustomerInfo as you expect. So in the debugger first name has the following path:

searchNode -> [0].[0].[0].value

if that makes sense?

Is there any better way of doing this? (without LINQ)?
Apologies, if something isn't clear....its 2:30AM! Let me know and I'll explain myself better.
Thanks!!

Body:
I think xpath is so much complex to understand , so better to use the GetElementsByTagName function

XmlDocument doc = new XmlDocument();
        doc.Load(@"sample.xml");
        XmlNodeList firstNameNodes =  doc.GetElementsByTagName("firstName");
        foreach (XmlNode node in firstNameNodes)
        {
            string firstName =  node.InnerText;
        }


问:
Plotting multiple images side by side using matplotlib
l have 21 images stored in my folder path="home/images" that l want to visualize in one figure.

how can l do that such that for each plot has a title  ?

Thank you

答:
I'd start by using glob:

```<code>from PIL import Image
import glob
image_list = []
for filename in glob.glob('home/images*.gif'): #assuming gif
    im=Image.open(filename)
    image_list.append(im)
</code>```

Then plot them following some example like this
See more examples here

Body:
I'd start by using glob:

from PIL import Image
import glob
image_list = []
for filename in glob.glob('home/images*.gif'): #assuming gif
    im=Image.open(filename)
    image_list.append(im)

Then plot them following some example like this
See more examples here


问:
How to create a TextArea in Android
How do I display a TextArea for my android project? From xml, the only choice is TextField, multi lined. But thats editable. I need a TextArea which is only for displaying messages/text can't be edit/input by the user.</p>

答:
Defining an Android Mulitline EditText Field is done via the inputType=”textMultiline”. Unfortunately the text looks strangely aligned. To solve that also use the gravity=”left|top” attribute.

```<code><EditText
   android:id="@+id/editText1"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:ems="10"
   android:gravity="left|top"
   android:inputType="textMultiLine" >

   <requestFocus />
</code>```

check this vogella blog

Title: How to create a TextArea in Android

Body:
Defining an Android Mulitline EditText Field is done via the inputType=”textMultiline”. Unfortunately the text looks strangely aligned. To solve that also use the gravity=”left|top” attribute.

<EditText
   android:id="@+id/editText1"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:ems="10"
   android:gravity="left|top"
   android:inputType="textMultiLine" >

   <requestFocus />

check this vogella blog


问:
Python http.server not print log
I am using Git Bash to run a simple local server with $ python3 -m http.server 8000

Git Bash never prints that it is running and does not get a log of the requests. I can access http://localhost:8000/ so the command is working. How do I get git bash to print the log?

答:
This appears to be a general issue with line-buffering under mingw. You should be able to work around this by avoiding buffering the outputs, which in your case is possible through

```<code>$ python -u -m http.server 8080
</code>```

This works as expected on

```<code>$ uname -a
MINGW64_NT-6.3 - 2.5.0(0.295/5/3) 2016-03-31 18:47 x86_64 Msys
</code>```

Title: Python http.server not print log

Body:
This appears to be a general issue with line-buffering under mingw. You should be able to work around this by avoiding buffering the outputs, which in your case is possible through

$ python -u -m http.server 8080

This works as expected on

$ uname -a
MINGW64_NT-6.3 - 2.5.0(0.295/5/3) 2016-03-31 18:47 x86_64 Msys


问:
Should Context be injected with Dagger?
I know it is possible to inject Context with Dagger. We can see examples here and here.

On the other end, there are numerous posts about not placing context on a static variable to avoid leaks.
Android Studio (lint) also warms about this:

Do not place Android context classes in static fields; this is a
  memory leak (and also breaks Instant Run)

I understand that by injecting a Context with Dagger, we are placing it on a singleton class, so context is somehow static. Doesn't this go against the lint warning?

Injecting the context seems to create cleaner code, since you don't have to pass it to several classes (that don't need it) so that they can further pass it to other classes that need it for some reason (getting a resource for instance).

I am just concerned that this may cause some undesired leak or breaks lint in some way.

答: You should never store/reference activity context (an activity is a context) for longer than the lifetime of the activity otherwise, as you rightly say, your app will leak memory. Application context has the lifetime of the app on the other hand so is safe to store/reference in singletons. Access application context via context.getApplicationContext().</p>

Title: Should Context be injected with Dagger?


问:
Protecting shared memory segment between kernel and user space
I have shared memory segment created in kernel using mmap. I need to access this mapped memory from both kernel and user space. What mechanism should I use to protect the memory from concurrent access ?
I want to have something like:

Kernel module:

```<code>#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/debugfs.h>
#include <linux/slab.h>
#include <linux/mm.h>

#ifndef VM_RESERVED
# define  VM_RESERVED   (VM_DONTEXPAND | VM_DONTDUMP)
#endif

struct dentry  *file;

struct mmap_info
{
    char *data;
    int reference;
};

void mmap_open(struct vm_area_struct *vma)
{
    struct mmap_info *info = (struct mmap_info *)vma->vm_private_data;
    info->reference++;
}

void mmap_close(struct vm_area_struct *vma)
{
    struct mmap_info *info = (struct mmap_info *)vma->vm_private_data;
    info->reference--;
}

static int mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
    struct page *page;
    struct mmap_info *info;

    info = (struct mmap_info *)vma->vm_private_data;
    if (!info->data)
    {
        printk("No data\n");
        return 0;
    }
    page = virt_to_page(info->data);
    get_page(page);
    vmf->page = page;
    return 0;
}

struct vm_operations_struct mmap_vm_ops =
{
    .open =     mmap_open,
    .close =    mmap_close,
    .fault =    mmap_fault,
};

int op_mmap(struct file *filp, struct vm_area_struct *vma)
{
    vma->vm_ops = &mmap_vm_ops;
    vma->vm_flags |= VM_RESERVED;
    vma->vm_private_data = filp->private_data;
    mmap_open(vma);
    return 0;
}

int mmapfop_close(struct inode *inode, struct file *filp)
{
    struct mmap_info *info = filp->private_data;
    free_page((unsigned long)info->data);
    kfree(info);
    filp->private_data = NULL;
    return 0;
}

int mmapfop_open(struct inode *inode, struct file *filp)
{
    struct mmap_info *info = kmalloc(sizeof(struct mmap_info), GFP_KERNEL);
    info->data = (char *)get_zeroed_page(GFP_KERNEL);
    memcpy(info->data, "hello from kernel this is file: ", 32);
    memcpy(info->data + 32, filp->f_dentry->d_name.name, strlen(filp->f_dentry->d_name.name));
    /* assign this info struct to the file */
    filp->private_data = info;
    return 0;
}

static const struct file_operations mmap_fops = {
    .open = mmapfop_open,
    .release = mmapfop_close,
    .mmap = op_mmap,
};

 static int __init mmapexample_module_init(void)
{
    file = debugfs_create_file("mmap_example", 0644, NULL, NULL, &mmap_fops);
    return 0;
}

static void __exit mmapexample_module_exit(void)
{
    debugfs_remove(file);
}

module_init(mmapexample_module_init);
module_exit(mmapexample_module_exit);
MODULE_LICENSE("GPL");
</code>```

User space:

```<code>#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mman.h>

#define PAGE_SIZE     4096

int main ( int argc, char **argv )
{
    int configfd;
    char * address = NULL;

    configfd = open("/sys/kernel/debug/mmap_example", O_RDWR);
    if(configfd < 0)
    {
        perror("Open call failed");
        return -1;
    }

    address = mmap(NULL, PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, configfd, 0);
    if (address == MAP_FAILED)
    {
        perror("mmap operation failed");
        return -1;
    }
    printf("Initial message: %s\n", address);
    memcpy(address + 11 , "*user*", 6);
    printf("Changed message: %s\n", address);
    close(configfd);
    return 0;
}
</code>```

but with locks.

答:
The problem with the ioctl is you need a kernel switch every time you want to access the share info->data.  If that is okay then the ioctl is good - but then why not just do a standard character read/write file operation instead?

You can also try a lock-less mechanism.  In the shared info->data area add a barrier variable.  When the user needs access, it will do an atomic_compare_and_xchg on the barrier variable until it is set to 0 (unused) and then set it to 1.  When the kernel needs access it will do the same but set it to 2.  See the gcc atomic builtin documentation.

Body:
I have shared memory segment created in kernel using mmap. I need to access this mapped memory from both kernel and user space. What mechanism should I use to protect the memory from concurrent access ?
I want to have something like:

Kernel module:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/debugfs.h>
#include <linux/slab.h>
#include <linux/mm.h>

#ifndef VM_RESERVED
# define  VM_RESERVED   (VM_DONTEXPAND | VM_DONTDUMP)
#endif

struct dentry  *file;

struct mmap_info
{
    char *data;
    int reference;
};

void mmap_open(struct vm_area_struct *vma)
{
    struct mmap_info *info = (struct mmap_info *)vma->vm_private_data;
    info->reference++;
}

void mmap_close(struct vm_area_struct *vma)
{
    struct mmap_info *info = (struct mmap_info *)vma->vm_private_data;
    info->reference--;
}

static int mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
    struct page *page;
    struct mmap_info *info;

    info = (struct mmap_info *)vma->vm_private_data;
    if (!info->data)
    {
        printk("No data\n");
        return 0;
    }
    page = virt_to_page(info->data);
    get_page(page);
    vmf->page = page;
    return 0;
}

struct vm_operations_struct mmap_vm_ops =
{
    .open =     mmap_open,
    .close =    mmap_close,
    .fault =    mmap_fault,
};

int op_mmap(struct file *filp, struct vm_area_struct *vma)
{
    vma->vm_ops = &mmap_vm_ops;
    vma->vm_flags |= VM_RESERVED;
    vma->vm_private_data = filp->private_data;
    mmap_open(vma);
    return 0;
}

int mmapfop_close(struct inode *inode, struct file *filp)
{
    struct mmap_info *info = filp->private_data;
    free_page((unsigned long)info->data);
    kfree(info);
    filp->private_data = NULL;
    return 0;
}

int mmapfop_open(struct inode *inode, struct file *filp)
{
    struct mmap_info *info = kmalloc(sizeof(struct mmap_info), GFP_KERNEL);
    info->data = (char *)get_zeroed_page(GFP_KERNEL);
    memcpy(info->data, "hello from kernel this is file: ", 32);
    memcpy(info->data + 32, filp->f_dentry->d_name.name, strlen(filp->f_dentry->d_name.name));
    /* assign this info struct to the file */
    filp->private_data = info;
    return 0;
}

static const struct file_operations mmap_fops = {
    .open = mmapfop_open,
    .release = mmapfop_close,
    .mmap = op_mmap,
};

 static int __init mmapexample_module_init(void)
{
    file = debugfs_create_file("mmap_example", 0644, NULL, NULL, &mmap_fops);
    return 0;
}

static void __exit mmapexample_module_exit(void)
{
    debugfs_remove(file);
}

module_init(mmapexample_module_init);
module_exit(mmapexample_module_exit);
MODULE_LICENSE("GPL");

User space:

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mman.h>

#define PAGE_SIZE     4096

int main ( int argc, char **argv )
{
    int configfd;
    char * address = NULL;

    configfd = open("/sys/kernel/debug/mmap_example", O_RDWR);
    if(configfd < 0)
    {
        perror("Open call failed");
        return -1;
    }

    address = mmap(NULL, PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, configfd, 0);
    if (address == MAP_FAILED)
    {
        perror("mmap operation failed");
        return -1;
    }
    printf("Initial message: %s\n", address);
    memcpy(address + 11 , "*user*", 6);
    printf("Changed message: %s\n", address);
    close(configfd);
    return 0;
}

but with locks.


问:
python logging to stdout in git bash
I have a python script with logging that outputs to stdout

```<code>logger = logging.getLogger()
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(v_level)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
</code>```

It works just fine when I run my script on my linux box, but when I run the script in git-bash on windows, there is no output to the console.

Any thoughts?

答: Going by the information in this question, it looks like this could well be an issue with output buffering. You can skip buffering by running your script with python -u.

Title: python logging to stdout in git bash

Body:
I have a python script with logging that outputs to stdout

logger = logging.getLogger()
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(v_level)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)

It works just fine when I run my script on my linux box, but when I run the script in git-bash on windows, there is no output to the console.

Any thoughts?


问:
Evenly distribute points on a circle
I need to distribute points evenly on a circumference of a circle, and I'm out of my wits. The result is not exactly circular but rather spiraly, especially with larger numbers of points. I've researched it vigorously but still can't figure out where I could make a mistake.

  window.onload = function() {
      var num = 15;

      var angle = (2 * Math.PI)/(num+1); var count = 0;
      var demo = document.getElementById("demo");

      function Dot() {
          this.angle = angle * count;
          count++;
          this.x = Math.cos(this.angle) * 200;
          this.y = Math.sin(this.angle) * 200;
      }

      Dot.prototype.create = function() {
          var dot = document.createElement("div");
          dot.style.top = this.y + 100 + "px";
          dot.style.left = this.x + 200 + "px";
          dot.className = "dot";
          demo.appendChild(dot);
      }

      for (var i = 0; i < num; i++) {
          var d = new Dot();
          d.create();
      }
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  .dot {
      height: 20px;
      width: 20px;
      border-radius: 50%;
      background: blue;
      position: relative;
      text-align: center;
  }</code>```

    <!DOCTYPE html>

      <title>Metcalfe's Law Demo</title>
      <link rel="stylesheet" href="style.css">

    ```

答:
The main mistake is bloody simple - just change the style position: relative to position: absolute:

window.onload = function() {
      var num = 12;

      var angle = (2 * Math.PI)/(num); var count = 0;
      var demo = document.getElementById("demo");
      console.log(angle)

      function Dot() {
          this.angle = angle * count;
          count++;
          console.log(this.angle,count)
          this.x = Math.cos(this.angle) * 200;
          this.y = Math.sin(this.angle) * 200;
      }

      Dot.prototype.create = function() {
          var dot = document.createElement("div");
          dot.style.top = this.y + 200 + "px";
          dot.style.left = this.x + 200 + "px";
          dot.className = "dot";
          demo.appendChild(dot);
      }

      for (var i = 0; i < num; i++) {
          var d = new Dot();
          d.create();
      }
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dot {
      height: 20px;
      width: 20px;
      border-radius: 50%;
      background: blue;
      position: absolute;
      text-align: center;
  }</code>```

<!DOCTYPE html>

      <title>Metcalfe's Law Demo</title>
      <link rel="stylesheet" href="style.css">

    ```

Title: Evenly distribute points on a circle

Body:
I need to distribute points evenly on a circumference of a circle, and I'm out of my wits. The result is not exactly circular but rather spiraly, especially with larger numbers of points. I've researched it vigorously but still can't figure out where I could make a mistake.

  window.onload = function() {
      var num = 15;

      var angle = (2 * Math.PI)/(num+1); var count = 0;
      var demo = document.getElementById("demo");

      function Dot() {
          this.angle = angle * count;
          count++;
          this.x = Math.cos(this.angle) * 200;
          this.y = Math.sin(this.angle) * 200;
      }

      Dot.prototype.create = function() {
          var dot = document.createElement("div");
          dot.style.top = this.y + 100 + "px";
          dot.style.left = this.x + 200 + "px";
          dot.className = "dot";
          demo.appendChild(dot);
      }

      for (var i = 0; i < num; i++) {
          var d = new Dot();
          d.create();
      }
  }

  .dot {
      height: 20px;
      width: 20px;
      border-radius: 50%;
      background: blue;
      position: relative;
      text-align: center;
  }

    <!DOCTYPE html>

      <title>Metcalfe's Law Demo</title>
      <link rel="stylesheet" href="style.css">

Body:
The main mistake is bloody simple - just change the style position: relative to position: absolute:

window.onload = function() {
      var num = 12;

      var angle = (2 * Math.PI)/(num); var count = 0;
      var demo = document.getElementById("demo");
      console.log(angle)

      function Dot() {
          this.angle = angle * count;
          count++;
          console.log(this.angle,count)
          this.x = Math.cos(this.angle) * 200;
          this.y = Math.sin(this.angle) * 200;
      }

      Dot.prototype.create = function() {
          var dot = document.createElement("div");
          dot.style.top = this.y + 200 + "px";
          dot.style.left = this.x + 200 + "px";
          dot.className = "dot";
          demo.appendChild(dot);
      }

      for (var i = 0; i < num; i++) {
          var d = new Dot();
          d.create();
      }
  }

.dot {
      height: 20px;
      width: 20px;
      border-radius: 50%;
      background: blue;
      position: absolute;
      text-align: center;
  }

<!DOCTYPE html>
    <html>
    <head>
      <title>Metcalfe's Law Demo</title>
      <link rel="stylesheet" href="style.css">
      <script type="text/javascript" src="code.js"></script>
    </head>
        <body>
            <div id="container">
                <div id="demo">
                </div>
            </div>
        </body>
    </html>


问:
SQL Server and asp.net application security models / best practice
For my asp.net web applications against sql server(at least the ones that require a logon to access) I generally implement security as follows:

I generally roll my own user signup, user login pages and keep a userid and an encrypted password in an sql server and validate the login against that table - I also provide for forgotten passwords, 'send me my password', email verification to activate accounts etc all thru custom code.

Once the user has been validated by the app (and lets assume that all users have the same privileges), I generally use a utility logonid to let asp.net talk to sql server, so in other words I only need to create a single logon id per application, and since 100% of all data access is done thru stored procedures, I need only grant access to a single user to execute stored procedures, and no other work is required on sql server. Each application has its own database, and the logon for that app can only access that database.

All this works perfectly well for me, the only negative of this is that it would be nice to be able to setup a trace in sql server and see the userid and the procs that are being called, but since all users are 'talking' to the database thru a single database logon, this can't happen.

So, two part question:

1) Are there security models are you folks using that I should consider? Its easy to always do the same thing over and over, - especially since it works - but are there other models that would work better or that I should consider? Is it recommended practice that all database access from an asp.net app would all share a single database login? or is this considered bad practice? and if so, why?

2) Assuming I stick with my model, is there a way to allow for the application login id to be seen in the sql trace window? It would be nice to see the sp's being called and the user id of the person logged into the system (not the database login).

答: From a .NET best practices point of view, you may want to consider taking a look at Microsoft Enterprise Library.  It contains a set of practices, patterns, and features that assist with issues such as Security and Data Access.</p>

OwnerDisplayName: E.J. Brennan


问:
Problem to connect mysql and Java
I am trying to connect Java code to mySQL. Here is the error that I got. I dont understand why no driver is found since I have put the connector jar at the classpath.

```<code>Class Not Found Exception:
No suitable driver found for jdbc:mysql://localhost/hpdata?user=root&password=12
3456
Exception in thread "main" java.lang.NullPointerException
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.open(FeatureSpe
cRDB.java:122)
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.<init>(FeatureS
pecRDB.java:66)
    at edu.indiana.iucbrf.domain.componentfactory.RDBComponentFactory.constr
uctProblemFeatureSpecCollection(RDBComponentFactory.java:112)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:239)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:197)
    at edu.indiana.iucbrf.examples.honeypotRDBTemplate.HDomainRDB.<in
it>(HDomainRDB.java:56)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.set
 upDomain(HSystemRDB.java:198)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.<in
it>(HSystemRDB.java:131)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HTestClassRDB.
main(HTestClassRDB.java:65)
</code>```

Here is my code :

```<code>   private static void flush() {

  Class.forName("com.mysql.jdbc.Driver").newInstance();

    try {

   conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hpdata?user=root&password=123456");

      } catch (Exception e) {
          System.out.println("Class Not Found Exception:");
          System.out.println(e.getMessage());
      }
</code>```

答:
You're assuming that you've set CLASSPATH properly.  Please explain how you're doing that so we can tell you whether it's correct or not.

If you've set an environment variable named CLASSPATH, that's almost certainly wrong.

It makes a difference if your app is for the web or desktop.  Please tell us which is true for you.

UPDATE:

The right way to set CLASSPATH for a desktop app is to use the -classpath option on the JVM when you run:

```<code>java -classpath .;<paths-to-your-JARs-separated-by-semi-colons>;<paths-to-the-root-of-package-trees> foo.YourCode
</code>```

Title: Problem to connect mysql and Java

Body:
I am trying to connect Java code to mySQL. Here is the error that I got. I dont understand why no driver is found since I have put the connector jar at the classpath.

Class Not Found Exception:
No suitable driver found for jdbc:mysql://localhost/hpdata?user=root&password=12
3456
Exception in thread "main" java.lang.NullPointerException
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.open(FeatureSpe
cRDB.java:122)
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.<init>(FeatureS
pecRDB.java:66)
    at edu.indiana.iucbrf.domain.componentfactory.RDBComponentFactory.constr
uctProblemFeatureSpecCollection(RDBComponentFactory.java:112)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:239)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:197)
    at edu.indiana.iucbrf.examples.honeypotRDBTemplate.HDomainRDB.<in
it>(HDomainRDB.java:56)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.set
 upDomain(HSystemRDB.java:198)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.<in
it>(HSystemRDB.java:131)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HTestClassRDB.
main(HTestClassRDB.java:65)

Here is my code :

   private static void flush() {

  Class.forName("com.mysql.jdbc.Driver").newInstance();

    try {

   conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hpdata?user=root&password=123456");

      } catch (Exception e) {
          System.out.println("Class Not Found Exception:");
          System.out.println(e.getMessage());
      }

Body:
You're assuming that you've set CLASSPATH properly.  Please explain how you're doing that so we can tell you whether it's correct or not.

If you've set an environment variable named CLASSPATH, that's almost certainly wrong.

It makes a difference if your app is for the web or desktop.  Please tell us which is true for you.

UPDATE:

The right way to set CLASSPATH for a desktop app is to use the -classpath option on the JVM when you run:

java -classpath .;<paths-to-your-JARs-separated-by-semi-colons>;<paths-to-the-root-of-package-trees> foo.YourCode


问:
jQuery How to hide all span containing td in a table
I have some rows in a table like the code below and I want after some seconds to hide the contents of td's (i have filled them with text in a loop).
My sample code is this

```<code>setTimeout(function() {
  $('span').each(function(index, el) {
      $(this).hide();//nothing happens
  });
}, 5000);

<tr>
  <span class="myspan"><td></td></span>
  <span class="myspan"><td></td></span>
  <span class="myspan"><td></td></span>
  <span class="myspan"><td></td></span>
</tr>
</code>```

I tried using other ways too, like saving all spans to an array, or selecting the class and hiding it.

```<code>var arr=$('span');
for (var i=0;i<arr.length;i++){
  arr[i].css('visibility','hidden');
}
</code>```

but same thing happened. I want to be able to show and hide the contents of td's when it's needed without hiding the border if it is possible

答:
To hide all after 5 seconds, you can use the following code

```<code>setTimeout(function() {
 $('table tr span').hide(5000);
}, 5000);
</code>```

or

```<code>setTimeout(function() {
     $('table tr span').css('visibility','hidden');
 }, 5000);
</code>```

Body:
I have some rows in a table like the code below and I want after some seconds to hide the contents of td's (i have filled them with text in a loop).
My sample code is this

setTimeout(function() {
  $('span').each(function(index, el) {
      $(this).hide();//nothing happens
  });
}, 5000);

I tried using other ways too, like saving all spans to an array, or selecting the class and hiding it.

var arr=$('span');
for (var i=0;i<arr.length;i++){
  arr[i].css('visibility','hidden');
}

but same thing happened. I want to be able to show and hide the contents of td's when it's needed without hiding the border if it is possible

Body:
To hide all after 5 seconds, you can use the following code

setTimeout(function() {
 $('table tr span').hide(5000);
}, 5000);

or

setTimeout(function() {
     $('table tr span').css('visibility','hidden');
 }, 5000);


问:
Retrieve stored procedure definition from SQL Server
```<code>SELECT
    OBJECT_NAME(object_id),
    OBJECT_DEFINITION(object_id)
FROM
    sys.procedures
WHERE
    OBJECT_DEFINITION(object_id) LIKE '%xxxx%'
</code>```

The above query displays the stored procedure definition, but the result is displayed in a single line. It is really hard to read.

I tried to change the display result by text. But it has max length limit 8000 char.

Is there any way I can query a readable stored procedure definition or any tool I can use to convert the single line stored procedure to a more readable script.

答:
you can export the definition to file.
If you want to seach which procesures container some text, you can use red gate free tools SQL Search</p>

```<code>DECLARE @OLE            INT
DECLARE @FileID         INT
DECLARE    @File VARCHAR(2000), @Text VARCHAR(max)

EXECUTE sp_OACreate 'Scripting.FileSystemObject', @OLE OUT
EXECUTE sp_OAMethod @OLE, 'OpenTextFile', @FileID OUT, @File, 8, 1
EXECUTE sp_OAMethod @FileID, 'WriteLine', Null, @Text
EXECUTE sp_OADestroy @FileID
EXECUTE sp_OADestroy @OLE
</code>```

Body:
SELECT
    OBJECT_NAME(object_id),
    OBJECT_DEFINITION(object_id)
FROM
    sys.procedures
WHERE
    OBJECT_DEFINITION(object_id) LIKE '%xxxx%'

The above query displays the stored procedure definition, but the result is displayed in a single line. It is really hard to read.

I tried to change the display result by text. But it has max length limit 8000 char.

Is there any way I can query a readable stored procedure definition or any tool I can use to convert the single line stored procedure to a more readable script.

Body:
you can export the definition to file.
If you want to seach which procesures container some text, you can use red gate free tools SQL Search

DECLARE @OLE            INT
DECLARE @FileID         INT
DECLARE    @File VARCHAR(2000), @Text VARCHAR(max)

EXECUTE sp_OACreate 'Scripting.FileSystemObject', @OLE OUT
EXECUTE sp_OAMethod @OLE, 'OpenTextFile', @FileID OUT, @File, 8, 1
EXECUTE sp_OAMethod @FileID, 'WriteLine', Null, @Text
EXECUTE sp_OADestroy @FileID
EXECUTE sp_OADestroy @OLE


问:
How does django know which user owns what data?
If for example I want to show a zero(0) for all users to see, and I want all users to add one(1) to the number With their Identity only shown for superusers. And how to make sure that each user only can add one time, and of course what is the Security requirements that have to be done to prevent unautohrized Access to change any of this or to get any information?

I understand this is a big topic, but could someone briefly explain for me what parts of Programming that are involved, and maybe some good books on these topics?

答:
The web is stateless. This means that if a browser requests the same page twice, a traditional web server has no real way of knowing if it's the same user.

Enter sessions. Django has an authentication system which requires each user to log in. When the user is logged in they're given a session. A session is made of two parts; A cookie containing a randomly generated token, and a database entry with that same token.

When a user logs in, a new session token is generated and sent, via a cookie, back to the user which the browser stores. At the same time, that record is created in the database. Each time a browser makes a request to Django, it sends its session cookie along with the request and Django compares this to the tokens in the database. If the token exists, the user is considered to be logged in. If the token doesn't exist, the user isn't logged in.

In Django, there are User models which make it easy to check who the currently logged in user is for each request. They're doing all that token checking in the background for us on each and every request made by every user. Armed with this, we can associate other models via "foreign key" relationships to indicate who owns what.

Say you were making a blog where multiple users could write articles. If you wanted to build an editing feature you'd probably want to restrict users to only be allowed to edit their own articles and nobody else's. In this situation, you'd receive the request, find out who the current user was from it, compare that user to the "author" field on the blog Post model and see if that foreign key matches. If it matches, then the user making the current request is the owner and is allowed to edit.

This whole process is secured by the fact that the session tokens are randomly generated hashes, rather than simple ID numbers. A malicious attacker can't simply take the hash and increment the value to try and access adjacent accounts, they'd have to intercept another user's hash entirely. This can be further secured by using SSL certificates so that your connections go over https:// and all traffic is encrypted between the browser and your server.


问:
Can't access Port 9200 Remotely
Have just started using elastic search 5.4.0, first i have  installed it on Mac(local) and then in server.
In Mac when i am running in browser as  'http://localhost:9200' it is showing me output :

{
  "name" : "Node_1",
  "cluster_name" : "bhujang_bipl",
  "cluster_uuid" : "N75mGOiSQCufpBl_2B7jSg",
  "version" : {
    "number" : "5.4.0",
    "build_hash" : "780f8c4",
    "build_date" : "2017-04-28T17:43:27.229Z",
    "build_snapshot" : false,
    "lucene_version" : "6.5.0"
  },
  "tagline" : "You Know, for Search"
}```
</div>
</div>
</p>

<p>which means i am connected to 9200 which is elasticsaerch.</p>

<p>But when i am running it on server by http://192.168.1.126:9200 , then it is not getting connected and shows me an output as :page not found !!</p>

<p>I disabled firewall on both the server and client as solutions I got from internet but couldn't get it working.</p>

<p>My elasticsaerch.yml file is</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>
# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
#       Before you set out to tweak and tune the configuration, make sure you
#       understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
#cluster.name: my-application
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
#node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
#path.data: /path/to/data
#
# Path to log files:
#
#path.logs: /path/to/logs
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#network.host:192.168.1.126
#
# Set a custom port for HTTP:
#http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when new node is started:
#The default list of hosts is ["127.0.0.1", "[::1]","103.240.195.45","103.240.195.45"]
#
#discovery.zen.ping.unicast.hosts: ["host1", "host2"]
#
# Prevent the "split brain" by configuring the majority of nodes (total number of master-eligible nodes / 2 + 1):
#
#discovery.zen.minimum_master_nodes: 3
#
# For more information, consult the zen discovery module documentation.
#
# ---------------------------------- Gateway -----------------------------------
#
# Block initial recovery after a full cluster restart until N nodes are started:
#
#gateway.recover_after_nodes: 3
#
# For more information, consult the gateway module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Require explicit names when deleting indices:
#
#action.destructive_requires_name: true</code>```

Can anyone help me with what can be the best possible mistake from my side ?

答:
From the link
https://github.com/elastic/elasticsearch/issues/19987

add this two line in the yml file

```<code>transport.host: localhost
network.host: 192.168.1.126
</code>```

Title: Can't access Port 9200 Remotely

Body:
Have just started using elastic search 5.4.0, first i have  installed it on Mac(local) and then in server.
In Mac when i am running in browser as  'http://localhost:9200' it is showing me output :

{
  "name" : "Node_1",
  "cluster_name" : "bhujang_bipl",
  "cluster_uuid" : "N75mGOiSQCufpBl_2B7jSg",
  "version" : {
    "number" : "5.4.0",
    "build_hash" : "780f8c4",
    "build_date" : "2017-04-28T17:43:27.229Z",
    "build_snapshot" : false,
    "lucene_version" : "6.5.0"
  },
  "tagline" : "You Know, for Search"
}

which means i am connected to 9200 which is elasticsaerch.

But when i am running it on server by http://192.168.1.126:9200 , then it is not getting connected and shows me an output as :page not found !!

I disabled firewall on both the server and client as solutions I got from internet but couldn't get it working.

My elasticsaerch.yml file is

# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
#       Before you set out to tweak and tune the configuration, make sure you
#       understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
#cluster.name: my-application
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
#node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
#path.data: /path/to/data
#
# Path to log files:
#
#path.logs: /path/to/logs
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#network.host:192.168.1.126
#
# Set a custom port for HTTP:
#http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when new node is started:
#The default list of hosts is ["127.0.0.1", "[::1]","103.240.195.45","103.240.195.45"]
#
#discovery.zen.ping.unicast.hosts: ["host1", "host2"]
#
# Prevent the "split brain" by configuring the majority of nodes (total number of master-eligible nodes / 2 + 1):
#
#discovery.zen.minimum_master_nodes: 3
#
# For more information, consult the zen discovery module documentation.
#
# ---------------------------------- Gateway -----------------------------------
#
# Block initial recovery after a full cluster restart until N nodes are started:
#
#gateway.recover_after_nodes: 3
#
# For more information, consult the gateway module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Require explicit names when deleting indices:
#
#action.destructive_requires_name: true

Can anyone help me with what can be the best possible mistake from my side ?

Body:
From the link
https://github.com/elastic/elasticsearch/issues/19987

add this two line in the yml file

transport.host: localhost
network.host: 192.168.1.126

ContentLicense: CC BY-SA 4.0


问:
How to pass HashMap from one Actor to another
I have a method getAggOutput() that returns a HashMap, in Actor A.

```<code>def getAggOutput: HashMap[X, List[Y]] = {
    println("***** Inside getAggOutput, rMap is: " + rMap)
    return rMap
 }
</code>```

Also, in Actor A, the method is called that under the case object GETOUTPUT:

```<code>case GETOUTPUT =>
   println("***** Inside GETOUTPUT")
   getAggOutput
</code>```

In Actor B, I am doing the following:

```<code> implicit val timeout = Timeout(5 seconds)
 val reducerInput = sender ? GETOUTPUT
 val result = Await.result(reducerInput, timeout.duration)
 println("****** RESULT is: " + result)
</code>```

The print statements show that the value for rMap is correct, however, I am getting the following error:

```<code>java.util.concurrent.TimeoutException: Futures timed out after [5 seconds]
</code>```

And result is not assigned the value of the HashMap.

How do I make this work?  Or, is there a better way entirely?  I just need to get rMap into Actor B

UPDATE:

I figured out this part.  In the case GETOUTPUT, I need:

```<code>sender ! getAggOutput.
</code>```

The println shows that the HashMap in the result variable is correct.

Now, I am trying to loop over the HashMap:

```<code> for( (key,value) <- result)
     {
       redOut += (key -> value)
     }
</code>```

And I am getting the following error:

```<code>type mismatch;
[error]  found   : (Any, Any)
[error]  required: (X, U)
[error]            redOut += (key -> value)
</code>```

UPDATE:

```<code>I also tried:

for( (key,value) <- result)
     {
       redOut += (key.asInstanceOf[X] -> value.asInstanceOf[U])
     }
</code>```

However, I received the following error:

```<code>value withFilter is not a member of Any
[error]          for( (key,value) <- result)
</code>```

答: There was no need to do this, I just looped over the Hashmap in Actor A and sent each (key, value) pair to Actor B</p>

Body:
I have a method getAggOutput() that returns a HashMap, in Actor A.

def getAggOutput: HashMap[X, List[Y]] = {
    println("***** Inside getAggOutput, rMap is: " + rMap)
    return rMap
 }

Also, in Actor A, the method is called that under the case object GETOUTPUT:

case GETOUTPUT =>
   println("***** Inside GETOUTPUT")
   getAggOutput

In Actor B, I am doing the following:

 implicit val timeout = Timeout(5 seconds)
 val reducerInput = sender ? GETOUTPUT
 val result = Await.result(reducerInput, timeout.duration)
 println("****** RESULT is: " + result)

The print statements show that the value for rMap is correct, however, I am getting the following error:

java.util.concurrent.TimeoutException: Futures timed out after [5 seconds]

And result is not assigned the value of the HashMap.

How do I make this work?  Or, is there a better way entirely?  I just need to get rMap into Actor B

UPDATE:

I figured out this part.  In the case GETOUTPUT, I need:

sender ! getAggOutput.

The println shows that the HashMap in the result variable is correct.

Now, I am trying to loop over the HashMap:

 for( (key,value) <- result)
     {
       redOut += (key -> value)
     }

And I am getting the following error:

type mismatch;
[error]  found   : (Any, Any)
[error]  required: (X, U)
[error]            redOut += (key -> value)

UPDATE:

I also tried:

for( (key,value) <- result)
     {
       redOut += (key.asInstanceOf[X] -> value.asInstanceOf[U])
     }

However, I received the following error:

value withFilter is not a member of Any
[error]          for( (key,value) <- result)


问:
Are unbound variables allowed in Lambda Calculus?
Hello i am trying to understand lambda calculus, unfortunately i am confused on the topic of unbound variables.
Here is a list i got from my professor about valid lambda expressions (No idea why he doesn't use dots like i see everywhere else on the internet btw)

Now i am confused about a couple of them. Say the fifth one: Lambda x.(xy)
Why is this a valid expression? I don't think i can use this expression like this for example, because y is unbound : (Lambda x.(xy)) 5

Here are some exercises i tried:

Are these answers correct?

a)Yes

b)Yes

c)Yes

d)No

e)Yes

f)Yes

g)Yes

It all doesn't feel right, it would all be more logical if unbound variables would not be allowed. Then the answers would look something like this:

a)Yes

b)No

c)Yes

d)No

e)Yes

f)No

g)No

I think I am close to understanding this but i need a last push in the back to get it fully. Anyways, thanks for the help!

答:
There is nothing wrong with having unbound (free) variables in your expression. They are typically just considered to be in global scope.

It is very similar to stating:

```<code>f(x) = x^y
</code>```

where clearly x is a bound local variable, and y is a free global. We don't have enough information presented to solve f(x) for a given value of x numerically, but algebraically, f(5) = 5^y.

By the same logic it is valid to say (λx.y)(...) = y. We don't have a value for that y, but we don't need to.

What do you call a lambda without free variables? A combinator. It's funny because it's true.

Body:
There is nothing wrong with having unbound (free) variables in your expression. They are typically just considered to be in global scope.

It is very similar to stating:

f(x) = x^y

where clearly x is a bound local variable, and y is a free global. We don't have enough information presented to solve f(x) for a given value of x numerically, but algebraically, f(5) = 5^y.

By the same logic it is valid to say (λx.y)(...) = y. We don't have a value for that y, but we don't need to.

What do you call a lambda without free variables? A combinator. It's funny because it's true.


问:
conditionally contain arguments in url path in rails
I have a search function which allows a user to search for items. From the generated list, the user can add items to a list. After adding an item from the list, the page reloads and the user is returned to their current search list. However, currently, if a user has not searched for anything, and just adds an item of the top of the list (starting at 'A, for example), when the page reloads it includes a blank search query in the url. I know why, it is because of this line

```<code>redirect_to admin_job_job_products_path(@job, search_term: params[:search_term])
</code>```

I want to make the last argument in the redirect path a conditional one so that, if say the :search_term == nil || == "" || " " then the redirect_to only includes the first argument.

How would I best achieve this?

Thanks in advance!

答:
The second example of MrYoshiji probably will not work, but you can write it short and simple this why:

```<code>redirect_to admin_job_job_products_path(@job, search_term: params[:search_term].present? ? params[:search_term] : nil)
</code>```

So if the result will be nil rails will not include that param in the url

Body:
I have a search function which allows a user to search for items. From the generated list, the user can add items to a list. After adding an item from the list, the page reloads and the user is returned to their current search list. However, currently, if a user has not searched for anything, and just adds an item of the top of the list (starting at 'A, for example), when the page reloads it includes a blank search query in the url. I know why, it is because of this line

redirect_to admin_job_job_products_path(@job, search_term: params[:search_term])

I want to make the last argument in the redirect path a conditional one so that, if say the :search_term == nil || == "" || " " then the redirect_to only includes the first argument.

How would I best achieve this?

Thanks in advance!

Body:
The second example of MrYoshiji probably will not work, but you can write it short and simple this why:

redirect_to admin_job_job_products_path(@job, search_term: params[:search_term].present? ? params[:search_term] : nil)

So if the result will be nil rails will not include that param in the url


问:
Emulator in Android Studio doesn't start
I think it's a problem with the SDK reference in Project Structure, but when I click run and I choose Launch Emulator nothing appears.</p>

答:
I had the same problem, but now I'm using it successfully.  As you know, the minimum RAM required to run android studio is 4 GB, but if you only have 4 GB RAM, you probably won't be able to run many other applications at the same time.

It's also possible that some windows driver, e.g. graphics, is incompatible. You may want to experiment with software and hardware options for graphics:  https://developer.android.com/studio/run/emulator-acceleration.html

It might also help to increase the connection timeout in settings/tasks.


问:
Return first word in sentence?
Heres the question I have to answer for school

For the purposes of this question, we will define a word as ending a sentence if that word is immediately followed by a period. For example, in the text “This is a sentence. The last sentence had four words.”, the ending words are ‘sentence’ and ‘words’. In a similar fashion, we will define the starting word of a sentence as any word that is preceded by the end of a sentence. The starting words from the previous example text would be “The”. You do not need to consider the first word of the text as a starting word. Write a program that has:

An endwords function that takes a single string argument. This functioin must return a list of all sentence ending words that appear in the given string. There should be no duplicate entries in the returned list and the periods should not be included in the ending words.

The code I have so far is:

```<code>def startwords(astring):
    mylist = astring.split()
    if mylist.endswith('.') == True:
        return my list
</code>```

but I don't know if I'm using the right approach. I need some help

答:
This is one way to do it ->

```<code>#!/bin/env/ python

from sets import Set

sentence = 'This is a sentence. The last sentence had four words.'
uniq_end_words = Set()

for word in sentence.split():
    if '.' in word:
        # check if period (.) is at the end
        if '.' == word[len(word) -1]:
            uniq_end_words.add(word.rstrip('.'))

print list(uniq_end_words)
</code>```

Output (list of all the end words in a given sentence) ->

```<code>['words', 'sentence']
</code>```

If your input string has a period in one of its word (lets say the last word),  something like this ->

'I like the documentation of numpy.random.rand.'

The output would be -  ['numpy.random.rand']

And for input string 'I like the documentation of numpy.random.rand a lot.'

The output would be -  ['lot']

Title: Return first word in sentence?

Body:
Heres the question I have to answer for school

For the purposes of this question, we will define a word as ending a sentence if that word is immediately followed by a period. For example, in the text “This is a sentence. The last sentence had four words.”, the ending words are ‘sentence’ and ‘words’. In a similar fashion, we will define the starting word of a sentence as any word that is preceded by the end of a sentence. The starting words from the previous example text would be “The”. You do not need to consider the first word of the text as a starting word. Write a program that has:

An endwords function that takes a single string argument. This functioin must return a list of all sentence ending words that appear in the given string. There should be no duplicate entries in the returned list and the periods should not be included in the ending words.

The code I have so far is:

def startwords(astring):
    mylist = astring.split()
    if mylist.endswith('.') == True:
        return my list

but I don't know if I'm using the right approach. I need some help

Body:
This is one way to do it ->

#!/bin/env/ python

from sets import Set

sentence = 'This is a sentence. The last sentence had four words.'
uniq_end_words = Set()

for word in sentence.split():
    if '.' in word:
        # check if period (.) is at the end
        if '.' == word[len(word) -1]:
            uniq_end_words.add(word.rstrip('.'))

print list(uniq_end_words)

Output (list of all the end words in a given sentence) ->

['words', 'sentence']

If your input string has a period in one of its word (lets say the last word),  something like this ->

'I like the documentation of numpy.random.rand.'

The output would be -  ['numpy.random.rand']

And for input string 'I like the documentation of numpy.random.rand a lot.'

The output would be -  ['lot']


问:
why I get blank page when I browse to localhost:3000?
trying this react example after I start the server at port 3000 I get a blank page. Here is the code:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react-dom.js"></script>
  </head>
  <body>
      <div id="app"></div>

      <script type="text/babel">
        ReactDOM.render(

          <h1>Hello React</h1>,
          document.getElementById('app')
        );

      </script>
  </body>
</html>
</code>```

So why I get blank page ?

I see there is an error in the console but I dont know if this is the problem or not. I am on windows 10

答: it seems last version of babel has a problem I switched to 5.8.23 and I get "Hello Ract" normally !!</p>

Body:
trying this react example after I start the server at port 3000 I get a blank page. Here is the code:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

So why I get blank page ?

I see there is an error in the console but I dont know if this is the problem or not. I am on windows 10


问:
Exclude word from redirect with Regex in NGINX
I am trying to match anything the user could input but a single word. This will match anything but the word, but variable $1 is empty.

```<code>rewrite ^/folder/((?:(?!word).)*)/$ /folder/$1/;
rewrite ^/folder/((?:(?!word).)*)/$ /folder/index.php?i=$1;
</code>```

Example:

www.example.com/folder/a will just rewrite to www.example.com/folder/a//
And also redirects to //
www.example.com/folder/a/ will just rewrite to www.example.com/folder/a//

I feel like I am very close to the solution, what am I missing?

答:
That happens because the first capturing group is quantified, and the . is re-captured 0 or more times, with the last char captured with . in Group 1 ($1) at the end.

You need to re-write the tempered greedy token with a non-capturing group and wrap it with a capturing one:

```<code>rewrite ^/folder/((?:(?!word).)*)/$ /folder/$1/;
                 ^^^^           ^
</code>```

Now, the (?:(?!word).)* construct uses a non-capturing group (no redundant group re-assignment is involved) and the outer (...) form a capturing group with ID 1.

Body:
I am trying to match anything the user could input but a single word. This will match anything but the word, but variable $1 is empty.

rewrite ^/folder/((?:(?!word).)*)/$ /folder/$1/;
rewrite ^/folder/((?:(?!word).)*)/$ /folder/index.php?i=$1;

Example:

www.example.com/folder/a will just rewrite to www.example.com/folder/a//
And also redirects to //
www.example.com/folder/a/ will just rewrite to www.example.com/folder/a//

I feel like I am very close to the solution, what am I missing?

Body:
That happens because the first capturing group is quantified, and the . is re-captured 0 or more times, with the last char captured with . in Group 1 ($1) at the end.

You need to re-write the tempered greedy token with a non-capturing group and wrap it with a capturing one:

rewrite ^/folder/((?:(?!word).)*)/$ /folder/$1/;
                 ^^^^           ^

Now, the (?:(?!word).)* construct uses a non-capturing group (no redundant group re-assignment is involved) and the outer (...) form a capturing group with ID 1.


问:
Laravel unknown column
I have a problem with this error:

```<code>https://pastebin.com/cgm5yq0P
</code>```

This is my form:

```<code>https://pastebin.com/bSU5X5EC
</code>```

This is my web.php (route controller):

Route::post('/komentarz', 'VideosController@postComment');

This is my VideoController postComment function:

```<code>https://pastebin.com/SYbEjB8H
</code>```

This is my Comment model:

```<code>https://pastebin.com/SxHX6gTP
</code>```

This is my User model comments function:

```<code>    public function comments() {
    return $this->hasMany('App\Comment');
}
</code>```

This is my Video model comments function:

public function comments(){
        return $this->belongsToMany('App\Comment')->withTimestamps();
    }

And finally, Migration file named create_comments_table:

https://pastebin.com/2cHscQfq

My Routes:
 https://pastebin.com/ki8FZ0C6
Please help me with this.. I dunno what is wrong

答:
in comment model i see 'user' in fillable, not 'user_id'. i think it should be user_id. or you could use

```<code>protected guarded = [];
</code>```

instead of using fillable array.

Title: Laravel unknown column

Body:
I have a problem with this error:

https://pastebin.com/cgm5yq0P

This is my form:

https://pastebin.com/bSU5X5EC

This is my web.php (route controller):

Route::post('/komentarz', 'VideosController@postComment');

This is my VideoController postComment function:

https://pastebin.com/SYbEjB8H

This is my Comment model:

https://pastebin.com/SxHX6gTP

This is my User model comments function:

    public function comments() {
    return $this->hasMany('App\Comment');
}

This is my Video model comments function:

public function comments(){
        return $this->belongsToMany('App\Comment')->withTimestamps();
    }

And finally, Migration file named create_comments_table:

https://pastebin.com/2cHscQfq

My Routes:
 https://pastebin.com/ki8FZ0C6
Please help me with this.. I dunno what is wrong

Body:
in comment model i see 'user' in fillable, not 'user_id'. i think it should be user_id. or you could use

protected guarded = [];

instead of using fillable array.


问:
java.lang.OutOfMemoryError: requested 1958536 bytes for Chunk::new. Out of swap space
We are facing the below problem at our production enviournment in unpredictable manner
sometimes the server is down in a day or sometimes in a week, below is the exact error
dump, below are the settings for the server.

```
JDK: jdk1.6.0_21
Server: Tomcat 7.0.2
OS: Red Hat Enterprise Linux Server release 5.5
```

In catalina.sh the following setting has been done:

```<code>JAVA_OPTS="-Xms1024M -Xmx1536M -XX:+HeapDumpOnOutOfMemoryError -XX:+AggressiveOpts
-XX:-DisableExplicitGC  -XX:AdaptiveSizeThroughPutPolicy=0
-XX:+UsePSAdaptiveSurvivorSizePolicy
-XX:+UseAdaptiveGenerationSizePolicyAtMinorCollection
-XX:+UseAdaptiveGenerationSizePolicyAtMajorCollection -XX:PermSize=768M
-XX:MaxPermSize=768M    -XX:+PrintGCDetails -Xloggc:/tmp/gcLogs.txt"

export CATALINA_OPTS="-Dcom.sun.management.jmxremote.port=22222
-Dcom.sun.management.jmxremote.authenticate=true -Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.password.file=/jakarta-tomcat7/apache-tomcat-7.0.2/conf
/jmxremote.password -Dcom.sun.management.jmxremote.access.file=/jakarta-tomcat7/apache-
tomcat-7.0.2/conf/jmxremote.access"
</code>```

Error Trace:-

```
#
# A fatal error has been detected by the Java Runtime Environment:
#
# java.lang.OutOfMemoryError: requested 1958536 bytes for Chunk::new. Out of swap space?
#
#  Internal Error (allocation.cpp:215), pid=18658, tid=589781904
#  Error: Chunk::new
#
# JRE version: 6.0_21-b06
# Java VM: Java HotSpot(TM) Server VM (17.0-b16 mixed mode linux-x86 )
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
#

---------------  T H R E A D  ---------------

Current thread (0x23787400):  JavaThread "CompilerThread0" daemon [_thread_in_native, id=18668, stack(0x231f5000,0x23276000)]

Stack: [0x231f5000,0x23276000],  sp=0x23272e70,  free space=1f723276000k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
V  [libjvm.so+0x6a9262]
V  [libjvm.so+0x2b277f]
V  [libjvm.so+0x12e03c]
V  [libjvm.so+0x12e536]
V  [libjvm.so+0x5d67d0]
V  [libjvm.so+0x2f809d]
V  [libjvm.so+0x4f65a9]
V  [libjvm.so+0x27b85f]
V  [libjvm.so+0x278043]
V  [libjvm.so+0x209767]
V  [libjvm.so+0x280f8c]
V  [libjvm.so+0x280839]
V  [libjvm.so+0x66feb6]
V  [libjvm.so+0x66959e]
V  [libjvm.so+0x57a89e]
C  [libpthread.so.0+0x5832]

Current CompileTask:
C2:3230  !   org.apache.jsp.com.common.press_jsp._jspService(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V (4433 bytes)

---------------  P R O C E S S  ---------------

Java Threads: ( => current thread )
  0x09a21400 JavaThread "http-8080-exec-904" daemon [_thread_in_native, id=17126, stack(SIGTERM: [libjvm.so+0x57aaf0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004
SIGQUIT: [libjvm.so+0x57aaf0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004

---------------  S Y S T E M  ---------------

OS:Red Hat Enterprise Linux Server release 5.5 (Tikanga)

uname:Linux 2.6.18-194.17.1.el5PAE #1 SMP Mon Sep 20 07:34:07 EDT 2010 i686
libc:glibc 2.5 NPTL 2.5
rlimit: STACK 10240k, CORE 0k, NPROC 114688, NOFILE 1024, AS infinity
load average:0.39 0.54 0.38

CPU:total 2 (2 cores per cpu, 1 threads per core) family 6 model 15 stepping 11, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3

Memory: 4k page, physical 6228576k(225096k free), swap 6974456k(6974352k free)

vm_info: Java HotSpot(TM) Server VM (17.0-b16) for linux-x86 JRE (1.6.0_21-b06), built on Jun 22 2010 01:04:46 by "java_re" with gcc 3.2.1-7a (J2SE release)

time: Fri Dec 10 14:01:06 2010
elapsed time: 79552 seconds
```

Thanks in advance,
Amit

答: You're running with a lot of JVM args that affect memory.  Have you tried empirically removing each option to see which one is causing the OOM?  This particular OOM is not coming from the Java heap, it's coming from the JVM's own C heap. </p>

Body:
We are facing the below problem at our production enviournment in unpredictable manner
sometimes the server is down in a day or sometimes in a week, below is the exact error
dump, below are the settings for the server.

JDK: jdk1.6.0_21
Server: Tomcat 7.0.2
OS: Red Hat Enterprise Linux Server release 5.5

In catalina.sh the following setting has been done:

JAVA_OPTS="-Xms1024M -Xmx1536M -XX:+HeapDumpOnOutOfMemoryError -XX:+AggressiveOpts
-XX:-DisableExplicitGC  -XX:AdaptiveSizeThroughPutPolicy=0
-XX:+UsePSAdaptiveSurvivorSizePolicy
-XX:+UseAdaptiveGenerationSizePolicyAtMinorCollection
-XX:+UseAdaptiveGenerationSizePolicyAtMajorCollection -XX:PermSize=768M
-XX:MaxPermSize=768M    -XX:+PrintGCDetails -Xloggc:/tmp/gcLogs.txt"

export CATALINA_OPTS="-Dcom.sun.management.jmxremote.port=22222
-Dcom.sun.management.jmxremote.authenticate=true -Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.password.file=/jakarta-tomcat7/apache-tomcat-7.0.2/conf
/jmxremote.password -Dcom.sun.management.jmxremote.access.file=/jakarta-tomcat7/apache-
tomcat-7.0.2/conf/jmxremote.access"

Error Trace:-

#
# A fatal error has been detected by the Java Runtime Environment:
#
# java.lang.OutOfMemoryError: requested 1958536 bytes for Chunk::new. Out of swap space?
#
#  Internal Error (allocation.cpp:215), pid=18658, tid=589781904
#  Error: Chunk::new
#
# JRE version: 6.0_21-b06
# Java VM: Java HotSpot(TM) Server VM (17.0-b16 mixed mode linux-x86 )
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
#

---------------  T H R E A D  ---------------

Current thread (0x23787400):  JavaThread "CompilerThread0" daemon [_thread_in_native, id=18668, stack(0x231f5000,0x23276000)]

Stack: [0x231f5000,0x23276000],  sp=0x23272e70,  free space=1f723276000k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
V  [libjvm.so+0x6a9262]
V  [libjvm.so+0x2b277f]
V  [libjvm.so+0x12e03c]
V  [libjvm.so+0x12e536]
V  [libjvm.so+0x5d67d0]
V  [libjvm.so+0x2f809d]
V  [libjvm.so+0x4f65a9]
V  [libjvm.so+0x27b85f]
V  [libjvm.so+0x278043]
V  [libjvm.so+0x209767]
V  [libjvm.so+0x280f8c]
V  [libjvm.so+0x280839]
V  [libjvm.so+0x66feb6]
V  [libjvm.so+0x66959e]
V  [libjvm.so+0x57a89e]
C  [libpthread.so.0+0x5832]

Current CompileTask:
C2:3230  !   org.apache.jsp.com.common.press_jsp._jspService(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V (4433 bytes)

---------------  P R O C E S S  ---------------

Java Threads: ( => current thread )
  0x09a21400 JavaThread "http-8080-exec-904" daemon [_thread_in_native, id=17126, stack(SIGTERM: [libjvm.so+0x57aaf0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004
SIGQUIT: [libjvm.so+0x57aaf0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004

---------------  S Y S T E M  ---------------

OS:Red Hat Enterprise Linux Server release 5.5 (Tikanga)

uname:Linux 2.6.18-194.17.1.el5PAE #1 SMP Mon Sep 20 07:34:07 EDT 2010 i686
libc:glibc 2.5 NPTL 2.5
rlimit: STACK 10240k, CORE 0k, NPROC 114688, NOFILE 1024, AS infinity
load average:0.39 0.54 0.38

CPU:total 2 (2 cores per cpu, 1 threads per core) family 6 model 15 stepping 11, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3

Memory: 4k page, physical 6228576k(225096k free), swap 6974456k(6974352k free)

vm_info: Java HotSpot(TM) Server VM (17.0-b16) for linux-x86 JRE (1.6.0_21-b06), built on Jun 22 2010 01:04:46 by "java_re" with gcc 3.2.1-7a (J2SE release)

time: Fri Dec 10 14:01:06 2010
elapsed time: 79552 seconds

Thanks in advance,
Amit


问:
String doesn't appear in class when using constructor
I have made monopoly game in C# for a month already and i finished everything, i have only one problem from start. There are 2 forms. First one is where you select how many players are playing and typing their names. Second is the game, and i have tested, it passes player names from form1 to form2, but it seems like it doesn't apply it when i use constructor for class Player.
It looks like this
Form 2:

```<code>    public static string PlayerName1;
    public static string PlayerName2;
    public static string PlayerName3;
    public static string PlayerName4;
    public static Player Player1 = new Player(0, PlayerName1, 1, 10000);
    public static Player Player2 = new Player(1, PlayerName2, 1, 10000);
    public static Player Player3 = new Player(2, PlayerName3, 1, 10000);
    public static Player Player4 = new Player(3, PlayerName4, 1, 10000);
</code>```

As i said, PlayerName (all of them) works perfectly in form2 i tested it in label and it shows it right, so it isn't problem passing it from form1

Now the Player class code:

```<code>    public int ID;
    public string Name;
    public int Field;
    public int Money;
    public Player(int id, string name, int field, int money)
    {
        ID = id;
        Name = name;
        Field = field;
        Money = money;
    }
</code>```

So now this is where i use those values in form2:

```<code> private void update()
    {
        switch (turn)
        {
            case 0: PlayerName.Text = Player1.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;

            case 1: PlayerName.Text = Player2.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;

            case 2: PlayerName.Text = Player3.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;

            case 3: PlayerName.Text = Player4.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;
        }
    }
</code>```

PlayerName and Money in form2 are labels, Money label works perfectly with every "update" but PlayerName label is always empty. It is visible and it has text "Name" in it when i open Form2 but after first "update" it is empty and stays like that until i restart program. I also use Player.PlayerName in message boxes when paying rent from one player to another and it also doesn't work there... Hopefully someone can help me, i have to finish this by tomorrow, it's not like i'll get lesser grade for this but i want to everything be perfectly :)

答:
you should init string values.</p>

```<code>public static string PlayerName1 ="Bob";
</code>```

Body:
I have made monopoly game in C# for a month already and i finished everything, i have only one problem from start. There are 2 forms. First one is where you select how many players are playing and typing their names. Second is the game, and i have tested, it passes player names from form1 to form2, but it seems like it doesn't apply it when i use constructor for class Player.
It looks like this
Form 2:

    public static string PlayerName1;
    public static string PlayerName2;
    public static string PlayerName3;
    public static string PlayerName4;
    public static Player Player1 = new Player(0, PlayerName1, 1, 10000);
    public static Player Player2 = new Player(1, PlayerName2, 1, 10000);
    public static Player Player3 = new Player(2, PlayerName3, 1, 10000);
    public static Player Player4 = new Player(3, PlayerName4, 1, 10000);

As i said, PlayerName (all of them) works perfectly in form2 i tested it in label and it shows it right, so it isn't problem passing it from form1

Now the Player class code:

    public int ID;
    public string Name;
    public int Field;
    public int Money;
    public Player(int id, string name, int field, int money)
    {
        ID = id;
        Name = name;
        Field = field;
        Money = money;
    }

So now this is where i use those values in form2:

 private void update()
    {
        switch (turn)
        {
            case 0: PlayerName.Text = Player1.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;

            case 1: PlayerName.Text = Player2.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;

            case 2: PlayerName.Text = Player3.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;

            case 3: PlayerName.Text = Player4.Name;
            Money.Text = Convert.ToString(Player1.Money) + "$";
            break;
        }
    }

PlayerName and Money in form2 are labels, Money label works perfectly with every "update" but PlayerName label is always empty. It is visible and it has text "Name" in it when i open Form2 but after first "update" it is empty and stays like that until i restart program. I also use Player.PlayerName in message boxes when paying rent from one player to another and it also doesn't work there... Hopefully someone can help me, i have to finish this by tomorrow, it's not like i'll get lesser grade for this but i want to everything be perfectly :)

Body:
you should init string values.

public static string PlayerName1 ="Bob";