问:
swiftui : Custom Button doesnt work in the ListView
I created a custom button with Y and N options. (I could not use the Toggle button as I needed no options being selected at the beginning.

If the button is added in a Vstack it is working perfectly fine. Pressed option is being highlighted, the other option is dimmed.

But when it is added in a list view, when any button is clicked, it looks like whole cell is clicked and always the second option is being selected.
How can I fix the issue?

    import SwiftUI

```<code>struct ContentView: View {

    var body: some View {

        VStack{
            MultiSelectionButtonView()

            Form{
                MultiSelectionButtonView()

                MultiSelectionButtonGroup()
            }
        }
    }
}

struct MultiSelectionButtonView: View {

    var body: some View {
        HStack{
            Text("Question")
            Spacer()
            MultiSelectionButtonGroup()

        }
    }
}

struct MultiSelectionButtonGroup: View {
    @State private var selectedOption : Int = 0

    var body: some View {

        HStack (spacing: 0){
            MultiSelectionButton(tag: 1, text: "Y", selectedOption: $selectedOption)
            MultiSelectionButton(tag: 2, text: "N", selectedOption: $selectedOption)
        }

    }
}

struct MultiSelectionButton: View {

    @State var tag : Int
    @State var text : String
    @Binding var selectedOption : Int

    var shapeSize : CGFloat = CGFloat(35)
    var strokeWidth : CGFloat = CGFloat(0.5)
    var cornerRadius : CGFloat = CGFloat(2)

    var colorSelected : Color = Color.green
    var colorNoSelected : Color = Color.gray.opacity(0.5)
    var colorStroke : Color = Color.gray

    var body: some View {

        Button(action: {
            self.selectedOption = self.tag
        }) {
            ZStack{
                Group {
                    RoundedRectangle(cornerRadius: self.cornerRadius, style: .continuous)
                        //Circle()
                        .fill((self.selectedOption == self.tag) ? colorSelected : colorNoSelected )

                    RoundedRectangle(cornerRadius: self.cornerRadius, style: .continuous)
                        //Circle()
                        .stroke(colorStroke, lineWidth: strokeWidth)
                }
                .frame(width: shapeSize, height: shapeSize)

                Text(text)
                    .font(.subheadline)
                    .fontWeight(.light)
                    .foregroundColor(Color.white)
            }
        }
    }
}
</code>```

答:
check this answer here:

SwiftUI - Multiple Buttons in a List row

and try the borderlessbuttonstyle

Body:
I created a custom button with Y and N options. (I could not use the Toggle button as I needed no options being selected at the beginning.

If the button is added in a Vstack it is working perfectly fine. Pressed option is being highlighted, the other option is dimmed.

But when it is added in a list view, when any button is clicked, it looks like whole cell is clicked and always the second option is being selected.
How can I fix the issue?

    import SwiftUI

struct ContentView: View {

    var body: some View {

        VStack{
            MultiSelectionButtonView()

            Form{
                MultiSelectionButtonView()

                MultiSelectionButtonGroup()
            }
        }
    }
}

struct MultiSelectionButtonView: View {

    var body: some View {
        HStack{
            Text("Question")
            Spacer()
            MultiSelectionButtonGroup()

        }
    }
}

struct MultiSelectionButtonGroup: View {
    @State private var selectedOption : Int = 0

    var body: some View {

        HStack (spacing: 0){
            MultiSelectionButton(tag: 1, text: "Y", selectedOption: $selectedOption)
            MultiSelectionButton(tag: 2, text: "N", selectedOption: $selectedOption)
        }

    }
}

struct MultiSelectionButton: View {

    @State var tag : Int
    @State var text : String
    @Binding var selectedOption : Int

    var shapeSize : CGFloat = CGFloat(35)
    var strokeWidth : CGFloat = CGFloat(0.5)
    var cornerRadius : CGFloat = CGFloat(2)

    var colorSelected : Color = Color.green
    var colorNoSelected : Color = Color.gray.opacity(0.5)
    var colorStroke : Color = Color.gray

    var body: some View {

        Button(action: {
            self.selectedOption = self.tag
        }) {
            ZStack{
                Group {
                    RoundedRectangle(cornerRadius: self.cornerRadius, style: .continuous)
                        //Circle()
                        .fill((self.selectedOption == self.tag) ? colorSelected : colorNoSelected )

                    RoundedRectangle(cornerRadius: self.cornerRadius, style: .continuous)
                        //Circle()
                        .stroke(colorStroke, lineWidth: strokeWidth)
                }
                .frame(width: shapeSize, height: shapeSize)

                Text(text)
                    .font(.subheadline)
                    .fontWeight(.light)
                    .foregroundColor(Color.white)
            }
        }
    }
}


来源: stackexchange

问:
AJAX pattern in Rails for submitting small chunks of data
I have a web page with lots of small images on it. In a typical scenario  user clicks on image and expects it to change with a new image.

Requirements:

When user clicks on image, it should be immediately known to a controller in an Ajax way.

Some strings should be passed to a controller when user clicks on image.

Controller does its job and returns another image (which replaces old one).

Along with image controller returns a couple of extra strings (such as completion status).

Web page updates old image with new one and also updates other parts with these new strings.

Number of images on a page varies but potentially it can be a couple of dozens.

Question: What Ajax technique should be used here? I'm quite new to Ajax and don't feel solid with patterns. Should it be Json or something else?

Any code example would be very very welcome and helpful.

Thank you.

答:
As far as I known, the only browser-safe way to change an image is by assigning a new URL to it's src attribute. If you return an image to a request that pass some parameters, it might prevent client-side cashing of the images. For these reasons, I would treat separately the transfer of textual data and images.
The completion status can always be return as the HTTP status text but if more information is needed from the server, you can always return it in JSON or XML, the simplest being JSON.
The responsiveness could be improved by preloading images on the mouseover event.</p>

OwnerDisplayName: Valentin Vasiliev

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Maurice Perry


问:
Get current working directory from Vte (GTK Terminal Widget) in Python
Hey,
How can I get the current working directory of a VTE widget in Python?
Thanks.</p>

答:
This is a kludge, but the best way I can think of would be:</p>

```<code>import vte
import os
v = vte.Terminal()
vPid = v.fork_command()
# make a system call to pwdx to get working director
sIn, sOut = os.popen2("pwdx " + vPid)
workingDir = sOut.read()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is a kludge, but the best way I can think of would be:

import vte
import os
v = vte.Terminal()
vPid = v.fork_command()
# make a system call to pwdx to get working director
sIn, sOut = os.popen2("pwdx " + vPid)
workingDir = sOut.read()


问:
Error "No tests found" when running Android instrumentation tests
I am a beginner to testing. I have created a simple test case for login activity in android studio. But I got an error and I could not solve it. Here is my test code. Help will be really appreciated.

```<code>package com.example.hassidiczaddic.testinglist;

import android.app.Application;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.ActivityInstrumentationTestCase2;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.LargeTest;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class ApplicationTest {

    public static final String STRING_TO_BE_TYPED = "Wolfmatrix";

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void LoginActivity() {
        onView(withId(R.id.etFName))
                .perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard());
        onView(withId(R.id.etLName))
                .perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard());
        onView(withId(R.id.btnSubmit))
            .perform(click());
        onView(withId(R.id.tvView))
            .check(matches(withText(STRING_TO_BE_TYPED)));
    }

}
</code>```

This is my error:

```<code>Running tests

$ adb shell am instrument -w -r   -e debug false -e class
com.example.hassidiczaddic.testinglist.ApplicationTest
com.example.hassidiczaddic.testinglist.
test/android.test.InstrumentationTestRunner
Client not ready yet..Test running started
junit.framework.AssertionFailedError: No tests found in
com.example.hassidiczaddic.testinglist.ApplicationTest
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
at
android.test.InstrumentationTestRunner.onStart
(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run
(Instrumentation.java:1619)
Tests ran to completion.
</code>```

Here is my gradle file:

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

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.hassidiczaddic.testinglist"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'
        }
    }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:23.0.1'
        // App dependencies
        compile 'com.android.support:support-annotations:23.0.1'
        compile 'com.google.guava:guava:18.0'
        androidTestCompile 'com.android.support:support-annotations:23.0.1'
        androidTestCompile 'com.android.support.test:runner:0.4.1'
        androidTestCompile 'com.android.support.test:rules:0.4.1'
        androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
    }
}
</code>```

答:
check build.gradle

replace testInstrumentationRunner "androidx.test.runner.AndroidJUnit4"

```<code>android {
    defaultConfig {
        testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
    }
}
</code>```

Look for app/src/androidTest/AndroidManifest.xml

change android:name to androidx.multidex.MultiDexApplication

```<code><application
        android:allowBackup="true"
        android:label="Components Tests App"
        android:supportsRtl="true"
        android:name="android.support.multidex.MultiDexApplication">
</code>```

To

```<code><application
            android:allowBackup="true"
            android:label="Components Tests App"
            android:supportsRtl="true"
            android:name="androidx.multidex.MultiDexApplication">
</code>```

More suggestions:
No tests found when running instrumented tests with AndroidX

Body:
I am a beginner to testing. I have created a simple test case for login activity in android studio. But I got an error and I could not solve it. Here is my test code. Help will be really appreciated.

package com.example.hassidiczaddic.testinglist;

import android.app.Application;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.ActivityInstrumentationTestCase2;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.LargeTest;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class ApplicationTest {

    public static final String STRING_TO_BE_TYPED = "Wolfmatrix";

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void LoginActivity() {
        onView(withId(R.id.etFName))
                .perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard());
        onView(withId(R.id.etLName))
                .perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard());
        onView(withId(R.id.btnSubmit))
            .perform(click());
        onView(withId(R.id.tvView))
            .check(matches(withText(STRING_TO_BE_TYPED)));
    }

}

This is my error:

Running tests

$ adb shell am instrument -w -r   -e debug false -e class
com.example.hassidiczaddic.testinglist.ApplicationTest
com.example.hassidiczaddic.testinglist.
test/android.test.InstrumentationTestRunner
Client not ready yet..Test running started
junit.framework.AssertionFailedError: No tests found in
com.example.hassidiczaddic.testinglist.ApplicationTest
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
at
android.test.InstrumentationTestRunner.onStart
(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run
(Instrumentation.java:1619)
Tests ran to completion.

Here is my gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.hassidiczaddic.testinglist"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'
        }
    }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:23.0.1'
        // App dependencies
        compile 'com.android.support:support-annotations:23.0.1'
        compile 'com.google.guava:guava:18.0'
        androidTestCompile 'com.android.support:support-annotations:23.0.1'
        androidTestCompile 'com.android.support.test:runner:0.4.1'
        androidTestCompile 'com.android.support.test:rules:0.4.1'
        androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
    }
}

Body:
check build.gradle

replace testInstrumentationRunner "androidx.test.runner.AndroidJUnit4"

android {
    defaultConfig {
        testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
    }
}

Look for app/src/androidTest/AndroidManifest.xml

change android:name to androidx.multidex.MultiDexApplication

<application
        android:allowBackup="true"
        android:label="Components Tests App"
        android:supportsRtl="true"
        android:name="android.support.multidex.MultiDexApplication">

To

<application
            android:allowBackup="true"
            android:label="Components Tests App"
            android:supportsRtl="true"
            android:name="androidx.multidex.MultiDexApplication">

More suggestions:
No tests found when running instrumented tests with AndroidX

ContentLicense: CC BY-SA 4.0


问:
How to Get Unique Record for each category in django
I have a table called product_type & Product.

```<code>class Product_type(models.Model):
    product_type_id = models.AutoField(primary_key=True)
    product_type_name = models.CharField(max_length=255, null = False, unique=True)
    product_type_title = models.CharField(max_length=255, null = True)
    product_type_description = models.TextField(null = False)
    product_type_slug = models.SlugField(unique=True, blank=True, null=True)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='category')
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    product_name = models.CharField(max_length=255, null = False, unique=True)
    product_slug = models.SlugField(unique=True, blank=True, null=True)
    product_title = models.CharField(max_length=255, null = True)
    product_info = models.TextField(null = False)
    product_description = models.CharField(max_length = 255)
    product_price = models.CharField(max_length = 255)
    brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True)
    product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
    product_status = models.CharField(max_length = 100, default = "publish")
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Brand(models.Model):
    brand_id = models.AutoField(primary_key=True)
    brand_name = models.CharField(max_length=255, null = False, unique=True)
    brand_slug = models.SlugField(unique=True, blank=True, null=True)
    brand_title = models.CharField(max_length = 255)
    brand_logo = models.ImageField(upload_to = 'brand/logo/%Y/%m/')
    brand_logo_alt_text = models.CharField(max_length=255, null = False)
    brand_info = models.TextField(null = False)
    brand_description = models.CharField(max_length = 255)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
    country = models.ForeignKey(Country, default = '1', on_delete=models.SET_DEFAULT, null=True)
    brand_status = models.CharField(max_length = 100, default = "publish")
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)
</code>```

in product table I've linked brand table as brand and product_type table as product_type, so suppose I've multiple records for each brand in product table. So I only want 1 record for each brand which has a lowest product_price and that record must match with product_type.

for example:
I want only those product which contains product_type = 'accounting'.
so here is a demo data:
product(model data)

product_id:1,product_name:abc, product_type: accounting, brand:aaa, price:$100

product_id:2,product_name:xyz, product_type: accounting, brand:aaa, price:$50

product_id:3,product_name:bdf, product_type: accounting, brand:bbb, price:$150

product_id:4,product_name:ghf, product_type: other, brand:ccc, price:$150

so my query result will be product_id 2,3 because 1,2 have same brand but 2 has the lowest price & 2,3 both have product_type = accounting.

I tried too much but nothing works.

I want your help!

答:
First, use models.DecimalField for product prices. Do not use models.CharField for numbers. Change the product_price field to product_price = models.DecimalField(max_digits=6, decimal_places=2) (Stores $0 to $9999.99).

Then, you can try the following:

from django.db.models import F, Min

Product.objects.filter(
    product_type=my_product_type
).annotate(
    min_brand_price=Min('brand__product_type__product_price')
).filter(
    product_price=F('min_brand_price')
)
```

Other related questions on StackOverflow:

How to get only latest record on filter of foreign key django

Django model get unique foreign key rows based on other column max value

Body:
I have a table called product_type & Product.

class Product_type(models.Model):
    product_type_id = models.AutoField(primary_key=True)
    product_type_name = models.CharField(max_length=255, null = False, unique=True)
    product_type_title = models.CharField(max_length=255, null = True)
    product_type_description = models.TextField(null = False)
    product_type_slug = models.SlugField(unique=True, blank=True, null=True)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='category')
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    product_name = models.CharField(max_length=255, null = False, unique=True)
    product_slug = models.SlugField(unique=True, blank=True, null=True)
    product_title = models.CharField(max_length=255, null = True)
    product_info = models.TextField(null = False)
    product_description = models.CharField(max_length = 255)
    product_price = models.CharField(max_length = 255)
    brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True)
    product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
    product_status = models.CharField(max_length = 100, default = "publish")
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Brand(models.Model):
    brand_id = models.AutoField(primary_key=True)
    brand_name = models.CharField(max_length=255, null = False, unique=True)
    brand_slug = models.SlugField(unique=True, blank=True, null=True)
    brand_title = models.CharField(max_length = 255)
    brand_logo = models.ImageField(upload_to = 'brand/logo/%Y/%m/')
    brand_logo_alt_text = models.CharField(max_length=255, null = False)
    brand_info = models.TextField(null = False)
    brand_description = models.CharField(max_length = 255)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
    country = models.ForeignKey(Country, default = '1', on_delete=models.SET_DEFAULT, null=True)
    brand_status = models.CharField(max_length = 100, default = "publish")
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

in product table I've linked brand table as brand and product_type table as product_type, so suppose I've multiple records for each brand in product table. So I only want 1 record for each brand which has a lowest product_price and that record must match with product_type.

for example:
I want only those product which contains product_type = 'accounting'.
so here is a demo data:
product(model data)

product_id:1,product_name:abc, product_type: accounting, brand:aaa, price:$100

product_id:2,product_name:xyz, product_type: accounting, brand:aaa, price:$50

product_id:3,product_name:bdf, product_type: accounting, brand:bbb, price:$150

product_id:4,product_name:ghf, product_type: other, brand:ccc, price:$150

so my query result will be product_id 2,3 because 1,2 have same brand but 2 has the lowest price & 2,3 both have product_type = accounting.

I tried too much but nothing works.

I want your help!

Body:
First, use models.DecimalField for product prices. Do not use models.CharField for numbers. Change the product_price field to product_price = models.DecimalField(max_digits=6, decimal_places=2) (Stores $0 to $9999.99).

Then, you can try the following:

from django.db.models import F, Min

Product.objects.filter(
    product_type=my_product_type
).annotate(
    min_brand_price=Min('brand__product_type__product_price')
).filter(
    product_price=F('min_brand_price')
)

Other related questions on StackOverflow:

How to get only latest record on filter of foreign key django

Django model get unique foreign key rows based on other column max value


问:
Database design for Likes and Total Likes
I have created a basic like system for my system. The likes are stored in the below format

```<code>user_id, post_id, liked_at
</code>```

I want to keep the total likes in the database (as it will help in getting total post likes when retrieving post lists)

```<code>post_id, total_likes
</code>```

I'm currently having 2 options for making these function.

Creating a view to generate post-wise total likes

Trigger to update total likes

what is the best way to go?

答:
Personally when it is possible I prefer not to add redundant information. So I would prefere a view. If you add 'total_like' to the post table and keep it updated via trigger nothing (other than another trigger) would prevent someone to update directly that field and misalign the data).
Only if it gets to slow I would consider the idea of a trigger.
Hope it helps</p>

Body:
I have created a basic like system for my system. The likes are stored in the below format

user_id, post_id, liked_at

I want to keep the total likes in the database (as it will help in getting total post likes when retrieving post lists)

post_id, total_likes

I'm currently having 2 options for making these function.

Creating a view to generate post-wise total likes

Trigger to update total likes

what is the best way to go?


问:
react native modal: Button on press calls a prop function and resets the state?
in parent screen:

```<code><CoolName add={function} />
</code>```

in CoolName modal:

```<code>state={ a: 'some string a', b: 'some string b'}

<Button title="Add" onPress={this.props.add.bind(this, this.state)}/>
</code>```

how can I do this and reset the state (this.setState({a: '', b: ''})) at the same time inside the onPress prop??

答:
Define a callback in the onPress prop. Whitespace is only for readability.</p>

```<code><Button title="Add" onPress={() => {
                                    this.props.add.bind(this, this.state);
                                    this.setState({a: '', b: ''});
                                   }
                            }
/>
</code>```

Body:
in parent screen:

<CoolName add={function} />

in CoolName modal:

state={ a: 'some string a', b: 'some string b'}

<Button title="Add" onPress={this.props.add.bind(this, this.state)}/>

how can I do this and reset the state (this.setState({a: '', b: ''})) at the same time inside the onPress prop??

Body:
Define a callback in the onPress prop. Whitespace is only for readability.

<Button title="Add" onPress={() => {
                                    this.props.add.bind(this, this.state);
                                    this.setState({a: '', b: ''});
                                   }
                            }
/>


问:
Sitecore OMS - best practice for content hierarchy
I am inheriting an existing Sitecore implementation that has large folders of content all using the same template. Some of the folders contain literally hundreds of articles. Different folders should be of interest to different type of Personas. I would like to not have to go article by article setting the Personas and Profile properties for each individual page. Ideally I would like to enter the properties only once for an entire folder of articles. What is the best practice in a case like this?

Should I be creating a different template for each type of article? Or is there a way to inherit these properties from a parent item in the content tree?

Thanks

EDIT

I had a conversation online with John West, CTO of Sitecore USA. Here are his suggestions to approach this problem. I thought of sharing them here since some other people might be interested in solving a similar problem.

I don't know of any existing solution to inherit these values, but there are probably other approaches (maybe similar to language fallback).

If the number of templates is relatively small, I would probably go with the templating approach - turn the existing template into a base template for templates for all of the existing items, and update insert options accordingly. It wouldn't hurt to put these things in folders, but they won't inherit these values that way (you could implement something that would inherit them as mentioned above). One of the benefits here is that you could update those details in standard values, which would apply to all items based on those templates.

Another way would be to implement something like layout and security presets, but for these other values.

Whatever you do, make sure that when the user creates a new item, they can eaily apply these properties, or they get applied automatically.

Another way would be to write a script that updates the existing items, but that doesn't help with future items (unless you do something like a save handler to apply the same values automatically on creation). Maybe copy the values from that parent folder.

I liked the idea of adding a boolean field to the existing template that controls whether the item is supposed to copy the Profile values from its direct parent and then implement a save handler to do the copy when that field is set to true. So I asked John if there was documentation on how to build such handlers. Here is his kind reply:

This explains some of the ways you can tap in to item creation/change to set your values:

http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/11/Intercepting-Item-Updates-with-Sitecore.aspx

I assume you could use an item:saved event handler. I avoid item:created handlers because if my logic goes wrong, I want it to run again on the next save event. In your case, if these fields are empty, you probably want to set the value.

You can use the factory to pass parameters to your event handler to avoid hard-coding. For example, you might pass the database name master (abort the handler if the saved item is in a different database) and a list of the affected template IDs. Then you can more easily add templates to the list in the future.

http://www.sitecore.net/en/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2011/02/The-Sitecore-ASPNET-CMS-Configuration-Factory.aspx

Here's some information about events:

http://sdn.sitecore.net/Articles/API/Using%20Events.aspx

This includes an example that uses a save handler:

http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/06/Sitecore-Shared-Source-NewsMover-Categorizes-News-by-Date.aspx

答:
I think there may be a better way of doing this, using the startTracking pipeline. Check out the Sitecore.Analytics.Pipelines.StartTracking.ProcessItem processor. This is where Sitecore obtains the context item, and logs its profile values to the AnalyticsTracker using a supporting class, TrackingFieldProcessor. You could duplicate this class, and depending on the template of the context item (or a flag on the template), log its parent's profile data as well using the TrackingFieldProcessor.Process(Item) method.

EDIT

This is a little new to me too as far as the Sitecore API goes, but here are more specific steps you should try. You should use IlSpy to look at referenced classes in Sitecore.Analytics.dll.

Create a subclass of Sitecore.Analytics.Pipelines.StartTracking.StartTrackingProcessor

Implement the Process method, using Sitecore.Analytics.Pipelines.StartTracking.ProcessItem as a reference. If Context.Item meets your criteria (e.g. Template GUID), then use the code below to track analytics based on its parent.

Add your class to Sitecore.Analytics.config as the last item in the startTracking pipeline.

TrackingFieldProcessor trackingFieldProcessor = new TrackingFieldProcessor();
trackingFieldProcessor.Process(item.Parent);

In case you aren't familiar with using pipelines:

http://adeneys.wordpress.com/2008/08/27/creating-and-running-custom-pipelines-in-sitecore/

(Though this isn't a custom pipeline, you're just tapping into an existing one.)


问:
Is there any way to dump boolean object in Cloud BigTable?
I have certain usecase where api service are retrieving BigTable rows using rowKey. The issue I'm going through is api service is trying to retrieve some columns with boolean value and doing boolean comparison in front-end side. Since BigTable doesn't support that datatype. The front-end service comparison part is not working as expected. I'm using the below code to store boolean value in BigTable.

```<code>                    Boolean value = Boolean.parseBoolean(newImageMap.get(Key).toString());
                    SetCell setCell = SetCell.newBuilder()
                            .setFamilyName(Utility.COLUMN_FAMILY)
                            .setColumnQualifier(Utility.str_to_bb(Key,StandardCharsets.UTF_8))
                            .setTimestampMicros(yearAgoMillis)
                            .setValue(ByteString.copyFrom(Bytes.toBytes(value)))
                        //  .setValue(Utility.str_to_bb(String.valueOf(value),StandardCharsets.UTF_8))
                            .build();
</code>```

But the boolean value is stored as string in BigTable. You can see the stored value in below snapshot.
Let me know in case there is a way-out to handle this type of use-cases.
boolean-value-ss

答:
Dumping boolean object in BigTable is not possible as BigTable doesn't support boolean datatype. Rather I will suggest you to make the changes in your driver code and type-case the datatype to suitable form and send it to front-end side, which would be more suitable. For that you have to pre-identify the boolean datatype from source end and stored it as configuration which will be an input to  driver code.
Let me know in case this solution works.</p>

Body:
I have certain usecase where api service are retrieving BigTable rows using rowKey. The issue I'm going through is api service is trying to retrieve some columns with boolean value and doing boolean comparison in front-end side. Since BigTable doesn't support that datatype. The front-end service comparison part is not working as expected. I'm using the below code to store boolean value in BigTable.

                    Boolean value = Boolean.parseBoolean(newImageMap.get(Key).toString());
                    SetCell setCell = SetCell.newBuilder()
                            .setFamilyName(Utility.COLUMN_FAMILY)
                            .setColumnQualifier(Utility.str_to_bb(Key,StandardCharsets.UTF_8))
                            .setTimestampMicros(yearAgoMillis)
                            .setValue(ByteString.copyFrom(Bytes.toBytes(value)))
                        //  .setValue(Utility.str_to_bb(String.valueOf(value),StandardCharsets.UTF_8))
                            .build();

But the boolean value is stored as string in BigTable. You can see the stored value in below snapshot.
Let me know in case there is a way-out to handle this type of use-cases.
boolean-value-ss


问:
Get parent name
With what method or variable can I find out the name of the parent object in this example? That is, during the event of hovering the mouse over the first button, get the name $GetParentName = "Button01", second $GetParentName = "Button02", third $GetParentName = "Button03". $GetParentName is [string].

If instead of the variable $GetParentName to apply $This, then the variable $This allows you to get the values of the object, but does not get the name of the object. But how to get the name of the object? Thanks

Edited: without using $This.Name.

```<code>$A = @{

    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }

    Button01 = [System.Windows.Forms.Button] @{ Top = 0 }
    Button02 = [System.Windows.Forms.Button] @{ Top = 30 }
    Button03 = [System.Windows.Forms.Button] @{ Top = 60 }
}

$Script = { Write-host $GetParentName }

1..3 | % {

    $A["Button0$_"].Add_MouseEnter($Script)

    $A.Main.Controls.Add($A["Button0$_"])
}

[void]$A.Main.ShowDialog()
</code>```

答:
As Theo points out in his answer, you need to name your button objects by assigning to their .Name property.

To avoid naming your buttons twice - once as a property name in your hashtable, and again via the .Name property - you can create the buttons as an array, which simplifies the solution overall:

```<code>$A = @{

    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }

    # Create an *array* of buttons
    Buttons = [System.Windows.Forms.Button] @{ Top = 0; Name = 'Button1' },
              [System.Windows.Forms.Button] @{ Top = 30; Name = 'Button2' },
              [System.Windows.Forms.Button] @{ Top = 60; Name = 'Button3' }
}

# Print the name of the button being moused over.
$Script = { $this.Name | Out-Host }

# Attach the event-handler script block to each button.
$A.Buttons | % {

    $_.Add_MouseEnter($Script)

}

# Add the buttons to the form.
$A.Main.Controls.AddRange($A.Buttons)

$null = $A.Main.ShowDialog()
</code>```

If you want to avoid assigning to the .Name property, you can use the following approach:

Use PowerShell's ETS (Extended Type System) to add the key of the hashtable entry in which each button is stored as a custom property (a NoteProperty instance member), using Add-Member, which the event-handler script can query:

```<code>Add-Type -AssemblyName System.Windows.Forms

$A = @{

    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }

    Button01 = [System.Windows.Forms.Button] @{ Top = 0 }
    Button02 = [System.Windows.Forms.Button] @{ Top = 30 }
    Button03 = [System.Windows.Forms.Button] @{ Top = 60 }
}

$Script = {
    # Access the custom .CustomParent property added to each button instance below.
    Write-Host $this.CustomParent
}

1..3 | % {

    $key = "Button0$_"
    $btn = $A[$key]
    # Add a .CustomParent NoteProperty member to the button object
    # storing the key of the hashtable entry in which that button is stored.
    $btn | Add-Member -NotePropertyMembers @{ CustomParent = $key }

    $btn.Add_MouseEnter($Script)

    $A.Main.Controls.Add($btn)
}

[void]$A.Main.ShowDialog()
</code>```

As for why PowerShell doesn't - and shouldn't - provide an automatic (built in) variable such as $GetParentName to support this scenario:

There are two unrelated worlds involved in this scenario:

PowerShell variables

The .NET types from the System.Windows.Forms namespace (WinForms)

WinForms is language-agnostic - any .NET language can use it; all it knows about is how instance of its types are nested at runtime and how to raise appropriate .NET events, typically in response to user events.

The source object of an event, as reported by WinForms, is surfaced as $this in a PowerShell script block acting as a .NET event delegate invoked directly by WinForms.

WinForms (rightfully) has no knowledge of what data structure or variable on the PowerShell side the event-originating object is stored in.

Even on the PowerShell side this is completely at your discretion - you could have chosen individual variables, for instance, or an array, as shown above, so there is no general pattern here that an automatic variable could support.

In the case at hand, PowerShell itself has no way of knowing that your $Script block happens to be indirectly associated with a button instance incidentally stored in a hashtable entry.

Title: Get parent name

Body:
With what method or variable can I find out the name of the parent object in this example? That is, during the event of hovering the mouse over the first button, get the name $GetParentName = "Button01", second $GetParentName = "Button02", third $GetParentName = "Button03". $GetParentName is [string].

If instead of the variable $GetParentName to apply $This, then the variable $This allows you to get the values of the object, but does not get the name of the object. But how to get the name of the object? Thanks

Edited: without using $This.Name.

$A = @{

    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }

    Button01 = [System.Windows.Forms.Button] @{ Top = 0 }
    Button02 = [System.Windows.Forms.Button] @{ Top = 30 }
    Button03 = [System.Windows.Forms.Button] @{ Top = 60 }
}

$Script = { Write-host $GetParentName }

1..3 | % {

    $A["Button0$_"].Add_MouseEnter($Script)

    $A.Main.Controls.Add($A["Button0$_"])
}

[void]$A.Main.ShowDialog()

Body:
As Theo points out in his answer, you need to name your button objects by assigning to their .Name property.

To avoid naming your buttons twice - once as a property name in your hashtable, and again via the .Name property - you can create the buttons as an array, which simplifies the solution overall:

$A = @{

    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }

    # Create an *array* of buttons
    Buttons = [System.Windows.Forms.Button] @{ Top = 0; Name = 'Button1' },
              [System.Windows.Forms.Button] @{ Top = 30; Name = 'Button2' },
              [System.Windows.Forms.Button] @{ Top = 60; Name = 'Button3' }
}

# Print the name of the button being moused over.
$Script = { $this.Name | Out-Host }

# Attach the event-handler script block to each button.
$A.Buttons | % {

    $_.Add_MouseEnter($Script)

}

# Add the buttons to the form.
$A.Main.Controls.AddRange($A.Buttons)

$null = $A.Main.ShowDialog()

If you want to avoid assigning to the .Name property, you can use the following approach:

Use PowerShell's ETS (Extended Type System) to add the key of the hashtable entry in which each button is stored as a custom property (a NoteProperty instance member), using Add-Member, which the event-handler script can query:

Add-Type -AssemblyName System.Windows.Forms

$A = @{

    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }

    Button01 = [System.Windows.Forms.Button] @{ Top = 0 }
    Button02 = [System.Windows.Forms.Button] @{ Top = 30 }
    Button03 = [System.Windows.Forms.Button] @{ Top = 60 }
}

$Script = {
    # Access the custom .CustomParent property added to each button instance below.
    Write-Host $this.CustomParent
}

1..3 | % {

    $key = "Button0$_"
    $btn = $A[$key]
    # Add a .CustomParent NoteProperty member to the button object
    # storing the key of the hashtable entry in which that button is stored.
    $btn | Add-Member -NotePropertyMembers @{ CustomParent = $key }

    $btn.Add_MouseEnter($Script)

    $A.Main.Controls.Add($btn)
}

[void]$A.Main.ShowDialog()

As for why PowerShell doesn't - and shouldn't - provide an automatic (built in) variable such as $GetParentName to support this scenario:

There are two unrelated worlds involved in this scenario:

PowerShell variables

The .NET types from the System.Windows.Forms namespace (WinForms)

WinForms is language-agnostic - any .NET language can use it; all it knows about is how instance of its types are nested at runtime and how to raise appropriate .NET events, typically in response to user events.

The source object of an event, as reported by WinForms, is surfaced as $this in a PowerShell script block acting as a .NET event delegate invoked directly by WinForms.

WinForms (rightfully) has no knowledge of what data structure or variable on the PowerShell side the event-originating object is stored in.

Even on the PowerShell side this is completely at your discretion - you could have chosen individual variables, for instance, or an array, as shown above, so there is no general pattern here that an automatic variable could support.

In the case at hand, PowerShell itself has no way of knowing that your $Script block happens to be indirectly associated with a button instance incidentally stored in a hashtable entry.


问:
How to get selected item group name in "loudev" multi-select
For Ex:

If select 'Yoda' I want to get that group name 'Friends' in the loudev afterSelect method.

答:
I got a solution. The above ref image is lou-dev multi-select rendered elements.

So first we find selected item element with that name.

Next we get that near by li with .ms-optgroup-label class name

The code ref:

```<code>afterSelect: (selectedVals) => { //selectedVals=[Yoda]
  $(`span:contains('${selectedVals[0]}')`).first().closest('li').siblings('li.ms-optgroup-label').text()
}
</code>```

Body:
I got a solution. The above ref image is lou-dev multi-select rendered elements.

So first we find selected item element with that name.

Next we get that near by li with .ms-optgroup-label class name

The code ref:

afterSelect: (selectedVals) => { //selectedVals=[Yoda]
  $(`span:contains('${selectedVals[0]}')`).first().closest('li').siblings('li.ms-optgroup-label').text()
}


问:
How to insert PAGE_NUMBER and PAGE_COUNT in footer
I'm looking for exemple of paragraph and element paragraph in footer.
I'd tried but i only can insert text in footer:

```<code>$requests = array (new \Google_Service_Docs_Request(array(
    'insertText' => array(
        'location' => array(
            'segmentId' => $segmentId,
                'index' => 0
            ),
            "text" => 'My Text'
        )
)),
</code>```

I tried to implement new footers like this :

```<code>$footers = array(
        new \Google_Service_Docs_Footer(array(
            'footerId' => $segmentId,
            'content' => [
                'paragraph' => [
                    'element' => [
                        'textRun' => [
                            'content' => 'My Text - '
                        ]
                    ]
                ]
            ]
        )),
        new \Google_Service_Docs_Footer(array(
            'footerId' => $segmentId,
            'content' => [
                  'paragraph' => [
                      'element' => [
                          'AutoText' => [
                              'type' => 'PAGE_NUMBER'
                          ]
                      ]
                  ]
            ]
        )),
        new \Google_Service_Docs_Footer(array(
            'footerId' => $segmentId,
            'content' => [
                'paragraph' => [
                    'element' => [
                        'AutoText' => [
                            'type' => 'PAGE_COUNT'
                        ]
                    ]
                ]
            ]
        ))
    );
    $document->setFooters($footers);
</code>```

Can we manage paragraph of Footer ?

答:
Issue in progress https://issuetracker.google.com/issues/149275293
i keep you in touch when i have a feedback</p>

Body:
I'm looking for exemple of paragraph and element paragraph in footer.
I'd tried but i only can insert text in footer:

$requests = array (new \Google_Service_Docs_Request(array(
    'insertText' => array(
        'location' => array(
            'segmentId' => $segmentId,
                'index' => 0
            ),
            "text" => 'My Text'
        )
)),

I tried to implement new footers like this :

$footers = array(
        new \Google_Service_Docs_Footer(array(
            'footerId' => $segmentId,
            'content' => [
                'paragraph' => [
                    'element' => [
                        'textRun' => [
                            'content' => 'My Text - '
                        ]
                    ]
                ]
            ]
        )),
        new \Google_Service_Docs_Footer(array(
            'footerId' => $segmentId,
            'content' => [
                  'paragraph' => [
                      'element' => [
                          'AutoText' => [
                              'type' => 'PAGE_NUMBER'
                          ]
                      ]
                  ]
            ]
        )),
        new \Google_Service_Docs_Footer(array(
            'footerId' => $segmentId,
            'content' => [
                'paragraph' => [
                    'element' => [
                        'AutoText' => [
                            'type' => 'PAGE_COUNT'
                        ]
                    ]
                ]
            ]
        ))
    );
    $document->setFooters($footers);

Can we manage paragraph of Footer ?


问:
Where is the crash-free sessions metric in firebase?
Since Fabric will be deprecated soon, I've migrated my project from Fabric to Firebase. In Fabric, Crashlytics reported crash-free users and sessions metrics, but in firebase I can only see the crash-free users metric.
Where can I see the crash-free sessions?

答: Crashlytics announced on it's Twitter account that it'll be available slightly after Fabric shuts down. You can see it here : https://twitter.com/crashlytics/status/1222959191121432577?s=21</p>


问:
How to get current user data from firebase realtime database in React Native
I'm trying to get current signed user's image and name from the firebase realtime database in which his data was stored when he signup. I want to put these two items in the drawer header. enter image description hereYou can see the attached screenshots.

Here is the current user

here is the data of the current user. I want to get that data on the basis of current user signed in

答:
you can get the currentUser.uid if you are loggedin with firebase.

try my code,

```<code>firebase
      .database()
      .ref('Users/' + firebase.auth().currentUser.uid)
      .once('value')
      .then(snapshot => {
        console.log(snapshot.val()) <--will print the user data
      });
</code>```

hope this works for you.

Body:
you can get the currentUser.uid if you are loggedin with firebase.

try my code,

firebase
      .database()
      .ref('Users/' + firebase.auth().currentUser.uid)
      .once('value')
      .then(snapshot => {
        console.log(snapshot.val()) <--will print the user data
      });

hope this works for you.


问:
Reverse Bits JavaScript
The problem is standard but the solution in JavaScript takes a lot more effort to code.

I got the solution but my answer is coming half of what is desired.

Problem Description

Reverse the bits of a 32-bit unsigned integer A.

Problem Constraints

0 <= A <= 2^32

Input Format

The first and only argument of input contains an integer A.

Output Format

Return a single unsigned integer denoting minimum xor value.

Example Input

```<code>Input 1:
0
Input 2:
3
</code>```

Example Output

```<code>Output 1:
0
Output 2:
3221225472
</code>```

My solution

```<code>
function modulo(a, b) {
        return a - Math.floor(a/b)*b;
}
function ToUint32(x) {
    return modulo(parseInt(x), Math.pow(2, 32));
}
function revereBits(A){
    A = A.toString(2);
    while (A.length < 31){
        A = "0"+A;
    }
    var reverse = 0;
    var NO_OF_BITS = A.length;
    for(var i = NO_OF_BITS; i >= 1; i--){
        var temp = (parseInt(A, 2) & (1 << i - 1));
        if(temp){
            reverse |= 1 << (NO_OF_BITS - i);

        }
    }
    if( reverse << 1 < 0 ) reverse = ToUint32(reverse << 1);
    return reverse;

}
</code>```

Now, in the line

```<code> if( reverse << 1 < 0 ) reverse = ToUint32(reverse << 1);
</code>```

You see that I  have to double the answer. I cannot, however, get the part of why is this required.

I took the approach from https://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/

Had to make few adjustments to it. For example, run the loop from 31 to 1 rather than 0 to 31. The latter gives negative values in first left shift operation for i = 0 itself.

Can someone please help in fixing this solution and point to the problem in this?

UPDATE - Problem is related to Bit manipulation. So guys, please don't answer or comment for anything consisting of in-built string functions of Javascript. Cheers!

答:
You should be able to do it using just bitwise operators, and a typed array to solve the sign issue:

Update
Changing slightly approach of the rev function after @bryc comment. Since having multiple function for "history" purpose makes the answer difficult to read, I'm putting first the latest code.
However, I'm keeping the comments about the different steps – the rest can be found in the edit history.

```<code>function rev(x) {
    x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1);
    x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2);
    x = ((x >> 4) & 0x0F0F0F0F) | ((x & 0x0F0F0F0F) << 4);
    x = ((x >> 8) & 0x00FF00FF) | ((x & 0x00FF00FF) << 8);
    x = (x >>> 16) | (x << 16);

    return x >>> 0;
}
</code>```

This is the same code you would write in other languages as well to reverse bits, the only difference here is the addition of the typed array.

As @harold pointed out in the comment, the zero-fill right shift returns an unsigned (it's the only bitwise operator to do so) therefore we can omit the typed array and just add >>> 0 before the return.

In fact, doing >>> 0 is commonly used to simulate the ToUint32 in JS polyfilll; e.g.:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

```<code>    // 2. Let lenValue be the result of calling the Get internal method
    //    of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;
</code>```

Title: Reverse Bits JavaScript

Body:
The problem is standard but the solution in JavaScript takes a lot more effort to code.

I got the solution but my answer is coming half of what is desired.

Problem Description

Reverse the bits of a 32-bit unsigned integer A.

Problem Constraints

0 <= A <= 2^32

Input Format

The first and only argument of input contains an integer A.

Output Format

Return a single unsigned integer denoting minimum xor value.

Example Input

Input 1:
0
Input 2:
3

Example Output

Output 1:
0
Output 2:
3221225472

My solution

function modulo(a, b) {
        return a - Math.floor(a/b)*b;
}
function ToUint32(x) {
    return modulo(parseInt(x), Math.pow(2, 32));
}
function revereBits(A){
    A = A.toString(2);
    while (A.length < 31){
        A = "0"+A;
    }
    var reverse = 0;
    var NO_OF_BITS = A.length;
    for(var i = NO_OF_BITS; i >= 1; i--){
        var temp = (parseInt(A, 2) & (1 << i - 1));
        if(temp){
            reverse |= 1 << (NO_OF_BITS - i);

        }
    }
    if( reverse << 1 < 0 ) reverse = ToUint32(reverse << 1);
    return reverse;

}

Now, in the line

 if( reverse << 1 < 0 ) reverse = ToUint32(reverse << 1);

You see that I  have to double the answer. I cannot, however, get the part of why is this required.

I took the approach from https://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/

Had to make few adjustments to it. For example, run the loop from 31 to 1 rather than 0 to 31. The latter gives negative values in first left shift operation for i = 0 itself.

Can someone please help in fixing this solution and point to the problem in this?

UPDATE - Problem is related to Bit manipulation. So guys, please don't answer or comment for anything consisting of in-built string functions of Javascript. Cheers!

Body:
You should be able to do it using just bitwise operators, and a typed array to solve the sign issue:

Update
Changing slightly approach of the rev function after @bryc comment. Since having multiple function for "history" purpose makes the answer difficult to read, I'm putting first the latest code.
However, I'm keeping the comments about the different steps – the rest can be found in the edit history.

function rev(x) {
    x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1);
    x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2);
    x = ((x >> 4) & 0x0F0F0F0F) | ((x & 0x0F0F0F0F) << 4);
    x = ((x >> 8) & 0x00FF00FF) | ((x & 0x00FF00FF) << 8);
    x = (x >>> 16) | (x << 16);

    return x >>> 0;
}

This is the same code you would write in other languages as well to reverse bits, the only difference here is the addition of the typed array.

As @harold pointed out in the comment, the zero-fill right shift returns an unsigned (it's the only bitwise operator to do so) therefore we can omit the typed array and just add >>> 0 before the return.

In fact, doing >>> 0 is commonly used to simulate the ToUint32 in JS polyfilll; e.g.:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

    // 2. Let lenValue be the result of calling the Get internal method
    //    of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;


问:
In Jenkins-Pipeline how do I use sshPut to copy contents of folder, not folder itself?
On my Jenkins server, I have a simple test pipeline to check into copying build data to a remote server.
I'm using the SSH Pipeline Steps plugin.

My code is:

```<code>            stage('Remote SSH') {
              steps {
                sshRemove remote: remote, path: "/mnt/test"
                sshCommand remote: remote, command: "mkdir /mnt/test"

                writeFile file: './tst/abc.sh', text: 'ls -lrt'
                sshPut remote: remote, from: './tst/', into: '/mnt/test/.'
            }
</code>```

The result is that in /mnt/test I have the created "tst" folder and it's contents.
What I wanted was just the contents of this tst folder to be transfered to the target.

How should I be formatting the sshPut step?

答:
There is an issue about this very use case on Jenkins'Jira https://issues.jenkins-ci.org/browse/JENKINS-58778

I would expect the following to work but it apparently does not:

```<code>remote.fileTransfer = 'SCP'
sshPut remote: remote, from: './tst/*', into: '/mnt/test/'
</code>```

Another way could be to do one sshCommand more after sshPut to 'mv' the files as you please

Usually I Go to https://<myJenkins>/pipeline-syntax and use the step builder. A shame it's not working for sshPut

Body:
On my Jenkins server, I have a simple test pipeline to check into copying build data to a remote server.
I'm using the SSH Pipeline Steps plugin.

My code is:

            stage('Remote SSH') {
              steps {
                sshRemove remote: remote, path: "/mnt/test"
                sshCommand remote: remote, command: "mkdir /mnt/test"

                writeFile file: './tst/abc.sh', text: 'ls -lrt'
                sshPut remote: remote, from: './tst/', into: '/mnt/test/.'
            }

The result is that in /mnt/test I have the created "tst" folder and it's contents.
What I wanted was just the contents of this tst folder to be transfered to the target.

How should I be formatting the sshPut step?

Body:
There is an issue about this very use case on Jenkins'Jira https://issues.jenkins-ci.org/browse/JENKINS-58778

I would expect the following to work but it apparently does not:

remote.fileTransfer = 'SCP'
sshPut remote: remote, from: './tst/*', into: '/mnt/test/'

Another way could be to do one sshCommand more after sshPut to 'mv' the files as you please

Usually I Go to https://<myJenkins>/pipeline-syntax and use the step builder. A shame it's not working for sshPut


问:
We have a dataframe of n column. and want to count frequency of a particular number from each column
dataframe is like

```<code>1  2  4  ....n

0  2  0  ....n

1  0  4  ....n

0  0  4  ....n
</code>```

now i want to count 1 from column 1, count 2 from column 2,count 4 from column 3 and so on.

but i also want to count few values by adding columns like

```<code>1+2  ,        1+4     ,    2+4   ,   1+2+4

0+2  ,        0+0     ,    2+0   ,   0+2+0

1+0  ,         1+4    ,     0+4  ,    1+0+4

0+0  ,         0+4    ,     0+4  ,    0+0+4
</code>```

Count 3      count 5   count 6     count 7  from above columns respectively.

Sotr these values/number in list, array or dataframe like

```<code>Values/Number -- Frequency

1 , 2

2 , 2

3 , 1

4 , 3

5 , 2

6 , 1

7 , 1

</code>```

答:
I believe you need:

```<code>from itertools import chain, combinations
#https://stackoverflow.com/a/5898031
comb = chain(*map(lambda x: combinations(df.columns, x), range(2, len(df.columns)+1)))

cols = df.columns
for c in comb:
    df[f'{"+".join(c)}'] = df.loc[:, c].sum(axis=1)
print (df)
   a  b  c  a+b  a+c  b+c  a+b+c
0  1  2  4    3    5    6      7
1  0  2  0    2    0    2      2
2  1  0  4    1    5    4      5
3  0  0  4    0    4    4      4
</code>```

Then is possible count each column, values in DataFrame are counts and index values are counted numbers:

```<code>df1 = df.apply(pd.value_counts)
print (df1)
     a    b    c  a+b  a+c  b+c  a+b+c
0  2.0  2.0  1.0  1.0  1.0  NaN    NaN
1  2.0  NaN  NaN  1.0  NaN  NaN    NaN
2  NaN  2.0  NaN  1.0  NaN  1.0    1.0
3  NaN  NaN  NaN  1.0  NaN  NaN    NaN
4  NaN  NaN  3.0  NaN  1.0  2.0    1.0
5  NaN  NaN  NaN  NaN  2.0  NaN    1.0
6  NaN  NaN  NaN  NaN  NaN  1.0    NaN
7  NaN  NaN  NaN  NaN  NaN  NaN    1.0
</code>```

And if want maximum counts per rows use:

```<code>df2 = df1.max(axis=1).astype(int).rename_axis('Num').reset_index(name='count')
print (df2)
   Num  count
0    0      2
1    1      2
2    2      2
3    3      1
4    4      3
5    5      2
6    6      1
7    7      1
</code>```

Body:
dataframe is like

1  2  4  ....n

0  2  0  ....n

1  0  4  ....n

0  0  4  ....n

now i want to count 1 from column 1, count 2 from column 2,count 4 from column 3 and so on.

but i also want to count few values by adding columns like

1+2  ,        1+4     ,    2+4   ,   1+2+4

0+2  ,        0+0     ,    2+0   ,   0+2+0

1+0  ,         1+4    ,     0+4  ,    1+0+4

0+0  ,         0+4    ,     0+4  ,    0+0+4

Count 3      count 5   count 6     count 7  from above columns respectively.

Sotr these values/number in list, array or dataframe like

Values/Number -- Frequency

1 , 2

2 , 2

3 , 1

4 , 3

5 , 2

6 , 1

7 , 1

Body:
I believe you need:

from itertools import chain, combinations
#https://stackoverflow.com/a/5898031
comb = chain(*map(lambda x: combinations(df.columns, x), range(2, len(df.columns)+1)))

cols = df.columns
for c in comb:
    df[f'{"+".join(c)}'] = df.loc[:, c].sum(axis=1)
print (df)
   a  b  c  a+b  a+c  b+c  a+b+c
0  1  2  4    3    5    6      7
1  0  2  0    2    0    2      2
2  1  0  4    1    5    4      5
3  0  0  4    0    4    4      4

Then is possible count each column, values in DataFrame are counts and index values are counted numbers:

df1 = df.apply(pd.value_counts)
print (df1)
     a    b    c  a+b  a+c  b+c  a+b+c
0  2.0  2.0  1.0  1.0  1.0  NaN    NaN
1  2.0  NaN  NaN  1.0  NaN  NaN    NaN
2  NaN  2.0  NaN  1.0  NaN  1.0    1.0
3  NaN  NaN  NaN  1.0  NaN  NaN    NaN
4  NaN  NaN  3.0  NaN  1.0  2.0    1.0
5  NaN  NaN  NaN  NaN  2.0  NaN    1.0
6  NaN  NaN  NaN  NaN  NaN  1.0    NaN
7  NaN  NaN  NaN  NaN  NaN  NaN    1.0

And if want maximum counts per rows use:

df2 = df1.max(axis=1).astype(int).rename_axis('Num').reset_index(name='count')
print (df2)
   Num  count
0    0      2
1    1      2
2    2      2
3    3      1
4    4      3
5    5      2
6    6      1
7    7      1


问:
How to split path and file names from multiple items from a list
This is a list below

```<code>list = ['C:/Users/user/Desktop/1.docx', 'C:/Users/user/Desktop/2.docx',
'C:/Users/user/Desktop/3.docx']
</code>```

I want to split path and file names from the list like this:

```<code>pathlist = ['C:/Users/user/Desktop/'], and filelist = ['1.docx', '2.docx', '3.docx']
</code>```

Any help and suggestions will be appreciated

答:
You can rsplit your list by the delimiter "/", and then append the parts to your path and file lists:

```<code>pathlist = []
filelist = []

for item in list:
     pathlist.append(item.rsplit("/",1)[0])
     filelist.append(item.rsplit("/",1)[1])
</code>```

Body:
This is a list below

list = ['C:/Users/user/Desktop/1.docx', 'C:/Users/user/Desktop/2.docx',
'C:/Users/user/Desktop/3.docx']

I want to split path and file names from the list like this:

pathlist = ['C:/Users/user/Desktop/'], and filelist = ['1.docx', '2.docx', '3.docx']

Any help and suggestions will be appreciated

Body:
You can rsplit your list by the delimiter "/", and then append the parts to your path and file lists:

pathlist = []
filelist = []

for item in list:
     pathlist.append(item.rsplit("/",1)[0])
     filelist.append(item.rsplit("/",1)[1])


问:
Authenticate a user by role
I have a user with ROLE_ADMIN and I want to connect him as "ROLE_USER" when calling http://localhost/login but connect him as "ROLE_ADMIN" when calling http://localhost/login?role=admin.
Is it possible to do it in Symfony ?</p>

答:
You can just check if the "role" GET parameter is set and defined as "admin" and then write your code.

If there is a role inheritance and that your admin has ROLE_USER and ROLE_ADMIN, just define custom actions if you detect that it's an admin:

```<code>        if ($this->isGranted('ROLE_ADMIN')) {
            //adminCode
        } else {
           //userCode
        }
</code>```

Title: Authenticate a user by role

Body:
You can just check if the "role" GET parameter is set and defined as "admin" and then write your code.

If there is a role inheritance and that your admin has ROLE_USER and ROLE_ADMIN, just define custom actions if you detect that it's an admin:

        if ($this->isGranted('ROLE_ADMIN')) {
            //adminCode
        } else {
           //userCode
        }


问:
What is the point of calling initComponents() through class constructor in netbeans, though it can be called through main methods too?

Difference between calling initComponents() through UserMode Constructor and calling initComponents() through the main method.

答:
As comment says, being a private method forbis its call from external, including the class containing the main(...) method of the Java program.

Furthermore, the main(...) method in Java programs are static, resulting that they can call only other static methods (or the methods of the global, or locally created objects). Doing something like a

```<code>public static void main(String[] args) {
  ...
  UserMode um = new UserMode();
  um.initComponents();
  ...
}
</code>```

would work if initComponents() would not be private, but it would be still a bad practice: the constructor of UserMode should actually initialize the class; doing it in two steps needs some stronger reason.

Body:
As comment says, being a private method forbis its call from external, including the class containing the main(...) method of the Java program.

Furthermore, the main(...) method in Java programs are static, resulting that they can call only other static methods (or the methods of the global, or locally created objects). Doing something like a

public static void main(String[] args) {
  ...
  UserMode um = new UserMode();
  um.initComponents();
  ...
}

would work if initComponents() would not be private, but it would be still a bad practice: the constructor of UserMode should actually initialize the class; doing it in two steps needs some stronger reason.


问:
Why the extra text in my XSLT output?
Below is an example of the XML and XSLT:

XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <count>5</count>
  <idx>10</idx>
  <cds>
    <cd>
      <title>Empire Burlesque</title>
      <artist>Bob Dylan</artist>
      <country>USA</country>
      <company>Columbia</company>
      <price>10.90</price>
      <year>1985</year>
    </cd>
    <cd>
      <title>Hide your heart</title>
      <artist>Bonnie Tyler</artist>
      <country>UK</country>
      <company>CBS Records</company>
      <price>9.90</price>
      <year>1988</year>
    </cd>
  </cds>
</catalog>
</code>```

XSLT:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="html" omit-xml-declaration="yes" standalone="yes" />
    <xsl:template match="/catalog/cds">
      <html>
      <body>
      <h2>My CD Collection</h2>
        <table border="1">
          <tr bgcolor="#9acd32">
            <th style="text-align:left">Title</th>
            <th style="text-align:left">Artist</th>
          </tr>
          <xsl:for-each select="cd">
          <tr>
            <td><xsl:value-of select="title"/></td>
            <td><xsl:value-of select="artist"/></td>
          </tr>
          </xsl:for-each>
        </table>
      </body>
      </html>
    </xsl:template>
</xsl:stylesheet>
</code>```

Question: Why is it that when transforming the given XML document the content of the elements count and idx is being printed out before the table all the time?

答:
Another option is to override the built-in template rule in your stylesheet with a version that does nothing:</p>

```<code><xsl:template match="text()|@*" mode="#all"/>
</code>```

Title: Why the extra text in my XSLT output?

Body:
Below is an example of the XML and XSLT:

XML:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <count>5</count>
  <idx>10</idx>
  <cds>
    <cd>
      <title>Empire Burlesque</title>
      <artist>Bob Dylan</artist>
      <country>USA</country>
      <company>Columbia</company>
      <price>10.90</price>
      <year>1985</year>
    </cd>
    <cd>
      <title>Hide your heart</title>
      <artist>Bonnie Tyler</artist>
      <country>UK</country>
      <company>CBS Records</company>
      <price>9.90</price>
      <year>1988</year>
    </cd>
  </cds>
</catalog>

XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="html" omit-xml-declaration="yes" standalone="yes" />
    <xsl:template match="/catalog/cds">

My CD Collection

            Title
            Artist

          <xsl:for-each select="cd">

            <xsl:value-of select="title"/>
            <xsl:value-of select="artist"/>

          </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

Question: Why is it that when transforming the given XML document the content of the elements count and idx is being printed out before the table all the time?

Body:
Another option is to override the built-in template rule in your stylesheet with a version that does nothing:

<xsl:template match="text()|@*" mode="#all"/>


问:
Dark Theme through out the app in flutter
I am making an app where i want to have dark theme for app on switch.I have written the code and is working fine but just for one page.When i go back and open that page again it shows "BAD STATE ERROR". when i searched on stackoverflow, many of them suggested to use shared preferences.But i am unable to implement it.

CODE

```<code>    class Settings extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    // TODO: implement build
    return StreamBuilder(

      stream: bloc.darkThemeEnabled,
      initialData: false,
      builder: (context,snapshot) => MaterialApp(
        debugShowCheckedModeBanner: false ,
        theme: snapshot.data?ThemeData.dark():ThemeData.light(),
        home: HomePage(snapshot.data),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
 final bool darkThemeEnabled;

  HomePage(this.darkThemeEnabled);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(

        title: Text('Settings'),
      ),
      body: ListView(
        children: <Widget>[
          ListTile(
              title: Text("Dark Theme",style:
              TextStyle(
                  fontSize: 20.0
              ),),
              trailing: Switch(
                value: darkThemeEnabled,
                onChanged:bloc.changeTheme,
              )
          )],
      ),
    );
  }
}

class Bloc{
  final _themecontroller = StreamController<bool>();
  get changeTheme => _themecontroller.sink.add;
  get darkThemeEnabled => _themecontroller.stream;

}

final bloc = Bloc();
</code>```

答:
Adding shared prefs:

add shared_preferences: ^0.5.4+8 to you pubspec.yaml

import 'package:shared_preferences/shared_preferences.dart';
in your class

to store call

```<code>final prefs = await SharedPreferences.getInstance();
prefs.setString(key, value);
</code>```

to read call

```<code>final prefs = await SharedPreferences.getInstance();
var value = prefs.getString(key);
</code>```

to remove call

```<code>final prefs = await SharedPreferences.getInstance();
prefs.remove(key);
</code>```

key is the key of the value and value is the value you want to store
In your instance you can use key == theme , value == dark/light

Body:
I am making an app where i want to have dark theme for app on switch.I have written the code and is working fine but just for one page.When i go back and open that page again it shows "BAD STATE ERROR". when i searched on stackoverflow, many of them suggested to use shared preferences.But i am unable to implement it.

CODE

    class Settings extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    // TODO: implement build
    return StreamBuilder(

      stream: bloc.darkThemeEnabled,
      initialData: false,
      builder: (context,snapshot) => MaterialApp(
        debugShowCheckedModeBanner: false ,
        theme: snapshot.data?ThemeData.dark():ThemeData.light(),
        home: HomePage(snapshot.data),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
 final bool darkThemeEnabled;

  HomePage(this.darkThemeEnabled);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(

        title: Text('Settings'),
      ),
      body: ListView(
        children: <Widget>[
          ListTile(
              title: Text("Dark Theme",style:
              TextStyle(
                  fontSize: 20.0
              ),),
              trailing: Switch(
                value: darkThemeEnabled,
                onChanged:bloc.changeTheme,
              )
          )],
      ),
    );
  }
}

class Bloc{
  final _themecontroller = StreamController<bool>();
  get changeTheme => _themecontroller.sink.add;
  get darkThemeEnabled => _themecontroller.stream;

}

final bloc = Bloc();

Body:
Adding shared prefs:

add shared_preferences: ^0.5.4+8 to you pubspec.yaml

import 'package:shared_preferences/shared_preferences.dart';
in your class

to store call

final prefs = await SharedPreferences.getInstance();
prefs.setString(key, value);

to read call

final prefs = await SharedPreferences.getInstance();
var value = prefs.getString(key);

to remove call

final prefs = await SharedPreferences.getInstance();
prefs.remove(key);

key is the key of the value and value is the value you want to store
In your instance you can use key == theme , value == dark/light


问:
How to convert one byte (8 bit) to signed integer in JavaScript?
I need to convert one byte into java script signed integer. I have checked this link which converts 2 bytes , but how could I downgrade and convert only one byte? </p>

<p>for example 0x0A would be 10, how about 0xD4?  </p>

答:
This solution converts using 2's complement for negative numbers, which is the standard way negative numbers are encoded.

```<code>function uncomplement(val, bitwidth) {
    var isnegative = val & (1 << (bitwidth - 1));
    var boundary = (1 << bitwidth);
    var minval = -boundary;
    var mask = boundary - 1;
    return isnegative ? minval + (val & mask) : val;
}
</code>```

uncomplement(0xFF, 8) returns -1

uncomplement(0x80, 8) returns -128

uncomplement(0x7F, 8) returns 127

Body:
I need to convert one byte into java script signed integer. I have checked this link which converts 2 bytes , but how could I downgrade and convert only one byte?

for example 0x0A would be 10, how about 0xD4?

Body:
This solution converts using 2's complement for negative numbers, which is the standard way negative numbers are encoded.

function uncomplement(val, bitwidth) {
    var isnegative = val & (1 << (bitwidth - 1));
    var boundary = (1 << bitwidth);
    var minval = -boundary;
    var mask = boundary - 1;
    return isnegative ? minval + (val & mask) : val;
}

uncomplement(0xFF, 8) returns -1

uncomplement(0x80, 8) returns -128

uncomplement(0x7F, 8) returns 127


问:
Oracle SQL - creating "unstored" procedure
I have this SQL query

```<code>SELECT ACCBAL_DATE, ACCBAL_AMOUNT
FROM ACCOUNT_BALANCES t
WHERE ACC_KEY = '964570223'
AND ACCBAL_KEY = '16'
ORDER BY ACCBAL_DATE DESC
FETCH FIRST 1 ROWS ONLY;
</code>```

It returns one row but I need to use this query for many ACC_KEYS (about 600).

So first way to do that is to run this query about 600x with different ACC_KEY parameter.

The second one is creating a procedure I think.

Procedure which will use variable acc_key and move it to WHERE statement.
Issue is that I can't create procedure stored on server because of permissions.

Is there some way to solve it without storing procedure on server?

EDIT: I know the IN clause but that is not what I need. I need something which will run the query about 600x, each execution with another ACC_KEY in WHERE clause and the output should be 600 rows.

答:
Step-1 : CREATE TABLE WITH 1 COLUMN  ACC_KEY STORES ALL LIST OF ACC_KEY.

Step-2 : Code Run.

```<code>SELECT T.ACCBAL_DATE, T.ACCBAL_AMOUNT
FROM ACCOUNT_BALANCES t
WHERE EXISTS(SELECT A.ACC_KEY FROM <TABLENAME> A WHERE A.ACC_KEY=T.ACC_KEY)
AND T.ACCBAL_KEY = '16'
ORDER BY T.ACCBAL_DATE DESC
FETCH FIRST 1 ROWS ONLY;
</code>```

Body:
I have this SQL query

SELECT ACCBAL_DATE, ACCBAL_AMOUNT
FROM ACCOUNT_BALANCES t
WHERE ACC_KEY = '964570223'
AND ACCBAL_KEY = '16'
ORDER BY ACCBAL_DATE DESC
FETCH FIRST 1 ROWS ONLY;

It returns one row but I need to use this query for many ACC_KEYS (about 600).

So first way to do that is to run this query about 600x with different ACC_KEY parameter.

The second one is creating a procedure I think.

Procedure which will use variable acc_key and move it to WHERE statement.
Issue is that I can't create procedure stored on server because of permissions.

Is there some way to solve it without storing procedure on server?

EDIT: I know the IN clause but that is not what I need. I need something which will run the query about 600x, each execution with another ACC_KEY in WHERE clause and the output should be 600 rows.

Body:
Step-1 : CREATE TABLE WITH 1 COLUMN  ACC_KEY STORES ALL LIST OF ACC_KEY.

Step-2 : Code Run.

SELECT T.ACCBAL_DATE, T.ACCBAL_AMOUNT
FROM ACCOUNT_BALANCES t
WHERE EXISTS(SELECT A.ACC_KEY FROM <TABLENAME> A WHERE A.ACC_KEY=T.ACC_KEY)
AND T.ACCBAL_KEY = '16'
ORDER BY T.ACCBAL_DATE DESC
FETCH FIRST 1 ROWS ONLY;


问:
can't start activity
I write some class (icalevent, calendermanager and icalexception) and create demo (demo is activity).  I want to test to my iCal and write this. I can't start activity and I don't understand why.</p>

```<code>this.startActivity(intent());

public Intent getIntent(){
    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setType("vnd.android.cursor.item/event");
    intent.putExtra("title", theEvent.getName());  here is problem
    intent.putExtra("description", theEvent.getSummary()); and here

    intent.putExtra("beginTime", theEvent.getStart().getTime());and here
    intent.putExtra("endTime", theEvent.getEnd().getTime()); and here
    return intent;
}
public Intent intent(){
    CalendarManager calandermanager = new CalendarManager();
    return calandermanager.getIntent();
}
</code>```

答:
The putExtra wants a different data type for that field.  Try possibly convert the time to a string?

Look here for more information on it.
http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String,android.os.Bundle)

Title: can't start activity

Body:
I write some class (icalevent, calendermanager and icalexception) and create demo (demo is activity).  I want to test to my iCal and write this. I can't start activity and I don't understand why.

this.startActivity(intent());

public Intent getIntent(){
    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setType("vnd.android.cursor.item/event");
    intent.putExtra("title", theEvent.getName());  here is problem
    intent.putExtra("description", theEvent.getSummary()); and here

    intent.putExtra("beginTime", theEvent.getStart().getTime());and here
    intent.putExtra("endTime", theEvent.getEnd().getTime()); and here
    return intent;
}
public Intent intent(){
    CalendarManager calandermanager = new CalendarManager();
    return calandermanager.getIntent();
}


问:
ReactJs : What is the proper way of accessing the state data in the root component where the link between React and Redux has been implemented?
DISCLAIMER: This error has been mentioned on stackoverflow before but my case is different.

I have had a problem with the user login which I have explained in this stackOverFlow question. I invite you to go and quickly take a look.

So as I mentioned in that question in my root file I have this:

App.js

```<code>class App extends Component {
  render() {
    const authLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
        <Route
          path="/home"
          name="Home"
          render={props => <DefaultLayout {...props} />}
        />
      </Switch>
    );

    const guestLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/register"
          name="Register Page"
          render={props => <Register {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
      </Switch>
    );

    const currentState = store.getState();
    console.log(
      "currentState.auth.isAuthenticated: ",
      currentState.auth.isAuthenticated
    );
    return (
      <Provider store={store}>
        <HashRouter>
          <React.Suspense fallback={loading()}>
            {console.log(currentState.auth.isAuthenticated)}
            {/* TODO: Not sure if this always works. If after the user logsin he gets a blank page and he has to reload to be redirected to home then
            this way of routing may need to modified */}
            {currentState.auth.isAuthenticated ? authLinks : guestLinks}
          </React.Suspense>
        </HashRouter>
      </Provider>
    );
  }
}
</code>```

I have been told that I am accessing the state isAuthenticated incorrectly:

```<code> {currentState.auth.isAuthenticated ? authLinks : guestLinks}
</code>```

That I should access it by using connect(). That was actually the first thing I have tried. It didn't work. But, I took their advice and tried it again:

```<code>class App extends Component {
  render() {
    const authLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
        <Route
          path="/home"
          name="Home"
          render={props => <DefaultLayout {...props} />}
        />
      </Switch>
    );

    const guestLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/register"
          name="Register Page"
          render={props => <Register {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
      </Switch>
    );

    const currentState = store.getState();
    console.log(
      "currentState.auth.isAuthenticated: ",
      currentState.auth.isAuthenticated
    );
    return (
      <Provider store={store}>
        <HashRouter>
          <React.Suspense fallback={loading()}>
            {console.log(currentState.auth.isAuthenticated)}
            {/* TODO: Not sure if this always works. If after the user logsin he gets a blank page and he has to reload to be redirected to home then
            this way of routing may need to modified */}
            {/* {currentState.auth.isAuthenticated ? authLinks : guestLinks} */}
            {this.props.auth.isAuthenticated ? authLinks : guestLinks}
          </React.Suspense>
        </HashRouter>
      </Provider>
    );
  }
}

App.propTypes = {
  auth: PropTypes.object.isRequired,
  errors: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
  auth: state.auth,
  errors: state.errors
});
export default connect(mapStateToProps, null)(withRouter(App));
</code>```

which gives the error I've mentioned:

```<code>Could not find "store" in the context of "Connect(withRouter(App))". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(withRouter(App)) in connect options.
</code>```

which kind of makes sense, since the store is passed root component App.js through the router. So the state of the app shouldn't be accessed in the same way it is accessed in childComponents through connect.
So I have two questions:

QUESTION 1: Why am I getting this error?

QUESTION 2: What is the right way of accessing the state data inside the root component where the link between the redux and react is implemented?

答:
ANSWER 1:
I think that you should use "connect" on a component called inside Provider.
The docs says:

```<code>Could not find "store" in either the context or props
If you have context issues,

Make sure you don’t have a duplicate instance of React on the page.
Make sure you didn’t forget to wrap your root or some other ancestor component in <Provider>.
Make sure you’re running the latest versions of React and React Redux.
</code>```

/*Into App.js*/
return (
      <Provider store={store}>
        <HashRouter>
          <React.Suspense fallback={loading()}>
            <ConnectedComponent>
          </React.Suspense>
        </HashRouter>
      </Provider>
    );

    /*ConnectedComponent.js*/
    class ConnectedComponent extends React
    {
      render(){
      {
        /* move all your routing and app code Here*/
      }
    }

    //call connect on your ConnectedComponent
    export connect(mapStateToProps, null)(ConnectedComponent)
```

I also think that you don't need to use withRouter because seems that you don't need the ReactRouter props (match, history, location) on your App component.

You can see here wen you should use withRouter: https://reacttraining.com/react-router/web/api/withRouter

ANSWER 2:
The connect() function do the job of connecting the Redux store to your React components tree. You should always access to the store data through the props object.

Body:
DISCLAIMER: This error has been mentioned on stackoverflow before but my case is different.

I have had a problem with the user login which I have explained in this stackOverFlow question. I invite you to go and quickly take a look.

So as I mentioned in that question in my root file I have this:

App.js

class App extends Component {
  render() {
    const authLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
        <Route
          path="/home"
          name="Home"
          render={props => <DefaultLayout {...props} />}
        />
      </Switch>
    );

    const guestLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/register"
          name="Register Page"
          render={props => <Register {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
      </Switch>
    );

    const currentState = store.getState();
    console.log(
      "currentState.auth.isAuthenticated: ",
      currentState.auth.isAuthenticated
    );
    return (
      <Provider store={store}>
        <HashRouter>
          <React.Suspense fallback={loading()}>
            {console.log(currentState.auth.isAuthenticated)}
            {/* TODO: Not sure if this always works. If after the user logsin he gets a blank page and he has to reload to be redirected to home then
            this way of routing may need to modified */}
            {currentState.auth.isAuthenticated ? authLinks : guestLinks}
          </React.Suspense>
        </HashRouter>
      </Provider>
    );
  }
}

I have been told that I am accessing the state isAuthenticated incorrectly:

 {currentState.auth.isAuthenticated ? authLinks : guestLinks}

That I should access it by using connect(). That was actually the first thing I have tried. It didn't work. But, I took their advice and tried it again:

class App extends Component {
  render() {
    const authLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
        <Route
          path="/home"
          name="Home"
          render={props => <DefaultLayout {...props} />}
        />
      </Switch>
    );

    const guestLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/register"
          name="Register Page"
          render={props => <Register {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
      </Switch>
    );

    const currentState = store.getState();
    console.log(
      "currentState.auth.isAuthenticated: ",
      currentState.auth.isAuthenticated
    );
    return (
      <Provider store={store}>
        <HashRouter>
          <React.Suspense fallback={loading()}>
            {console.log(currentState.auth.isAuthenticated)}
            {/* TODO: Not sure if this always works. If after the user logsin he gets a blank page and he has to reload to be redirected to home then
            this way of routing may need to modified */}
            {/* {currentState.auth.isAuthenticated ? authLinks : guestLinks} */}
            {this.props.auth.isAuthenticated ? authLinks : guestLinks}
          </React.Suspense>
        </HashRouter>
      </Provider>
    );
  }
}

App.propTypes = {
  auth: PropTypes.object.isRequired,
  errors: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
  auth: state.auth,
  errors: state.errors
});
export default connect(mapStateToProps, null)(withRouter(App));

which gives the error I've mentioned:

Could not find "store" in the context of "Connect(withRouter(App))". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(withRouter(App)) in connect options.

which kind of makes sense, since the store is passed root component App.js through the router. So the state of the app shouldn't be accessed in the same way it is accessed in childComponents through connect.
So I have two questions:

QUESTION 1: Why am I getting this error?

QUESTION 2: What is the right way of accessing the state data inside the root component where the link between the redux and react is implemented?

Body:
ANSWER 1:
I think that you should use "connect" on a component called inside Provider.
The docs says:

Could not find "store" in either the context or props
If you have context issues,

Make sure you don’t have a duplicate instance of React on the page.
Make sure you didn’t forget to wrap your root or some other ancestor component in <Provider>.
Make sure you’re running the latest versions of React and React Redux.

/*Into App.js*/
return (
      <Provider store={store}>
        <HashRouter>
          <React.Suspense fallback={loading()}>
            <ConnectedComponent>
          </React.Suspense>
        </HashRouter>
      </Provider>
    );

    /*ConnectedComponent.js*/
    class ConnectedComponent extends React
    {
      render(){
      {
        /* move all your routing and app code Here*/
      }
    }

    //call connect on your ConnectedComponent
    export connect(mapStateToProps, null)(ConnectedComponent)

I also think that you don't need to use withRouter because seems that you don't need the ReactRouter props (match, history, location) on your App component.

You can see here wen you should use withRouter: https://reacttraining.com/react-router/web/api/withRouter

ANSWER 2:
The connect() function do the job of connecting the Redux store to your React components tree. You should always access to the store data through the props object.


问:
Splitting Character String to Extract Date and Time
I have a character string in a column of a tibble that looks like Nov 01, 2019 8:00:41 AM CDT.

I would like to create new columns of the mentioned column, Date and Time.

What is the best approaches into doing this? Lubridate?

```<code>Time <- tibble(Call = 1, Date_Time = 'Nov 01, 2019 8:00:41 AM CDT')
Time %>%
    mutate(Date_Time = mdy(`Contact Start Date/Time`))
</code>```

I tried the code above but, my new column had nothing, but "NAs" in them.

答:
1) We can use as.POSIXct and as.Date as shown. I am not sure what you want for the time but have provided a character string time below.

```<code>library(dplyr)

DF %>% mutate(x = as.POSIXct(x, format = "%b %d, %Y %I:%M:%S %p"),
         date = as.Date(x),
         time = sub(".* ", "", x))
##                     x       date     time
## 1 2019-11-01 08:00:41 2019-11-01 08:00:41
</code>```

2) The chron package can represent dates and times separately:

```<code>library(dplyr)
library(chron)

DF %>%
  mutate(x = as.chron(as.character(x), format = "%b %d, %Y %I:%M:%S %p"),
         date = dates(x),
         time = x - date)

##                     x     date     time
## 1 (11/01/19 08:00:41) 11/01/19 08:00:41
</code>```

Note

```<code>DF <- data.frame(x = "Nov 01, 2019 8:00:41 AM CDT")
</code>```

Body:
I have a character string in a column of a tibble that looks like Nov 01, 2019 8:00:41 AM CDT.

I would like to create new columns of the mentioned column, Date and Time.

What is the best approaches into doing this? Lubridate?

Time <- tibble(Call = 1, Date_Time = 'Nov 01, 2019 8:00:41 AM CDT')
Time %>%
    mutate(Date_Time = mdy(`Contact Start Date/Time`))

I tried the code above but, my new column had nothing, but "NAs" in them.

Body:
1) We can use as.POSIXct and as.Date as shown. I am not sure what you want for the time but have provided a character string time below.

library(dplyr)

DF %>% mutate(x = as.POSIXct(x, format = "%b %d, %Y %I:%M:%S %p"),
         date = as.Date(x),
         time = sub(".* ", "", x))
##                     x       date     time
## 1 2019-11-01 08:00:41 2019-11-01 08:00:41

2) The chron package can represent dates and times separately:

library(dplyr)
library(chron)

DF %>%
  mutate(x = as.chron(as.character(x), format = "%b %d, %Y %I:%M:%S %p"),
         date = dates(x),
         time = x - date)

##                     x     date     time
## 1 (11/01/19 08:00:41) 11/01/19 08:00:41

Note

DF <- data.frame(x = "Nov 01, 2019 8:00:41 AM CDT")