问:
ListView Interference with AppBarLayout
My problem with ListView

ListView Interference with AppBarLayout

I want to be under the AppBarLayout

progressbar in center page

problem screenshot

How to App bar Title and back button to Right?

activity_category.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_category"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.sokhanak.CategoryActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="?attr/colorPrimary" />

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v4.widget.ContentLoadingProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|center_vertical"
        android:visibility="visible" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</FrameLayout>
</LinearLayout>
</code>```

CategoryActivity.java

```<code>package com.example;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.adapter.QuoteArrayAdapter;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class CategoryActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ListView listView;
    private ArrayList<QuoteDataModel> list;
    private QuoteArrayAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);

        Intent i = getIntent();
        final String categoryId = i.getStringExtra("categoryId");
        String categoryName = i.getStringExtra("categoryName");

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle(categoryName);

        /**
         * Array List for Binding Data from JSON to this List
         */
        list = new ArrayList<>();

        adapter = new QuoteArrayAdapter(this, list);

        /**
         * Getting List and Setting List Adapter
         */
        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Snackbar.make(findViewById(R.id.parentLayout), list.get(position).getProfileName() + " => " + list.get(position).getQuoteLike(), Snackbar.LENGTH_LONG).show();
            }
        });

        /**
         * Check internet connection
         */
        if (!MainActivity.NetworkUtil.isOnline(getApplicationContext())) {
            Toast.makeText(CategoryActivity.this, "اتصال به اینترنت برقرار نیست",
                    Toast.LENGTH_LONG).show();
        }

        new GetDataCategory().execute(categoryId);

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {

            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {

                if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
                {
                    new GetDataCategory().execute(categoryId);
                }
            }
        });

        // screen turn on ever
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }

/* */
}
</code>```

答:
```<code>    For putting list below app bar you need to update listview layout with below app bar.
    Here is the updated code.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/activity_category"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.sokhanak.CategoryActivity"
        >
        <android.support.design.widget.AppBarLayout
            android:id="@+id/appBarLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="56dp"
                android:background="?attr/colorPrimary"
                />

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.ContentLoadingProgressBar
            android:id="@+id/progress"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="visible" />

        <ListView app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:id="@+id/listView"
            android:layout_below="@+id/appBarLayout"
            android:layout_width="fill_parent"
            android:layout_height="match_parent" />

    </RelativeLayout>
</code>```

Title: ListView Interference with AppBarLayout

Body:
My problem with ListView

ListView Interference with AppBarLayout

I want to be under the AppBarLayout

progressbar in center page

problem screenshot

How to App bar Title and back button to Right?

activity_category.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_category"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.sokhanak.CategoryActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="?attr/colorPrimary" />

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v4.widget.ContentLoadingProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|center_vertical"
        android:visibility="visible" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</FrameLayout>
</LinearLayout>

CategoryActivity.java

package com.example;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.adapter.QuoteArrayAdapter;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class CategoryActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ListView listView;
    private ArrayList<QuoteDataModel> list;
    private QuoteArrayAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);

        Intent i = getIntent();
        final String categoryId = i.getStringExtra("categoryId");
        String categoryName = i.getStringExtra("categoryName");

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle(categoryName);

        /**
         * Array List for Binding Data from JSON to this List
         */
        list = new ArrayList<>();

        adapter = new QuoteArrayAdapter(this, list);

        /**
         * Getting List and Setting List Adapter
         */
        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Snackbar.make(findViewById(R.id.parentLayout), list.get(position).getProfileName() + " => " + list.get(position).getQuoteLike(), Snackbar.LENGTH_LONG).show();
            }
        });

        /**
         * Check internet connection
         */
        if (!MainActivity.NetworkUtil.isOnline(getApplicationContext())) {
            Toast.makeText(CategoryActivity.this, "اتصال به اینترنت برقرار نیست",
                    Toast.LENGTH_LONG).show();
        }

        new GetDataCategory().execute(categoryId);

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {

            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {

                if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
                {
                    new GetDataCategory().execute(categoryId);
                }
            }
        });

        // screen turn on ever
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }

/* */
}


来源: stackexchange

问:
How generate a cloudinary URL from the rails controller
I'm Using rails and the cloudinary's gem with carrierwave. I would like make a URL from the controller:

```<code>url = myModel.url_field
options = { width: 200 }
Cloudinary::Utils.cloudinary_url(url, options)
</code>```

But I only get the URL without the crop options

(The urls are only examples)

http://res.cloudinary.com/cloud/image/upload/v1458860591/logos/20160324170310.jpg

There is one way to get the url?
like:

http://res.cloudinary.com/cloud/image/upload/w_200/v1458860591/logos/20160324170310.jpg

答:
After some more searching I found an answer that's working for me in python, the same should work for the ruby version.

Basically, don't pass the width inside the options, place it directly:

```<code>Cloudinary::Utils.cloudinary_url(url, width=200)
</code>```

This should give you the url with the width in it :)

ContentLicense: CC BY-SA 3.0

Body:
I'm Using rails and the cloudinary's gem with carrierwave. I would like make a URL from the controller:

url = myModel.url_field
options = { width: 200 }
Cloudinary::Utils.cloudinary_url(url, options)

But I only get the URL without the crop options

(The urls are only examples)

http://res.cloudinary.com/cloud/image/upload/v1458860591/logos/20160324170310.jpg

There is one way to get the url?
like:

http://res.cloudinary.com/cloud/image/upload/w_200/v1458860591/logos/20160324170310.jpg

Body:
After some more searching I found an answer that's working for me in python, the same should work for the ruby version.

Basically, don't pass the width inside the options, place it directly:

Cloudinary::Utils.cloudinary_url(url, width=200)

This should give you the url with the width in it :)


问:
How Can I Restart The Redis Server If It Goes Down Automatically using a script?
Redis has master slave configuration.If the master goes down,slave becomes the new master.How can i restart the previous redis master ( as a slave of new master or if it again become master that's fine ) using a script.I don't want to do it manually.</p>

答:
This can be done using a small script. Make a watcher script that keeps pinging REDIS at port 6379 and if it fails. Just restart the server using redis-server command. </p>

```<code>#!/bin/bash
a=$(redis-cli -p 6379 PING)
if [ "$a" = "PONG" ]
then
    echo 'Already running'
else
    b=$(/etc/init.d/redis_6379 start)
    echo $b
fi
</code>```

<p>Now schedule this script in crontab for everyone minute. </p>

Body:
This can be done using a small script. Make a watcher script that keeps pinging REDIS at port 6379 and if it fails. Just restart the server using redis-server command.

#!/bin/bash
a=$(redis-cli -p 6379 PING)
if [ "$a" = "PONG" ]
then
    echo 'Already running'
else
    b=$(/etc/init.d/redis_6379 start)
    echo $b
fi

Now schedule this script in crontab for everyone minute.


问:
CustomView dependency injection with dagger 2 (within activity scope)
My question is similar to this.

So for instance, I have a LiveData implementation:

```<code>public class CustomLiveData extends LiveData<SomeEvent> {

    @Inject
    public CustomLiveData(@ActivityContext Context context) {
        //....
    }

}
</code>```

that I want to inject into a custom view:

```<code>public class CustomView extends View {
   @Inject
   SomeApplicationProvider anyProvider;

   @Inject
   CustomLiveData dataProvider;
   // Getting @com.di.qualifiers.ActivityContext  android.content.Context cannot be provided without an @Provides-annotated method.
   // @com.di.qualifiers.ActivityContext android.content.Context is injected at com.repositories.CustomLiveData.<init>(context)
   // com.repositories.CustomLiveData is injected at com.ui.CustomView.dataProvider com.ui.CustomView is injected at
   // com.di.ApplicationComponent.inject(view)

   public CustomView(Context context) { this(context, null); }
   public CustomView(Context AttributeSet attrs) {
      super(context, attrs);

      // Works ok for application provider
      Application.getComponent(context).inject(this);
   }
}
</code>```

And here is the rest of DI classes:

```<code>@ApplicationScope
@Component(
        modules = {AndroidInjectionModule.class,
                ActivityBuilder.class
        })

public interface ApplicationComponent extends AndroidInjector<MyApp> {

    void inject(MyApp application);

    void inject(CustomView view);

    @Component.Builder
    abstract class Builder extends AndroidInjector.Builder<MyApp> {

        public abstract ApplicationComponent build();
    }
}

@ActivityScope
@Module (subcomponents = MainActivitySubcomponent.class)
public abstract class ActivityBuilder {

    @Binds
    @IntoMap
    @ActivityKey(MainActivity.class)
    abstract AndroidInjector.Factory<? extends Activity>
    bindActivityInjectorFactory(MainActivitySubcomponent.Builder builder);

    //...

}

@Subcomponent(modules = {MainActivityModule.class})
public interface MainActivitySubcomponent extends AndroidInjector<MainActivity> {

    @Subcomponent.Builder
    abstract class Builder extends AndroidInjector.Builder<MainActivity> {

    }
}

@ActivityScope
@Module
public class MainActivityModule {

    @Provides
    @ActivityContext
    public Context provideActivityContext(MainActivity activity) {
        return activity;
    }

    // Seems to be wrong or not enough!?
    @Provides
    public CustomLiveData provideCustomLiveData(@ActivityContext Context context) {
        return new CustomLiveData(context);
    }
}

@Qualifier
public @interface ActivityContext{
}
</code>```

Note, that I don't get any compiler complaints if CustomLiveData is injected into MainActivity instead into the view.
Thanks!

答:
Your Dagger hierarchy looks like this:
appcomponent -> activitycomponent

You try to inject activity context inside view, that depends on appcomponent directly.

It's not possible since there is no method that could provide activity context in appcomponent. Instead, inside view, you should retrieve activity  (for example using getContext), extract activitycomponent from it and only then inject CustomLiveData.

Body:
My question is similar to this.

So for instance, I have a LiveData implementation:

public class CustomLiveData extends LiveData<SomeEvent> {

    @Inject
    public CustomLiveData(@ActivityContext Context context) {
        //....
    }

}

that I want to inject into a custom view:

public class CustomView extends View {
   @Inject
   SomeApplicationProvider anyProvider;

   @Inject
   CustomLiveData dataProvider;
   // Getting @com.di.qualifiers.ActivityContext  android.content.Context cannot be provided without an @Provides-annotated method.
   // @com.di.qualifiers.ActivityContext android.content.Context is injected at com.repositories.CustomLiveData.<init>(context)
   // com.repositories.CustomLiveData is injected at com.ui.CustomView.dataProvider com.ui.CustomView is injected at
   // com.di.ApplicationComponent.inject(view)

   public CustomView(Context context) { this(context, null); }
   public CustomView(Context AttributeSet attrs) {
      super(context, attrs);

      // Works ok for application provider
      Application.getComponent(context).inject(this);
   }
}

And here is the rest of DI classes:

@ApplicationScope
@Component(
        modules = {AndroidInjectionModule.class,
                ActivityBuilder.class
        })

public interface ApplicationComponent extends AndroidInjector<MyApp> {

    void inject(MyApp application);

    void inject(CustomView view);

    @Component.Builder
    abstract class Builder extends AndroidInjector.Builder<MyApp> {

        public abstract ApplicationComponent build();
    }
}

@ActivityScope
@Module (subcomponents = MainActivitySubcomponent.class)
public abstract class ActivityBuilder {

    @Binds
    @IntoMap
    @ActivityKey(MainActivity.class)
    abstract AndroidInjector.Factory<? extends Activity>
    bindActivityInjectorFactory(MainActivitySubcomponent.Builder builder);

    //...

}

@Subcomponent(modules = {MainActivityModule.class})
public interface MainActivitySubcomponent extends AndroidInjector<MainActivity> {

    @Subcomponent.Builder
    abstract class Builder extends AndroidInjector.Builder<MainActivity> {

    }
}

@ActivityScope
@Module
public class MainActivityModule {

    @Provides
    @ActivityContext
    public Context provideActivityContext(MainActivity activity) {
        return activity;
    }

    // Seems to be wrong or not enough!?
    @Provides
    public CustomLiveData provideCustomLiveData(@ActivityContext Context context) {
        return new CustomLiveData(context);
    }
}

@Qualifier
public @interface ActivityContext{
}

Note, that I don't get any compiler complaints if CustomLiveData is injected into MainActivity instead into the view.
Thanks!


问:
set LocalizationSourceName in domain service
I have got a class extending DomainService abstract class as below:

```<code>public class ScheduleManager : DomainService, IScheduleManager
</code>```

The following line does not work:

```<code>throw new UserFriendlyException(L("ScheduleIsNotValid"));
</code>```

because of:
Abp.AbpException: Must set LocalizationSourceName before, in order to get LocalizationSource

Just wonder where the proper place if for setting the LocalizationSourceName, like it was set in MyCarParkControllerBase, but in Core (Domain) layer?

By the way the there are 2 usages of localization in the UserRegistrationManager class as:

```<code>Line 96 >>> throw new UserFriendlyException(L("UnknownTenantId{0}", tenantId));
Line  101 >>> throw new UserFriendlyException(L("TenantIdIsNotActive{0}", tenantId));
</code>```

That are failing due to the same issue!

Cheers,

答:
In Core project, create an abstract base class for DomainService.
Set localization source in constructor.
That's it!

Body:
I have got a class extending DomainService abstract class as below:

public class ScheduleManager : DomainService, IScheduleManager

The following line does not work:

throw new UserFriendlyException(L("ScheduleIsNotValid"));

because of:
Abp.AbpException: Must set LocalizationSourceName before, in order to get LocalizationSource

Just wonder where the proper place if for setting the LocalizationSourceName, like it was set in MyCarParkControllerBase, but in Core (Domain) layer?

By the way the there are 2 usages of localization in the UserRegistrationManager class as:

Line 96 >>> throw new UserFriendlyException(L("UnknownTenantId{0}", tenantId));
Line  101 >>> throw new UserFriendlyException(L("TenantIdIsNotActive{0}", tenantId));

That are failing due to the same issue!

Cheers,


问:
Why are non-placement `new` and `delete` built into the language and not just regular functions?
Why were the non-placement new expression and the delete expression implemented as language built-in instead of regular functions?

If we have...

a way of requesting/giving back memory to the OS

a way of explicitly invoking a constructor (placement new)

a way of explicitly invoking a destructor (~T())

...why couldn't non-placement new and delete just be regular functions in the Standard Library? Example:

```<code>template <typename T, typename... Ts>
T* library_new(Ts&&... xs)
{
    auto* ptr = /* request enough memory for `T` from OS */;
    new (ptr) T(std::forward<Ts>(xs)...);
    return ptr;
}

template <typename T>
void library_delete(T* ptr)
{
    ptr->~T();
    /* reclaim memory for `T` from OS */
}
</code>```

答:
If the user's goal was to create an object in some memory location, then new seemed like a natural approach since forwarding references, variadic templates and placement new were not a thing back in those days.  As correctly pointed out by @T.C. templates were released in 1990 and placement new in 1989.  Variadic templates on the other hand, became a part of C++ only in C++11.

tl;dr There was no way to forward a bunch of arguments to a constructor of an arbitrary type (as you can do these days with make functions).

Body:
Why were the non-placement new expression and the delete expression implemented as language built-in instead of regular functions?

If we have...

a way of requesting/giving back memory to the OS

a way of explicitly invoking a constructor (placement new)

a way of explicitly invoking a destructor (~T())

...why couldn't non-placement new and delete just be regular functions in the Standard Library? Example:

template <typename T, typename... Ts>
T* library_new(Ts&&... xs)
{
    auto* ptr = /* request enough memory for `T` from OS */;
    new (ptr) T(std::forward<Ts>(xs)...);
    return ptr;
}

template <typename T>
void library_delete(T* ptr)
{
    ptr->~T();
    /* reclaim memory for `T` from OS */
}


问:
UIButton animation view
I am new developer in iPhone.

I want to create uibutton.

When I click the button, then the button will be flash like as below.

How to create the flash, when I click my button?

答:
```<code>toolbar = [UIToolbar new];
 toolbar.barStyle = UIBarStyleDefault;
 [toolbar sizeToFit];
 toolbar.frame = CGRectMake(0, 410, 320, 50);

 //Add buttons
 UIBarButtonItem *systemItem1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                     target:self
                     action:@selector(pressButton1:)];

 UIBarButtonItem *systemItem2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                     target:self
                     action:@selector(pressButton2:)];

 UIBarButtonItem *systemItem3 = [[UIBarButtonItem alloc]
         initWithBarButtonSystemItem:UIBarButtonSystemItemCamera
         target:self action:@selector(pressButton3:)];

 //Use this to put space in between your toolbox buttons
 UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                     target:nil
                     action:nil];

 //Add buttons to the array
 NSArray *items = [NSArray arrayWithObjects: systemItem1, flexItem, systemItem2, flexItem, systemItem3, nil];

 //release buttons
 [systemItem1 release];
 [systemItem2 release];
 [systemItem3 release];
 [flexItem release];

 //add array of buttons to toolbar
 [toolbar setItems:items animated:NO];

 [self.view addSubview:toolbar];
</code>```

use this to create toolBar.

and use this for search button

```<code>UIBarButtonSystemItemSearch
</code>```

Title: UIButton animation view

Body:
toolbar = [UIToolbar new];
 toolbar.barStyle = UIBarStyleDefault;
 [toolbar sizeToFit];
 toolbar.frame = CGRectMake(0, 410, 320, 50);

 //Add buttons
 UIBarButtonItem *systemItem1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                     target:self
                     action:@selector(pressButton1:)];

 UIBarButtonItem *systemItem2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                     target:self
                     action:@selector(pressButton2:)];

 UIBarButtonItem *systemItem3 = [[UIBarButtonItem alloc]
         initWithBarButtonSystemItem:UIBarButtonSystemItemCamera
         target:self action:@selector(pressButton3:)];

 //Use this to put space in between your toolbox buttons
 UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                     target:nil
                     action:nil];

 //Add buttons to the array
 NSArray *items = [NSArray arrayWithObjects: systemItem1, flexItem, systemItem2, flexItem, systemItem3, nil];

 //release buttons
 [systemItem1 release];
 [systemItem2 release];
 [systemItem3 release];
 [flexItem release];

 //add array of buttons to toolbar
 [toolbar setItems:items animated:NO];

 [self.view addSubview:toolbar];

use this to create toolBar.

and use this for search button

UIBarButtonSystemItemSearch

ContentLicense: CC BY-SA 2.5


问:
Calling a public Class in onClick
I have an onClick event:

```<code>   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mPrayerTime = (Button)findViewById(R.id.muteButton);
    mPrayerTime.setOnClickListener(new  View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //call CityModelHere
        }
    });
</code>```

and I want to call this class (and specifically get the fajr variable without it returning null as it does if I instantiate a new cityModel in the onClick):

```<code> public class cityModel implements Serializable {
    private String fajr;

    public void setFajr(String fajr) {
        this.fajr= fajr;

    }
    public String getFajr() {

        return fajr;
    }
}
</code>```

the class takes the string from a later class here just in case:

```<code>        protected void outputTimings(JSONArray jsonArray) {
        String[] prayers = {"fajr", "shurooq", "dhuhr", "asr", "maghrib", "isha"};
        cityModel cityObj;
        try {
            cityObj= new cityModel();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject cityObject =
                        jsonArray.getJSONObject(i);
                result = result + "fajr" + " : "
                        + cityObject.getString("fajr") + "\n" + result + "shurooq" + " : "
                        + cityObject.getString("shurooq") + "\n" + result + "dhuhr" + " : "
                        + cityObject.getString("dhuhr") + "\n" + result + "asr" + " : "
                        + cityObject.getString("asr") + "\n" + result + "maghrib" + " : "
                        + cityObject.getString("maghrib") + "\n" + result + "isha" + " : "
                        + cityObject.getString("isha") + "\n";

                cityObj.setFajr(""+cityObject.getString("fajr"));

            }

        } catch (JSONException e1) {
            e1.printStackTrace();
        }

    }
</code>```

答: Make your variable final, and then you can access it from the setOnClickListener.</p>

Title: Calling a public Class in onClick

Body:
I have an onClick event:

   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mPrayerTime = (Button)findViewById(R.id.muteButton);
    mPrayerTime.setOnClickListener(new  View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //call CityModelHere
        }
    });

and I want to call this class (and specifically get the fajr variable without it returning null as it does if I instantiate a new cityModel in the onClick):

 public class cityModel implements Serializable {
    private String fajr;

    public void setFajr(String fajr) {
        this.fajr= fajr;

    }
    public String getFajr() {

        return fajr;
    }
}

the class takes the string from a later class here just in case:

        protected void outputTimings(JSONArray jsonArray) {
        String[] prayers = {"fajr", "shurooq", "dhuhr", "asr", "maghrib", "isha"};
        cityModel cityObj;
        try {
            cityObj= new cityModel();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject cityObject =
                        jsonArray.getJSONObject(i);
                result = result + "fajr" + " : "
                        + cityObject.getString("fajr") + "\n" + result + "shurooq" + " : "
                        + cityObject.getString("shurooq") + "\n" + result + "dhuhr" + " : "
                        + cityObject.getString("dhuhr") + "\n" + result + "asr" + " : "
                        + cityObject.getString("asr") + "\n" + result + "maghrib" + " : "
                        + cityObject.getString("maghrib") + "\n" + result + "isha" + " : "
                        + cityObject.getString("isha") + "\n";

                cityObj.setFajr(""+cityObject.getString("fajr"));

            }

        } catch (JSONException e1) {
            e1.printStackTrace();
        }

    }


问:
I cant connect to the outlook server
I am trying to make an imap parser where it connects to the outlook server but when I run the code, I run into this error:

Warning: imap_open(): Couldn't open stream
  {outlook.office365.com:143/STARTTLS}INBOX in
  C:\xampp\htdocs\Imap_parser1.php on line 49 Cannot connect to
  kraken.im: Can't open mailbox
  {outlook.office365.com:143/STARTTLS}INBOX: invalid remote
  specification Notice: Unknown: Can't open mailbox
  {outlook.office365.com:143/STARTTLS}INBOX: invalid remote
  specification (errflg=2) in Unknown on line 0

Would it be possible to get a solution on how to fix the problem please?

```<code><html>
<head>
    <title>Kraken.im Email Parser</title>
</head>
<body>
    <?php

    //include Imap_parser class
    include './Imap_parser1.php';
       //$myfile = fopen("Imap_parser.php", "r");

    //create Imap_parser Object
    $email = new Imap_parser();

    //data
    $data = array
    (
        //email account
        'email' => array
        (
            'hostname' => '{outlook.office365.com:143/STARTTLS}INBOX',
            'username' => 'nathan.hanlon@kraken.im',
            'password' => 'XXXXXXXXXX'
        ),
        //inbox pagination
        'pagination' => array
        (
            'sort' => 'DESC', // or ASC
            'limit' => 3,
            'offset' => (empty($_GET['offset']) ? 0 : $_GET['offset'])
        )
    );

    //get inbox by pagination. Array
    $result = $email->inbox($data);

    //HTML
    $html = '<table>';
    $html .= '<tr><td>subject</td><td>form</td><td>email</td><td>date</td>
    <td>message</td><td>image</td></tr>';
    foreach($result['inbox'] as $r)
    {
        $html .= '<tr><td>'.$r['subject'].'</td><td>'.$r['form'].'</td>
        <td>'.$r['email'].'</td><td>'.$r['date'].'</td><td>
        ```'.$r['message'].'```</td><td>'.(!empty($r['image'])? '<img
        src="'.$r['image'].'"/>' : '').'</td></tr>';
    }

    $html .= '</table>';

    echo $html;

    ?>
 </body>
 </html>

 class Imap_parser {

function inbox($data)
{

    $result = array();

    ***$imap =  imap_open($data['email']['hostname'], $data['email']
    ['username'], $data['email']['password']) or die ('Cannot connect to
    kraken.im: ' . imap_last_error());***
    array('DISABLE_AUTHENTICATOR' => 'GSSAPI');
    array('DISABLE_AUTHENTICATOR' => 'PLAIN');

    if ($imap)
    {

        $result['status'] = 'success';
        $result['email']  = $data['email']['username'];

        $read = imap_search($imap, 'ALL');

        if($data['pagination']['sort'] == 'DESC')
        {
            rsort($read);
        }

        $num = count($read);

        $result['count'] = $num;

        $stop = $data['pagination']['limit'] + $data['pagination']
        ['offset'];

        if($stop > $num)
        {
            $stop = $num;
        }

        for ($i = $data['pagination']['offset']; $i < $stop; $i++)
        {

            $overview   = imap_fetch_overview($imap, $read[$i], 0);
            $message    = imap_body($imap, $read[$i], 0);
            $header     = imap_headerinfo($imap, $read[$i], 0);
            $mail= $header->from[0]->mailbox . '@' . $header->from[0]->host;
            $image = '';

            $message = preg_replace('/--(.*)/i', '', $message);
            $message = preg_replace('/X\-(.*)/i', '', $message);
            $message = preg_replace('/Content\-ID\:/i', '', $message);

            $msg = '';

            if (preg_match('/Content-Type/', $message))
            {
                $message = strip_tags($message);
                $content = explode('Content-Type: ', $message);
                foreach ($content as $c) {
                    if (preg_match('/base64/', $c))
                    {
                        $b64 = explode('base64', $c);
                        if (preg_match('/==/', $b64[1]))
                        {
                            $str = explode('==', $b64[1]);
                            $dec = $str[0];
                        } else
                        {
                            $dec = $b64[1];
                        }
                        if (preg_match('/image\/(.*)\;/', $c, $mime))
                        {
                            $image = 'data:image/' . $mime[1] . ';base64,' .
                            trim($dec);
                        }
                    } else {
                        if (!empty($c))
                        {
                            $msg = $c;
                        }
                    }
                }
            } else
            {
                $msg = $message;
            }

            $msg = preg_replace('/text\/(.*)UTF\-8/', '', $msg);
            $msg = preg_replace('/text\/(.*)\;/', '', $msg);
            $msg = preg_replace('/charset\=(.*)\"/', '', $msg);
            $msg = preg_replace('/Content\-Transfer\-Encoding\:(.*)/i', '',
            $msg);

            $result['inbox'][] = array
            (
                'id' => $read[$i],
                'subject' => strip_tags($overview[0]->subject),
                'from' => $overview[0]->from,
                'email' => $mail,
                'date' => $overview[0]->date,
                'message' => trim($msg),
                'image' => $image
            );

            $result['pagination'] = array
            (
                'sort' => $data['pagination']['sort'],
                'limit' => $data['pagination']['limit'],
                'offset' => array
                (
                    'back' => ($data['pagination']['offset'] == 0 ? null :
                     $data['pagination']['offset'] - $data['pagination']
                     ['limit']),
                    'next' => ($data['pagination']['offset'] < $num ?
                     $data['pagination']['offset'] + $data['pagination']
                     ['limit'] : null)
                )
            );

        }

        imap_close($imap);

    } else
    {
        $result['status'] = 'error';
    }

    return $result;

}

}

?>
</code>```

答:
Try changing the hostname portion of the connection to that shown below - it allowed me to connect and showed the message "connected" ~ but I would suggest that you immediately change your password as a matter of urgency!!

```<code>$config =(object)array(
    'hostname' => '{outlook.office365.com:993/imap/ssl}INBOX',
    'username' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'password' => 'xxxxxxxxxxxxxx'
);

try{

    $imap=imap_open( $config->hostname, $config->username, $config->password, OP_DEBUG|OP_READONLY );
    echo $imap ? 'Connected' : 'Not connected!!!';
    @imap_close( $imap );

}catch(Exception $e){
    echo $e->getMessage();
}
</code>```

Title: I cant connect to the outlook server

Body:
I am trying to make an imap parser where it connects to the outlook server but when I run the code, I run into this error:

Warning: imap_open(): Couldn't open stream
  {outlook.office365.com:143/STARTTLS}INBOX in
  C:\xampp\htdocs\Imap_parser1.php on line 49 Cannot connect to
  kraken.im: Can't open mailbox
  {outlook.office365.com:143/STARTTLS}INBOX: invalid remote
  specification Notice: Unknown: Can't open mailbox
  {outlook.office365.com:143/STARTTLS}INBOX: invalid remote
  specification (errflg=2) in Unknown on line 0

Would it be possible to get a solution on how to fix the problem please?

    <title>Kraken.im Email Parser</title>

    <?php

    //include Imap_parser class
    include './Imap_parser1.php';
       //$myfile = fopen("Imap_parser.php", "r");

    //create Imap_parser Object
    $email = new Imap_parser();

    //data
    $data = array
    (
        //email account
        'email' => array
        (
            'hostname' => '{outlook.office365.com:143/STARTTLS}INBOX',
            'username' => 'nathan.hanlon@kraken.im',
            'password' => 'XXXXXXXXXX'
        ),
        //inbox pagination
        'pagination' => array
        (
            'sort' => 'DESC', // or ASC
            'limit' => 3,
            'offset' => (empty($_GET['offset']) ? 0 : $_GET['offset'])
        )
    );

    //get inbox by pagination. Array
    $result = $email->inbox($data);

    //HTML
    $html = '
';
    $html .= '
subject	form	email	date
    message	image
';
    foreach($result['inbox'] as $r)
    {
        $html .= '
'.$r['subject'].'	'.$r['form'].'
        '.$r['email'].'	'.$r['date'].'

'.$r['message'].'
	'.(!empty($r['image'])? '' : '').'
';
    }

    $html .= '
';

    echo $html;

    ?>

 class Imap_parser {

function inbox($data)
{

    $result = array();

    ***$imap =  imap_open($data['email']['hostname'], $data['email']
    ['username'], $data['email']['password']) or die ('Cannot connect to
    kraken.im: ' . imap_last_error());***
    array('DISABLE_AUTHENTICATOR' => 'GSSAPI');
    array('DISABLE_AUTHENTICATOR' => 'PLAIN');

    if ($imap)
    {

        $result['status'] = 'success';
        $result['email']  = $data['email']['username'];

        $read = imap_search($imap, 'ALL');

        if($data['pagination']['sort'] == 'DESC')
        {
            rsort($read);
        }

        $num = count($read);

        $result['count'] = $num;

        $stop = $data['pagination']['limit'] + $data['pagination']
        ['offset'];

        if($stop > $num)
        {
            $stop = $num;
        }

        for ($i = $data['pagination']['offset']; $i < $stop; $i++)
        {

            $overview   = imap_fetch_overview($imap, $read[$i], 0);
            $message    = imap_body($imap, $read[$i], 0);
            $header     = imap_headerinfo($imap, $read[$i], 0);
            $mail= $header->from[0]->mailbox . '@' . $header->from[0]->host;
            $image = '';

            $message = preg_replace('/--(.*)/i', '', $message);
            $message = preg_replace('/X\-(.*)/i', '', $message);
            $message = preg_replace('/Content\-ID\:/i', '', $message);

            $msg = '';

            if (preg_match('/Content-Type/', $message))
            {
                $message = strip_tags($message);
                $content = explode('Content-Type: ', $message);
                foreach ($content as $c) {
                    if (preg_match('/base64/', $c))
                    {
                        $b64 = explode('base64', $c);
                        if (preg_match('/==/', $b64[1]))
                        {
                            $str = explode('==', $b64[1]);
                            $dec = $str[0];
                        } else
                        {
                            $dec = $b64[1];
                        }
                        if (preg_match('/image\/(.*)\;/', $c, $mime))
                        {
                            $image = 'data:image/' . $mime[1] . ';base64,' .
                            trim($dec);
                        }
                    } else {
                        if (!empty($c))
                        {
                            $msg = $c;
                        }
                    }
                }
            } else
            {
                $msg = $message;
            }

            $msg = preg_replace('/text\/(.*)UTF\-8/', '', $msg);
            $msg = preg_replace('/text\/(.*)\;/', '', $msg);
            $msg = preg_replace('/charset\=(.*)\"/', '', $msg);
            $msg = preg_replace('/Content\-Transfer\-Encoding\:(.*)/i', '',
            $msg);

            $result['inbox'][] = array
            (
                'id' => $read[$i],
                'subject' => strip_tags($overview[0]->subject),
                'from' => $overview[0]->from,
                'email' => $mail,
                'date' => $overview[0]->date,
                'message' => trim($msg),
                'image' => $image
            );

            $result['pagination'] = array
            (
                'sort' => $data['pagination']['sort'],
                'limit' => $data['pagination']['limit'],
                'offset' => array
                (
                    'back' => ($data['pagination']['offset'] == 0 ? null :
                     $data['pagination']['offset'] - $data['pagination']
                     ['limit']),
                    'next' => ($data['pagination']['offset'] < $num ?
                     $data['pagination']['offset'] + $data['pagination']
                     ['limit'] : null)
                )
            );

        }

        imap_close($imap);

    } else
    {
        $result['status'] = 'error';
    }

    return $result;

}

}

?>

Body:
Try changing the hostname portion of the connection to that shown below - it allowed me to connect and showed the message "connected" ~ but I would suggest that you immediately change your password as a matter of urgency!!

$config =(object)array(
    'hostname' => '{outlook.office365.com:993/imap/ssl}INBOX',
    'username' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'password' => 'xxxxxxxxxxxxxx'
);

try{

    $imap=imap_open( $config->hostname, $config->username, $config->password, OP_DEBUG|OP_READONLY );
    echo $imap ? 'Connected' : 'Not connected!!!';
    @imap_close( $imap );

}catch(Exception $e){
    echo $e->getMessage();
}


问:
Handling multiple changesets in source control systems
I have a fairly infrequent problem occuring with source control. In the example here the problem was occuring with Perforce, but I suspect the same problem will occur with many SCMs, especially distributed SCMs.

Perforce supports changelists (or changesets if you prefer). Changelists support two common usages:

When you commit a changelist, the commit is atomic so that all the files are committed or none are. This is the headline feature that most people talk about when referring to changelists.

Perforce supports multiple changelists. Basically, when you check out a file you tell it which changelist it belongs to. So, if you are working on the fancy new email feature which is going to take months of work and makes millions of dollars and somebody from tech support comes to you with a bug that must be fixed yesterday, you don't have to start with a new branch of the whole project. You can just check out the buggy file into a new changelist, fix the problem, check in the new changelist and get back to the real work of the new email feature, as though nothing had happened.

For the most part everything works great. However, when you are implemening the email feature you are making zillions of changes all over the place, especially in main.h, and it just so happens that when go to work on the bug fix you discover that the tiny change you have to make is also in main.h. The changelist for the new feature already has main.h checked out, so you can't easily put it in the changelist for the bug fix.

Now what do you do? You have several choices:

Create a new clientspec. A clientspec in Perforce is a list of files/directories in the depot and a local destination where everything is to be copied. So you can create a second copy of the project without any of changes for the email feature.

Do a fudge. Backup your modified copy of main.h and revert this file. You are then free to checkout main.h into the bugfix changelist. You fix the bug, check in the bugfix changelist, then checkout main.h into the email feature changelist. Finally you merge all your changes from the backup you made at the start.

You determine that all the changes you have made to main.h have no side affects or dependencies, so you just move main.h into the bugfix changelist, make the change and check it in. You then check it out again into the email feature changelist. Obviously there are two problems with this approach: firstly there may in fact be side affects that you hadn't considered and secondly you have corrupted your version histoty.

Option 1 is probably the cleanest, but not always practical. A project I was working on had millions of lines of code and a really complicated build process. It would take a day to setup a new environment, so it was not really practical for a 5 minute bug fix.

Option 3 is a bad option, but is is the quickest, so it can be very seductive.

That leaves Option 2, which is the one I would generally use.

Does anybody have a better solution?

My apologies for the lengthy question, but I have discovered on StackOverflow that fully thought out questions elicit better answers.

答:
ClearCase supports also changelist (called "activity" in its UCM flavor), and presents a similar challenge.

Option 1 ("kind of branch") makes sense only when you determine that the "debug effort" is not compatible with the current development effort (email feature) and is best kept in a separate branch. Then you can retrofit whatever correction done in the "patch" branch to the main branch (since not every bug you will fix have to be present in both: the current development may have render some fixes obsolete).

See also "What is a branch", and what is your merge workflow.

Option 3 is an illustration of the limit of the notion of changeset: a single revision (or "version") of a file can only be part of one changeset at a time.

The git add -p (add patch) mentioned by Greg is an alternation to Option 1 and 3, since it takes advantage of the staging feature of the "Index" (Staging Area), zone in which you decide what will actually be committed, and what will remain in your private space.

That is nice but also in my experience quite difficult to sustain on a long period of time, especially on a common set of files upon which you apply two different evolutions. A branch is cleaner, simpler to unit-test. However, for a small fix like you mention, it could be a nice way out.

Option 2 is the practical solution when you realize you have two changes for two different efforts (that are still compatible, which do not "break" one another).

But may be an even simpler solution would be to just:

checkin the current state of main.h in email,

checkout in bug, fix it, checkin in bug

and then checkout in email to resume the email feature development.

Again, if the two development efforts (email and bug) are compatible, you can have a revision history with mixed activities.

OwnerDisplayName: Mike Thompson

OwnerDisplayName: VonC

LastEditorDisplayName: VonC


问:
change uri without use input output in jena
Below is my simple sparql query. I want to change my sparql query uri but i have no idea how can i change this specific thing without using input/output.

input string:

```<code>PREFIX ab: <http://learningsparql.com/ns/addressbook#>

SELECT ?craigEmail
WHERE
{ ab:craig ab:email ?craigEmail . }
</code>```

output string:

```<code>PREFIX ab: <http://example.com#>

SELECT ?craigEmail
WHERE
{ ab:craig ab:email ?craigEmail . }
</code>```

Can you please provide me code to this simple thing in jena...

答:
You can use the Jena ARQ API and replace the namespace for the prefix ab programmatically by iterating over the triple pattern elements of a SPARQL query:

import org.apache.jena.graph.Node;
import org.apache.jena.graph.NodeFactory;
import org.apache.jena.graph.Triple;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.sparql.core.TriplePath;
import org.apache.jena.sparql.syntax.ElementPathBlock;
import org.apache.jena.sparql.syntax.ElementTriplesBlock;
import org.apache.jena.sparql.syntax.ElementVisitorBase;
import org.apache.jena.sparql.syntax.ElementWalker;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Test {

public static void main(String[] args) {
        Query query = QueryFactory.create("" +
                "PREFIX ab: <http://learningsparql.com/ns/addressbook#> " +
                "SELECT ?craigEmail WHERE { ab:craig ab:email ?craigEmail . }");

        // This will walk through all parts of the query// This will walk through all parts of the query

        final String ns = "http://example.com#";

        ElementWalker.walk(query.getQueryPattern(), new ElementVisitorBase() { // ...when it's a block of triples...
            public void visit(ElementPathBlock el){ // ...go through all the triples...
                Iterator<TriplePath> triples = el.patternElts();
                List<Triple> newTriples = new ArrayList<>();
                while (triples.hasNext()) {
                    TriplePath triple = triples.next();
                    if(triple.isTriple()) {
                        Node s = triple.getSubject();
                        if(s.isURI()) {
                            String localName = s.getLocalName();
                            s = NodeFactory.createURI(ns + localName);
                        }
                        Node p = triple.getPredicate();
                        if(p.isURI()) {
                            String localName = p.getLocalName();
                            p = NodeFactory.createURI(ns + localName);
                        }
                        Node o = triple.getSubject();
                        if(o.isURI()) {
                            String localName = o.getLocalName();
                            o = NodeFactory.createURI(ns + localName);
                        }

                        newTriples.add(Triple.create(s, p, o));

                    } else {
                        // TODO handle triple path
                    }
                    triples.remove();
                }
                for(Triple t : newTriples) {
                    el.addTriple(t);
                }
            }

            @Override
            public void visit(ElementTriplesBlock el) {
                Iterator<Triple> triples = el.patternElts();
                List<Triple> newTriples = new ArrayList<>();
                while (triples.hasNext()) {
                    Triple triple = triples.next();

                    Node s = triple.getSubject();
                    if(s.isURI()) {
                        String localName = s.getLocalName();
                        s = NodeFactory.createURI(ns + localName);
                    }
                    Node p = triple.getPredicate();
                    if(p.isURI()) {
                        String localName = p.getLocalName();
                        p = NodeFactory.createURI(ns + localName);
                    }
                    Node o = triple.getSubject();
                    if(o.isURI()) {
                        String localName = o.getLocalName();
                        o = NodeFactory.createURI(ns + localName);
                    }

                    newTriples.add(Triple.create(s, p, o));

                    triples.remove();
                }
                for(Triple t : newTriples) {
                    el.addTriple(t);
                }
            }
        });

        query.setPrefix("ab", ns);
        System.out.println(query);
    }
}
```

Body:
Below is my simple sparql query. I want to change my sparql query uri but i have no idea how can i change this specific thing without using input/output.

input string:

PREFIX ab: <http://learningsparql.com/ns/addressbook#>

SELECT ?craigEmail
WHERE
{ ab:craig ab:email ?craigEmail . }

output string:

PREFIX ab: <http://example.com#>

SELECT ?craigEmail
WHERE
{ ab:craig ab:email ?craigEmail . }

Can you please provide me code to this simple thing in jena...


问:
Websocket sharp log file output
I'm using Websocket sharp (https://github.com/sta/websocket-sharp) for a console program, how do I output all debug/trace information that are displayed on the console to a text file?

For example:

```<code>using (var ws = new WebSocket(WebAddr))
            {

                ws.Log.Level = LogLevel.Debug;
                ws.OnOpen += (ss, ee) =>
                {
                  System.IO.File.WriteAllText(@"C:\log.txt", ws.Log.ToString());

                };
</code>```

But the output for this is "WebSocketSharp.Logger".

I would expecting something like this:

Screenshot

答:
You will need to provide alot more information (which data?, how often? etc.) but you can use the System.IO.File methods for easy writing to a file;</p>

```<code>// To create a new file
System.IO.File.WriteAllText(@"FileNameToWriteTo.txt", aString);
System.IO.File.WriteAllLines(@"FileNameToWriteTo.txt", listOfStrings);

// To add to the end of an existing file
System.IO.File.AppendAllText(@"FileNameToWriteTo.txt", aString);
System.IO.File.AppendAllLines(@"FileNameToWriteTo.txt", listOfStrings);
</code>```

Title: Websocket sharp log file output

Body:
I'm using Websocket sharp (https://github.com/sta/websocket-sharp) for a console program, how do I output all debug/trace information that are displayed on the console to a text file?

For example:

using (var ws = new WebSocket(WebAddr))
            {

                ws.Log.Level = LogLevel.Debug;
                ws.OnOpen += (ss, ee) =>
                {
                  System.IO.File.WriteAllText(@"C:\log.txt", ws.Log.ToString());

                };

But the output for this is "WebSocketSharp.Logger".

I would expecting something like this:

Screenshot

Body:
You will need to provide alot more information (which data?, how often? etc.) but you can use the System.IO.File methods for easy writing to a file;

// To create a new file
System.IO.File.WriteAllText(@"FileNameToWriteTo.txt", aString);
System.IO.File.WriteAllLines(@"FileNameToWriteTo.txt", listOfStrings);

// To add to the end of an existing file
System.IO.File.AppendAllText(@"FileNameToWriteTo.txt", aString);
System.IO.File.AppendAllLines(@"FileNameToWriteTo.txt", listOfStrings);


问:
AutoMapper Threading Issue (Missing type map configuration or unsupported mapping)?
I'm not sure if I have a threading issue here or not.  On the page load I am executing two Ajax requests to load some additional data from a third party API.  Here is what each method looks like that gets called:

```<code>private List<CaseCommentModel> GetCaseCommentModels(string caseId) {
    var comments = CaseService.GetAllCaseCommentsByCaseId(caseId);

    Mapper.Reset();
    Mapper.CreateMap<CrmCaseComment, CaseCommentModel>();

    var caseCommentModels = Mapper.Map<List<CrmCaseComment>, List<CaseCommentModel>>(comments);

    return caseCommentModels;
}

private List<CaseAttachmentModel> GetCaseAttachmentModels(string caseId) {
    var attachments = AttachmentService.GetAttachmentsByParentId(caseId);

    Mapper.Reset();
    Mapper.CreateMap<CrmAttachment, CaseAttachmentModel>();

    var caseAttachmentModels = Mapper.Map<List<CrmAttachment>, List<CaseAttachmentModel>>(attachments);

    return caseAttachmentModels;
}
</code>```

Sometimes both responses succeed.  But, if I refresh the page, sometimes one will fail with the following exception:

Missing type map configuration or unsupported mapping

I can go from both requests succeeding to one failing without making any code changes; all it takes is a refresh of the page.  Is this a threading issue or am I using the mapper incorrectly?

答:
Yes, you have a threading issue and the best solutionis (in my opinion) is to stop using static API from AutoMapper.

I propose you configure automapper in follwoing way:
// IoC registration (Autofac in my case)

```<code>builder
    .Register(c => new MapperConfiguration(cfg => {
        cfg.AddProfile<AutoMapperProfile>();
    }))
    .SingleInstance();
builder
    .Register(c => c.Resolve<MapperConfiguration>().CreateMapper())
    .As<AutoMapper.IMapper>();
</code>```

Please note that I create MapperConfiguration as single instance.
Class AutoMapperProfile.cs contains configuration of automapper:

```<code>class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        CreateMap<Source, Destination>();
        // usual configurations...
    }
}
</code>```

Body:
I'm not sure if I have a threading issue here or not.  On the page load I am executing two Ajax requests to load some additional data from a third party API.  Here is what each method looks like that gets called:

private List<CaseCommentModel> GetCaseCommentModels(string caseId) {
    var comments = CaseService.GetAllCaseCommentsByCaseId(caseId);

    Mapper.Reset();
    Mapper.CreateMap<CrmCaseComment, CaseCommentModel>();

    var caseCommentModels = Mapper.Map<List<CrmCaseComment>, List<CaseCommentModel>>(comments);

    return caseCommentModels;
}

private List<CaseAttachmentModel> GetCaseAttachmentModels(string caseId) {
    var attachments = AttachmentService.GetAttachmentsByParentId(caseId);

    Mapper.Reset();
    Mapper.CreateMap<CrmAttachment, CaseAttachmentModel>();

    var caseAttachmentModels = Mapper.Map<List<CrmAttachment>, List<CaseAttachmentModel>>(attachments);

    return caseAttachmentModels;
}

Sometimes both responses succeed.  But, if I refresh the page, sometimes one will fail with the following exception:

Missing type map configuration or unsupported mapping

I can go from both requests succeeding to one failing without making any code changes; all it takes is a refresh of the page.  Is this a threading issue or am I using the mapper incorrectly?

Body:
Yes, you have a threading issue and the best solutionis (in my opinion) is to stop using static API from AutoMapper.

I propose you configure automapper in follwoing way:
// IoC registration (Autofac in my case)

builder
    .Register(c => new MapperConfiguration(cfg => {
        cfg.AddProfile<AutoMapperProfile>();
    }))
    .SingleInstance();
builder
    .Register(c => c.Resolve<MapperConfiguration>().CreateMapper())
    .As<AutoMapper.IMapper>();

Please note that I create MapperConfiguration as single instance.
Class AutoMapperProfile.cs contains configuration of automapper:

class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        CreateMap<Source, Destination>();
        // usual configurations...
    }
}


问:
Python - Collapse Groups of strings
I have a list of strings, e.g. ['Apple', 'Appl','Elephnt', 'Elephant']. I need collapse this list of strings into distinct groups i.e. ['Apple', 'Elephnt'].

My criteria for strings that should be in the same group is based on a percentage match of above 80%. i.e. Apple and Appl share an 88% match, and Elephnt and Elephant share a 93% match.

```<code>def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()
</code>```

The function similar is used to calculate the percentage match of two strings.
How do I compute this collapse grouping using the above function?

答:
This seems to be what you want. Its main problem is that it has quadratic order for large lists of non-similar strings. Given that "similar" is close to equality but not quite the same (it is not transitive, for example), I cannot see any way to reduce the order of the algorithm. For example, I do not see how to sort the items so that itertool's groupby function can be used.

The main idea is to add a string to the result list if it is not similar to any of the previous strings.

```<code>from difflib import SequenceMatcher

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

def collapse_similar(strlist):
    """Eliminate "duplicate" strings in a list, where "duplicate" means
    similar() is more than 80%.
    """
    result = []
    for s in strlist:
        if all(similar(s, v) <= 0.8 for v in result):
            result.append(s)
    return result
</code>```

The result of collapse_similar(['Apple', 'Appl','Elephnt', 'Elephant']) is ['Apple', 'Elephnt'], as desired.

Title: Python - Collapse Groups of strings

Body:
I have a list of strings, e.g. ['Apple', 'Appl','Elephnt', 'Elephant']. I need collapse this list of strings into distinct groups i.e. ['Apple', 'Elephnt'].

My criteria for strings that should be in the same group is based on a percentage match of above 80%. i.e. Apple and Appl share an 88% match, and Elephnt and Elephant share a 93% match.

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

The function similar is used to calculate the percentage match of two strings.
How do I compute this collapse grouping using the above function?

Body:
This seems to be what you want. Its main problem is that it has quadratic order for large lists of non-similar strings. Given that "similar" is close to equality but not quite the same (it is not transitive, for example), I cannot see any way to reduce the order of the algorithm. For example, I do not see how to sort the items so that itertool's groupby function can be used.

The main idea is to add a string to the result list if it is not similar to any of the previous strings.

from difflib import SequenceMatcher

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

def collapse_similar(strlist):
    """Eliminate "duplicate" strings in a list, where "duplicate" means
    similar() is more than 80%.
    """
    result = []
    for s in strlist:
        if all(similar(s, v) <= 0.8 for v in result):
            result.append(s)
    return result

The result of collapse_similar(['Apple', 'Appl','Elephnt', 'Elephant']) is ['Apple', 'Elephnt'], as desired.


问:
Percentage loading bar for a SWF file through JavaScript
I have jsp that is suppose to load the .swf file which is large in size which takes of about 7 sec to load completely, could I hide the loading and put the JavaScript percentage loading bar for Swf file.</p>

答:
As far as I know, you can't build a proper progress bar for a single file in JavaScript. Progress bars for web sites usually monitor load completion for multiple images to fake having access to the actual percentage of a page being loaded (if 1 out of 10 images is loaded, that's 10 percent, right?).

Alternatively, you could show an animated GIF, something like a spinning wheel or something else that moves and is not directly related to the size of the file being loaded.  You would then add a listener to the page's onLoad event, and hide the GIF when it's fired.

...or you can still have a nice progress bar, if you don't do it in JavaScript: Try reorganizing your Flash file instead! Here is a tutorial on preloading a single SWF file.

ContentLicense: CC BY-SA 4.0


问:
change colour of partial text css or javascript
Is there any way of achieving a different colour on part of text, via css or script, based on a shape outline e.g a circle or oval curve...with CSS or JS only.

An example is this, see how the colour of the S and part of the U are different based on the image?-
example of effect

Theres a similar question but this is in illustrator - https://graphicdesign.stackexchange.com/questions/20127/text-silhouette-change-color-in-middle-of-a-letter-illustrator

Instinct says no way, but there could be some magical clipping effect that can achieve the same?

答:
There are two or more ways to do that. I can come up with 2 on the spot.

One solution would be to use SVG text. Which i cant advise if you have a lot of places or dynamic text. Animating SVG text is a bit complicated sometimes.

What you could do instead is using mix-blend-mode css. It allows blending colors of text and backgrounds. Kind of how you might know it from Photoshop or Illustrator.

You can read more about it here on CSS tricks. You might wan't to check up on browser compatibility, since mix-blend-mode is poorly supported in general. You can check out which browser can make use of it here on Caniuse.

If you need inspiration for workarounds or examples of usage you could always search codepen.io for mix-blend-mode or something similar.


问:
CheckBox Checked event fires before bound collection updates
I have a custom control to show items with checkboxes inside a ComboBox. To realize this, I used a DataTemplate with a CheckBox. The ItemSource of the ComboBox uses a binding to a ObserableCollection<FilterValue> which contains my filter values. FilterValue is a custom class implementing INotifyPropertyChanged. The properties Content and IsChecked of the CheckBox use bindings as well to use the values of my list. This control will be used in Silverlight.

Binding itself works fine, as seen here:

The problem appears when I register the Checked or Unchecked event.

As soon as one of the check boxes changed its state, the event is fired as expected but at this moment, the value in the bound list is still not updated.
What I saw while debugging is that the Checked/Unchecked events are firing before the PropertyChanged event of the FilterValue.
This means that at the time the event is firing, I can't ask the list for all active (checked) filters. What could I do to achieve this?

FilterControl.xaml:

```<code><UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
    xmlns:local="clr-namespace:Controls" x:Class="Controls.FilterControl"
    mc:Ignorable="d"
    d:DesignHeight="45" d:DesignWidth="140">

    <StackPanel x:Name="LayoutRoot">
        <sdk:Label x:Name="LblFilterDescription" Content="-" />
        <ComboBox x:Name="Filter"  Width="120" ItemsSource="{Binding AvailableFilters, RelativeSource={RelativeSource FindAncestor, AncestorType=local:FilterControl}}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding Path=Text}" IsChecked="{Binding Path=IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Checked="FilterChanged" Unchecked="FilterChanged" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </StackPanel>
</UserControl>
</code>```

FilterControl.xaml.cs:

```<code>public partial class FilterControl : UserControl
{
    public delegate void FilterChangedHandler(object sender);
    public event FilterChangedHandler OnFilterChanged;

    public ObservableCollection<FilterValue> AvailableFilters { get; set; }
    public List<string> AppliedFilters
    {
        get
        {
            return new List<string>(AvailableFilters.Where(filter => filter.IsChecked).Select(filter => filter.Text));
        }
    }

    public FilterControl()
    {
        InitializeComponent();

        AvailableFilters = new ObservableCollection<FilterValue>();
    }

    public bool AddFilterValue(string filterValue)
    {
        bool found = false;

        foreach (FilterValue f in AvailableFilters)
        {
            if (f.Text == filterValue)
            {
                found = true;
                break;
            }
        }

        if (!found)
            AvailableFilters.Add(new FilterValue() { IsChecked = false, Text = filterValue });

        return found;
    }

    private void FilterChanged(object sender, RoutedEventArgs e)
    {
        //Here if I check AvailableFilters, the value is not changed yet.
        //PropertyChanged allways fires after this, what makes me unable to
        //get all currently applied filters (checked items)...
    }
}
</code>```

FilterValue:

```<code>public class FilterValue : INotifyPropertyChanged
{
    private bool _IsChecked;
    private string _Text;

    public bool IsChecked
    {
        get { return _IsChecked; }
        set
        {
            _IsChecked = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsChecked"));
        }
    }
    public string Text
    {
        get { return _Text; }
        set
        {
            _Text = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Text"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
</code>```

答:
So, as I tried to reproduce this behavior, I realized that this appears to be a behavior that only occurs like that in Silverlight. If you try this example on WPF, the Changed fires after the bound property is updated. So you can just access your AppliedFilters property in the FilterChanged method and it will reflect the actual current situation. On Silverlight though, not so much. Even worse, this behavior didn’t even appear to be consistent to me. I did encounter situations in which the event fired after the property has been updated (resulting in the expected output).

A way to get around this is to clean up your component logic. If you look at it, you are mixing two different concepts: Event-driven UI logic, and clear data binding. Of course, doing it “properly” has multiple effects you likely cannot just ensure in an existing project, but you can at least try to get in the right direction here which should then also solve this issue.

So your logic right now uses data binding to provide the data for the view, and to reflect changes of the displayed items. But you are using events on the item level to perform additional logic depending on the former changes. As we have seen, the order of execution appears not be guaranteed across platforms, so it’s best to avoid having to rely on it.

In this case, you should have your data be the source of truth and make changes in the data tell you when applied filters change. You’re already halfway there by having an ObservableCollection and items that implement INotifyPropertyChanged. Unfortunately, an observable collection will only notify you about changes to the collection but not to changes to the contained items. But there are multiple solutions to expand the collection to also look at the items inside the collection.

This related question covers exactly that topic and there are multiple ideas on how to expand the observable collection for exactly that behavior. In my case, I have used the FullyObservableCollection implementation by Bob Sammers.

All you have to do for that is to change your ObservableCollection<FilterValue> into a FullyObservableCollection<FilterValue> and subscribe to the ItemPropertyChanged event:

```<code>AvailableFilters = new FullyObservableCollection<FilterValue>();
AvailableFilters.ItemPropertyChanged += AvailableFilters_ItemPropertyChanged;
</code>```

In that event handler, you will then correctly see the proper behavior.

Body:
I have a custom control to show items with checkboxes inside a ComboBox. To realize this, I used a DataTemplate with a CheckBox. The ItemSource of the ComboBox uses a binding to a ObserableCollection<FilterValue> which contains my filter values. FilterValue is a custom class implementing INotifyPropertyChanged. The properties Content and IsChecked of the CheckBox use bindings as well to use the values of my list. This control will be used in Silverlight.

Binding itself works fine, as seen here:

The problem appears when I register the Checked or Unchecked event.

As soon as one of the check boxes changed its state, the event is fired as expected but at this moment, the value in the bound list is still not updated.
What I saw while debugging is that the Checked/Unchecked events are firing before the PropertyChanged event of the FilterValue.
This means that at the time the event is firing, I can't ask the list for all active (checked) filters. What could I do to achieve this?

FilterControl.xaml:

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
    xmlns:local="clr-namespace:Controls" x:Class="Controls.FilterControl"
    mc:Ignorable="d"
    d:DesignHeight="45" d:DesignWidth="140">

    <StackPanel x:Name="LayoutRoot">
        <sdk:Label x:Name="LblFilterDescription" Content="-" />
        <ComboBox x:Name="Filter"  Width="120" ItemsSource="{Binding AvailableFilters, RelativeSource={RelativeSource FindAncestor, AncestorType=local:FilterControl}}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding Path=Text}" IsChecked="{Binding Path=IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Checked="FilterChanged" Unchecked="FilterChanged" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </StackPanel>
</UserControl>

FilterControl.xaml.cs:

public partial class FilterControl : UserControl
{
    public delegate void FilterChangedHandler(object sender);
    public event FilterChangedHandler OnFilterChanged;

    public ObservableCollection<FilterValue> AvailableFilters { get; set; }
    public List<string> AppliedFilters
    {
        get
        {
            return new List<string>(AvailableFilters.Where(filter => filter.IsChecked).Select(filter => filter.Text));
        }
    }

    public FilterControl()
    {
        InitializeComponent();

        AvailableFilters = new ObservableCollection<FilterValue>();
    }

    public bool AddFilterValue(string filterValue)
    {
        bool found = false;

        foreach (FilterValue f in AvailableFilters)
        {
            if (f.Text == filterValue)
            {
                found = true;
                break;
            }
        }

        if (!found)
            AvailableFilters.Add(new FilterValue() { IsChecked = false, Text = filterValue });

        return found;
    }

    private void FilterChanged(object sender, RoutedEventArgs e)
    {
        //Here if I check AvailableFilters, the value is not changed yet.
        //PropertyChanged allways fires after this, what makes me unable to
        //get all currently applied filters (checked items)...
    }
}

FilterValue:

public class FilterValue : INotifyPropertyChanged
{
    private bool _IsChecked;
    private string _Text;

    public bool IsChecked
    {
        get { return _IsChecked; }
        set
        {
            _IsChecked = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsChecked"));
        }
    }
    public string Text
    {
        get { return _Text; }
        set
        {
            _Text = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Text"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Body:
So, as I tried to reproduce this behavior, I realized that this appears to be a behavior that only occurs like that in Silverlight. If you try this example on WPF, the Changed fires after the bound property is updated. So you can just access your AppliedFilters property in the FilterChanged method and it will reflect the actual current situation. On Silverlight though, not so much. Even worse, this behavior didn’t even appear to be consistent to me. I did encounter situations in which the event fired after the property has been updated (resulting in the expected output).

A way to get around this is to clean up your component logic. If you look at it, you are mixing two different concepts: Event-driven UI logic, and clear data binding. Of course, doing it “properly” has multiple effects you likely cannot just ensure in an existing project, but you can at least try to get in the right direction here which should then also solve this issue.

So your logic right now uses data binding to provide the data for the view, and to reflect changes of the displayed items. But you are using events on the item level to perform additional logic depending on the former changes. As we have seen, the order of execution appears not be guaranteed across platforms, so it’s best to avoid having to rely on it.

In this case, you should have your data be the source of truth and make changes in the data tell you when applied filters change. You’re already halfway there by having an ObservableCollection and items that implement INotifyPropertyChanged. Unfortunately, an observable collection will only notify you about changes to the collection but not to changes to the contained items. But there are multiple solutions to expand the collection to also look at the items inside the collection.

This related question covers exactly that topic and there are multiple ideas on how to expand the observable collection for exactly that behavior. In my case, I have used the FullyObservableCollection implementation by Bob Sammers.

All you have to do for that is to change your ObservableCollection<FilterValue> into a FullyObservableCollection<FilterValue> and subscribe to the ItemPropertyChanged event:

AvailableFilters = new FullyObservableCollection<FilterValue>();
AvailableFilters.ItemPropertyChanged += AvailableFilters_ItemPropertyChanged;

In that event handler, you will then correctly see the proper behavior.


问:
Automapper conditional map from multiple source fields
I've got a source class like the following:

```<code>public class Source
{
    public Field[] Fields { get; set; }
    public Result[] Results { get; set; }
}
</code>```

And have a destination class like:

```<code>public class Destination
{
    public Value[] Values { get; set; }
}
</code>```

So I want to map from EITHER Fields or Results to Values depending on which one is not null (only one will ever have a value).

I tried the following map:

```<code>CreateMap<Fields, Values>();
CreateMap<Results, Values>();

CreateMap<Source, Destination>()
            .ForMember(d => d.Values, opt =>
            {
                opt.PreCondition(s => s.Fields != null);
                opt.MapFrom(s => s.Fields });
            })
            .ForMember(d => d.Values, opt =>
            {
                opt.PreCondition(s => s.Results != null);
                opt.MapFrom(s => s.Results);
            });
</code>```

Only issue with this is that it looks if the last .ForMember map doesn't meet the condition it wipes out the mapping result from the first map.

I also thought about doing it as a conditional operator:

opt => opt.MapFrom(s => s.Fields != null ? s.Fields : s.Results)

But obviously they are different types so don't compile.

How can I map to a single property from source properties of different types based on a condition?

Thanks

答:
There is a ResolveUsing() method that allows you for more complex binding and you can use a IValueResolver or a Func. Something like this:

```<code>CreateMap<Source, Destination>()
    .ForMember(dest => dest.Values, mo => mo.ResolveUsing<ConditionalSourceValueResolver>());
</code>```

And the value resolver depending on your needs may look like:

```<code> public class ConditionalSourceValueResolver : IValueResolver<Source, Destination, Value[]>
    {
        public Value[] Resolve(Source source, Destination destination, Value[] destMember, ResolutionContext context)
        {
            if (source.Fields == null)
                return context.Mapper.Map<Value[]>(source.Results);
            else
                return context.Mapper.Map<Value[]>(source.Fields);
        }
    }
</code>```

Body:
I've got a source class like the following:

public class Source
{
    public Field[] Fields { get; set; }
    public Result[] Results { get; set; }
}

And have a destination class like:

public class Destination
{
    public Value[] Values { get; set; }
}

So I want to map from EITHER Fields or Results to Values depending on which one is not null (only one will ever have a value).

I tried the following map:

CreateMap<Fields, Values>();
CreateMap<Results, Values>();

CreateMap<Source, Destination>()
            .ForMember(d => d.Values, opt =>
            {
                opt.PreCondition(s => s.Fields != null);
                opt.MapFrom(s => s.Fields });
            })
            .ForMember(d => d.Values, opt =>
            {
                opt.PreCondition(s => s.Results != null);
                opt.MapFrom(s => s.Results);
            });

Only issue with this is that it looks if the last .ForMember map doesn't meet the condition it wipes out the mapping result from the first map.

I also thought about doing it as a conditional operator:

opt => opt.MapFrom(s => s.Fields != null ? s.Fields : s.Results)

But obviously they are different types so don't compile.

How can I map to a single property from source properties of different types based on a condition?

Thanks

Body:
There is a ResolveUsing() method that allows you for more complex binding and you can use a IValueResolver or a Func. Something like this:

CreateMap<Source, Destination>()
    .ForMember(dest => dest.Values, mo => mo.ResolveUsing<ConditionalSourceValueResolver>());

And the value resolver depending on your needs may look like:

 public class ConditionalSourceValueResolver : IValueResolver<Source, Destination, Value[]>
    {
        public Value[] Resolve(Source source, Destination destination, Value[] destMember, ResolutionContext context)
        {
            if (source.Fields == null)
                return context.Mapper.Map<Value[]>(source.Results);
            else
                return context.Mapper.Map<Value[]>(source.Fields);
        }
    }


问:
Stopping thread that doesnt throw Exception Android
So Im getting the location fix from the phone and the problem comes up if it never finds the location or takes wayy too long.  below is the sample code from the loading screen

How could i set up a timer to stop the thread(load screen) once a certain amount of time has passed?

```<code>lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
</code>```

1000, 10f, this);

Handler handler = new Handler();
  Runnable showWaitDialog = new Runnable() {
   int wait = 0;
   @Override
   public void run() {
    while (loc == null) {

```<code>}
// After receiving first GPS Fix dismiss the Progress Dialog
dialog.dismiss();
</code>```

}
  };

// Create a Dialog to let the User know that we're waiting for a GPS Fix
  dialog = ProgressDialog.show(Weather.this, "Please wait...",
    "Retrieving GPS data ...", true);

Thread t = new Thread(showWaitDialog);
  t.start();

答: If you want to stop a thread instead of using normal thread to do background jobs use Android sdk's AsyncTask, there you can find a cancel().

Body:
So Im getting the location fix from the phone and the problem comes up if it never finds the location or takes wayy too long.  below is the sample code from the loading screen

How could i set up a timer to stop the thread(load screen) once a certain amount of time has passed?

lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,

1000, 10f, this);

Handler handler = new Handler();
  Runnable showWaitDialog = new Runnable() {
   int wait = 0;
   @Override
   public void run() {
    while (loc == null) {

}
// After receiving first GPS Fix dismiss the Progress Dialog
dialog.dismiss();

}
  };

// Create a Dialog to let the User know that we're waiting for a GPS Fix
  dialog = ProgressDialog.show(Weather.this, "Please wait...",
    "Retrieving GPS data ...", true);

Thread t = new Thread(showWaitDialog);
  t.start();


问:
Maven + Tycho, adding Maven dependencies
We have an Eclipse Plugin which we build using Maven and Tycho. Currently
however, we still provide all project dependencies through a bunch of manually
added JAR files and not by Maven. This is due to the following reasons: (1) The
dependencies are not available through a standard Eclipse update site (at least
not in a current version), (2) the dependencies are not available as bundles.

The biggest part of these dependencies are the Selenium libraries (API, Remote,
browser-specific libs and their transitive dependencies, such as Guava, etc.)

I've wasted hours, trying to pull those dependencies during our Maven build.
Following this SO question, I tried the p2-maven-plugin, created an update
site with our dependencies which I added to my Eclipse target platform. However,
during runtime, classes, which are referenced across different JARs could not be
loaded (I assume, from my very limited OSGi knowledge, because some
necessary information was missing in the MANIFEST.MF files). Here's an example
of the issue, when trying to create a RemoteWebDriver, which uses the
DesiredCapabilities class (both classes in different bundles):

```<code>Exception in thread "Thread-8" java.lang.NoClassDefFoundError: org/openqa/selenium/remote/DesiredCapabilities
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:243)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:126)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:153)
    …
Caused by: java.lang.ClassNotFoundException: org.openqa.selenium.remote.DesiredCapabilities cannot be found by org.seleniumhq.selenium.remote-driver_2.45.0
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:439)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:352)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:344)
    at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:160)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more
</code>```

Is there anything I still need to take care of, when using the p2-maven-plugin? The relevant parts of the pom.xml looked like this:

```<code><plugin>
    <groupId>org.reficio</groupId>
    <artifactId>p2-maven-plugin</artifactId>
    <version>1.1.1-SNAPSHOT</version>
    <executions>
        <execution>
            <id>default-cli</id>
            <configuration>
                <artifacts>
                    <artifact>
                        <id>org.seleniumhq.selenium:selenium-remote-driver:2.45.0</id>
                    </artifact>
                </artifacts>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

答:
I also build an Eclipse plugin with Maven and Tycho. I have the same problem: the bundle org.eclipse.team.svn.core and org.eclipse.team.svn.ui are not available through a standard Eclipse update site.

Maybe you can try this to solve this kind of problem:

In Dependencies, find the box Automated Management of
Dependencies.

Add the wanted plugin using Add...

Choose Analyze code and add dependencies to the MANIFEST.MF via: Import-Package

Click on Add Dependencies so that you find required packages in the box Imported Packages nearby.

Then you can run the Maven build.

Body:
We have an Eclipse Plugin which we build using Maven and Tycho. Currently
however, we still provide all project dependencies through a bunch of manually
added JAR files and not by Maven. This is due to the following reasons: (1) The
dependencies are not available through a standard Eclipse update site (at least
not in a current version), (2) the dependencies are not available as bundles.

The biggest part of these dependencies are the Selenium libraries (API, Remote,
browser-specific libs and their transitive dependencies, such as Guava, etc.)

I've wasted hours, trying to pull those dependencies during our Maven build.
Following this SO question, I tried the p2-maven-plugin, created an update
site with our dependencies which I added to my Eclipse target platform. However,
during runtime, classes, which are referenced across different JARs could not be
loaded (I assume, from my very limited OSGi knowledge, because some
necessary information was missing in the MANIFEST.MF files). Here's an example
of the issue, when trying to create a RemoteWebDriver, which uses the
DesiredCapabilities class (both classes in different bundles):

Exception in thread "Thread-8" java.lang.NoClassDefFoundError: org/openqa/selenium/remote/DesiredCapabilities
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:243)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:126)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:153)
    …
Caused by: java.lang.ClassNotFoundException: org.openqa.selenium.remote.DesiredCapabilities cannot be found by org.seleniumhq.selenium.remote-driver_2.45.0
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:439)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:352)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:344)
    at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:160)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more

Is there anything I still need to take care of, when using the p2-maven-plugin? The relevant parts of the pom.xml looked like this:

<plugin>
    <groupId>org.reficio</groupId>
    <artifactId>p2-maven-plugin</artifactId>
    <version>1.1.1-SNAPSHOT</version>
    <executions>
        <execution>
            <id>default-cli</id>
            <configuration>
                <artifacts>
                    <artifact>
                        <id>org.seleniumhq.selenium:selenium-remote-driver:2.45.0</id>
                    </artifact>
                </artifacts>
            </configuration>
        </execution>
    </executions>
</plugin>


问:
Kotlin's data class, Android Room and custom setter
I got an entity for Android Room which looks like that. So far, no worries.

```<code>@Entity(tableName = "users",
        indices = arrayOf(Index(value = "nickName", unique = true)))
data class User(@ColumnInfo(name = "nickName") var nickName: String,
                @ColumnInfo(name = "password") var password: String) {

    @ColumnInfo(name = "id")
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0
}
</code>```

Now I need to encrypt the password. With Java, this would simply be done with a setter and that would work.

How would you do that with Kotlin. I cannot find a solution to combine Android Room, custom setters and data classes.

答:
You can try something like this:

```<code>@Entity(tableName = "users",
        indices = arrayOf(Index(value = "nickName", unique = true)))
data class User(@ColumnInfo(name = "nickName") var nickName: String,
                private var _password: String) {

    @ColumnInfo(name = "id")
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0

    @ColumnInfo(name = "password")
    var password: String = _password
        set(value) {
            field = "encrypted"
        }

    override fun toString(): String {
        return "User(id=$id, nickName='$nickName', password='$password')"
    }

}
</code>```

But I wouldn't recommend encrypting password inside Entity or modifying it somehow as it isn't its responsibility and you may face errors with double encryption of your password as when you retrieve your entity from database Room will populate the entity with data which will lead to encryption of already encrypted data.

Body:
I got an entity for Android Room which looks like that. So far, no worries.

@Entity(tableName = "users",
        indices = arrayOf(Index(value = "nickName", unique = true)))
data class User(@ColumnInfo(name = "nickName") var nickName: String,
                @ColumnInfo(name = "password") var password: String) {

    @ColumnInfo(name = "id")
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0
}

Now I need to encrypt the password. With Java, this would simply be done with a setter and that would work.

How would you do that with Kotlin. I cannot find a solution to combine Android Room, custom setters and data classes.

Body:
You can try something like this:

@Entity(tableName = "users",
        indices = arrayOf(Index(value = "nickName", unique = true)))
data class User(@ColumnInfo(name = "nickName") var nickName: String,
                private var _password: String) {

    @ColumnInfo(name = "id")
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0

    @ColumnInfo(name = "password")
    var password: String = _password
        set(value) {
            field = "encrypted"
        }

    override fun toString(): String {
        return "User(id=$id, nickName='$nickName', password='$password')"
    }

}

But I wouldn't recommend encrypting password inside Entity or modifying it somehow as it isn't its responsibility and you may face errors with double encryption of your password as when you retrieve your entity from database Room will populate the entity with data which will lead to encryption of already encrypted data.


问:
submitting PHP - HTML DATE to MySQL DATE
i would like to help with my code how to edit HTML input date into MySQL TIMESTEMP format cause my SQL code is invalid and data are not added to my database, Thanks for help

also i asking to check this code on bottom cause 2nd SQL deppends on 1st SQL, thanks

```<code>if (isset($_POST['pridaj_anime_submit'])) {
   $sql_vloz_anime = "INSERT INTO anime (a_name, a_year, a_translated_min, a_translated_max, a_rate_min, a_rate_max, a_edit, a_condition)
                              VALUES ('$_POST[nazov]', '$_POST[rok]', '0', '$_POST[pocet]', '8', '10', '$_POST[preklad]', '$_POST[stav]')";
   mysqli_query($connect_to_db , $sql_vloz_anime);
   $sql_ziskaj_a_id_pridaneho_anime = "SELECT * FROM anime WHERE a_name = '$_POST[nazov]'";
   $run_sql_ziskaj_a_id_pridaneho_anime = mysqli_query($sql_ziskaj_a_id_pridaneho_anime);
   $a_id_ziskane = "";
while ($db_data = mysqli_fetch_assoc($run_sql_ziskaj_a_id_pridaneho_anime)) {
    $a_id_ziskane = $db_data['a_id'];
}

   $sql_vloz_anime_info = "INSERT INTO anime_info (a_id, a_img, a_start, a_stop, a_time_ep, a_akihabara)
                                        VALUES ('$a_id_ziskane' , '$_POST[obrazok]', '$_POST[zaciatok]', '$_POST[koniec]', '$_POST[cas]', '$_POST[akihabara]')";
   mysqli_query($connect_to_db , $sql_vloz_anime_info);
}
</code>```

答:
MySql datetime considered yyyy-mm-dd h:i:s format.

Your input date is like dd-mm-yyyy h:i:s and so on.

Then use convert date to yyyy-mm-dd h:i:s. Read strtotime manual.

For e.g.

```<code>$inputDate = '06-06-2017 05:21:34';
$mysqlDate = date("Y-m-d H:i:s",strtotime($inputDate));

// MySql Query.
INSERT INTO table_name SET `your_field`='$mysqlDate'
</code>```

Body:
i would like to help with my code how to edit HTML input date into MySQL TIMESTEMP format cause my SQL code is invalid and data are not added to my database, Thanks for help

also i asking to check this code on bottom cause 2nd SQL deppends on 1st SQL, thanks

if (isset($_POST['pridaj_anime_submit'])) {
   $sql_vloz_anime = "INSERT INTO anime (a_name, a_year, a_translated_min, a_translated_max, a_rate_min, a_rate_max, a_edit, a_condition)
                              VALUES ('$_POST[nazov]', '$_POST[rok]', '0', '$_POST[pocet]', '8', '10', '$_POST[preklad]', '$_POST[stav]')";
   mysqli_query($connect_to_db , $sql_vloz_anime);
   $sql_ziskaj_a_id_pridaneho_anime = "SELECT * FROM anime WHERE a_name = '$_POST[nazov]'";
   $run_sql_ziskaj_a_id_pridaneho_anime = mysqli_query($sql_ziskaj_a_id_pridaneho_anime);
   $a_id_ziskane = "";
while ($db_data = mysqli_fetch_assoc($run_sql_ziskaj_a_id_pridaneho_anime)) {
    $a_id_ziskane = $db_data['a_id'];
}

   $sql_vloz_anime_info = "INSERT INTO anime_info (a_id, a_img, a_start, a_stop, a_time_ep, a_akihabara)
                                        VALUES ('$a_id_ziskane' , '$_POST[obrazok]', '$_POST[zaciatok]', '$_POST[koniec]', '$_POST[cas]', '$_POST[akihabara]')";
   mysqli_query($connect_to_db , $sql_vloz_anime_info);
}

Body:
MySql datetime considered yyyy-mm-dd h:i:s format.

Your input date is like dd-mm-yyyy h:i:s and so on.

Then use convert date to yyyy-mm-dd h:i:s. Read strtotime manual.

For e.g.

$inputDate = '06-06-2017 05:21:34';
$mysqlDate = date("Y-m-d H:i:s",strtotime($inputDate));

// MySql Query.
INSERT INTO table_name SET `your_field`='$mysqlDate'