问:
How do I revert a Git repository to a previous commit?
How do I revert from my current state to a snapshot made on a certain commit?

If I do git log, then I get the following output:

```<code>$ git log
commit a867b4af366350be2e7c21b8de9cc6504678a61b`
Author: Me <me@me.com>
Date:   Thu Nov 4 18:59:41 2010 -0400

blah blah blah...

commit 25eee4caef46ae64aa08e8ab3f988bc917ee1ce4
Author: Me <me@me.com>
Date:   Thu Nov 4 05:13:39 2010 -0400

more blah blah blah...

commit 0766c053c0ea2035e90f504928f8df3c9363b8bd
Author: Me <me@me.com>
Date:   Thu Nov 4 00:55:06 2010 -0400

And yet more blah blah...

commit 0d1d7fc32e5a947fbd92ee598033d85bfc445a50
Author: Me <me@me.com>
Date:   Wed Nov 3 23:56:08 2010 -0400

Yep, more blah blah.
</code>```

How do I revert to the commit from November 3, i.e. commit 0d1d7fc?

答:
The least complicated way I have found to revert a branch to any particular commit, where you can't change the history, is to:

Check out the commit or branch your wish to revert from.

Edit .git/HEAD and change the ref to the branch you which to revert to.

Such as:

```<code>echo 'ref: refs/heads/example' > .git/HEAD
</code>```

If you then do git status, you should see all the changes between the branch you're on and the one you wish to revert to.

If everything looks good, you can commit. You can also use git diff revert..example to ensure that it's the same.

Body:
How do I revert from my current state to a snapshot made on a certain commit?

If I do git log, then I get the following output:

$ git log
commit a867b4af366350be2e7c21b8de9cc6504678a61b`
Author: Me <me@me.com>
Date:   Thu Nov 4 18:59:41 2010 -0400

blah blah blah...

commit 25eee4caef46ae64aa08e8ab3f988bc917ee1ce4
Author: Me <me@me.com>
Date:   Thu Nov 4 05:13:39 2010 -0400

more blah blah blah...

commit 0766c053c0ea2035e90f504928f8df3c9363b8bd
Author: Me <me@me.com>
Date:   Thu Nov 4 00:55:06 2010 -0400

And yet more blah blah...

commit 0d1d7fc32e5a947fbd92ee598033d85bfc445a50
Author: Me <me@me.com>
Date:   Wed Nov 3 23:56:08 2010 -0400

Yep, more blah blah.

How do I revert to the commit from November 3, i.e. commit 0d1d7fc?

Body:
The least complicated way I have found to revert a branch to any particular commit, where you can't change the history, is to:

Check out the commit or branch your wish to revert from.

Edit .git/HEAD and change the ref to the branch you which to revert to.

Such as:

echo 'ref: refs/heads/example' > .git/HEAD

If you then do git status, you should see all the changes between the branch you're on and the one you wish to revert to.

If everything looks good, you can commit. You can also use git diff revert..example to ensure that it's the same.


来源: stackexchange

问:
How to get all users in a telegram channel using telethon?
I'm new to telethon and python. I have installed telethon in python3 and I want to get all members of a telegram channel or a group . I was searching a lot in the internet and found below code . And I'm trying really hard to understand it .Telegram documentation is not enough to do this . Is there a better solution ?

```<code>from telethon import TelegramClient

from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.functions.channels import GetAdminLogRequest
from telethon.tl.functions.channels import GetParticipantsRequest

from telethon.tl.types import ChannelParticipantsRecent
from telethon.tl.types import InputChannel
from telethon.tl.types import ChannelAdminLogEventsFilter
from telethon.tl.types import InputUserSelf
from telethon.tl.types import InputUser
# These example values won't work. You must get your own api_id and
# api_hash from https://my.telegram.org, under API Development.
api_id = 12345
api_hash = '8710a45f0f81d383qwertyuiop'
phone_number = '+123456789'

client = TelegramClient(phone_number, api_id, api_hash)

client.session.report_errors = False
client.connect()

if not client.is_user_authorized():
    client.send_code_request(phone_number)
    client.sign_in(phone_number, input('Enter the code: '))

channel = client(ResolveUsernameRequest('channelusername')) # Your channel username

user = client(ResolveUsernameRequest('admin')) # Your channel admin username
admins = [InputUserSelf(), InputUser(user.users[0].id, user.users[0].access_hash)] # admins
admins = [] # No need admins for join and leave and invite filters

filter = None # All events
filter = ChannelAdminLogEventsFilter(True, False, False, False, True, True, True, True, True, True, True, True, True, True)
cont = 0
list = [0,100,200,300]
for num in list:
    result = client(GetParticipantsRequest(InputChannel(channel.chats[0].id, channel.chats[0].access_hash), filter, num, 100))
    for _user in result.users:
        print( str(_user.id) + ';' + str(_user.username) + ';' + str(_user.first_name) + ';' + str(_user.last_name) )
with open(''.join(['users/', str(_user.id)]), 'w') as f: f.write(str(_user.id))
</code>```

But I'm getting this error . What have I missed ?

```<code>Traceback (most recent call last):
  File "run.py", line 51, in <module>
    result = client(GetParticipantsRequest(InputChannel(channel.chats[0].id, channel.chats[0].access_hash), filter, num, 100))
TypeError: __init__() missing 1 required positional argument: 'hash'
</code>```

答:
Use client.invoke() instead of client().

You can refer to official guide.

ContentLicense: CC BY-SA 3.0

Body:
I'm new to telethon and python. I have installed telethon in python3 and I want to get all members of a telegram channel or a group . I was searching a lot in the internet and found below code . And I'm trying really hard to understand it .Telegram documentation is not enough to do this . Is there a better solution ?

from telethon import TelegramClient

from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.functions.channels import GetAdminLogRequest
from telethon.tl.functions.channels import GetParticipantsRequest

from telethon.tl.types import ChannelParticipantsRecent
from telethon.tl.types import InputChannel
from telethon.tl.types import ChannelAdminLogEventsFilter
from telethon.tl.types import InputUserSelf
from telethon.tl.types import InputUser
# These example values won't work. You must get your own api_id and
# api_hash from https://my.telegram.org, under API Development.
api_id = 12345
api_hash = '8710a45f0f81d383qwertyuiop'
phone_number = '+123456789'

client = TelegramClient(phone_number, api_id, api_hash)

client.session.report_errors = False
client.connect()

if not client.is_user_authorized():
    client.send_code_request(phone_number)
    client.sign_in(phone_number, input('Enter the code: '))

channel = client(ResolveUsernameRequest('channelusername')) # Your channel username

user = client(ResolveUsernameRequest('admin')) # Your channel admin username
admins = [InputUserSelf(), InputUser(user.users[0].id, user.users[0].access_hash)] # admins
admins = [] # No need admins for join and leave and invite filters

filter = None # All events
filter = ChannelAdminLogEventsFilter(True, False, False, False, True, True, True, True, True, True, True, True, True, True)
cont = 0
list = [0,100,200,300]
for num in list:
    result = client(GetParticipantsRequest(InputChannel(channel.chats[0].id, channel.chats[0].access_hash), filter, num, 100))
    for _user in result.users:
        print( str(_user.id) + ';' + str(_user.username) + ';' + str(_user.first_name) + ';' + str(_user.last_name) )
with open(''.join(['users/', str(_user.id)]), 'w') as f: f.write(str(_user.id))

But I'm getting this error . What have I missed ?

Traceback (most recent call last):
  File "run.py", line 51, in <module>
    result = client(GetParticipantsRequest(InputChannel(channel.chats[0].id, channel.chats[0].access_hash), filter, num, 100))
TypeError: __init__() missing 1 required positional argument: 'hash'


问:
How to add pagination for custom Apiview result data in DRF
I have created a ListView in DRF 3. As database structure is complex I have written a custom query i.e. raw query to fetch the data. But as the data size is huge, it takes a lot of time to load it. So I need to implement pagination. Below is the code.</p>

```<code>class SubnetList(APIView):

    def get(self, request, format=None):
        subnet_list = get_subnet_details(None)
        return Response(subnet_list, status=status.HTTP_200_OK)

    def get_subnet_details(subnet_id=None):
        if subnet_id:
            subnets = Subnet.objects.filter(id=subnet_id).values()
        if not subnets:
            raise Http404
        else:
            subnets = Subnet.objects.values()

        subnet_list = []
        subnet_option_query = ' SELECT  ' \
                              ' options_value.id as value_id,' \
                              ' options_value.content,' \
                              ' options_option.id,' \
                              ' options_option.name' \
                              ' FROM subnets_subnetoption' \
                              ' INNER JOIN subnets_subnet ON (subnets_subnetoption.subnet_id = subnets_subnet.id)' \
                              ' INNER JOIN options_value ON (subnets_subnetoption.value_id = options_value.id)' \
                              ' INNER JOIN options_option ON (options_value.option_id = options_option.id)' \
                              ' INNER JOIN options_scope ON (options_option.scope_id = options_scope.id)' \
                              ' WHERE subnets_subnetoption.subnet_id = %s '

        try:
            for subnet in subnets:
                subnet_dictionary = collections.OrderedDict()
                subnet_dictionary['subnet_id'] = str(subnet['id'])
                subnet_dictionary['name'] = str(subnet['name'])
                subnet_dictionary['base_address'] = str(subnet['base_address'])
                subnet_dictionary['bcast_address'] = str(subnet['bcast_address'])
                subnet_dictionary['bits'] = str(subnet['bits'])
                subnet_dictionary['begin'] = str(subnet['base_address'])
                subnet_dictionary['end'] = str(subnet['bcast_address'])
                subnet_dictionary['parent_id'] = str(subnet['parent_id'])
                subnet_dictionary['vlan_common_name'] = str(subnet['vlan_common_name'])
                subnet_dictionary['admin'] = str(subnet['admin'])
                subnet_dictionary['responsible'] = str(subnet['responsible'])
                subnet_dictionary['comments'] = str(subnet['comments'])

                super_subnet = 'True' if subnet['is_physical'] else 'False'
                subnet_dictionary['is_physical'] = super_subnet
                options = SubnetOption.objects.raw(subnet_option_query % (subnet['id']))

                physical_attributes = collections.OrderedDict()
                range_attributes = collections.OrderedDict()
                gatewaydevice_attributes = collections.OrderedDict()
                securityzone_attributes = collections.OrderedDict()
                for option in options:
                    if option.name.lower() == 'provider':
                        subnet_dictionary['provider'] = str(option.value_id)
                    elif option.name.lower() == 'customer':
                        subnet_dictionary['customer'] = str(option.value_id)
                    elif option.name == 'Allocated by RIPE/ARIN/APNIC':
                        subnet_dictionary['allocated_by'] = str(option.value_id)

                    if super_subnet == 'True':
                        if option.name.lower() == 'vlan usage':
                            physical_attributes['vlan_usage'] = str(option.value_id)
                        elif option.name.lower() == 'environment':
                            physical_attributes['environment'] = str(option.value_id)
                        elif option.name.lower() == 'status':
                            physical_attributes['status'] = str(option.value_id)
                        elif option.name.lower() == 'vrf':
                            physical_attributes['vrf'] = str(option.value_id)
                        elif option.name.lower() == 'dns on demand status':
                            physical_attributes['dns_on_demand_status'] = str(option.value_id)

                        dmz = 'True' if subnet['dmz'] else 'False'
                        physical_attributes['dmz'] = dmz
        except ValueError as e:
            print(e)
            pass
        return subnet_list
</code>```

答:
Pass in a couple more parameters (you can make them optional if you want) - something like page and pagesize. Then use them to limit the query. For MySQL it would be something like LIMIT (pagesize * page),page. However, the specifics will vary depending on the database engine.

So, use the Django ORM. I can't say for sure without seeing the models, but I am fairly certain you can rewrite the query as a simple Django ORM query:

SubnetOption.objects.filter(subnet=subnet['id'])

and the various INNER JOINs should come through automagically.

Then you can use a range line [page*pagesize:(page+1)*pagesize] at the end of the query and Django will translate that into a LIMIT or the equivalent for your database engine.

Body:
I have created a ListView in DRF 3. As database structure is complex I have written a custom query i.e. raw query to fetch the data. But as the data size is huge, it takes a lot of time to load it. So I need to implement pagination. Below is the code.

class SubnetList(APIView):

    def get(self, request, format=None):
        subnet_list = get_subnet_details(None)
        return Response(subnet_list, status=status.HTTP_200_OK)

    def get_subnet_details(subnet_id=None):
        if subnet_id:
            subnets = Subnet.objects.filter(id=subnet_id).values()
        if not subnets:
            raise Http404
        else:
            subnets = Subnet.objects.values()

        subnet_list = []
        subnet_option_query = ' SELECT  ' \
                              ' options_value.id as value_id,' \
                              ' options_value.content,' \
                              ' options_option.id,' \
                              ' options_option.name' \
                              ' FROM subnets_subnetoption' \
                              ' INNER JOIN subnets_subnet ON (subnets_subnetoption.subnet_id = subnets_subnet.id)' \
                              ' INNER JOIN options_value ON (subnets_subnetoption.value_id = options_value.id)' \
                              ' INNER JOIN options_option ON (options_value.option_id = options_option.id)' \
                              ' INNER JOIN options_scope ON (options_option.scope_id = options_scope.id)' \
                              ' WHERE subnets_subnetoption.subnet_id = %s '

        try:
            for subnet in subnets:
                subnet_dictionary = collections.OrderedDict()
                subnet_dictionary['subnet_id'] = str(subnet['id'])
                subnet_dictionary['name'] = str(subnet['name'])
                subnet_dictionary['base_address'] = str(subnet['base_address'])
                subnet_dictionary['bcast_address'] = str(subnet['bcast_address'])
                subnet_dictionary['bits'] = str(subnet['bits'])
                subnet_dictionary['begin'] = str(subnet['base_address'])
                subnet_dictionary['end'] = str(subnet['bcast_address'])
                subnet_dictionary['parent_id'] = str(subnet['parent_id'])
                subnet_dictionary['vlan_common_name'] = str(subnet['vlan_common_name'])
                subnet_dictionary['admin'] = str(subnet['admin'])
                subnet_dictionary['responsible'] = str(subnet['responsible'])
                subnet_dictionary['comments'] = str(subnet['comments'])

                super_subnet = 'True' if subnet['is_physical'] else 'False'
                subnet_dictionary['is_physical'] = super_subnet
                options = SubnetOption.objects.raw(subnet_option_query % (subnet['id']))

                physical_attributes = collections.OrderedDict()
                range_attributes = collections.OrderedDict()
                gatewaydevice_attributes = collections.OrderedDict()
                securityzone_attributes = collections.OrderedDict()
                for option in options:
                    if option.name.lower() == 'provider':
                        subnet_dictionary['provider'] = str(option.value_id)
                    elif option.name.lower() == 'customer':
                        subnet_dictionary['customer'] = str(option.value_id)
                    elif option.name == 'Allocated by RIPE/ARIN/APNIC':
                        subnet_dictionary['allocated_by'] = str(option.value_id)

                    if super_subnet == 'True':
                        if option.name.lower() == 'vlan usage':
                            physical_attributes['vlan_usage'] = str(option.value_id)
                        elif option.name.lower() == 'environment':
                            physical_attributes['environment'] = str(option.value_id)
                        elif option.name.lower() == 'status':
                            physical_attributes['status'] = str(option.value_id)
                        elif option.name.lower() == 'vrf':
                            physical_attributes['vrf'] = str(option.value_id)
                        elif option.name.lower() == 'dns on demand status':
                            physical_attributes['dns_on_demand_status'] = str(option.value_id)

                        dmz = 'True' if subnet['dmz'] else 'False'
                        physical_attributes['dmz'] = dmz
        except ValueError as e:
            print(e)
            pass
        return subnet_list


问:
Java Class.cast() vs. cast operator
Having being taught during my C++ days about evils of the C-style cast operator I was pleased at first to find that in Java 5 java.lang.Class had acquired a cast method.

I thought that finally we have an OO way of dealing with casting.

Turns out Class.cast is not the same as static_cast in C++.  It is more like reinterpret_cast.  It will not generate a compilation error where it is expected and instead will defer to runtime.  Here is a simple test case to demonstrate different behaviors.

```<code>package test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class TestCast
{
    static final class Foo
    {
    }

    static class Bar
    {
    }

    static final class BarSubclass
        extends Bar
    {
    }

    @Test
    public void test ( )
    {
        final Foo foo = new Foo( );
        final Bar bar = new Bar( );
        final BarSubclass bar_subclass = new BarSubclass( );

        {
            final Bar bar_ref = bar;
        }

        {
            // Compilation error
            final Bar bar_ref = foo;
        }
        {
            // Compilation error
            final Bar bar_ref = (Bar) foo;
        }

        try
        {
            // !!! Compiles fine, runtime exception
            Bar.class.cast( foo );
        }
        catch ( final ClassCastException ex )
        {
            assertTrue( true );
        }

        {
            final Bar bar_ref = bar_subclass;
        }

        try
        {
            // Compiles fine, runtime exception, equivalent of C++ dynamic_cast
            final BarSubclass bar_subclass_ref = (BarSubclass) bar;
        }
        catch ( final ClassCastException ex )
        {
            assertTrue( true );
        }
    }
}
</code>```

So, these are my questions.

Should Class.cast() be banished to Generics land? There it has quite a few legitimate uses.

Should compilers generate compile errors when Class.cast() is used and illegal conditions can be determined at compile time?

Should Java provide a cast operator as a language construct similar to C++?

答:
In addition to remove ugly cast warnings as most mentioned ,Class.cast is run-time cast mostly used with generic casting ,due to generic info will be erased at run time and some how each generic will be considered Object , this leads to not to throw an early ClassCastException.

for example serviceLoder use this trick when creating the objects,check        S p = service.cast(c.newInstance()); this will throw a class cast exception
when S P =(S) c.newInstance(); won't and may show a warning 'Type safety: Unchecked cast from Object to S'.(same as Object P =(Object) c.newInstance();)

-simply it checks that the casted object is instance of casting class then it will use the cast operator to cast and hide the warning by suppressing it.

java implementation for dynamic cast:

```<code>@SuppressWarnings("unchecked")
public T cast(Object obj) {
    if (obj != null && !isInstance(obj))
        throw new ClassCastException(cannotCastMsg(obj));
    return (T) obj;
}

    private S nextService() {
        if (!hasNextService())
            throw new NoSuchElementException();
        String cn = nextName;
        nextName = null;
        Class<?> c = null;
        try {
            c = Class.forName(cn, false, loader);
        } catch (ClassNotFoundException x) {
            fail(service,
                 "Provider " + cn + " not found");
        }
        if (!service.isAssignableFrom(c)) {
            fail(service,
                 "Provider " + cn  + " not a subtype");
        }
        try {
            S p = service.cast(c.newInstance());
            providers.put(cn, p);
            return p;
        } catch (Throwable x) {
            fail(service,
                 "Provider " + cn + " could not be instantiated",
                 x);
        }
        throw new Error();          // This cannot happen
    }
</code>```

Title: Java Class.cast() vs. cast operator

Body:
Having being taught during my C++ days about evils of the C-style cast operator I was pleased at first to find that in Java 5 java.lang.Class had acquired a cast method.

I thought that finally we have an OO way of dealing with casting.

Turns out Class.cast is not the same as static_cast in C++.  It is more like reinterpret_cast.  It will not generate a compilation error where it is expected and instead will defer to runtime.  Here is a simple test case to demonstrate different behaviors.

package test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class TestCast
{
    static final class Foo
    {
    }

    static class Bar
    {
    }

    static final class BarSubclass
        extends Bar
    {
    }

    @Test
    public void test ( )
    {
        final Foo foo = new Foo( );
        final Bar bar = new Bar( );
        final BarSubclass bar_subclass = new BarSubclass( );

        {
            final Bar bar_ref = bar;
        }

        {
            // Compilation error
            final Bar bar_ref = foo;
        }
        {
            // Compilation error
            final Bar bar_ref = (Bar) foo;
        }

        try
        {
            // !!! Compiles fine, runtime exception
            Bar.class.cast( foo );
        }
        catch ( final ClassCastException ex )
        {
            assertTrue( true );
        }

        {
            final Bar bar_ref = bar_subclass;
        }

        try
        {
            // Compiles fine, runtime exception, equivalent of C++ dynamic_cast
            final BarSubclass bar_subclass_ref = (BarSubclass) bar;
        }
        catch ( final ClassCastException ex )
        {
            assertTrue( true );
        }
    }
}

So, these are my questions.

Should Class.cast() be banished to Generics land? There it has quite a few legitimate uses.

Should compilers generate compile errors when Class.cast() is used and illegal conditions can be determined at compile time?

Should Java provide a cast operator as a language construct similar to C++?

Body:
In addition to remove ugly cast warnings as most mentioned ,Class.cast is run-time cast mostly used with generic casting ,due to generic info will be erased at run time and some how each generic will be considered Object , this leads to not to throw an early ClassCastException.

for example serviceLoder use this trick when creating the objects,check        S p = service.cast(c.newInstance()); this will throw a class cast exception
when S P =(S) c.newInstance(); won't and may show a warning 'Type safety: Unchecked cast from Object to S'.(same as Object P =(Object) c.newInstance();)

-simply it checks that the casted object is instance of casting class then it will use the cast operator to cast and hide the warning by suppressing it.

java implementation for dynamic cast:

@SuppressWarnings("unchecked")
public T cast(Object obj) {
    if (obj != null && !isInstance(obj))
        throw new ClassCastException(cannotCastMsg(obj));
    return (T) obj;
}

    private S nextService() {
        if (!hasNextService())
            throw new NoSuchElementException();
        String cn = nextName;
        nextName = null;
        Class<?> c = null;
        try {
            c = Class.forName(cn, false, loader);
        } catch (ClassNotFoundException x) {
            fail(service,
                 "Provider " + cn + " not found");
        }
        if (!service.isAssignableFrom(c)) {
            fail(service,
                 "Provider " + cn  + " not a subtype");
        }
        try {
            S p = service.cast(c.newInstance());
            providers.put(cn, p);
            return p;
        } catch (Throwable x) {
            fail(service,
                 "Provider " + cn + " could not be instantiated",
                 x);
        }
        throw new Error();          // This cannot happen
    }


问:
Cant access properties of object obtained via ajax call
On Ajax success im getting the following data in a count variable. Using(snippet of ajax call success):

```<code>success: function (count) {
             console.log(count);
         }
</code>```

And below console.log(count) hold this data as shown in browser console:

```<code>{
    '07/12/2017': {
        'day': {'failed': 0, 'success': 3},
        'night': {'failed': 0, 'success': 0}
    },
    '06/12/2017': {
        'day': {'failed': 2, 'success': 20},
        'night': {'failed': 1, 'success': 291}
    },
    '05/12/2017': {
        'day': {'failed': 6, 'success': 50},
        'night': {'failed': 1, 'success': 51}
    }
}
</code>```

My issue when i try to access the data(all within the ajax success function), say i have a variable date = '07/12/2017' and i do count[date] i get undefined, but if i manually copy and hardcode the data to count like below then count[date] will return the object inside the corresponding date:

```<code>count = {
        '07/12/2017': {
            'day': {'failed': 0, 'success': 3},
            'night': {'failed': 0, 'success': 0}
        },
        '06/12/2017': {
            'day': {'failed': 2, 'success': 20},
            'night': {'failed': 1, 'success': 291}
        },
        '05/12/2017': {
            'day': {'failed': 6, 'success': 50},
            'night': {'failed': 1, 'success': 51}
        }
    }
</code>```

Might be something simple but its totally escaping me right now.

Thanks in advance

答:
From the evidence in the question and in the comments, I think count contains a string. What you've shown is invalid JSON and also not how any console I've ever seen represents objects when you console.log them, so I suspect it's a string and it's literally what's coming to your browser from the server.

If so, the server is sending invalid JSON. Property names (and all other strings) must be in double quotes, not single quotes.

So the solution is:

Correct the server's output. The best way to output JSON is not to handcraft it, but instead to build an object graph and then use your server-side environment's equivalent of JSON.stringify.

If you're still receiving a string at that point, update the server code to correctly identify what you're sending back as JSON by having it send this header:

```<code>Content-Type: application/json
</code>```

jQuery will see that content type on the response and automatically parse the string for you.

Then, count will refer to an object graph, and your code using count[date] where date is the string 07/12/2017 will work.

Here it is working on jsFiddle using jsFiddle's handy "echo" feature which lets us tell the server to echo something back to us: https://jsfiddle.net/narxfmdm/ Here's the code in the fiddle:

```<code>var json = '{' +
'    "07/12/2017": {' +
'        "day": {"failed": 0, "success": 3}, ' +
'        "night": {"failed": 0, "success": 0}' +
'    }, ' +
'    "06/12/2017": {' +
'        "day": {"failed": 2, "success": 20}, ' +
'        "night": {"failed": 1, "success": 291}' +
'    }, ' +
'    "05/12/2017": {' +
'        "day": {"failed": 6, "success": 50}, ' +
'        "night": {"failed": 1, "success": 51}' +
'    }' +
'}';
$.ajax({
    type: "POST",
  url: "/echo/json/",
  data: {json: json, delay: 1},
  success: function(count) {
    var date = "07/12/2017";
    $("<p>").text("Data for " + date + ": " + JSON.stringify(count[date])).appendTo(document.body);
  }
});
</code>```

Body:
On Ajax success im getting the following data in a count variable. Using(snippet of ajax call success):

success: function (count) {
             console.log(count);
         }

And below console.log(count) hold this data as shown in browser console:

{
    '07/12/2017': {
        'day': {'failed': 0, 'success': 3},
        'night': {'failed': 0, 'success': 0}
    },
    '06/12/2017': {
        'day': {'failed': 2, 'success': 20},
        'night': {'failed': 1, 'success': 291}
    },
    '05/12/2017': {
        'day': {'failed': 6, 'success': 50},
        'night': {'failed': 1, 'success': 51}
    }
}

My issue when i try to access the data(all within the ajax success function), say i have a variable date = '07/12/2017' and i do count[date] i get undefined, but if i manually copy and hardcode the data to count like below then count[date] will return the object inside the corresponding date:

count = {
        '07/12/2017': {
            'day': {'failed': 0, 'success': 3},
            'night': {'failed': 0, 'success': 0}
        },
        '06/12/2017': {
            'day': {'failed': 2, 'success': 20},
            'night': {'failed': 1, 'success': 291}
        },
        '05/12/2017': {
            'day': {'failed': 6, 'success': 50},
            'night': {'failed': 1, 'success': 51}
        }
    }

Might be something simple but its totally escaping me right now.

Thanks in advance

Body:
From the evidence in the question and in the comments, I think count contains a string. What you've shown is invalid JSON and also not how any console I've ever seen represents objects when you console.log them, so I suspect it's a string and it's literally what's coming to your browser from the server.

If so, the server is sending invalid JSON. Property names (and all other strings) must be in double quotes, not single quotes.

So the solution is:

Correct the server's output. The best way to output JSON is not to handcraft it, but instead to build an object graph and then use your server-side environment's equivalent of JSON.stringify.

If you're still receiving a string at that point, update the server code to correctly identify what you're sending back as JSON by having it send this header:

Content-Type: application/json

jQuery will see that content type on the response and automatically parse the string for you.

Then, count will refer to an object graph, and your code using count[date] where date is the string 07/12/2017 will work.

Here it is working on jsFiddle using jsFiddle's handy "echo" feature which lets us tell the server to echo something back to us: https://jsfiddle.net/narxfmdm/ Here's the code in the fiddle:

var json = '{' +
'    "07/12/2017": {' +
'        "day": {"failed": 0, "success": 3}, ' +
'        "night": {"failed": 0, "success": 0}' +
'    }, ' +
'    "06/12/2017": {' +
'        "day": {"failed": 2, "success": 20}, ' +
'        "night": {"failed": 1, "success": 291}' +
'    }, ' +
'    "05/12/2017": {' +
'        "day": {"failed": 6, "success": 50}, ' +
'        "night": {"failed": 1, "success": 51}' +
'    }' +
'}';
$.ajax({
    type: "POST",
  url: "/echo/json/",
  data: {json: json, delay: 1},
  success: function(count) {
    var date = "07/12/2017";
    $("<p>").text("Data for " + date + ": " + JSON.stringify(count[date])).appendTo(document.body);
  }
});


问:
How to ask for NSPhotoLibraryAddUsageDescription manually?
In IOS there is a permission NSPhotoLibraryAddUsageDescription
and I would like to ask for it when my app is started for the first time.

So I want just to check if it is permitted and ask for it.

What I can do to force this permission check?

答:
You can request with PHPhotoLibrary.requestAuthorization(_:) and check status with PHPhotoLibrary.authorizationStatus

See: Apple docummentation for requestAuthorization


问:
Displaying a final price as currency format and reading from file in java
I'm nearly finished with a program I've been writing for quite some time for a school final assignment.  It's 99% complete, but I'd like to add a couple things to make it as perfect as possible and need help.

I'd like to display the final price of an order in currency format, but have only figured out a way to format as currency if it's in my tostring method.

There's also bonus points to be had with this if I create a method that creates an order from a file. (ex: orders 1 Reece's Pieces, 6 sugar cookies, 1 chocolate chip cookie, and 1 scoop of caramel ice cream).

Here's my code.  Any help is appreciated.

```<code>    package dessertshop;

import java.text.NumberFormat;
import java.util.Scanner;

abstract class DessertItem
{
   protected String name;

   public DessertItem()
   {
      this.name = "";
   }

   public DessertItem( String name )
   {
      this.name = name;
   }

   public final String getName()
   {
      return name;
   }

   public abstract double getCost(int number);
}

class Candy extends DessertItem
{
   private double pricePerPound;

   public Candy( String name, double unitPrice )
   {
      super( name );
      this.pricePerPound = unitPrice;
   }

   @Override
   public double getCost(int amount)
   {
      return( amount * pricePerPound );
   }

   public String toString()
   {
      NumberFormat   formatter = NumberFormat.getCurrencyInstance();
      return( "Candy\t" + name + "\t @ " + formatter.format( this.pricePerPound ) + " per pound");
   }
}

class Cookie extends DessertItem
{
    private double pricePerDozen;

    public Cookie(String name, double pricePerDozen)
    {
        super(name);
        this.pricePerDozen=pricePerDozen;
    }

    @Override
    public double getCost(int amount)
    {
        return(amount * pricePerDozen)/12;
    }

    public String toString()
    {
        NumberFormat formatter = NumberFormat.getCurrencyInstance();
        return( "Cookie\t" + name + "\t @ " + formatter.format( this.pricePerDozen) + " per dozen");
    }
}

class IceCream extends DessertItem
{
    private double cost;

    public IceCream(String name, double cost)
    {
        super(name);
        this.cost=cost;
    }

    @Override
    public double getCost(int amount)
    {
        return(amount * cost);
    }

    public String toString()
    {
        NumberFormat   formatter = NumberFormat.getCurrencyInstance();
        return( "Ice Cream\t" + name + "\t @ " + formatter.format( this.cost ) + " per scoop");
    }
}

public class DessertShop
{
    private String name = "";
    private DessertItem[] menu;
    private int numberOfItems = 0;

    public DessertShop(String name)
    {
        this.name = name;
        menu = new DessertItem[200];
    }
    public DessertShop()
    {
        menu = new DessertItem[200];
    }

    public void addToMenu(DessertItem item)
    {
        menu[numberOfItems++] = item;
    }

    public void printMenu()
    {
        System.out.println(this.toString());
        for (int i = 0; i < numberOfItems; i++)
        {
            System.out.print((i + 1) + ": " + menu[i].toString());
            System.out.println("");
        }
    }

    public double createNewOrder()
    {
        double totalCost = 0;
        Scanner input = new Scanner(System.in);
            while (true)
            {
            this.printMenu();
            System.out.print("What would you like to purchase? (0 to checkout) > ");
            int choice = input.nextInt();
            if (choice == 0)
            {
                break;
            }
            System.out.print("How many (lbs. or amount) > ");
            int amount = input.nextInt();
            totalCost += menu[(choice - 1)].getCost(amount);
            }
        input.close();
        return totalCost;
    }

    public String toString()
    {
        return ("Welcome to " + name);
    }

    public static void main( String[] args )
    {

        DessertShop shop01 = new DessertShop("Chuck D's Dessert Depot");
        Candy candy01 = new Candy("Reece's Pieces", 3.99);
        Candy candy02 = new Candy("Chocolate Covered Raisins", 4.99);
        Cookie cookie01 = new Cookie("Peanut Butter", 5.99);
        Cookie cookie02 = new Cookie("Chocolate Chip", 4.99);
        Cookie cookie03 = new Cookie("Sugar", 4.50);
        IceCream icecream01 = new IceCream("Cookie Dough", 3.00);
        IceCream icecream02 = new IceCream("Vanilla", 2.00);
        IceCream icecream03 = new IceCream("Caramel", 3.50);
        IceCream icecream04 = new IceCream("Rocky Road", 2.99);
        IceCream icecream05 = new IceCream("Mint Chocolate Chip", 3.99);
        shop01.addToMenu(candy01);
        shop01.addToMenu(candy02);
        shop01.addToMenu(cookie01);
        shop01.addToMenu(cookie02);
        shop01.addToMenu(cookie03);
        shop01.addToMenu(icecream01);
        shop01.addToMenu(icecream02);
        shop01.addToMenu(icecream03);
        shop01.addToMenu(icecream04);
        shop01.addToMenu(icecream05);

        double frankOrder = shop01.createNewOrder();

        System.out.println(frankOrder);
    }
}
</code>```

答:
Depending on what you seek, you can format your price at your last line of code:

System.out.println(frankOrder)

have a look: here.

About the other question, reading in from file, I suggest you have a look at csv files: here and how to read them:here

Body:
I'm nearly finished with a program I've been writing for quite some time for a school final assignment.  It's 99% complete, but I'd like to add a couple things to make it as perfect as possible and need help.

I'd like to display the final price of an order in currency format, but have only figured out a way to format as currency if it's in my tostring method.

There's also bonus points to be had with this if I create a method that creates an order from a file. (ex: orders 1 Reece's Pieces, 6 sugar cookies, 1 chocolate chip cookie, and 1 scoop of caramel ice cream).

Here's my code.  Any help is appreciated.

    package dessertshop;

import java.text.NumberFormat;
import java.util.Scanner;

abstract class DessertItem
{
   protected String name;

   public DessertItem()
   {
      this.name = "";
   }

   public DessertItem( String name )
   {
      this.name = name;
   }

   public final String getName()
   {
      return name;
   }

   public abstract double getCost(int number);
}

class Candy extends DessertItem
{
   private double pricePerPound;

   public Candy( String name, double unitPrice )
   {
      super( name );
      this.pricePerPound = unitPrice;
   }

   @Override
   public double getCost(int amount)
   {
      return( amount * pricePerPound );
   }

   public String toString()
   {
      NumberFormat   formatter = NumberFormat.getCurrencyInstance();
      return( "Candy\t" + name + "\t @ " + formatter.format( this.pricePerPound ) + " per pound");
   }
}

class Cookie extends DessertItem
{
    private double pricePerDozen;

    public Cookie(String name, double pricePerDozen)
    {
        super(name);
        this.pricePerDozen=pricePerDozen;
    }

    @Override
    public double getCost(int amount)
    {
        return(amount * pricePerDozen)/12;
    }

    public String toString()
    {
        NumberFormat formatter = NumberFormat.getCurrencyInstance();
        return( "Cookie\t" + name + "\t @ " + formatter.format( this.pricePerDozen) + " per dozen");
    }
}

class IceCream extends DessertItem
{
    private double cost;

    public IceCream(String name, double cost)
    {
        super(name);
        this.cost=cost;
    }

    @Override
    public double getCost(int amount)
    {
        return(amount * cost);
    }

    public String toString()
    {
        NumberFormat   formatter = NumberFormat.getCurrencyInstance();
        return( "Ice Cream\t" + name + "\t @ " + formatter.format( this.cost ) + " per scoop");
    }
}

public class DessertShop
{
    private String name = "";
    private DessertItem[] menu;
    private int numberOfItems = 0;

    public DessertShop(String name)
    {
        this.name = name;
        menu = new DessertItem[200];
    }
    public DessertShop()
    {
        menu = new DessertItem[200];
    }

    public void addToMenu(DessertItem item)
    {
        menu[numberOfItems++] = item;
    }

    public void printMenu()
    {
        System.out.println(this.toString());
        for (int i = 0; i < numberOfItems; i++)
        {
            System.out.print((i + 1) + ": " + menu[i].toString());
            System.out.println("");
        }
    }

    public double createNewOrder()
    {
        double totalCost = 0;
        Scanner input = new Scanner(System.in);
            while (true)
            {
            this.printMenu();
            System.out.print("What would you like to purchase? (0 to checkout) > ");
            int choice = input.nextInt();
            if (choice == 0)
            {
                break;
            }
            System.out.print("How many (lbs. or amount) > ");
            int amount = input.nextInt();
            totalCost += menu[(choice - 1)].getCost(amount);
            }
        input.close();
        return totalCost;
    }

    public String toString()
    {
        return ("Welcome to " + name);
    }

    public static void main( String[] args )
    {

        DessertShop shop01 = new DessertShop("Chuck D's Dessert Depot");
        Candy candy01 = new Candy("Reece's Pieces", 3.99);
        Candy candy02 = new Candy("Chocolate Covered Raisins", 4.99);
        Cookie cookie01 = new Cookie("Peanut Butter", 5.99);
        Cookie cookie02 = new Cookie("Chocolate Chip", 4.99);
        Cookie cookie03 = new Cookie("Sugar", 4.50);
        IceCream icecream01 = new IceCream("Cookie Dough", 3.00);
        IceCream icecream02 = new IceCream("Vanilla", 2.00);
        IceCream icecream03 = new IceCream("Caramel", 3.50);
        IceCream icecream04 = new IceCream("Rocky Road", 2.99);
        IceCream icecream05 = new IceCream("Mint Chocolate Chip", 3.99);
        shop01.addToMenu(candy01);
        shop01.addToMenu(candy02);
        shop01.addToMenu(cookie01);
        shop01.addToMenu(cookie02);
        shop01.addToMenu(cookie03);
        shop01.addToMenu(icecream01);
        shop01.addToMenu(icecream02);
        shop01.addToMenu(icecream03);
        shop01.addToMenu(icecream04);
        shop01.addToMenu(icecream05);

        double frankOrder = shop01.createNewOrder();

        System.out.println(frankOrder);
    }
}


问:
TSQL Pivot Switch
I am trying to pivot the DataDescription rows into columns, and unpivot the Number* columns into rows aliased into a new column.

The desired columns would be:

```<code>Location, 2016-01-01, 2016-01-02, 2016-01-03, 2016-01-04, 2016-01-05,CountType
</code>```

Below is the code to setup the scenario.  Would this be done more cleanly in C# or TSQL?  Any suggestions?

```<code>if (object_id('tempdb..#data') is not null)
    begin
        drop table #data
    end

    create table #data
    (
        DateDescription VARCHAR(50),
        Location VARCHAR(50),
        NumberOfVisits INT,
        NumberOfPositiveVisits INT,
        NumberOfNegativeVisits INT
    )

    insert into #data
    SELECT '2016-01-01', 'SiteA', 100, 80, 20
    union all
    SELECT '2016-01-02', 'SiteA', 95, 81, 21
    union all
    SELECT '2016-01-03', 'SiteA', 95, 81, 21
    union all
    SELECT '2016-01-04', 'SiteA', 95, 81, 21
    union all
    SELECT '2016-01-05', 'SiteA', 95, 81, 21
    union all
    SELECT '2016-01-01', 'SiteB', 95, 81, 21
    union all
    SELECT '2016-01-02', 'SiteB', 95, 81, 21
    union all
    SELECT '2016-01-03', 'SiteB', 95, 81, 21
    union all
    SELECT '2016-01-04', 'SiteB', 95, 81, 21
    union all
    SELECT '2016-01-05', 'SiteB', 95, 81, 21

    select * from #data
</code>```

答:
If you are looking for T-Sql solution, you'd probably want to dig into Pivot capabilities. Not sure what do you expect from the CountType column, but grouping might be done in the following way:

```<code>SELECT Location
      ,[2016-01-01]
      ,[2016-01-02]
      ,[2016-01-03]
      ,[2016-01-04]
      ,[2016-01-05]
      ,[Type]
FROM (
    SELECT [DateDescription]
          ,Location
          ,NumberOfVisits as visits
          ,'Total' AS [Type]
    FROM #data) AS Source
PIVOT
(
    SUM(visits)
    FOR
    DateDescription IN
    (
       [2016-01-01]
      ,[2016-01-02]
      ,[2016-01-03]
      ,[2016-01-04]
      ,[2016-01-05]
    )
) AS PivotTable

UNION

SELECT Location
      ,[2016-01-01]
      ,[2016-01-02]
      ,[2016-01-03]
      ,[2016-01-04]
      ,[2016-01-05]
      ,[Type]
FROM (
    SELECT [DateDescription]
          ,Location
          ,NumberOfPositiveVisits as visits
          ,'Positive' AS [Type]
    FROM #data) AS Source
PIVOT
(
    SUM(visits)
    FOR
    DateDescription IN
    (
       [2016-01-01]
      ,[2016-01-02]
      ,[2016-01-03]
      ,[2016-01-04]
      ,[2016-01-05]
    )
) AS PivotTable

UNION

    SELECT Location
      ,[2016-01-01]
      ,[2016-01-02]
      ,[2016-01-03]
      ,[2016-01-04]
      ,[2016-01-05]
      ,[Type]
FROM (
    SELECT [DateDescription]
          ,Location
          ,NumberOfNegativeVisits as visits
          ,'Negative' AS [Type]
    FROM #data) AS Source
PIVOT
(
    SUM(visits)
    FOR
    DateDescription IN
    (
       [2016-01-01]
      ,[2016-01-02]
      ,[2016-01-03]
      ,[2016-01-04]
      ,[2016-01-05]
    )
) AS PivotTable;
</code>```

Title: TSQL Pivot Switch

Body:
I am trying to pivot the DataDescription rows into columns, and unpivot the Number* columns into rows aliased into a new column.

The desired columns would be:

Location, 2016-01-01, 2016-01-02, 2016-01-03, 2016-01-04, 2016-01-05,CountType

Below is the code to setup the scenario.  Would this be done more cleanly in C# or TSQL?  Any suggestions?

if (object_id('tempdb..#data') is not null)
    begin
        drop table #data
    end

    create table #data
    (
        DateDescription VARCHAR(50),
        Location VARCHAR(50),
        NumberOfVisits INT,
        NumberOfPositiveVisits INT,
        NumberOfNegativeVisits INT
    )

    insert into #data
    SELECT '2016-01-01', 'SiteA', 100, 80, 20
    union all
    SELECT '2016-01-02', 'SiteA', 95, 81, 21
    union all
    SELECT '2016-01-03', 'SiteA', 95, 81, 21
    union all
    SELECT '2016-01-04', 'SiteA', 95, 81, 21
    union all
    SELECT '2016-01-05', 'SiteA', 95, 81, 21
    union all
    SELECT '2016-01-01', 'SiteB', 95, 81, 21
    union all
    SELECT '2016-01-02', 'SiteB', 95, 81, 21
    union all
    SELECT '2016-01-03', 'SiteB', 95, 81, 21
    union all
    SELECT '2016-01-04', 'SiteB', 95, 81, 21
    union all
    SELECT '2016-01-05', 'SiteB', 95, 81, 21

    select * from #data

Body:
If you are looking for T-Sql solution, you'd probably want to dig into Pivot capabilities. Not sure what do you expect from the CountType column, but grouping might be done in the following way:

SELECT Location
      ,[2016-01-01]
      ,[2016-01-02]
      ,[2016-01-03]
      ,[2016-01-04]
      ,[2016-01-05]
      ,[Type]
FROM (
    SELECT [DateDescription]
          ,Location
          ,NumberOfVisits as visits
          ,'Total' AS [Type]
    FROM #data) AS Source
PIVOT
(
    SUM(visits)
    FOR
    DateDescription IN
    (
       [2016-01-01]
      ,[2016-01-02]
      ,[2016-01-03]
      ,[2016-01-04]
      ,[2016-01-05]
    )
) AS PivotTable

UNION

SELECT Location
      ,[2016-01-01]
      ,[2016-01-02]
      ,[2016-01-03]
      ,[2016-01-04]
      ,[2016-01-05]
      ,[Type]
FROM (
    SELECT [DateDescription]
          ,Location
          ,NumberOfPositiveVisits as visits
          ,'Positive' AS [Type]
    FROM #data) AS Source
PIVOT
(
    SUM(visits)
    FOR
    DateDescription IN
    (
       [2016-01-01]
      ,[2016-01-02]
      ,[2016-01-03]
      ,[2016-01-04]
      ,[2016-01-05]
    )
) AS PivotTable

UNION

    SELECT Location
      ,[2016-01-01]
      ,[2016-01-02]
      ,[2016-01-03]
      ,[2016-01-04]
      ,[2016-01-05]
      ,[Type]
FROM (
    SELECT [DateDescription]
          ,Location
          ,NumberOfNegativeVisits as visits
          ,'Negative' AS [Type]
    FROM #data) AS Source
PIVOT
(
    SUM(visits)
    FOR
    DateDescription IN
    (
       [2016-01-01]
      ,[2016-01-02]
      ,[2016-01-03]
      ,[2016-01-04]
      ,[2016-01-05]
    )
) AS PivotTable;

ContentLicense: CC BY-SA 4.0


问:
Swift UITextFields jumps back to position
I have searched pretty much everywhere and can't find a solution for this.  So i have a log in screen and when the keyboard shows the textfields move up for readability. However as soon as I type or switch to a different textfield the fields jump back to their original position...

Here is the code

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    usernameField.delegate = self

    passwordField.delegate = self
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()

    return true
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    self.animateTextField(textField: textField, up:true)
}

func textFieldDidEndEditing(_ textField: UITextField) {

    self.animateTextField(textField: textField, up:false)
}

func animateTextField(textField: UITextField, up: Bool)
{
    let movementDuration: Double = 0.3

    var labelMove: CGFloat = -20
    var userMove: CGFloat = -40
    var passMove: CGFloat = -50

    if up
    {
        labelMove = -20
        userMove = -40
        passMove = -50
    }
    else
    {
        labelMove = 20
        userMove = 40
        passMove = 50
    }
    UIView.beginAnimations("animateTextField", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration)
    self.titleLabel.frame = self.titleLabel.frame.offsetBy(dx: 0, dy: labelMove)
    self.usernameField.frame = self.usernameField.frame.offsetBy(dx: 0, dy: userMove)
    self.passwordField.frame = self.passwordField.frame.offsetBy(dx: 0, dy: passMove)
    UIView.commitAnimations()
}
</code>```

Please help?

答:
You should add these on an UIScrollView and not animate them Up/Down.

Inside of the delegates DidBeginEditing and DidEndEditing, you scroll up and down inside of the UIScrollView respectively.

The reason why your issue is happening is because as soon as you start the second animation, the position of the Textfields reset to the original position defined (since you defined an animation not set a new origin for the textfields)

Hope this helps!

Body:
I have searched pretty much everywhere and can't find a solution for this.  So i have a log in screen and when the keyboard shows the textfields move up for readability. However as soon as I type or switch to a different textfield the fields jump back to their original position...

Here is the code

override func viewDidLoad() {
    super.viewDidLoad()

    usernameField.delegate = self

    passwordField.delegate = self
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()

    return true
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    self.animateTextField(textField: textField, up:true)
}

func textFieldDidEndEditing(_ textField: UITextField) {

    self.animateTextField(textField: textField, up:false)
}

func animateTextField(textField: UITextField, up: Bool)
{
    let movementDuration: Double = 0.3

    var labelMove: CGFloat = -20
    var userMove: CGFloat = -40
    var passMove: CGFloat = -50

    if up
    {
        labelMove = -20
        userMove = -40
        passMove = -50
    }
    else
    {
        labelMove = 20
        userMove = 40
        passMove = 50
    }
    UIView.beginAnimations("animateTextField", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration)
    self.titleLabel.frame = self.titleLabel.frame.offsetBy(dx: 0, dy: labelMove)
    self.usernameField.frame = self.usernameField.frame.offsetBy(dx: 0, dy: userMove)
    self.passwordField.frame = self.passwordField.frame.offsetBy(dx: 0, dy: passMove)
    UIView.commitAnimations()
}

Please help?


问:
About The switch Statement in Java
I'm still learning. Today I have a question in SoloLearn, into The switch Statement lesion:

```<code>int day = 3;

switch(day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;

// Outputs "Wednesday"
</code>```

and I thinks, I can have a example to remember about input and switch Statement: I want input a number, and 1 as Monday, 2 as Tuesday.... to 7 as Sunday, and repeat: 8 as Monday, 9 as Tuesday....
This is my code:

```<code>import java.util.Scanner;

public class Program {
public static void main(String[] args) {
    Scanner day = new Scanner(System.in);

        if (day.nextInt()>7){
            day.nextInt()=day.nextInt()%7;
        }

    switch(day.nextInt()){
        case 1 :
            System.out.println("Monday");
            break;
        case 2:
            System.out.println("Tuesday");
            break;
        case 3:
            System.out.println("Wednesday");
            break;
        case 4:
            System.out.println("Thursday");
            break;
        case 5:
            System.out.println("Friday");
            break;
        case 6:
            System.out.println("Saturday");
            break;
        case 0:
            System.out.println("Sunday");
        case 7:
            System.out.println("Sunday");
            break;

        }
    }
}
</code>```

and error. My knowledge's not enough to fix this thing (I think so, because i'm a newbie and still learning). Can you expand for me, fix this thing and thanks for teach!
Have fun!

答:
Add break after case 0:

```<code>            case 6:
                System.out.println("Saturday");
                break;
            case 0:
                System.out.println("Sunday");
              break;
</code>```

If the value in switch() goes beyond 7 than you will get error as you have not provided any default case here. You can either do something like number%7to get the value always in case range.

Title: About The switch Statement in Java

Body:
I'm still learning. Today I have a question in SoloLearn, into The switch Statement lesion:

int day = 3;

switch(day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;

// Outputs "Wednesday"

and I thinks, I can have a example to remember about input and switch Statement: I want input a number, and 1 as Monday, 2 as Tuesday.... to 7 as Sunday, and repeat: 8 as Monday, 9 as Tuesday....
This is my code:

import java.util.Scanner;

public class Program {
public static void main(String[] args) {
    Scanner day = new Scanner(System.in);

        if (day.nextInt()>7){
            day.nextInt()=day.nextInt()%7;
        }

    switch(day.nextInt()){
        case 1 :
            System.out.println("Monday");
            break;
        case 2:
            System.out.println("Tuesday");
            break;
        case 3:
            System.out.println("Wednesday");
            break;
        case 4:
            System.out.println("Thursday");
            break;
        case 5:
            System.out.println("Friday");
            break;
        case 6:
            System.out.println("Saturday");
            break;
        case 0:
            System.out.println("Sunday");
        case 7:
            System.out.println("Sunday");
            break;

        }
    }
}

and error. My knowledge's not enough to fix this thing (I think so, because i'm a newbie and still learning). Can you expand for me, fix this thing and thanks for teach!
Have fun!

Body:
Add break after case 0:

            case 6:
                System.out.println("Saturday");
                break;
            case 0:
                System.out.println("Sunday");
              break;

If the value in switch() goes beyond 7 than you will get error as you have not provided any default case here. You can either do something like number%7to get the value always in case range.


答:
The problem is here:

```<code>    if (day.nextInt()>7){
        day.nextInt()=day.nextInt()%7;
    }
</code>```

You're trying to assign a value back to the method call day.nextInt(), which you can't do. Instead, try something like the following:

```<code>int dayNum = day.nextInt() % 7;
</code>```

Also, your switch includes a case for dayNum == 7, which will never be the case.

Title: About The switch Statement in Java

Body:
The problem is here:

    if (day.nextInt()>7){
        day.nextInt()=day.nextInt()%7;
    }

You're trying to assign a value back to the method call day.nextInt(), which you can't do. Instead, try something like the following:

int dayNum = day.nextInt() % 7;

Also, your switch includes a case for dayNum == 7, which will never be the case.


问:
Why aren't my html links working in 'Owl Carousel'
I've developed this site http://aevoe.com.au

I've used Owl Carousel for the sliding carousel on the home page.

However the links I've wrapped the slides in aren't working or even clickable.

This is the markup for the carousel:

```<code><div class="fourteen columns offset-by-one">
    <div class="row" id="slide-margin">
        <div id="owl-demo" class="owl-carousel">
            <div><a href="works/summer-selections"><img src="images/dissolve-now.jpg" /></a></div>
            <div><a href="works/summer-selections"><img src="images/need-you-now.jpg" /></a></div>
            <div><a href="works/arcade-fire"><img src="images/the-suburbs.jpg" /></a></div>
        </div>
    </div>
</div>
</code>```

Not sure what the problem is..

答:
Just remove this line:
"e.preventDefault();"</p>

```<code>$('#carousel-cartoes li a').on('click', function(e){
            e.preventDefault();
            var .....
</code>```

Body:
I've developed this site http://aevoe.com.au

I've used Owl Carousel for the sliding carousel on the home page.

However the links I've wrapped the slides in aren't working or even clickable.

This is the markup for the carousel:

Not sure what the problem is..

Body:
Just remove this line:
"e.preventDefault();"

$('#carousel-cartoes li a').on('click', function(e){
            e.preventDefault();
            var .....


问:
JBuilder as_json to_json
Does Jbuilder use as_json or to_json to render?

I am attempting to override the as_json and to_json with an alias, similar to the below:

```<code>  module BSON
    class ObjectId

      def as_json(*args)
        to_s
      end

      alias :to_json :as_json

    end
  end
</code>```

Then use JBuilder to render the return object. However, it acts as if it is using neither to_json or as_json to render.

答:
Jbuilder uses MultiJson, which by default will use the JSON gem. That gem is currently tangled with ActiveSupport's all-Ruby #to_json implementation.

Reference: http://www.rubydoc.info/gems/jbuilder/2.5.0

Title: JBuilder as_json to_json

Body:
Does Jbuilder use as_json or to_json to render?

I am attempting to override the as_json and to_json with an alias, similar to the below:

  module BSON
    class ObjectId

      def as_json(*args)
        to_s
      end

      alias :to_json :as_json

    end
  end

Then use JBuilder to render the return object. However, it acts as if it is using neither to_json or as_json to render.


问:
How update collections using Azure functions
I want to create the azure Function which is bind to cosmos DB.

Whenever some insertion happens in "A" collection I want to update "B" collection.

"B" collection has stored procedure which I want to call after the insertion in collection "A".

I am new to Azure and cosmos-DB.

Suggest me what need to be done to accomplish the requirement.

So far I have created Azure Function

Also Updated the function.json with below code.

```<code>{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "input",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "cdb-swm-dev-001_DOCUMENTDB",
      "databaseName": "admin",
      "collectionName": "aomsorders",
      "createLeaseCollectionIfNotExists": true
    },
    {
      "type": "documentDB",
      "name": "inputDocument",
      "databaseName": "admin",
      "collectionName": "aomsorders",
      "connection": "cdb-swm-dev-001_DOCUMENTDB",
      "direction": "in"
    },
    {
      "type": "documentDB",
      "name": "outputDocument",
      "databaseName": "admin",
      "collectionName": "test",
      "createIfNotExists": true,
      "connection": "cdb-swm-dev-001_DOCUMENTDB",
      "direction": "out"
    }
  ],
  "disabled": false
}
</code>```

Also Updated the Integrate Part as below

Any Suggestion will be appreciable.

答:
Here is an example of an Azure Function that gets triggered by a CosmosDBTrigger and then it uses a DocumentDB Output Binding to write to a second collection:

function.json

```<code>{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "input",
      "direction": "in",
      "databaseName": "your-database",
      "collectionName": "your-collection1",
      "connectionStringSetting": "name-of-connectionstring-setting-for-collection1",
      "leaseCollectionName": "your-lease-collection"
    },
    {
      "type": "documentDB",
      "direction": "out",
      "name": "docsToSave",
      "databaseName": "your-database2",
      "collectionName": "your-collection2",
      "connection": "name-of-connectionstring-setting-for-collection2",
      "createIfNotExists": false
    }
  ]
}
</code>```

run.csx (C#)

```<code>#r "Microsoft.Azure.Documents.Client"
using Microsoft.Azure.Documents;
using System.Collections.Generic;
using System;
public static async Task Run(IReadOnlyList<Document> input, IAsyncCollector<Document> docsToSave)
{
    foreach(var doc in input){
        // Do something here, process the document or do your compute
        // Here I am saving the same document to the second collection but you could send a new document created within the processing logic or send the same document modified by some logic
        await docsToSave.AddAsync(doc);
    }
}
</code>```

index.js (NodeJS)

```<code>module.exports = function(context, input) {
    if(!!input && input.length > 0){
        context.bindings.docsToSave = [];
        for(var i = 0, len=input.length; i<len;i++){
            var doc = input[i];
            // Do something here with the doc or create a new one
            context.bindings.docsToSave.push(doc);
        }
    }
    context.done();
}
</code>```

Body:
I want to create the azure Function which is bind to cosmos DB.

Whenever some insertion happens in "A" collection I want to update "B" collection.

"B" collection has stored procedure which I want to call after the insertion in collection "A".

I am new to Azure and cosmos-DB.

Suggest me what need to be done to accomplish the requirement.

So far I have created Azure Function

Also Updated the function.json with below code.

{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "input",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "cdb-swm-dev-001_DOCUMENTDB",
      "databaseName": "admin",
      "collectionName": "aomsorders",
      "createLeaseCollectionIfNotExists": true
    },
    {
      "type": "documentDB",
      "name": "inputDocument",
      "databaseName": "admin",
      "collectionName": "aomsorders",
      "connection": "cdb-swm-dev-001_DOCUMENTDB",
      "direction": "in"
    },
    {
      "type": "documentDB",
      "name": "outputDocument",
      "databaseName": "admin",
      "collectionName": "test",
      "createIfNotExists": true,
      "connection": "cdb-swm-dev-001_DOCUMENTDB",
      "direction": "out"
    }
  ],
  "disabled": false
}

Also Updated the Integrate Part as below

Any Suggestion will be appreciable.

Body:
Here is an example of an Azure Function that gets triggered by a CosmosDBTrigger and then it uses a DocumentDB Output Binding to write to a second collection:

function.json

{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "input",
      "direction": "in",
      "databaseName": "your-database",
      "collectionName": "your-collection1",
      "connectionStringSetting": "name-of-connectionstring-setting-for-collection1",
      "leaseCollectionName": "your-lease-collection"
    },
    {
      "type": "documentDB",
      "direction": "out",
      "name": "docsToSave",
      "databaseName": "your-database2",
      "collectionName": "your-collection2",
      "connection": "name-of-connectionstring-setting-for-collection2",
      "createIfNotExists": false
    }
  ]
}

run.csx (C#)

#r "Microsoft.Azure.Documents.Client"
using Microsoft.Azure.Documents;
using System.Collections.Generic;
using System;
public static async Task Run(IReadOnlyList<Document> input, IAsyncCollector<Document> docsToSave)
{
    foreach(var doc in input){
        // Do something here, process the document or do your compute
        // Here I am saving the same document to the second collection but you could send a new document created within the processing logic or send the same document modified by some logic
        await docsToSave.AddAsync(doc);
    }
}

index.js (NodeJS)

module.exports = function(context, input) {
    if(!!input && input.length > 0){
        context.bindings.docsToSave = [];
        for(var i = 0, len=input.length; i<len;i++){
            var doc = input[i];
            // Do something here with the doc or create a new one
            context.bindings.docsToSave.push(doc);
        }
    }
    context.done();
}


问:
Import Excel files with different Date types
Got a lot of Excel files, all containing the same columns. One of the columns is called "DateTime". The problem is, that this column contain different formats, e.g:

```<code>2/12/2013  11:59:45 PM
20/2/2013 14:36:58
</code>```

As you can see, the first example contains a PM at the end. Here is my problem:

My code to import all the Excel files in the specific folder:

```<code>file.list <- list.files(pattern='*.xlsx')
df.list <- lapply(file.list, read_excel)
df <- bind_rows(df.list, .id = "id")
</code>```

But, after I run the second line (df.list <- lapply(file.list, read_excel)) I got a warnings like (Expecting numeric, got a date).

I tried different things, such as assigning col_types = "text" (I hoped that I could import all the data as character, and afterwards change remove the PM at the end and change the characters back to as.Date again). But unfortunately the results was a lot of NA's.

Another thing that I tried was to import the the file as numeric (but again, received the same message "Expecting numeric, got a date).

So how can I tackle this problem? I can do it by changing the columns type in Excel, but that is not what I want to do (I prefer to do everything in R).

Edit

Some data as requested (after I imported the data into R with as "character" with the lubridate as_date function, as suggested).

```<code>Num Date
1  41277.000601851854
2  41277.004710648151
3  41277.004826388889
4  41277.007372685184
5  41277.007789351854
6  41277.007870370369
7  41277.010335648149
8  41277.010868055557
9  41277.013842592591
10 41277.014548611114
</code>```

答:
First read in all data as char strings, it will be easy to clean afterwards.

Then I think the lubridate package could help you here. I don't know how many files/formats you have but the example given can be read by the same lubridate::dmy_hms() function:

```<code># >datim <- c("20/2/2013 14:36:58", "2/12/2013  11:59:45 PM")
# >dmy_hms(datim)
# [1] "2013-02-20 14:36:58 UTC" "2013-12-02 23:59:45 UTC"
</code>```

There is a function for each ordering of time units. mdy_hm() for example. If you have more variation in your time formats you would use stringr::str_detect(your_date_variable, "date_format_regex") to identify lines with each type of format before applying the appropriate dmy_hm() function.

Body:
Got a lot of Excel files, all containing the same columns. One of the columns is called "DateTime". The problem is, that this column contain different formats, e.g:

2/12/2013  11:59:45 PM
20/2/2013 14:36:58

As you can see, the first example contains a PM at the end. Here is my problem:

My code to import all the Excel files in the specific folder:

file.list <- list.files(pattern='*.xlsx')
df.list <- lapply(file.list, read_excel)
df <- bind_rows(df.list, .id = "id")

But, after I run the second line (df.list <- lapply(file.list, read_excel)) I got a warnings like (Expecting numeric, got a date).

I tried different things, such as assigning col_types = "text" (I hoped that I could import all the data as character, and afterwards change remove the PM at the end and change the characters back to as.Date again). But unfortunately the results was a lot of NA's.

Another thing that I tried was to import the the file as numeric (but again, received the same message "Expecting numeric, got a date).

So how can I tackle this problem? I can do it by changing the columns type in Excel, but that is not what I want to do (I prefer to do everything in R).

Edit

Some data as requested (after I imported the data into R with as "character" with the lubridate as_date function, as suggested).

Num Date
1  41277.000601851854
2  41277.004710648151
3  41277.004826388889
4  41277.007372685184
5  41277.007789351854
6  41277.007870370369
7  41277.010335648149
8  41277.010868055557
9  41277.013842592591
10 41277.014548611114

Body:
First read in all data as char strings, it will be easy to clean afterwards.

Then I think the lubridate package could help you here. I don't know how many files/formats you have but the example given can be read by the same lubridate::dmy_hms() function:

# >datim <- c("20/2/2013 14:36:58", "2/12/2013  11:59:45 PM")
# >dmy_hms(datim)
# [1] "2013-02-20 14:36:58 UTC" "2013-12-02 23:59:45 UTC"

There is a function for each ordering of time units. mdy_hm() for example. If you have more variation in your time formats you would use stringr::str_detect(your_date_variable, "date_format_regex") to identify lines with each type of format before applying the appropriate dmy_hm() function.


问:
How to bind datagridview's data source property to combobox?

I am trying to bind list of objects as a data source for data grid, on of the columns should be a combobox where selected value of the combobox should be value in the filed related in my object.

This is how I set the datasource of gridview :

```<code>var s = new BindingSource();
s.DataSource = dbc.GetResults();
dataGridView.DataSource = s;
</code>```

dbc.GetResults(id) will return List and myClass which is

```<code>Class myClass
{
 int productID{ set; get; }
 int price{ set; get; }
}
</code>```

And then I am initialling data grid view like this :

```<code>dataGridView.AutoGenerateColumns = false;
DataGridViewComboBoxColumn dgvc = new DataGridViewComboBoxColumn();
dgvc.HeaderText = "Products";
dgvc.DataSource = dbc.GetAllProducts();
dgvc.DisplayMember = "Name";
dgvc.ValueMember = "ID";
dataGridView.Columns.Add(dgvc);
dataGridView.Columns[0].DataPropertyName = "productID";
</code>```

and dbc.GetAllProducts() returns list and :

```<code>Class Products
{
 int ID;
 string Name;
}
</code>```

Here I expect that data grids get productID from myClass and pass it to combobox on each row, then the combo box gets the productID matches it with the ID in products column and then shows the Name property of it.

when I run this I get the error that DataGridViewComboBoxCell value is not valid.

答:
You should use a dictionary to bind your property to your combo :

```<code>private Dictionary<int, string> cbProductVals= new Dictionary<int, string>();
</code>```

Populate your dictionary with product objects and bind it on your grid column.

In your datagrid AutoGeneratingColumn event :

```<code>if (e.PropertyName == "productID")
{
    DataGridComboBoxColumn cb = new DataGridComboBoxColumn();
    e.Column = cb;
    cb.ItemsSource = cbProductVals;
    cb.DisplayMemberPath = "Value";
    cb.SelectedValuePath = "Key";
    cb.SelectedValueBinding = new Binding("productID");
    e.Column.Header = "product price";
}
</code>```

Body:
I am trying to bind list of objects as a data source for data grid, on of the columns should be a combobox where selected value of the combobox should be value in the filed related in my object.

This is how I set the datasource of gridview :

var s = new BindingSource();
s.DataSource = dbc.GetResults();
dataGridView.DataSource = s;

dbc.GetResults(id) will return List and myClass which is

Class myClass
{
 int productID{ set; get; }
 int price{ set; get; }
}

And then I am initialling data grid view like this :

dataGridView.AutoGenerateColumns = false;
DataGridViewComboBoxColumn dgvc = new DataGridViewComboBoxColumn();
dgvc.HeaderText = "Products";
dgvc.DataSource = dbc.GetAllProducts();
dgvc.DisplayMember = "Name";
dgvc.ValueMember = "ID";
dataGridView.Columns.Add(dgvc);
dataGridView.Columns[0].DataPropertyName = "productID";

and dbc.GetAllProducts() returns list and :

Class Products
{
 int ID;
 string Name;
}

Here I expect that data grids get productID from myClass and pass it to combobox on each row, then the combo box gets the productID matches it with the ID in products column and then shows the Name property of it.

when I run this I get the error that DataGridViewComboBoxCell value is not valid.

Body:
You should use a dictionary to bind your property to your combo :

private Dictionary<int, string> cbProductVals= new Dictionary<int, string>();

Populate your dictionary with product objects and bind it on your grid column.

In your datagrid AutoGeneratingColumn event :

if (e.PropertyName == "productID")
{
    DataGridComboBoxColumn cb = new DataGridComboBoxColumn();
    e.Column = cb;
    cb.ItemsSource = cbProductVals;
    cb.DisplayMemberPath = "Value";
    cb.SelectedValuePath = "Key";
    cb.SelectedValueBinding = new Binding("productID");
    e.Column.Header = "product price";
}


问:
Rails: scope order question
I have some posts that belongs to location and category, sort of like craigslist post.

I want to order by most recently posted and also filter by location and category if those are specified by the user.

Can someone give an example/hints on how to do this?

答:
In Rails 3 you can change together orders, wheres and more. ASCICasts on activerecord queries in Rails3</p>

```<code>query = Post.order("published_at desc")
query = query.where("location_id = ?", params[:location_id]) unless params[:location_id].blank?
query = query.where("category_id = ?", params[:category_id]) unless params[:category_id].blank?
@posts = query.all
</code>```

ContentLicense: CC BY-SA 2.5

Title: Rails: scope order question

Body:
In Rails 3 you can change together orders, wheres and more. ASCICasts on activerecord queries in Rails3

query = Post.order("published_at desc")
query = query.where("location_id = ?", params[:location_id]) unless params[:location_id].blank?
query = query.where("category_id = ?", params[:category_id]) unless params[:category_id].blank?
@posts = query.all


问:
Why the type cannot be inferred if a parameterless method group is passed to LINQ methods?
Can someone explain me(or show the specification/documentation) why following is not allowed:

```<code>string[] fiveFoos = Enumerable.Range(1, 5).Select(GetFoo).ToArray();
</code>```

...

```<code>static string GetFoo()
{
    return "Foo";
}
</code>```

Only this will compile:

```<code>string[] fiveFoos = Enumerable.Range(1, 5).Select(i => GetFoo()).ToArray();
</code>```

The integer projected from Enumerable.Range is not relevant and the method GetFoo is parameterless and clearly returns String, so why do i get following compiler error anyway:

Error CS0411  The type arguments for method 'Enumerable.Select(IEnumerable, Func)' cannot be
  inferred from the usage. Try specifying the type arguments
  explicitly.

答:
Select here expects a Func<int, string> - your GetFoo method needs to take an int for this to work.

Method group conversion works by inferring the overload of the method which takes the appropriate parameters - you don't have one here. The integer projected from Enumerable.Range is not relevant - it might not be relevant to you, in this use case, but it is to the compiler!!

Body:
Can someone explain me(or show the specification/documentation) why following is not allowed:

string[] fiveFoos = Enumerable.Range(1, 5).Select(GetFoo).ToArray();

...

static string GetFoo()
{
    return "Foo";
}

Only this will compile:

string[] fiveFoos = Enumerable.Range(1, 5).Select(i => GetFoo()).ToArray();

The integer projected from Enumerable.Range is not relevant and the method GetFoo is parameterless and clearly returns String, so why do i get following compiler error anyway:

Error CS0411  The type arguments for method 'Enumerable.Select(IEnumerable, Func)' cannot be
  inferred from the usage. Try specifying the type arguments
  explicitly.


问:
How to Authorize android app to communicate with woocommerce site using postman
I am trying to build an Android app that connects local users to a WordPress/WooCommerce site and retrive data from it to use them in the app.

How could I autorize app to retreive woocomerce data from my site using postman please?

Any help would be appricaited.

答:
actually I asked this question because I spent months (and I mean months) trying to figure it out; and I did not get any answer that really helped me, beside this tutsplus.com  tutorial which was instrumental in order for me to solve the problem; the WooCommerce REST API doc is so confusing it made things even worst for me but it still worth reading.

First step: Setting plugins and getting necessary information to start

First of all, install and activate  “WooCommerce”, "WP REST API" and  "WP REST API - OAuth 1.0a Server" plugins on your WoordPress site;

Then, install postman on your computer;

Then go to the API Tab from WooCommerce setting page of the dashboard and make sure the activate REST API check box is ticked;

Still in WoordPress backend,  create a new user  by clicking the add new button on the users>applications page (this will only show if you have properly installed and activated the plugins mentioned above );

After the user is created; Copy the client key (CK) and the client secret(CS) and saved them somewhere safe;

Then, go back to the users>applications page and hover the edit link under the name of the user you have just created; the user id appears bellow the page (in the left corner of your screen); Write it down to have it at hand.

We finished the first step to collect necessary data to start authenticating the app and establishing the communication between the website and the app.

Second step:  Getting the final Token and building the WC authorization URL

This steps consists of using data we collected above to get the final token (not to be confused with temporary token) and build the WooCommerce authorization URL that establishes the communication between the app and the website.

I should only have used postman for this step but since I couldn’t login to my website dashboard from postman for windows, I switched between postman and my browser. I guess the newest version of postman will solve this since they are killing the chrome add on… never mind let go:

In the postman dashboard,in the URL area, paste the following:  mysite.com/wp-json. Chose GET as a method and pressed the SEND button; You will get this:

"authentication": {"oauth1": {
  "request": "mysite.com/oauth1/request",

  "authorize": "mysite.com/oauth1/authorize",
  "access":"mysite.com/oauth1/access","version": "0.1"}

as part of your response.
2.  Click the first link (mysite.com/oauth1/request) ; postman opens a new tab;  Under TYPE, chose  OAuth 1.0 ; new fields appear at the right. Fill in the client key (CK) and the client secret (CS) we got from the step above respectively in the Consumer Key and Consumer Secret fields; then, click the SEND button again.  The response you will get is something like this:

oauth_token=your_oauth_token_is_here&oauth_token_secret=your_oauth_token_secret_is_here&oauth_callback_confirmed=true

Copy the value of your oauth_token (TK) and your oauth_token_secret( TKS ); but remember this are only temporary values not to be confused with the final  oauth_token  and the final token secret;

Go back to your very first tab in postman and click the second link from the response (mysite.com/oauth1/authorize) ; postman opens a new tab;  Under TYPE chose  OAuth 1.0 ; new fields appear at the right. Fill in your temporary  oauth_token (TK) and your temporary   oauth_token_secret( TKS ). Click send. In the response section  click the Preview link to see what the response looks like and it will ask to login as a WoordPress user which you can’t from postman;

So scroll to the top of postman and clicke on the code link under the Save button; Select JAVA OK HTTP as the language;  You will get this kind of code:

mysite.com/oauth1/authorize?oauth_consumer_key=your_costumer_key_is_here&oauth_token=your_temporary_token_key_is_here&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1512645061&oauth_nonce=VHeUrwCl4CP&oauth_version=1.0&oauth_signature=3bMUiF8%2Fg57EkwaDOdnQ8m3s8TQ%3D

Copy the URL in the parenthesis and paste it in your browser where you are already logged in as a WoordPress user;

Give the app authorization; it will redirect you to a page with your verification Token (VT) which you have to copy and keep somewhere.

Go back to your very first tab in postman and clicked the third link from the response (mysite.com/oauth1/access) ; postman opens a new tab;  Chose OAuth 1.0 as a type ; new fields appear at the right. Before the SEND button there is a Params button; click it ;new fields appears; Enter oauth_verifier as a key and your verification Token (VT) as value; then  press SEND; the response looks like this:

oauth_token=your_final_token_is_here&oauth_token_secret=your_final_token_secrete_is_here

These are your final oauth_token (FTK) and your final  oauth_token_secret( FTKS );
8.  Now we can build our final URL; Open a new tab in postman ; In the URL section , paste (mysite.com/wc-auth/v1/authorize )  ; select OAuth 1.0 as a type; fields appear at the right. Replace the Access Token value with your final oauth_token (FTK)  and the Token Secret with final  oauth_token_secret( FTKS);
9.   Click on the Params button and enter the following as  pairs of key/value:

app_name => your_app_name (from step 1); user_id => your_user_id (from
  step 1) return_url=> your_return_url (I used mysite.com)
  callback_url=> your_callbak_url (I used mysite.com)

Click the SEND button; once your response is 200 OK; click on the code link to view the corresponding JAVA OK HTTP code ; copy the URL and past it in your browser and only then you could see the app asking for approval to access WooCommerce data;
I mean this:

So all you need to do now is to copy the entire OKHTTP code generated from postman and use it in your ANDROID java app to get permission; I used webview to display this response page in my app . I hope that will help lots of people struggling with this problem.


答: NextInt() is a method .. you can't assign it a value</p>

Title: About The switch Statement in Java


答:
As mentioned by @kolosy You are missing a break statement below case 0 and by writing day.nextInt() four times, you are actually asking the user to enter four times.
Also you cant day.nextInt()=day.nextInt()%7; do this. By doing it you're trying to assign a value back to the method call Change your code of main function to this

```<code>        Scanner day = new Scanner(System.in);
        int enteredDay = day.nextInt();

        if (enteredDay > 7) {
            enteredDay = enteredDay % 7;
        }

        switch (enteredDay) {
        case 1:
            System.out.println("Monday");
            break;
        case 2:
            System.out.println("Tuesday");
            break;
        case 3:
            System.out.println("Wednesday");
            break;
        case 4:
            System.out.println("Thursday");
            break;
        case 5:
            System.out.println("Friday");
            break;
        case 6:
            System.out.println("Saturday");
            break;
        case 0:
            System.out.println("Sunday");
            break;
        case 7:
            System.out.println("Sunday");
            break;

        }
</code>```

Title: About The switch Statement in Java

Body:
As mentioned by @kolosy You are missing a break statement below case 0 and by writing day.nextInt() four times, you are actually asking the user to enter four times.
Also you cant day.nextInt()=day.nextInt()%7; do this. By doing it you're trying to assign a value back to the method call Change your code of main function to this

        Scanner day = new Scanner(System.in);
        int enteredDay = day.nextInt();

        if (enteredDay > 7) {
            enteredDay = enteredDay % 7;
        }

        switch (enteredDay) {
        case 1:
            System.out.println("Monday");
            break;
        case 2:
            System.out.println("Tuesday");
            break;
        case 3:
            System.out.println("Wednesday");
            break;
        case 4:
            System.out.println("Thursday");
            break;
        case 5:
            System.out.println("Friday");
            break;
        case 6:
            System.out.println("Saturday");
            break;
        case 0:
            System.out.println("Sunday");
            break;
        case 7:
            System.out.println("Sunday");
            break;

        }


问:
How to check if template argument is a callable with a given signature
Basically, what I want to achieve is compile-time verification (with possibly nice error message) that registered callable (either a function, a lambda, a struct with call operator) has correct signature. Example (contents of the static_assert are to be filled):

```<code>struct A {
  using Signature = void(int, double);

  template <typename Callable>
  void Register(Callable &&callable) {
    static_assert(/* ... */);
    callback = callable;
  }

  std::function<Signature> callback;
};
</code>```

答:
You can use the detection idiom, which is a form of sfinae. I believe this works in c++11.

```<code>template <typename...>
using void_t = void;

template <typename Callable, typename enable=void>
struct callable_the_way_i_want : std::false_type {};

template <typename Callable>
struct callable_the_way_i_want <Callable, void_t <decltype (std::declval <Callable>()(int {},double {}))>> : std::true_type {};
</code>```

Then you can write a static assert in your code like so:

```<code>static_assert (is_callable_the_way_i_want <Callable>::value, "Not callable with required signature!");
</code>```

The advantage of this over the answers I see above is:

It works for any callable, not just a lambda

theres no runtime overhead or std::function business. std::function may cause a dynamic allocation, for instance, that would be otherwise unnecessary.

you can actually write a static_assert against the test and put a nice human-readable error message there

Tartan Llama wrote a great blogpost about this technique, and several alternatives, check it out! https://blog.tartanllama.xyz/detection-idiom/

If you need to do this alot then you may want to look at the callable_traits library.

Body:
Basically, what I want to achieve is compile-time verification (with possibly nice error message) that registered callable (either a function, a lambda, a struct with call operator) has correct signature. Example (contents of the static_assert are to be filled):

struct A {
  using Signature = void(int, double);

  template <typename Callable>
  void Register(Callable &&callable) {
    static_assert(/* ... */);
    callback = callable;
  }

  std::function<Signature> callback;
};

Body:
You can use the detection idiom, which is a form of sfinae. I believe this works in c++11.

template <typename...>
using void_t = void;

template <typename Callable, typename enable=void>
struct callable_the_way_i_want : std::false_type {};

template <typename Callable>
struct callable_the_way_i_want <Callable, void_t <decltype (std::declval <Callable>()(int {},double {}))>> : std::true_type {};

Then you can write a static assert in your code like so:

static_assert (is_callable_the_way_i_want <Callable>::value, "Not callable with required signature!");

The advantage of this over the answers I see above is:

It works for any callable, not just a lambda

theres no runtime overhead or std::function business. std::function may cause a dynamic allocation, for instance, that would be otherwise unnecessary.

you can actually write a static_assert against the test and put a nice human-readable error message there

Tartan Llama wrote a great blogpost about this technique, and several alternatives, check it out! https://blog.tartanllama.xyz/detection-idiom/

If you need to do this alot then you may want to look at the callable_traits library.


问:
JavaScript Submit and Button
1.A user is guided through a sequence of web pages, entering details which are then stored in hidden fields until all the user information is finally sent to the server.
Each button on each webpage should be:

```<code><input type=button>
<input type=submit>
</code>```

2.A user has to enter some information on a web page. After successful validation, the information is sent to a servlet or CGI script.
The button on the webpage should be:

```<code><input type=button>
<input type=submit>
</code>```

There are two scenarios to ask you the difference between ‘submit’ and ‘button’. Can you tell me the best choice for above scenarios and why?

答:
From MDN,
"Note: While input tags of type "button" are still perfectly valid HTML, the newer button tag is now the favored way to create buttons, which has some advantages. It supports the "menu" type, which lets the button serve as the trigger for a popup menu, and given that a button's label text is inserted between the opening and closing tags, you can include HTML in the label, even images."

input type='button', input type='submit', and input type='reset' all create a button on the page. Types submit and reset perform special operations on their form. Type button typically calls some JavaScript to do perform the action.

Title: JavaScript Submit and Button

Body:
1.A user is guided through a sequence of web pages, entering details which are then stored in hidden fields until all the user information is finally sent to the server.
Each button on each webpage should be:

<input type=button>
<input type=submit>

2.A user has to enter some information on a web page. After successful validation, the information is sent to a servlet or CGI script.
The button on the webpage should be:

<input type=button>
<input type=submit>

There are two scenarios to ask you the difference between ‘submit’ and ‘button’. Can you tell me the best choice for above scenarios and why?


问:
What is the correct way to configure Traefik to work with the Rancher backend?
I've been trying to get Traefik to work with the Rancher backend by following the documentation but when looking at the web interface I always get a Rancher tab that is completely blank.

Starting the container with the following parameters gives me the blank page:

```<code>--web.address=0.0.0.0:8080
--rancher
--rancher.domain=subdomain.example.co.uk
--rancher.endpoint=https://rancher.example.co.uk/v1
--rancher.accesskey=EXAMPLEKEY
--rancher.secretkey=EXAMPLESECRETKEY
--logLevel=DEBUG
</code>```

Likewise the equivalent config file gives the same result:

```<code>logLegel = "DEBUG"
defaultEntryPoints = ["http"]
[entryPoints]
  [entryPoints.http]
  address = ":80"

[web]
address = ":8080"

[rancher]
domain = "subdomain.example.co.uk"
  [rancher.api]
  endpoint = "https://rancher.example.co.uk/v1"
  accessKey = "EXAMPLEKEY"
  secretKey = "EXAMPLESECRETKEY"
</code>```

The logs contain the following message for each of the services it finds:

```<code>07/12/2017 15:21:33DEBU[2017-12-07T15:21:33Z] Filtering service service/stack-name without traefik.port label
</code>```

Screenshot of blank Rancher tab

I've tried this on version 1.4, 1.5-rc1 and 1.5-rc2.

The instructions for the Rancher backend don't mention having to set the traefik.port label and I don't want to set it. I just want to use port 80 on all containers that expose it.

答:
It looks like traefik is connecting to Rancher fine. What kind of labels do you have set on the containers in Rancher? Reading your error it looks like the dockers in Rancher need these labels:

```<code>traefik.port=12345
</code>```

Or add a mapped port on your dockers in Rancher.

Body:
I've been trying to get Traefik to work with the Rancher backend by following the documentation but when looking at the web interface I always get a Rancher tab that is completely blank.

Starting the container with the following parameters gives me the blank page:

--web.address=0.0.0.0:8080
--rancher
--rancher.domain=subdomain.example.co.uk
--rancher.endpoint=https://rancher.example.co.uk/v1
--rancher.accesskey=EXAMPLEKEY
--rancher.secretkey=EXAMPLESECRETKEY
--logLevel=DEBUG

Likewise the equivalent config file gives the same result:

logLegel = "DEBUG"
defaultEntryPoints = ["http"]
[entryPoints]
  [entryPoints.http]
  address = ":80"

[web]
address = ":8080"

[rancher]
domain = "subdomain.example.co.uk"
  [rancher.api]
  endpoint = "https://rancher.example.co.uk/v1"
  accessKey = "EXAMPLEKEY"
  secretKey = "EXAMPLESECRETKEY"

The logs contain the following message for each of the services it finds:

07/12/2017 15:21:33DEBU[2017-12-07T15:21:33Z] Filtering service service/stack-name without traefik.port label

Screenshot of blank Rancher tab

I've tried this on version 1.4, 1.5-rc1 and 1.5-rc2.

The instructions for the Rancher backend don't mention having to set the traefik.port label and I don't want to set it. I just want to use port 80 on all containers that expose it.

Body:
It looks like traefik is connecting to Rancher fine. What kind of labels do you have set on the containers in Rancher? Reading your error it looks like the dockers in Rancher need these labels:

traefik.port=12345

Or add a mapped port on your dockers in Rancher.


问:
How to union two collections without overriding any value
I am trying to get the union of two collections without overriding any value:

First Collection:

```<code>Collection {#246 ▼
  #items: array [▼
    0 => array [▼
      "status" => "Invoice"
      "letterPaymentAmount" => 4240.0
      "BankAccountNo" => "SEK"
      "Date" => "2017-07-15T16:32:22"
      "DueDate" => "2017-07-28T00:00:00"
      "ocr" => "3000000202"
      "lastDatePayDay" => "28"
   ]]}
</code>```

Second Collection

```<code>Collection {#246 ▼
  #items: array [▼
    0 => array [▼
  "status": "Reminder",
  "letterPaymentAmount": 4300,
  "BankAccountNo": "SEK",
  "Date": "2017-08-15T16:01:30",
  "DueDate": "2017-08-30T00:00:00",
  "ocr": "3000002406",
  "lastDatePayDay": "30",
  "lastDatePayMonth": "Aug",
  "Country": "Singapore",
  "Customer": "TickTack"
   ]]}
</code>```

I want to acomplish this:

```<code>Collection {#246 ▼
  #items: array [▼
    0 => array [▼
      "status" => "Invoice"
      "letterPaymentAmount" => 4240.0
      "BankAccountNo" => "SEK"
      "Date" => "2017-07-15T16:32:22"
      "DueDate" => "2017-07-28T00:00:00"
      "ocr" => "3000000202"
      "lastDatePayDay" => "28"],
    1=> [
      "status": "Reminder",
      "letterPaymentAmount": 4300,
      "BankAccountNo": "SEK",
      "Date": "2017-08-15T16:01:30",
      "DueDate": "2017-08-30T00:00:00",
      "ocr": "3000002406",
      "lastDatePayDay": "30",
      "lastDatePayMonth": "Aug",
      "Country": "Singapore",
      "Customer": "TickTack"  ]]}
</code>```

I do not want to override any existing key or value just add them together.

I have tried union() but that overrides the existing keys and does not take keys that do not exist in first collection .

Any help would be much appreciated

答:
Use push to add new items to an existing collection without editing items.

```<code>$collection = collect([['a' => 'b']]);
$collection2 = collect([['c' => 'd']]);
$collection2->each(function ($e) use (&$collection) {
    $collection->push($e);
});
</code>```

Body:
I am trying to get the union of two collections without overriding any value:

First Collection:

Collection {#246 ▼
  #items: array [▼
    0 => array [▼
      "status" => "Invoice"
      "letterPaymentAmount" => 4240.0
      "BankAccountNo" => "SEK"
      "Date" => "2017-07-15T16:32:22"
      "DueDate" => "2017-07-28T00:00:00"
      "ocr" => "3000000202"
      "lastDatePayDay" => "28"
   ]]}

Second Collection

Collection {#246 ▼
  #items: array [▼
    0 => array [▼
  "status": "Reminder",
  "letterPaymentAmount": 4300,
  "BankAccountNo": "SEK",
  "Date": "2017-08-15T16:01:30",
  "DueDate": "2017-08-30T00:00:00",
  "ocr": "3000002406",
  "lastDatePayDay": "30",
  "lastDatePayMonth": "Aug",
  "Country": "Singapore",
  "Customer": "TickTack"
   ]]}

I want to acomplish this:

Collection {#246 ▼
  #items: array [▼
    0 => array [▼
      "status" => "Invoice"
      "letterPaymentAmount" => 4240.0
      "BankAccountNo" => "SEK"
      "Date" => "2017-07-15T16:32:22"
      "DueDate" => "2017-07-28T00:00:00"
      "ocr" => "3000000202"
      "lastDatePayDay" => "28"],
    1=> [
      "status": "Reminder",
      "letterPaymentAmount": 4300,
      "BankAccountNo": "SEK",
      "Date": "2017-08-15T16:01:30",
      "DueDate": "2017-08-30T00:00:00",
      "ocr": "3000002406",
      "lastDatePayDay": "30",
      "lastDatePayMonth": "Aug",
      "Country": "Singapore",
      "Customer": "TickTack"  ]]}

I do not want to override any existing key or value just add them together.

I have tried union() but that overrides the existing keys and does not take keys that do not exist in first collection .

Any help would be much appreciated

Body:
Use push to add new items to an existing collection without editing items.

$collection = collect([['a' => 'b']]);
$collection2 = collect([['c' => 'd']]);
$collection2->each(function ($e) use (&$collection) {
    $collection->push($e);
});