问:
boost::lockfree::spsc_queue busy wait strategy. Is there a blocking pop?
So i'm using a boost::lockfree::spec_queue to communicate via two boost_threads running functors of two objects in my application.

All is fine except for the fact that the spec_queue::pop() method is non blocking. It returns True or False even if there is nothing in the queue. However my queue always seems to return True (problem #1). I think this is because i preallocate the queue.

```<code>typedef boost::lockfree::spsc_queue<q_pl, boost::lockfree::capacity<100000> > spsc_queue;
</code>```

This means that to use the queue efficiently i have to busy wait constantly popping the queue using 100% cpu. Id rather not sleep for arbitrary amounts of time. I've used other queues in java which block until an object is made available. Can this be done with std:: or boost:: data structures?

答:
Use a semaphore to cause the producers to sleep when the queue is full, and another semaphore to cause the consumers to sleep when the queue is empty.
when the queue is neither full nor empty, the sem_post and sem_wait operations are nonblocking (in newer kernels)</p>

```<code>#include <semaphore.h>

template<typename lock_free_container>
class blocking_lock_free
{
public:
    lock_free_queue_semaphore(size_t n) : container(n)
    {
        sem_init(&pop_semaphore, 0, 0);
        sem_init(&push_semaphore, 0, n);
    }

    ~lock_free_queue_semaphore()
    {
        sem_destroy(&pop_semaphore);
        sem_destroy(&push_semaphore);
    }

    bool push(const lock_free_container::value_type& v)
    {
        sem_wait(&push_semaphore);
        bool ret = container::bounded_push(v);
        ASSERT(ret);
        if (ret)
            sem_post(&pop_semaphore);
        else
            sem_post(&push_semaphore); // shouldn't happen
        return ret;
    }

    bool pop(lock_free_container::value_type& v)
    {
        sem_wait(&pop_semaphore);
        bool ret = container::pop(v);
        ASSERT(ret);
        if (ret)
            sem_post(&push_semaphore);
        else
            sem_post(&pop_semaphore); // shouldn't happen
        return ret;
    }
private:
    lock_free_container container;
    sem_t pop_semaphore;
    sem_t push_semaphore;
};
</code>```

Body:
So i'm using a boost::lockfree::spec_queue to communicate via two boost_threads running functors of two objects in my application.

All is fine except for the fact that the spec_queue::pop() method is non blocking. It returns True or False even if there is nothing in the queue. However my queue always seems to return True (problem #1). I think this is because i preallocate the queue.

typedef boost::lockfree::spsc_queue<q_pl, boost::lockfree::capacity<100000> > spsc_queue;

This means that to use the queue efficiently i have to busy wait constantly popping the queue using 100% cpu. Id rather not sleep for arbitrary amounts of time. I've used other queues in java which block until an object is made available. Can this be done with std:: or boost:: data structures?

Body:
Use a semaphore to cause the producers to sleep when the queue is full, and another semaphore to cause the consumers to sleep when the queue is empty.
when the queue is neither full nor empty, the sem_post and sem_wait operations are nonblocking (in newer kernels)

#include <semaphore.h>

template<typename lock_free_container>
class blocking_lock_free
{
public:
    lock_free_queue_semaphore(size_t n) : container(n)
    {
        sem_init(&pop_semaphore, 0, 0);
        sem_init(&push_semaphore, 0, n);
    }

    ~lock_free_queue_semaphore()
    {
        sem_destroy(&pop_semaphore);
        sem_destroy(&push_semaphore);
    }

    bool push(const lock_free_container::value_type& v)
    {
        sem_wait(&push_semaphore);
        bool ret = container::bounded_push(v);
        ASSERT(ret);
        if (ret)
            sem_post(&pop_semaphore);
        else
            sem_post(&push_semaphore); // shouldn't happen
        return ret;
    }

    bool pop(lock_free_container::value_type& v)
    {
        sem_wait(&pop_semaphore);
        bool ret = container::pop(v);
        ASSERT(ret);
        if (ret)
            sem_post(&push_semaphore);
        else
            sem_post(&pop_semaphore); // shouldn't happen
        return ret;
    }
private:
    lock_free_container container;
    sem_t pop_semaphore;
    sem_t push_semaphore;
};


来源: stackexchange

问:
Meteor React: What is the simplest way to ensure a user is logged in before rendergin a page?

Situation:

I'm using React in a Meteor app.

My packages for authentication: accounts-password; useraccounts:core

I also use the gadicc:blaze-react-component to render the {{> atForm }} template in my react component =><Blaze template="atForm" />

Problem:

I don't know what should be the proper syntax to secure a specific page as described in the useraccounts guide but with react.

Lets suppose that I want to secure <Mypage /> imported from './mypage.jsx'

How can I call {{> ensureSignedIn template="myTemplate"}} and reaplace "myTemplate" by <Mypage /> ?

I tried <Blaze template="atForm" template={Mypage} /> without success...

Is it even possible to make something like this ?

答:
I found a solution:

With kadira:flow-router Meteor's package, using react-layout and useraccounts:flow-routing, I can do something like that:

```<code>FlowRouter.route('/private', {
  triggersEnter: [AccountsTemplates.ensureSignedIn],
  action: function() {
    ReactLayout.render(Mypage, {myprops: myprops.value});
  }
});
</code>```

It seems that it all happens into triggersEnter: [...] key.

More details here.

ContentLicense: CC BY-SA 3.0

Body:
I found a solution:

With kadira:flow-router Meteor's package, using react-layout and useraccounts:flow-routing, I can do something like that:

FlowRouter.route('/private', {
  triggersEnter: [AccountsTemplates.ensureSignedIn],
  action: function() {
    ReactLayout.render(Mypage, {myprops: myprops.value});
  }
});

It seems that it all happens into triggersEnter: [...] key.

More details here.


问:
JavaScript: Algorithm or method to bind an array of objects to a DOM display?
The Good:

We send a JSON array of nested objects using JQuery and .ajax().  We use JQuery and Microsoft templates to render the content.  It sends 100 objects in 400 ms.  This is so much faster than our equivalent server rendering of 50 products in 10 seconds.

The Difficulty:

We need to bind a JavaScript object array to the DOM html elements it represents, i.e., changes to the html input will reflect back to the JavaScript object.  Our difficulty is that our objects are nested, and only contain selected options:

```<code>Product[].Department[].deptid;
// We only store the departments for which this product participates
</code>```

We tried Microsoft data linking using JQuery, which requires both object properties and html elements to exist in order to bind them together.  That doesn't do well for the above situation.  We could do this:

```<code>Product[].Department[].Dept.id;
Product[].Department[].Dept.name;
Product[].Department[].Dept.selected;  // true if selected, false if not
// This requires all possible options in all needed products.  Yuck
</code>```

Are there any examples out there on how best to handle binding a JavaScript nested object array to the HTML elements they represent?

We don't submit form elements back to the server.  Instead we collect them in to a JSON array and send that back to the server.  It works extremely fast, but assembly is tedious.

答:
It's hard to know exactly what you're having trouble with from your description, but it seems like there are two things that might help:

1) You can store data on a dom element using jQuery's data() method http://api.jquery.com/data/

2) You can get the value of a form element using the change() event and the val() method. (You can also find those in the API docs.)

But it seems like you could be running into something more basic, like the question of how to know which Javascript object goes with with form element. Is that the case?

ContentLicense: CC BY-SA 2.5

Body:
The Good:

We send a JSON array of nested objects using JQuery and .ajax().  We use JQuery and Microsoft templates to render the content.  It sends 100 objects in 400 ms.  This is so much faster than our equivalent server rendering of 50 products in 10 seconds.

The Difficulty:

We need to bind a JavaScript object array to the DOM html elements it represents, i.e., changes to the html input will reflect back to the JavaScript object.  Our difficulty is that our objects are nested, and only contain selected options:

Product[].Department[].deptid;
// We only store the departments for which this product participates

We tried Microsoft data linking using JQuery, which requires both object properties and html elements to exist in order to bind them together.  That doesn't do well for the above situation.  We could do this:

Product[].Department[].Dept.id;
Product[].Department[].Dept.name;
Product[].Department[].Dept.selected;  // true if selected, false if not
// This requires all possible options in all needed products.  Yuck

Are there any examples out there on how best to handle binding a JavaScript nested object array to the HTML elements they represent?

We don't submit form elements back to the server.  Instead we collect them in to a JSON array and send that back to the server.  It works extremely fast, but assembly is tedious.


问:
crash in Android only, java.lang.NoClassDefFoundError: Failed resolution of: Lcom/squareup/okhttp/MediaType;
Update: Its only crashing on Android Lollipop.

I am getting this error

```<code>06-08 16:30:56.788 29535-29535/com.d.p E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.d.p, PID: 29535
  java.lang.NoClassDefFoundError: Failed resolution of: Lcom/squareup/okhttp/MediaType;
      at com.d.p.ui.base.DWBApplication.<clinit>(DWBApplication.java:164)
      at java.lang.reflect.Constructor.newInstance(Native Method)
      at java.lang.Class.newInstance(Class.java:1606)
      at android.app.Instrumentation.newApplication(Instrumentation.java:1000)
      at android.app.Instrumentation.newApplication(Instrumentation.java:985)
      at android.app.LoadedApk.makeApplication(LoadedApk.java:567)
      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4837)
      at android.app.ActivityThread.access$1500(ActivityThread.java:178)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1531)
      at android.os.Handler.dispatchMessage(Handler.java:111)
      at android.os.Looper.loop(Looper.java:194)
      at android.app.ActivityThread.main(ActivityThread.java:5643)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
   Caused by: java.lang.ClassNotFoundException: Didn't find class "com.squareup.okhttp.MediaType" on path: DexPathList[[zip file "/data/app/com.d.p-1/base.apk", zip file "/data/app/com.d.p-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]
      at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
      at com.d.p.ui.base.DWBApplication.<clinit>(DWBApplication.java:164)
      at java.lang.reflect.Constructor.newInstance(Native Method)
      at java.lang.Class.newInstance(Class.java:1606)
      at android.app.Instrumentation.newApplication(Instrumentation.java:1000)
      at android.app.Instrumentation.newApplication(Instrumentation.java:985)
      at android.app.LoadedApk.makeApplication(LoadedApk.java:567)
      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4837)
      at android.app.ActivityThread.access$1500(ActivityThread.java:178)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1531)
      at android.os.Handler.dispatchMessage(Handler.java:111)
      at android.os.Looper.loop(Looper.java:194)
      at android.app.ActivityThread.main(ActivityThread.java:5643)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    Suppressed: java.lang.ClassNotFoundException: com.squareup.okhttp.MediaType
      at java.lang.Class.classForName(Native Method)
      at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
      at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
            ... 17 more
   Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
</code>```

My gradle:

```<code>dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
    transitive = true;
}
//    compile 'com.google.android.gms:play-services-location:8.4.0'
compile('com.github.worker8:tourguide:1.0.17-SNAPSHOT@aar') {
    transitive = true
}
compile 'junit:junit:4.12'
compile 'junit:junit:4.12'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.google.android.gms:play-services-location:9.4.0'
compile 'com.android.support:design:25.3.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'

compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

compile 'com.wefika:flowlayout:0.4.1'
compile 'com.jeremyfeinstein.slidingmenu:library:1.3@aar'
compile 'com.googlecode.libphonenumber:libphonenumber:7.0.4'
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.commit451:PhotoView:1.2.5'
compile 'com.outlander.showcaseview:showcaseview:1.2.0'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:support-v13:25.3.1'
compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
compile 'com.google.firebase:firebase-crash:9.0.0'
compile 'com.github.PhilJay:MPAndroidChart:v3.0.0-beta1'
compile 'com.google.android.gms:play-services-analytics:9.4.0'
compile 'com.layer.sdk:layer-sdk:0.21.3'
compile 'org.slf4j:slf4j-nop:1.5.8'
compile 'com.google.android.gms:play-services-maps:9.4.0'
compile 'com.layer.atlas:layer-atlas:0.2.10'
compile 'io.jsonwebtoken:jjwt:0.6.0'
compile 'com.google.firebase:firebase-messaging:9.2.0'
compile 'com.google.android.gms:play-services:9.4.0'
compile 'com.android.support:multidex:1.0.1'
compile 'com.google.android.gms:play-services-ads:9.4.0'
compile 'com.google.android.gms:play-services-auth:9.4.0'
compile 'com.google.android.gms:play-services-gcm:9.4.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
}
android {
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
    exclude 'META-INF/LGPL2.1'
}
}

apply plugin: 'com.google.gms.google-services'
</code>```

My application file:

```<code>public class DWBApplication extends Application {

//Network interface for executing web services over internet
Retrofit networkInterfaceBuilder;
private DawaiBoxService dawaiboxServiceInterface;

//Holds the current application context
private static Context appContext;

private static HomeActivity homeActivity; //Holds the reference to homeActivity as it holds fragments.
// Some time 'onAttach' callback method may call slowly. So then homeActivity reference is used from here

private static DWBApplication mInstance;

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}

@Override
public void onCreate() {
    super.onCreate();
    ViewTarget.setTagId(R.id.glide_tag);
    mInstance = this;

//        firebase initialization
    FirebaseAnalytics.getInstance(this).setAnalyticsCollectionEnabled(true);

//        google analytics initialization
    AnalyticsTrackers.initialize(this);
    AnalyticsTrackers.getInstance().get(AnalyticsTrackers.Target.APP);

    if(BuildConfig.FABRIC_ENABLED){
        Fabric.with(this, new Crashlytics());
    }

    appContext = getApplicationContext();

    //Create builder for interacting to server
    networkInterfaceBuilder = new Retrofit.Builder()
            .baseUrl(BuildConfig.SERVER_URL)
            .addConverterFactory(new GsonStringConverterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    //Create service interface to execute dawaibox services
    dawaiboxServiceInterface = networkInterfaceBuilder.create(DawaiBoxService.class);

    try {
        //initialize Typefaces
        TypefaceUtils.initTypefaces(getApplicationContext());
    } catch (Exception ex) {
        DWB_Logs.e("typefaces", ex);
    }
}

public DawaiBoxService getDawaiboxServiceInterface() {
    return dawaiboxServiceInterface;
}

public static Context getAppContext() {
    return appContext;
}

/*------------------------------Current user reference methods ends---------------------*/

/*------------------------------Add prefix +91 to mobile no. Methods starts---------------------*/
/*
* Desc: appends the '+91' prefix to entered text in edit text.
* */
public static MobileNoTextWatcher getAppendPrefixTextWatcher() {
    return new MobileNoTextWatcher();
}

public static String getMobileNoFromEdTxt(EditText mMobileNoEd) {
    if (mMobileNoEd.getText() != null) {
        String mobileNo = mMobileNoEd.getText().toString();
        if (mobileNo.length() > Constants.MOBILE_PREFIX.length()) {
            return mobileNo.substring(Constants.MOBILE_PREFIX.length(), mobileNo.length());
        }
    }
    return "";
}
/*------------------------------Add prefix +91 to mobile no. Methods ends---------------------*/

/*------------------------------Base homeActivity holder methods starts---------------------*/

/*Set the reference to current base homeActivity which displays the fragments*/
public static void setHomeActivity(HomeActivity homeActivity) {
    DWBApplication.homeActivity = homeActivity;
}

/*Returns the reference of current base homeActivity which displays the fragments*/
public static HomeActivity getHomeActivity() {
    return homeActivity;
}

/*------------------------------Base homeActivity holder methods ends---------------------*/

/*
* Methods which will hides the keyboard*/
public static void hideSoftKeyboard(Activity activity) {
    try {
        activity.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
        );
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

/*
* Solves problem: adding extra quotes to multipart string form values
*/
private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

public class GsonStringConverterFactory extends Converter.Factory {
    @Override
    public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
        if (String.class.equals(type))// || (type instanceof Class && ((Class<?>) type).isEnum()))
        {
            return new Converter<String, RequestBody>() {
                @Override
                public RequestBody convert(String value) throws IOException {
                    return RequestBody.create(MEDIA_TYPE, value);
                }
            };
        }
        return null;
    }
}

public static synchronized DWBApplication getInstance() {
    return mInstance;
}

public synchronized Tracker getGoogleAnalyticsTracker() {
    AnalyticsTrackers analyticsTrackers = AnalyticsTrackers.getInstance();
    return analyticsTrackers.get(AnalyticsTrackers.Target.APP);
}

/***
 * Tracking screen view
 *
 * @param screenName screen name to be displayed on GA dashboard
 */
public void trackScreenView(String screenName) {
    Tracker t = getGoogleAnalyticsTracker();

    // Set screen name.
    t.setScreenName(screenName);

    // Send a screen view.
    t.send(new HitBuilders.ScreenViewBuilder().build());
    //t.set("&uid", DWB_SharedPreferences.getLayertID(this));
    GoogleAnalytics.getInstance(this).dispatchLocalHits();
}

/***
 * Tracking exception
 *
 * @param e exception to be tracked
 */
public void trackException(Exception e) {
    if (e != null) {
        Tracker t = getGoogleAnalyticsTracker();

        t.send(new HitBuilders.ExceptionBuilder()
                .setDescription(
                        new StandardExceptionParser(this, null)
                                .getDescription(Thread.currentThread().getName(), e))
                .setFatal(false)
                .build()
        );
    }
}

/***
 * Tracking event
 *
 * @param category event category
 * @param action   action of the event
 * @param label    label
 */
public void trackEvent(String category, String action, String label) {
    Tracker t = getGoogleAnalyticsTracker();
    t.set("&uid", Config.USER1);
    // Build and send an Event.
    t.send(new HitBuilders.EventBuilder().setCategory(category).setAction(action).setLabel(label).build());
}
}
</code>```

I am getting crash on private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain"); line in application.java

答:
Just a guess, but the error exists in a transitive dependency of Retrofit called Okhttp.

Retrofit is not in beta anymore. You can go through and upgrade your libraries.

```<code>compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit:converter-gson:2.3.0'
</code>```

Personally, I would rewrite like so in order to always keep versions consistent

```<code>ext {
    retrofitVer = '2.3.0'
}

dependencies {
   ...
    compile "com.squareup.retrofit2:retrofit:${retrofitVer}"
    compile "com.squareup.retrofit:converter-gson:${retrofitVer}"
}
</code>```

The same should be applied to the support libraries, Google play and Firebase

ContentLicense: CC BY-SA 4.0

Body:
Update: Its only crashing on Android Lollipop.

I am getting this error

06-08 16:30:56.788 29535-29535/com.d.p E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.d.p, PID: 29535
  java.lang.NoClassDefFoundError: Failed resolution of: Lcom/squareup/okhttp/MediaType;
      at com.d.p.ui.base.DWBApplication.<clinit>(DWBApplication.java:164)
      at java.lang.reflect.Constructor.newInstance(Native Method)
      at java.lang.Class.newInstance(Class.java:1606)
      at android.app.Instrumentation.newApplication(Instrumentation.java:1000)
      at android.app.Instrumentation.newApplication(Instrumentation.java:985)
      at android.app.LoadedApk.makeApplication(LoadedApk.java:567)
      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4837)
      at android.app.ActivityThread.access$1500(ActivityThread.java:178)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1531)
      at android.os.Handler.dispatchMessage(Handler.java:111)
      at android.os.Looper.loop(Looper.java:194)
      at android.app.ActivityThread.main(ActivityThread.java:5643)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
   Caused by: java.lang.ClassNotFoundException: Didn't find class "com.squareup.okhttp.MediaType" on path: DexPathList[[zip file "/data/app/com.d.p-1/base.apk", zip file "/data/app/com.d.p-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]
      at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
      at com.d.p.ui.base.DWBApplication.<clinit>(DWBApplication.java:164)
      at java.lang.reflect.Constructor.newInstance(Native Method)
      at java.lang.Class.newInstance(Class.java:1606)
      at android.app.Instrumentation.newApplication(Instrumentation.java:1000)
      at android.app.Instrumentation.newApplication(Instrumentation.java:985)
      at android.app.LoadedApk.makeApplication(LoadedApk.java:567)
      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4837)
      at android.app.ActivityThread.access$1500(ActivityThread.java:178)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1531)
      at android.os.Handler.dispatchMessage(Handler.java:111)
      at android.os.Looper.loop(Looper.java:194)
      at android.app.ActivityThread.main(ActivityThread.java:5643)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    Suppressed: java.lang.ClassNotFoundException: com.squareup.okhttp.MediaType
      at java.lang.Class.classForName(Native Method)
      at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
      at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
            ... 17 more
   Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

My gradle:

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
    transitive = true;
}
//    compile 'com.google.android.gms:play-services-location:8.4.0'
compile('com.github.worker8:tourguide:1.0.17-SNAPSHOT@aar') {
    transitive = true
}
compile 'junit:junit:4.12'
compile 'junit:junit:4.12'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.google.android.gms:play-services-location:9.4.0'
compile 'com.android.support:design:25.3.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'

compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

compile 'com.wefika:flowlayout:0.4.1'
compile 'com.jeremyfeinstein.slidingmenu:library:1.3@aar'
compile 'com.googlecode.libphonenumber:libphonenumber:7.0.4'
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.commit451:PhotoView:1.2.5'
compile 'com.outlander.showcaseview:showcaseview:1.2.0'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:support-v13:25.3.1'
compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
compile 'com.google.firebase:firebase-crash:9.0.0'
compile 'com.github.PhilJay:MPAndroidChart:v3.0.0-beta1'
compile 'com.google.android.gms:play-services-analytics:9.4.0'
compile 'com.layer.sdk:layer-sdk:0.21.3'
compile 'org.slf4j:slf4j-nop:1.5.8'
compile 'com.google.android.gms:play-services-maps:9.4.0'
compile 'com.layer.atlas:layer-atlas:0.2.10'
compile 'io.jsonwebtoken:jjwt:0.6.0'
compile 'com.google.firebase:firebase-messaging:9.2.0'
compile 'com.google.android.gms:play-services:9.4.0'
compile 'com.android.support:multidex:1.0.1'
compile 'com.google.android.gms:play-services-ads:9.4.0'
compile 'com.google.android.gms:play-services-auth:9.4.0'
compile 'com.google.android.gms:play-services-gcm:9.4.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
}
android {
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
    exclude 'META-INF/LGPL2.1'
}
}

apply plugin: 'com.google.gms.google-services'

My application file:

public class DWBApplication extends Application {

//Network interface for executing web services over internet
Retrofit networkInterfaceBuilder;
private DawaiBoxService dawaiboxServiceInterface;

//Holds the current application context
private static Context appContext;

private static HomeActivity homeActivity; //Holds the reference to homeActivity as it holds fragments.
// Some time 'onAttach' callback method may call slowly. So then homeActivity reference is used from here

private static DWBApplication mInstance;

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}

@Override
public void onCreate() {
    super.onCreate();
    ViewTarget.setTagId(R.id.glide_tag);
    mInstance = this;

//        firebase initialization
    FirebaseAnalytics.getInstance(this).setAnalyticsCollectionEnabled(true);

//        google analytics initialization
    AnalyticsTrackers.initialize(this);
    AnalyticsTrackers.getInstance().get(AnalyticsTrackers.Target.APP);

    if(BuildConfig.FABRIC_ENABLED){
        Fabric.with(this, new Crashlytics());
    }

    appContext = getApplicationContext();

    //Create builder for interacting to server
    networkInterfaceBuilder = new Retrofit.Builder()
            .baseUrl(BuildConfig.SERVER_URL)
            .addConverterFactory(new GsonStringConverterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    //Create service interface to execute dawaibox services
    dawaiboxServiceInterface = networkInterfaceBuilder.create(DawaiBoxService.class);

    try {
        //initialize Typefaces
        TypefaceUtils.initTypefaces(getApplicationContext());
    } catch (Exception ex) {
        DWB_Logs.e("typefaces", ex);
    }
}

public DawaiBoxService getDawaiboxServiceInterface() {
    return dawaiboxServiceInterface;
}

public static Context getAppContext() {
    return appContext;
}

/*------------------------------Current user reference methods ends---------------------*/

/*------------------------------Add prefix +91 to mobile no. Methods starts---------------------*/
/*
* Desc: appends the '+91' prefix to entered text in edit text.
* */
public static MobileNoTextWatcher getAppendPrefixTextWatcher() {
    return new MobileNoTextWatcher();
}

public static String getMobileNoFromEdTxt(EditText mMobileNoEd) {
    if (mMobileNoEd.getText() != null) {
        String mobileNo = mMobileNoEd.getText().toString();
        if (mobileNo.length() > Constants.MOBILE_PREFIX.length()) {
            return mobileNo.substring(Constants.MOBILE_PREFIX.length(), mobileNo.length());
        }
    }
    return "";
}
/*------------------------------Add prefix +91 to mobile no. Methods ends---------------------*/

/*------------------------------Base homeActivity holder methods starts---------------------*/

/*Set the reference to current base homeActivity which displays the fragments*/
public static void setHomeActivity(HomeActivity homeActivity) {
    DWBApplication.homeActivity = homeActivity;
}

/*Returns the reference of current base homeActivity which displays the fragments*/
public static HomeActivity getHomeActivity() {
    return homeActivity;
}

/*------------------------------Base homeActivity holder methods ends---------------------*/

/*
* Methods which will hides the keyboard*/
public static void hideSoftKeyboard(Activity activity) {
    try {
        activity.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
        );
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

/*
* Solves problem: adding extra quotes to multipart string form values
*/
private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

public class GsonStringConverterFactory extends Converter.Factory {
    @Override
    public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
        if (String.class.equals(type))// || (type instanceof Class && ((Class<?>) type).isEnum()))
        {
            return new Converter<String, RequestBody>() {
                @Override
                public RequestBody convert(String value) throws IOException {
                    return RequestBody.create(MEDIA_TYPE, value);
                }
            };
        }
        return null;
    }
}

public static synchronized DWBApplication getInstance() {
    return mInstance;
}

public synchronized Tracker getGoogleAnalyticsTracker() {
    AnalyticsTrackers analyticsTrackers = AnalyticsTrackers.getInstance();
    return analyticsTrackers.get(AnalyticsTrackers.Target.APP);
}

/***
 * Tracking screen view
 *
 * @param screenName screen name to be displayed on GA dashboard
 */
public void trackScreenView(String screenName) {
    Tracker t = getGoogleAnalyticsTracker();

    // Set screen name.
    t.setScreenName(screenName);

    // Send a screen view.
    t.send(new HitBuilders.ScreenViewBuilder().build());
    //t.set("&uid", DWB_SharedPreferences.getLayertID(this));
    GoogleAnalytics.getInstance(this).dispatchLocalHits();
}

/***
 * Tracking exception
 *
 * @param e exception to be tracked
 */
public void trackException(Exception e) {
    if (e != null) {
        Tracker t = getGoogleAnalyticsTracker();

        t.send(new HitBuilders.ExceptionBuilder()
                .setDescription(
                        new StandardExceptionParser(this, null)
                                .getDescription(Thread.currentThread().getName(), e))
                .setFatal(false)
                .build()
        );
    }
}

/***
 * Tracking event
 *
 * @param category event category
 * @param action   action of the event
 * @param label    label
 */
public void trackEvent(String category, String action, String label) {
    Tracker t = getGoogleAnalyticsTracker();
    t.set("&uid", Config.USER1);
    // Build and send an Event.
    t.send(new HitBuilders.EventBuilder().setCategory(category).setAction(action).setLabel(label).build());
}
}

I am getting crash on private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain"); line in application.java

Body:
Just a guess, but the error exists in a transitive dependency of Retrofit called Okhttp.

Retrofit is not in beta anymore. You can go through and upgrade your libraries.

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit:converter-gson:2.3.0'

Personally, I would rewrite like so in order to always keep versions consistent

ext {
    retrofitVer = '2.3.0'
}

dependencies {
   ...
    compile "com.squareup.retrofit2:retrofit:${retrofitVer}"
    compile "com.squareup.retrofit:converter-gson:${retrofitVer}"
}

The same should be applied to the support libraries, Google play and Firebase


问:
CSS selectors for inner grid lines with variable items
I have a list view of data displayed as cards and I'm trying to get to a pure CSS solution where I'll have only inner border lines.

The cards will display a max of two per row and will wrap to the next line when there are more. We're using bootstrap col-md-6 to achieve this.

Here's an example of three data items displayed as cards and what I'm trying to achieve with the inner grid lines.

Notes:

If there are only two items then the bottom line shouldn't be visible

I thought I could use adapt the technique mentioned here by Lea Verou, but I haven't been able to get it to work.

Regardless of how many items there are none of the outer borders should ever show. This is especially so with the last 1 or two items depending on the total count of items

Here's an example of the HTML markup for an individual list item:

```<code><div class="col-md-6">
    <div class="form-group">
        <label class="control-label">Name</label>
        <div class="form-control-static">Fund</div>
    </div>

    <div class="form-group">
        <label class="control-label">Tax Rate</label>
        <div class="form-control-static">1</div>
    </div>

    <div class="form-group">
        <label class="control-label">Amount</label>
        <div class="form-control-static">10</div>
    </div>

    <div class="edit-buttons">
        <a class="btn btn-link"><span class="glyphicon glyphicon-pencil"></span> edit</a>
        <a class="btn btn-link><span class="glyphicon glyphicon-remove"></span> delete</a>
    </div>
</div>
</code>```

I know to get the middle line I can use:
.col-md-6:nth-child(odd){
    border-right:1px solid gray;
}

The problem comes in with the bottom border, i.e. if you have a total of three data items then only the last one should have its bottom border set to 'none'. If there are four then the last two would need their bottom borders set to 'none'.

What's the best approach to getting this to work without the use of tables?

答:
you could wrap each 2 cols inside a row. and give border-bottom to that row instead of the cols

see below

.col-md-6:first-child { border-right:1px solid gray}
.row:not(:last-child) { border-bottom:1px solid gray}
.container-fluid { margin:15px auto;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>

<div class="container-fluid">

<div class="row">

<div class="col-md-6 col-xs-6 col-sm-6">
    <div class="form-group">
        <label class="control-label">Name</label>
        <div class="form-control-static">Fund</div>
    </div>

    <div class="form-group">
        <label class="control-label">Tax Rate</label>
        <div class="form-control-static">1</div>
    </div>

    <div class="form-group">
        <label class="control-label">Amount</label>
        <div class="form-control-static">10</div>
    </div>

    <div class="edit-buttons">
        <span class="glyphicon glyphicon-pencil"></span> edit
        <span class="glyphicon glyphicon-remove"></span> delete
    </div>
</div>
<div class="col-md-6 col-xs-6 col-sm-6">
    <div class="form-group">
        <label class="control-label">Name</label>
        <div class="form-control-static">Fund</div>
    </div>

    <div class="form-group">
        <label class="control-label">Tax Rate</label>
        <div class="form-control-static">1</div>
    </div>

    <div class="form-group">
        <label class="control-label">Amount</label>
        <div class="form-control-static">10</div>
    </div>

    <div class="edit-buttons">
        <span class="glyphicon glyphicon-pencil"></span> edit
        <span class="glyphicon glyphicon-remove"></span> delete
    </div>
</div>

</div>
<div class="row">

<div class="col-md-6 col-xs-6 col-sm-6">
    <div class="form-group">
        <label class="control-label">Name</label>
        <div class="form-control-static">Fund</div>
    </div>

    <div class="form-group">
        <label class="control-label">Tax Rate</label>
        <div class="form-control-static">1</div>
    </div>

    <div class="form-group">
        <label class="control-label">Amount</label>
        <div class="form-control-static">10</div>
    </div>

    <div class="edit-buttons">
        <span class="glyphicon glyphicon-pencil"></span> edit
        <span class="glyphicon glyphicon-remove"></span> delete
    </div>
</div>
<div class="col-md-6 col-xs-6 col-sm-6">
    <div class="form-group">
        <label class="control-label">Name</label>
        <div class="form-control-static">Fund</div>
    </div>

    <div class="form-group">
        <label class="control-label">Tax Rate</label>
        <div class="form-control-static">1</div>
    </div>

    <div class="form-group">
        <label class="control-label">Amount</label>
        <div class="form-control-static">10</div>
    </div>

    <div class="edit-buttons">
        <span class="glyphicon glyphicon-pencil"></span> edit
        <span class="glyphicon glyphicon-remove"></span> delete
    </div>
</div>

</div>
<div class="row">

<div class="col-md-6 col-xs-6 col-sm-6">
    <div class="form-group">
        <label class="control-label">Name</label>
        <div class="form-control-static">Fund</div>
    </div>

    <div class="form-group">
        <label class="control-label">Tax Rate</label>
        <div class="form-control-static">1</div>
    </div>

    <div class="form-group">
        <label class="control-label">Amount</label>
        <div class="form-control-static">10</div>
    </div>

    <div class="edit-buttons">
        <span class="glyphicon glyphicon-pencil"></span> edit
        <span class="glyphicon glyphicon-remove"></span> delete
    </div>
</div>

</div>
</div></code>```

Body:
I have a list view of data displayed as cards and I'm trying to get to a pure CSS solution where I'll have only inner border lines.

The cards will display a max of two per row and will wrap to the next line when there are more. We're using bootstrap col-md-6 to achieve this.

Here's an example of three data items displayed as cards and what I'm trying to achieve with the inner grid lines.

Notes:

If there are only two items then the bottom line shouldn't be visible

I thought I could use adapt the technique mentioned here by Lea Verou, but I haven't been able to get it to work.

Regardless of how many items there are none of the outer borders should ever show. This is especially so with the last 1 or two items depending on the total count of items

Here's an example of the HTML markup for an individual list item:

        Name

Fund

        Tax Rate

1

        Amount

10

         edit
         delete

I know to get the middle line I can use:
.col-md-6:nth-child(odd){
    border-right:1px solid gray;
}

The problem comes in with the bottom border, i.e. if you have a total of three data items then only the last one should have its bottom border set to 'none'. If there are four then the last two would need their bottom borders set to 'none'.

What's the best approach to getting this to work without the use of tables?

Body:
you could wrap each 2 cols inside a row. and give border-bottom to that row instead of the cols

see below

.col-md-6:first-child { border-right:1px solid gray}
.row:not(:last-child) { border-bottom:1px solid gray}
.container-fluid { margin:15px auto;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>

<div class="container-fluid">

<div class="row">

<div class="col-md-6 col-xs-6 col-sm-6">
    <div class="form-group">
        <label class="control-label">Name</label>
        <div class="form-control-static">Fund</div>
    </div>

    <div class="form-group">
        <label class="control-label">Tax Rate</label>
        <div class="form-control-static">1</div>
    </div>

    <div class="form-group">
        <label class="control-label">Amount</label>
        <div class="form-control-static">10</div>
    </div>

    <div class="edit-buttons">
        <a class="btn btn-link"><span class="glyphicon glyphicon-pencil"></span> edit</a>
        <a class="btn btn-link"><span class="glyphicon glyphicon-remove"></span> delete</a>
    </div>
</div>
<div class="col-md-6 col-xs-6 col-sm-6">
    <div class="form-group">
        <label class="control-label">Name</label>
        <div class="form-control-static">Fund</div>
    </div>

    <div class="form-group">
        <label class="control-label">Tax Rate</label>
        <div class="form-control-static">1</div>
    </div>

    <div class="form-group">
        <label class="control-label">Amount</label>
        <div class="form-control-static">10</div>
    </div>

    <div class="edit-buttons">
        <a class="btn btn-link"><span class="glyphicon glyphicon-pencil"></span> edit</a>
        <a class="btn btn-link"><span class="glyphicon glyphicon-remove"></span> delete</a>
    </div>
</div>

</div>
<div class="row">

<div class="col-md-6 col-xs-6 col-sm-6">
    <div class="form-group">
        <label class="control-label">Name</label>
        <div class="form-control-static">Fund</div>
    </div>

    <div class="form-group">
        <label class="control-label">Tax Rate</label>
        <div class="form-control-static">1</div>
    </div>

    <div class="form-group">
        <label class="control-label">Amount</label>
        <div class="form-control-static">10</div>
    </div>

    <div class="edit-buttons">
        <a class="btn btn-link"><span class="glyphicon glyphicon-pencil"></span> edit</a>
        <a class="btn btn-link"><span class="glyphicon glyphicon-remove"></span> delete</a>
    </div>
</div>
<div class="col-md-6 col-xs-6 col-sm-6">
    <div class="form-group">
        <label class="control-label">Name</label>
        <div class="form-control-static">Fund</div>
    </div>

    <div class="form-group">
        <label class="control-label">Tax Rate</label>
        <div class="form-control-static">1</div>
    </div>

    <div class="form-group">
        <label class="control-label">Amount</label>
        <div class="form-control-static">10</div>
    </div>

    <div class="edit-buttons">
        <a class="btn btn-link"><span class="glyphicon glyphicon-pencil"></span> edit</a>
        <a class="btn btn-link"><span class="glyphicon glyphicon-remove"></span> delete</a>
    </div>
</div>

</div>
<div class="row">

<div class="col-md-6 col-xs-6 col-sm-6">
    <div class="form-group">
        <label class="control-label">Name</label>
        <div class="form-control-static">Fund</div>
    </div>

    <div class="form-group">
        <label class="control-label">Tax Rate</label>
        <div class="form-control-static">1</div>
    </div>

    <div class="form-group">
        <label class="control-label">Amount</label>
        <div class="form-control-static">10</div>
    </div>

    <div class="edit-buttons">
        <a class="btn btn-link"><span class="glyphicon glyphicon-pencil"></span> edit</a>
        <a class="btn btn-link"><span class="glyphicon glyphicon-remove"></span> delete</a>
    </div>
</div>

</div>
</div>


问:
Is it necessary to restart Cassandra after updating its .truststore?
We are using Cassandra with SSL encryption. We have added a new user and generated its key/certificate that was referenced from cqlshrc. However it didn't work until Cassandra was restarted. Is it always necessary to restart Cassandra on an update of truststore (certificates store) or is there another way how to tell Cassandra that there is a new certificate?

It is not clear from Cassandra documentation as the necessity of restart is mentioned just for changes in yaml.

Thanks.

答:
Although it was asked a long time ago I will post my answer for the record: yes, it is necessary to restart Cassandra after updating the trustore.

As far as I can see from the source code the Cassandra loads truststores at start only.


问:
sort the list of links by the name of the link
I have list of links

```<code>links = [
  '<a href="http://127.0.0.1:5000/project/24/portfolio/">Packaging Only Demo</a>',
  '<a href="http://127.0.0.1:5000/project/38/portfolio/">QA Source</a>',
  '<a href="http://127.0.0.1:5000/project/44/portfolio/">Complete Demo</a>'
]
</code>```

And I need to sort the list by the name of the link.

I tried to sort it with a regular expression but it lasted too long. The list consists of a multitude of references

```<code>import re
def sorted(x):
  return re.search(r'\>(.*)<', x).group(1)

links = sorted(links, key=sorted)
print(links)
</code>```

答:
How about using sorted() or sort() with str.split() ?

```<code># Or:
# links.sort(key=lambda x: x.split(">")[1].split("<")[0])

sorted_list = sorted(links, key= lambda x: x.split(">")[1].split("<")[0])
</code>```

Output

```<code>>>> print(sorted_list)

 ['<a href="http://127.0.0.1:5000/project/44/portfolio/">Complete Demo</a>',
 '<a href="http://127.0.0.1:5000/project/24/portfolio/">Packaging Only Demo</a>',
 '<a href="http://127.0.0.1:5000/project/38/portfolio/">QA Source</a>']
</code>```

Body:
I have list of links

links = [
  'Packaging Only Demo',
  'QA Source',
  'Complete Demo'
]

And I need to sort the list by the name of the link.

I tried to sort it with a regular expression but it lasted too long. The list consists of a multitude of references

import re
def sorted(x):
  return re.search(r'\>(.*)<', x).group(1)

links = sorted(links, key=sorted)
print(links)

Body:
How about using sorted() or sort() with str.split() ?

# Or:
# links.sort(key=lambda x: x.split(">")[1].split("<")[0])

sorted_list = sorted(links, key= lambda x: x.split(">")[1].split("<")[0])

Output

>>> print(sorted_list)

 ['<a href="http://127.0.0.1:5000/project/44/portfolio/">Complete Demo</a>',
 '<a href="http://127.0.0.1:5000/project/24/portfolio/">Packaging Only Demo</a>',
 '<a href="http://127.0.0.1:5000/project/38/portfolio/">QA Source</a>']


问:
Iterating through a vector and using that value as column of dataframe
I am using this for loop to standardize the data in my columns. Here m_sel_cols is a vector with column names.

```<code>for(i in m_sel_cols)
    {
        cal <- work_data1$i
        cal <- ((cal-mean(cal))/sd(cal))
    }
</code>```

Suppose if my column name is "A" then is you do :

```<code>  ...
        cal <- work_data1$A
  ...
</code>```

The number of columns in my dataset is huge and I want to convert it back to data frame, I know cbind() can be used but how within the for loop?

答:
We can do this with tidyverse

```<code>library(tidyverse)
xy %>%
     mutate_all(scale)
#   a  b  c
#1 -1 -1 -1
#2  0  0  0
#3  1  1  1
</code>```

data

```<code>xy <- data.frame(a = 1:3, b = 4:6, c = 7:9)
</code>```

Body:
I am using this for loop to standardize the data in my columns. Here m_sel_cols is a vector with column names.

for(i in m_sel_cols)
    {
        cal <- work_data1$i
        cal <- ((cal-mean(cal))/sd(cal))
    }

Suppose if my column name is "A" then is you do :

  ...
        cal <- work_data1$A
  ...

The number of columns in my dataset is huge and I want to convert it back to data frame, I know cbind() can be used but how within the for loop?

Body:
We can do this with tidyverse

library(tidyverse)
xy %>%
     mutate_all(scale)
#   a  b  c
#1 -1 -1 -1
#2  0  0  0
#3  1  1  1

data

xy <- data.frame(a = 1:3, b = 4:6, c = 7:9)


问:
c# hosting a usercontrol in IE
Our web page is only available internally in our company and we am very intrested in being able to offer  interactive .net usercontrols on our departments website in the .Net 2.0 enviorment. I have been successful with embeding the object as so:

```<code><object id="Object1" classid="http:EmbedTest1.dll#EmbedTest1.UserControl1"
        width="400" height="400">
    <param name="TestStr" value="Test Param String" />
</object>
</code>```

The control worked just fine and the value was passed to the control without issue.
But I had a problem with passing  subsequent values back to the embedded control

 attempt to Recieve event from control:

attempt to update control:

```<code><script type="text/javascript">
   function UpdateStr()
   {
      Object1.Text = "update string";
   }
</script>
</code>```

Reference:

http://www.15seconds.com/issue/030610.htm

http://windowsclient.net/articles/iesourcing.aspx

Questions:

Is this technology outdated? - if so is there a replacement

Should I just work with action script instead of trying this?

I have got this to partially work and I was attempting to connect to a webservice that I have running and I got many security exceptions...I didn't get the same exceptions when I used action scipt2 in the same manner?

(side note : - how do i paste html script examples?)

Thanks.

Brad

答:
Not out-dated so much as rarely used, and IE-only. If you want web-like deployment for desktop apps, use ClickOnce. If you want C# code that runs in the browser without security issues, use Silverlight. You could also look at XBAPs, which are sandboxed WPF apps that run in the browser, works on IE and Firefox, but requires the full .NET to be installed client-side, whereas Silverlight does not have this problem. Bottom line: look at Silverlight.

That's certainly an option. If you're more familiar with the Microsoft stack, you should try Silverlight, where you can code C# against a subset of the .NET framework right inside the browser.

We've used .NET controls in web pages internally and had a wide variety of strange issues, mostly related to scripting or security. Hard to determine the problem without more information.

p.s. write all code examples using the ``` tags. There's a "code sample" button on the toolbar.

OwnerDisplayName: Brad

Title: c# hosting a usercontrol in IE

Body:
Our web page is only available internally in our company and we am very intrested in being able to offer  interactive .net usercontrols on our departments website in the .Net 2.0 enviorment. I have been successful with embeding the object as so:

<object id="Object1" classid="http:EmbedTest1.dll#EmbedTest1.UserControl1"
        width="400" height="400">
    <param name="TestStr" value="Test Param String" />
</object>

The control worked just fine and the value was passed to the control without issue.
But I had a problem with passing  subsequent values back to the embedded control

 attempt to Recieve event from control:

attempt to update control:

Reference:

http://www.15seconds.com/issue/030610.htm

http://windowsclient.net/articles/iesourcing.aspx

Questions:

Is this technology outdated? - if so is there a replacement

Should I just work with action script instead of trying this?

I have got this to partially work and I was attempting to connect to a webservice that I have running and I got many security exceptions...I didn't get the same exceptions when I used action scipt2 in the same manner?

(side note : - how do i paste html script examples?)

Thanks.

Brad

LastEditorDisplayName: Benoit

Body:
Not out-dated so much as rarely used, and IE-only. If you want web-like deployment for desktop apps, use ClickOnce. If you want C# code that runs in the browser without security issues, use Silverlight. You could also look at XBAPs, which are sandboxed WPF apps that run in the browser, works on IE and Firefox, but requires the full .NET to be installed client-side, whereas Silverlight does not have this problem. Bottom line: look at Silverlight.

That's certainly an option. If you're more familiar with the Microsoft stack, you should try Silverlight, where you can code C# against a subset of the .NET framework right inside the browser.

We've used .NET controls in web pages internally and had a wide variety of strange issues, mostly related to scripting or security. Hard to determine the problem without more information.

p.s. write all code examples using the <pre> tags. There's a "code sample" button on the toolbar.

OwnerDisplayName: Judah Himango


问:
Is now the time to start designing for 1280px wide screens instead of 1024px?
Need opinions on this, what do you guys think? A good idea or not so good idea.

I could do a seperate css style but not sure whether to drop 1024 for sure.

答:
IMHO, it really depends on the demographic of your target audience.

Let's say you're putting a site together targeted at gamers. Chances are that most people looking at that site have high resolution capable monitors, so it'd be safe (again, imo) to design at a higher res.

However, if you're developing a site or system that you don't want to turn anyone away from (i.e. commercial shopping or social networking type of site), then you really want to develop for the lowest common denominator. If someone stops visiting your site because it's annoying to them that it doesn't fit in their browser, that's one less customer.


问:
Elixir - Read postgres result
I need to read the raw Postgres output and iterate over the row value.

```<code>ww = %Postgrex.Result{columns: ["id", "tracking_link"], command: :select,
 connection_id: 22311, num_rows: 14,
 rows: [[2, "http://StarChef.com?id=1"],
  [3, "http://CaptainAmerica:TWSLiveWP.com?id=2"]]}
</code>```

ww[:rows] - not giving output

答:
You need to use . to access fields of a struct. The bracket syntax only works for maps which are not structs or structs which implement the Access behavior.

```<code>iex(1)> ww = %Postgrex.Result{columns: ["id", "tracking_link"], command: :select,
...(1)>  connection_id: 22311, num_rows: 14,
...(1)>  rows: [[2, "http://StarChef.com?id=1"],
...(1)>   [3, "http://CaptainAmerica:TWSLiveWP.com?id=2"]]}
%Postgrex.Result{columns: ["id", "tracking_link"], command: :select,
 connection_id: 22311, num_rows: 14,
 rows: [[2, "http://StarChef.com?id=1"],
  [3, "http://CaptainAmerica:TWSLiveWP.com?id=2"]]}
iex(2)> ww.rows
[[2, "http://StarChef.com?id=1"],
 [3, "http://CaptainAmerica:TWSLiveWP.com?id=2"]]
</code>```

Title: Elixir - Read postgres result

Body:
I need to read the raw Postgres output and iterate over the row value.

ww = %Postgrex.Result{columns: ["id", "tracking_link"], command: :select,
 connection_id: 22311, num_rows: 14,
 rows: [[2, "http://StarChef.com?id=1"],
  [3, "http://CaptainAmerica:TWSLiveWP.com?id=2"]]}

ww[:rows] - not giving output

Body:
You need to use . to access fields of a struct. The bracket syntax only works for maps which are not structs or structs which implement the Access behavior.

iex(1)> ww = %Postgrex.Result{columns: ["id", "tracking_link"], command: :select,
...(1)>  connection_id: 22311, num_rows: 14,
...(1)>  rows: [[2, "http://StarChef.com?id=1"],
...(1)>   [3, "http://CaptainAmerica:TWSLiveWP.com?id=2"]]}
%Postgrex.Result{columns: ["id", "tracking_link"], command: :select,
 connection_id: 22311, num_rows: 14,
 rows: [[2, "http://StarChef.com?id=1"],
  [3, "http://CaptainAmerica:TWSLiveWP.com?id=2"]]}
iex(2)> ww.rows
[[2, "http://StarChef.com?id=1"],
 [3, "http://CaptainAmerica:TWSLiveWP.com?id=2"]]


问:
Calling VB.Net from VBA in Excel
I am trying to get some code working between Excel VBA and VB.Net.  I have the following code in VB.Net in Visual Studio..

```<code>Public Class ThisAddIn

    Private Sub ThisAddIn_Startup() Handles Me.Startup

    End Sub

    Private Sub ThisAddIn_Shutdown() Handles Me.Shutdown

    End Sub

    Public Function Multiplication()
        Dim activeWorksheet As Excel.Worksheet = CType(Application.ActiveSheet, Excel.Worksheet)

        Dim Range1 As Excel.Range = activeWorksheet.Range("A1")
        Dim Range2 As Excel.Range = activeWorksheet.Range("A2")

        Dim x As Integer = Range1.Value
        Dim y As Integer = Range2.Value

        Return (x * y)

    End Function

End Class
</code>```

I also have this code in VBA that I am trying to run

```<code>Sub Macro1()

Dim x
x = ThisAddIn.Multiplication
MsgBox (x)

End Sub
</code>```

From Visual Studio I hit Start and I put this code into the Excel VBA for the new window that pops up.

I get the error '424 Object Required' on the VBA line "x = ThisAddIn.Multiplication".  How can I call a VB.Net function from VBA?

Edit: I am using Excel 2013, VB.Net version 2013(VB12), and I guess I am targeting .Net version 4.5+

Edit: I tried adding the following code:

```<code>Imports System
Imports System.Collections.Generic
Imports System.Text
</code>```

and

```<code>Private Sub Test()
 Dim testClass As New ThisAddIn
 MsgBox testClass.Multiplication()
End Sub
</code>```

Based off this guide, but its still not working.  I could not find the options to connect the project to Excel mentioned in Step 3 because it is an old guide.  Maybe this is my problem?

答:
if you want to call a function from vb.net first you must reference your dll to vba ftom tools->reference.
after reference you must define object from your class into dll file.
if your dll file name is mydll the below code is written in vba like below:</p>

```<code>dim x as mydll.ThisAddIn
set x =new mydll.ThisAddIn
dim y
y=x.Multiplication
</code>```

Title: Calling VB.Net from VBA in Excel

Body:
I am trying to get some code working between Excel VBA and VB.Net.  I have the following code in VB.Net in Visual Studio..

Public Class ThisAddIn

    Private Sub ThisAddIn_Startup() Handles Me.Startup

    End Sub

    Private Sub ThisAddIn_Shutdown() Handles Me.Shutdown

    End Sub

    Public Function Multiplication()
        Dim activeWorksheet As Excel.Worksheet = CType(Application.ActiveSheet, Excel.Worksheet)

        Dim Range1 As Excel.Range = activeWorksheet.Range("A1")
        Dim Range2 As Excel.Range = activeWorksheet.Range("A2")

        Dim x As Integer = Range1.Value
        Dim y As Integer = Range2.Value

        Return (x * y)

    End Function

End Class

I also have this code in VBA that I am trying to run

Sub Macro1()

Dim x
x = ThisAddIn.Multiplication
MsgBox (x)

End Sub

From Visual Studio I hit Start and I put this code into the Excel VBA for the new window that pops up.

I get the error '424 Object Required' on the VBA line "x = ThisAddIn.Multiplication".  How can I call a VB.Net function from VBA?

Edit: I am using Excel 2013, VB.Net version 2013(VB12), and I guess I am targeting .Net version 4.5+

Edit: I tried adding the following code:

Imports System
Imports System.Collections.Generic
Imports System.Text

and

Private Sub Test()
 Dim testClass As New ThisAddIn
 MsgBox testClass.Multiplication()
End Sub

Based off this guide, but its still not working.  I could not find the options to connect the project to Excel mentioned in Step 3 because it is an old guide.  Maybe this is my problem?

Body:
if you want to call a function from vb.net first you must reference your dll to vba ftom tools->reference.
after reference you must define object from your class into dll file.
if your dll file name is mydll the below code is written in vba like below:

dim x as mydll.ThisAddIn
set x =new mydll.ThisAddIn
dim y
y=x.Multiplication


问:
Unable to show pdf file in browser using response object
The pdf file I am generating using Dev Express and returning it to the browser using response object. I need to open file in the browser new window.

For the client side script the code to call method of web service:

```<code>window.open(dashboardService + "PrintableJobOrderDocument?JobOrderNo=" + jobOrderNo, "Job Order Documnet", "scrollbars=0,fullscreen=1", false);
</code>```

For the WCF service the method is:

```<code>[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json)]
public void PrintableJobOrderDocument(string JobOrderNo)
{
    if (!string.IsNullOrEmpty(JobOrderNo))
    {
        CommonServiceClient commonService = null;
        try
        {
            commonService = new CommonServiceClient();
            var data = commonService.JobOrderPDFDoc(JobOrderNo);
            if (data.Count() != 0)
            {
                //Excel file as a memory stream
                var excel = JobOrderTemplate(data);//this method will return the workbook object.
                MemoryStream ExcelStream = new MemoryStream();
                excel.SaveDocument(ExcelStream, DocumentFormat.Xlsx);
                ExcelStream.Position = 0;

                //Excel file to a pdf memory stream
                Workbook workbook = new Workbook();
                workbook.LoadDocument(ExcelStream, DocumentFormat.Xlsx);
                MemoryStream PDFStream = new MemoryStream();
                workbook.ExportToPdf(PDFStream);
                PDFStream.Seek(0, SeekOrigin.Begin);

                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.BufferOutput = true;
                response.ContentType = "application/pdf";
                response.AppendHeader("content-disposition", "Job Order No. " + JobOrderNo + ".pdf");
                byte[] fileToDownload = PDFStream.ToArray();
                response.BinaryWrite(fileToDownload);
                response.Flush();
                response.End();
            }
        }
        catch (Exception ex)
        {
            GeneralTask.AddMessageLog(MessageLogApplication.Portal, MessageLogModules.Common, MessageLogType.Error, MethodBase.GetCurrentMethod().Name, ex);
        }
        finally
        {
            ServiceHelper.CloseService(commonService);
        }
    }
}
</code>```

The response object show different behavior to different browser.
Like for:

Chrome: File some time opened and some time unable to open the file.

Mozilla: File never opened and give me error:

C:\Users\tach\AppData\Local\Temp\nJ0oODH4.pdf.part could not be saved,
  because the source file could not be read.

Try again later, or contact the server administrator.

Response Header in Mozilla:

Cache-Control: private

  Transfer-Encoding: chunked Content-Type:

  application/pdf Server: Microsoft-IIS/10.0

  Content-Disposition: Job
  Order No. ad_0003.pdf

  X-AspNet-Version: 4.0.30319 X-SourceFiles:
  =?UTF-8?B?RzpcRm1zMlRmc1xGTVNPZmZpY2UtVjEwNi1UcnVua1xGTVNQb3J0YWxcRGFzaGJvYXJkU2VydmljZS5zdmNcUHJpbnRhYmxlSm9iT3JkZXJEb2N1bWVudA==?=
  X-Powered-By: ASP.NET Access-Control-Allow-Origin: * Date: Thu, 08 Jun
  2017 09:48:00 GMT

Microsoft Edge: File never open.

I have the checked all the browsers Network tab and in header response file, file type, file name available but unable to open the file.

Update:

Below given AppHeader works for Chrome but not for Firefox or Edge.

```<code>response.AppendHeader("content-disposition", "inline; \"Job Order No " + JobOrderNo + ".pdf\"");
</code>```

and

```<code>response.AppendHeader("content-disposition", "Job Order No. " + JobOrderNo + ".pdf");
</code>```

答:
Change:

```<code>response.AppendHeader("content-disposition", "Job Order No. " + JobOrderNo + ".pdf");
</code>```

to:

```<code>response.AppendHeader("Content-Disposition", "inline; \"Job Order No " + JobOrderNo + ".pdf\"");
</code>```

Does that help?

Body:
The pdf file I am generating using Dev Express and returning it to the browser using response object. I need to open file in the browser new window.

For the client side script the code to call method of web service:

window.open(dashboardService + "PrintableJobOrderDocument?JobOrderNo=" + jobOrderNo, "Job Order Documnet", "scrollbars=0,fullscreen=1", false);

For the WCF service the method is:

[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json)]
public void PrintableJobOrderDocument(string JobOrderNo)
{
    if (!string.IsNullOrEmpty(JobOrderNo))
    {
        CommonServiceClient commonService = null;
        try
        {
            commonService = new CommonServiceClient();
            var data = commonService.JobOrderPDFDoc(JobOrderNo);
            if (data.Count() != 0)
            {
                //Excel file as a memory stream
                var excel = JobOrderTemplate(data);//this method will return the workbook object.
                MemoryStream ExcelStream = new MemoryStream();
                excel.SaveDocument(ExcelStream, DocumentFormat.Xlsx);
                ExcelStream.Position = 0;

                //Excel file to a pdf memory stream
                Workbook workbook = new Workbook();
                workbook.LoadDocument(ExcelStream, DocumentFormat.Xlsx);
                MemoryStream PDFStream = new MemoryStream();
                workbook.ExportToPdf(PDFStream);
                PDFStream.Seek(0, SeekOrigin.Begin);

                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.BufferOutput = true;
                response.ContentType = "application/pdf";
                response.AppendHeader("content-disposition", "Job Order No. " + JobOrderNo + ".pdf");
                byte[] fileToDownload = PDFStream.ToArray();
                response.BinaryWrite(fileToDownload);
                response.Flush();
                response.End();
            }
        }
        catch (Exception ex)
        {
            GeneralTask.AddMessageLog(MessageLogApplication.Portal, MessageLogModules.Common, MessageLogType.Error, MethodBase.GetCurrentMethod().Name, ex);
        }
        finally
        {
            ServiceHelper.CloseService(commonService);
        }
    }
}

The response object show different behavior to different browser.
Like for:

Chrome: File some time opened and some time unable to open the file.

Mozilla: File never opened and give me error:

C:\Users\tach\AppData\Local\Temp\nJ0oODH4.pdf.part could not be saved,
  because the source file could not be read.

Try again later, or contact the server administrator.

Response Header in Mozilla:

Cache-Control: private

  Transfer-Encoding: chunked Content-Type:

  application/pdf Server: Microsoft-IIS/10.0

  Content-Disposition: Job
  Order No. ad_0003.pdf

  X-AspNet-Version: 4.0.30319 X-SourceFiles:
  =?UTF-8?B?RzpcRm1zMlRmc1xGTVNPZmZpY2UtVjEwNi1UcnVua1xGTVNQb3J0YWxcRGFzaGJvYXJkU2VydmljZS5zdmNcUHJpbnRhYmxlSm9iT3JkZXJEb2N1bWVudA==?=
  X-Powered-By: ASP.NET Access-Control-Allow-Origin: * Date: Thu, 08 Jun
  2017 09:48:00 GMT

Microsoft Edge: File never open.

I have the checked all the browsers Network tab and in header response file, file type, file name available but unable to open the file.

Update:

Below given AppHeader works for Chrome but not for Firefox or Edge.

response.AppendHeader("content-disposition", "inline; \"Job Order No " + JobOrderNo + ".pdf\"");

and

response.AppendHeader("content-disposition", "Job Order No. " + JobOrderNo + ".pdf");

Body:
Change:

response.AppendHeader("content-disposition", "Job Order No. " + JobOrderNo + ".pdf");

to:

response.AppendHeader("Content-Disposition", "inline; \"Job Order No " + JobOrderNo + ".pdf\"");

Does that help?


问:
Check if date is free with SQL query
I need to check if the time that I'm choosing is free.
So as example the time that is between 17:00 - 17:06 is taken and I try to take time that is between 17:01 - 17:07
What would be the right SQL query to check if time is free or taken? Because in this situation 17:01,17:02,17:03 times are taken.

In database I have two fields laikas that means the start of the time that is taken(17:00), and laikas_end that means the end of taken time(17:07)

As far I got these queries:
To check if the time that I'm taking isn'bt between that time that is taken

```<code>$uzimtumas_laiko = "SELECT * FROM reklamos WHERE `laikas` >= '$laikas' AND `laikas_end` <= '$laikas_end'";
</code>```

To check if the start time and end time matches (that means it is taken):

```<code>$uzimtumas_laiko = "SELECT * FROM reklamos WHERE `laikas` = '$laikas' OR `laikas_end` = '$laikas_end'";
</code>```

The situation can be that I try to take time between 16:49 - 17:02, but 17:00 - 17:06 is taken. So 17:50-17:02 can't be chosen. I belive that I need something with BETWEEN but can't think out anything.

答:
I believe the following is a more efficient way to do what you want:

```<code>SELECT *
FROM reklamos
WHERE
liakas <= '$liakas_end' AND
liakas_end >= '$liakas'
</code>```

I think of this as checking for an "overlap" between the time slots.

Title: Check if date is free with SQL query

Body:
I need to check if the time that I'm choosing is free.
So as example the time that is between 17:00 - 17:06 is taken and I try to take time that is between 17:01 - 17:07
What would be the right SQL query to check if time is free or taken? Because in this situation 17:01,17:02,17:03 times are taken.

In database I have two fields laikas that means the start of the time that is taken(17:00), and laikas_end that means the end of taken time(17:07)

As far I got these queries:
To check if the time that I'm taking isn'bt between that time that is taken

$uzimtumas_laiko = "SELECT * FROM reklamos WHERE `laikas` >= '$laikas' AND `laikas_end` <= '$laikas_end'";

To check if the start time and end time matches (that means it is taken):

$uzimtumas_laiko = "SELECT * FROM reklamos WHERE `laikas` = '$laikas' OR `laikas_end` = '$laikas_end'";

The situation can be that I try to take time between 16:49 - 17:02, but 17:00 - 17:06 is taken. So 17:50-17:02 can't be chosen. I belive that I need something with BETWEEN but can't think out anything.

Body:
I believe the following is a more efficient way to do what you want:

SELECT *
FROM reklamos
WHERE
liakas <= '$liakas_end' AND
liakas_end >= '$liakas'

I think of this as checking for an "overlap" between the time slots.


问:
How to Use Virtual Mode for large data in DataGridView
I am posting to see if there is a way to improve some legacy code. The code will populate a DataGridView with x amount of rows. Initially, the code worked fine as the populating data was of a small quantity. However, there has been an extreme increase in data and I am finding that the performance in populating the DataGridView to be very slow.

Basically, I know there are several considerations (Virtual Mode, for instance). However, the approach that I want to take is using an array or List (and then convert it to an array) and add the range of the row by calling Rows.AddRange(array). However, I am having trouble implementing it.

As it stands, this is what code exists:

```<code>if (value !=0)
{
 int row = 0;
 dataGridView1.AddRow();
 dataGridView1.Rows[row].Cells[0] = "Test";
 dataGridView1.Rows[row].Cells[1] = 9;
 dataGridView1.Rows[row].Cells[2] = "Test Two";
 dataGridView1.Rows[row].Cells[3] = "Test Three";
 row++;
}

if (valueTwo !=0)
{
 dataGridView1.AddRow();
 dataGridView1.Rows[row].Cells[0] = "Test";
 dataGridView1.Rows[row].Cells[1] = 9;
 dataGridView1.Rows[row].Cells[2] = "Test Two";
 dataGridView1.Rows[row].Cells[3] = "Test Three";
 row++;
}
</code>```

So, this is not efficient at all, of course. I know .AddRow() is a taxing method in itself and individually adding rows, one-by-one is not great.

I have tried something like:

```<code>object[] data = {"Test", 9, "Test Two", "Test Three"};
List<DataGridViewRow> list = new List<DataGridViewRow>();
for (int i = 0; i < data.Length; i++)
{
  DataGridViewRow row = new DataGridViewRow();
  row.SetValues(data[i]);
  list.Add(row);
 }
 dataGridViewRow1.Rows.AddRange(list.ToArray());
</code>```

However, doing this gets me a NullPointerException on the SetValues line.

I understand that the best way of doing this is either make a DataTable or use Virtual Mode but I want to try out using this method of adding the range and passing in a container for the data, rather than adding a row.

I hope I am clear with my explanation. Let me know if I need to further explain.

EDIT: I think using Virtual Mode is the best way to go. I am not sure how to really do it, though. I checked MSN's tutorial but I was slightly confused by it. If I were to implement Virtual Mode for 100,000 rows, how would I go about doing it. Nothing really fancy, just displaying a total of 10,000 rows.

答:
for your case you need to add columns before rows,</p>

```<code>object[] data = { "Test", 9, "Test Two", "Test Three" };

            dataGridView1.Columns.Add("Name", "Name");
            dataGridView1.Columns.Add("No", "Number");
            dataGridView1.Columns.Add("Desc", "Description1");
            dataGridView1.Columns.Add("Desc1", "Description2");

            for (int i = 0; i < 10; i++)
                dataGridView1.Rows.Add(data);
</code>```

Body:
I am posting to see if there is a way to improve some legacy code. The code will populate a DataGridView with x amount of rows. Initially, the code worked fine as the populating data was of a small quantity. However, there has been an extreme increase in data and I am finding that the performance in populating the DataGridView to be very slow.

Basically, I know there are several considerations (Virtual Mode, for instance). However, the approach that I want to take is using an array or List (and then convert it to an array) and add the range of the row by calling Rows.AddRange(array). However, I am having trouble implementing it.

As it stands, this is what code exists:

if (value !=0)
{
 int row = 0;
 dataGridView1.AddRow();
 dataGridView1.Rows[row].Cells[0] = "Test";
 dataGridView1.Rows[row].Cells[1] = 9;
 dataGridView1.Rows[row].Cells[2] = "Test Two";
 dataGridView1.Rows[row].Cells[3] = "Test Three";
 row++;
}

if (valueTwo !=0)
{
 dataGridView1.AddRow();
 dataGridView1.Rows[row].Cells[0] = "Test";
 dataGridView1.Rows[row].Cells[1] = 9;
 dataGridView1.Rows[row].Cells[2] = "Test Two";
 dataGridView1.Rows[row].Cells[3] = "Test Three";
 row++;
}

So, this is not efficient at all, of course. I know .AddRow() is a taxing method in itself and individually adding rows, one-by-one is not great.

I have tried something like:

object[] data = {"Test", 9, "Test Two", "Test Three"};
List<DataGridViewRow> list = new List<DataGridViewRow>();
for (int i = 0; i < data.Length; i++)
{
  DataGridViewRow row = new DataGridViewRow();
  row.SetValues(data[i]);
  list.Add(row);
 }
 dataGridViewRow1.Rows.AddRange(list.ToArray());

However, doing this gets me a NullPointerException on the SetValues line.

I understand that the best way of doing this is either make a DataTable or use Virtual Mode but I want to try out using this method of adding the range and passing in a container for the data, rather than adding a row.

I hope I am clear with my explanation. Let me know if I need to further explain.

EDIT: I think using Virtual Mode is the best way to go. I am not sure how to really do it, though. I checked MSN's tutorial but I was slightly confused by it. If I were to implement Virtual Mode for 100,000 rows, how would I go about doing it. Nothing really fancy, just displaying a total of 10,000 rows.

Body:
for your case you need to add columns before rows,

object[] data = { "Test", 9, "Test Two", "Test Three" };

            dataGridView1.Columns.Add("Name", "Name");
            dataGridView1.Columns.Add("No", "Number");
            dataGridView1.Columns.Add("Desc", "Description1");
            dataGridView1.Columns.Add("Desc1", "Description2");

            for (int i = 0; i < 10; i++)
                dataGridView1.Rows.Add(data);


问:
Undefined index // php
I'm stuck in my php script for a blog where I want to display the time and date for all the articles. I created a function but I don't know why it doesn't want to work:

```<code>function articles(){
    global $bdd;

    $articles = $bdd->query("SELECT id, titre, accroche, contenu, publication, image FROM articles");
    $articles = $articles->fetchAll();

    return $articles;
}

function formattage_date($publication){
    $publication = explode(" ", $publication);
    $date = explode("-", $publication[0]);
    $heure = explode(":", $publication[1]);

    $mois = ["", "janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "decembre"];

    $resultat = $date[2] . ' ' . $mois[$date[1]] . ' ' . $date[0] . ' à ' . $heure[0] . 'h' . $heure[1];

    return $resultat;

}
</code>```

When I want to use $mois, php says: Notice: Undefined index: 03 in C:\wamp\www\entertheletter.dev\fonctions\blog.php on line 18

答:
you can try this function where i have added ltrim function in $mois array we have to converted 01 to 0 because array index start from 0,1,2 ...

so we have to remove 0 from 01.

```<code> function formattage_date($publication){
  $publication = explode(" ", $publication);
  $date = explode("-", $publication[0]);
  $heure = explode(":", $publication[1]);

  $mois = ["", "janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "decembre"];

  $resultat = $date[2] . ' ' . $mois[ltrim($date[1],0)] . ' ' . $date[0] . ' à ' . $heure[0] . 'h' . $heure[1];

return $resultat;

}
</code>```

Title: Undefined index // php

Body:
I'm stuck in my php script for a blog where I want to display the time and date for all the articles. I created a function but I don't know why it doesn't want to work:

function articles(){
    global $bdd;

    $articles = $bdd->query("SELECT id, titre, accroche, contenu, publication, image FROM articles");
    $articles = $articles->fetchAll();

    return $articles;
}

function formattage_date($publication){
    $publication = explode(" ", $publication);
    $date = explode("-", $publication[0]);
    $heure = explode(":", $publication[1]);

    $mois = ["", "janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "decembre"];

    $resultat = $date[2] . ' ' . $mois[$date[1]] . ' ' . $date[0] . ' à ' . $heure[0] . 'h' . $heure[1];

    return $resultat;

}

When I want to use $mois, php says: Notice: Undefined index: 03 in C:\wamp\www\entertheletter.dev\fonctions\blog.php on line 18

Body:
you can try this function where i have added ltrim function in $mois array we have to converted 01 to 0 because array index start from 0,1,2 ...

so we have to remove 0 from 01.

 function formattage_date($publication){
  $publication = explode(" ", $publication);
  $date = explode("-", $publication[0]);
  $heure = explode(":", $publication[1]);

  $mois = ["", "janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "decembre"];

  $resultat = $date[2] . ' ' . $mois[ltrim($date[1],0)] . ' ' . $date[0] . ' à ' . $heure[0] . 'h' . $heure[1];

return $resultat;

}


问:
Java classes not accessible
I am trying to build a dynamic web app using Eclipse Helios. I am trying to use a java class inside a jsp page. The page is visible during coding and deployment. In the runtime the java classes are not resolved to a type. Why does this happen?

Update:
Directory structure as in eclipse

```<code> Restarunt JAX-WS Web Services
 Deploymment Descriptor Java
 Resources:src
     default package
       LoginBean build WebContent    WebINF
      lib
      web.xml
      weblogic.xml jsp files
</code>```

答:
Classes in the default package are invisible/unimportable by classes in a package. JSP files end up as a class in a package, so it will be invisible to JSP as well. This works in very specific (Tomcat) environments only, you don't want to be dependent on that. Just put classes in a package. Always.

Unrelated to the problem, writing Java code in a JSP is a poor practice. Use a Servlet.

Title: Java classes not accessible

Body:
I am trying to build a dynamic web app using Eclipse Helios. I am trying to use a java class inside a jsp page. The page is visible during coding and deployment. In the runtime the java classes are not resolved to a type. Why does this happen?

Update:
Directory structure as in eclipse

 Restarunt JAX-WS Web Services
 Deploymment Descriptor Java
 Resources:src
     default package
       LoginBean build WebContent    WebINF
      lib
      web.xml
      weblogic.xml jsp files


问:
Excel - extract unique values from a column with several values in each cell
I have a list of publishers in a column.
I need to extract unique publishers into a separate list, like so:

```<code>PLoS
Nature
IMA
NAoS
Elsevier
PLoS
T&F, Ebsco
ONCOTARGET
Oxford, ProQuest
Nature
Elsevier, ProQuest
ACS
Springer
Ebsco/ProQuest
PLoS
Elsevier
Nature
</code>```

Needs to become:

```<code>PLoS
Nature
IMA
NAoS
Elsevier
T&F
Ebsco
ONCOTARGET
Oxford
ProQuest
ACS
Spring
</code>```

As you can see, in lines where there were several publishers, I need to count them all uniquely.

Is this possible?

答:
This short macro both parses the data and removes duplicates:

```<code>Sub dural()
    Dim K As Long, i As Long, N As Long
    Dim ary, a

    K = 1
    N = Cells(Rows.Count, "A").End(xlUp).Row

    ary = Range("A1:A" & N)

    For Each a In ary
        a = Replace(a, ", ", "/")
        If InStr(1, a, "/") > 0 Then
            bry = Split(a, "/")
                For Each b In bry
                    Cells(K, 2) = b
                    K = K + 1
                Next b
        Else
            Cells(K, 2).Value = a
            K = K + 1
        End If
    Next a

    Range("B:B").RemoveDuplicates Columns:=1, Header:=xlNo
End Sub
</code>```

Body:
I have a list of publishers in a column.
I need to extract unique publishers into a separate list, like so:

PLoS
Nature
IMA
NAoS
Elsevier
PLoS
T&F, Ebsco
ONCOTARGET
Oxford, ProQuest
Nature
Elsevier, ProQuest
ACS
Springer
Ebsco/ProQuest
PLoS
Elsevier
Nature

Needs to become:

PLoS
Nature
IMA
NAoS
Elsevier
T&F
Ebsco
ONCOTARGET
Oxford
ProQuest
ACS
Spring

As you can see, in lines where there were several publishers, I need to count them all uniquely.

Is this possible?

Body:
This short macro both parses the data and removes duplicates:

Sub dural()
    Dim K As Long, i As Long, N As Long
    Dim ary, a

    K = 1
    N = Cells(Rows.Count, "A").End(xlUp).Row

    ary = Range("A1:A" & N)

    For Each a In ary
        a = Replace(a, ", ", "/")
        If InStr(1, a, "/") > 0 Then
            bry = Split(a, "/")
                For Each b In bry
                    Cells(K, 2) = b
                    K = K + 1
                Next b
        Else
            Cells(K, 2).Value = a
            K = K + 1
        End If
    Next a

    Range("B:B").RemoveDuplicates Columns:=1, Header:=xlNo
End Sub


问:
Scan C disk and copy files
I would appreciate some help here.

The Powershell script should close Outlook process which works.

Aswell as scan C disk for .pst files which works.

Copy these files to "\fileserver01\temp\test\"

Export to csv/excel list where these files where located and last write time.

Possible hide error messages for the user when running the script since it complains about not full access on a few folders when running the scan.

Code:

```<code>Get-Process outlook | Foreach-Object { $_.CloseMainWindow() }

Get-ChildItem -path c:\ -recurse -include *.pst | `
Copy-Item -destination "\\fileserver01\temp\test\" | `
Select-object fullname,lastwritetime|export-csv "\\fileserver01\temp\test\"
</code>```

How should I fix the last couple of things on my list?
Thanks

答:
This is the final code.
Thanks everyone for your support.</p>

```<code>#Kill Oulook process
Get-Process outlook -ErrorAction SilentlyContinue |   Foreach-Object { $_.CloseMainWindow() }

#Scan for .pst files on the C disk
Get-ChildItem -path c:\ -recurse -include *.pst -ErrorAction SilentlyContinue |

#Copy located .pst files to the destination
Copy-Item -Destination "\\networkpath\home\$env:username\ComputerChange\" -Verbose -PassThru -ErrorAction SilentlyContinue |

#Log where files were located and when they were last written to.
Select-Object fullname,lastwritetime | export-csv \\networkpath\home\$env:username\ComputerChange\PSTlog.csv -Verbose

Write-Host "PST Files have successfully been copied, press any key to close" -ErrorAction SilentlyContinue
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
end
</code>```

Title: Scan C disk and copy files

Body:
I would appreciate some help here.

The Powershell script should close Outlook process which works.

Aswell as scan C disk for .pst files which works.

Copy these files to "\fileserver01\temp\test\"

Export to csv/excel list where these files where located and last write time.

Possible hide error messages for the user when running the script since it complains about not full access on a few folders when running the scan.

Code:

Get-Process outlook | Foreach-Object { $_.CloseMainWindow() }

Get-ChildItem -path c:\ -recurse -include *.pst | `
Copy-Item -destination "\\fileserver01\temp\test\" | `
Select-object fullname,lastwritetime|export-csv "\\fileserver01\temp\test\"

How should I fix the last couple of things on my list?
Thanks

Body:
This is the final code.
Thanks everyone for your support.

#Kill Oulook process
Get-Process outlook -ErrorAction SilentlyContinue |   Foreach-Object { $_.CloseMainWindow() }

#Scan for .pst files on the C disk
Get-ChildItem -path c:\ -recurse -include *.pst -ErrorAction SilentlyContinue |

#Copy located .pst files to the destination
Copy-Item -Destination "\\networkpath\home\$env:username\ComputerChange\" -Verbose -PassThru -ErrorAction SilentlyContinue |

#Log where files were located and when they were last written to.
Select-Object fullname,lastwritetime | export-csv \\networkpath\home\$env:username\ComputerChange\PSTlog.csv -Verbose

Write-Host "PST Files have successfully been copied, press any key to close" -ErrorAction SilentlyContinue
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
end


问:
Show XY Plot with only one value in Androidplot
I am using Androidplot to display real time data. The real time data is dynamic and the x axis is time. The domain is a fixed timespan. Because the values could be any double, rangeStepMode is set to subdivide the y-axis. The issue is that when all the values are the same, the plot does not draw correctly.

You can see in the image that there are no range grids or labels.

From this related question:

This happens because Androidplot does not have enough information to automatically calculate what a reasonable domain/range scale would be from a single point.

This makes sense, and the linked solution of setting a non-zero range boundary works but instead of an arbitrary range like miny - 1to maxy + 1, I'd like for there to be only one labeled range line in these cases across the middle of the screen.

My Activity:

```<code>public class SimpleXYPlotActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_xy_plot_example);
        XYPlot plot = (XYPlot) findViewById(R.id.plot);
        Number[] series1Numbers = new Number[]{
                1,
                1,
        };
        XYSeries series1 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Series1", series1Numbers);
        LineAndPointFormatter series1Format = new LineAndPointFormatter(Color.RED, Color.GREEN, null, null);
        plot.addSeries(series1, series1Format);

        StepMode stepMode = StepMode.SUBDIVIDE;
        int stepValue = 10;
        plot.setRangeStepMode(stepMode);
        plot.setRangeStepValue(stepValue);
    }
}
</code>```

My Layout:

```<code><com.androidplot.xy.XYPlot
    android:id="@+id/plot"
    style="@style/APDefacto.Dark"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    ap:rangeStep="5"
    ap:rangeStepMode="subdivide"
    ap:domainStep="1"
    ap:domainStepMode="increment_by_val"
    />
</code>```

What I've tried

The following works on the simple xy example, but when I try setting it within minmax in my time series class, the thread drawing the domain gridlines gets into a very long loop as it calculates xPix to be very very large. This also isn't a very solution for situations where I have multiple series. Any ideas on how I can get the results I want?

```<code>    Double minY = null;
    Double maxY = null;
    for (Double aDouble : series1Numbers) {
        if (minY == null) {
            minY = aDouble;
        } else {
            minY = Math.min(minY, aDouble);
        }
        if (maxY == null) {
            maxY = aDouble;
        } else {
            maxY = Math.max(maxY, aDouble);
        }
    }
    if (minY.equals(maxY)) {
        plot.setUserRangeOrigin(minY);
        plot.setRangeBoundaries(0, 2 * maxY, BoundaryMode.FIXED);
        plot.setRangeStepMode(StepMode.INCREMENT_BY_PIXELS);
        plot.setRangeStepValue(Double.POSITIVE_INFINITY);
    } else {
        plot.setUserRangeOrigin(0);
        plot.setRangeBoundaries(minY, maxY, BoundaryMode.FIXED);
        plot.setRangeStepMode(StepMode.SUBDIVIDE);
        plot.setRangeStepValue(5);
    }
</code>```

答:
This wont get rid of the CPU overhead but you can use PlotUtils.minMax to find these values for you

If implementing and using FastXYSeries is a possibility for you then the overhead of using minMax drops away too, as the calculation only ever gets done when your XYSeries data changes.

Body:
I am using Androidplot to display real time data. The real time data is dynamic and the x axis is time. The domain is a fixed timespan. Because the values could be any double, rangeStepMode is set to subdivide the y-axis. The issue is that when all the values are the same, the plot does not draw correctly.

You can see in the image that there are no range grids or labels.

From this related question:

This happens because Androidplot does not have enough information to automatically calculate what a reasonable domain/range scale would be from a single point.

This makes sense, and the linked solution of setting a non-zero range boundary works but instead of an arbitrary range like miny - 1to maxy + 1, I'd like for there to be only one labeled range line in these cases across the middle of the screen.

My Activity:

public class SimpleXYPlotActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_xy_plot_example);
        XYPlot plot = (XYPlot) findViewById(R.id.plot);
        Number[] series1Numbers = new Number[]{
                1,
                1,
        };
        XYSeries series1 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Series1", series1Numbers);
        LineAndPointFormatter series1Format = new LineAndPointFormatter(Color.RED, Color.GREEN, null, null);
        plot.addSeries(series1, series1Format);

        StepMode stepMode = StepMode.SUBDIVIDE;
        int stepValue = 10;
        plot.setRangeStepMode(stepMode);
        plot.setRangeStepValue(stepValue);
    }
}

My Layout:

<com.androidplot.xy.XYPlot
    android:id="@+id/plot"
    style="@style/APDefacto.Dark"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    ap:rangeStep="5"
    ap:rangeStepMode="subdivide"
    ap:domainStep="1"
    ap:domainStepMode="increment_by_val"
    />

What I've tried

The following works on the simple xy example, but when I try setting it within minmax in my time series class, the thread drawing the domain gridlines gets into a very long loop as it calculates xPix to be very very large. This also isn't a very solution for situations where I have multiple series. Any ideas on how I can get the results I want?

    Double minY = null;
    Double maxY = null;
    for (Double aDouble : series1Numbers) {
        if (minY == null) {
            minY = aDouble;
        } else {
            minY = Math.min(minY, aDouble);
        }
        if (maxY == null) {
            maxY = aDouble;
        } else {
            maxY = Math.max(maxY, aDouble);
        }
    }
    if (minY.equals(maxY)) {
        plot.setUserRangeOrigin(minY);
        plot.setRangeBoundaries(0, 2 * maxY, BoundaryMode.FIXED);
        plot.setRangeStepMode(StepMode.INCREMENT_BY_PIXELS);
        plot.setRangeStepValue(Double.POSITIVE_INFINITY);
    } else {
        plot.setUserRangeOrigin(0);
        plot.setRangeBoundaries(minY, maxY, BoundaryMode.FIXED);
        plot.setRangeStepMode(StepMode.SUBDIVIDE);
        plot.setRangeStepValue(5);
    }


问:
creating a literal for a Point - C++
I am trying to do a simple library where the object is a point on the xy-axis.

I want to be able to use literals like this:

Point a = (3,4);

where (3,4) is a point literal.

I read about user defined literals, but (as I understood) this seems to be impossible.

May be "(3,4)"_P is possible as I understand it.

However, I found on this page interesting use of user defined literals as follows:

```<code>#include <iostream>
#include <complex>

int main()
{
    using namespace std::complex_literals;
    std::complex<double> c = 1.0 + 1i;
    std::cout << "abs" << c << " = " << abs(c) << '\n';
}
</code>```

I can under stand the part 1i as a user defined literal, but not the whole thing 1.0 + 1i.

What I am missing, and what is the nearest possible way of getting a literal similar to (x,y) without using ".

答:
You have 3 options</p>

```<code>Point p = { 1,2 };
Point p2{ 1,2 };
Point p3(1,2);
</code>```

Title: creating a literal for a Point - C++

Body:
I am trying to do a simple library where the object is a point on the xy-axis.

I want to be able to use literals like this:

Point a = (3,4);

where (3,4) is a point literal.

I read about user defined literals, but (as I understood) this seems to be impossible.

May be "(3,4)"_P is possible as I understand it.

However, I found on this page interesting use of user defined literals as follows:

#include <iostream>
#include <complex>

int main()
{
    using namespace std::complex_literals;
    std::complex<double> c = 1.0 + 1i;
    std::cout << "abs" << c << " = " << abs(c) << '\n';
}

I can under stand the part 1i as a user defined literal, but not the whole thing 1.0 + 1i.

What I am missing, and what is the nearest possible way of getting a literal similar to (x,y) without using ".

Body:
You have 3 options

Point p = { 1,2 };
Point p2{ 1,2 };
Point p3(1,2);