问:
Titanium/ Appcelerator/ Alloy: Unable to get current location despite success returning true
I am running the following code using the iPhone 4s simulater:

```<code>Ti.Geolocation.getCurrentPosition(function(e){
    Ti.API.log(JSON.stringify(e));
});
</code>```

A formatted version of the output of the above gives the following information:

```<code>{
    "code": 0,
    "type":"location",
    "error":"The operation couldn’t be completed. (kCLErrorDomain error 0.)",
    "source":{},
    "success":true
}
</code>```

There seems to be quite contradictory information. It says success is true yet gives an error message.

Furthermore, according to the Location Results Docs, it says that if success is true, it should return a coords field. Yet the above does not have coords on it.

Please also note both of the following returns true so its not a permission issue:

Ti.Geolocation.locationServicesEnabled;
Ti.Geolocation.hasLocationPermissions(Ti.Geolocation.AUTHORIZATION_ALWAYS);

答:
There are 2 things to take notes of:

locationServicesEnabled property for device

hasLocationPermissions method

First of all, you will need to check for 1st property to make sure that the device location is on.

Then you will check for hasLocationPermissions because this can be true even the device location is not on, which I think is your case.

Sample code for this:

```<code>var authType = Ti.Geolocation. AUTHORIZATION_ALWAYS;

if (Ti.Geolocation.locationServicesEnabled) {
    if (Ti.Geolocation.hasLocationPermissions(authType)) {
        // voila...
    } else {
        Ti.Geolocation.requestLocationPermissions(authType, function (e) {
            if (e.success) {
                alert('voila...');
            }
        });
    }

} else {
   alert('Please turn on your device's location');
}
</code>```

Body:
I am running the following code using the iPhone 4s simulater:

Ti.Geolocation.getCurrentPosition(function(e){
    Ti.API.log(JSON.stringify(e));
});

A formatted version of the output of the above gives the following information:

{
    "code": 0,
    "type":"location",
    "error":"The operation couldn’t be completed. (kCLErrorDomain error 0.)",
    "source":{},
    "success":true
}

There seems to be quite contradictory information. It says success is true yet gives an error message.

Furthermore, according to the Location Results Docs, it says that if success is true, it should return a coords field. Yet the above does not have coords on it.

Please also note both of the following returns true so its not a permission issue:

Ti.Geolocation.locationServicesEnabled;
Ti.Geolocation.hasLocationPermissions(Ti.Geolocation.AUTHORIZATION_ALWAYS);

Body:
There are 2 things to take notes of:

locationServicesEnabled property for device

hasLocationPermissions method

First of all, you will need to check for 1st property to make sure that the device location is on.

Then you will check for hasLocationPermissions because this can be true even the device location is not on, which I think is your case.

Sample code for this:

var authType = Ti.Geolocation. AUTHORIZATION_ALWAYS;

if (Ti.Geolocation.locationServicesEnabled) {
    if (Ti.Geolocation.hasLocationPermissions(authType)) {
        // voila...
    } else {
        Ti.Geolocation.requestLocationPermissions(authType, function (e) {
            if (e.success) {
                alert('voila...');
            }
        });
    }

} else {
   alert('Please turn on your device's location');
}


来源: stackexchange

问:
How to query (LINQ) multiple table association link?
I have tables association such as (CaseClient is a bridge table):

Cases has many CaseClients

Client has many CaseClients

ClientType has many CaseClient

The easiest way just use the view in database but I heard that with linq you can join this somehow?  Or should I just created view in the database and linq query agains that view?

I am appreciated your comment

答:
I think you want to use the Join method, from your bridging table and resolving each of your relationships.  E.g.

```<code>// Where CaseId and TypeId are your members of CaseClient
var x = caseClients.Join( cases, cc => cc.CaseId, c => c.Id)
                                .Join( types, cc => cc.TypeId, t => t.Id)
                                .Select();
</code>```

Above code untested (so far) and from memory.  You may need to put a Select between the two joins.

ContentLicense: CC BY-SA 2.5

Body:
I think you want to use the Join method, from your bridging table and resolving each of your relationships.  E.g.

// Where CaseId and TypeId are your members of CaseClient
var x = caseClients.Join( cases, cc => cc.CaseId, c => c.Id)
                                .Join( types, cc => cc.TypeId, t => t.Id)
                                .Select();

Above code untested (so far) and from memory.  You may need to put a Select between the two joins.

OwnerDisplayName: Ray Hayes


问:
max date changes with mindate in datepicker
Here,I have selected max date as 3 week from current date. but actually I don't want to shift max date until current week gets over. I want something like, when current week gets over again max date change to next week end.</p>

```<code>jQuery(document).ready(function ($) {
    $("#datepicker").datepicker({
        dateFormat: 'yy-mm-dd',
        showAnim: "slideDown",
        minDate: 0,
        maxDate: "+3w",
        beforeShowDay: $.datepicker.noWeekends
    });
});
</code>```

答:
It may help you getting the current date and then applying the max date on it</p>

```<code>[ https://jsfiddle.net/cse_tushar/AcbUf/ ]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here,I have selected max date as 3 week from current date. but actually I don't want to shift max date until current week gets over. I want something like, when current week gets over again max date change to next week end.

jQuery(document).ready(function ($) {
    $("#datepicker").datepicker({
        dateFormat: 'yy-mm-dd',
        showAnim: "slideDown",
        minDate: 0,
        maxDate: "+3w",
        beforeShowDay: $.datepicker.noWeekends
    });
});

Body:
It may help you getting the current date and then applying the max date on it

[ https://jsfiddle.net/cse_tushar/AcbUf/ ]


问:
Insert NEW RECORD to PostgreSQL Line by Line in C#
Good day!

I am a newbie in C#.NET (I came from VB6).

I want to Insert new record to my database using PostgreQL.

I can use a single line of code, like:

```<code>Insert into table1 values("value1","value2","value3");
</code>```

But I wanted to insert new record line by line, like:

```<code>rs.open("Select * from table1",con,AdOpenDynamic, AdLockOptimistic)
rs.Fields("Field1").value = value1
rs.Fields("Field2").value = value2
rs.Fields("Field3").value = value3
rs.Update
</code>```

Again, I am a newbie here. Also again, I can insert using a single INSERT statement.

But IF I have 40 Fields, the code is hard to read (for readability). If the code is line by line, it is easy to read and the code is easy to update.

Is there any way to do it? Any help will be appreciated!

Happy Coding!

答:
Thanks @reds for the Answer and suggestions. I realized my only problem is the code readability, not the code itself. As you have said, Insert Query is the best workaround. That's why I came up with the following structure:

```<code>////saving
        //CODE TO DATABASE
        NpgsqlConnection iConnect = new NpgsqlConnection("Server=localhost;Port=5432;User ID=postgres;Password=sdferekrjsdf873()#3s;Database=DB");
        iConnect.Open();
        NpgsqlCommand iQuery = new NpgsqlCommand
           ("insert into tblstudents_secure values('" +
            myModule.studID + "','" +
            myModule.studFname + "','" +
            myModule.studMname + "','" +
            myModule.studLname + "','" +
            myModule.studGrade + "','" +
            myModule.studSection + "','" +
            myModule.studHomeAdd + "','" +
            myModule.studProvAdd + "','" +
            myModule.studBday + "','" +
            myModule.studAge + "','" +
            myModule.studCivilStat + "','" +
            myModule.studHomeContact + "','" +
            myModule.studProvContact + "','" +
            myModule.studBplace + "','" +
            myModule.studGender + "','" +
            myModule.studReligion + "','" +
            myModule.studFather + "','" +
            myModule.studFatherOcc + "','" +
            myModule.studMother + "','" +
            myModule.studMotherOcc + "','" +
            myModule.studGuardian + "','" +
            myModule.studGuardianOcc + "','" +
            myModule.studGuardianRel + "','" +
            myModule.studGuardianContact + "','" +
            myModule.studOldSchool + "','" +
            myModule.studOldSchoolAdd  + "','" +
            myModule.studOldGrade + "','" +
            myModule.studOldSY + "','" +
            myModule.studIsTransfer + "','" +
            myModule.studHas137 + "','" +
            myModule.studHas138 + "','" +
            myModule.studHasGoodMoral + "','" +
            myModule.studHasNSO + "','" +
            myModule.studHasMed + "','" +
            myModule.studRemarks + "','" +
            myModule.studDateRegistered + "','" +
            myModule.studEnrollmentStatus + "')", iConnect);

        iQuery.ExecuteNonQuery();
        iConnect.Close();
</code>```

Where:
`

myModule

is a class handler of static strings studID, studFname, etc...

Happy Coding!

Body:
Good day!

I am a newbie in C#.NET (I came from VB6).

I want to Insert new record to my database using PostgreQL.

I can use a single line of code, like:

Insert into table1 values("value1","value2","value3");

But I wanted to insert new record line by line, like:

rs.open("Select * from table1",con,AdOpenDynamic, AdLockOptimistic)
rs.Fields("Field1").value = value1
rs.Fields("Field2").value = value2
rs.Fields("Field3").value = value3
rs.Update

Again, I am a newbie here. Also again, I can insert using a single INSERT statement.

But IF I have 40 Fields, the code is hard to read (for readability). If the code is line by line, it is easy to read and the code is easy to update.

Is there any way to do it? Any help will be appreciated!

Happy Coding!

Body:
Thanks @reds for the Answer and suggestions. I realized my only problem is the code readability, not the code itself. As you have said, Insert Query is the best workaround. That's why I came up with the following structure:

////saving
        //CODE TO DATABASE
        NpgsqlConnection iConnect = new NpgsqlConnection("Server=localhost;Port=5432;User ID=postgres;Password=sdferekrjsdf873()#3s;Database=DB");
        iConnect.Open();
        NpgsqlCommand iQuery = new NpgsqlCommand
           ("insert into tblstudents_secure values('" +
            myModule.studID + "','" +
            myModule.studFname + "','" +
            myModule.studMname + "','" +
            myModule.studLname + "','" +
            myModule.studGrade + "','" +
            myModule.studSection + "','" +
            myModule.studHomeAdd + "','" +
            myModule.studProvAdd + "','" +
            myModule.studBday + "','" +
            myModule.studAge + "','" +
            myModule.studCivilStat + "','" +
            myModule.studHomeContact + "','" +
            myModule.studProvContact + "','" +
            myModule.studBplace + "','" +
            myModule.studGender + "','" +
            myModule.studReligion + "','" +
            myModule.studFather + "','" +
            myModule.studFatherOcc + "','" +
            myModule.studMother + "','" +
            myModule.studMotherOcc + "','" +
            myModule.studGuardian + "','" +
            myModule.studGuardianOcc + "','" +
            myModule.studGuardianRel + "','" +
            myModule.studGuardianContact + "','" +
            myModule.studOldSchool + "','" +
            myModule.studOldSchoolAdd  + "','" +
            myModule.studOldGrade + "','" +
            myModule.studOldSY + "','" +
            myModule.studIsTransfer + "','" +
            myModule.studHas137 + "','" +
            myModule.studHas138 + "','" +
            myModule.studHasGoodMoral + "','" +
            myModule.studHasNSO + "','" +
            myModule.studHasMed + "','" +
            myModule.studRemarks + "','" +
            myModule.studDateRegistered + "','" +
            myModule.studEnrollmentStatus + "')", iConnect);

        iQuery.ExecuteNonQuery();
        iConnect.Close();

Where:
`

myModule

is a class handler of static strings studID, studFname, etc...

Happy Coding!


问:
Require login in a Django Channels socket?
I'm trying out Channels in Django 1.10 and set up a few consumers.

I tried creating a login_required decorator for it that closes the connection before executing it to prevent guests from entering this private socket. Also integrated unit tests afterwards to test it and they keep failing because it keeps letting guests in (AnonymousUser errors everywhere).

Also, sometimes when logging in and logging out the session doesn't clear and it lets the old user in.

The decorator:

```<code>def login_required_websocket(func):
    """
    If user is not logged in, close connection immediately.
    """
    @functools.wraps(func)
    def inner(message, *args, **kwargs):
        if not message.user.is_authenticated():
            message.reply_channel.send({'close': True})
        return func(message, *args, **kwargs)
    return inner
</code>```

Here's the consumer code:

```<code>def ws_connect(message, slug):
    message.reply_channel.send({ 'accept': True })
    client = message.reply_channel
    client.send(signal.message("Welcome"))
    try:
        # import pdb; pdb.set_trace()
        Room.objects.get(name=slug)
    except Room.DoesNotExist:
        room = Room.objects.create(name=slug)
        room.users.add(message.user)
        room.turn = message.user.id
        room.save()
        story = Story(room=room)
        story.save()

    # We made sure it exists.
    room = Room.objects.get(name=slug)
    message.channel_session['room'] = room.name

    # Check if user is allowed here.
    if not room.user_allowed(message.user):
        # Close the connection. User is not allowed.
        client.send(Signal.error("User isn't allowed in this room."))
        client.send({'close': True})
</code>```

The strange thing is, when commenting out all the logic between client.send(signal.message)) forwards, it works just fine and unit tests pass (meaning guests are blocked and auth code does not run [hence AnonymousUser errors]). Any ideas?

Here's the tests too:

```<code>class RoomsTests(ChannelTestCase):

    def test_reject_guest(self):
        """
        This tests whether the login_required_websocket decorator is rejecting guests.
        """
        client = HttpClient()
        user = User.objects.create_user(
            username='test', password='password')

        client.send_and_consume('websocket.connect',
                                path='/rooms/test_room', check_accept=False)
        self.assertEqual(client.receive(), {'close': True})

    def test_accept_logged_in(self):
        """
        This tests whether the connection is accepted when a user is logged in.
        """
        client = HttpClient()
        user = User.objects.create_user(
            username='test', password='password')
        client.login(username='test', password='password')

        client.send_and_consume('websocket.connect', path='/rooms/test_room')
</code>```

Am I approaching this wrong, and if I am, how do I do this (require auth) properly?

EDIT: Integrated an actions system to try something out, looks like Django channels is simply not picking up any sessions from HTTP at all.

```<code>@enforce_ordering
@channel_session_user_from_http
def ws_connect(message, slug):
    message.reply_channel.send({'accept': True})
    message.reply_channel.send(Action.info(message.user.is_authenticated()).to_send())
</code>```

Just returns false.

EDIT2: I see it works now, I tried changing localhost to 127.0.0.1 and turns out it works now. Is there a way to make it detect localhost as a valid domain so it ports over the sessions?

EDIT3: Turns out I found the localhost vs 127.0.0.1 cookie issue haha. To not waste the bounty, how would you personally implement auth login_required in messages/channels?

edit4: While I still don't know why the thing didn't work, here's how I eventually changed my app around the issue:

I created an actions system. When entering in, the socket does nothing until you send it an AUTHENTICATE action through JSON. I separated logged in actions in guest_actions and user_actions. Once authenticated, it sets the session and you are able to use user_actions.

答:
Django Channels already supports session authentication:

```<code># In consumers.py
from channels import Channel, Group
from channels.sessions import channel_session
from channels.auth import channel_session_user, channel_session_user_from_http

# Connected to websocket.connect
@channel_session_user_from_http
def ws_add(message):
    # Accept connection
    message.reply_channel.send({"accept": True})
    # Add them to the right group
    Group("chat-%s" % message.user.username[0]).add(message.reply_channel)

# Connected to websocket.receive
@channel_session_user
def ws_message(message):
    Group("chat-%s" % message.user.username[0]).send({
        "text": message['text'],
    })

# Connected to websocket.disconnect
@channel_session_user
def ws_disconnect(message):
    Group("chat-%s" % message.user.username[0]).discard(message.reply_channel)
</code>```

http://channels.readthedocs.io/en/stable/getting-started.html#authentication

Body:
I'm trying out Channels in Django 1.10 and set up a few consumers.

I tried creating a login_required decorator for it that closes the connection before executing it to prevent guests from entering this private socket. Also integrated unit tests afterwards to test it and they keep failing because it keeps letting guests in (AnonymousUser errors everywhere).

Also, sometimes when logging in and logging out the session doesn't clear and it lets the old user in.

The decorator:

def login_required_websocket(func):
    """
    If user is not logged in, close connection immediately.
    """
    @functools.wraps(func)
    def inner(message, *args, **kwargs):
        if not message.user.is_authenticated():
            message.reply_channel.send({'close': True})
        return func(message, *args, **kwargs)
    return inner

Here's the consumer code:

def ws_connect(message, slug):
    message.reply_channel.send({ 'accept': True })
    client = message.reply_channel
    client.send(signal.message("Welcome"))
    try:
        # import pdb; pdb.set_trace()
        Room.objects.get(name=slug)
    except Room.DoesNotExist:
        room = Room.objects.create(name=slug)
        room.users.add(message.user)
        room.turn = message.user.id
        room.save()
        story = Story(room=room)
        story.save()

    # We made sure it exists.
    room = Room.objects.get(name=slug)
    message.channel_session['room'] = room.name

    # Check if user is allowed here.
    if not room.user_allowed(message.user):
        # Close the connection. User is not allowed.
        client.send(Signal.error("User isn't allowed in this room."))
        client.send({'close': True})

The strange thing is, when commenting out all the logic between client.send(signal.message)) forwards, it works just fine and unit tests pass (meaning guests are blocked and auth code does not run [hence AnonymousUser errors]). Any ideas?

Here's the tests too:

class RoomsTests(ChannelTestCase):

    def test_reject_guest(self):
        """
        This tests whether the login_required_websocket decorator is rejecting guests.
        """
        client = HttpClient()
        user = User.objects.create_user(
            username='test', password='password')

        client.send_and_consume('websocket.connect',
                                path='/rooms/test_room', check_accept=False)
        self.assertEqual(client.receive(), {'close': True})

    def test_accept_logged_in(self):
        """
        This tests whether the connection is accepted when a user is logged in.
        """
        client = HttpClient()
        user = User.objects.create_user(
            username='test', password='password')
        client.login(username='test', password='password')

        client.send_and_consume('websocket.connect', path='/rooms/test_room')

Am I approaching this wrong, and if I am, how do I do this (require auth) properly?

EDIT: Integrated an actions system to try something out, looks like Django channels is simply not picking up any sessions from HTTP at all.

@enforce_ordering
@channel_session_user_from_http
def ws_connect(message, slug):
    message.reply_channel.send({'accept': True})
    message.reply_channel.send(Action.info(message.user.is_authenticated()).to_send())

Just returns false.

EDIT2: I see it works now, I tried changing localhost to 127.0.0.1 and turns out it works now. Is there a way to make it detect localhost as a valid domain so it ports over the sessions?

EDIT3: Turns out I found the localhost vs 127.0.0.1 cookie issue haha. To not waste the bounty, how would you personally implement auth login_required in messages/channels?

edit4: While I still don't know why the thing didn't work, here's how I eventually changed my app around the issue:

I created an actions system. When entering in, the socket does nothing until you send it an AUTHENTICATE action through JSON. I separated logged in actions in guest_actions and user_actions. Once authenticated, it sets the session and you are able to use user_actions.

Body:
Django Channels already supports session authentication:

# In consumers.py
from channels import Channel, Group
from channels.sessions import channel_session
from channels.auth import channel_session_user, channel_session_user_from_http

# Connected to websocket.connect
@channel_session_user_from_http
def ws_add(message):
    # Accept connection
    message.reply_channel.send({"accept": True})
    # Add them to the right group
    Group("chat-%s" % message.user.username[0]).add(message.reply_channel)

# Connected to websocket.receive
@channel_session_user
def ws_message(message):
    Group("chat-%s" % message.user.username[0]).send({
        "text": message['text'],
    })

# Connected to websocket.disconnect
@channel_session_user
def ws_disconnect(message):
    Group("chat-%s" % message.user.username[0]).discard(message.reply_channel)

http://channels.readthedocs.io/en/stable/getting-started.html#authentication


问:
Android app main content is above title bar
Im building an android app in visual studio. in my feed.axml file my main body content is floating above my title bar. it should be below the title bar. i am confused as to why my code is doing this.

my android app as of this post
the content which is shown in this image that is above the title bar is a card and large text. if anyone knows how to float these elements below the title bar please tell me.

any help would be appreciated

here is my xml code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.DrawerLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_height="match_parent"
    android:layout_width="fill_parent"
    android:fitsSystemWindows="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <android.support.v7.widget.CardView
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/cardView1" />
        <TextView
            android:text="hello world"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView1" />
        <include
            layout="@layout/toolbar" />
    </LinearLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_height="match_parent"
        android:layout_width="300dp"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header" />
</android.support.v4.widget.DrawerLayout>
</code>```

答:
Replace your code with this

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
  layout="@layout/toolbar" />
<android.support.v4.widget.DrawerLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_height="match_parent"
    android:layout_width="fill_parent"
    android:fitsSystemWindows="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <android.support.v7.widget.CardView
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/cardView1" />
        <TextView
            android:text="hello world"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView1" />

    </LinearLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_height="match_parent"
        android:layout_width="300dp"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header" />
</android.support.v4.widget.DrawerLayout>
</code>```

LinearLayout places its child linearly, so you need to do something like this.
You can also place your toolbar thingy somewhere before CardView

Body:
Im building an android app in visual studio. in my feed.axml file my main body content is floating above my title bar. it should be below the title bar. i am confused as to why my code is doing this.

my android app as of this post
the content which is shown in this image that is above the title bar is a card and large text. if anyone knows how to float these elements below the title bar please tell me.

any help would be appreciated

here is my xml code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.DrawerLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_height="match_parent"
    android:layout_width="fill_parent"
    android:fitsSystemWindows="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <android.support.v7.widget.CardView
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/cardView1" />
        <TextView
            android:text="hello world"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView1" />
        <include
            layout="@layout/toolbar" />
    </LinearLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_height="match_parent"
        android:layout_width="300dp"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header" />
</android.support.v4.widget.DrawerLayout>

Body:
Replace your code with this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
  layout="@layout/toolbar" />
<android.support.v4.widget.DrawerLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_height="match_parent"
    android:layout_width="fill_parent"
    android:fitsSystemWindows="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <android.support.v7.widget.CardView
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/cardView1" />
        <TextView
            android:text="hello world"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView1" />

    </LinearLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_height="match_parent"
        android:layout_width="300dp"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header" />
</android.support.v4.widget.DrawerLayout>

LinearLayout places its child linearly, so you need to do something like this.
You can also place your toolbar thingy somewhere before CardView


问:
How do I install this package on a Linux (Centos) machine?
I found this package on GitHub (doctotext). I'd like to install it on my Centos-running dedicated server (x86_64), but I do not know how. Could someone offer instructions as to how I could do it. There are no instructions provided, unfortunately</p>

答:
There is a Makefile, so try to:

git clone the repo anywhere you want (typically within your home account)

```<code>cd
git clone https://github.com/karlproject/doctotext
cd doctotext
</code>```

type make and make install

You will then see if you can build and install it by compilation.

Body:
There is a Makefile, so try to:

git clone the repo anywhere you want (typically within your home account)

cd
git clone https://github.com/karlproject/doctotext
cd doctotext

type make and make install

You will then see if you can build and install it by compilation.


问:
Java sorting parallel arrays, help needed (NullPointerException Error)
Ok I am trying to finish this program for my into to java class and I am having trouble with this one part. Everything else is working except this. I have 3 arrays, 1 string, 2 type int, all parallel. I have to sort these into alphabetical order by name then by number (using the string array first, then the first int array, sorting is not affected by the third array, it is there to practice parallel in 3 dimensions)

This is the code I have so far.

```<code>    public static void sortDatabase(int numRecords, String[] sDeptArr,
              int[] iCourseNumArr, int[] iEnrollmentArr)
   {
       System.out.println("Sort the database. \n");
       String sTemp = null;
       int iTemp = 0;
       int eTemp = 0;
       for(int i=0; i<numRecords; i++)
       {
           int iPosMin = i;
           for(int j=i+1; j<numRecords; j++)
           {
               String a = sDeptArr[j];
               String b = sDeptArr[iPosMin];
               if(a.compareTo(b) != 0)
                   iPosMin = j;
               else if(!sDeptArr[j].equals(sDeptArr[iPosMin]) && iCourseNumArr[j] < iCourseNumArr[iPosMin])
                   iPosMin = j;
           }
           sDeptArr[i] = sTemp;
           sDeptArr[i] = sDeptArr[iPosMin];
           sDeptArr[iPosMin] = sTemp;
           iCourseNumArr[i] = iTemp;
           iCourseNumArr[i] = iCourseNumArr[iPosMin];
           iCourseNumArr[iPosMin] = iTemp;
           iEnrollmentArr[i] = eTemp;
           iEnrollmentArr[i] = iEnrollmentArr[iPosMin];
           iEnrollmentArr[iPosMin] = eTemp;
       }
   }
</code>```

It has to be done in java. I am getting an error in the 15th line consisting of

```<code>if(a.compareTo(b) != 0)
</code>```

and I am getting a NullPointerException.

Basically I am sorting fake class names and course numbers while keeping the number of people enrolled parallel with its corresponding index to the course name and number.

答:
This may happen only if a==null. But a is sDeptArr[j]. It means that this element of array is null.

So, data that you are sending to this method is inconsistent.

But why are you implementing sorting this way? The "right" way to solve this problem is to create new data structure that contains as many fields as you need. Then create one array and sort it using Arrays.sort(). The data structure I mentioned should implement Comparable.

Even if this is an exercise for sorting, create the data structure, one array and write sorting algorithm.

And yet another note. It seems that you have a C background because your method accepts array(s) and the length as separate parameter. Java arrays "know" their length. Use a.length to retrieve the length of array a.

Body:
Ok I am trying to finish this program for my into to java class and I am having trouble with this one part. Everything else is working except this. I have 3 arrays, 1 string, 2 type int, all parallel. I have to sort these into alphabetical order by name then by number (using the string array first, then the first int array, sorting is not affected by the third array, it is there to practice parallel in 3 dimensions)

This is the code I have so far.

    public static void sortDatabase(int numRecords, String[] sDeptArr,
              int[] iCourseNumArr, int[] iEnrollmentArr)
   {
       System.out.println("Sort the database. \n");
       String sTemp = null;
       int iTemp = 0;
       int eTemp = 0;
       for(int i=0; i<numRecords; i++)
       {
           int iPosMin = i;
           for(int j=i+1; j<numRecords; j++)
           {
               String a = sDeptArr[j];
               String b = sDeptArr[iPosMin];
               if(a.compareTo(b) != 0)
                   iPosMin = j;
               else if(!sDeptArr[j].equals(sDeptArr[iPosMin]) && iCourseNumArr[j] < iCourseNumArr[iPosMin])
                   iPosMin = j;
           }
           sDeptArr[i] = sTemp;
           sDeptArr[i] = sDeptArr[iPosMin];
           sDeptArr[iPosMin] = sTemp;
           iCourseNumArr[i] = iTemp;
           iCourseNumArr[i] = iCourseNumArr[iPosMin];
           iCourseNumArr[iPosMin] = iTemp;
           iEnrollmentArr[i] = eTemp;
           iEnrollmentArr[i] = iEnrollmentArr[iPosMin];
           iEnrollmentArr[iPosMin] = eTemp;
       }
   }

It has to be done in java. I am getting an error in the 15th line consisting of

if(a.compareTo(b) != 0)

and I am getting a NullPointerException.

Basically I am sorting fake class names and course numbers while keeping the number of people enrolled parallel with its corresponding index to the course name and number.


问:
Accessing "Media" files in Django
I'd like to love Django, but this business of static and media files in development environments is driving me nuts. Please rescue me from my stupidity.

I'm on my development machine. I have folder media in the root of my project directory.

In settings.py I have: MEDIA_ROOT = '' and MEDIA_URL = '/media/'.

In urls.py I have:

```<code>if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^media/(?P<path>.*)$',
            'django.views.static.serve',
            {'document_root': settings.MEDIA_ROOT, }),
    )
</code>```

But the only way I can get media files is by referencing /media/media/ e.g.
.

I expect (and want)

Can anyone tell me what is happening here, and give me a simple recipe for setting up media file handling?

Thank you very much.

@Timmy O'Mahony - thanks! epic post, and very clear. But it leaves a couple of questions:

(1) I have to use /media/ and /static/, not media/ and static/ as MEDIA_URL and and STATIC_URL - am I missing something?

(2) If collectstatic hoses /static/, where do you put site level CSS e.g. the site's CSS files? Not in /static/, evidently.

(3) I put them in a directory '_' off the project root and set STATICFILES_DIRS to point to it - and that seems to be where the development server gets its static files, despite the urlpatterns directive. If THAT is wrong, where do you put site level CSS during development, and what is the workflow around collectstatic when you modify them - do you have to edit them one place, and collect them someplace else after every edit?

答:
I am using Django 1.10. And my media folder is 'uploads'
This is the configuration in my settings.py:

```<code>MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/uploads/'
</code>```

And in the template I put the name o my MEDIA_URL before de object.name instead object.url like this:

```<code>    <img src="uploads/{{ imagen_identificativa.name }} " alt="{{imagen_identificativa}}">
</code>```

And it works for me.
I hope this helps.

Title: Accessing "Media" files in Django

Body:
I'd like to love Django, but this business of static and media files in development environments is driving me nuts. Please rescue me from my stupidity.

I'm on my development machine. I have folder media in the root of my project directory.

In settings.py I have: MEDIA_ROOT = '' and MEDIA_URL = '/media/'.

In urls.py I have:

if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^media/(?P<path>.*)$',
            'django.views.static.serve',
            {'document_root': settings.MEDIA_ROOT, }),
    )

But the only way I can get media files is by referencing /media/media/ e.g.
.

I expect (and want)

Can anyone tell me what is happening here, and give me a simple recipe for setting up media file handling?

Thank you very much.

@Timmy O'Mahony - thanks! epic post, and very clear. But it leaves a couple of questions:

(1) I have to use /media/ and /static/, not media/ and static/ as MEDIA_URL and and STATIC_URL - am I missing something?

(2) If collectstatic hoses /static/, where do you put site level CSS e.g. the site's CSS files? Not in /static/, evidently.

(3) I put them in a directory '_' off the project root and set STATICFILES_DIRS to point to it - and that seems to be where the development server gets its static files, despite the urlpatterns directive. If THAT is wrong, where do you put site level CSS during development, and what is the workflow around collectstatic when you modify them - do you have to edit them one place, and collect them someplace else after every edit?

Body:
I am using Django 1.10. And my media folder is 'uploads'
This is the configuration in my settings.py:

MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/uploads/'

And in the template I put the name o my MEDIA_URL before de object.name instead object.url like this:

    <img src="uploads/{{ imagen_identificativa.name }} " alt="{{imagen_identificativa}}">

And it works for me.
I hope this helps.


问:
What will happen to my App by Device Reset Date?
My Apple developer membership will expire in several days. So I renewed my membership just now. But I found Device Reset Date remained at August 27, 2016. It's the first time I renew my Apple membership. I don't know what I should do with my App. Should I renew my profiles/certificates? If yes, will my online Apps be able to receive remote notifications?

答: You will be presented with the option to reset your device list on that day...because you have a 100 device limit, you may wish to remove devices that are no longer being used for testing.</p>


问:
Calculate the percentage for python dictionary
I want to calculate the percentage of the occurrences of the values in a dictionary. d.values/sum(d.values)*100 it gives error: unsupported operand type(s) for /: 'list' and 'int' you cannot divide the whole list with any integer. I think, and I tried with  d=(Counter([Counter(i)['1'] for i in  f.readlines()])) at the time of counting you can calculate the percentage but it didn't work. If anyone has an idea, please let me known.

```<code>from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
import pylab as pl
with open("data_binary.txt") as f:
    d=(Counter([Counter(i)['1'] for i in  f.readlines()]))
    print d

    p = d.values()
    X = np.arange(len(d))
    pl.bar(X, p, align='center',width=0.25)
    a = np.array(d.items())
    pl.xticks(X,d.keys())
    a = a[np.argsort(a[:,0])]
    #print a
    ymax=max(d.values())+1
    pl.ylim(0, 70000)
    plt.xlabel ("Number of ones")
    plt.ylabel ("Number of Signatures")
    plt.title("Adder@1")
    pl.show()
</code>```

答:
Use numpy</p>

```<code>x = np.array(d.values())
print x*100.0/sum(x)
</code>```

Body:
I want to calculate the percentage of the occurrences of the values in a dictionary. d.values/sum(d.values)*100 it gives error: unsupported operand type(s) for /: 'list' and 'int' you cannot divide the whole list with any integer. I think, and I tried with  d=(Counter([Counter(i)['1'] for i in  f.readlines()])) at the time of counting you can calculate the percentage but it didn't work. If anyone has an idea, please let me known.

from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
import pylab as pl
with open("data_binary.txt") as f:
    d=(Counter([Counter(i)['1'] for i in  f.readlines()]))
    print d

    p = d.values()
    X = np.arange(len(d))
    pl.bar(X, p, align='center',width=0.25)
    a = np.array(d.items())
    pl.xticks(X,d.keys())
    a = a[np.argsort(a[:,0])]
    #print a
    ymax=max(d.values())+1
    pl.ylim(0, 70000)
    plt.xlabel ("Number of ones")
    plt.ylabel ("Number of Signatures")
    plt.title("Adder@1")
    pl.show()

Body:
Use numpy

x = np.array(d.values())
print x*100.0/sum(x)


问:
QScopedPointer declaration in header, definition in src
Can you have a QScopedPointer declared in a header:

```<code>QScopedPointer <T> _name;
</code>```

And in the .cpp definition/instantiation:

```<code>_name ( /*new T*/ );
</code>```

Note: i am aware that QScopedPointer doesn't have the operator to do this, only a ctor, but conceptually, can this be inplemented somehow?

答:
Can we use QScopedPointer<T>-typed class member in the header with our
  class declaration?

Yes. Make sure that the type T either defined or declared:

```<code>///
/// File MyClass.h
///

// Either have:
#include "MyType.h" // defines MyType

// Or:
class MyType; // forward declaraion

class MyClass
{
public:
    MyClass();
    ////
private:
    QScopedPointer<MyType> m_pTypeObj;
};
</code>```

But you should always have the type defined where you instantiate the object and store the pointer in that QScopedPointer<MyType>:

```<code>#include "MyClass.h" // defines MyClass
// If not through MyClass.h then must have:
#include "MyType.h"  // defines MyType

MyClass::MyClass()
{
    // now we can instantiate MyType
    m_pTypeObj.reset(new MyType);
    // and use the scoped pointer
    m_pTypeObj->method();
}
</code>```

Or maybe as the author implies:

```<code>MyClass::MyClass() : m_pTypeObj(new MyType)
{
    // and use the scoped pointer
    m_pTypeObj->method();
}
</code>```

The approach is also applicable to std::unique_ptr which can now replace QScopedPointer.

Body:
Can you have a QScopedPointer declared in a header:

QScopedPointer <T> _name;

And in the .cpp definition/instantiation:

_name ( /*new T*/ );

Note: i am aware that QScopedPointer doesn't have the operator to do this, only a ctor, but conceptually, can this be inplemented somehow?

Body:
Can we use QScopedPointer<T>-typed class member in the header with our
  class declaration?

Yes. Make sure that the type T either defined or declared:

///
/// File MyClass.h
///

// Either have:
#include "MyType.h" // defines MyType

// Or:
class MyType; // forward declaraion

class MyClass
{
public:
    MyClass();
    ////
private:
    QScopedPointer<MyType> m_pTypeObj;
};

But you should always have the type defined where you instantiate the object and store the pointer in that QScopedPointer<MyType>:

#include "MyClass.h" // defines MyClass
// If not through MyClass.h then must have:
#include "MyType.h"  // defines MyType

MyClass::MyClass()
{
    // now we can instantiate MyType
    m_pTypeObj.reset(new MyType);
    // and use the scoped pointer
    m_pTypeObj->method();
}

Or maybe as the author implies:

MyClass::MyClass() : m_pTypeObj(new MyType)
{
    // and use the scoped pointer
    m_pTypeObj->method();
}

The approach is also applicable to std::unique_ptr which can now replace QScopedPointer.


问:
Ionic 2 floating ion-labels issue
I'm having an issue with some of the floating labels that I'm using but not all of them, which makes it even stranger. As far as I can see my ion-items are written exactly the same. Below are some pictures to show the issue.
I'm not sure whether this is a bug in Ionic 2 or if I'm doing something wrong. If there's anything unclear or you need more code, feel free to ask.

As you can see, the description and photo/video label are already acting like they should when they're in focus (they're not) but it's not displaying the highlights.

Here is an image where I put it in focus and then out of focus again.

Once I do that it works correctly.

The html I wrote:

```<code><ion-content padding>
  <form [formGroup]="complaint" (ngSubmit)="send()">

    <ion-item>
      <ion-label floating>Description*</ion-label>
      <ion-textarea [(ngModel)]="description" type="text" formControlName="description"></ion-textarea>
    </ion-item>

    <ion-item>
      <ion-label floating>Number of completed tests*</ion-label>
      <ion-input [(ngModel)]="nrTests" type="number" formControlName="nrTests"></ion-input>
    </ion-item>

    <ion-item>
      <ion-label floating>Photo/Video</ion-label>
      <ion-input [(ngModel)]="media" formControlName="media"></ion-input>
    </ion-item>

    <button ion-button type="submit" [disabled]="!complaint.valid">Send</button>

  </form>
</ion-content>
</code>```

答: Use stacked attribute to the ionic label and use the ion-item with in the ion-list.</p>

Title: Ionic 2 floating ion-labels issue

Body:
I'm having an issue with some of the floating labels that I'm using but not all of them, which makes it even stranger. As far as I can see my ion-items are written exactly the same. Below are some pictures to show the issue.
I'm not sure whether this is a bug in Ionic 2 or if I'm doing something wrong. If there's anything unclear or you need more code, feel free to ask.

As you can see, the description and photo/video label are already acting like they should when they're in focus (they're not) but it's not displaying the highlights.

Here is an image where I put it in focus and then out of focus again.

Once I do that it works correctly.

The html I wrote:

<ion-content padding>
  <form [formGroup]="complaint" (ngSubmit)="send()">

    <ion-item>
      <ion-label floating>Description*</ion-label>
      <ion-textarea [(ngModel)]="description" type="text" formControlName="description"></ion-textarea>
    </ion-item>

    <ion-item>
      <ion-label floating>Number of completed tests*</ion-label>
      <ion-input [(ngModel)]="nrTests" type="number" formControlName="nrTests"></ion-input>
    </ion-item>

    <ion-item>
      <ion-label floating>Photo/Video</ion-label>
      <ion-input [(ngModel)]="media" formControlName="media"></ion-input>
    </ion-item>

    <button ion-button type="submit" [disabled]="!complaint.valid">Send</button>

  </form>
</ion-content>


问:
Identifier not found FindFirstFile
I'm trying to use this function FindFirstFile that is in the windows API and I've used it before but I can't find it anymore. It just tells me identifier not found. I have other variations of it FindFirstFileExW, FindFirstFileExA, and FindFirstFileEx but I don't have FindFirstFile. I can even include the specific header that it is supposed to be in FileAPI.h. I read on here with a similar problem that I should include stdafx.h before windows.h but I can't even find stdafx.h.

https://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx

If you can't answer the question could one describe how to use FindFirstFileEx to do the same thing as FindFirstFile as FindFirstFileEx has been described on msdn as being FindFirstFile with more attributes too it.

答:
According to APIs present on all Windows 10 devices, FindFirstFile is present in Windows 10 from version 10.0.14393.0, whereas FindFirstFileEx from version 10.0.10240.0. 14393 is the Anniversary Update, and 10240 from "Threshold 1" a.k.a. RTM a.k.a. "Version 1507". So it's possible you have an older version of Windows API. I'm not sure why Microsoft would include one function but not the other, when both were available previously - maybe just an oversight?

So your simplest solution is to upgrade to Windows 10 Anniversary Update or later.

Failing that, it's also a very simple code change. According to TFM:

The following call:

```<code>FindFirstFileEx( lpFileName,
                 FindExInfoStandard,
                 lpFindData,
                 FindExSearchNameMatch,
                 NULL,
                 0 );
</code>```

Is equivalent to the following call:

```<code>FindFirstFile( lpFileName, lpFindData );
</code>```

Title: Identifier not found FindFirstFile

Body:
According to APIs present on all Windows 10 devices, FindFirstFile is present in Windows 10 from version 10.0.14393.0, whereas FindFirstFileEx from version 10.0.10240.0. 14393 is the Anniversary Update, and 10240 from "Threshold 1" a.k.a. RTM a.k.a. "Version 1507". So it's possible you have an older version of Windows API. I'm not sure why Microsoft would include one function but not the other, when both were available previously - maybe just an oversight?

So your simplest solution is to upgrade to Windows 10 Anniversary Update or later.

Failing that, it's also a very simple code change. According to TFM:

The following call:

FindFirstFileEx( lpFileName,
                 FindExInfoStandard,
                 lpFindData,
                 FindExSearchNameMatch,
                 NULL,
                 0 );

Is equivalent to the following call:

FindFirstFile( lpFileName, lpFindData );


问:
Exponential of large negative numbers
How does one compute a number such as np.exp(-28000) on Python? The answer is around 5E-12161. I've been told that due to the double-precision floating point format, I would only be able to calculate a number > 1e-2048</p>

答:
Try mpmath for floating-point arithmetic with arbitrary precision

Edit 1:

```<code>>>> import mpmath as mp
>>> import numpy as np
>>> a = np.matrix((0,0))
>>> print(a)
[0.0 0.0]
>>> b = mp.matrix(a.tolist())
>>> c = b.apply(mp.exp)
>>> print(c)
[1.0]
[1.0]
</code>```

Title: Exponential of large negative numbers

Body:
Try mpmath for floating-point arithmetic with arbitrary precision

Edit 1:

>>> import mpmath as mp
>>> import numpy as np
>>> a = np.matrix((0,0))
>>> print(a)
[0.0 0.0]
>>> b = mp.matrix(a.tolist())
>>> c = b.apply(mp.exp)
>>> print(c)
[1.0]
[1.0]


问:
How to convert "/Date(1490065200000)/" to "21/03/2017"?
Please check in jsfiddle.

Code:

```<code>$( document ).ready(function() {
  var str = moment("/Date(1490065200000)/"); //Convert to "21/03/2017"
  console.log(str.toString());
});
</code>```

Here docs: https://momentjs.com/docs/#/parsing/asp-net-json-date/

Any Solution ?

答:
You could use a regexp with a capture group.

```<code>str = "/Date(1490065200000)/"
timestamp = parseInt(str.match(/Date\((\d+)\)/)[1])
formatted = moment(timestamp).format('DD/MM/YYY')
console.log(formatted)
</code>```

Explanation of the regexp /Date\((\d+)\)/:

Date will simply match string Date.

There are two pairs of parentheses. The outer one is escaped, hence the backslashes. This will literally match the parentheses characters as they appear in the date string.

The inner parentheses, because they are not escaped, delimit a capture group. These say "I want to keep whatever string this actually matches". The resulting match object will have the captured strings in an array, which we can reference with [1] to get the desired number.

Body:
Please check in jsfiddle.

Code:

$( document ).ready(function() {
  var str = moment("/Date(1490065200000)/"); //Convert to "21/03/2017"
  console.log(str.toString());
});

Here docs: https://momentjs.com/docs/#/parsing/asp-net-json-date/

Any Solution ?

Body:
You could use a regexp with a capture group.

str = "/Date(1490065200000)/"
timestamp = parseInt(str.match(/Date\((\d+)\)/)[1])
formatted = moment(timestamp).format('DD/MM/YYY')
console.log(formatted)

Explanation of the regexp /Date\((\d+)\)/:

Date will simply match string Date.

There are two pairs of parentheses. The outer one is escaped, hence the backslashes. This will literally match the parentheses characters as they appear in the date string.

The inner parentheses, because they are not escaped, delimit a capture group. These say "I want to keep whatever string this actually matches". The resulting match object will have the captured strings in an array, which we can reference with [1] to get the desired number.


问:
Call form request from controller based on request input
I have a controller that accepts input. This input is parsed by a request validation (POSRequest). If the request validation succeeded, the request is then passed into the controller. Standard laravel stuff.

I have to typehint in the controller POSRequest $requests in order to fire the request validation, how can I call other requests based on the input provided in POSRequest $request?

Here is some code to clear things up a bit:
public function process(POSRequest $request){ ... }

All of my requests come to process function and based on input of $requests i need to call other functions:
private function StartRequest(POSStartRequest $request) { ... }
private function CheckRequest(POSCheckRequest $request) { ... }

How can i call these frunctions from within the controller from within the process function and convert POSRequest to either one of other requests?

Thank you in advance!

答:
You can manually create validators in controller method</p>

```<code>public function process(Request $request) {
        $rulesFirstRequest = ['field1' => 'required', 'field2' => 'required'];
        $rulesSecondRequest = ['field12' => 'required', 'field22' => 'required'];

        $validator1 = Validator::make($request->all(), $rulesFirstRequest);
        $validator2 = Validator::make($request->all(), $rulesSecondRequest);

        if ($validator1->fails()) {
            //do your stuff
            if ($validator2->fails()) {
                //do your stuff
            }
        }
        // next stuff
    }
</code>```

Body:
You can manually create validators in controller method

public function process(Request $request) {
        $rulesFirstRequest = ['field1' => 'required', 'field2' => 'required'];
        $rulesSecondRequest = ['field12' => 'required', 'field22' => 'required'];

        $validator1 = Validator::make($request->all(), $rulesFirstRequest);
        $validator2 = Validator::make($request->all(), $rulesSecondRequest);

        if ($validator1->fails()) {
            //do your stuff
            if ($validator2->fails()) {
                //do your stuff
            }
        }
        // next stuff
    }


问:
How to Map a string and char pair to a string using a std::map?
I am trying to take a std::pair and map it to a std::string using a std::map. The way it works being given a pair consisting of a char and a string, map it to a particular string.

This setup so far works just fine(compiler accepts it):

```<code>std::map<std::pair<char, std::string>, std::string> mymap;
std::map<std::pair<char, std::string>, std::string>::iterator it;
</code>```

But when i try to do this:

```<code>mymap['a', "Q1"] = "Q4";
mymap['b', "Q2"] = "Q3";
mymap['c', "Q3"] = "Q2";
mymap['d', "Q4"] = "Q1";
</code>```

it comes back as this error which I do not understand:

```<code>Error   1   error C2679: binary '[' : no operator found which takes a right-hand operand of type 'const char [3]' (or there is no acceptable conversion)
</code>```

which is the error associated under the left bracket of each of the four lines of code(where a red squiggly appears)

can someone help me to understand what I am doing wrong?

答:
The [] operator on map doesn't take two items. It takes just one. In your case it's expecting a std::pair object. So something like this will work:

```<code>mymap[std::pair<char, std::string>('c', "Q1")] = "Q4";
</code>```

You might want to make a typedef for your pair class:

```<code>using myPair = std::pair<char, std::string>;
mymap[myPair('c', "Q1")] = "Q4";
</code>```

Body:
I am trying to take a std::pair and map it to a std::string using a std::map. The way it works being given a pair consisting of a char and a string, map it to a particular string.

This setup so far works just fine(compiler accepts it):

std::map<std::pair<char, std::string>, std::string> mymap;
std::map<std::pair<char, std::string>, std::string>::iterator it;

But when i try to do this:

mymap['a', "Q1"] = "Q4";
mymap['b', "Q2"] = "Q3";
mymap['c', "Q3"] = "Q2";
mymap['d', "Q4"] = "Q1";

it comes back as this error which I do not understand:

Error   1   error C2679: binary '[' : no operator found which takes a right-hand operand of type 'const char [3]' (or there is no acceptable conversion)

which is the error associated under the left bracket of each of the four lines of code(where a red squiggly appears)

can someone help me to understand what I am doing wrong?

Body:
The [] operator on map doesn't take two items. It takes just one. In your case it's expecting a std::pair object. So something like this will work:

mymap[std::pair<char, std::string>('c', "Q1")] = "Q4";

You might want to make a typedef for your pair class:

using myPair = std::pair<char, std::string>;
mymap[myPair('c', "Q1")] = "Q4";


问:
Select in sql statement
Can anyone assist me with this below?

I have 10 records in a table with same acc no and different branches. If I fired the query it should not return any values while where condition is matched.

For example:

```<code> SELECT *
 FROM temp
 WHERE branch != "xxx"
</code>```

It should not return other 9 records also.

Can someone help me?

Thanks

答:
Using group by statement.

Select * from temp where Branch !=  "xxx" group by acc no

Or you can your top 1 so the query will show only 1 record

Select top 1 * from temp where branch != "xxx"

Title: Select in sql statement

Body:
Can anyone assist me with this below?

I have 10 records in a table with same acc no and different branches. If I fired the query it should not return any values while where condition is matched.

For example:

 SELECT *
 FROM temp
 WHERE branch != "xxx"

It should not return other 9 records also.

Can someone help me?

Thanks


问:
Error accessing field xxx by reflection for persistent property
I don't know what's up. My jpa mapping seems fine, yet I get this error :

Error accessing field [private main.java.entities.User
  main.java.entities.GPSCoordinates.user] by reflection for persistent
  property [main.java.entities.GPSCoordinates#user] :
  main.java.entities.GPSCoordinates

```<code>Caused by: javax.persistence.PersistenceException: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private main.java.entities.User main.java.entities.GPSCoordinates.user] by reflection for persistent property [main.java.entities.GPSCoordinates#user] : main.java.entities.GPSCoordinates@1
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
    at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:560)
    at main.java.lookup.UserServiceImp.findByUuid
</code>```

User class:

```<code>@Entity
@Table
@NamedQuery(name = "User.findByUuid", query = "SELECT u FROM User u WHERE u.uuid=:uuid")
public class User implements Serializable, PictureHolder {
    //...
    @OneToOne(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    private GPSCoordinates coordinates;

    public GPSCoordinates getCoordinates() { return coordinates;}
    public void setCoordinates(GPSCoordinates coordinates) {this.coordinates = coordinates;}
}
</code>```

GPSCoordinates class:

```<code>@Entity
@Table(name="user_gps_coordinates")
public class GPSCoordinates implements Serializable{

    @Id
    @OneToOne
    @JoinColumn(name="user")
    private User user;

    public User getUser() { return user; }
    public void setUser(User user) {this.user = user;}
}
</code>```

答:
Change

```<code>@JoinColumn(name="user")
</code>```

to

```<code>@JoinColumn(name="column_name_of_user_id")
</code>```

Body:
I don't know what's up. My jpa mapping seems fine, yet I get this error :

Error accessing field [private main.java.entities.User
  main.java.entities.GPSCoordinates.user] by reflection for persistent
  property [main.java.entities.GPSCoordinates#user] :
  main.java.entities.GPSCoordinates

Caused by: javax.persistence.PersistenceException: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private main.java.entities.User main.java.entities.GPSCoordinates.user] by reflection for persistent property [main.java.entities.GPSCoordinates#user] : main.java.entities.GPSCoordinates@1
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
    at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:560)
    at main.java.lookup.UserServiceImp.findByUuid

User class:

@Entity
@Table
@NamedQuery(name = "User.findByUuid", query = "SELECT u FROM User u WHERE u.uuid=:uuid")
public class User implements Serializable, PictureHolder {
    //...
    @OneToOne(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    private GPSCoordinates coordinates;

    public GPSCoordinates getCoordinates() { return coordinates;}
    public void setCoordinates(GPSCoordinates coordinates) {this.coordinates = coordinates;}
}

GPSCoordinates class:

@Entity
@Table(name="user_gps_coordinates")
public class GPSCoordinates implements Serializable{

    @Id
    @OneToOne
    @JoinColumn(name="user")
    private User user;

    public User getUser() { return user; }
    public void setUser(User user) {this.user = user;}
}

Body:
Change

@JoinColumn(name="user")

to

@JoinColumn(name="column_name_of_user_id")


问:
perl6 Is there a way to do editable prompt input?
In bash shell, if you hit up or down arrows, the shell will show you your previous or next command that you entered, and you can edit those commands to be new shell commands.

In perl6, if you do

```<code>my $name = prompt("Enter name: ");
</code>```

it will print "Enter name: " and then ask for input; is there a way to have perl6 give you a default value and then you just edit the default to be the new value. E.g.:

```<code>my $name = prompt("Your name:", "John Doe");
</code>```

and it prints

```<code>Your name: John Doe
</code>```

where the John Doe part is editable, and when you hit enter, the edited string is the value of $name.

https://docs.raku.org/routine/prompt does not show how to do it.

This is useful if you have to enter many long strings each of which is just a few chars different from others.

Thanks.

答:
Another solution :

Use io-prompt
With that you can set a default value and even a default type:

```<code>my $a = ask( "Life, the universe and everything?", 42, type => Num );
Life, the universe and everything? [42]
Int $a = 42
</code>```

You can install it with:

```<code>zef install IO::Prompt
</code>```

However, if just a default value is not enough. Then it is better you use the approach Liz has suggested.

ContentLicense: CC BY-SA 4.0

Body:
In bash shell, if you hit up or down arrows, the shell will show you your previous or next command that you entered, and you can edit those commands to be new shell commands.

In perl6, if you do

my $name = prompt("Enter name: ");

it will print "Enter name: " and then ask for input; is there a way to have perl6 give you a default value and then you just edit the default to be the new value. E.g.:

my $name = prompt("Your name:", "John Doe");

and it prints

Your name: John Doe

where the John Doe part is editable, and when you hit enter, the edited string is the value of $name.

https://docs.raku.org/routine/prompt does not show how to do it.

This is useful if you have to enter many long strings each of which is just a few chars different from others.

Thanks.

Body:
Another solution :

Use io-prompt
With that you can set a default value and even a default type:

my $a = ask( "Life, the universe and everything?", 42, type => Num );
Life, the universe and everything? [42]
Int $a = 42

You can install it with:

zef install IO::Prompt

However, if just a default value is not enough. Then it is better you use the approach Liz has suggested.


问:
Include global functions in Vue.js
In my Vue.js application I want to have some global functions. For example a callApi() function which I can call every time I need access to my data.

What is the best way to include these functions so I can access it in all my components?

Should I create a file functions.js and include it in my main.js?

Should I create a Mixin and include it in my main.js?

Is there a better option?

答: Mixins can be registered globally too. https://v2.vuejs.org/v2/guide/mixins.html#Global-Mixin</p>

Title: Include global functions in Vue.js


问:
How can I correct my PHP code for this SQL query?
I've been messing with this for a while and I'm nearly there. Just need to get past this wall I've hit.

I have the following tables:

```<code>tracks (trackid, tracktitle, albumid, composerid)
albums (albumid, albumname)
composers (composerid, composername)
</code>```

I can insert a new record via PhpMyAdmin SQL tab with

```<code>INSERT INTO tracks (tracktitle, albumid, composerid) VALUES ('New Song', 1, 1);
</code>```

and it works fine.

My PHP form though isn't doing the same thing and I must have overlooked something.
Please can someone check out the code for my addtrack page and tell me what is wrong?

```<code> if (isset($_POST['tracktitle'])):
 // A new track has been entered
 // using the form.

 $cid= $_POST['cid'];
 $tracktitle = $_POST['tracktitle'];
 $albs = $_POST['albs'];

 if ($cid == '') {
 exit('<p>You must choose an composer for this track.
 Click "Back" and try again.</p>');
  }

  $sql = "INSERT INTO tracks SET
  tracks.tracktitle='$tracktitle'" ;
  if (@mysql_query($sql)) {
  echo '<p>New track added</p>';
  } else {
  exit('<p>Error adding new track' . mysql_error() . '</p>');
  }

  $trackid = mysql_insert_id();

  if (isset($_POST['albs'])) {
   $albs = $_POST['albs'];
   } else {
   $albs = array();
   }

  $numAlbs = 0;
  foreach ($albs as $albID) {
  $sql = "INSERT IGNORE INTO tracks (trackid, albumid,
  composerid) VALUES " .
"($trackid, $albs, $cid)";

if ($ok) {
  $numAlbs = $numAlbs + 1;
} else {
  echo "<p>Error inserting track into album $albID: " .
      mysql_error() . '</p>';
}
}
 ?>

<p>Track was added to <?php echo $numAlbs; ?> albums.</p>

 <p><a href="<?php echo $_SERVER['PHP_SELF']; ?>">Add another
 track</a></p>
 <p><a href="tracks.php">Return to track search</a></p>

 <?php
 else: // Allow the user to enter a new track

 $composers = @mysql_query('SELECT composerid, composername
 FROM composers');
  if (!$composers) {
 exit('<p>Unable to obtain composer list from the
database.</p>');
 }

$albs = @mysql_query('SELECT albumid, albumname FROM albums');
 if (!$albs) {
 exit('<p>Unable to obtain album list from the
 database.</p>');
 }
 ?>

 <form action="<?php echo $_SERVER['PHP_SELF']; ?>"
 method="post">
 <p>Enter the new track:<br />
 <textarea name="tracktitle" rows="1" cols="20">
 </textarea></p>
 <p>Composer:
 <select name="cid" size="1">
  <option selected value="">Select One</option>
  <option value="">---------</option>
  <?php
   while ($composer= mysql_fetch_array($composers)) {
    $cid = $composer['composerid'];
    $cname = htmlspecialchars($composer['composername']);
    echo "<option value='$cid'>$cname</option>\n";
     }
    ?>
    </select></p>
    <p>Place in albums:<br />
   <?php
   while ($alb = mysql_fetch_array($albs)) {
    $aid = $alb['albumid'];
    $aname = htmlspecialchars($alb['albumname']);
     echo "<label><input type='checkbox' name='albs[]'
    value='$aid' />$aname</label><br />\n";
    }
   ?>
</code>```

Once I have this sorted, I can move on to expanding it and also sorting out the security issues. Someone on here recommended I look into PDO's which are a new thing to me.
But one hurdle at a time....

Thanks

答:
The problems are in your queries. Try using mysql_error function to get extra information on what you are doing wrong.

As an example your INSERT statement is malformed.

You have:

```<code>$sql="INSERT INTO tracks SET tracks.tracktitle='$tracktitle'"
</code>```

It should be something like:

```<code>$sql="INSERT INTO tracks (tracktitle) VALUES ('$tracktitle')";
</code>```

Body:
I've been messing with this for a while and I'm nearly there. Just need to get past this wall I've hit.

I have the following tables:

tracks (trackid, tracktitle, albumid, composerid)
albums (albumid, albumname)
composers (composerid, composername)

I can insert a new record via PhpMyAdmin SQL tab with

INSERT INTO tracks (tracktitle, albumid, composerid) VALUES ('New Song', 1, 1);

and it works fine.

My PHP form though isn't doing the same thing and I must have overlooked something.
Please can someone check out the code for my addtrack page and tell me what is wrong?

 if (isset($_POST['tracktitle'])):
 // A new track has been entered
 // using the form.

 $cid= $_POST['cid'];
 $tracktitle = $_POST['tracktitle'];
 $albs = $_POST['albs'];

 if ($cid == '') {
 exit('
You must choose an composer for this track.
 Click "Back" and try again.
');
  }

  $sql = "INSERT INTO tracks SET
  tracks.tracktitle='$tracktitle'" ;
  if (@mysql_query($sql)) {
  echo '
New track added
';
  } else {
  exit('
Error adding new track' . mysql_error() . '
');
  }

  $trackid = mysql_insert_id();

  if (isset($_POST['albs'])) {
   $albs = $_POST['albs'];
   } else {
   $albs = array();
   }

  $numAlbs = 0;
  foreach ($albs as $albID) {
  $sql = "INSERT IGNORE INTO tracks (trackid, albumid,
  composerid) VALUES " .
"($trackid, $albs, $cid)";

if ($ok) {
  $numAlbs = $numAlbs + 1;
} else {
  echo "
Error inserting track into album $albID: " .
      mysql_error() . '
';
}
}
 ?>

Track was added to <?php echo $numAlbs; ?> albums.

<a href="<?php echo $_SERVER['PHP_SELF']; ?>">Add another
 track

Return to track search

 <?php
 else: // Allow the user to enter a new track

 $composers = @mysql_query('SELECT composerid, composername
 FROM composers');
  if (!$composers) {
 exit('
Unable to obtain composer list from the
database.
');
 }

$albs = @mysql_query('SELECT albumid, albumname FROM albums');
 if (!$albs) {
 exit('
Unable to obtain album list from the
 database.
');
 }
 ?>

 <form action="<?php echo $_SERVER['PHP_SELF']; ?>"
 method="post">

Enter the new track:

 <textarea name="tracktitle" rows="1" cols="20">
 </textarea>

Composer:
 <select name="cid" size="1">
  <option selected value="">Select One</option>
  <option value="">---------</option>
  <?php
   while ($composer= mysql_fetch_array($composers)) {
    $cid = $composer['composerid'];
    $cname = htmlspecialchars($composer['composername']);
    echo "<option value='$cid'>$cname</option>\n";
     }
    ?>
    </select>

Place in albums:

   <?php
   while ($alb = mysql_fetch_array($albs)) {
    $aid = $alb['albumid'];
    $aname = htmlspecialchars($alb['albumname']);
     echo "<input type='checkbox' name='albs[]'
    value='$aid' />$aname
\n";
    }
   ?>

Once I have this sorted, I can move on to expanding it and also sorting out the security issues. Someone on here recommended I look into PDO's which are a new thing to me.
But one hurdle at a time....

Thanks

Body:
The problems are in your queries. Try using mysql_error function to get extra information on what you are doing wrong.

As an example your INSERT statement is malformed.

You have:

$sql="INSERT INTO tracks SET tracks.tracktitle='$tracktitle'"

It should be something like:

$sql="INSERT INTO tracks (tracktitle) VALUES ('$tracktitle')";


问:
how to separate click event from siblings?
I finally got my nav to show and hide the submenu on click, but what's happening now is that when I click, to have it slideToggle, is affecting its siblings and opening and closing at the same time.

my structure look something like this:

Home

Item1

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 2

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 3

            <
SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 4

Item - 5

About

Services

Blog

Contact

```
</div>
</div>
</p>

<p>and this is my jQuery:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.has-children ul').click(function(e){
    e.stopPropagation();
    var el = (event.target || event.srcElement);
    console.log('clicked');
    $(this).find('ul.submenu').slideToggle();
     $(el).find('span').toggleClass('arrow-down arrow-up');
  });</code>```

So if I click on the li with the class of has children, all my uls with class of submenu are opening at the same time.
Perhaps I am doing more than I am supposed to here, all the help would be appreciate it.

答:
by using this code toggle sub item when click on Item and when click on sub item it wont toggle item

```<code>  $('.has-children > a').click(function (e) {
        e.stopPropagation();
        var el = (event.target || event.srcElement);
        console.log('clicked');
        $(this).parent().find('ul.submenu').slideToggle();
        $(el).find('span').toggleClass('arrow-down arrow-up');
    });
</code>```

Body:
I finally got my nav to show and hide the submenu on click, but what's happening now is that when I click, to have it slideToggle, is affecting its siblings and opening and closing at the same time.

my structure look something like this:

Home

Item1

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 2

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 3

            <
SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 4

Item - 5

About

Services

Blog

Contact

and this is my jQuery:

$('.has-children ul').click(function(e){
    e.stopPropagation();
    var el = (event.target || event.srcElement);
    console.log('clicked');
    $(this).find('ul.submenu').slideToggle();
     $(el).find('span').toggleClass('arrow-down arrow-up');
  });

So if I click on the li with the class of has children, all my uls with class of submenu are opening at the same time.
Perhaps I am doing more than I am supposed to here, all the help would be appreciate it.

Body:
by using this code toggle sub item when click on Item and when click on sub item it wont toggle item

  $('.has-children > a').click(function (e) {
        e.stopPropagation();
        var el = (event.target || event.srcElement);
        console.log('clicked');
        $(this).parent().find('ul.submenu').slideToggle();
        $(el).find('span').toggleClass('arrow-down arrow-up');
    });


问:
odoo website withought login download product attachment showing error
odoo website withought login download product attachment showing error
 "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."

Same code for downloading product level attachment working well if your logged in. But not working for without login. Attached all screen shoot please check.
Without Login: Without Login

While clicking on Catalogue it will open in another window and showing:After Clicking

答:
IN the controller of odoo we can make the authorization to 'public', 'user', 'None'.
you should check your controller eg:</p>

```<code>@http.route('/path', csrf=False, type="http", methods=['POST', 'GET'], auth="public", website=True)
</code>```

Body:
IN the controller of odoo we can make the authorization to 'public', 'user', 'None'.
you should check your controller eg:

@http.route('/path', csrf=False, type="http", methods=['POST', 'GET'], auth="public", website=True)


问:
Vertx - Restrict Upload file type
I'm creating an API using Vertx to let user upload images but I want to restrict to certain file types - jpg|Jpeg|png.

What's the best way to do this?

```<code>private void uploadLogoHandler(RoutingContext context) {
   //Filter content type

}
</code>```

答:
HTML:

<input type="file" name="myImage" accept="image/*" />

On vert.x we need to check the content type of uploaded file, assuming we will have only one upload:

```<code>Set<FileUpload> fileUploads = routingContext.fileUploads();
FileUpload fileUpload = fileUploads.iterator().next();
fileUpload.contentType();
if(!fileUpload.contentType().startsWith("image/")){
    routingContext.response().putHeader("content-type", "text/html").end("Please upload an image.");
}else{
    // Process your image
}
</code>```

Title: Vertx - Restrict Upload file type

Body:
I'm creating an API using Vertx to let user upload images but I want to restrict to certain file types - jpg|Jpeg|png.

What's the best way to do this?

private void uploadLogoHandler(RoutingContext context) {
   //Filter content type

}

Body:
HTML:

<input type="file" name="myImage" accept="image/*" />

On vert.x we need to check the content type of uploaded file, assuming we will have only one upload:

Set<FileUpload> fileUploads = routingContext.fileUploads();
FileUpload fileUpload = fileUploads.iterator().next();
fileUpload.contentType();
if(!fileUpload.contentType().startsWith("image/")){
    routingContext.response().putHeader("content-type", "text/html").end("Please upload an image.");
}else{
    // Process your image
}


问:
Git cherry pick creates duplicate commits
After cherry-picking some commits from one branch to another branch, i still see commits when a pull request is created later.

Say for example, There is a git project which has two branches : Dev , Release.

And commit history is in following order.

DEV : a1, a2, a3, a4, a5, a6

RELEASE : a1, a2

Now if i cherry-picked commits a3 and a5 alone from Dev to Release. Now the commit history will be as shown below. cherry-picked commits will have new SHA (b1 & b2).

RELEASE : a1, a2, b1, b2.

Later if i try to create a pull request from Dev to Release branch, i stil see the commits a3 and a5.

But in this case how can i find difference in commits between these two branches?

I saw some articles stating 'rebase' but not able to understand the logic behind it.

答:
Ideally, you rebase dev on top on the updated release first.

```<code>git checkout dev
git rebase release
</code>```

The logic behind that is that Git should detect that a3 and a5 are the same as b1 and b2: meaning a3 and a5 won't be replayed at all.

The new dev branch (from which you will create a PR) won't have a3 and a5 anymore.

See also:

"git merge after git cherry-pick: avoiding duplicate commits"

"using git rebase to remove duplicate cherry-picked commits"

Body:
Ideally, you rebase dev on top on the updated release first.

git checkout dev
git rebase release

The logic behind that is that Git should detect that a3 and a5 are the same as b1 and b2: meaning a3 and a5 won't be replayed at all.

The new dev branch (from which you will create a PR) won't have a3 and a5 anymore.

See also:

"git merge after git cherry-pick: avoiding duplicate commits"

"using git rebase to remove duplicate cherry-picked commits"


问:
Dictionary<T,Delegate> with Delegates of different types: Cleaner, non string method names?
There has to be a cleaner method. Currently I have:

```<code>... Constructor()
{
      parseDictionary = new Dictionary<typeOfStream, Delegate>()
            {
                {typeOfStream.SOME_ENUM_VAL, Delegate.CreateDelegate(typeof(ParseDelegate<string>), this, "MyMethod")},
                {typeOfStream.SOME_OTHER_ENUM_VAL, Delegate.CreateDelegate(typeof(ParseDelegate<XmlNode>), this, "MyOtherMethod")}
            };
}

public bool MyMethod(string some_string)
{
    ...
}

public bool MyOtherMethod(XmlNode some_node)
{
    ...
}
</code>```

and I would like to get rid of "MyMethod" and MyOtherMethod and make it this.MyMethod and this.MyOtherMethod. Options?

I am open to any solution that allows me to use a Dictionary lookup, and point my data mojo into an arbitrary method (well a defined method with an arbitrary bunch of arguments) for parsing.

答:
Just cast to the right kind of delegate:</p>

```<code>parseDictionary = new Dictionary<typeOfStream, Delegate>()
{
    { typeOfStream.SOME_ENUM_VAL, (ParseDelegate<string>) MyMethod) },
    { typeOfStream.SOME_OTHER_ENUM_VAL, (ParseDelegate<XmlNode>) MyOtherMethod }
};
</code>```

Body:
There has to be a cleaner method. Currently I have:

... Constructor()
{
      parseDictionary = new Dictionary<typeOfStream, Delegate>()
            {
                {typeOfStream.SOME_ENUM_VAL, Delegate.CreateDelegate(typeof(ParseDelegate<string>), this, "MyMethod")},
                {typeOfStream.SOME_OTHER_ENUM_VAL, Delegate.CreateDelegate(typeof(ParseDelegate<XmlNode>), this, "MyOtherMethod")}
            };
}

public bool MyMethod(string some_string)
{
    ...
}

public bool MyOtherMethod(XmlNode some_node)
{
    ...
}

and I would like to get rid of "MyMethod" and MyOtherMethod and make it this.MyMethod and this.MyOtherMethod. Options?

I am open to any solution that allows me to use a Dictionary lookup, and point my data mojo into an arbitrary method (well a defined method with an arbitrary bunch of arguments) for parsing.

Body:
Just cast to the right kind of delegate:

parseDictionary = new Dictionary<typeOfStream, Delegate>()
{
    { typeOfStream.SOME_ENUM_VAL, (ParseDelegate<string>) MyMethod) },
    { typeOfStream.SOME_OTHER_ENUM_VAL, (ParseDelegate<XmlNode>) MyOtherMethod }
};


问:
JMeter Response Assertion fails pattern
Apply to: Main sample and sub-samples
Response Field to Test: Text Response
Pattern Matching Rules: Contains

Patterns to test:

```<code><?xml version="1.0" encoding="ISO-8859-5" standalone="yes"?>
<CIT_REQUEST>
    <SYSTEM>
        <CIT_Version Value="1.0"/>
        <ERR Value=""/>
        <FORMAT Value="XML"/>
        <INTERFACE_RET Value=""/>
        <MAIN_ID Value="37407427745"/>
        <MSG_ID Value=".*"/> - regexp not working
        <SYNC Value="N"/>
        <Version Value="002"/>
    </SYSTEM>
    <DATA>
        <PACKAGE_B64>
    PE1zZ0NsaWVudEFkZFJzIHhtbG5zPSJ1cm46c2NoZW1hcy1wc2l0LXJ1OmdwIj48
UnFVSUQ+Mzc0MDc0Mjc3NDU8L1JxVUlEPjxScVJlc3VsdD48U3RhdHVzPk9rPC9T
dGF0dXM+PENvbW1lbnQ+TmV3PC9Db21tZW50PgoJCQk8L1JxUmVzdWx0PjxSZXN1
bHQ+PENsaWVudElkPjc3MzY0NTgyPC9DbGllbnRJZD48SW50ZXJuYWxfQ2xpZW50
SWQ+MjY3PC9JbnRlcm5hbF9DbGllbnRJZD4KCQkJPC9SZXN1bHQ+CgkJPC9Nc2dD
bGllbnRBZGRScz4=

</PACKAGE_B64>
    </DATA>
</CIT_REQUEST>
</code>```

Response:

```<code><?xml version="1.0" encoding="ISO-8859-5" standalone="yes"?>
<CIT_REQUEST>
    <SYSTEM>
        <CIT_Version Value="1.0"/>
        <ERR Value=""/>
        <FORMAT Value="XML"/>
        <INTERFACE_RET Value=""/>
        <MAIN_ID Value="37407427745"/>
        <MSG_ID Value="F3C826680F5E45C3AA97DEE4DA51F54B"/> - MSG_ID Value changes for each request
        <SYNC Value="N"/>
        <Version Value="002"/>
    </SYSTEM>
    <DATA>
        <PACKAGE_B64>
    PE1zZ0NsaWVudEFkZFJzIHhtbG5zPSJ1cm46c2NoZW1hcy1wc2l0LXJ1OmdwIj48
UnFVSUQ+Mzc0MDc0Mjc3NDU8L1JxVUlEPjxScVJlc3VsdD48U3RhdHVzPk9rPC9T
dGF0dXM+PENvbW1lbnQ+TmV3PC9Db21tZW50PgoJCQk8L1JxUmVzdWx0PjxSZXN1
bHQ+PENsaWVudElkPjc3MzY0NTgyPC9DbGllbnRJZD48SW50ZXJuYWxfQ2xpZW50
SWQ+MjY3PC9JbnRlcm5hbF9DbGllbnRJZD4KCQkJPC9SZXN1bHQ+CgkJPC9Nc2dD
bGllbnRBZGRScz4=

</PACKAGE_B64>
    </DATA>
</CIT_REQUEST>
</code>```

Assertion failure message:

```<code>Assertion error: false
Assertion failure: true
Assertion failure message: Test failed: text expected to contain /<?xml version="1.0" encoding="ISO-8859-5" standalone="yes"?>
<CIT_REQUEST>
    <SYSTEM>
        <CIT_Version Value="1.0"/>
        <ERR Value=""/>
        <FORMAT Value="XML"/>
        <INTERFACE_RET Value=""/>
        <MAIN_ID Value="37407427745"/>
        <MSG_ID Value=".*"/>
        <SYNC Value="N"/>
        <Version Value="002"/>
    </SYSTEM>
    <DATA>
        <PACKAGE_B64>
    PE1zZ0NsaWVudEFkZFJzIHhtbG5zPSJ1cm46c2NoZW1hcy1wc2l0LXJ1OmdwIj48
UnFVSUQ+Mzc0MDc0Mjc3NDU8L1JxVUlEPjxScVJlc3VsdD48U3RhdHVzPk9rPC9T
dGF0dXM+PENvbW1lbnQ+TmV3PC9Db21tZW50PgoJCQk8L1JxUmVzdWx0PjxSZXN1
bHQ+PENsaWVudElkPjc3MzY0NTgyPC9DbGllbnRJZD48SW50ZXJuYWxfQ2xpZW50
SWQ+MjY3PC9JbnRlcm5hbF9DbGllbnRJZD4KCQkJPC9SZXN1bHQ+CgkJPC9Nc2dD
bGllbnRBZGRScz4=

</PACKAGE_B64>
    </DATA>
</CIT_REQUEST>/
</code>```

Please help with regexp or another way out.

答: For XML assertion best way is to use XML assertion provided by jmeter this will check whole syntax of XML</p>

Title: JMeter Response Assertion fails pattern

Body:
Apply to: Main sample and sub-samples
Response Field to Test: Text Response
Pattern Matching Rules: Contains

Patterns to test:

<?xml version="1.0" encoding="ISO-8859-5" standalone="yes"?>
<CIT_REQUEST>
    <SYSTEM>
        <CIT_Version Value="1.0"/>
        <ERR Value=""/>
        <FORMAT Value="XML"/>
        <INTERFACE_RET Value=""/>
        <MAIN_ID Value="37407427745"/>
        <MSG_ID Value=".*"/> - regexp not working
        <SYNC Value="N"/>
        <Version Value="002"/>
    </SYSTEM>
    <DATA>
        <PACKAGE_B64>
    PE1zZ0NsaWVudEFkZFJzIHhtbG5zPSJ1cm46c2NoZW1hcy1wc2l0LXJ1OmdwIj48
UnFVSUQ+Mzc0MDc0Mjc3NDU8L1JxVUlEPjxScVJlc3VsdD48U3RhdHVzPk9rPC9T
dGF0dXM+PENvbW1lbnQ+TmV3PC9Db21tZW50PgoJCQk8L1JxUmVzdWx0PjxSZXN1
bHQ+PENsaWVudElkPjc3MzY0NTgyPC9DbGllbnRJZD48SW50ZXJuYWxfQ2xpZW50
SWQ+MjY3PC9JbnRlcm5hbF9DbGllbnRJZD4KCQkJPC9SZXN1bHQ+CgkJPC9Nc2dD
bGllbnRBZGRScz4=

</PACKAGE_B64>
    </DATA>
</CIT_REQUEST>

Response:

<?xml version="1.0" encoding="ISO-8859-5" standalone="yes"?>
<CIT_REQUEST>
    <SYSTEM>
        <CIT_Version Value="1.0"/>
        <ERR Value=""/>
        <FORMAT Value="XML"/>
        <INTERFACE_RET Value=""/>
        <MAIN_ID Value="37407427745"/>
        <MSG_ID Value="F3C826680F5E45C3AA97DEE4DA51F54B"/> - MSG_ID Value changes for each request
        <SYNC Value="N"/>
        <Version Value="002"/>
    </SYSTEM>
    <DATA>
        <PACKAGE_B64>
    PE1zZ0NsaWVudEFkZFJzIHhtbG5zPSJ1cm46c2NoZW1hcy1wc2l0LXJ1OmdwIj48
UnFVSUQ+Mzc0MDc0Mjc3NDU8L1JxVUlEPjxScVJlc3VsdD48U3RhdHVzPk9rPC9T
dGF0dXM+PENvbW1lbnQ+TmV3PC9Db21tZW50PgoJCQk8L1JxUmVzdWx0PjxSZXN1
bHQ+PENsaWVudElkPjc3MzY0NTgyPC9DbGllbnRJZD48SW50ZXJuYWxfQ2xpZW50
SWQ+MjY3PC9JbnRlcm5hbF9DbGllbnRJZD4KCQkJPC9SZXN1bHQ+CgkJPC9Nc2dD
bGllbnRBZGRScz4=

</PACKAGE_B64>
    </DATA>
</CIT_REQUEST>

Assertion failure message:

Assertion error: false
Assertion failure: true
Assertion failure message: Test failed: text expected to contain /<?xml version="1.0" encoding="ISO-8859-5" standalone="yes"?>
<CIT_REQUEST>
    <SYSTEM>
        <CIT_Version Value="1.0"/>
        <ERR Value=""/>
        <FORMAT Value="XML"/>
        <INTERFACE_RET Value=""/>
        <MAIN_ID Value="37407427745"/>
        <MSG_ID Value=".*"/>
        <SYNC Value="N"/>
        <Version Value="002"/>
    </SYSTEM>
    <DATA>
        <PACKAGE_B64>
    PE1zZ0NsaWVudEFkZFJzIHhtbG5zPSJ1cm46c2NoZW1hcy1wc2l0LXJ1OmdwIj48
UnFVSUQ+Mzc0MDc0Mjc3NDU8L1JxVUlEPjxScVJlc3VsdD48U3RhdHVzPk9rPC9T
dGF0dXM+PENvbW1lbnQ+TmV3PC9Db21tZW50PgoJCQk8L1JxUmVzdWx0PjxSZXN1
bHQ+PENsaWVudElkPjc3MzY0NTgyPC9DbGllbnRJZD48SW50ZXJuYWxfQ2xpZW50
SWQ+MjY3PC9JbnRlcm5hbF9DbGllbnRJZD4KCQkJPC9SZXN1bHQ+CgkJPC9Nc2dD
bGllbnRBZGRScz4=

</PACKAGE_B64>
    </DATA>
</CIT_REQUEST>/

Please help with regexp or another way out.


问:
Use of literal 'dquote' string in icalendar values
I'm looking at an open-source PHP program which performs the following transformation to replace double-quote characters in string values:

```<code>$text = str_replace("\"", "DQUOTE", $text);
</code>```

For example, the string Call me "foo"., after this transformation, would be represented in an icalendar DESCRIPTION field like so:

```DESCRIPTION:Call me DQUOTEfooDQUOTE.```

My reading of various online documentation (http://www.ietf.org/rfc/rfc2445.txt and its summaries at http://www.kanzaki.com/docs/ical/) indicate that this is incorrect, and the correct representation should be

```DESCRIPTION:Call me \"foo\".```

What is the correct representation?

答:
The spec at https://www.rfc-editor.org/rfc/rfc2445#section-4.3.11 indicates that double and single quotes need not be escaped at all, as does the example for the DESCRIPTION field (https://www.rfc-editor.org/rfc/rfc2445#section-4.8.1.5), so the correct representation would be

```DESCRIPTION:Call me "foo".```

BTW, in the time since this question was asked, the affected open-source project has fixed this issue: https://issues.civicrm.org/jira/browse/CRM-20350

Body:
I'm looking at an open-source PHP program which performs the following transformation to replace double-quote characters in string values:

$text = str_replace("\"", "DQUOTE", $text);

For example, the string Call me "foo"., after this transformation, would be represented in an icalendar DESCRIPTION field like so:

DESCRIPTION:Call me DQUOTEfooDQUOTE.

My reading of various online documentation (http://www.ietf.org/rfc/rfc2445.txt and its summaries at http://www.kanzaki.com/docs/ical/) indicate that this is incorrect, and the correct representation should be

DESCRIPTION:Call me \"foo\".

What is the correct representation?

Body:
The spec at https://www.rfc-editor.org/rfc/rfc2445#section-4.3.11 indicates that double and single quotes need not be escaped at all, as does the example for the DESCRIPTION field (https://www.rfc-editor.org/rfc/rfc2445#section-4.8.1.5), so the correct representation would be

DESCRIPTION:Call me "foo".

BTW, in the time since this question was asked, the affected open-source project has fixed this issue: https://issues.civicrm.org/jira/browse/CRM-20350


问:
jQuery Issue on Animate Border Until Selected Element by sequent
Can you please take a look at this demo and let me know how I can add animation to borders properly so when use clicks on a the all previous borders get the anime100 class after each other in a sequence

what is happening now is adding the anime100 to all anime classes at the same time!

$("a:eq( 1 )").on("click", function() {
  $('.anime:eq( 0 )').addClass('anime100');
});

$("a:eq( 2 )").on("click", function() {
  $('.anime:eq( 0 )').addClass('anime100');
  $('.anime:eq( 1 )').addClass('anime100');
});

$("a:eq( 3 )").on("click", function() {
  $('.anime:eq( 0 )').addClass('anime100');
  $('.anime:eq( 1 )').addClass('anime100');
  $('.anime:eq( 2 )').addClass('anime100');
});

$("a:eq( 4 )").on("click", function() {
  $('.anime:eq( 0 )').addClass('anime100');
  $('.anime:eq( 1 )').addClass('anime100');
  $('.anime:eq( 2 )').addClass('anime100');
  $('.anime:eq( 3 )').addClass('anime100');
});

$("a:eq( 5 )").on("click", function() {
  $('.anime:eq( 0 )').addClass('anime100');
  $('.anime:eq( 1 )').addClass('anime100');
  $('.anime:eq( 2 )').addClass('anime100');
  $('.anime:eq( 3 )').addClass('anime100');
  $('.anime:eq( 4 )').addClass('anime100');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.anime {
  height: 10px;
  width: 0px;
  background: gold;
  transition: all 0.7s;
}

.anime100 {
  width: 250px;
}</code>```

A

B

C

D

E

F

```

答:
You could minify this code quite a bit doing something like the following by looping through your elements and using a combination of .delay(), .queue() and .dequeue():

JS Fiddle

```<code>var startEq = 0; // Start at 0 (first element)

$("a").on("click", function() {
  var maxEq = $('li').has(this).index(); // Current clicked element's parent index

  $('.anime').each(function(i) {

    if (startEq >= maxEq) {
      return; // Stop loop once current target is reached
    }

    $('.anime:eq(' + startEq + ')').delay(200 * i).queue(function() {
      $(this).addClass('anime100').dequeue();
    });

    startEq += 1; // Add 1 after each loop
  });
});
</code>```

Body:
Can you please take a look at this demo and let me know how I can add animation to borders properly so when use clicks on a the all previous borders get the anime100 class after each other in a sequence

what is happening now is adding the anime100 to all anime classes at the same time!

$("a:eq( 1 )").on("click", function() {
  $('.anime:eq( 0 )').addClass('anime100');
});

$("a:eq( 2 )").on("click", function() {
  $('.anime:eq( 0 )').addClass('anime100');
  $('.anime:eq( 1 )').addClass('anime100');
});

$("a:eq( 3 )").on("click", function() {
  $('.anime:eq( 0 )').addClass('anime100');
  $('.anime:eq( 1 )').addClass('anime100');
  $('.anime:eq( 2 )').addClass('anime100');
});

$("a:eq( 4 )").on("click", function() {
  $('.anime:eq( 0 )').addClass('anime100');
  $('.anime:eq( 1 )').addClass('anime100');
  $('.anime:eq( 2 )').addClass('anime100');
  $('.anime:eq( 3 )').addClass('anime100');
});

$("a:eq( 5 )").on("click", function() {
  $('.anime:eq( 0 )').addClass('anime100');
  $('.anime:eq( 1 )').addClass('anime100');
  $('.anime:eq( 2 )').addClass('anime100');
  $('.anime:eq( 3 )').addClass('anime100');
  $('.anime:eq( 4 )').addClass('anime100');
});

.anime {
  height: 10px;
  width: 0px;
  background: gold;
  transition: all 0.7s;
}

.anime100 {
  width: 250px;
}

A

B

C

D

E

F

Body:
You could minify this code quite a bit doing something like the following by looping through your elements and using a combination of .delay(), .queue() and .dequeue():

JS Fiddle

var startEq = 0; // Start at 0 (first element)

$("a").on("click", function() {
  var maxEq = $('li').has(this).index(); // Current clicked element's parent index

  $('.anime').each(function(i) {

    if (startEq >= maxEq) {
      return; // Stop loop once current target is reached
    }

    $('.anime:eq(' + startEq + ')').delay(200 * i).queue(function() {
      $(this).addClass('anime100').dequeue();
    });

    startEq += 1; // Add 1 after each loop
  });
});


问:
JavaFX: How do you execute files located in your package?
If I have a .png file located in my package that I want to open when a button widget is pressed. The only information I can find is about file choosers, but that isn't helpful because I already know the exact location. How do you go about doing this?</p>

答:
You can try

```<code>Desktop.getDesktop().open(File file);
</code>```

Which tries to open files with standard applications. Here is the documentation https://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html#getDesktop()

Body:
You can try

Desktop.getDesktop().open(File file);

Which tries to open files with standard applications. Here is the documentation https://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html#getDesktop()


问:
Inconsistent behavior in java date formatter
Either I'm missing something completely obvious or making unwarranted assumptions about the behavior of SimpleDateFormat.

I'd assume that it ought to be symmetric, right? If I have

```<code>SimpleDateFormatter formatter;
String datestr=...
Date d = formatter.parse(datestr);
String s=formatter.format(d);
</code>```

I should get back my original String. However -

```<code>public static final String DATE_FORMAT = "E MMM dd HH:mm:dd zz yyyy";
String test = "Mon Nov 29 09:53:24 EST 2010";
long l = new SimpleDateFormat(DATE_FORMAT).parse(test).getTime();
System.out.println(test);
System.out.println(new SimpleDateFormat(DATE_FORMAT).format(new Date(l)));
</code>```

prints out :

Mon Nov 29 09:53:24 EST 2010

Wed Nov 24 09:53:24 EST 2010

How am I losing 5 days?

答:
```
"E MMM dd HH:mm:dd zz yyyy";
       ^^       ^^
```

Body:
Either I'm missing something completely obvious or making unwarranted assumptions about the behavior of SimpleDateFormat.

I'd assume that it ought to be symmetric, right? If I have

SimpleDateFormatter formatter;
String datestr=...
Date d = formatter.parse(datestr);
String s=formatter.format(d);

I should get back my original String. However -

public static final String DATE_FORMAT = "E MMM dd HH:mm:dd zz yyyy";
String test = "Mon Nov 29 09:53:24 EST 2010";
long l = new SimpleDateFormat(DATE_FORMAT).parse(test).getTime();
System.out.println(test);
System.out.println(new SimpleDateFormat(DATE_FORMAT).format(new Date(l)));

prints out :

Mon Nov 29 09:53:24 EST 2010

Wed Nov 24 09:53:24 EST 2010

How am I losing 5 days?

Body:
"E MMM dd HH:mm:dd zz yyyy";
       ^^       ^^