问:
Android - checkBox always sending true to a different activity
I have manually created a Preferences Activity, where the checkbox data will be sent to a different Activity. When I send it, it is right. But when I receive it, I need to know if it is true or false, and I always get false.

Here's my code to send:

```<code>@Override
    public void onBackPressed() {

        if(checkBox.isChecked())
        {
            String trueThumb_check = "checked_thumb";
            Intent i = new Intent(getBaseContext(), MainActivity.class);
            i.putExtra("trueThumbnail", trueThumb_check);
            Toast.makeText(Preferences.this, "check prefs", Toast.LENGTH_SHORT).show();
            startActivity(i);
            killAc();
        }
        else
        {
            String falseThumb_check = "not_check_thumb";
            Intent i = new Intent(getBaseContext(), MainActivity.class);
            i.putExtra("trueThumbnail", falseThumb_check);
            Toast.makeText(Preferences.this, "not check prefs", Toast.LENGTH_SHORT).show();
            startActivity(i);
            killAc();
        }

    }
</code>```

And to receive:

```<code>try {
            SharedPreferences thumb_check = this.getSharedPreferences(
              "ch4an.ytheloader", Context.MODE_PRIVATE);

            //To read preferences
            String thumb_thumb = thumb_check.getString("trueThumbnail", "checked_thumb");

            if (thumb_thumb.contains("checked_thumb")){
            Toast.makeText(MainActivity.this, "checkBox ativo", Toast.LENGTH_SHORT).show();
            }  if(thumb_thumb.contains("not_checked_thumb")) {
            Toast.makeText(MainActivity.this, "checkBox não ativo", Toast.LENGTH_SHORT).show();
            }

            SharedPreferences.Editor editor = thumb_check.edit();
            editor.apply();

        } catch (Throwable e) {
            Toast.makeText(MainActivity.this, "Null checkBox", Toast.LENGTH_SHORT).show();
            e.printStackTrace();

        }
</code>```

I believe the problem might be here:

```<code>String thumb_thumb = thumb_check.getString("trueThumbnail", "checked_thumb");
</code>```

I always get a single " checked_thumb", but I don't know how to get "thumb_thumb" for both.
I've tried sending different keys and values (because both are under the "trueThumbnail" key) but I still get true only.

答:
If you don't know how to ask your questions in english visit pt.stackoverflow.com

But as I'm Portuguese I'm gonna answer here, but in english.

Your receiving code is wrong. When you're sending the data you're sending through a intent, there's nothing wrong in there but when you're trying to receive you are getting from the SharedPreferences

So to access the data instead of this

```<code>SharedPreferences thumb_check = this.getSharedPreferences(
              "ch4an.ytheloader", Context.MODE_PRIVATE);
</code>```

It should be this

```<code>Intent thumb_check = getIntent();
String thumb_thumb = thumb_check.getStringExtra("trueThumbnail", "checked_thumb");
</code>```

A rewrite of the receive code

```<code>    try {
    // Get the intent passed through activities
    Intent thumb_check = getIntent();
    // Get the string in the extra
    String intent_Thumb = thumb_check.getStringExtra("trueThumbnail", "checked_thumb");

    // Get the shared preferences
    SharedPreferences prefs = this.getSharedPreferences(
                          "ch4an.ytheloader", Context.MODE_PRIVATE);

    //To read from preferences
        String pref_Thumb = prefs("trueThumbnail", "checked_thumb");

    // preform what ever you want

} catch (Throwable e) {
    Toast.makeText(MainActivity.this, "Null checkBox", Toast.LENGTH_SHORT).show();
         e.printStackTrace();
}
</code>```

You're mixing the SharedPreferences and Intents and it seems that you are lost in that code
Make sure you read the android documentation it helps a lot.
https://developer.android.com/guide/components/intents-filters.html

EDIT Responding your comment

```<code>SharedPreferences sharedPref = getSharedPreferences("ch4an.ytheloader", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("trueThumbnail", intent_Thumb);
// Or if you want to put a bool assuming that you have a
// variable called intent_Thumb_as_boolean as a boolean
editor.putBoolean("trueThumbnail", intent_Thumb_as_boolean);
editor.commit();
</code>```

Check the android docs for the SharedPreferences

https://developer.android.com/training/data-storage/shared-preferences.html

Body:
I have manually created a Preferences Activity, where the checkbox data will be sent to a different Activity. When I send it, it is right. But when I receive it, I need to know if it is true or false, and I always get false.

Here's my code to send:

@Override
    public void onBackPressed() {

        if(checkBox.isChecked())
        {
            String trueThumb_check = "checked_thumb";
            Intent i = new Intent(getBaseContext(), MainActivity.class);
            i.putExtra("trueThumbnail", trueThumb_check);
            Toast.makeText(Preferences.this, "check prefs", Toast.LENGTH_SHORT).show();
            startActivity(i);
            killAc();
        }
        else
        {
            String falseThumb_check = "not_check_thumb";
            Intent i = new Intent(getBaseContext(), MainActivity.class);
            i.putExtra("trueThumbnail", falseThumb_check);
            Toast.makeText(Preferences.this, "not check prefs", Toast.LENGTH_SHORT).show();
            startActivity(i);
            killAc();
        }

    }

And to receive:

try {
            SharedPreferences thumb_check = this.getSharedPreferences(
              "ch4an.ytheloader", Context.MODE_PRIVATE);

            //To read preferences
            String thumb_thumb = thumb_check.getString("trueThumbnail", "checked_thumb");

            if (thumb_thumb.contains("checked_thumb")){
            Toast.makeText(MainActivity.this, "checkBox ativo", Toast.LENGTH_SHORT).show();
            }  if(thumb_thumb.contains("not_checked_thumb")) {
            Toast.makeText(MainActivity.this, "checkBox não ativo", Toast.LENGTH_SHORT).show();
            }

            SharedPreferences.Editor editor = thumb_check.edit();
            editor.apply();

        } catch (Throwable e) {
            Toast.makeText(MainActivity.this, "Null checkBox", Toast.LENGTH_SHORT).show();
            e.printStackTrace();

        }

I believe the problem might be here:

String thumb_thumb = thumb_check.getString("trueThumbnail", "checked_thumb");

I always get a single " checked_thumb", but I don't know how to get "thumb_thumb" for both.
I've tried sending different keys and values (because both are under the "trueThumbnail" key) but I still get true only.

Body:
If you don't know how to ask your questions in english visit pt.stackoverflow.com

But as I'm Portuguese I'm gonna answer here, but in english.

Your receiving code is wrong. When you're sending the data you're sending through a intent, there's nothing wrong in there but when you're trying to receive you are getting from the SharedPreferences

So to access the data instead of this

SharedPreferences thumb_check = this.getSharedPreferences(
              "ch4an.ytheloader", Context.MODE_PRIVATE);

It should be this

Intent thumb_check = getIntent();
String thumb_thumb = thumb_check.getStringExtra("trueThumbnail", "checked_thumb");

A rewrite of the receive code

    try {
    // Get the intent passed through activities
    Intent thumb_check = getIntent();
    // Get the string in the extra
    String intent_Thumb = thumb_check.getStringExtra("trueThumbnail", "checked_thumb");

    // Get the shared preferences
    SharedPreferences prefs = this.getSharedPreferences(
                          "ch4an.ytheloader", Context.MODE_PRIVATE);

    //To read from preferences
        String pref_Thumb = prefs("trueThumbnail", "checked_thumb");

    // preform what ever you want

} catch (Throwable e) {
    Toast.makeText(MainActivity.this, "Null checkBox", Toast.LENGTH_SHORT).show();
         e.printStackTrace();
}

You're mixing the SharedPreferences and Intents and it seems that you are lost in that code
Make sure you read the android documentation it helps a lot.
https://developer.android.com/guide/components/intents-filters.html

EDIT Responding your comment

SharedPreferences sharedPref = getSharedPreferences("ch4an.ytheloader", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("trueThumbnail", intent_Thumb);
// Or if you want to put a bool assuming that you have a
// variable called intent_Thumb_as_boolean as a boolean
editor.putBoolean("trueThumbnail", intent_Thumb_as_boolean);
editor.commit();

Check the android docs for the SharedPreferences

https://developer.android.com/training/data-storage/shared-preferences.html


来源: stackexchange

问:
Links in header design question
Hey guys, I was planning to add links in my header, and designing them is causing me a bit of a problem. I'm aiming on making one similar to that of twitter, but there are two problems I'm facing. First, when I change the background color of one link, it changes the color of the background just around the link, but I want it to change the background of the link from the top of the header to the bottom of the header.(Refer to twitter to understand better) and also, how can I change the background color of just the link that is active? By active I mean that if the link links to homepage.php and the user is in homepage.php I want the link to have a different background color. Here's the code that I've come up with till now:

```<code><div class="littleheader"><div class="logo"><a HREF="index.php"><img class="fleft" src="graphics/little-logo.png" alt="Cliproid" ></a></div>

<div class="navbuttons">
<div class="navigations">
<a class="nav">test</a>
</div>
<br/><br/>
</div>
</div>
</code>```

and the styles:

```<code>    div.littleheader
    {
        background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#aadbba), to(#009933));
        background: -moz-linear-gradient(top, #aadbba, #009933);
        padding: 0.5em;
        color: white;
        clear: left;
        z-index: 1;
        height: 30px;
        }
     .logo
     {
        margin-left: 100px;
        vertical-align: middle;
        }
       div.navbuttons{
        float: left;
        text-align: left;
        margin-left: 50px;
        }
.fleft
{
    float: left;
    }
.navigations
{
    float: left;
    vertical-align: middle;
    margin-left: 10px;
    }
a.nav
{
    vertical-align: middle;
    color: white;
    }
</code>```

答:
My first thought would be to change the a.nav:

```<code>a.nav {
  display: block;
  float: right;
  line-height: 120px;      /* just an example, line-height causes vertically aligned */
}
</code>```

and take it from there.

You will have to float your whole navigation bar right and other stuff left, but this is the basic start.

ContentLicense: CC BY-SA 2.5

Title: Links in header design question

Body:
Hey guys, I was planning to add links in my header, and designing them is causing me a bit of a problem. I'm aiming on making one similar to that of twitter, but there are two problems I'm facing. First, when I change the background color of one link, it changes the color of the background just around the link, but I want it to change the background of the link from the top of the header to the bottom of the header.(Refer to twitter to understand better) and also, how can I change the background color of just the link that is active? By active I mean that if the link links to homepage.php and the user is in homepage.php I want the link to have a different background color. Here's the code that I've come up with till now:

test

and the styles:

    div.littleheader
    {
        background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#aadbba), to(#009933));
        background: -moz-linear-gradient(top, #aadbba, #009933);
        padding: 0.5em;
        color: white;
        clear: left;
        z-index: 1;
        height: 30px;
        }
     .logo
     {
        margin-left: 100px;
        vertical-align: middle;
        }
       div.navbuttons{
        float: left;
        text-align: left;
        margin-left: 50px;
        }
.fleft
{
    float: left;
    }
.navigations
{
    float: left;
    vertical-align: middle;
    margin-left: 10px;
    }
a.nav
{
    vertical-align: middle;
    color: white;
    }

Body:
My first thought would be to change the a.nav:

a.nav {
  display: block;
  float: right;
  line-height: 120px;      /* just an example, line-height causes vertically aligned */
}

and take it from there.

You will have to float your whole navigation bar right and other stuff left, but this is the basic start.


问:
Electron : Confirm and Alert of a website in a webview doesn't show
I have an electron app with a webview in the page loaded in my BrowserWindow.
This website is emitting in some occasion Confirm or Alert but electron is showing them. Is there any way of modifying this behavior for example in the code I inject on the website page?</p>

答:
As the  website is alerting when the user want to quit the page after modifying some data. The website is using onbeforeunload attibute of the document.body.
So I'm writing a piece of code using MutationObserver to listen in the injected code of the webview at this attibute and reset it myself plus using the Electron Confirm located in override.js to warn the use. Not finish yet because of others problems but it is the way...

ContentLicense: CC BY-SA 3.0


问:
Automatically set the primary key for one table as the foreign key for another?
I have two Django models:

```<code>class seller_event(models.Model):
    event_id = models.AutoField(primary_key=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length = 300, default = 'Null')
    description = models.CharField(max_length = 300, default = 'Null')
    location = models.CharField(max_length= 300, default = 'Null')
    cash_payment = models.BooleanField(default=True)
    paytm_payment = models.BooleanField(default=False)

    def __unicode__(self):
        return str(self.event_id)

class seller_event_items(models.Model):
    item_id = models.AutoField(primary_key=True)
    event_id = models.ForeignKey(seller_event)
    item_name = models.CharField(max_length = 300, default = 'Null')
    item_price = models.CharField(max_length = 300, default = 'Null')
    item_quant = models.CharField(max_length = 300, default = 'Null')

    def __unicode__(self):
        return str(self.item_id)
</code>```

The foreign key for the second table is the primary key for the first table. Essentially, I am trying to associate items with a sale. I have a forms like such:

forms.py:

```<code>class Seller_event(forms.ModelForm):

    class Meta:
        model = seller_event
        exclude = {'user'}

class Seller_event_items(forms.ModelForm):

    class Meta:
        model = seller_event_items
        exclude = {'event_id'}
</code>```

views.py:

```<code>def newlist(request):
    if request.user.is_authenticated():
        user = request.user
        print user
        if request.method == 'POST':
            seller_event_form = Seller_event(request.POST)
            seller_event_items_form = Seller_event_items(request.POST)
            if seller_event_form.is_valid() and seller_event_items_form.is_valid():
                new_seller_event = seller_event_form.save(commit=False)
                new_seller_event.user = user
                new_seller_event.save()
                seller_event_items_form.save()
                return redirect('/home')

        else:
            seller_event_form = Seller_event()
            seller_event_items_form = Seller_event_items()

        return render(request, 'home/newlist.html', {'seller_event_form': seller_event_form, 'seller_event_items_form': seller_event_items_form})
</code>```

The form here is helping a seller both create a sale and then populate the sale with items.

How can I go about automatically setting the fk on the items table as the event_id (pk for seller_events table)? I have excluded it from the form, but I'm not sure what to do after this.

Thanks in advance!

答:
You do it in exactly the same way you are already setting the user on the new_seller_event.

The relationship between the event and the user is the same as the relationship between the item and the event.

Body:
I have two Django models:

class seller_event(models.Model):
    event_id = models.AutoField(primary_key=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length = 300, default = 'Null')
    description = models.CharField(max_length = 300, default = 'Null')
    location = models.CharField(max_length= 300, default = 'Null')
    cash_payment = models.BooleanField(default=True)
    paytm_payment = models.BooleanField(default=False)

    def __unicode__(self):
        return str(self.event_id)

class seller_event_items(models.Model):
    item_id = models.AutoField(primary_key=True)
    event_id = models.ForeignKey(seller_event)
    item_name = models.CharField(max_length = 300, default = 'Null')
    item_price = models.CharField(max_length = 300, default = 'Null')
    item_quant = models.CharField(max_length = 300, default = 'Null')

    def __unicode__(self):
        return str(self.item_id)

The foreign key for the second table is the primary key for the first table. Essentially, I am trying to associate items with a sale. I have a forms like such:

forms.py:

class Seller_event(forms.ModelForm):

    class Meta:
        model = seller_event
        exclude = {'user'}

class Seller_event_items(forms.ModelForm):

    class Meta:
        model = seller_event_items
        exclude = {'event_id'}

views.py:

def newlist(request):
    if request.user.is_authenticated():
        user = request.user
        print user
        if request.method == 'POST':
            seller_event_form = Seller_event(request.POST)
            seller_event_items_form = Seller_event_items(request.POST)
            if seller_event_form.is_valid() and seller_event_items_form.is_valid():
                new_seller_event = seller_event_form.save(commit=False)
                new_seller_event.user = user
                new_seller_event.save()
                seller_event_items_form.save()
                return redirect('/home')

        else:
            seller_event_form = Seller_event()
            seller_event_items_form = Seller_event_items()

        return render(request, 'home/newlist.html', {'seller_event_form': seller_event_form, 'seller_event_items_form': seller_event_items_form})

The form here is helping a seller both create a sale and then populate the sale with items.

How can I go about automatically setting the fk on the items table as the event_id (pk for seller_events table)? I have excluded it from the form, but I'm not sure what to do after this.

Thanks in advance!


问:
Android App crashes on older devices
My app works perfectly on my phone. On some older devices it crashes though:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blub.bla/com.blub.bla.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class ImageButton
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
...
Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class ImageButton
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
    at
...
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_google_plus_icon.xml from drawable resource ID #0x7f0700ab
    at android.content.res.Resources.loadDrawableForCookie(Resources.java:2872)
...
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #0: invalid color state list tag gradient
    at android.content.res.ColorStateList.createFromXmlInner(ColorStateList.java:217)
    at
...
</code>```

I checked other posts and most of the time it had something to do with gradle, and I can say that i have vectorDrawables.useSupportLibrary = true set.

Gradle file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 27

    repositories {
        mavenCentral()
    }
    defaultConfig {
        applicationId "com.blub.bla"
        vectorDrawables.useSupportLibrary = true
        minSdkVersion 19
        targetSdkVersion 27

        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    android {
        lintOptions {
            disable 'RestrictedApi'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'com.facebook.android:facebook-login:[4,5)'
    implementation 'com.facebook.android:facebook-share:[4,5)'
    implementation 'com.android.support:appcompat-v7:27.0.1'
    implementation 'com.android.support:design:27.0.1'
    implementation 'com.android.support:support-v4:27.0.1'

    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.squareup.okhttp:okhttp:2.4.0'
    implementation 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
    implementation 'com.google.android.gms:play-services-location:10.+'
    implementation 'com.google.android.gms:play-services-places:10.+'
    implementation 'com.google.maps.android:android-maps-utils:0.4+'

    implementation 'eu.the4thfloor.volley:com.android.volley:2015.05.28'
    testImplementation 'junit:junit:4.12'
}
</code>```

Edit:
activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@drawable/bg"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"
        app:menu="@menu/activity_main_drawer">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:paddingBottom="10dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                >
                <com.facebook.share.widget.ShareButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentLeft="true"
                    android:id="@+id/fb_share_button"/>
                <ImageButton
                    android:id="@+id/sm_twitter"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_twitter_bird_logo"
                    android:background="@color/transparent"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentRight="true"
                    />
                <ImageButton
                    android:id="@+id/sm_facebook"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_f_icon_color"
                    android:background="@color/transparent"
                    android:layout_alignParentBottom="true"
                    android:layout_toLeftOf="@id/sm_twitter"
                    />
                <ImageButton
                    android:id="@+id/sm_gplus"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_google_plus_icon"
                    android:background="@color/transparent"
                    android:layout_alignParentBottom="true"
                    android:layout_toLeftOf="@id/sm_facebook"
                    />
            </RelativeLayout >
        </RelativeLayout>
    </android.support.design.widget.NavigationView>>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view_right"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:background="@drawable/bg"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_filter"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="175dp"
            android:orientation="horizontal">
            <include
                layout="@layout/filter_layout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                />
        </RelativeLayout>
    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
</code>```

Does anyone know how to fix that? :(

答:
First Problem: I had some resources in drawable/v21 instead of drawable (not easy to see, since it's showing the same folder in Android studio, just with a (21) next to the file name

Second Problem: Use app:srcCompat instead of android:background or android:res

Title: Android App crashes on older devices

Body:
My app works perfectly on my phone. On some older devices it crashes though:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blub.bla/com.blub.bla.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class ImageButton
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
...
Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class ImageButton
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
    at
...
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_google_plus_icon.xml from drawable resource ID #0x7f0700ab
    at android.content.res.Resources.loadDrawableForCookie(Resources.java:2872)
...
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #0: invalid color state list tag gradient
    at android.content.res.ColorStateList.createFromXmlInner(ColorStateList.java:217)
    at
...

I checked other posts and most of the time it had something to do with gradle, and I can say that i have vectorDrawables.useSupportLibrary = true set.

Gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27

    repositories {
        mavenCentral()
    }
    defaultConfig {
        applicationId "com.blub.bla"
        vectorDrawables.useSupportLibrary = true
        minSdkVersion 19
        targetSdkVersion 27

        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    android {
        lintOptions {
            disable 'RestrictedApi'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'com.facebook.android:facebook-login:[4,5)'
    implementation 'com.facebook.android:facebook-share:[4,5)'
    implementation 'com.android.support:appcompat-v7:27.0.1'
    implementation 'com.android.support:design:27.0.1'
    implementation 'com.android.support:support-v4:27.0.1'

    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.squareup.okhttp:okhttp:2.4.0'
    implementation 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
    implementation 'com.google.android.gms:play-services-location:10.+'
    implementation 'com.google.android.gms:play-services-places:10.+'
    implementation 'com.google.maps.android:android-maps-utils:0.4+'

    implementation 'eu.the4thfloor.volley:com.android.volley:2015.05.28'
    testImplementation 'junit:junit:4.12'
}

Edit:
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@drawable/bg"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"
        app:menu="@menu/activity_main_drawer">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:paddingBottom="10dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                >
                <com.facebook.share.widget.ShareButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentLeft="true"
                    android:id="@+id/fb_share_button"/>
                <ImageButton
                    android:id="@+id/sm_twitter"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_twitter_bird_logo"
                    android:background="@color/transparent"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentRight="true"
                    />
                <ImageButton
                    android:id="@+id/sm_facebook"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_f_icon_color"
                    android:background="@color/transparent"
                    android:layout_alignParentBottom="true"
                    android:layout_toLeftOf="@id/sm_twitter"
                    />
                <ImageButton
                    android:id="@+id/sm_gplus"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_google_plus_icon"
                    android:background="@color/transparent"
                    android:layout_alignParentBottom="true"
                    android:layout_toLeftOf="@id/sm_facebook"
                    />
            </RelativeLayout >
        </RelativeLayout>
    </android.support.design.widget.NavigationView>>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view_right"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:background="@drawable/bg"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_filter"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="175dp"
            android:orientation="horizontal">
            <include
                layout="@layout/filter_layout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                />
        </RelativeLayout>
    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

Does anyone know how to fix that? :(


问:
iOS cordova allow location access 'Always'
I am developing an app with Cordova for iOS which includes geolocation functionalities (I use the official plugin https://github.com/apache/cordova-plugin-geolocation). I saw in options of my app that location access can be either set as "Never" or "While Using the App". However some other apps may also the option "Always" as shown in the attached screenshot. I would like to know whether it is possible to also have the option "Always" for Cordova-based applications.

Thanks!

答:
I'm using Ionic 2 and had to add the following to my App-Info.plist file. Even though cordova inserts 'NSLocationAlwaysUsageDescription' and 'NSLocationWhenInUseUsageDescription' keys. This only gave a 'Never' and 'While Using App' option on launch. Xcode suggested using the option below and that worked for me.</p>

```<code>        <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
        <string>This app requires background location tracking</string>
</code>```

Body:
I'm using Ionic 2 and had to add the following to my App-Info.plist file. Even though cordova inserts 'NSLocationAlwaysUsageDescription' and 'NSLocationWhenInUseUsageDescription' keys. This only gave a 'Never' and 'While Using App' option on launch. Xcode suggested using the option below and that worked for me.

        <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
        <string>This app requires background location tracking</string>


问:
How to use Jenkins 2.63 with jobs which should be built using Java 1.7?
we have a Jenkins job which is/was configured to use JDK7. Upon inspecting the logs, i noticed following ERRORs:

```<code>ERROR: Invalid project setup: jenkins/security/MasterToSlaveCallable : Unsupported major.minor version 52.0
ERROR: [JENKINS-18403][JENKINS-28294] JDK 'JDK 1.7.0_45' not supported to run Maven projects.
ERROR: Maven projects have to be launched with a Java version greater or equal to the minimum version required by the master.
ERROR: Use the Maven JDK Toolchains (plugin) to build your maven project with an older JDK.
ERROR: Retrying with slave Java and setting compile/test properties to point to /usr/java/jdk1.7.0_45/.
</code>```

After some googling it seems that there is some interaction between the Job and Jenkins itself. Since Jenkins is started with JDK8 and the Job with JDK7 it seems to produce this ERROR. The build is OK, because Jenkins then proceeds to build with JDK8. But we actually want this built with 1.7.

So the question is:
If we start Jenkins with JDK8, how can i get the Jobs to compile with JDK7 without this error?

答:
As you might probably know Jenkins >= 2.54 requires Java >= 8 thus Maven jobs must be launched with Java >= 8

Besides that the Error message is guiding you with:

Use the Maven JDK Toolchains (plugin) to build your maven project...

Using that plugin would probably help you to run your jenkins job using Java 8 and also compile your project files using Java 7.

I resolved my problem this way some years ago.

You can see more details on this Answer.

Body:
we have a Jenkins job which is/was configured to use JDK7. Upon inspecting the logs, i noticed following ERRORs:

ERROR: Invalid project setup: jenkins/security/MasterToSlaveCallable : Unsupported major.minor version 52.0
ERROR: [JENKINS-18403][JENKINS-28294] JDK 'JDK 1.7.0_45' not supported to run Maven projects.
ERROR: Maven projects have to be launched with a Java version greater or equal to the minimum version required by the master.
ERROR: Use the Maven JDK Toolchains (plugin) to build your maven project with an older JDK.
ERROR: Retrying with slave Java and setting compile/test properties to point to /usr/java/jdk1.7.0_45/.

After some googling it seems that there is some interaction between the Job and Jenkins itself. Since Jenkins is started with JDK8 and the Job with JDK7 it seems to produce this ERROR. The build is OK, because Jenkins then proceeds to build with JDK8. But we actually want this built with 1.7.

So the question is:
If we start Jenkins with JDK8, how can i get the Jobs to compile with JDK7 without this error?

ContentLicense: CC BY-SA 4.0


问:
C - declare and init array inside struct
language: C

i am trying to declare and initialize an array inside a struct and pass it to a pointer, which is itself declared in the struct xD

yes, i know my attempt is... let's say "not correct" :D
but it would be very useful if something similar would exist.

any ideas?

```<code>struct structname {
    int* section_A;
    int* section_B;
};

static const struct structname structvariable_a = {

    .section_A = (int[]) {
            [0x01] = 1,
            [0x02] = 2,
            [0x03] = 3
        },

    .section_B = (int[]) {
            [0x33] = 4,
            [0x34] = 5
        },

};

static const struct structname structvariable_b = {

    .section_A = (int[]) {
            [0x01] = 10,
            [0x02] = 20,
            [0x03] = 30
        },

    .section_B = (int[]) {
            [0x33] = 7,
            [0x34] = 8
        },

};
</code>```

later, i want to access the values ...

```<code>int main()
{

    struct structname* structvariablepointer;

    if(foo == 1){
        structvariablepointer = &structvariable_a;
    } else {
        structvariablepointer = &structvariable_b;
    }

    printf("%i", ARRAY_SIZE(structvariablepointer->section_A));     // ARRAY_SIZE(arr) equals sizeof(arr) / sizeof(arr[0]));

    int b = 2;

    printf("%i", structvariablepointer->section_A[b]);
}
</code>```

the only error is

```<code>./include/linux/build_bug.h:29:45: Fehler: Negative Breite in Bitfeld »<anonym>«
 #define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:(-!!(e)); }))
                                             ^
./include/linux/compiler-gcc.h:64:28: Anmerkung: bei Substitution des Makros »BUILD_BUG_ON_ZERO«
 #define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0]))
                            ^~~~~~~~~~~~~~~~~
./include/linux/kernel.h:60:59: Anmerkung: bei Substitution des Makros »__must_be_array«
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
                                                           ^~~~~~~~~~~~~~~
</code>```

答:
Once you take a pointer to the first element of an array, you can no longer find the size of the array through that pointer. So you will also need to make variables to hold the array size. (Or use a sentinel value for the end of the array).

One way to solve your problem would be through ugly macros:

```<code>#include <stddef.h>
#define ARRAY_SIZE(a) ( (sizeof(a)) / sizeof((a)[0]) )

struct structname {
    int* section_A;
    size_t A_len;
    int* section_B;
    size_t B_len;
};

#define A_INIT (int[]) { 0, 1, 2, 3 }
#define B_INIT (int[]) { [0x33] = 1, [0x34] = 2 }

static const struct structname structvariable_a =
{
    .section_A = A_INIT,
    .A_len = ARRAY_SIZE(A_INIT),
    .section_B = B_INIT,
    .B_len = ARRAY_SIZE(B_INIT)
};
#undef A_INIT
#undef B_INIT
</code>```

It would also be possible to define static named int arrays and then use that array's name in the initializers for structvariable_a.

Consider using int const * and int const[] respectively, if you don't intend to change the contents of the arrays at runtime. Note that if this code is in a header, each translation unit will have their own copy of the arrays.

Update (as suggested by comment): using a sentinel value would look like:

```<code>struct structname {
    int* section_A;
    int* section_B;
};

static const struct structname structvariable_a =
{
    .section_A = (int[]) { 0, 1, 2, 3, INT_MAX },
    .section_B = (int[]) { [0x33] = 1, [0x34] = 2, INT_MAX }
};
</code>```

and the in main or whatever, you look for INT_MAX to know where the end of the array is, e.g.:

```<code>size_t a_len;
for (a_len = 0; structvariable_a.section_A[a_len] != INT_MAX; ++a_len) { }
</code>```

Obviously this means the range of valid data for the array needs to exclude the sentinel value.

Body:
language: C

i am trying to declare and initialize an array inside a struct and pass it to a pointer, which is itself declared in the struct xD

yes, i know my attempt is... let's say "not correct" :D
but it would be very useful if something similar would exist.

any ideas?

struct structname {
    int* section_A;
    int* section_B;
};

static const struct structname structvariable_a = {

    .section_A = (int[]) {
            [0x01] = 1,
            [0x02] = 2,
            [0x03] = 3
        },

    .section_B = (int[]) {
            [0x33] = 4,
            [0x34] = 5
        },

};

static const struct structname structvariable_b = {

    .section_A = (int[]) {
            [0x01] = 10,
            [0x02] = 20,
            [0x03] = 30
        },

    .section_B = (int[]) {
            [0x33] = 7,
            [0x34] = 8
        },

};

later, i want to access the values ...

int main()
{

    struct structname* structvariablepointer;

    if(foo == 1){
        structvariablepointer = &structvariable_a;
    } else {
        structvariablepointer = &structvariable_b;
    }

    printf("%i", ARRAY_SIZE(structvariablepointer->section_A));     // ARRAY_SIZE(arr) equals sizeof(arr) / sizeof(arr[0]));

    int b = 2;

    printf("%i", structvariablepointer->section_A[b]);
}

the only error is

./include/linux/build_bug.h:29:45: Fehler: Negative Breite in Bitfeld »<anonym>«
 #define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:(-!!(e)); }))
                                             ^
./include/linux/compiler-gcc.h:64:28: Anmerkung: bei Substitution des Makros »BUILD_BUG_ON_ZERO«
 #define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0]))
                            ^~~~~~~~~~~~~~~~~
./include/linux/kernel.h:60:59: Anmerkung: bei Substitution des Makros »__must_be_array«
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
                                                           ^~~~~~~~~~~~~~~

Body:
Once you take a pointer to the first element of an array, you can no longer find the size of the array through that pointer. So you will also need to make variables to hold the array size. (Or use a sentinel value for the end of the array).

One way to solve your problem would be through ugly macros:

#include <stddef.h>
#define ARRAY_SIZE(a) ( (sizeof(a)) / sizeof((a)[0]) )

struct structname {
    int* section_A;
    size_t A_len;
    int* section_B;
    size_t B_len;
};

#define A_INIT (int[]) { 0, 1, 2, 3 }
#define B_INIT (int[]) { [0x33] = 1, [0x34] = 2 }

static const struct structname structvariable_a =
{
    .section_A = A_INIT,
    .A_len = ARRAY_SIZE(A_INIT),
    .section_B = B_INIT,
    .B_len = ARRAY_SIZE(B_INIT)
};
#undef A_INIT
#undef B_INIT

It would also be possible to define static named int arrays and then use that array's name in the initializers for structvariable_a.

Consider using int const * and int const[] respectively, if you don't intend to change the contents of the arrays at runtime. Note that if this code is in a header, each translation unit will have their own copy of the arrays.

Update (as suggested by comment): using a sentinel value would look like:

struct structname {
    int* section_A;
    int* section_B;
};

static const struct structname structvariable_a =
{
    .section_A = (int[]) { 0, 1, 2, 3, INT_MAX },
    .section_B = (int[]) { [0x33] = 1, [0x34] = 2, INT_MAX }
};

and the in main or whatever, you look for INT_MAX to know where the end of the array is, e.g.:

size_t a_len;
for (a_len = 0; structvariable_a.section_A[a_len] != INT_MAX; ++a_len) { }

Obviously this means the range of valid data for the array needs to exclude the sentinel value.


问:
Swift: Why do I get the error: "Binary operator '<=' cannot be applied to operands of type 'Int?' and 'Int' ", in my function:
have this swift Code:

```<code>let from = newDate
let now = NSDate()
let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfMonth])
let difference = Calendar.current.dateComponents(components, from: from, to: now as Date)

if difference.second <= 0{
    cell.DateLbl.text = "now"
}
</code>```

my Problem is, that I get the following error and I don't really now how to solve it.

Binary operator '<=' cannot be applied to operands of type 'Int?' and
  'Int'

Thank you guys in advance

答:
You are getting this error because Int and Int? are not the same type.  You need to handle cases where difference.second is nil.

One way to do this would be to use a nil-coalescing operator to treat nil as if it was zero.  So you could say if (difference.second ?? 0) <= 0 {...

Body:
have this swift Code:

let from = newDate
let now = NSDate()
let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfMonth])
let difference = Calendar.current.dateComponents(components, from: from, to: now as Date)

if difference.second <= 0{
    cell.DateLbl.text = "now"
}

my Problem is, that I get the following error and I don't really now how to solve it.

Binary operator '<=' cannot be applied to operands of type 'Int?' and
  'Int'

Thank you guys in advance


问:
Access Query - Invalid Operation when using Order By clause
The following query works fine but as soon as I add the Order By clause, I get an

error - "invalid operation"

Can any one help me please?

```<code>SELECT dbo_jobs.jobid,
       dbo_jobs.jobrefno,
       dbo_jobs.createdon,
       dbo_jobs.archived,
       dbo_jobs.published,
       dbo_jobs.jobtitle,
       dbo_jobs.statusid,
       dbo_jobs.clientid,
       dbo_clients.company,
       dbo_clientcontacts.clientcontactid,
       dbo_employmenttypes.employmenttypeid,
       dbo_employmenttypes.description,
       dbo_locations.description,
       dbo_jobsectordefinedcolumns.clientname,
       dbo_jobsectordefinedcolumns.natureofcase,
       dbo_jobsectordefinedcolumns.timescaletodeadline,
       dbo_jobs.notes,
       dbo_jobsectordefinedcolumns.status,
       dbo_clientcontacts.contactpersonid,
       dbo_jobsectordefinedcolumns.vat,
       dbo_jobsectordefinedcolumns.postcode,
       dbo_jobsectordefinedcolumns.additionalinfo,
       dbo_jobsectordefinedcolumns.solicitorref,
       dbo_jobconsultants.userid,
       dbo_users.loginname,
       dbo_jobs.positionattributeid,
       dbo_jobsectordefinedcolumns.consultancyservice,
       [dbo_person].[PersonName] & ' ' & [dbo_person].[Surname] AS ClientCon,
       dbo_person.personname,
       dbo_person.surname,
       dbo_jobstatus.description,
       dbo_jobsectordefinedcolumns.priority,
       RevListCount.countofrevids,
       CVCount.cvsentcount
FROM   (((SELECT dbo_jobs.jobid,
                dbo_jobs.jobrefno,
                dbo_jobs.createdon,
                dbo_jobs.archived,
                dbo_jobs.published,
                dbo_jobs.jobtitle,
                dbo_jobs.statusid,
                dbo_jobs.clientid,
                dbo_clients.company,
                dbo_clientcontacts.clientcontactid,
                dbo_employmenttypes.employmenttypeid,
                dbo_employmenttypes.description,
                dbo_locations.description,
                dbo_jobsectordefinedcolumns.clientname,
                dbo_jobsectordefinedcolumns.natureofcase,
                dbo_jobsectordefinedcolumns.timescaletodeadline,
                dbo_jobs.notes,
                dbo_jobsectordefinedcolumns.status,
                dbo_clientcontacts.contactpersonid,
                dbo_jobsectordefinedcolumns.vat,
                dbo_jobsectordefinedcolumns.postcode,
                dbo_jobsectordefinedcolumns.additionalinfo,
                dbo_jobsectordefinedcolumns.solicitorref,
                dbo_jobconsultants.userid,
                dbo_users.loginname,
                dbo_jobs.positionattributeid,
                dbo_jobsectordefinedcolumns.consultancyservice,
                [dbo_person].[personname] & ' ' & [dbo_person].[surname] AS
                 ClientCon,
                dbo_person.personname,
                dbo_person.surname,
                dbo_jobstatus.description,
                dbo_jobsectordefinedcolumns.priority
         FROM   ((((((((dbo_employmenttypes
                        INNER JOIN dbo_jobs
                                ON dbo_employmenttypes.employmenttypeid =
                                  dbo_jobs.employmenttypeid)
                       INNER JOIN dbo_clients
                               ON dbo_jobs.clientid = dbo_clients.clientid)
                      INNER JOIN dbo_clientcontacts
                              ON dbo_jobs.clientcontactid =
                                 dbo_clientcontacts.clientcontactid)
                     LEFT JOIN dbo_jobsectordefinedcolumns
                            ON dbo_jobs.jobid =
dbo_jobsectordefinedcolumns.jobid)
                    INNER JOIN dbo_person
                            ON dbo_clientcontacts.contactpersonid =
                   dbo_person.personid)
                   LEFT JOIN dbo_jobconsultants
                          ON dbo_jobs.jobid = dbo_jobconsultants.jobid)
                  LEFT JOIN dbo_users
                         ON dbo_jobconsultants.userid = dbo_users.userid)
                 LEFT JOIN dbo_jobstatus
                        ON dbo_jobs.statusid = dbo_jobstatus.jobstatusid)
                LEFT JOIN dbo_locations
                       ON dbo_jobs.locationid = dbo_locations.locationid
         WHERE  ( ( ( dbo_jobs.archived ) = 'N' )
                  AND ( ( dbo_employmenttypes.employmenttypeid ) <> 12 )
                  AND ( ( dbo_jobconsultants.userrelationshipid ) = 9 )
                  AND
         ( ( dbo_jobstatus.description ) <> 'Filled'
           AND ( dbo_jobstatus.description ) <> 'Filled - Ongoing' ) )) AS
        AllJobs
         LEFT JOIN (SELECT dbo_reviewlists.jobid,
                           Count(dbo_reviewlistapplicants.reviewlistid) AS
                           CountOfRevIDs
                    FROM   dbo_reviewlists
                           LEFT JOIN dbo_reviewlistapplicants
                                  ON dbo_reviewlists.reviewlistid =
                                     dbo_reviewlistapplicants.reviewlistid
                    GROUP  BY dbo_reviewlists.jobid) AS RevListCount
                ON AllJobs.jobid = RevListCount.jobid)
        LEFT JOIN (SELECT dbo_applicantactions.jobid,
                          Count(dbo_applicantactions.statusid) AS CVSentCount
                   FROM   dbo_applicantactions
                   WHERE  (( ( dbo_applicantactions.statusid ) = 29 ))
                   GROUP  BY dbo_applicantactions.jobid) AS CVCount
               ON AllJobs.jobid = CVCount.jobid)
ORDER  BY dbo_jobs.jobid DESC
</code>```

答:
Holy extraneous parenthesis, Batman! This should work. Looks like you needed the outer table alias of AllJobs applied to the columns of the outer select statement. I also cleaned up all the unnecessary parenthesis.

```<code>SELECT
    AllJobs.jobid
    ,AllJobs.jobrefno
    ,AllJobs.createdon
    ,AllJobs.archived
    ,AllJobs.published
    ,AllJobs.jobtitle
    ,AllJobs.statusid
    ,AllJobs.clientid
    ,AllJobs.company
    ,AllJobs.clientcontactid
    ,AllJobs.employmenttypeid
    ,AllJobs.description
    ,AllJobs.description
    ,AllJobs.clientname
    ,AllJobs.natureofcase
    ,AllJobs.timescaletodeadline
    ,AllJobs.notes
    ,AllJobs.status
    ,AllJobs.contactpersonid
    ,AllJobs.vat
    ,AllJobs.postcode
    ,AllJobs.additionalinfo
    ,AllJobs.solicitorref
    ,AllJobs.userid
    ,AllJobs.loginname
    ,AllJobs.positionattributeid
    ,AllJobs.consultancyservice
    ,AllJobs.ClientCon
    ,AllJobs.personname
    ,AllJobs.surname
    ,AllJobs.description
    ,AllJobs.priority
    ,RevListCount.CountOfRevIDs
    ,CVCount.CVSentCount
FROM(
        SELECT
            dbo_jobs.jobid
            ,dbo_jobs.jobrefno
            ,dbo_jobs.createdon
            ,dbo_jobs.archived
            ,dbo_jobs.published
            ,dbo_jobs.jobtitle
            ,dbo_jobs.statusid
            ,dbo_jobs.clientid
            ,dbo_clients.company
            ,dbo_clientcontacts.clientcontactid
            ,dbo_employmenttypes.employmenttypeid
            ,dbo_employmenttypes.description
            ,dbo_locations.description
            ,dbo_jobsectordefinedcolumns.clientname
            ,dbo_jobsectordefinedcolumns.natureofcase
            ,dbo_jobsectordefinedcolumns.timescaletodeadline
            ,dbo_jobs.notes
            ,dbo_jobsectordefinedcolumns.status
            ,dbo_clientcontacts.contactpersonid
            ,dbo_jobsectordefinedcolumns.vat
            ,dbo_jobsectordefinedcolumns.postcode
            ,dbo_jobsectordefinedcolumns.additionalinfo
            ,dbo_jobsectordefinedcolumns.solicitorref
            ,dbo_jobconsultants.userid
            ,dbo_users.loginname
            ,dbo_jobs.positionattributeid
            ,dbo_jobsectordefinedcolumns.consultancyservice
            ,[dbo_person].[personname] & ' ' & [dbo_person].[surname] AS ClientCon
            ,dbo_person.personname
            ,dbo_person.surname
            ,dbo_jobstatus.description
            ,dbo_jobsectordefinedcolumns.priority
        FROM dbo_employmenttypes
        INNER JOIN dbo_jobs ON dbo_employmenttypes.employmenttypeid = dbo_jobs.employmenttypeid
        INNER JOIN dbo_clients ON dbo_jobs.clientid = dbo_clients.clientid
        INNER JOIN dbo_clientcontacts ON dbo_jobs.clientcontactid = dbo_clientcontacts.clientcontactid
        LEFT JOIN dbo_jobsectordefinedcolumns ON dbo_jobs.jobid = dbo_jobsectordefinedcolumns.jobid
        INNER JOIN dbo_person ON dbo_clientcontacts.contactpersonid = dbo_person.personid
        LEFT JOIN dbo_jobconsultants ON dbo_jobs.jobid = dbo_jobconsultants.jobid
        LEFT JOIN dbo_users ON dbo_jobconsultants.userid = dbo_users.userid
        LEFT JOIN dbo_jobstatus ON dbo_jobs.statusid = dbo_jobstatus.jobstatusid
        LEFT JOIN dbo_locations ON dbo_jobs.locationid = dbo_locations.locationid
        WHERE dbo_jobs.archived = 'N'
            AND dbo_employmenttypes.employmenttypeid <> 12
            AND dbo_jobconsultants.userrelationshipid = 9
            AND (
                    dbo_jobstatus.description <> 'Filled'
                    AND dbo_jobstatus.description <> 'Filled - Ongoing'
                )
    )      AS AllJobs
LEFT JOIN(
             SELECT
                 dbo_reviewlists.jobid
                 ,COUNT(dbo_reviewlistapplicants.reviewlistid) AS CountOfRevIDs
             FROM dbo_reviewlists
             LEFT JOIN dbo_reviewlistapplicants ON dbo_reviewlists.reviewlistid = dbo_reviewlistapplicants.reviewlistid
             GROUP BY dbo_reviewlists.jobid
         ) AS RevListCount ON AllJobs.jobid = RevListCount.jobid
LEFT JOIN(
             SELECT
                 dbo_applicantactions.jobid
                 ,COUNT(dbo_applicantactions.statusid) AS CVSentCount
             FROM dbo_applicantactions
             WHERE dbo_applicantactions.statusid = 29
             GROUP BY dbo_applicantactions.jobid
         ) AS CVCount ON AllJobs.jobid = CVCount.jobid
ORDER BY AllJobs.jobid DESC;
</code>```

Body:
The following query works fine but as soon as I add the Order By clause, I get an

error - "invalid operation"

Can any one help me please?

SELECT dbo_jobs.jobid,
       dbo_jobs.jobrefno,
       dbo_jobs.createdon,
       dbo_jobs.archived,
       dbo_jobs.published,
       dbo_jobs.jobtitle,
       dbo_jobs.statusid,
       dbo_jobs.clientid,
       dbo_clients.company,
       dbo_clientcontacts.clientcontactid,
       dbo_employmenttypes.employmenttypeid,
       dbo_employmenttypes.description,
       dbo_locations.description,
       dbo_jobsectordefinedcolumns.clientname,
       dbo_jobsectordefinedcolumns.natureofcase,
       dbo_jobsectordefinedcolumns.timescaletodeadline,
       dbo_jobs.notes,
       dbo_jobsectordefinedcolumns.status,
       dbo_clientcontacts.contactpersonid,
       dbo_jobsectordefinedcolumns.vat,
       dbo_jobsectordefinedcolumns.postcode,
       dbo_jobsectordefinedcolumns.additionalinfo,
       dbo_jobsectordefinedcolumns.solicitorref,
       dbo_jobconsultants.userid,
       dbo_users.loginname,
       dbo_jobs.positionattributeid,
       dbo_jobsectordefinedcolumns.consultancyservice,
       [dbo_person].[PersonName] & ' ' & [dbo_person].[Surname] AS ClientCon,
       dbo_person.personname,
       dbo_person.surname,
       dbo_jobstatus.description,
       dbo_jobsectordefinedcolumns.priority,
       RevListCount.countofrevids,
       CVCount.cvsentcount
FROM   (((SELECT dbo_jobs.jobid,
                dbo_jobs.jobrefno,
                dbo_jobs.createdon,
                dbo_jobs.archived,
                dbo_jobs.published,
                dbo_jobs.jobtitle,
                dbo_jobs.statusid,
                dbo_jobs.clientid,
                dbo_clients.company,
                dbo_clientcontacts.clientcontactid,
                dbo_employmenttypes.employmenttypeid,
                dbo_employmenttypes.description,
                dbo_locations.description,
                dbo_jobsectordefinedcolumns.clientname,
                dbo_jobsectordefinedcolumns.natureofcase,
                dbo_jobsectordefinedcolumns.timescaletodeadline,
                dbo_jobs.notes,
                dbo_jobsectordefinedcolumns.status,
                dbo_clientcontacts.contactpersonid,
                dbo_jobsectordefinedcolumns.vat,
                dbo_jobsectordefinedcolumns.postcode,
                dbo_jobsectordefinedcolumns.additionalinfo,
                dbo_jobsectordefinedcolumns.solicitorref,
                dbo_jobconsultants.userid,
                dbo_users.loginname,
                dbo_jobs.positionattributeid,
                dbo_jobsectordefinedcolumns.consultancyservice,
                [dbo_person].[personname] & ' ' & [dbo_person].[surname] AS
                 ClientCon,
                dbo_person.personname,
                dbo_person.surname,
                dbo_jobstatus.description,
                dbo_jobsectordefinedcolumns.priority
         FROM   ((((((((dbo_employmenttypes
                        INNER JOIN dbo_jobs
                                ON dbo_employmenttypes.employmenttypeid =
                                  dbo_jobs.employmenttypeid)
                       INNER JOIN dbo_clients
                               ON dbo_jobs.clientid = dbo_clients.clientid)
                      INNER JOIN dbo_clientcontacts
                              ON dbo_jobs.clientcontactid =
                                 dbo_clientcontacts.clientcontactid)
                     LEFT JOIN dbo_jobsectordefinedcolumns
                            ON dbo_jobs.jobid =
dbo_jobsectordefinedcolumns.jobid)
                    INNER JOIN dbo_person
                            ON dbo_clientcontacts.contactpersonid =
                   dbo_person.personid)
                   LEFT JOIN dbo_jobconsultants
                          ON dbo_jobs.jobid = dbo_jobconsultants.jobid)
                  LEFT JOIN dbo_users
                         ON dbo_jobconsultants.userid = dbo_users.userid)
                 LEFT JOIN dbo_jobstatus
                        ON dbo_jobs.statusid = dbo_jobstatus.jobstatusid)
                LEFT JOIN dbo_locations
                       ON dbo_jobs.locationid = dbo_locations.locationid
         WHERE  ( ( ( dbo_jobs.archived ) = 'N' )
                  AND ( ( dbo_employmenttypes.employmenttypeid ) <> 12 )
                  AND ( ( dbo_jobconsultants.userrelationshipid ) = 9 )
                  AND
         ( ( dbo_jobstatus.description ) <> 'Filled'
           AND ( dbo_jobstatus.description ) <> 'Filled - Ongoing' ) )) AS
        AllJobs
         LEFT JOIN (SELECT dbo_reviewlists.jobid,
                           Count(dbo_reviewlistapplicants.reviewlistid) AS
                           CountOfRevIDs
                    FROM   dbo_reviewlists
                           LEFT JOIN dbo_reviewlistapplicants
                                  ON dbo_reviewlists.reviewlistid =
                                     dbo_reviewlistapplicants.reviewlistid
                    GROUP  BY dbo_reviewlists.jobid) AS RevListCount
                ON AllJobs.jobid = RevListCount.jobid)
        LEFT JOIN (SELECT dbo_applicantactions.jobid,
                          Count(dbo_applicantactions.statusid) AS CVSentCount
                   FROM   dbo_applicantactions
                   WHERE  (( ( dbo_applicantactions.statusid ) = 29 ))
                   GROUP  BY dbo_applicantactions.jobid) AS CVCount
               ON AllJobs.jobid = CVCount.jobid)
ORDER  BY dbo_jobs.jobid DESC

Body:
Holy extraneous parenthesis, Batman! This should work. Looks like you needed the outer table alias of AllJobs applied to the columns of the outer select statement. I also cleaned up all the unnecessary parenthesis.

SELECT
    AllJobs.jobid
    ,AllJobs.jobrefno
    ,AllJobs.createdon
    ,AllJobs.archived
    ,AllJobs.published
    ,AllJobs.jobtitle
    ,AllJobs.statusid
    ,AllJobs.clientid
    ,AllJobs.company
    ,AllJobs.clientcontactid
    ,AllJobs.employmenttypeid
    ,AllJobs.description
    ,AllJobs.description
    ,AllJobs.clientname
    ,AllJobs.natureofcase
    ,AllJobs.timescaletodeadline
    ,AllJobs.notes
    ,AllJobs.status
    ,AllJobs.contactpersonid
    ,AllJobs.vat
    ,AllJobs.postcode
    ,AllJobs.additionalinfo
    ,AllJobs.solicitorref
    ,AllJobs.userid
    ,AllJobs.loginname
    ,AllJobs.positionattributeid
    ,AllJobs.consultancyservice
    ,AllJobs.ClientCon
    ,AllJobs.personname
    ,AllJobs.surname
    ,AllJobs.description
    ,AllJobs.priority
    ,RevListCount.CountOfRevIDs
    ,CVCount.CVSentCount
FROM(
        SELECT
            dbo_jobs.jobid
            ,dbo_jobs.jobrefno
            ,dbo_jobs.createdon
            ,dbo_jobs.archived
            ,dbo_jobs.published
            ,dbo_jobs.jobtitle
            ,dbo_jobs.statusid
            ,dbo_jobs.clientid
            ,dbo_clients.company
            ,dbo_clientcontacts.clientcontactid
            ,dbo_employmenttypes.employmenttypeid
            ,dbo_employmenttypes.description
            ,dbo_locations.description
            ,dbo_jobsectordefinedcolumns.clientname
            ,dbo_jobsectordefinedcolumns.natureofcase
            ,dbo_jobsectordefinedcolumns.timescaletodeadline
            ,dbo_jobs.notes
            ,dbo_jobsectordefinedcolumns.status
            ,dbo_clientcontacts.contactpersonid
            ,dbo_jobsectordefinedcolumns.vat
            ,dbo_jobsectordefinedcolumns.postcode
            ,dbo_jobsectordefinedcolumns.additionalinfo
            ,dbo_jobsectordefinedcolumns.solicitorref
            ,dbo_jobconsultants.userid
            ,dbo_users.loginname
            ,dbo_jobs.positionattributeid
            ,dbo_jobsectordefinedcolumns.consultancyservice
            ,[dbo_person].[personname] & ' ' & [dbo_person].[surname] AS ClientCon
            ,dbo_person.personname
            ,dbo_person.surname
            ,dbo_jobstatus.description
            ,dbo_jobsectordefinedcolumns.priority
        FROM dbo_employmenttypes
        INNER JOIN dbo_jobs ON dbo_employmenttypes.employmenttypeid = dbo_jobs.employmenttypeid
        INNER JOIN dbo_clients ON dbo_jobs.clientid = dbo_clients.clientid
        INNER JOIN dbo_clientcontacts ON dbo_jobs.clientcontactid = dbo_clientcontacts.clientcontactid
        LEFT JOIN dbo_jobsectordefinedcolumns ON dbo_jobs.jobid = dbo_jobsectordefinedcolumns.jobid
        INNER JOIN dbo_person ON dbo_clientcontacts.contactpersonid = dbo_person.personid
        LEFT JOIN dbo_jobconsultants ON dbo_jobs.jobid = dbo_jobconsultants.jobid
        LEFT JOIN dbo_users ON dbo_jobconsultants.userid = dbo_users.userid
        LEFT JOIN dbo_jobstatus ON dbo_jobs.statusid = dbo_jobstatus.jobstatusid
        LEFT JOIN dbo_locations ON dbo_jobs.locationid = dbo_locations.locationid
        WHERE dbo_jobs.archived = 'N'
            AND dbo_employmenttypes.employmenttypeid <> 12
            AND dbo_jobconsultants.userrelationshipid = 9
            AND (
                    dbo_jobstatus.description <> 'Filled'
                    AND dbo_jobstatus.description <> 'Filled - Ongoing'
                )
    )      AS AllJobs
LEFT JOIN(
             SELECT
                 dbo_reviewlists.jobid
                 ,COUNT(dbo_reviewlistapplicants.reviewlistid) AS CountOfRevIDs
             FROM dbo_reviewlists
             LEFT JOIN dbo_reviewlistapplicants ON dbo_reviewlists.reviewlistid = dbo_reviewlistapplicants.reviewlistid
             GROUP BY dbo_reviewlists.jobid
         ) AS RevListCount ON AllJobs.jobid = RevListCount.jobid
LEFT JOIN(
             SELECT
                 dbo_applicantactions.jobid
                 ,COUNT(dbo_applicantactions.statusid) AS CVSentCount
             FROM dbo_applicantactions
             WHERE dbo_applicantactions.statusid = 29
             GROUP BY dbo_applicantactions.jobid
         ) AS CVCount ON AllJobs.jobid = CVCount.jobid
ORDER BY AllJobs.jobid DESC;


问:
Linker flags for iOS with Xcode
Where can I find documentation on the compiler flags and linker flags that we can specify for our iOS projects in Xcode?

The present reason I want to read more on the possible flags in the first place is that the Google Admob SDK says we MUST set the linker -Objc flag, whereas Facebook SDK suggests NOT setting it for smaller binaries. So, I was wondering, can we set Objc for a particular library (google admob in this case) and have it unset for another library (facebook)? I expected to be able to find a man page or some other doc about what the compiler and linker options are in the first place, and then zoom in on Objc. There's tons of documentation and stackoverflow posts etc. on how to set linker flags in Xcode. What's lacking is a listing of possible linker flags we can set, and what they each mean.

Surprisingly, googling around made me quite confused, as there's stuff on clang, llvm, llvm-gcc, etc., and LLVM site lists a number of llvm commands but I don't see -Objc listed in any of the corresponding pages. Apart from the question of whether the compiler and linker are clang or llvm, or whatever they're called, is there a place we could go to in order to read documentation on whatever Xcode is currently using by default for compiling and linking iOS projects? (say, both Xcode 4.6 and Xcode 5.0.2, in case there are different doc sets?) Thanks!

答:
I had this problem when I put a function into my .hpp file.

```<code>void logError(char const* szError)
{
    ...
}
</code>```

I had to add in the inline to make it work.

```<code>inline void logError(char const* szError)
{
    ...
}
</code>```

Even better don't define your functions inside your headers.

Title: Linker flags for iOS with Xcode

Body:
I had this problem when I put a function into my .hpp file.

void logError(char const* szError)
{
    ...
}

I had to add in the inline to make it work.

inline void logError(char const* szError)
{
    ...
}

Even better don't define your functions inside your headers.


问:
Emacs Org-mode: How to include properties in diary anniversaries?
I am trying to have the "Birthday" and "Name" properties of an Org-mode entry added to the agenda automatically:

```<code>* John
  :PROPERTIES:
  :Name: John
  :Birthday: (5 4 1900)
  :END:
</code>```

I found a way to add an entry at the correct anniversary date in the agenda by inserting the following line right after the properties:

```<code>%%(apply 'diary-anniversary (read (org-entry-get nil "Birthday"))) John
</code>```

However, using this code, I still have to enter the name manually. Is there a way to have the value of the "Name" property added to the diary text automatically for all entries?

EDIT 1: the example did not work before, now added parantheses around the value of the birthday property

答: It is probably better to ask this at the Org mailing list, they are very active, and Carsten Dominik (the creator of org-mode) usually answers posts on this list almost immediately (BTW, this is the main list email.</p>

Body:
I am trying to have the "Birthday" and "Name" properties of an Org-mode entry added to the agenda automatically:

* John
  :PROPERTIES:
  :Name: John
  :Birthday: (5 4 1900)
  :END:

I found a way to add an entry at the correct anniversary date in the agenda by inserting the following line right after the properties:

%%(apply 'diary-anniversary (read (org-entry-get nil "Birthday"))) John

However, using this code, I still have to enter the name manually. Is there a way to have the value of the "Name" property added to the diary text automatically for all entries?

EDIT 1: the example did not work before, now added parantheses around the value of the birthday property


问:
How to find the difference/mismatch between two JSON file?
I have two json files, one is expected json and the another one is the result of GET API call. I need to compare and find out the mismatch in the file.

Expected Json:

```<code>{
  "array": [
    1,
    2,
    3
  ],
  "boolean": true,
  "null": null,
  "number": 123,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "Hello World"
}
</code>```

Actual Json response:

```<code>{
  "array": [
    1,
    2,
    3
  ],
  "boolean": true,
  "null": null,
  "number": 456,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "India"
}
</code>```

Actually there are two mismatch: number received is 456 and string is India.

Is there a way to compare and get these two mismatch as results.

This need to be implemented in gatling/scala.

答: json4s has a handy diff function described here: https://github.com/json4s/json4s (search for Merging & Diffing) and API doc here: https://static.javadoc.io/org.json4s/json4s-core_2.9.1/3.0.0/org/json4s/Diff.html</p>

Body:
I have two json files, one is expected json and the another one is the result of GET API call. I need to compare and find out the mismatch in the file.

Expected Json:

{
  "array": [
    1,
    2,
    3
  ],
  "boolean": true,
  "null": null,
  "number": 123,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "Hello World"
}

Actual Json response:

{
  "array": [
    1,
    2,
    3
  ],
  "boolean": true,
  "null": null,
  "number": 456,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "India"
}

Actually there are two mismatch: number received is 456 and string is India.

Is there a way to compare and get these two mismatch as results.

This need to be implemented in gatling/scala.


问:
Codeigniter 3.1.16 routing issues
I'm having some troubles with routing in codeigniter.
My routing file is as below:

```<code>$route['admin/newgallery'] = 'gallery/do_upload';
$route['admin/listgallery'] = 'gallery/list';
$route['admin/create'] = 'posts/create';
$route['admin/listposts'] = 'posts/list';
$route['admin'] = 'admin/index';
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['default_controller'] = 'pages/index';
$route['(:any)'] = 'pages/index/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
</code>```

All routes work just fine except for the first two:

```<code>$route['admin/newgallery'] = 'gallery/do_upload';
$route['admin/listgallery'] = 'gallery/list';
</code>```

When I type mypage/admin/listgallery it calls gallery/list correctly. The problem is when I type the address with the original controller/method (in this case gallery/list) it goes to the list page as well when it should call a 404 error! Every other routing rule I have set does that, except the first two!

答:
Out of the Box, Codeigniter allows you to directly access any Controller/Method from the URL.

It also provides the creation of custom routes so you could have 10 or more urls all pointing at the same controller/method with parameter passing if that was your desire...

So in the case you ONLY want access to any Controller/Method that are defiend in the Routes config.

You need to test if the url is defined in the routes config array.

The main code is something like...

```<code>$this->load->helper('url');
if(!isset($this->router->routes[uri_string()])){
    show_404(); // Or whatever you want ...
}
</code>```

And you would put this in your controller's constructor you want to protect.

Of course you could create a common controller and extend those controllers you want to protect in this manner.

( NOT Recommended ) Or if you want to get really "hacky" you could put it in the system/core/controller constructor and make it system wide. SO Everything needs to be defined in a route.
NOTE: This breaks the 'default_controller'.

Title: Codeigniter 3.1.16 routing issues

Body:
I'm having some troubles with routing in codeigniter.
My routing file is as below:

$route['admin/newgallery'] = 'gallery/do_upload';
$route['admin/listgallery'] = 'gallery/list';
$route['admin/create'] = 'posts/create';
$route['admin/listposts'] = 'posts/list';
$route['admin'] = 'admin/index';
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['default_controller'] = 'pages/index';
$route['(:any)'] = 'pages/index/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

All routes work just fine except for the first two:

$route['admin/newgallery'] = 'gallery/do_upload';
$route['admin/listgallery'] = 'gallery/list';

When I type mypage/admin/listgallery it calls gallery/list correctly. The problem is when I type the address with the original controller/method (in this case gallery/list) it goes to the list page as well when it should call a 404 error! Every other routing rule I have set does that, except the first two!

Body:
Out of the Box, Codeigniter allows you to directly access any Controller/Method from the URL.

It also provides the creation of custom routes so you could have 10 or more urls all pointing at the same controller/method with parameter passing if that was your desire...

So in the case you ONLY want access to any Controller/Method that are defiend in the Routes config.

You need to test if the url is defined in the routes config array.

The main code is something like...

$this->load->helper('url');
if(!isset($this->router->routes[uri_string()])){
    show_404(); // Or whatever you want ...
}

And you would put this in your controller's constructor you want to protect.

Of course you could create a common controller and extend those controllers you want to protect in this manner.

( NOT Recommended ) Or if you want to get really "hacky" you could put it in the system/core/controller constructor and make it system wide. SO Everything needs to be defined in a route.
NOTE: This breaks the 'default_controller'.


问:
How to convert Numpy NaT values to Pandas datetime values
I need to convert numpy.datetime64('NaT') values to Pandas datetime values. I used Gord Thompson's solution below to convert numpy.datetime64 values.

```<code>def dt64_to_datetime(dt64):
   unix_epoch = np.datetime64(0, 's')
   one_second = np.timedelta64(1, 's')
   seconds_since_epoch = (dt64 - unix_epoch) / one_second
   return datetime.utcfromtimestamp(seconds_since_epoch)
</code>```

Example usage:

```<code>for value in df[col].values: ##Convert each np.datetime64 value in DF column to Pandas datetime
    dt = dt64_to_datetime(value)
</code>```

When the function reaches a np.datetime64('NaT') value, the following error is shown: OSError: [Errno 22] Invalid argument.

What can I do to convert np.datetime64('NaT') values to Python datetime values?

EDIT / UPDATE:

I am trying to convert np.datetime64('NaT') values to Python datetime values because research has shown that this can help me upload the values from DataFrame column into MS Access table. How can I do this?

答:
Adding to Alexander's comment, it's best to explicitly handle null values. One way would be to edit your function like so:

```<code>import pandas as pd

def dt64_to_datetime(dt64):
    unix_epoch = np.datetime64(0, 's')
    one_second = np.timedelta64(1, 's')
    if pd.isnull(dt64):
        return pd.NaT
    else:
        seconds_since_epoch = (dt64 - unix_epoch) / one_second
        return datetime.utcfromtimestamp(seconds_since_epoch)
</code>```

On my environment pd.isnull(numpy.datetime64('NaT')) returns True. Also, my environment actually can't replicate your error (it returns nan without explicitly handling nulls). So consider upgrading pandas and / or numpy.

Body:
I need to convert numpy.datetime64('NaT') values to Pandas datetime values. I used Gord Thompson's solution below to convert numpy.datetime64 values.

def dt64_to_datetime(dt64):
   unix_epoch = np.datetime64(0, 's')
   one_second = np.timedelta64(1, 's')
   seconds_since_epoch = (dt64 - unix_epoch) / one_second
   return datetime.utcfromtimestamp(seconds_since_epoch)

Example usage:

for value in df[col].values: ##Convert each np.datetime64 value in DF column to Pandas datetime
    dt = dt64_to_datetime(value)

When the function reaches a np.datetime64('NaT') value, the following error is shown: OSError: [Errno 22] Invalid argument.

What can I do to convert np.datetime64('NaT') values to Python datetime values?

EDIT / UPDATE:

I am trying to convert np.datetime64('NaT') values to Python datetime values because research has shown that this can help me upload the values from DataFrame column into MS Access table. How can I do this?

Body:
Adding to Alexander's comment, it's best to explicitly handle null values. One way would be to edit your function like so:

import pandas as pd

def dt64_to_datetime(dt64):
    unix_epoch = np.datetime64(0, 's')
    one_second = np.timedelta64(1, 's')
    if pd.isnull(dt64):
        return pd.NaT
    else:
        seconds_since_epoch = (dt64 - unix_epoch) / one_second
        return datetime.utcfromtimestamp(seconds_since_epoch)

On my environment pd.isnull(numpy.datetime64('NaT')) returns True. Also, my environment actually can't replicate your error (it returns nan without explicitly handling nulls). So consider upgrading pandas and / or numpy.


答:
You can't compare optional values (other than with ==).

As written, difference.second is of type Int? (an optional Int).

The second property of DateComponents is optional. But since you specifically requested the .second component, it won't be nil in this usage so it is safe to force-unwrap it.

```<code>if difference.second! <= 0 {
</code>```

Title: Swift: Why do I get the error: "Binary operator '<=' cannot be applied to operands of type 'Int?' and 'Int' ", in my function:

Body:
You can't compare optional values (other than with ==).

As written, difference.second is of type Int? (an optional Int).

The second property of DateComponents is optional. But since you specifically requested the .second component, it won't be nil in this usage so it is safe to force-unwrap it.

if difference.second! <= 0 {


问:
Spring Data JPA JPQL list in constructor
In my application, a non-standard situation, I have a layer of entity in mysql, layer of dominain in controllers. My domain model contains a few entities, can this be integrated into one JPQL query?

entity layer:

PersonEntity table

EventEntity table

EventVisitorEntity table

PersonEntity many to many EventEntity

EventVisitorEntity interim table

domain layer:

```<code>class PersonInfo {
Person person;
List<PersonEvent> personEvent
...
}
</code>```

Now I get all Person to take their ids and get the PersonEvent, using this query:

```<code>@Query("SELECT new domain.PersonEvent(ev.personId,ev.eventId,e.name,ev.state)" +
        " FROM EventVisitorEntity AS ev ,EventEntity AS e WHERE e.id = ev.eventId AND ev.personId IN (?1)")
List<PersonEvent> findEventsForPerson(List<Integer> ids);
</code>```

It is possible to write one query to get persons with an personEvents ?
in the constructor which is below:

```<code>public PersonInfo(Person person, List<PersonEvent> personEvents)
</code>```

答:
Hardly doubt it is possible. JPQL subqueries, which might help you outline personEvents, are allowed only in where and having clauses.

Instead, I'd suggest you to just embrace the query as-is and move the logic of gathering to your DAO tier. This link might be helpful: https://dzone.com/articles/add-custom-functionality-to-a-spring-data-reposito. Declare a method List<PersonEvent> findEventsForPerson(List<Integer> ids), implement custom repository for it, doing all nesessary JPQL queries and combinations there. But beware of N+1 issue.

Also it may be convenient to use entity graphs in such custom implementation.

EDIT: After rereading the spec on fresh mind, I realized that I have mistaken saying that subqueries are allowed only in WHERE/HAVING clauses. It says that it may be used there, which doesn't exclude the opposite. Anyway, even if it is possible, such approach (extracting relation via subqueries) would most probably lead to N+1 issues, unless JPA implementors are smart enough to predict that (I wouldn't count on that anyway).

Body:
In my application, a non-standard situation, I have a layer of entity in mysql, layer of dominain in controllers. My domain model contains a few entities, can this be integrated into one JPQL query?

entity layer:

PersonEntity table

EventEntity table

EventVisitorEntity table

PersonEntity many to many EventEntity

EventVisitorEntity interim table

domain layer:

class PersonInfo {
Person person;
List<PersonEvent> personEvent
...
}

Now I get all Person to take their ids and get the PersonEvent, using this query:

@Query("SELECT new domain.PersonEvent(ev.personId,ev.eventId,e.name,ev.state)" +
        " FROM EventVisitorEntity AS ev ,EventEntity AS e WHERE e.id = ev.eventId AND ev.personId IN (?1)")
List<PersonEvent> findEventsForPerson(List<Integer> ids);

It is possible to write one query to get persons with an personEvents ?
in the constructor which is below:

public PersonInfo(Person person, List<PersonEvent> personEvents)


问:
Unable to read REF_CURSOR with StoredProcedureItemReader
I try to call stored proc

```<code>create or replace PROCEDURE "PROC"(cur OUT SYS_REFCURSOR)
</code>```

with this bean.

```<code>@Bean
    StoredProcedureItemReader<?> itemReader() {
        StoredProcedureItemReader<?> storedProcedureItemReader = new StoredProcedureItemReader<>();
        storedProcedureItemReader.setDataSource(dataSource);
        storedProcedureItemReader.setProcedureName("PROC");
        storedProcedureItemReader.setRefCursorPosition(1);
        storedProcedureItemReader.setRowMapper(new ColumnMapRowMapper());
        storedProcedureItemReader.open(new ExecutionContext());
        return storedProcedureItemReader;
    }
</code>```

But i get

```<code>org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:134)
    ... 54 more
Caused by: java.sql.SQLException: Invalid column index
    at oracle.jdbc.driver.OracleCallableStatement.registerOutParameterInternal(OracleCallableStatement.java:125)
    at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:304)
    at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:393)
    at oracle.jdbc.driver.OracleCallableStatementWrapper.registerOutParameter(OracleCallableStatementWrapper.java:1569)
    at org.springframework.batch.item.database.StoredProcedureItemReader.openCursor(StoredProcedureItemReader.java:202)
    ... 56 more
</code>```

How can I call the PROC with just one out cursor and get iterate the result?

答:
Thats how I use here, we must set cursor´s position otherwise spring will try to do a getObject( 0 )!</p>

```<code>@Bean
    public ItemReader<FailuredProcess> getFailuredProcessReader() throws BatchOMSException {
        StoredProcedureItemReader<FailuredProcess> reader;

        try {
            reader = new StoredProcedureItemReader<FailuredProcess>();

            reader.setDataSource(dataSource);
            reader.setProcedureName(queryHelper.getQuery("query.oms.listFailuredProcessJobs"));
            reader.setRowMapper(new AlarmRowMapper());
            reader.setPreparedStatementSetter(new PreparedStatementSetterAdapter());
            reader.setVerifyCursorPosition(false);
            reader.setParameters(new SqlParameter[] { new SqlParameter("cur", OracleTypes.CURSOR) });
            reader.setRefCursorPosition(NumberUtils.INTEGER_ONE);
            reader.afterPropertiesSet();

            return reader;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new BatchOMSException(e);
        }
</code>```

Body:
I try to call stored proc

create or replace PROCEDURE "PROC"(cur OUT SYS_REFCURSOR)

with this bean.

@Bean
    StoredProcedureItemReader<?> itemReader() {
        StoredProcedureItemReader<?> storedProcedureItemReader = new StoredProcedureItemReader<>();
        storedProcedureItemReader.setDataSource(dataSource);
        storedProcedureItemReader.setProcedureName("PROC");
        storedProcedureItemReader.setRefCursorPosition(1);
        storedProcedureItemReader.setRowMapper(new ColumnMapRowMapper());
        storedProcedureItemReader.open(new ExecutionContext());
        return storedProcedureItemReader;
    }

But i get

org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:134)
    ... 54 more
Caused by: java.sql.SQLException: Invalid column index
    at oracle.jdbc.driver.OracleCallableStatement.registerOutParameterInternal(OracleCallableStatement.java:125)
    at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:304)
    at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:393)
    at oracle.jdbc.driver.OracleCallableStatementWrapper.registerOutParameter(OracleCallableStatementWrapper.java:1569)
    at org.springframework.batch.item.database.StoredProcedureItemReader.openCursor(StoredProcedureItemReader.java:202)
    ... 56 more

How can I call the PROC with just one out cursor and get iterate the result?

Body:
Thats how I use here, we must set cursor´s position otherwise spring will try to do a getObject( 0 )!

@Bean
    public ItemReader<FailuredProcess> getFailuredProcessReader() throws BatchOMSException {
        StoredProcedureItemReader<FailuredProcess> reader;

        try {
            reader = new StoredProcedureItemReader<FailuredProcess>();

            reader.setDataSource(dataSource);
            reader.setProcedureName(queryHelper.getQuery("query.oms.listFailuredProcessJobs"));
            reader.setRowMapper(new AlarmRowMapper());
            reader.setPreparedStatementSetter(new PreparedStatementSetterAdapter());
            reader.setVerifyCursorPosition(false);
            reader.setParameters(new SqlParameter[] { new SqlParameter("cur", OracleTypes.CURSOR) });
            reader.setRefCursorPosition(NumberUtils.INTEGER_ONE);
            reader.afterPropertiesSet();

            return reader;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new BatchOMSException(e);
        }