问:
How To Disable Uploading Within a Time Limit
How can I keep a client from uploading more after having uploaded something within a time limit?  Based on IP address.</p>

答:
Basing your disabling on the user's IP address is ineffective.  In addition to what Kel said, the client also may have a dynamic IP, or be using Tor.

Really the only way would be to force the user to identify him/herself in some way.  There are lots of options out there: Facebook, OpenID, Twitter, etc.  You could create a user account system for your site, but that would be much more inconvenient for the user; using an infrastructure that's already in place would be better.

As for the more technical side of things, basically you'll keep a database table of users that have uploaded files, and a timestamp column that holds the time that they uploaded.  You'll regularly traverse this table with a Cron job, and remove users that are older than a pre-defined threshold.

When a person attempts to upload, check if they're in the database.  If they are, they can't upload; if they aren't, they're good to go.


来源: stackexchange

问:
How to solve " TypeError: list indices must be integers or slices, not tuple " when comparing tuples in two different lists?
```<code>for x in no_dupes: #looks at tuple in list
    if x != totallist[x]: #checks when a tuple in no_dupes is not in totallist
        return "The graph violates the STC" #ends the function, because as soon as one tuple in no_dupes isn't in totallist, the graph violats the STC.
</code>```

I want to compare all the tuples from one list (in the list no_dupes) with another list (totallist), in order to see whether a tuple of a list in no_dupes is not in totallist.

This is how no_dupes looks like

This is how totallist looks like

How the error looks like

How can this error be solved?

答:
The Error is caused by the fact, that x is a tuple and you can not use a tuple as an index for the totallist. This has to be an integer.

The problem is avoided if you compare the tuples directly by looping through both list.

```<code>no_dupes = [(1,2), (3,4), (5,6)]
totallist = [(8,9), (7,8), (6,7), (5,6), (4,5), (3,4), (2,3), (1,2)]

for tup in no_dupes:
    found = False;
    for other_tup in totallist:
        if tup == other_tup:
            found = True
            break
    if found:
        print "Tuple", str(tup), "was found"
    else:
        print "Tuple", str(tup), "was not found"
</code>```

In this example the output is

```<code>Tuple (1, 2) was found
Tuple (3, 4) was found
Tuple (5, 6) was found
</code>```

ContentLicense: CC BY-SA 3.0

Body:
for x in no_dupes: #looks at tuple in list
    if x != totallist[x]: #checks when a tuple in no_dupes is not in totallist
        return "The graph violates the STC" #ends the function, because as soon as one tuple in no_dupes isn't in totallist, the graph violats the STC.

I want to compare all the tuples from one list (in the list no_dupes) with another list (totallist), in order to see whether a tuple of a list in no_dupes is not in totallist.

This is how no_dupes looks like

This is how totallist looks like

How the error looks like

How can this error be solved?

Body:
The Error is caused by the fact, that x is a tuple and you can not use a tuple as an index for the totallist. This has to be an integer.

The problem is avoided if you compare the tuples directly by looping through both list.

no_dupes = [(1,2), (3,4), (5,6)]
totallist = [(8,9), (7,8), (6,7), (5,6), (4,5), (3,4), (2,3), (1,2)]

for tup in no_dupes:
    found = False;
    for other_tup in totallist:
        if tup == other_tup:
            found = True
            break
    if found:
        print "Tuple", str(tup), "was found"
    else:
        print "Tuple", str(tup), "was not found"

In this example the output is

Tuple (1, 2) was found
Tuple (3, 4) was found
Tuple (5, 6) was found


问:
What's faster, an inline function call or a hashmap lookup
Say I have a class ClassToSort which I need to sort with std::sort() based on the values of val and secondVal (in ascending order of (val * 100) + secondVal).

```<code>class ClassToSort {
  private:
    int val;
    long int secondVal;
    int id;

  public:
    inline const int getVal() const { return val; }
    inline const long int getSecondVal() const { return secondVal; }
    inline const int getID() const { return id; }
};

std::vector<ClassToSort*> objs;
</code>```

Now, I have two ways to sort it, either precompute the value of (val * 100) + secondVal and store it in an std::unordered_map<int, long> valMap and refer to this map while sorting, or make function calls to getVal() and getSecondVal() each time while sorting (this will cause the number of function calls to double). Here are the two options:

```<code>std::sort(objs.begin(), objs.end(),
         [&](const ClassToSort* first, const ClassToSort* second) {
          return valMap[first->getID()] < valMap[second->getID()];
         });
</code>```

and

```<code>std::sort(objs.begin(), objs.end(),
         [](const ClassToSort* first, const ClassToSort* second) {
          return (first->getVal() * 100 + first->getSecondVal()) <
                 (second->getVal() * 100 + second->getSecondVal());
         });
</code>```

It is clear that the second option will not only call getter functions for each object twice, but also do the same computation twice. Intuitively, I would think that for large number of inputs, hashtable lookup would be faster than when the number of function calls is more, along with recalculation. Is my understanding correct?

答:
Direct functions calls are inlined automatically most of the time.

The complexity in your example isn’t that you call »the getter« twice but that you do your calculation several times – for all comparisons with a specific element.

Using unordered_map you also have to create the hash table first.

Have a look at these benchmarks.

Using the members directly vs a getter function makes no difference.

The hash lookups are 10 times as slow as doing the calculation for each comparison.

If you have to sort several times it may be useful to keep the calculated value (cache) by storing it as a pair (as a cheaper alternative to a hashmap).

Using pointers to your class instead of values may change the performance (for the worse) but it shouldn’t change the observed differences.

Body:
Say I have a class ClassToSort which I need to sort with std::sort() based on the values of val and secondVal (in ascending order of (val * 100) + secondVal).

class ClassToSort {
  private:
    int val;
    long int secondVal;
    int id;

  public:
    inline const int getVal() const { return val; }
    inline const long int getSecondVal() const { return secondVal; }
    inline const int getID() const { return id; }
};

std::vector<ClassToSort*> objs;

Now, I have two ways to sort it, either precompute the value of (val * 100) + secondVal and store it in an std::unordered_map<int, long> valMap and refer to this map while sorting, or make function calls to getVal() and getSecondVal() each time while sorting (this will cause the number of function calls to double). Here are the two options:

std::sort(objs.begin(), objs.end(),
         [&](const ClassToSort* first, const ClassToSort* second) {
          return valMap[first->getID()] < valMap[second->getID()];
         });

and

std::sort(objs.begin(), objs.end(),
         [](const ClassToSort* first, const ClassToSort* second) {
          return (first->getVal() * 100 + first->getSecondVal()) <
                 (second->getVal() * 100 + second->getSecondVal());
         });

It is clear that the second option will not only call getter functions for each object twice, but also do the same computation twice. Intuitively, I would think that for large number of inputs, hashtable lookup would be faster than when the number of function calls is more, along with recalculation. Is my understanding correct?


问:
My "if statements" do not run, even though the parameters are true
Ok, so my code will compile as if there are no errors, but then the code that should be executed will not truly run. Please help.

```<code>public static void newGameCheck()   {
    String newCharacter = scan.next();
    if (newCharacter.equals("New game"))    {
    //more code here, but it does not get executed for some reason
    }
</code>```

And another example is here:

```<code>public static void warriorTurn()    {
    if (warriorAlive==true) {
        etut.choosingTarget();
        int target= scan.nextInt();
        System.out.println("Now type in which ability you want him to use, make sure to use capitals");
        warrior_Weapons_and_Abilities();

String ability= scan.next();
            if (ability.equals("Anduril, Foe of Terror"))   {
                int damage= 100+((int) (Math.random()*50));
                etut.loseHealth(target, damage);
                mana2=mana2-0;
                etut.displayHealth(target);
            }
            else if (ability.equals("Aethereal Blades"))    {

int damage= 250+((int) (Math.random()*100));
                etut.loseHealth(target, damage);
                mana2=mana2-2;
                etut.displayHealth(target);
            }
            else if (ability.equals("Potion"))  {
            health2=health2+100;
            mana=mana-0;
            etut.displayHealth(target);

    }
</code>```

Here^, whenever I type in the ability name, the code still will not execute

答: The next() method on Scanner returns the next token.  It's probably just returning the first word, unless you have the delimiter set to newline.</p>

Body:
Ok, so my code will compile as if there are no errors, but then the code that should be executed will not truly run. Please help.

public static void newGameCheck()   {
    String newCharacter = scan.next();
    if (newCharacter.equals("New game"))    {
    //more code here, but it does not get executed for some reason
    }

And another example is here:

public static void warriorTurn()    {
    if (warriorAlive==true) {
        etut.choosingTarget();
        int target= scan.nextInt();
        System.out.println("Now type in which ability you want him to use, make sure to use capitals");
        warrior_Weapons_and_Abilities();

String ability= scan.next();
            if (ability.equals("Anduril, Foe of Terror"))   {
                int damage= 100+((int) (Math.random()*50));
                etut.loseHealth(target, damage);
                mana2=mana2-0;
                etut.displayHealth(target);
            }
            else if (ability.equals("Aethereal Blades"))    {

int damage= 250+((int) (Math.random()*100));
                etut.loseHealth(target, damage);
                mana2=mana2-2;
                etut.displayHealth(target);
            }
            else if (ability.equals("Potion"))  {
            health2=health2+100;
            mana=mana-0;
            etut.displayHealth(target);

    }

Here^, whenever I type in the ability name, the code still will not execute


问:
How can I attach custom behaviour to a double click in jsTree?
I'm using the jsTree jQuery plugin and want to execute code when the user double clicks a node.

I can't seem to get it to work. I found some documentation on a ondblclk event but it doesn't fire.

```<code>    browser.jstree(
            {
                plugins: ["themes", "json_data", "ui", "cookies"],
                callback:
                {
                    ondblclk: function (node, tree) {
                        if (!thisReportBrowserthis._isFoldersOnly) {
                            var f = node;
                        }
                    }
                }
            }
        );
</code>```

How can I handle double click events with jstree?

答:
The above answers do not work on the latest version of jstree (which is 3.3.4)

This cost me a day of mind bending work but I finally got it.
Here is working doubleclick to Edit code:

$('#tree1').bind("dblclick.jstree", function (event) {
  var tree = $(this).jstree();
  var node = tree.get_node(event.target);
  tree.edit(node);
});```

and here is a working jsfiddle.

ContentLicense: CC BY-SA 2.5

Body:
I'm using the jsTree jQuery plugin and want to execute code when the user double clicks a node.

I can't seem to get it to work. I found some documentation on a ondblclk event but it doesn't fire.

    browser.jstree(
            {
                plugins: ["themes", "json_data", "ui", "cookies"],
                callback:
                {
                    ondblclk: function (node, tree) {
                        if (!thisReportBrowserthis._isFoldersOnly) {
                            var f = node;
                        }
                    }
                }
            }
        );

How can I handle double click events with jstree?

Body:
The above answers do not work on the latest version of jstree (which is 3.3.4)

This cost me a day of mind bending work but I finally got it.
Here is working doubleclick to Edit code:

$('#tree1').bind("dblclick.jstree", function (event) {
  var tree = $(this).jstree();
  var node = tree.get_node(event.target);
  tree.edit(node);
});

and here is a working jsfiddle.


问:
Python 3.4/Ftputil 3.4 only runs a single command then exits
I'm currently making the base of a personal ftp program, using ftputil 3.4 and python 3.4, ive successfully gotten it to log in and i can run follow up commands in the python interpreter but after a single command it goes back to the main interpreter. as an example if i login, then run list, then it lists once, if i were to try it again it returns the result of typing list in pythons idle shell.

```<code>import ftputil

User = input()
Password = input()
ftp = ftputil.FTPHost('ip', User, Password)

names = ftp.listdir(ftp.curdir)
print(names)

userinput = input()
if userinput == 'list':
print(names)

#not yet implemented download function
#if userinput == 'get':
#   ftp.
</code>```

I'm looking for a way to keep the program from 'closing' so that i can continue running commands to and from the ftp server

答:
You need to tell python you want to repeat the section of the code. In this case, a while loop probably would do the trick.

```<code>import ftputil
# ...
while True:
    userinput = input()
    # ...
</code>```

This is an infinite loop, so to kill it you'll probably have to press Ctrl+C. Alternatively, if you want to implement an exit command you could do so by doing something like the following;

```<code>while userinput != "exit":
</code>```

Body:
I'm currently making the base of a personal ftp program, using ftputil 3.4 and python 3.4, ive successfully gotten it to log in and i can run follow up commands in the python interpreter but after a single command it goes back to the main interpreter. as an example if i login, then run list, then it lists once, if i were to try it again it returns the result of typing list in pythons idle shell.

import ftputil

User = input()
Password = input()
ftp = ftputil.FTPHost('ip', User, Password)

names = ftp.listdir(ftp.curdir)
print(names)

userinput = input()
if userinput == 'list':
print(names)

#not yet implemented download function
#if userinput == 'get':
#   ftp.

I'm looking for a way to keep the program from 'closing' so that i can continue running commands to and from the ftp server

Body:
You need to tell python you want to repeat the section of the code. In this case, a while loop probably would do the trick.

import ftputil
# ...
while True:
    userinput = input()
    # ...

This is an infinite loop, so to kill it you'll probably have to press Ctrl+C. Alternatively, if you want to implement an exit command you could do so by doing something like the following;

while userinput != "exit":


问:
Wordpress WooCommerce Checkout - SyntaxError: Unexpected token < in JSON at position 0
One of our Wordpress sites is facing an issue on the checkout page of WooCommerce. When "Place Order" button is clicked an error triggers:

```<code>SyntaxError: Unexpected token < in JSON at position 0
</code>```

This is the error that is shown in the console:

```<code><br />
<b>Fatal error</b>:  Call to a member function update_status() on
boolean in <b>/home/public_html/wp-
content/plugins/woocommerce/includes/gateways/bacs/class-wc-gateway-
bacs.php</b> on line <b>346</b><br />
</code>```

I have disabled all plugins except WooCommerce and the problem persists;

I have tried default themes like TwentyThirteen and the problem persists;

WooCommerce is up-to-date (Version 3.2.3);

We have COD (Cash on Delivery) and Bank Transfer as options for payments.

Any thoughts?

答:
After debugging the code, I figured out that my problem was somewhere in the database, with the ID of the order that wasn't saved properly (The value passed was always 0). My guess is that some plugin messed up my database.

The auto-increment was off in my database, so the ID of the order couldn't be saved correctly, thus resulting the above error mentioned in the 1st post.

The solution was to fix the database, by adding auto-increment where it was needed and delete all the entries with 0 as ID in table wp_posts.

Body:
One of our Wordpress sites is facing an issue on the checkout page of WooCommerce. When "Place Order" button is clicked an error triggers:

SyntaxError: Unexpected token < in JSON at position 0

This is the error that is shown in the console:

Fatal error:  Call to a member function update_status() on
boolean in /home/public_html/wp-
content/plugins/woocommerce/includes/gateways/bacs/class-wc-gateway-
bacs.php on line 346

I have disabled all plugins except WooCommerce and the problem persists;

I have tried default themes like TwentyThirteen and the problem persists;

WooCommerce is up-to-date (Version 3.2.3);

We have COD (Cash on Delivery) and Bank Transfer as options for payments.

Any thoughts?


问:
How can I implement search Objective-c?
I have a record like this.

FirstName - LastName -    PhoneNo -  Address  -      Designation

A         -    Mick     -   789367789 -    New york -    Professor

B       -     Jossef   -    534647458     -     USA     -        Doctor

C       -     Sha      -    342576765    -      USA     -        Doctor

D      -      Gee     -     535346457 -     USA     -        Business Man

......Like this

I am displaying one FirstName in UITableView with UISearchBar. Search is working fine it filters data according the keyword your typing in the SearchBar but suppose you are typing M it list all the items of M and after then when i click on the first item of M, it displays the Details of A rather then M on the next View.

I think you can understand my problem.

How can i resolve this how to pass multiple values in the Next view corresponding to record.?

Thanks,

This function i took from the same code of TableView(apple sample code with searchbar ).
and i modified this according to my logic.

```<code> - (void) searchTableView
{

    NSString *searchText = searchBar.text;
    NSMutableArray *searchArray = [[NSMutableArray alloc] init];

    NSInteger TotalNoOfRecords=[self.SearchtableDataSource count];
    for (int i=0;i<TotalNoOfRecords;i++)
    {   NSDictionary *dictionary = [self.SearchtableDataSource objectAtIndex:i];
        NSArray *array = [dictionary objectForKey:@"Title"];
        NSString *arrayID=  [dictionary objectForKey:@"ID"];
        NSLog(@"Testing - Id-%d",arrayID);
        [searchArrayID addObject:arrayID];
        [searchArray addObject:array];
    }

    for (NSString *sTemp in searchArray)
    {

        NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];

        if (titleResultsRange.length > 0)
        {
                [copyListOfItems addObject:sTemp];
        }
    }

    [searchArray release];
    searchArray = nil;
 }
</code>```

This is my didSelectRowAtIndexPath code i know this need modification but i don't know how?

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dictionary = [self.SearchtableDataSource objectAtIndex:indexPath.row];
    FirstName=  [dictionary objectForKey:@"FirstName"];
    LastName=[dictionary objectForKey:@"LastName"];
    DetailViewController *ivc = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:[NSBundle mainBundle]];
    ivc.FirstName = FirstName;
    ivc.LastName=LastName;
    ivc.Title=[dictionary objectForKey:@"Details of Person"];
    [self.navigationController pushViewController:ivc animated:YES];
    [ivc release];
}
</code>```

Please help me out...

Thanks

答:
Check that you are retrieving the value from copyListOfItems in -didSelectRowAtIndexPath.

EDIT:

You should clearly understand the logic first. SearchedTableDatasource contains the tableViews complete set of data to be loaded in the tableview.  copyListofItems contains filtered items. So in didSelectRowAtIndexPath you should code as follows,

```<code>if(searching==YES)

{

//retrieve the values from copyListofItems array

}

else

{

//retrieve the values from SearchedTableDatasource array

}
</code>```

And also you are using a void function for searching, if so declare the copyListofItems array as global, or else make the function to return a NSMutableArray instance.

Title: How can I implement search Objective-c?

Body:
I have a record like this.

FirstName - LastName -    PhoneNo -  Address  -      Designation

A         -    Mick     -   789367789 -    New york -    Professor

B       -     Jossef   -    534647458     -     USA     -        Doctor

C       -     Sha      -    342576765    -      USA     -        Doctor

D      -      Gee     -     535346457 -     USA     -        Business Man

......Like this

I am displaying one FirstName in UITableView with UISearchBar. Search is working fine it filters data according the keyword your typing in the SearchBar but suppose you are typing M it list all the items of M and after then when i click on the first item of M, it displays the Details of A rather then M on the next View.

I think you can understand my problem.

How can i resolve this how to pass multiple values in the Next view corresponding to record.?

Thanks,

This function i took from the same code of TableView(apple sample code with searchbar ).
and i modified this according to my logic.

 - (void) searchTableView
{

    NSString *searchText = searchBar.text;
    NSMutableArray *searchArray = [[NSMutableArray alloc] init];

    NSInteger TotalNoOfRecords=[self.SearchtableDataSource count];
    for (int i=0;i<TotalNoOfRecords;i++)
    {   NSDictionary *dictionary = [self.SearchtableDataSource objectAtIndex:i];
        NSArray *array = [dictionary objectForKey:@"Title"];
        NSString *arrayID=  [dictionary objectForKey:@"ID"];
        NSLog(@"Testing - Id-%d",arrayID);
        [searchArrayID addObject:arrayID];
        [searchArray addObject:array];
    }

    for (NSString *sTemp in searchArray)
    {

        NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];

        if (titleResultsRange.length > 0)
        {
                [copyListOfItems addObject:sTemp];
        }
    }

    [searchArray release];
    searchArray = nil;
 }

This is my didSelectRowAtIndexPath code i know this need modification but i don't know how?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dictionary = [self.SearchtableDataSource objectAtIndex:indexPath.row];
    FirstName=  [dictionary objectForKey:@"FirstName"];
    LastName=[dictionary objectForKey:@"LastName"];
    DetailViewController *ivc = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:[NSBundle mainBundle]];
    ivc.FirstName = FirstName;
    ivc.LastName=LastName;
    ivc.Title=[dictionary objectForKey:@"Details of Person"];
    [self.navigationController pushViewController:ivc animated:YES];
    [ivc release];
}

Please help me out...

Thanks

Body:
Check that you are retrieving the value from copyListOfItems in -didSelectRowAtIndexPath.

EDIT:

You should clearly understand the logic first. SearchedTableDatasource contains the tableViews complete set of data to be loaded in the tableview.  copyListofItems contains filtered items. So in didSelectRowAtIndexPath you should code as follows,

if(searching==YES)

{

//retrieve the values from copyListofItems array

}

else

{

//retrieve the values from SearchedTableDatasource array

}

And also you are using a void function for searching, if so declare the copyListofItems array as global, or else make the function to return a NSMutableArray instance.


问:
Load data in view in Laravel
I have a simple controller function that fetch all records from db. but when i am trying to show all these records it show nothing. In fact it shows me hard coded foreach loop like this.

```<code> @foreach ($compactData as $value) {{ $value->Name }} @endforeach
</code>```

this is my contoller function.

```<code>public function showallProducts()
{
    $productstock = Product::all()->stocks;
    $productoldprice = Product::all()->OldPrices;
    $productcurrentprice = Product::all()->CurrentPrice;
    $compactData=array('productstock', 'productoldprice', 'productcurrentprice');
    return view('welcome', compact($compactData));
}
</code>```

this is my view

```<code>       <!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>

 </head>
 <body>
    <div class="flex-center position-ref full-height">

        <div class="content">
            <div class="title m-b-md">
                Laravel
            </div>

            <div class="title m-b-md">
                All products
            </div>

            <table>

                <tbody>
                @foreach ($compactData as $value)
                    {{ $value->Name }}

                @endforeach

                </tbody>

            </table>
        </div>
    </div>
</body>
</code>```

 why it is behaving like this. any solution?? I am using phpstorm version 17. Is their any setting issue to run project because what ever project I ran it gives me the only page which i ran with only html?
My route is.

```<code>   Route::get('/', function () {

    $action = 'showallProducts';
    return App::make('ProductController')->$action();
 });
</code>```

答:
Have you checked your $compactData variable? Please dd($compactData) to see what it contains.

Problem 1

You are accessing a relational property as a property of Eloquent collection, like this:

Product::all()->stocks

which is not correct. Because the Collection object doesn't have the property stocks but yes the Product object might have a stocks property. Please read the Laravel documentation about Collection.

Problem 2

$compactData = array('productstock', 'productoldprice', 'productcurrentprice');

This line creating an array of 4 string, plain string not variable. So, your $compactData is containing an array of 4 string. If you want to have a variable with associative array then you need to do the following:

$compactData = compact('productstock', 'productoldprice', 'productcurrentprice');

Problem 3

```<code>return view('welcome', compact($compactData));
</code>```

Here you are trying to pass the $compactDate to the welcome view but unfortunately compact() function doesn't accept variable but the string name of that variable as I have written in Problem 2. So, it should be:

```<code>return view('welcome', compact('compactData'));
</code>```

Problem 4

Finally, in the blade you are accessing each element of the $compactData data variable and print them as string which might be an object.

Title: Load data in view in Laravel

Body:
I have a simple controller function that fetch all records from db. but when i am trying to show all these records it show nothing. In fact it shows me hard coded foreach loop like this.

 @foreach ($compactData as $value) {{ $value->Name }} @endforeach

this is my contoller function.

public function showallProducts()
{
    $productstock = Product::all()->stocks;
    $productoldprice = Product::all()->OldPrices;
    $productcurrentprice = Product::all()->CurrentPrice;
    $compactData=array('productstock', 'productoldprice', 'productcurrentprice');
    return view('welcome', compact($compactData));
}

this is my view

       <!doctype html>
getLocale() }}">

                Laravel

                All products

                @foreach ($compactData as $value)
                    {{ $value->Name }}

                @endforeach

 why it is behaving like this. any solution?? I am using phpstorm version 17. Is their any setting issue to run project because what ever project I ran it gives me the only page which i ran with only html?
My route is.

   Route::get('/', function () {

    $action = 'showallProducts';
    return App::make('ProductController')->$action();
 });

Body:
Have you checked your $compactData variable? Please dd($compactData) to see what it contains.

Problem 1

You are accessing a relational property as a property of Eloquent collection, like this:

Product::all()->stocks

which is not correct. Because the Collection object doesn't have the property stocks but yes the Product object might have a stocks property. Please read the Laravel documentation about Collection.

Problem 2

$compactData = array('productstock', 'productoldprice', 'productcurrentprice');

This line creating an array of 4 string, plain string not variable. So, your $compactData is containing an array of 4 string. If you want to have a variable with associative array then you need to do the following:

$compactData = compact('productstock', 'productoldprice', 'productcurrentprice');

Problem 3

return view('welcome', compact($compactData));

Here you are trying to pass the $compactDate to the welcome view but unfortunately compact() function doesn't accept variable but the string name of that variable as I have written in Problem 2. So, it should be:

return view('welcome', compact('compactData'));

Problem 4

Finally, in the blade you are accessing each element of the $compactData data variable and print them as string which might be an object.


问:
Code for making a triangle not working
So I am trying to make a code for school where it makes a hollow triangle with a symbol input and a maximum number of symbol input. Instead of creating a triangle, it is instead making a vertical line of the symbols, so with an input of A and 9, instead of this:

```<code>    A
   A A
  A   A
 A     A
AAAAAAAAA
</code>```

It Gives me a long line of A's

Here is my code

```<code>def SetValues():
    global symbol
    symbol = input("Enter Symbol: ")
    InputMaxNumberOfSymbols()
    global NumberOfSpaces
    NumberOfSpaces = (MaxNumberOfSymbols - 1) / 2
    global NumberOfSymbols
    NumberOfSymbols = 1

def InputMaxNumberOfSymbols():
    global MaxNumberOfSymbols
    MaxNumberOfSymbols = int(input("Max Number of symbols: "))
    while MaxNumberOfSymbols % 2 == 0:
        MaxNumberOfSymbols = int(input("Max Number of symbols: "))

def OutputSpaces():
    for i in range(0, int(NumberOfSpaces)):
        print(" ")

def OutputSymbols():
    for i in range(0, NumberOfSymbols):
        print(symbol)
        print("\n")

def AdjustValuesForNextRow():
    global NumberOfSpaces
    NumberOfSpaces -= 1
    global NumberOfSymbols
    NumberOfSymbols += 2

#Main Code
SetValues()
while not NumberOfSymbols > MaxNumberOfSymbols:
    OutputSpaces()
    OutputSymbols()
    AdjustValuesForNextRow()
</code>```

答:
edited since a commenter mentioned it was for python 3

one of the issues that you are facing is that print statements automatically move to the next line. Change print statements from

```<code>print(something)
</code>```

to

```<code>print(something, end = "")
</code>```

note the use of the comma after the print

Title: Code for making a triangle not working

Body:
So I am trying to make a code for school where it makes a hollow triangle with a symbol input and a maximum number of symbol input. Instead of creating a triangle, it is instead making a vertical line of the symbols, so with an input of A and 9, instead of this:

    A
   A A
  A   A
 A     A
AAAAAAAAA

It Gives me a long line of A's

Here is my code

def SetValues():
    global symbol
    symbol = input("Enter Symbol: ")
    InputMaxNumberOfSymbols()
    global NumberOfSpaces
    NumberOfSpaces = (MaxNumberOfSymbols - 1) / 2
    global NumberOfSymbols
    NumberOfSymbols = 1

def InputMaxNumberOfSymbols():
    global MaxNumberOfSymbols
    MaxNumberOfSymbols = int(input("Max Number of symbols: "))
    while MaxNumberOfSymbols % 2 == 0:
        MaxNumberOfSymbols = int(input("Max Number of symbols: "))

def OutputSpaces():
    for i in range(0, int(NumberOfSpaces)):
        print(" ")

def OutputSymbols():
    for i in range(0, NumberOfSymbols):
        print(symbol)
        print("\n")

def AdjustValuesForNextRow():
    global NumberOfSpaces
    NumberOfSpaces -= 1
    global NumberOfSymbols
    NumberOfSymbols += 2

#Main Code
SetValues()
while not NumberOfSymbols > MaxNumberOfSymbols:
    OutputSpaces()
    OutputSymbols()
    AdjustValuesForNextRow()

Body:
edited since a commenter mentioned it was for python 3

one of the issues that you are facing is that print statements automatically move to the next line. Change print statements from

print(something)

to

print(something, end = "")

note the use of the comma after the print


问:
Having an issue with a loop in Java. Explanation in description
I am creating a program that counts the number of vowels, consonants, spaces, and punctuation in a string. Before moving on to anything else, I'm making sure that the vowel checker works. I've created a loop that seems to work logically, as I've run it through a java visualizer, and everything checks out. But, I get an error when I run it through the BlueJ IDE. It says: java.lang.StringIndexOutOfBoundsException: String index out of range. I have no idea what the issue is, and I would appreciate any and all help. This is a link to the java visualizer if anyone wants to test it for themselves, and I have the code posted below:</p>

```<code>//**************************************************************
 // Testing program for VCP program (temporary).
 //
 // @aaron_ford
 // @version_1.0_11.9.17
 //**************************************************************
public class VCPTest
{
    public static void main(String[] args)
    {
        System.out.println("Enter a string.");
        String user_str = "a vowel is here";
        System.out.println("You entered: " + user_str);

        char vowels[] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};

        // counter variables
        int v_counter = 0;
        int c_counter = 0;
        int s_counter = 0;
        int p_counter = 0;
        int count = 0;
        int str_compare = user_str.charAt(count);

        for (; count < str_compare; count++)
        {
            str_compare = user_str.charAt(count);
            for (int a:vowels)
            {
                if (a == str_compare)
                {
                    v_counter++;
                }
            }
        }

        System.out.println("There are " + v_counter + " vowels.");
        System.out.println("There are " + c_counter + " consonants.");
        System.out.println("There are " + s_counter + " spaces.");
        System.out.println("There are " + p_counter + " punctuation marks.");
    }
}
</code>```

答:
The problem is with your "for" loop. You check if count value is less than str_compare value (which is a numeric representation of character from given string). I think this is not what you were expecting. I would suggest few little modifications - it provides checking character from given string ( str_compare = user_str.charAt(count); ) and after every loop count value is being increased to check next character from this string. In every loop there is validation made, to check whether the end of string is currently reached (count < user_str.length())

```<code>for (count = 0; count < user_str.length(); count++)
        {
            str_compare = user_str.charAt(count);
            for (int a : vowels)
            {
                if (a == str_compare)
                {
                    v_counter++;
                }
            }
        }
</code>```

And now the output of your program looks better:

```<code>Enter a string.
You entered: a vowel is here
There are 6 vowels.
There are 0 consonants.
There are 0 spaces.
</code>```

Body:
I am creating a program that counts the number of vowels, consonants, spaces, and punctuation in a string. Before moving on to anything else, I'm making sure that the vowel checker works. I've created a loop that seems to work logically, as I've run it through a java visualizer, and everything checks out. But, I get an error when I run it through the BlueJ IDE. It says: java.lang.StringIndexOutOfBoundsException: String index out of range. I have no idea what the issue is, and I would appreciate any and all help. This is a link to the java visualizer if anyone wants to test it for themselves, and I have the code posted below:

//**************************************************************
 // Testing program for VCP program (temporary).
 //
 // @aaron_ford
 // @version_1.0_11.9.17
 //**************************************************************
public class VCPTest
{
    public static void main(String[] args)
    {
        System.out.println("Enter a string.");
        String user_str = "a vowel is here";
        System.out.println("You entered: " + user_str);

        char vowels[] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};

        // counter variables
        int v_counter = 0;
        int c_counter = 0;
        int s_counter = 0;
        int p_counter = 0;
        int count = 0;
        int str_compare = user_str.charAt(count);

        for (; count < str_compare; count++)
        {
            str_compare = user_str.charAt(count);
            for (int a:vowels)
            {
                if (a == str_compare)
                {
                    v_counter++;
                }
            }
        }

        System.out.println("There are " + v_counter + " vowels.");
        System.out.println("There are " + c_counter + " consonants.");
        System.out.println("There are " + s_counter + " spaces.");
        System.out.println("There are " + p_counter + " punctuation marks.");
    }
}

Body:
The problem is with your "for" loop. You check if count value is less than str_compare value (which is a numeric representation of character from given string). I think this is not what you were expecting. I would suggest few little modifications - it provides checking character from given string ( str_compare = user_str.charAt(count); ) and after every loop count value is being increased to check next character from this string. In every loop there is validation made, to check whether the end of string is currently reached (count < user_str.length())

for (count = 0; count < user_str.length(); count++)
        {
            str_compare = user_str.charAt(count);
            for (int a : vowels)
            {
                if (a == str_compare)
                {
                    v_counter++;
                }
            }
        }

And now the output of your program looks better:

Enter a string.
You entered: a vowel is here
There are 6 vowels.
There are 0 consonants.
There are 0 spaces.


问:
Loop for generating lottery numbers
I am working with R and using the expression sort(sample(1:60,6,replace=FALSE)) for generating 6 numbers between 1 and 60, without replacement...

I would like to create a loop using FOR statements that allow to generate n different samples, using the logic above.

Any suggestion about how to build this loop?

答:
You can use the rerun function that returns a list with the result that you need

```<code>library(purrr)

rerun(.n = 1000, sort(sample(1:60, 6, replace = FALSE))) %>%
  unique()
</code>```

Title: Loop for generating lottery numbers

Body:
You can use the rerun function that returns a list with the result that you need

library(purrr)

rerun(.n = 1000, sort(sample(1:60, 6, replace = FALSE))) %>%
  unique()


问:
ARM Assembly TBB Instruction - how does jumping work?
so I'm trying to understand how TBB works for switch statements in Assembly. I see how it's written in the textbook/online manual, but I don't understand how the offsets work in the branch table. How does it go from branch table to instruction? How are labels subtracted to get the correct offset, and why divide by 2?

In my textbook it says

The memory address of the instruction to which the program should
  branch is calculated as follows:

  target = PC + 4 + (
  2*BranchTable[r0] )

Where r0 is the counter containing the offset within the branch table. At TBB, PC already points to the next instruction (branch table, which is PC = PC+4). The branch table supposedly loads a second offset to the proper instruction (2*BranchTable[r0]). From what I've seen in my textbook and online, the branch table label is subtracted from the instruction label. This should give an offset of something like 4n. Why divide by 2? Thank you!

Edit: Did some math

So I did some math and it turns out that the offset in the branch table is [ (label2 - label1)/2]. Plugged into the equation earlier gives target = PC + 4 + (label 2 - label). This makes sense, but I'd still like to know if anyone has the reason why, or if my logic is wrong - why is TBB set up to divide by 2/multiply the difference by 2?

答:
TBB / TBH are only available in Thumb2 mode.

ARM Thumb2 instructions always start on an even address.  Being able to branch to PC+4 + {0, 2, 4, 6, 8, ..., 508, 510} is more useful than

PC+4 + {0, 1, 2, 3, 4, ..., 254, 255 }, because all the odd offsets are useless.  As @Jester explained in the first comment, multiplying by 2 gives you twice the range from one-byte offsets with no loss in flexibility.

ARM's designers could have designed it to always multiply by 4, but 512B is generally enough range, and it would sometimes require padding the code blocks to be multiples of 4 bytes long.  If larger offsets are needed, TBH uses half-word 16-bit offsets (still multiplied by 2).

Here's a real example of a jump table using TBB, with the raw hex and commented disassembly working out the math of how each branch target was reached  (like

case 3: (0x3164 + 0x9 * 2)):
Confused by TBB in a section of ARM disassembly


问:
Why aren't there quotes in sys.argv when they were used at the command line?
Is this a bug?

```<code>#!/usr/bin/env python3.6
# filename: tmp.py
import sys

print(sys.argv)
</code>```

Invoked:

```<code>python tmp.py find . -name '*.py'
</code>```

Actual output:

```<code>['tmp.py', 'find', '.', '-name', '*.py']
</code>```

Expected output:

```<code>['tmp.py', 'find', '.', '-name', "'*.py'"]
</code>```

Note the lack of quotations within the actual output.

答:
The shell is responsible for breaking down the command it's running into a list of C strings. Those strings are then passed to the program being run.

In the example:

```<code>python tmp.py find . -name '*.py'
</code>```

...the argument list a correctly-implemented shell will generate for the argv element of the execve syscall would look (in C syntax) like:

char[][]{ "python", "tmp.py", "find", ".", "-name", "*.py", NULL }
```

When Python runs, it doesn't know what the original command was: It has no way of knowing if you typed '*.py' or \*.py or any other thing; it only sees the argument list the shell handed off to the operating system.

Body:
Is this a bug?

#!/usr/bin/env python3.6
# filename: tmp.py
import sys

print(sys.argv)

Invoked:

python tmp.py find . -name '*.py'

Actual output:

['tmp.py', 'find', '.', '-name', '*.py']

Expected output:

['tmp.py', 'find', '.', '-name', "'*.py'"]

Note the lack of quotations within the actual output.

Body:
The shell is responsible for breaking down the command it's running into a list of C strings. Those strings are then passed to the program being run.

In the example:

python tmp.py find . -name '*.py'

...the argument list a correctly-implemented shell will generate for the argv element of the execve syscall would look (in C syntax) like:

char[][]{ "python", "tmp.py", "find", ".", "-name", "*.py", NULL }

When Python runs, it doesn't know what the original command was: It has no way of knowing if you typed '*.py' or \*.py or any other thing; it only sees the argument list the shell handed off to the operating system.


问:
Any solutions to capture data within a website automatically?
I want to write an application to capture data from a website, and the website are using ajax to retrieve data from server.

Is there any solutions that I can get those data conveniently and store into my own database ? As the data in that website is dynamic, historical data will disappear, and I want to keep track them.

Please suggest any solutions, thanks in advance !

答:
Selenium RC can do this with a little bit of work.\

http://seleniumhq.org/


问:
Laravel 5.2.11, sessions are not working, session cookie not being set
I'm new to Laravel, I have learned about the models, views, blade, controllers and routes and how they work together. So far everything has been working smoothly.

I'm having trouble with sessions though.

When I use the AuthController that comes with Laravel and hit auth/register with a POST request, the data for the user that I register does get inserted into the users table (using mysql) and I do get back a response with the "Location" header redirecting to / like it does out of the box. It redirects like it should. But in the same response there is no "Set-Cookie" header set/sent. The session part of Laravel is not working properly for me. This is the same for a POST to auth/login, it authenticates properly and redirects to the profile page but no session cookie is sent back in the response.

I'm using:

Laravel 5.2.11

PHP 5.5.9

xubuntu 14.04 (Ubuntu)

Linux kernel 3.19.0-42-generic

Composer 1.0

All of the php modules that Laravel requires are installed. I'm running the app with php's built in web server. I run that with sudo. The exact command I run is this:

```<code>sudo php -S localhost:8888 -t public/
</code>```

All routes are being responded to properly.

I have tried both ways of installing Laravel that the installation docs recommend, through the laravel executable and composer create-project. Still no cookies set either way. I have made all the files and directories of the laravel project mod 777. The app key is set in .env if that makes any difference.

The config/session.php file is using the file driver for the session.
There are no session files in the storage/framework/sessions directory after setting a session.

When I try setting a session myself with the session function like it states in the docs:

```<code>session(['sesskey' => 'somevalue']);
</code>```

Again no "Set-Cookie" header is sent in the response and no session file is created. There are no error messages reported back either I should add.

When I do set a session key with the session function like above I can get that value back however and echo it back to the browser like so:

```<code>echo session('sesskey');
</code>```

So it does seem to save it at least in php's memory.

When I try setting a cookie using the withCookie method, I do get the proper response with the Set-Cookie header set:

```<code>return response()->view('welcome')->withCookie(cookie("test", "val" , 3600));
</code>```

I tried going down the illuminate rabbit hole to see if I could find a problem but that is a bit over my head atm.

Any help would be much appriciated, thanks!

答:
use middleware for the request \Illuminate\Session\Middleware\StartSession::class</p>

```<code>Route::group(['middleware' => [\Illuminate\Session\Middleware\StartSession::class]], function () {

});
</code>```

Body:
I'm new to Laravel, I have learned about the models, views, blade, controllers and routes and how they work together. So far everything has been working smoothly.

I'm having trouble with sessions though.

When I use the AuthController that comes with Laravel and hit auth/register with a POST request, the data for the user that I register does get inserted into the users table (using mysql) and I do get back a response with the "Location" header redirecting to / like it does out of the box. It redirects like it should. But in the same response there is no "Set-Cookie" header set/sent. The session part of Laravel is not working properly for me. This is the same for a POST to auth/login, it authenticates properly and redirects to the profile page but no session cookie is sent back in the response.

I'm using:

Laravel 5.2.11

PHP 5.5.9

xubuntu 14.04 (Ubuntu)

Linux kernel 3.19.0-42-generic

Composer 1.0

All of the php modules that Laravel requires are installed. I'm running the app with php's built in web server. I run that with sudo. The exact command I run is this:

sudo php -S localhost:8888 -t public/

All routes are being responded to properly.

I have tried both ways of installing Laravel that the installation docs recommend, through the laravel executable and composer create-project. Still no cookies set either way. I have made all the files and directories of the laravel project mod 777. The app key is set in .env if that makes any difference.

The config/session.php file is using the file driver for the session.
There are no session files in the storage/framework/sessions directory after setting a session.

When I try setting a session myself with the session function like it states in the docs:

session(['sesskey' => 'somevalue']);

Again no "Set-Cookie" header is sent in the response and no session file is created. There are no error messages reported back either I should add.

When I do set a session key with the session function like above I can get that value back however and echo it back to the browser like so:

echo session('sesskey');

So it does seem to save it at least in php's memory.

When I try setting a cookie using the withCookie method, I do get the proper response with the Set-Cookie header set:

return response()->view('welcome')->withCookie(cookie("test", "val" , 3600));

I tried going down the illuminate rabbit hole to see if I could find a problem but that is a bit over my head atm.

Any help would be much appriciated, thanks!

Body:
use middleware for the request \Illuminate\Session\Middleware\StartSession::class

Route::group(['middleware' => [\Illuminate\Session\Middleware\StartSession::class]], function () {

});


问:
Asynchronous for cycle in JavaScript
I need a loop that waits for an async call before continuing. Something like:

```<code>for ( /* ... */ ) {

  someFunction(param1, praram2, function(result) {

    // Okay, for cycle could continue

  })

}

alert("For cycle ended");
</code>```

How could I do this? Do you have any ideas?

答:
I needed to call some asynchronous function X times, each iteration must have happened after the previous one was done, so I wrote a litte library that can be used like this:

```<code>// https://codepen.io/anon/pen/MOvxaX?editors=0012
var loop = AsyncLoop(function(iteration, value){
  console.log("Loop called with iteration and value set to: ", iteration, value);

  var random = Math.random()*500;

  if(random < 200)
    return false;

  return new Promise(function(resolve){
    setTimeout(resolve.bind(null, random), random);
  });
})
.finished(function(){
  console.log("Loop has ended");
});
</code>```

Each time user defined loop function is called, it has two arguments, iteration index and previous call return value.

This is an example of output:

```<code>"Loop called with iteration and value set to: " 0 null
"Loop called with iteration and value set to: " 1 496.4137048207333
"Loop called with iteration and value set to: " 2 259.6020382449663
"Loop called with iteration and value set to: " 3 485.5400568702862
"Loop has ended"
</code>```

Title: Asynchronous for cycle in JavaScript

Body:
I need a loop that waits for an async call before continuing. Something like:

for ( /* ... */ ) {

  someFunction(param1, praram2, function(result) {

    // Okay, for cycle could continue

  })

}

alert("For cycle ended");

How could I do this? Do you have any ideas?

Body:
I needed to call some asynchronous function X times, each iteration must have happened after the previous one was done, so I wrote a litte library that can be used like this:

// https://codepen.io/anon/pen/MOvxaX?editors=0012
var loop = AsyncLoop(function(iteration, value){
  console.log("Loop called with iteration and value set to: ", iteration, value);

  var random = Math.random()*500;

  if(random < 200)
    return false;

  return new Promise(function(resolve){
    setTimeout(resolve.bind(null, random), random);
  });
})
.finished(function(){
  console.log("Loop has ended");
});

Each time user defined loop function is called, it has two arguments, iteration index and previous call return value.

This is an example of output:

"Loop called with iteration and value set to: " 0 null
"Loop called with iteration and value set to: " 1 496.4137048207333
"Loop called with iteration and value set to: " 2 259.6020382449663
"Loop called with iteration and value set to: " 3 485.5400568702862
"Loop has ended"


问:
How can I make my Sharepoint / Website available online?
I'm trying to learn a few things about SharePoint and I would like to figure out what do I have to do to make my content available online so I can access it from my other computer in my work / home so I can add documents to it.

I did some research on how to set up websites on IIS and setting up my DNS host on Windows Server 2012 with some demo html files I've made. I tried to do research online with port forwarding but I can't find info clear enough for me to get the job done.

Could somebody maybe give me some direction on where to look and a checklist on what I need to complete this task? I feel like I'm shooting in the air trying to figure this out. I've never really dabbled in this before.

答:
Here are some resources you might find useful in getting this setup. It's difficult to say exactly what you need to do without knowing what it is you've already done.

I haven't watched through the channel9 video but according to the description it includes how to setup internet facing sites in an on-premise environment.

Providing SharePoint is up and running, it should just be a case of configuring the Alternate Access Mappings for internet access, DNS and Port Forwarding.

https://channel9.msdn.com/Events/SharePoint-Conference/2014/SPC390

https://blog.blksthl.com/2012/12/03/a-guide-to-alternate-access-mappings-basics-in-sharepoint-2013

The final guide to Alternate Access Mappings


问:
Is there a .NET equivalent to MediaWiki's 'PLURAL' construct for dealing with parameters in localized text?
I'm in the process of getting resource files (resx) put together for the localization of an ASP .NET web application. These resource files will later be provided to translators so that the contents can be translated into all of the languages that we'll need to support.

It's my understanding that dealing with issues like pluralization can be difficult when you start dealing with different languages. Consider the example of wanting to display a confirmation message to a users asking if they want to delete one or more of the records on the current screen. As part of that message we want to include the number of records that want to be deleted, so we might define the resource text as:

Are you sure you want to delete these {0} record(s)?

This sidesteps the issue of using the word "record" vs. records. It's a bit of a grammatical hack, but I suppose it works well enough in English. That said, I don't want to assume that this same approach will work for other languages. In some cases (like Chinese), the pluralization isn't even an issue, but in other languages it certainly will be and using the (s) hack probably isn't going to cut it.

I've been reading the Localization Article on the MediaWiki wiki (dogfooding!) and found that they actually have the ability to embed different text to use in the message depending upon whether the value of the parameter is plural or not. So the resource text above would become (note the use of $1 for the parameter placeholder instead of {0}, but the concept is the same):

Are you sure you want to delete these $1 {{PLURAL:$1|record|records}}?

I like this syntax and was wondering if there were any .NET libraries out there that could interpret this that I might be able to plug in to a custom resource manager for my web application to support functionality like this.

答:
So far, only English is supported in System.Data.Entity.Design.PluralizationServices =(

http://msdn.microsoft.com/en-us/library/system.data.entity.design.pluralizationservices.pluralizationservice.aspx


问:
DBContext, EF6 and MySQL
I'm dealing with a weird problem. Everything works fine locally (VS 2017 IISexpress, MySQL Server 5.7.20, EF6 and Automatic Migrations Enabled = true).

I've started a MySQL Server on AWS (Server version 5.6.37) and it gives me the error "Specified key was too long; max key length is 767 bytes".

It's driving me crazy. Don't know what to do anymore. Any help?

Context:

```<code>[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class AuthContext : IdentityDbContext<IdentityUser>
{
    public AuthContext()
        : base("AuthContext")
    {
        Database.SetInitializer(new MySqlInitializer());
    }

    public DbSet<Client> Clients { get; set; }
    public DbSet<RefreshToken> RefreshTokens { get; set; }
    public DbSet<ItemCarteira> ItensCarteira { get; set; }
}
</code>```

答: After more research I was able to solve. The resizing for the 3 fields did the job. Link</p>

Title: DBContext, EF6 and MySQL

Body:
I'm dealing with a weird problem. Everything works fine locally (VS 2017 IISexpress, MySQL Server 5.7.20, EF6 and Automatic Migrations Enabled = true).

I've started a MySQL Server on AWS (Server version 5.6.37) and it gives me the error "Specified key was too long; max key length is 767 bytes".

It's driving me crazy. Don't know what to do anymore. Any help?

Context:

[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class AuthContext : IdentityDbContext<IdentityUser>
{
    public AuthContext()
        : base("AuthContext")
    {
        Database.SetInitializer(new MySqlInitializer());
    }

    public DbSet<Client> Clients { get; set; }
    public DbSet<RefreshToken> RefreshTokens { get; set; }
    public DbSet<ItemCarteira> ItensCarteira { get; set; }
}


问:
python transitions lib - Wait for multiple events before transition from single state possible?
Cross-post from github issue https://github.com/pytransitions/transitions/issues/247.

I'm using python's transitions FSM library and I need to wait for 3 things to happen before I transition to the next state.

```<code>State = WAIT_FOR_3_THINGS
Events = thing_1_done, thing_2_done, thing_3_done
</code>```

The thing_*_events can come in any order, so I'd prefer to avoid having a:

thing_1_and_2_done, thing_1_and_3_done, thing_2_and_3_done states

I can track events, 1, 2, & 3 and advance with a

```<code>conditions=[thing_1_and_2_done, thing_1_and_3_done, thing_2_and_3_done]
</code>```

but I'm not sure where best to aggregate these event occurences.

Is there a more skookum (ok, pythonic) way of doing this?

答:
From a pragmatic point of view your solution is the way to go with transitions, imho. For problems like this, concurrent state machines might be worth a look.

For this particular case this surely is over the top though but I'd like to use the opportunity to show how transitions might handle concurrency.
More precisely, we can use its ability to deal with multiple models to implement concurrency.
In the example below I extended Machine with a) a method to trigger an event on all models and b) with a method that initialises worker models and stores the actual models in an internal variable (this is not a proper stack though).
With ignore_invalid_triggers, every worker waits for the corresponding event and removes itself from the ParallelMachine model list when its done. When the model list is empty, ParallelMachine restores the actual model state again.

```<code>from transitions import Machine

class WorkerModel:

    def __init__(self, machine):
        self.machine = machine

    # I show myself out when I am done
    def on_enter_Done(self):
        self.machine.remove_model(self)

class ParallelMachine(Machine):

    def __init__(self, *args, **kwargs):
        self._pushed_models = []
        super(ParallelMachine, self).__init__(*args, **kwargs)

    # save actual models and initialise worker tasks
    def add_worker(self, tasks):
        self._pushed_models = self.models
        self.models = []
        for t in tasks:
            self.add_model(WorkerModel(self), initial=t)

    # trigger an event on ALL models (either workers or actual models)
    def trigger(self, trigger, *args, **kwargs):
        for m in self.models:
            getattr(m, trigger)(*args, **kwargs)
        if not self.models:
            self.models = self._pushed_models
            self._pushed_models = []
            for m in self.models:
                getattr(m, trigger)(*args, **kwargs)

class Model:

    def __init__(self):
        # the state list contains model states as well as worker states
        states = ['Idle', 'Processing', 'Done', 'need_1', 'need_2', 'need_3']
        # potentially got_1/2/3 all can trigger a transition to 'Done'
        # but the model will only be triggered when the worker list
        # has been emptied before
        transitions = [['process', 'Idle', 'Processing'],
                       ['got_1', ['Processing', 'need_1'], 'Done'],
                       ['got_2', ['Processing', 'need_2'], 'Done'],
                       ['got_3', ['Processing', 'need_3'], 'Done']]
        # assigning machine to a model attribute prevents the need
        # to pass it around
        self.machine = ParallelMachine(model=self, states=states,
                                       transitions=transitions, initial='Idle',
                                       ignore_invalid_triggers=True)

    def on_enter_Processing(self):
        self.machine.add_worker(['need_1', 'need_2', 'need_3'])

    def on_enter_Done(self):
        print("I am done")

model = Model()
machine = model.machine
assert model.state == 'Idle'
# we use ParallelMachine.trigger instead of model.<event_name>
machine.trigger('process')
assert model.state == 'Processing'
machine.trigger('got_3')
machine.trigger('got_1')
# duplicated events do not matter
machine.trigger('got_3')
assert model.state == 'Processing'
machine.trigger('got_2')
# worker stack was empty and
assert model.state == 'Done'
</code>```

This way the global state may be "Processing(need_1/need_2/done)" or "Processing(done/need_2/done)" without the need of explicitly modelling all variants.

Concurrency is on transitions To-Do list but requires some changes. For instance, callbacks are expected to be available in all models (removing on_enter_Done from Model will raise an Exception for instance).

Body:
Cross-post from github issue https://github.com/pytransitions/transitions/issues/247.

I'm using python's transitions FSM library and I need to wait for 3 things to happen before I transition to the next state.

State = WAIT_FOR_3_THINGS
Events = thing_1_done, thing_2_done, thing_3_done

The thing_*_events can come in any order, so I'd prefer to avoid having a:

thing_1_and_2_done, thing_1_and_3_done, thing_2_and_3_done states

I can track events, 1, 2, & 3 and advance with a

conditions=[thing_1_and_2_done, thing_1_and_3_done, thing_2_and_3_done]

but I'm not sure where best to aggregate these event occurences.

Is there a more skookum (ok, pythonic) way of doing this?

Body:
From a pragmatic point of view your solution is the way to go with transitions, imho. For problems like this, concurrent state machines might be worth a look.

For this particular case this surely is over the top though but I'd like to use the opportunity to show how transitions might handle concurrency.
More precisely, we can use its ability to deal with multiple models to implement concurrency.
In the example below I extended Machine with a) a method to trigger an event on all models and b) with a method that initialises worker models and stores the actual models in an internal variable (this is not a proper stack though).
With ignore_invalid_triggers, every worker waits for the corresponding event and removes itself from the ParallelMachine model list when its done. When the model list is empty, ParallelMachine restores the actual model state again.

from transitions import Machine

class WorkerModel:

    def __init__(self, machine):
        self.machine = machine

    # I show myself out when I am done
    def on_enter_Done(self):
        self.machine.remove_model(self)

class ParallelMachine(Machine):

    def __init__(self, *args, **kwargs):
        self._pushed_models = []
        super(ParallelMachine, self).__init__(*args, **kwargs)

    # save actual models and initialise worker tasks
    def add_worker(self, tasks):
        self._pushed_models = self.models
        self.models = []
        for t in tasks:
            self.add_model(WorkerModel(self), initial=t)

    # trigger an event on ALL models (either workers or actual models)
    def trigger(self, trigger, *args, **kwargs):
        for m in self.models:
            getattr(m, trigger)(*args, **kwargs)
        if not self.models:
            self.models = self._pushed_models
            self._pushed_models = []
            for m in self.models:
                getattr(m, trigger)(*args, **kwargs)

class Model:

    def __init__(self):
        # the state list contains model states as well as worker states
        states = ['Idle', 'Processing', 'Done', 'need_1', 'need_2', 'need_3']
        # potentially got_1/2/3 all can trigger a transition to 'Done'
        # but the model will only be triggered when the worker list
        # has been emptied before
        transitions = [['process', 'Idle', 'Processing'],
                       ['got_1', ['Processing', 'need_1'], 'Done'],
                       ['got_2', ['Processing', 'need_2'], 'Done'],
                       ['got_3', ['Processing', 'need_3'], 'Done']]
        # assigning machine to a model attribute prevents the need
        # to pass it around
        self.machine = ParallelMachine(model=self, states=states,
                                       transitions=transitions, initial='Idle',
                                       ignore_invalid_triggers=True)

    def on_enter_Processing(self):
        self.machine.add_worker(['need_1', 'need_2', 'need_3'])

    def on_enter_Done(self):
        print("I am done")

model = Model()
machine = model.machine
assert model.state == 'Idle'
# we use ParallelMachine.trigger instead of model.<event_name>
machine.trigger('process')
assert model.state == 'Processing'
machine.trigger('got_3')
machine.trigger('got_1')
# duplicated events do not matter
machine.trigger('got_3')
assert model.state == 'Processing'
machine.trigger('got_2')
# worker stack was empty and
assert model.state == 'Done'

This way the global state may be "Processing(need_1/need_2/done)" or "Processing(done/need_2/done)" without the need of explicitly modelling all variants.

Concurrency is on transitions To-Do list but requires some changes. For instance, callbacks are expected to be available in all models (removing on_enter_Done from Model will raise an Exception for instance).


问:
Need to create ArrayList method that fills with a Scanner
I'm trying to create a method that takes input from a data file (double type) using scanner and fills the Arraylist(double). I have a scanner created in my main class. I'm not sure how to get this to work correctly, though I feel like I'm almost there.

This is my main and public class

```<code>import java.util.Scanner;
import java.util.*;
public class Prog11{

public static void main(String [] args){

    Scanner inFile = new Scanner(System.in);
    readArr(inFile);
}
</code>```

Here is my method

```<code>public static double[] readArr(Scanner inFile){

    ArrayList <Double> examList = new ArrayList<Double>();

    while(inFile.hasNextDouble()){
        input.add(inFile.nextDouble());
    }

    return examList;

}
</code>```

here are the two errors left

```<code>./Prog11.java:33: error: cannot find symbol
            input.add(inFile.nextDouble());
            ^
  symbol:   variable input
  location: class Prog11

./Prog11.java:36: error: incompatible types: ArrayList<Double> cannot be
converted to double[]
return examList;
</code>```

答:
Two problems. One, you need to return a list, not an array; Two, your variable is inFile not input.

```<code>public static List<Double> readList(Scanner inFile){
    List<Double> examList = new ArrayList<Double>();

    while(inFile.hasNextDouble()){
        inFile.add(inFile.nextDouble());
    }

    return examList;

}
</code>```

If you absolutely have to return an array, then use

```<code>public static double[] readList(Scanner inFile) {
    List<Double> examList = new ArrayList<Double>();

    while(inFile.hasNextDouble()){
        inFile.add(inFile.nextDouble());
    }
    double[] arr = new double[examList.size()];
    for (int i = 0; i < examList.size(); i++) {
        arr[i] = examList.get(i);
    }
    return arr;
}
</code>```

Body:
I'm trying to create a method that takes input from a data file (double type) using scanner and fills the Arraylist(double). I have a scanner created in my main class. I'm not sure how to get this to work correctly, though I feel like I'm almost there.

This is my main and public class

import java.util.Scanner;
import java.util.*;
public class Prog11{

public static void main(String [] args){

    Scanner inFile = new Scanner(System.in);
    readArr(inFile);
}

Here is my method

public static double[] readArr(Scanner inFile){

    ArrayList <Double> examList = new ArrayList<Double>();

    while(inFile.hasNextDouble()){
        input.add(inFile.nextDouble());
    }

    return examList;

}

here are the two errors left

./Prog11.java:33: error: cannot find symbol
            input.add(inFile.nextDouble());
            ^
  symbol:   variable input
  location: class Prog11

./Prog11.java:36: error: incompatible types: ArrayList<Double> cannot be
converted to double[]
return examList;

Body:
Two problems. One, you need to return a list, not an array; Two, your variable is inFile not input.

public static List<Double> readList(Scanner inFile){
    List<Double> examList = new ArrayList<Double>();

    while(inFile.hasNextDouble()){
        inFile.add(inFile.nextDouble());
    }

    return examList;

}

If you absolutely have to return an array, then use

public static double[] readList(Scanner inFile) {
    List<Double> examList = new ArrayList<Double>();

    while(inFile.hasNextDouble()){
        inFile.add(inFile.nextDouble());
    }
    double[] arr = new double[examList.size()];
    for (int i = 0; i < examList.size(); i++) {
        arr[i] = examList.get(i);
    }
    return arr;
}


问:
How to initialize values inside nested json struct in GO?
I have this struct right now

```<code>type ServiceStruct struct {
      Name     string `json:"name"`
      DataStruct struct {
          ID    string `json:"id"`
          Size  string `json:"size"`
     }
}
</code>```

But im not sure how to assign values to the elements inside this struct. Specially the DataStruct inside the ServiceStruct

答:
You can either use an anonymous struct literal (which requires copy-pasting the type of DataStruct) or assign values to individual fields using =.

```<code>package main

import (
    "fmt"
)

type ServiceStruct struct {
    Name       string `json:"name"`
    DataStruct struct {
        ID   string `json:"id"`
        Size string `json:"size"`
    }
}

func main() {
    s1 := ServiceStruct{
        Name: "foo",
        DataStruct: struct {
            ID   string `json:"id"`
            Size string `json:"size"`
        }{
            ID:   "bar",
            Size: "100",
        },
    }

    s2 := ServiceStruct{
        Name: "foo",
    }
    s2.DataStruct.ID = "bar"
    s2.DataStruct.Size = "100"

    fmt.Println(s1)
    fmt.Println(s2)

    // Output:
    // {foo {bar 100}}
    // {foo {bar 100}}
}
</code>```

Alternatively, consider giving the type of DataStruct a name so you can refer to it in the struct literal instead of copy-pasting (which is not recommended).

Body:
I have this struct right now

type ServiceStruct struct {
      Name     string `json:"name"`
      DataStruct struct {
          ID    string `json:"id"`
          Size  string `json:"size"`
     }
}

But im not sure how to assign values to the elements inside this struct. Specially the DataStruct inside the ServiceStruct

Body:
You can either use an anonymous struct literal (which requires copy-pasting the type of DataStruct) or assign values to individual fields using =.

package main

import (
    "fmt"
)

type ServiceStruct struct {
    Name       string `json:"name"`
    DataStruct struct {
        ID   string `json:"id"`
        Size string `json:"size"`
    }
}

func main() {
    s1 := ServiceStruct{
        Name: "foo",
        DataStruct: struct {
            ID   string `json:"id"`
            Size string `json:"size"`
        }{
            ID:   "bar",
            Size: "100",
        },
    }

    s2 := ServiceStruct{
        Name: "foo",
    }
    s2.DataStruct.ID = "bar"
    s2.DataStruct.Size = "100"

    fmt.Println(s1)
    fmt.Println(s2)

    // Output:
    // {foo {bar 100}}
    // {foo {bar 100}}
}

Alternatively, consider giving the type of DataStruct a name so you can refer to it in the struct literal instead of copy-pasting (which is not recommended).


问:
Django 1.11 Image Gallery with Django Filer

Problem

I need to display a gallery of images on a product page. This worked when we were at Django 1.6, but have since upgraded to Django 1.11 (Big Process). I am now stuck at how to get this to work within the new environment. Right now clicking Add Image brings up a pop up where I can select the image, and the regions associated with it (US, Canada, Spain, Etc..), but after clicking "Save" The popup title changes to Popup closing... and never closes - also the image is not added to the gallery. The image I upload itself IS added to the rest of the Images within filer, however it is not added to the ProductGallery Model.

What I've Got

Django: 1.11.7

Django-Filer: 1.2.7

Django-Suit: 0.2.25

Vanilla-Views: 1.0.4

I have Product models, these products have a many to many relationship to a ProductGallery model like so:

```<code>class Product(models.Model):
    gallery = models.ManyToManyField('products.ProductGallery')
</code>```

The ProductGallery is supposed to house Images and Videos allowing for upload of either, and providing one list to iterate through on the front end for display purposes.

The ProductGallery is defined as:

```<code>class ProductGallery(models.Model):
    limit = models.Q(app_label='media', model='image') | models.Q(app_label='media', model='video')

    order = models.PositiveIntegerField(default=0)
    content_type = models.ForeignKey(ContentType, limit_choices_to=limit)
    object_id = models.PositiveIntegerField(db_index=True)
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    class Meta:
        ordering = ('order',)

    def __str__(self):
        return six.text_type(self.content_object)
</code>```

where media.image is defined as: (I'll ignore video for the time being)

```<code>class Image(CountryInfoModel, models.Model):
    image = FilerImageField(null=True, blank=True)

    def __str__(self):
        return str(self.image.name or self.image.original_filename)
</code>```

I've got a view for Adding new Media like so:

```<code>class AddMedia(LoginRequiredMixin, StaffuserRequiredMixin, JsonRequestResponseMixin, GenericView):
    require_json = True

    def post(self, request, *args, **kwargs):
        object_id = self.request_json["objectId"]
        object_var = self.request_json["objectVarName"]
        content_type_id = self.request_json["contentType"]
        order = self.request_json["order"]
        media_id = self.request_json["mediaId"]
        media_type = self.request_json["mediaType"]

        content_type = _get_content_type_or_404(content_type_id)
        content_object = _get_object_or_404(content_type, object_id)
        model_var = getattr(content_object, object_var)

        try:
            if media_type.lower() == "image":
                obj = Image.objects.get(pk=media_id)
            elif media_type.lower() == "video":
                obj = Video.objects.get(pk=media_id)
            else:
                raise Http404("Invalid mediaType parameter: {0}".format(media_type))
            media_item = model_var.create(content_object=obj)
            media_item.order = order
            media_item.save()
        except model_var.model.DoesNotExist:
            pass

        return self.render_json_response({'message': "Order successfully updated"})
</code>```

And I think thats all the pieces there are to this. I am lost on why when I click "save" the Image is not saved to the ProductGallery model at all. I'd be happy to provide more context if needed, and any help is very much appreciated.

答:
Just in case anyone else comes across this and wants to know how it was fixed.

It turns out that some of the django-admin template functionality had been overwritten and was causing some issues.

Specifically this project had overwritten parts of the save button functionality. The function dismissAddRelatedObjectPopup used to be named dismissAddAnotherPopup

These functions were overwritten to provide the custom functionality outlined above with the ProductGallery. Django went to call the function, but this was throwing an error on the popup related to something called SelectBoxwhich then broke the ajax call that was needed to save the model correctly.

Hopefully this can help someone in the future!

Body:
Problem

I need to display a gallery of images on a product page. This worked when we were at Django 1.6, but have since upgraded to Django 1.11 (Big Process). I am now stuck at how to get this to work within the new environment. Right now clicking Add Image brings up a pop up where I can select the image, and the regions associated with it (US, Canada, Spain, Etc..), but after clicking "Save" The popup title changes to Popup closing... and never closes - also the image is not added to the gallery. The image I upload itself IS added to the rest of the Images within filer, however it is not added to the ProductGallery Model.

What I've Got

Django: 1.11.7

Django-Filer: 1.2.7

Django-Suit: 0.2.25

Vanilla-Views: 1.0.4

I have Product models, these products have a many to many relationship to a ProductGallery model like so:

class Product(models.Model):
    gallery = models.ManyToManyField('products.ProductGallery')

The ProductGallery is supposed to house Images and Videos allowing for upload of either, and providing one list to iterate through on the front end for display purposes.

The ProductGallery is defined as:

class ProductGallery(models.Model):
    limit = models.Q(app_label='media', model='image') | models.Q(app_label='media', model='video')

    order = models.PositiveIntegerField(default=0)
    content_type = models.ForeignKey(ContentType, limit_choices_to=limit)
    object_id = models.PositiveIntegerField(db_index=True)
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    class Meta:
        ordering = ('order',)

    def __str__(self):
        return six.text_type(self.content_object)

where media.image is defined as: (I'll ignore video for the time being)

class Image(CountryInfoModel, models.Model):
    image = FilerImageField(null=True, blank=True)

    def __str__(self):
        return str(self.image.name or self.image.original_filename)

I've got a view for Adding new Media like so:

class AddMedia(LoginRequiredMixin, StaffuserRequiredMixin, JsonRequestResponseMixin, GenericView):
    require_json = True

    def post(self, request, *args, **kwargs):
        object_id = self.request_json["objectId"]
        object_var = self.request_json["objectVarName"]
        content_type_id = self.request_json["contentType"]
        order = self.request_json["order"]
        media_id = self.request_json["mediaId"]
        media_type = self.request_json["mediaType"]

        content_type = _get_content_type_or_404(content_type_id)
        content_object = _get_object_or_404(content_type, object_id)
        model_var = getattr(content_object, object_var)

        try:
            if media_type.lower() == "image":
                obj = Image.objects.get(pk=media_id)
            elif media_type.lower() == "video":
                obj = Video.objects.get(pk=media_id)
            else:
                raise Http404("Invalid mediaType parameter: {0}".format(media_type))
            media_item = model_var.create(content_object=obj)
            media_item.order = order
            media_item.save()
        except model_var.model.DoesNotExist:
            pass

        return self.render_json_response({'message': "Order successfully updated"})

And I think thats all the pieces there are to this. I am lost on why when I click "save" the Image is not saved to the ProductGallery model at all. I'd be happy to provide more context if needed, and any help is very much appreciated.


问:
MuleSoft ESB Batch Transactions
Thanks is advance for any help. Here is the scenario that I am trying to recreate in Mulesoft.

1,500,000 records in a table. Here is the current process that we use.

Start a transaction.

delete all records from the table.

reload the table from a flat file.

commit the transaction.

in the end we need the file in a good state, thus the use of the transaction. If there is any failure, the data in the table will be rolled back to the initial valid state.

I was able to get the speed that we needed by using the Batch element < 10 minutes, but it appears that transactions are not supported around the whole batch flow.

Any ideas how I could get this to work in Mulesoft?

Thanks again.

答:
For this you might try the following:

Use XA transactions (since more than one connector will be used,
regardless of the use of the same transport or not)

Enlist in the transaction the resource used in the custom Java code.

This also can be applied within the same transport (e.g. JDBC on the Mule configuration and also on the Java component), so it's not restricted to the case demonstrated in the PoC, which is only given as a reference.

Title: MuleSoft ESB Batch Transactions


问:
Dataflow Workers unable to connect to Dataflow Service
I am using Google Dataprep to start Dataflow jobs and am facing some difficulties.

For background, we used Dataprep for some weeks and it worked without problem before we started to have authorization issues with the service account. When we finally solved this, we restarted the jobs we used to launch but they failed with "The Dataflow appears to be stuck.".

We tried with another very simple job but we met the same error. Here are the full error messages, the job fails after one hour being stuck:

Dataflow -

```<code>(1ff58651b9d6bab2): Workflow failed. Causes: (1ff58651b9d6b915): The Dataflow appears to be stuck.
</code>```

Dataprep -

```<code>The Dataflow job (ID: 2017-11-15_00_23_23-9997011066491247322) failed. Please
contact Support and provide the Dataprep Job ID 20825 and the Dataflow Job ID.
</code>```

It seems this kind of error has various origins and I have no clue about where to start.
Thanks in advance

答:
Please check if there have been any changes to your project's default network. This is the common reason for workers not being able to contact the service, causing 1 hour timeouts.

Update:

After looking into further, <project-number>-compute@developer.gserviceaccount.com service account for Compute Engine is missing under 'Editor' role. This is usually automatically created. Probably this was removed later by mistake. See 'Compute Engine Service Account' section in https://cloud.google.com/dataflow/security-and-permissions.

We are working on fixes to improve early detection of such missing permissions so that the failure points the root cause better.

This implies your other Dataflow jobs fail similarly as well.

ContentLicense: CC BY-SA 4.0

Body:
I am using Google Dataprep to start Dataflow jobs and am facing some difficulties.

For background, we used Dataprep for some weeks and it worked without problem before we started to have authorization issues with the service account. When we finally solved this, we restarted the jobs we used to launch but they failed with "The Dataflow appears to be stuck.".

We tried with another very simple job but we met the same error. Here are the full error messages, the job fails after one hour being stuck:

Dataflow -

(1ff58651b9d6bab2): Workflow failed. Causes: (1ff58651b9d6b915): The Dataflow appears to be stuck.

Dataprep -

The Dataflow job (ID: 2017-11-15_00_23_23-9997011066491247322) failed. Please
contact Support and provide the Dataprep Job ID 20825 and the Dataflow Job ID.

It seems this kind of error has various origins and I have no clue about where to start.
Thanks in advance


问:
Need help understanding a specific alloc/release idiom in iOS/Objective-C programming
I'm an experienced C/C++ programmer starting to learn Objective-C development. I'm currently looking through the UICatalog sample and came across another instance of an idiom I've seen several places and never understood.

Code:

```<code>ButtonsViewController *buttonsViewController = [[ButtonsViewController alloc] initWithNibName:@"ButtonsViewController" bundle:nil];
[self.menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                       NSLocalizedString(@"ButtonsTitle", @""), kTitleKey,
                                       NSLocalizedString(@"ButtonsExplain", @""), kExplainKey,
                                       buttonsViewController, kViewControllerKey, nil]];
[buttonsViewController release];
</code>```

AFAIK, this allocates and initializes a ButtonsViewController, creates an NSDictionary for the ButtonsViewController and adds the dictionary to an NSMutableArray called menuList (which is a member variable of the MainViewController where the above code lives) and then releases the buttonsViewController that it just created. Later, the MainViewController uses the dictionary entry to switch views to the buttonsViewController when necessary.

My question is: why is the buttonsViewController still valid after this code? It was allocated and released with no 'retains' between. Does adding something to an NSDictionary or NSMutableArray have an implicit 'retain'? If so, was I supposed to be able to figure that out somehow, or is it just one of those things you have to read and remember?

答:
So, while it's true that the object is valid afterwards because the collection retains it, I'm not sure it's useful to think of it that way. If you intend to use the object in that method after adding it to the collection, you shouldn't release it until you're done with it.

The way to think about it is this:

1) I have a claim of ownership of this object I created

2) Now the collection and I both have ownership of this object

3) Now just the collection does, and I shouldn't use the object because I don't have ownership of it

and ignore the fact that you can technically get away with not paying attention to 3 in this case.

This allows you to keep using the NARC (new-alloc-retain-copy) rule for thinking about what retains objects.

Body:
I'm an experienced C/C++ programmer starting to learn Objective-C development. I'm currently looking through the UICatalog sample and came across another instance of an idiom I've seen several places and never understood.

Code:

ButtonsViewController *buttonsViewController = [[ButtonsViewController alloc] initWithNibName:@"ButtonsViewController" bundle:nil];
[self.menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                       NSLocalizedString(@"ButtonsTitle", @""), kTitleKey,
                                       NSLocalizedString(@"ButtonsExplain", @""), kExplainKey,
                                       buttonsViewController, kViewControllerKey, nil]];
[buttonsViewController release];

AFAIK, this allocates and initializes a ButtonsViewController, creates an NSDictionary for the ButtonsViewController and adds the dictionary to an NSMutableArray called menuList (which is a member variable of the MainViewController where the above code lives) and then releases the buttonsViewController that it just created. Later, the MainViewController uses the dictionary entry to switch views to the buttonsViewController when necessary.

My question is: why is the buttonsViewController still valid after this code? It was allocated and released with no 'retains' between. Does adding something to an NSDictionary or NSMutableArray have an implicit 'retain'? If so, was I supposed to be able to figure that out somehow, or is it just one of those things you have to read and remember?