问:
Toggle button not working for navigation drawer
I am implementing a Navigation Drawer for my android application. I got the drawer to work by dragging from the side, but the home/toggle button on the action bar doesn't change to the icon I want and doesn't respond to clicks, thou the onDrawerClosed and onDrawerOpened methods defined in it are called.
My code is as follows:

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/drawer_layout"
     android:layout_width="match_parent"
     android:layout_height="match_parent">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/loadingFragment"
        android:name="com.whostr.clients.android.LoadingFragment" />

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/eventFragment"
        android:name="com.whostr.clients.android.EventDisplayFragment"/>

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/emptyFragment"
        android:name="com.whostr.clients.android.EmptyView"/>

<!--  Listview to display slider menu -->
<ListView android:id="@+id/left_drawer"
    android:layout_width = "240dp"
    android:layout_height = "match_parent"
    android:layout_gravity = "start"
    android:choiceMode = "singleChoice"
    android:dividerHeight = "1dp"
    android:divider = "@android:color/transparent"
    android:background="#111"
    />
</code>```

And in the activity I have the following code:

```<code>    @Override
public void onCreate(Bundle savedDataInstace)
{
    super.onCreate(savedDataInstace);
    setContentView(R.layout.eventdisplay);

    fm = getSupportFragmentManager();
    //get fragments by id
    fragments[EVENT_VIEW]= fm.findFragmentById(R.id.eventFragment);
    fragments[LOADING] = fm.findFragmentById(R.id.loadingFragment);
    fragments[EMPTY_VIEW] = fm.findFragmentById(R.id.emptyFragment);

    menuList = getResources().getStringArray(R.array.menuArray);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawwer_open, R.string.drawer_closed)
                        {
                            /*
                             * Called when a drawer has settled in a completely closed state
                             */
                            public void onDrawerClosed(View view)
                            {
                                Log.d("drawerToggle", "Drawer closed");
                                super.onDrawerClosed(view);
                                getActionBar().setTitle(R.string.app_name);
                                invalidateOptionsMenu(); //Creates call to onPrepareOptionsMenu()
                            }

                            /*
                             * Called when a drawer has settled in a completely open state
                             */
                            public void onDrawerOpened(View drawerView)
                            {
                                Log.d("drawerToggle", "Drawer opened");
                                super.onDrawerOpened(drawerView);
                                getActionBar().setTitle("NavigationDrawer");
                                invalidateOptionsMenu();
                            }
                        };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    //Set the adapter for the list view
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, menuList));
    mDrawerList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position,
                long id) {
            Log.d("navigationDrawer", "Clicked on an item");
        }

    });

    FragmentTransaction transaction = fm.beginTransaction();

    //Hide the event view
    transaction.hide(fragments[EVENT_VIEW]);
    transaction.hide(fragments[EMPTY_VIEW]);
    transaction.commit();

    AsyncTask<String, Void, EventResponseCollection> task = new GetEventsNearByAsyncTask().execute();
    try {
        if(task != null)
            events = task.get().getItems();

    } catch (InterruptedException | ExecutionException e) {
        Log.d("viewEvent", "Error when retrieving task details " + e.getMessage());
    }

    if(events == null)
    {
        //show create your own event fragment
        changeFragment(EMPTY_VIEW);
    }
    else
    {
        Log.d("viewEvent", "I have " + events.size());
        //show proper fragment with the first event displayed
        currentEvent = events.get(eventIndex);
        ((EventDisplayFragment) fragments[EVENT_VIEW]).updateFragment(currentEvent);
        changeFragment(EVENT_VIEW);
    }
}

    @Override
public boolean onOptionsItemSelected(MenuItem item)
{
    Log.d("onOptionsItemSelected", "In the on item select");
    //Pass the event to ActionBarDrawerToggle, if it returns
    //true, then it has handled the app icon touch event
    if(mDrawerToggle.onOptionsItemSelected(item))
    {
        Log.d("onOptionsItemSelected", "Clicked on action bar item");
        return true;
    }

    //Handle your other action bar items...

    return super.onOptionsItemSelected(item);
}
</code>```

Does anyone have any suggestion on what I can do? I've tried all solutions I found online to make this work, but apparently I'm out of luck and nothing seems to be working :(

答:
Years later but anyway..... it could help anyone, when you have a layout with a Drawerlayout, the Drawer assumes that the First child is the view to overlap when shown and the Second child is the navigation panel. So in your case you could do something like...

```<code>enter code here

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/drawer_layout"
 android:layout_width="match_parent"
 android:layout_height="match_parent">

<RelativeLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent">

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/loadingFragment"
    android:name="com.whostr.clients.android.LoadingFragment" />

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/eventFragment"
    android:name="com.whostr.clients.android.EventDisplayFragment"/>

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/emptyFragment"
    android:name="com.whostr.clients.android.EmptyView"/>

</RelativeLayout>

<!--  Listview to display slider menu -->
<ListView android:id="@+id/left_drawer"
android:layout_width = "240dp"
android:layout_height = "match_parent"
android:layout_gravity = "start"
android:choiceMode = "singleChoice"
android:dividerHeight = "1dp"
android:divider = "@android:color/transparent"
android:background="#111"
/>
</code>```

So in that way, the Drawer knows that the RelativeLayout is the view to overlap and the ListView is the left panel you want.

Also you have to do in the java code all the things you know.. setting up the toolbar, setting up the drawer indicating the toolbar, setting up the toogle etc... it's all in the comments.

Body:
I am implementing a Navigation Drawer for my android application. I got the drawer to work by dragging from the side, but the home/toggle button on the action bar doesn't change to the icon I want and doesn't respond to clicks, thou the onDrawerClosed and onDrawerOpened methods defined in it are called.
My code is as follows:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/drawer_layout"
     android:layout_width="match_parent"
     android:layout_height="match_parent">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/loadingFragment"
        android:name="com.whostr.clients.android.LoadingFragment" />

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/eventFragment"
        android:name="com.whostr.clients.android.EventDisplayFragment"/>

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/emptyFragment"
        android:name="com.whostr.clients.android.EmptyView"/>

<ListView android:id="@+id/left_drawer"
    android:layout_width = "240dp"
    android:layout_height = "match_parent"
    android:layout_gravity = "start"
    android:choiceMode = "singleChoice"
    android:dividerHeight = "1dp"
    android:divider = "@android:color/transparent"
    android:background="#111"
    />

And in the activity I have the following code:

    @Override
public void onCreate(Bundle savedDataInstace)
{
    super.onCreate(savedDataInstace);
    setContentView(R.layout.eventdisplay);

    fm = getSupportFragmentManager();
    //get fragments by id
    fragments[EVENT_VIEW]= fm.findFragmentById(R.id.eventFragment);
    fragments[LOADING] = fm.findFragmentById(R.id.loadingFragment);
    fragments[EMPTY_VIEW] = fm.findFragmentById(R.id.emptyFragment);

    menuList = getResources().getStringArray(R.array.menuArray);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawwer_open, R.string.drawer_closed)
                        {
                            /*
                             * Called when a drawer has settled in a completely closed state
                             */
                            public void onDrawerClosed(View view)
                            {
                                Log.d("drawerToggle", "Drawer closed");
                                super.onDrawerClosed(view);
                                getActionBar().setTitle(R.string.app_name);
                                invalidateOptionsMenu(); //Creates call to onPrepareOptionsMenu()
                            }

                            /*
                             * Called when a drawer has settled in a completely open state
                             */
                            public void onDrawerOpened(View drawerView)
                            {
                                Log.d("drawerToggle", "Drawer opened");
                                super.onDrawerOpened(drawerView);
                                getActionBar().setTitle("NavigationDrawer");
                                invalidateOptionsMenu();
                            }
                        };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    //Set the adapter for the list view
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, menuList));
    mDrawerList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position,
                long id) {
            Log.d("navigationDrawer", "Clicked on an item");
        }

    });

    FragmentTransaction transaction = fm.beginTransaction();

    //Hide the event view
    transaction.hide(fragments[EVENT_VIEW]);
    transaction.hide(fragments[EMPTY_VIEW]);
    transaction.commit();

    AsyncTask<String, Void, EventResponseCollection> task = new GetEventsNearByAsyncTask().execute();
    try {
        if(task != null)
            events = task.get().getItems();

    } catch (InterruptedException | ExecutionException e) {
        Log.d("viewEvent", "Error when retrieving task details " + e.getMessage());
    }

    if(events == null)
    {
        //show create your own event fragment
        changeFragment(EMPTY_VIEW);
    }
    else
    {
        Log.d("viewEvent", "I have " + events.size());
        //show proper fragment with the first event displayed
        currentEvent = events.get(eventIndex);
        ((EventDisplayFragment) fragments[EVENT_VIEW]).updateFragment(currentEvent);
        changeFragment(EVENT_VIEW);
    }
}

    @Override
public boolean onOptionsItemSelected(MenuItem item)
{
    Log.d("onOptionsItemSelected", "In the on item select");
    //Pass the event to ActionBarDrawerToggle, if it returns
    //true, then it has handled the app icon touch event
    if(mDrawerToggle.onOptionsItemSelected(item))
    {
        Log.d("onOptionsItemSelected", "Clicked on action bar item");
        return true;
    }

    //Handle your other action bar items...

    return super.onOptionsItemSelected(item);
}

Does anyone have any suggestion on what I can do? I've tried all solutions I found online to make this work, but apparently I'm out of luck and nothing seems to be working :(

Body:
Years later but anyway..... it could help anyone, when you have a layout with a Drawerlayout, the Drawer assumes that the First child is the view to overlap when shown and the Second child is the navigation panel. So in your case you could do something like...

enter code here

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/drawer_layout"
 android:layout_width="match_parent"
 android:layout_height="match_parent">

<RelativeLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent">

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/loadingFragment"
    android:name="com.whostr.clients.android.LoadingFragment" />

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/eventFragment"
    android:name="com.whostr.clients.android.EventDisplayFragment"/>

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/emptyFragment"
    android:name="com.whostr.clients.android.EmptyView"/>

</RelativeLayout>

<!--  Listview to display slider menu -->
<ListView android:id="@+id/left_drawer"
android:layout_width = "240dp"
android:layout_height = "match_parent"
android:layout_gravity = "start"
android:choiceMode = "singleChoice"
android:dividerHeight = "1dp"
android:divider = "@android:color/transparent"
android:background="#111"
/>

So in that way, the Drawer knows that the RelativeLayout is the view to overlap and the ListView is the left panel you want.

Also you have to do in the java code all the things you know.. setting up the toolbar, setting up the drawer indicating the toolbar, setting up the toogle etc... it's all in the comments.


来源: stackexchange

问:
Building URL- Confusion on a couple of lines
I am trying to understand this class/method involved in a Udacity Android Development course, and I am confused on a couple lines. I was wondering how the String Param_QUERY = "q" works, and looking for any explanation. In addition, I was also confused about PARAM_SORT, and sortBy. Any explanation on these three variables and how they are used would be much appreciated. Thanks, and sorry for any strange formatting. </p>

```<code>public class NetworkUtils {

     final static String GITHUB_BASE_URL =
             "https://api.github.com/search/repositories";

     final static String PARAM_QUERY = "q";

     final static String PARAM_SORT = "sort";
     final static String sortBy = "stars";

/**
 * Builds the URL used to query Github.
 *
 * @param githubSearchQuery The keyword that will be queried for.
 * @return The URL to use to query the weather server.
 */
public static URL buildUrl(String githubSearchQuery) {

    Uri builtUri = Uri.parse(GITHUB_BASE_URL).buildUpon()
            .appendQueryParameter(PARAM_QUERY, githubSearchQuery)
            .appendQueryParameter(PARAM_SORT, sortBy)
            .build();

    URL url = null;
    try {
        url = new URL(builtUri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    return url;
}
</code>```

答:
This isn't really an Android issue, but I'll explain what is going on. First, what the code is doing is building a string like:

```<code>https://api.github.com/search/repositories?q=githubSearchQuery&sort=stars
</code>```

This is a REST endpoint, and when you query that page on GitHub, it searches repositories, with the search string passed through q=githubSearchQuery, replaced with of course your input, and sorts the results according to sort=stars, sorting by the number of stars. Now, the Java part works as follows:

```<code>appendQueryParameter(PARAM_SORT, sortBy)
</code>```

For the simple case, with constant strings, this specifies the sort=stars part, plus adds any required & to chain with other parameters.

```<code>appendQueryParameter(PARAM_QUERY, githubSearchQuery)
</code>```

This is similar for the q=githubSearchQuery, but since this is user input, there may be spaces or other special characters in the string, so appendQueryParameter() also mangles your string into valid HTML query parameters. So, if I search for & = /?, I get the query parameter q=%26+%3D+%2F%3F.

By the way, the q= part is not a standard, just a convention for queries (Google uses that too), and sort=stars is an option specific to GitHub.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to understand this class/method involved in a Udacity Android Development course, and I am confused on a couple lines. I was wondering how the String Param_QUERY = "q" works, and looking for any explanation. In addition, I was also confused about PARAM_SORT, and sortBy. Any explanation on these three variables and how they are used would be much appreciated. Thanks, and sorry for any strange formatting.

public class NetworkUtils {

     final static String GITHUB_BASE_URL =
             "https://api.github.com/search/repositories";

     final static String PARAM_QUERY = "q";

     final static String PARAM_SORT = "sort";
     final static String sortBy = "stars";

/**
 * Builds the URL used to query Github.
 *
 * @param githubSearchQuery The keyword that will be queried for.
 * @return The URL to use to query the weather server.
 */
public static URL buildUrl(String githubSearchQuery) {

    Uri builtUri = Uri.parse(GITHUB_BASE_URL).buildUpon()
            .appendQueryParameter(PARAM_QUERY, githubSearchQuery)
            .appendQueryParameter(PARAM_SORT, sortBy)
            .build();

    URL url = null;
    try {
        url = new URL(builtUri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    return url;
}

Body:
This isn't really an Android issue, but I'll explain what is going on. First, what the code is doing is building a string like:

https://api.github.com/search/repositories?q=githubSearchQuery&sort=stars

This is a REST endpoint, and when you query that page on GitHub, it searches repositories, with the search string passed through q=githubSearchQuery, replaced with of course your input, and sorts the results according to sort=stars, sorting by the number of stars. Now, the Java part works as follows:

appendQueryParameter(PARAM_SORT, sortBy)

For the simple case, with constant strings, this specifies the sort=stars part, plus adds any required & to chain with other parameters.

appendQueryParameter(PARAM_QUERY, githubSearchQuery)

This is similar for the q=githubSearchQuery, but since this is user input, there may be spaces or other special characters in the string, so appendQueryParameter() also mangles your string into valid HTML query parameters. So, if I search for & = /?, I get the query parameter q=%26+%3D+%2F%3F.

By the way, the q= part is not a standard, just a convention for queries (Google uses that too), and sort=stars is an option specific to GitHub.


问:
Test for strongly typed views
In asp.net mvc 2 I need to get programatically all the views thar are strongly typed, and show a list for views that are not strongly typed.

How can I do that?

Thanks In Advance.

答:
Strongly-typed views inherit from System.Web.Mvc.ViewPage. Untyped views inherit from System.Web.Mvc.ViewPage. N.B. ViewPage inherits from ViewPage. You would have to load up the compiled assembly containing the views (generated via aspnet_compiler.exe) and then run the following LINQ-to-Objects queries:</p>

```<code>var stronglyTypedViews = from type in assemblyContainingViews.GetTypes()
                         where typeof(ViewPage<>).IsAssignableFrom(type)
                         select type;
var weaklyTypedViews = from type in assemblyContainingViews.GetTypes()
                       where typeof(ViewPage).IsAssignableFrom(type)
                          && !typeof(ViewPage<>).IsAssignableFrom(type)
                       select type;
</code>```

ContentLicense: CC BY-SA 2.5

Title: Test for strongly typed views

Body:
Strongly-typed views inherit from System.Web.Mvc.ViewPage. Untyped views inherit from System.Web.Mvc.ViewPage. N.B. ViewPage inherits from ViewPage. You would have to load up the compiled assembly containing the views (generated via aspnet_compiler.exe) and then run the following LINQ-to-Objects queries:

var stronglyTypedViews = from type in assemblyContainingViews.GetTypes()
                         where typeof(ViewPage<>).IsAssignableFrom(type)
                         select type;
var weaklyTypedViews = from type in assemblyContainingViews.GetTypes()
                       where typeof(ViewPage).IsAssignableFrom(type)
                          && !typeof(ViewPage<>).IsAssignableFrom(type)
                       select type;


问:
Call a Google App Maker App with a parameter
Hello i am new here so if i ask a stupid question please forgive me.

We at AppAtSchool are working with Google ApMaker and we want to call a published App with 2 parameters. How can we read those in App Maker? Thanks in advance!

答:
I'm guessing, that you are trying to read page URL parameters. In this case you can pass parameters like this:

```<code>https://script.google.com/<SomeMagic>/exec/?param1=value1&param2=value2#PageName
</code>```

And then read them in page onAttach event(https://developers.google.com/appmaker/ui/logic#events):

```<code>google.script.url.getLocation(function(location) {
  var params = location.parameter;
  var param1 = params.param1;
  var param2 = params.param2;

  // Use parameters...
});
</code>```

Maybe you also will need a way to genarate such links with parameters:

Integration between different Google Appmaker Apps

Body:
I'm guessing, that you are trying to read page URL parameters. In this case you can pass parameters like this:

https://script.google.com/<SomeMagic>/exec/?param1=value1&param2=value2#PageName

And then read them in page onAttach event(https://developers.google.com/appmaker/ui/logic#events):

google.script.url.getLocation(function(location) {
  var params = location.parameter;
  var param1 = params.param1;
  var param2 = params.param2;

  // Use parameters...
});

Maybe you also will need a way to genarate such links with parameters:

Integration between different Google Appmaker Apps


问:
How to take R.string value instead of hardcoded value, if it's a class field?
For instance I want to take this

```<code>public class SomeClass {
    public static final String GREET_STRING = "Hello!";
    //...
</code>```

and change it to something like:

```<code>public class SomeClass {
    public static final String GREET_STRING = getString(R.string.greet_string);
    //...
</code>```

Can this be done or do I need some kind of Context instantiation to get the resources for the string loading?

答: To use getString() you will need a context. A Resource string cannot be static final because it is possible for String resources to change as you change Locales (if you have multiple String files such as strings.xml (us) and strings.xml (uk))

Body:
For instance I want to take this

public class SomeClass {
    public static final String GREET_STRING = "Hello!";
    //...

and change it to something like:

public class SomeClass {
    public static final String GREET_STRING = getString(R.string.greet_string);
    //...

Can this be done or do I need some kind of Context instantiation to get the resources for the string loading?


问:
Centering an unordered list
Have an image with a h2 that's centered to it, and want the list below it to also be centered. Been struggling for just over an hour now and don't seem to be getting anywhere with it. Any suggestions?

.images {
  display: inline-block;
  text-align: center;
  width: 33%;
  /* all ements align to the largest element within the div */
  vertical-align: top;
}

.images ol {
  width: 70%;
}

.images ol li {
  line-height: 1.2em;
  border: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="images">
  <h3>Panacotta Vanilla</h3>
  <img src="photo1.png.png">
  <p>recipe ingridients</p>
  <ol>
    <li>Macro free Ranged Chicken</li>
    <li>Cover chicken in almond meal</li>
    <li>Add cayenne pepper, chilli flakes, mixed herbs and paprika</li>
    <li>Cook until all pink of chicken disappears Salad
    </li>

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

答:
Run this in full page view for best results.

.images{
    display:inline-block;
    text-align:center;
    width:33%;
    /* all ements align to the largest element within the div */
    vertical-align:top;

}

.images ol{
    margin-left:auto;width:100%;margin-right:auto;
}
.images ol li{
  text-align:left;
  margin-left:15%;margin-right:20%;
  line-height:1.2em;
  border:0;

}

   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "images">
  <h3>Panacotta Vanilla</h3>
    <img src = "photo1.png.png">
    <p>recipe ingridients</p>
    <ol id="mylist">
     <li>Macro free Ranged Chicken</li>
     <li>Cover chicken in almond meal</li>
     <li>Add cayenne pepper, chilli flakes, mixed herbs and paprika</li>
     <li>Cook until all pink of chicken disappears
     Salad</li>

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

Title: Centering an unordered list

Body:
Have an image with a h2 that's centered to it, and want the list below it to also be centered. Been struggling for just over an hour now and don't seem to be getting anywhere with it. Any suggestions?

.images {
  display: inline-block;
  text-align: center;
  width: 33%;
  /* all ements align to the largest element within the div */
  vertical-align: top;
}

.images ol {
  width: 70%;
}

.images ol li {
  line-height: 1.2em;
  border: 0;
}

Panacotta Vanilla

recipe ingridients

Macro free Ranged Chicken

Cover chicken in almond meal

Add cayenne pepper, chilli flakes, mixed herbs and paprika

Cook until all pink of chicken disappears Salad

Body:
Run this in full page view for best results.

.images{
    display:inline-block;
    text-align:center;
    width:33%;
    /* all ements align to the largest element within the div */
    vertical-align:top;

}

.images ol{
    margin-left:auto;width:100%;margin-right:auto;
}
.images ol li{
  text-align:left;
  margin-left:15%;margin-right:20%;
  line-height:1.2em;
  border:0;

}

<div class = "images">
  <h3>Panacotta Vanilla</h3>
    <img src = "photo1.png.png">
    <p>recipe ingridients</p>
    <ol id="mylist">
     <li>Macro free Ranged Chicken</li>
     <li>Cover chicken in almond meal</li>
     <li>Add cayenne pepper, chilli flakes, mixed herbs and paprika</li>
     <li>Cook until all pink of chicken disappears
     Salad</li>

    </ol>
  </div>


问:
How to implement ng2-ui (NPM package) using Angular CLI?
I wish to use the following NPM package with Angular CLI: ng2-ui

The implementation guide is for SystemJS, and not for Webpack, what is used by Angular CLI, what I have to use in this project.

What did I already do?

Installed the package by npm install ng2-ui --save

Added the following line to app.module.ts

```<code>import { Ng2UIModule } from 'ng2-ui';
</code>```

Added Ng2UIModule to the imports array in @NgModule.

By this point I didn't use Ng2UIModule in any of the components yet and before doing the mentioned operations the application worked just fine.

When I try to run the application by ng serve, I get the following error in console:

```<code>ERROR in [default] C:\tools\test-package.net\node_modules\ng2-ui\dist\index.d.ts:1:31
Cannot find module 'ng2-overlay'.

ERROR in [default] C:\tools\test-package.net\node_modules\ng2-ui\dist\index.d.ts:2:32
Cannot find module 'ng2-map'.

ERROR in [default] C:\tools\test-package.net\node_modules\ng2-ui\dist\index.d.ts:3:60
Cannot find module 'ng2-popup'.

ERROR in [default] C:\tools\test-package.net\node_modules\ng2-ui\dist\index.d.ts:4:39
Cannot find module 'ng2-scrollable'.
</code>```

I guess the application simply lacks the following systemjs.config.js settings:

```<code>map['ng2-ui'] =  'node_modules/ng2-ui/dist';
packages['ng2-ui'] = {main: 'ng2-ui.umd.js', defaultExtension: 'js'}
</code>```

Just I don't know how to make it work in the Angular CLI version of Webpack...

(Currently I use Angular CLI 1.0.0-beta.17)

Thanks for your help!

答:
the ng2-ui has been changed to @ngui/overlay https://github.com/ng2-ui/overlay.

Here is my sample code.

ex.component.html

  Div 1

  Loading data......

  Loading data......

<button (click)="showOverlay($event)" class='btn btn-success'>Show Overlay</button>
<button (click)="hideOverlay()" class='btn btn-danger'>Hide Overlay</button>

<button (click)="showOverlay2($event)" class='btn btn-success'>Show Overlay</button>
<button (click)="hideOverlay2()" class='btn btn-danger'>Hide Overlay</button>```
</div>
</div>
</p>

<p>ex.component.ts
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component, OnInit } from '@angular/core';
import { NguiOverlayManager } from '@ngui/overlay';
@Component({
  selector: 'app-ex',
  templateUrl: './ex.component.html',
  styleUrls: [ './ex.component.css' ],
  providers:[NguiOverlayManager]

})
export class ExComponent implements OnInit {

  constructor(private overManager:NguiOverlayManager) { }

  ngOnInit() {
  }

  showOverlay(event: Event) {

    this.overManager.open('overlay',event);
  }

  hideOverlay() {
    this.overManager.close('overlay');
  }

  showOverlay2(event: Event) {

    this.overManager.open('overlay2', event);
  }

  hideOverlay2() {
    this.overManager.close('overlay2');
  }

}</code>```

Add import { NguiOverlayModule } from '@ngui/overlay'; to the module and add NguiOverlayModule to the imports array.

Body:
I wish to use the following NPM package with Angular CLI: ng2-ui

The implementation guide is for SystemJS, and not for Webpack, what is used by Angular CLI, what I have to use in this project.

What did I already do?

Installed the package by npm install ng2-ui --save

Added the following line to app.module.ts

import { Ng2UIModule } from 'ng2-ui';

Added Ng2UIModule to the imports array in @NgModule.

By this point I didn't use Ng2UIModule in any of the components yet and before doing the mentioned operations the application worked just fine.

When I try to run the application by ng serve, I get the following error in console:

ERROR in [default] C:\tools\test-package.net\node_modules\ng2-ui\dist\index.d.ts:1:31
Cannot find module 'ng2-overlay'.

ERROR in [default] C:\tools\test-package.net\node_modules\ng2-ui\dist\index.d.ts:2:32
Cannot find module 'ng2-map'.

ERROR in [default] C:\tools\test-package.net\node_modules\ng2-ui\dist\index.d.ts:3:60
Cannot find module 'ng2-popup'.

ERROR in [default] C:\tools\test-package.net\node_modules\ng2-ui\dist\index.d.ts:4:39
Cannot find module 'ng2-scrollable'.

I guess the application simply lacks the following systemjs.config.js settings:

map['ng2-ui'] =  'node_modules/ng2-ui/dist';
packages['ng2-ui'] = {main: 'ng2-ui.umd.js', defaultExtension: 'js'}

Just I don't know how to make it work in the Angular CLI version of Webpack...

(Currently I use Angular CLI 1.0.0-beta.17)

Thanks for your help!

Body:
the ng2-ui has been changed to @ngui/overlay https://github.com/ng2-ui/overlay.

Here is my sample code.

ex.component.html

<div id='div1' class='container row'>
  Div 1

</div>

<div id="overlay" ngui-overlay-of="div1" style='background-color:black'>
  Loading data......
</div>

<div id="overlay2" ngui-overlay-of="div1" style='background-color:blue'>
  Loading data......
</div>

<button (click)="showOverlay($event)" class='btn btn-success'>Show Overlay</button>
<button (click)="hideOverlay()" class='btn btn-danger'>Hide Overlay</button>

<br /><br />
<button (click)="showOverlay2($event)" class='btn btn-success'>Show Overlay</button>
<button (click)="hideOverlay2()" class='btn btn-danger'>Hide Overlay</button>

ex.component.ts

import { Component, OnInit } from '@angular/core';
import { NguiOverlayManager } from '@ngui/overlay';
@Component({
  selector: 'app-ex',
  templateUrl: './ex.component.html',
  styleUrls: [ './ex.component.css' ],
  providers:[NguiOverlayManager]

})
export class ExComponent implements OnInit {

  constructor(private overManager:NguiOverlayManager) { }

  ngOnInit() {
  }

  showOverlay(event: Event) {

    this.overManager.open('overlay',event);
  }

  hideOverlay() {
    this.overManager.close('overlay');
  }

  showOverlay2(event: Event) {

    this.overManager.open('overlay2', event);
  }

  hideOverlay2() {
    this.overManager.close('overlay2');
  }

}

Add import { NguiOverlayModule } from '@ngui/overlay'; to the module and add NguiOverlayModule to the imports array.


问:
Can you use an Azure Function to trigger an Azure Logic App?
The time triggers within Logic Apps aren't really specific enough to meet my scheduling requirements, but using the scheduler looks overly expensive for our needs.

I see that functions can use CRON for timed triggering, so wondered if functions can actually be used to call Logic Apps, and hence have the Logic Apps triggered by the CRON time schedules?

答: Logic Apps support complex schedule just like Azure Scheduler, currently this is configurable only via code view, but will soon be available in designer. You can view the syntax here.</p>


问:
Background Position Transition Not Working in Safari
I'm changing the background position of an element on hover, it is working fine on chrome but when I try it on safari the background jumps up and down rapidly, I've tried applying a few fixes I've found from a google search and it's still not working, here is the code (the html, the original rules, the transition property, and the :hover rules) - </p>

```<code><div class="port-big">
  <a class="port-item campbell" href="http://www.campbellmgmt.com/" target="_blank">
    <div class="port-img"></div>
    <h3 class="port-title">Campbell Property Management</h3>
    <img class="port-logo" src="images/campbell-logo-white.png" />
    <p class="port-descr">Campbell Property Management was my largest project while I was at Juvo Web. The client was looking to completely update their website and
    add some new features. After extensive research on property and real estate UI/UX I designed the new front end and implemented it on their website.</p>
  </a>
</div>

.port-img {
  overflow: hidden;
  width: 100%;
  height: 100%;
  background-blend-mode: overlay;
  background-size: cover;
  background-position: center top;
  background-position-x: 0%;
  background-position-y: 0%;
}

.campbell .port-img {
  background-image: url(../../images/campbell-screenshot.png);
  background-color: #dd3a00;
}

.port-title, .port-descr, .port-logo, .port-img {
  -webkit-transition: all ease-in-out 0.4s,
                      background-position linear 24s;
  transition: all ease-in-out 0.4s,
              background-position linear 24s;
}

.port-big .port-item:hover .port-img {
  background-position: center bottom;
  background-position-x: 0%;
  background-position-y: 100%;
}
</code>```

答:
I found the answer, When I separated the background-position transition into it's own rule it worked fine, ended up looking like this - </p>

```<code>.port-img {
  -webkit-transition: background-position linear 24s;
  -moz-transition: background-position linear 24s;
  -o-transition: background-position linear 24s;
  transition: background-position linear 24s;
}
</code>```

Body:
I'm changing the background position of an element on hover, it is working fine on chrome but when I try it on safari the background jumps up and down rapidly, I've tried applying a few fixes I've found from a google search and it's still not working, here is the code (the html, the original rules, the transition property, and the :hover rules) -

Campbell Property Management

Campbell Property Management was my largest project while I was at Juvo Web. The client was looking to completely update their website and
    add some new features. After extensive research on property and real estate UI/UX I designed the new front end and implemented it on their website.

.port-img {
  overflow: hidden;
  width: 100%;
  height: 100%;
  background-blend-mode: overlay;
  background-size: cover;
  background-position: center top;
  background-position-x: 0%;
  background-position-y: 0%;
}

.campbell .port-img {
  background-image: url(../../images/campbell-screenshot.png);
  background-color: #dd3a00;
}

.port-title, .port-descr, .port-logo, .port-img {
  -webkit-transition: all ease-in-out 0.4s,
                      background-position linear 24s;
  transition: all ease-in-out 0.4s,
              background-position linear 24s;
}

.port-big .port-item:hover .port-img {
  background-position: center bottom;
  background-position-x: 0%;
  background-position-y: 100%;
}

Body:
I found the answer, When I separated the background-position transition into it's own rule it worked fine, ended up looking like this -

.port-img {
  -webkit-transition: background-position linear 24s;
  -moz-transition: background-position linear 24s;
  -o-transition: background-position linear 24s;
  transition: background-position linear 24s;
}


问:
Embedded Signing View Docusign returning 404
I am trying to get the embedded signing view to redirect my user so they can sign the document. Everytime I make the request I get a 404 with no message. There is nothing with the response other than the HTTP code. Sending the envelope works completely fine, I get an email everytime I try to test this.

```<code>$data = json_encode(array(
  "returnUrl" => base_url() . "dashboard/home",
  "authenticationMethod" => "email",
  "email" => $this->userEmail,
  "userName" => "seller",
  "clientUserId" => $this->user,
  'recipientId' => '1'
));

$ch = curl_init($this->baseUrl . "/envelope/$this->envelopeId/views/recipient");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Content-Type: application/json',
  'Content-Length: ' . strlen($data),
  'X-DocuSign-Authentication: ' . $this->header
  )
);

$resp = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $headers = curl_getinfo($ch, CURLINFO_HEADER_OUT);

if ($status != 201) {
  error_log($resp);
  die();
}

$response = json_decode($resp, true);
return $response['url'];
</code>```

I have followed the examples on Docusign's documentation and even have this working in another section, this just uses composite templates instead. I tried searching for the Embedded Signing returning a 404 but found nothing. I would attach the error message but all it gives is that its receiving a 404. Thank you in advance!

答:
You have misspelled envelopes

```<code>$ch = curl_init($this->baseUrl . "/envelope/$this->envelopeId/views/recipient");
</code>```

should be

```<code>$ch = curl_init($this->baseUrl . "/envelopes/$this->envelopeId/views/recipient");
</code>```

The url for the EnvelopeViews:createRecipient should be of the following format.

POST /v2/accounts/{accountId}/envelopes/{envelopeId}/views/recipient

For example, if you are using the Sandbox environment then you will have to do a HTTP POST to the following url

https://demo.docusign.net/restapi/v2/accounts/{accountId}/envelopes/{envelopeId}/views/recipient

Body:
I am trying to get the embedded signing view to redirect my user so they can sign the document. Everytime I make the request I get a 404 with no message. There is nothing with the response other than the HTTP code. Sending the envelope works completely fine, I get an email everytime I try to test this.

$data = json_encode(array(
  "returnUrl" => base_url() . "dashboard/home",
  "authenticationMethod" => "email",
  "email" => $this->userEmail,
  "userName" => "seller",
  "clientUserId" => $this->user,
  'recipientId' => '1'
));

$ch = curl_init($this->baseUrl . "/envelope/$this->envelopeId/views/recipient");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Content-Type: application/json',
  'Content-Length: ' . strlen($data),
  'X-DocuSign-Authentication: ' . $this->header
  )
);

$resp = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $headers = curl_getinfo($ch, CURLINFO_HEADER_OUT);

if ($status != 201) {
  error_log($resp);
  die();
}

$response = json_decode($resp, true);
return $response['url'];

I have followed the examples on Docusign's documentation and even have this working in another section, this just uses composite templates instead. I tried searching for the Embedded Signing returning a 404 but found nothing. I would attach the error message but all it gives is that its receiving a 404. Thank you in advance!

Body:
You have misspelled envelopes

$ch = curl_init($this->baseUrl . "/envelope/$this->envelopeId/views/recipient");

should be

$ch = curl_init($this->baseUrl . "/envelopes/$this->envelopeId/views/recipient");

The url for the EnvelopeViews:createRecipient should be of the following format.

POST /v2/accounts/{accountId}/envelopes/{envelopeId}/views/recipient

For example, if you are using the Sandbox environment then you will have to do a HTTP POST to the following url

https://demo.docusign.net/restapi/v2/accounts/{accountId}/envelopes/{envelopeId}/views/recipient


问:
C loop with two conditions - difference
Whats the difference between:

```<code>int i;
for( i=0;i<5 && i<3;i++)
{
    printf("stackoverflow.com");
}
</code>```

and

```<code>int i;
for( i=0;i<5 , i<3;i++)
{
    printf("stackoverflow.com");
}
</code>```

I mean use of && instead of ','

Regards

答:
When using the comma operator , in a statement like the:

```<code>( <expression1>, <expression2> )
</code>```

the <expression1> is evaluated and discarded, then the <expression2> is evaluated and its value is returned. In summary the right most expression is evaluated and its value returned. Other expressions are evaluated and discarded. So your statement of:

```<code>for(i=0; i<5 , i<3; i++)
</code>```

is equivalent to:

```<code>for(i=0; i<3; i++)
</code>```

As for the first statement, this expression:

```<code>(i<5 && i<3)
</code>```

is a simple AND boolean evaluation. A funny one because it is enough to say:

```<code>(i<3)
</code>```

Long story short, who ever made this example probably expects you to say "both conditions evaluate to second expression".

Title: C loop with two conditions - difference

Body:
Whats the difference between:

int i;
for( i=0;i<5 && i<3;i++)
{
    printf("stackoverflow.com");
}

and

int i;
for( i=0;i<5 , i<3;i++)
{
    printf("stackoverflow.com");
}

I mean use of && instead of ','

Regards

Body:
When using the comma operator , in a statement like the:

( <expression1>, <expression2> )

the <expression1> is evaluated and discarded, then the <expression2> is evaluated and its value is returned. In summary the right most expression is evaluated and its value returned. Other expressions are evaluated and discarded. So your statement of:

for(i=0; i<5 , i<3; i++)

is equivalent to:

for(i=0; i<3; i++)

As for the first statement, this expression:

(i<5 && i<3)

is a simple AND boolean evaluation. A funny one because it is enough to say:

(i<3)

Long story short, who ever made this example probably expects you to say "both conditions evaluate to second expression".


问:
R ggplot2 faceting standardizing date limits
I am trying to create a graph with 3 survey seasons, each crossing over a year boundary (ie 2009-2010, 2010-2011, 2016-2017), but where survey effort starts and ends at a different point in each survey season. What I currently have is:

I'd like to end up with each x-axis showing November-April of that survey season (ie the 2009-2010 survey season would show November 2009-April 2010) to better show where survey effort is lacking in terms of interannual comparison. I'm just not sure how to do that within the context of scale_x_date(). My current scale statement is simply scale_x_date(date_breaks = '1 month',date_labels='%b')+ My only thought so far is to basically just create a bunch of NA data with the relevant dates and continue to let the dates scale automatically, but for my future reference I'm wondering if there's a better way to create those kind of "year-less" date limits.

Some more information:

the head of my data (which in this case will be in the top-left facet of the plot):

```<code>structure(list(SPID = c("Cho_001", "Cho_001", "Cho_001", "Cho_001",
"Cho_001", "Cho_001"), season = c(2009, 2009, 2009, 2009, 2009,
2009), Date = structure(c(14579, 14580, 14581, 14582, 14583,
14584), class = "Date"), DayOfYear = c(335, 336, 337, 338, 339,
340), year = c(2009L, 2009L, 2009L, 2009L, 2009L, 2009L), month = c(12L,
12L, 12L, 12L, 12L, 12L), day = 1:6, RatePerMin = c(3.6667, 4.8667,
13.1667, 23.0333, 24.6667, 25.4667), N = c(3L, 30L, 30L, 30L,
30L, 30L), sd = c(3.5119, 6.9269, 8.1074, 4.2789, 4.9434, 4.2729
), se = c(2.0276, 1.2647, 1.4802, 0.7812, 0.9025, 0.7801), Illu = c(0.999348417128253,
0.999986511310919, 0.991435775301254, 0.955915838251852, 0.894428866388813,
0.810868946410883)), .Names = c("SPID", "season", "Date", "DayOfYear",
"year", "month", "day", "RatePerMin", "N", "sd", "se", "Illu"
), row.names = c(NA, -6L), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), vars = c("SPID", "season", "year", "month",
"day", "Date"), drop = TRUE, indices = list(0L, 1L, 2L, 3L, 4L,
    5L), group_sizes = c(1L, 1L, 1L, 1L, 1L, 1L), biggest_group_size = 1L, labels = structure(list(
    SPID = c("Cho_001", "Cho_001", "Cho_001", "Cho_001", "Cho_001",
    "Cho_001"), season = c(2009, 2009, 2009, 2009, 2009, 2009
    ), year = c(2009L, 2009L, 2009L, 2009L, 2009L, 2009L), month = c(12L,
    12L, 12L, 12L, 12L, 12L), day = 1:6, Date = structure(c(14579,
    14580, 14581, 14582, 14583, 14584), class = "Date")), row.names = c(NA,
-6L), class = "data.frame", vars = c("SPID", "season", "year",
"month", "day", "Date"), drop = TRUE, .Names = c("SPID", "season",
"year", "month", "day", "Date")))
</code>```

Body:
I am trying to create a graph with 3 survey seasons, each crossing over a year boundary (ie 2009-2010, 2010-2011, 2016-2017), but where survey effort starts and ends at a different point in each survey season. What I currently have is:

I'd like to end up with each x-axis showing November-April of that survey season (ie the 2009-2010 survey season would show November 2009-April 2010) to better show where survey effort is lacking in terms of interannual comparison. I'm just not sure how to do that within the context of scale_x_date(). My current scale statement is simply scale_x_date(date_breaks = '1 month',date_labels='%b')+ My only thought so far is to basically just create a bunch of NA data with the relevant dates and continue to let the dates scale automatically, but for my future reference I'm wondering if there's a better way to create those kind of "year-less" date limits.

Some more information:

the head of my data (which in this case will be in the top-left facet of the plot):

structure(list(SPID = c("Cho_001", "Cho_001", "Cho_001", "Cho_001",
"Cho_001", "Cho_001"), season = c(2009, 2009, 2009, 2009, 2009,
2009), Date = structure(c(14579, 14580, 14581, 14582, 14583,
14584), class = "Date"), DayOfYear = c(335, 336, 337, 338, 339,
340), year = c(2009L, 2009L, 2009L, 2009L, 2009L, 2009L), month = c(12L,
12L, 12L, 12L, 12L, 12L), day = 1:6, RatePerMin = c(3.6667, 4.8667,
13.1667, 23.0333, 24.6667, 25.4667), N = c(3L, 30L, 30L, 30L,
30L, 30L), sd = c(3.5119, 6.9269, 8.1074, 4.2789, 4.9434, 4.2729
), se = c(2.0276, 1.2647, 1.4802, 0.7812, 0.9025, 0.7801), Illu = c(0.999348417128253,
0.999986511310919, 0.991435775301254, 0.955915838251852, 0.894428866388813,
0.810868946410883)), .Names = c("SPID", "season", "Date", "DayOfYear",
"year", "month", "day", "RatePerMin", "N", "sd", "se", "Illu"
), row.names = c(NA, -6L), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), vars = c("SPID", "season", "year", "month",
"day", "Date"), drop = TRUE, indices = list(0L, 1L, 2L, 3L, 4L,
    5L), group_sizes = c(1L, 1L, 1L, 1L, 1L, 1L), biggest_group_size = 1L, labels = structure(list(
    SPID = c("Cho_001", "Cho_001", "Cho_001", "Cho_001", "Cho_001",
    "Cho_001"), season = c(2009, 2009, 2009, 2009, 2009, 2009
    ), year = c(2009L, 2009L, 2009L, 2009L, 2009L, 2009L), month = c(12L,
    12L, 12L, 12L, 12L, 12L), day = 1:6, Date = structure(c(14579,
    14580, 14581, 14582, 14583, 14584), class = "Date")), row.names = c(NA,
-6L), class = "data.frame", vars = c("SPID", "season", "year",
"month", "day", "Date"), drop = TRUE, .Names = c("SPID", "season",
"year", "month", "day", "Date")))

Body:
We could use the day after Nov-01 to plot in the x-axis, which depends just in the month and day.

data$start <- ymd(paste(year(data$Date), "-11-01", sep=""))
data$yday = data$Date - data$start #yday(data$Date)
data$yday = ifelse(data$yday < 0, 365 + data$yday,data$yday)

bre <- seq(1,152,1)
lab <- format(seq.Date(ymd("2010-11-01"),ymd("2011-04-01"),by="day"),format= "%b %d")

library(ggplot2)
library(lubridate)
x11(); ggplot(data) + geom_bar(aes(x = yday , y = RatePerMin), stat = "identity") +
  scale_x_continuous(breaks = bre,
  labels = lab, limits = c(1,152))+ theme(axis.text.x = element_text(angle = 90, hjust = 1))+
  facet_grid(year ~ .)

PS: I think that adding some NA values (at each Nov-01 and Apr 01) would be more effective than this solution.

Data:

structure(list(SPID = c("Cho_001", "Cho_001", "Cho_001", "Cho_001",
"Cho_001", "Cho_001", "Cho_001", "Cho_001", "Cho_001", "Cho_001",
"Cho_001", "Cho_001", "Cho_001", "Cho_001", "Cho_001"), season = c(2009,
2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009,
2009, 2009, 2009), Date = structure(c(14579, 14580, 14581, 14582,
14583, 14584, 14944, 14945, 14946, 14947, 14948, 14949, 14610,
14611, 14612), class = "Date"), DayOfYear = c(335, 336, 337,
338, 339, 340, 335, 336, 337, 338, 339, 340, 335, 336, 337),
    year = c(2009, 2009, 2009, 2009, 2009, 2009, 2010, 2010,
    2010, 2010, 2010, 2010, 2010, 2010, 2010), month = c(12L,
    12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L,
    12L, 12L), day = c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L,
    5L, 6L, 1L, 2L, 3L), RatePerMin = c(3.6667, 4.8667, 13.1667,
    23.0333, 24.6667, 25.4667, 3.6667, 4.8667, 13.1667, 23.0333,
    24.6667, 25.4667, 3.6667, 4.8667, 13.1667), N = c(3L, 30L,
    30L, 30L, 30L, 30L, 3L, 30L, 30L, 30L, 30L, 30L, 3L, 30L,
    30L), sd = c(3.5119, 6.9269, 8.1074, 4.2789, 4.9434, 4.2729,
    3.5119, 6.9269, 8.1074, 4.2789, 4.9434, 4.2729, 3.5119, 6.9269,
    8.1074), se = c(2.0276, 1.2647, 1.4802, 0.7812, 0.9025, 0.7801,
    2.0276, 1.2647, 1.4802, 0.7812, 0.9025, 0.7801, 2.0276, 1.2647,
    1.4802), Illu = c(0.999348417128253, 0.999986511310919, 0.991435775301254,
    0.955915838251852, 0.894428866388813, 0.810868946410883,
    0.999348417128253, 0.999986511310919, 0.991435775301254,
    0.955915838251852, 0.894428866388813, 0.810868946410883,
    0.999348417128253, 0.999986511310919, 0.991435775301254),
    yday = c(30, 31, 32, 33, 34, 35, 30, 31, 32, 33, 34, 35,
    61, 62, 63), start = structure(c(14549, 14549, 14549, 14549,
    14549, 14549, 14914, 14914, 14914, 14914, 14914, 14914, 14914,
    14914, 14914), class = "Date"), end = structure(c(14700,
    14700, 14700, 14700, 14700, 14700, 15065, 15065, 15065, 15065,
    15065, 15065, 15065, 15065, 15065), class = "Date")), .Names = c("SPID",
"season", "Date", "DayOfYear", "year", "month", "day", "RatePerMin",
"N", "sd", "se", "Illu", "yday", "start", "end"), row.names = c(NA,
15L), vars = c("SPID", "season", "year", "month", "day", "Date"
), drop = TRUE, indices = list(0L, 1L, 2L, 3L, 4L, 5L), group_sizes = c(1L,
1L, 1L, 1L, 1L, 1L), biggest_group_size = 1L, labels = structure(list(
    SPID = c("Cho_001", "Cho_001", "Cho_001", "Cho_001", "Cho_001",
    "Cho_001"), season = c(2009, 2009, 2009, 2009, 2009, 2009
    ), year = c(2009L, 2009L, 2009L, 2009L, 2009L, 2009L), month = c(12L,
    12L, 12L, 12L, 12L, 12L), day = 1:6, Date = structure(c(14579,
    14580, 14581, 14582, 14583, 14584), class = "Date")), .Names = c("SPID",
"season", "year", "month", "day", "Date"), row.names = c(NA,
-6L), class = "data.frame", vars = c("SPID", "season", "year",
"month", "day", "Date"), drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))


答:
In this case they will do exactly the same.

The thing that differs is that in the first case i<3 will not be evaluated every time. A statement on the form A && B will only execute B if the return value of A is true. The reason is that the logical value of && is true if both operands are true. If one of them are false, the whole expression is false, so if the left operand evaluates to false, there's no need to evaluate the right operand.

The comma operator on the other hand evaluates both operands, but the result of the left operand is discarded.

Title: C loop with two conditions - difference


问:
gradlew/Android Studio - Unsupported major.minor version 52.0
I am running:

```<code>./gradlew assembleDebug
</code>```

from my project folder and getting the error:

```<code>* What went wrong:
A problem occurred evaluating project ':app'.
> java.lang.UnsupportedClassVersionError: com/android/build/gradle/AppPlugin : Unsupported major.minor version 52.0
</code>```

I have the following build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://jitpack.io"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

and I have:

答:
I updated the java in /usr/bin/java from: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

and it builds now.

Body:
I am running:

./gradlew assembleDebug

from my project folder and getting the error:

* What went wrong:
A problem occurred evaluating project ':app'.
> java.lang.UnsupportedClassVersionError: com/android/build/gradle/AppPlugin : Unsupported major.minor version 52.0

I have the following build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://jitpack.io"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and I have:


问:
android progressbar inside edittext
I want to display progressbar(spinner) to the right of editText when activity is doing some processing and hide upon completion, is there a simple way to do this?</p>

答:
I'd use RelativeLayout, something like this:

```<code><RelativeLayout>
    <EditText
        android:id="@+id/the_id"/>
    <ProgressBar
        style="?android:attr/progressBarStyleSmall"
        android:layout_alignTop="@id/the_id"
        android:layout_alignBottom="@id/the_id"
        android:layout_alignRight="@id/the_id"/>
</RelativeLayout>
</code>```

Title: android progressbar inside edittext

Body:
I'd use RelativeLayout, something like this:

<RelativeLayout>
    <EditText
        android:id="@+id/the_id"/>
    <ProgressBar
        style="?android:attr/progressBarStyleSmall"
        android:layout_alignTop="@id/the_id"
        android:layout_alignBottom="@id/the_id"
        android:layout_alignRight="@id/the_id"/>
</RelativeLayout>


答:
How about using pd.read_fwf()?

```<code>psz2_2017 =pd.read_fwf('http://cdsarc.u-strasbg.fr/ftp/cats/J/A+A/594/A27/psz2.dat',header=None)
</code>```

Title: How to configure Pandas to read .dat file

Body:
Can't seem to load this file with pd.read_csv or pd.read_table:

http://cdsarc.u-strasbg.fr/ftp/cats/J/A+A/594/A27/psz2.dat

I've tried:

psz2_2017 = pd.read_csv('http://cdsarc.u-strasbg.fr/ftp/cats/J/A+A/594/A27/psz2.dat', sep=';', header=None)

Also tried pd.read_table with/wo sep='\t' (same result) and sep='\s+' (gets Error tokenizing data).

Results in:

0
0   1 PSZ2 G000.04+45.13 0.0405432 45.135175...
1   2 PSZ2 G000.13+78.04 0.1380577 78.042113...
2   3 PSZ2 G000.40-41.86 0.4029953 -41.860792...

Any suggestions?

The first line looks like this:

1 PSZ2 G000.04+45.13   0.0405432  45.1351750 229.1905120  -1.0172220  4.107310  6.75319 2 111 0     1 0 0.938825   5.481591  1.899500  20 RXC J1516.5-0056           0.119800  3.962411 0.393290 0.370242 J1516.5-0056 RMJ151653.9-010506.3

Body:
How about using pd.read_fwf()?

psz2_2017 =pd.read_fwf('http://cdsarc.u-strasbg.fr/ftp/cats/J/A+A/594/A27/psz2.dat',header=None)


问:
Is gRPC(HTTP/2) faster than REST with HTTP/2?
The goal is to introduce a transport and application layer protocol that is better in its latency and network throughput. Currently, the application uses REST with HTTP/1.1 and we experience a high latency. I need to resolve this latency problem and I am open to use either gRPC(HTTP/2) or REST/HTTP2.

HTTP/2:

Multiplexed

Single TCP Connection

Binary instead of textual

Header compression

Server Push

I am aware of all the above advantages. Question No. 1: If I use REST with HTTP/2, I am sure, I will get a significant performance improvement when compared to REST with HTTP/1.1, but how does this compare with gRPC(HTTP/2)?

I am also aware that gRPC uses proto buffer, which is the best binary serialization technique for transmission of structured data on the wire. Proto buffer also helps in developing an language agnostic approach. I agree with that and I can implement the same feature in REST using graphQL. But my concern is over serialization: Question No. 2: When HTTP/2 implements this binary feature, does using proto buffer give an added advantage on top of HTTP/2?

Question No. 3: In terms of streaming, bi-directional use-cases, how does gRPC(HTTP/2) compare with (REST and HTTP/2)?

There are so many blogs/videos out in the internet that compares gRPC(HTTP/2) with (REST and HTTP/1.1) like this. As stated earlier, I would like to know the differences, benefits on comparing GRPC(HTTP/2) and (REST with HTTP/2).

答:
gRPC is not faster than REST over HTTP/2 by default, but it gives you the tools to make it faster.  There are some things that would be difficult or impossible to do with REST.

Selective message compression.  In gRPC a streaming RPC can decide to compress or not compress messages.  For example, if you are streaming mixed text and images over a single stream (or really any mixed compressible content), you can turn off compression for the images.  This saves you from compressing already compressed data which won't get any smaller, but will burn up your CPU.

First class load balancing.  While not an improvement in point to point connections, gRPC can intelligently pick which backend to send traffic to.   (this is a library feature, not a wire protocol feature).  This means you can send your requests to the least loaded backend server without resorting to using a proxy.  This is a latency win.

Heavily optimized.   gRPC (the library) is under continuous benchmarks to ensure that there are no speed regressions.  Those benchmarks are improving constantly.  Again, this doesn't have anything to do with gRPC the protocol, but your program will be faster for having used gRPC.

As nfirvine said, you will see most of your performance improvement just from using Protobuf.  While you could use proto with REST, it is very nicely integrated with gRPC.  Technically, you could use JSON with gRPC, but most people don't want to pay the performance cost after getting used to protos.

ContentLicense: CC BY-SA 4.0


问:
C beginner's problems with multiple boolean operators
I'm looking for a way to use multiple boolean operators in a single expression, but can't figure it out.
The code below is an attempt to translate the following into C:

pseudocode:

```<code>if
(100 = 100) AND (10 is either 10 or 100)
print "1"
else
print "0"
</code>```

C:

```<code>#include <stdio.h>
#include <stdbool.h>

int main(void)
{
    int num;
    num= 10;
    bool n;
    n = ((100==100) && (num == (10 || 100)));
    printf("%i", n);
}
</code>```

Obviously I'm doing something wrong.

答:
I think I know what you want to do, if you're just interested in the expression, here's what should the if statement would be.

```<code>if(a == b && (c == d || c == f))//It says here, IF A IS EQUAL TO B and C IS EQUAL TO D or F
{
    printf("1");
}
else
{
    printf("0");
}
</code>```

don't worry about the curly braces '{}', you can remove that. It just became my hobby.

Body:
I'm looking for a way to use multiple boolean operators in a single expression, but can't figure it out.
The code below is an attempt to translate the following into C:

pseudocode:

if
(100 = 100) AND (10 is either 10 or 100)
print "1"
else
print "0"

C:

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
    int num;
    num= 10;
    bool n;
    n = ((100==100) && (num == (10 || 100)));
    printf("%i", n);
}

Obviously I'm doing something wrong.

Body:
I think I know what you want to do, if you're just interested in the expression, here's what should the if statement would be.

if(a == b && (c == d || c == f))//It says here, IF A IS EQUAL TO B and C IS EQUAL TO D or F
{
    printf("1");
}
else
{
    printf("0");
}

don't worry about the curly braces '{}', you can remove that. It just became my hobby.


问:
Adobe Analytics Python API
I am trying to return page hits for the last month.  I am using a Python Sdk that can be found  HERE

I am using the code below:

```<code>report = suite.report.element("evar3").run()
</code>```

It is only returning the top 10. How can I get to provide the full list?

答:
As far as the Adobe API request itself, you need to specify the top property.

I'm not familiar with that python-sdk library you linked or even python in general so this is just an educated guess, but looking at the documentation you linked, looks like you should be able to do the following:

report = suite.report.element("evar3",top=10).run()

Title: Adobe Analytics Python API

Body:
I am trying to return page hits for the last month.  I am using a Python Sdk that can be found  HERE

I am using the code below:

report = suite.report.element("evar3").run()

It is only returning the top 10. How can I get to provide the full list?


问:
Hierarchyid datatype using Varchar column
In a table, Have a columns like DepartmentCode and ParentDepartmentCode which
 are of varchar(5) columns.
The sample values of DepartmentCode are like 1,123,ABC,DEF

I am trying to create HierarchyId datatype column using above. When creating hierarchy as /1/123 it is fine,however when creating hierarchy as /1/ABC it is throwing error as below. So i wonder can't we use string data in HierarchyId?

```<code>CREATE TABLE [dbo].[Test_Department](
[GLDHierarchyID] hierarchyid NOT NULL
)
insert into Test_Department([GLDHierarchyID]) select hierarchyid::GetRoot();
insert into Test_Department([GLDHierarchyID]) select hierarchyid::Parse('/'+
cast(1 as varchar(4))+'/');
select [GLDHierarchyID].ToString() from [Test_Department]

--This works good
Declare @testData varchar(3)='123'
Declare @hiearchy hierarchyid
SELECT @hiearchy=[GLDHierarchyID] FROM [Test_Department] where
[GLDHierarchyID].GetLevel()=1
INSERT INTO Test_Department([GLDHierarchyID])
SELECT
Case when try_parse(@testData as int)>0 then
hierarchyid::Parse(@hiearchy.ToString()  + cast(cast(@testData as int) as
varchar(5))+'/')
else hierarchyid::Parse(@hiearchy.ToString() + cast(@testData as varchar(5))
+'/')
end as GLDHierarchyID
--select [GLDHierarchyID].ToString() from [Test_Department]

--This does not work
Declare @testData varchar(3)='ABC'
Declare @hiearchy hierarchyid
SELECT @hiearchy=[GLDHierarchyID] FROM [Test_Department] where
[GLDHierarchyID].GetLevel()=1
INSERT INTO Test_Department([GLDHierarchyID])
SELECT
Case when try_parse(@testData as int)>0 then
hierarchyid::Parse(@hiearchy.ToString()  + cast(cast(@testData as int) as
varchar(5))+'/')
else hierarchyid::Parse(@hiearchy.ToString() + cast(@testData as varchar(5))
+'/')
end as GLDHierarchyID
--select [GLDHierarchyID].ToString() from [Test_Department]

Msg 6522, Level 16, State 2, Line 1
A .NET Framework error occurred during execution of user-defined routine or
aggregate "hierarchyid":
Microsoft.SqlServer.Types.HierarchyIdException: 24001: SqlHierarchyId.Parse
failed because the input string '/1/ABC/' is not a valid string
representation of a SqlHierarchyId node.
Microsoft.SqlServer.Types.HierarchyIdException:
at Microsoft.SqlServer.Types.OrdPath.InitFromString(String chDottedString)
at Microsoft.SqlServer.Types.SqlHierarchyId.Parse(SqlString input)
.
</code>```

答:
The documentation says:

A slash starts the representation, and a path that only visits the root is represented by a single slash. For levels underneath the root, each label is encoded as a sequence of integers separated by dots. Comparison between children is performed by comparing the integer sequences separated by dots in dictionary order. Each level is followed by a slash. Therefore a slash separates parents from their children.

So, you can have things like /1/1.2/3.17/, but that's about as exotic as it gets.

I've had good luck doing a slash-separated list of IDs. It has the added benefit of being self-documenting (i.e. you could re-create the path yourself).

Body:
In a table, Have a columns like DepartmentCode and ParentDepartmentCode which
 are of varchar(5) columns.
The sample values of DepartmentCode are like 1,123,ABC,DEF

I am trying to create HierarchyId datatype column using above. When creating hierarchy as /1/123 it is fine,however when creating hierarchy as /1/ABC it is throwing error as below. So i wonder can't we use string data in HierarchyId?

CREATE TABLE [dbo].[Test_Department](
[GLDHierarchyID] hierarchyid NOT NULL
)
insert into Test_Department([GLDHierarchyID]) select hierarchyid::GetRoot();
insert into Test_Department([GLDHierarchyID]) select hierarchyid::Parse('/'+
cast(1 as varchar(4))+'/');
select [GLDHierarchyID].ToString() from [Test_Department]

--This works good
Declare @testData varchar(3)='123'
Declare @hiearchy hierarchyid
SELECT @hiearchy=[GLDHierarchyID] FROM [Test_Department] where
[GLDHierarchyID].GetLevel()=1
INSERT INTO Test_Department([GLDHierarchyID])
SELECT
Case when try_parse(@testData as int)>0 then
hierarchyid::Parse(@hiearchy.ToString()  + cast(cast(@testData as int) as
varchar(5))+'/')
else hierarchyid::Parse(@hiearchy.ToString() + cast(@testData as varchar(5))
+'/')
end as GLDHierarchyID
--select [GLDHierarchyID].ToString() from [Test_Department]

--This does not work
Declare @testData varchar(3)='ABC'
Declare @hiearchy hierarchyid
SELECT @hiearchy=[GLDHierarchyID] FROM [Test_Department] where
[GLDHierarchyID].GetLevel()=1
INSERT INTO Test_Department([GLDHierarchyID])
SELECT
Case when try_parse(@testData as int)>0 then
hierarchyid::Parse(@hiearchy.ToString()  + cast(cast(@testData as int) as
varchar(5))+'/')
else hierarchyid::Parse(@hiearchy.ToString() + cast(@testData as varchar(5))
+'/')
end as GLDHierarchyID
--select [GLDHierarchyID].ToString() from [Test_Department]

Msg 6522, Level 16, State 2, Line 1
A .NET Framework error occurred during execution of user-defined routine or
aggregate "hierarchyid":
Microsoft.SqlServer.Types.HierarchyIdException: 24001: SqlHierarchyId.Parse
failed because the input string '/1/ABC/' is not a valid string
representation of a SqlHierarchyId node.
Microsoft.SqlServer.Types.HierarchyIdException:
at Microsoft.SqlServer.Types.OrdPath.InitFromString(String chDottedString)
at Microsoft.SqlServer.Types.SqlHierarchyId.Parse(SqlString input)
.


问:
I'm trying to get a count of records from a related entity that match a criteria
I have an entity matches which has a related to-many entity sets. I want to get a count of how many sets have the attribute 'set_finished' set to YES for a particular match. I'm trying to do this with:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY set_finished == YES"];
 NSUInteger numberOfFinishedSets = [[[match valueForKeyPath:@"sets"] filteredArrayUsingPredicate:predicate ] count];

The second line crashes with this error, which I don't understand. Can anyone shed some light on this for me? Thanks.

2010-12-20 13:17:13.814
  DartScorer[2154:207] * Terminating
  app due to uncaught exception
  'NSInvalidArgumentException', reason:
  '-[_NSFaultingMutableSet
  filteredArrayUsingPredicate:]:
  unrecognized selector sent to instance
  0x617fb20'

答:
```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(ANY set_finished == YES).@count"];
NSUInteger numberOfFinishedSets = [[match valueForKeyPath:@"sets"] filteredSetUsingPredicate:predicate];
</code>```

This will just return the count of how many objects there are instead of actually retrieving the objects from disk and counting them.

Body:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(ANY set_finished == YES).@count"];
NSUInteger numberOfFinishedSets = [[match valueForKeyPath:@"sets"] filteredSetUsingPredicate:predicate];

This will just return the count of how many objects there are instead of actually retrieving the objects from disk and counting them.


问:
How do you execute C# code with a button click in asp.net?
I need help executing C# code with a button click. I`m sure there are multiple things wrong with this, however; any help would be much appreciated. Thank you for taking the time to view this post, and have a wonderful day!</p>

```<code>            @{
                CommentController controller = new CommentController();

                UpVotes Upvote = new UpVotes(Misc.GetUser(), c.Postid);

            }

            @{
                if (controller.CheckVote(Upvote))
                {
                    <button type="button" onclick="@{

                        c.Upvotes += 1;

                        controller.PersonUpVote(Upvote);
                        }
                            }">
                        Like
                    </button>
                        }

                        else
                        {

                        <button type="button" onclick="@{

                            controller.PersonDownVote(Upvote);
                            c.Upvotes -= 1;
                        }

                                }">
                            Unlike
                        </button>

                    }
                 }
</code>```

答:
View should never instantiate a controller.

You lack the basics understanding of how ASP.NET MVC work or even basic HTML.

Please watch a free video training ASP.NET MVC 5 Fundamentals
 By Scott Allen at PluralSight.

Body:
I need help executing C# code with a button click. I`m sure there are multiple things wrong with this, however; any help would be much appreciated. Thank you for taking the time to view this post, and have a wonderful day!

            @{
                CommentController controller = new CommentController();

                UpVotes Upvote = new UpVotes(Misc.GetUser(), c.Postid);

            }

            @{
                if (controller.CheckVote(Upvote))
                {
                    <button type="button" onclick="@{

                        c.Upvotes += 1;

                        controller.PersonUpVote(Upvote);
                        }
                            }">
                        Like
                    </button>
                        }

                        else
                        {

                        <button type="button" onclick="@{

                            controller.PersonDownVote(Upvote);
                            c.Upvotes -= 1;
                        }

                                }">
                            Unlike
                        </button>

                    }
                 }


问:
How to convert xml to json in Groovy?
In groovy I have the below xml

```<code><data>
   <row>
      <id>USA</id>
      <value>United States of America</value>
   </row>
   <row>
      <id>CAN</id>
      <value>Canada</value>
   </row>
</data>
</code>```

I need to transform the above xml in groovy to the below json format

```<code>{
   "data": [
      {
         "KEY": "USA",
         "VALUE": "United States of America"
      },
      {
         "KEY": "CAN",
         "VALUE": "Canada"
      }
   ]
}
</code>```

Any help would be greatly appreciated.

Thanks

Hari

答:
Here you go:

```<code>//Pass xml as string to below parseText method
def parsed = new XmlSlurper().parseText(xml)
//Create the map as needed out of parsed xml
def map = [(parsed[0].name): parsed.'**'
  .findAll{it.name() == 'row'}
  .collect{ row ->
     row.collectEntries{[KEY: row.id.text(), VALUE:row.value.text()]}
   }
]
println new groovy.json.JsonBuilder(map).toPrettyString()
</code>```

You can quickly try it online Demo

Title: How to convert xml to json in Groovy?

Body:
In groovy I have the below xml

<data>
   <row>
      <id>USA</id>
      <value>United States of America</value>
   </row>
   <row>
      <id>CAN</id>
      <value>Canada</value>
   </row>
</data>

I need to transform the above xml in groovy to the below json format

{
   "data": [
      {
         "KEY": "USA",
         "VALUE": "United States of America"
      },
      {
         "KEY": "CAN",
         "VALUE": "Canada"
      }
   ]
}

Any help would be greatly appreciated.

Thanks

Hari

Body:
Here you go:

//Pass xml as string to below parseText method
def parsed = new XmlSlurper().parseText(xml)
//Create the map as needed out of parsed xml
def map = [(parsed[0].name): parsed.'**'
  .findAll{it.name() == 'row'}
  .collect{ row ->
     row.collectEntries{[KEY: row.id.text(), VALUE:row.value.text()]}
   }
]
println new groovy.json.JsonBuilder(map).toPrettyString()

You can quickly try it online Demo


问:
Hover on divs changes background smoothly
I made a quick hub for two websites I created and I wanted to have two divs centered side by side, so that when you put your mouse over each div, it changes the body background image. I have made it so that when you hover over it, it changes the background but, its not smooth.

I really want to learn java script and I feel like this a good experience for me, thanks for any help

I'm using jQuery and Bootstrap.

Is there a way to just use css? if there isn't a way then its fine.

HTML:

```<code><body>
  <div class="container">
    <div class="row vertical-center">
      <div class="col-md-6">
        <div class="fre">
          <h3>Howdy</h3>
          <a href="http://www.google.com">
            <div class="fre-moveleft smooth" id="fre">
              <img src="http://www.logospike.com/wp-content/uploads/2015/11/Logo_Image_03.png" class="scale">
            </div>
          </a>
          <div class="caption">
            <p>Lorem ipsum dolor sit
              <br> consectetur adipiscing elit. Aliquam</p>
          </div>
        </div>
      </div>
      <div class="col-md-6">
        <div class="med">
          <h3>Partner</h3>
          <a href="http://www.google.com">
            <div class="med-moveright smooth" id="med">
              <img src="http://www.logospike.com/wp-content/uploads/2015/11/Logo_Image_03.png" class="scale">
            </div>
          </a>
          <div class="caption">
            <p>Lorem ipsum dolor sit
              <br> consectetur adipiscing elit. Aliquam</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</code>```

CSS:

```<code>.vertical-center {
  min-height: 100%;
  /* Fallback for browsers do NOT support vh unit */
  min-height: 100vh;
  /* These two lines are counted as one :-)       */
  display: flex;
  align-items: center;
}

.scale {
  width: 60%;
  position: relative;
}

.smooth {
  transition: 0.3s ease;
  cursor: pointer;
}

.med {
  float: left;
}

.med-moveright:hover {
  transform: translate(50px);
}

.fre {
  float: right;
  text-align: right;
}

.fre-moveleft:hover {
  transform: translate(-50px);
}

/*
body {
    background-image: url(../images/kabobi.jpg);

}
*/

/*
body .fre-moveleft:hover {
    background-image: url(http://img.mynet.com/ha2/tayyip.jpg);
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
*/
</code>```

JS:

```<code>$("#med").hover(function() {
  $('body').css("background", "url(https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
});

$("#fre").hover(function() {
  $('body').css("background", "url(https://www.purinamills.com/2.purinamills.com/media/Images/MasterBrand/Lifestages/horse_lifestage_any-life-stage.png?ext=.png");
});
</code>```

JSFiddle

答:
Here's a way you can fade between the two by toggling a class and setting a data attribute in jQuery, the rest controlled in CSS.

var $body = $('body');

function setBg(str) {
  var bg = $body.attr('data-bg');
    $body.addClass('out');
    var t = setTimeout(function() {
      $body.attr('data-bg', str).removeClass('out');
    },250);
}

function hideBg() {
  $body.addClass('out');
}

$("#med img").hover(function() {
  setBg('med');
},function() {
  hideBg();
});

$("#fre img").hover(function() {
  setBg('fre');
},function() {
  hideBg();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.vertical-center {
  min-height: 100%;
  /* Fallback for browsers do NOT support vh unit */
  min-height: 100vh;
  /* These two lines are counted as one :-)       */
  display: flex;
  align-items: center;
}

.scale {
  width: 60%;
  position: relative;
}

.smooth {
  transition: 0.3s ease;
  cursor: pointer;
}

.med {
  float: left;
}

.med-moveright:hover {
  transform: translate(50px);
}

.fre {
  float: right;
  text-align: right;
}

.fre-moveleft:hover {
  transform: translate(-50px);
}

/* new stuff */

body::before,
body::after {
  transition: opacity .25s;
  z-index: -1;
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.out::after,
.out::before {
  opacity: 0;
}

[data-bg="med"]::before {
  background-image: url("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
}

[data-bg="fre"]::after {
  background-image: url("https://www.purinamills.com/2.purinamills.com/media/Images/MasterBrand/Lifestages/horse_lifestage_any-life-stage.png?ext=.png");
}</code>```

Howdy

Lorem ipsum dolor sit

 consectetur adipiscing elit. Aliquam

Partner

Lorem ipsum dolor sit

 consectetur adipiscing elit. Aliquam

```

Body:
I made a quick hub for two websites I created and I wanted to have two divs centered side by side, so that when you put your mouse over each div, it changes the body background image. I have made it so that when you hover over it, it changes the background but, its not smooth.

I really want to learn java script and I feel like this a good experience for me, thanks for any help

I'm using jQuery and Bootstrap.

Is there a way to just use css? if there isn't a way then its fine.

HTML:

Howdy

Lorem ipsum dolor sit

 consectetur adipiscing elit. Aliquam

Partner

Lorem ipsum dolor sit

 consectetur adipiscing elit. Aliquam

CSS:

.vertical-center {
  min-height: 100%;
  /* Fallback for browsers do NOT support vh unit */
  min-height: 100vh;
  /* These two lines are counted as one :-)       */
  display: flex;
  align-items: center;
}

.scale {
  width: 60%;
  position: relative;
}

.smooth {
  transition: 0.3s ease;
  cursor: pointer;
}

.med {
  float: left;
}

.med-moveright:hover {
  transform: translate(50px);
}

.fre {
  float: right;
  text-align: right;
}

.fre-moveleft:hover {
  transform: translate(-50px);
}

/*
body {
    background-image: url(../images/kabobi.jpg);

}
*/

/*
body .fre-moveleft:hover {
    background-image: url(http://img.mynet.com/ha2/tayyip.jpg);
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
*/

JS:

$("#med").hover(function() {
  $('body').css("background", "url(https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
});

$("#fre").hover(function() {
  $('body').css("background", "url(https://www.purinamills.com/2.purinamills.com/media/Images/MasterBrand/Lifestages/horse_lifestage_any-life-stage.png?ext=.png");
});

JSFiddle

Body:
Here's a way you can fade between the two by toggling a class and setting a data attribute in jQuery, the rest controlled in CSS.

var $body = $('body');

function setBg(str) {
  var bg = $body.attr('data-bg');
    $body.addClass('out');
    var t = setTimeout(function() {
      $body.attr('data-bg', str).removeClass('out');
    },250);
}

function hideBg() {
  $body.addClass('out');
}

$("#med img").hover(function() {
  setBg('med');
},function() {
  hideBg();
});

$("#fre img").hover(function() {
  setBg('fre');
},function() {
  hideBg();
});

.vertical-center {
  min-height: 100%;
  /* Fallback for browsers do NOT support vh unit */
  min-height: 100vh;
  /* These two lines are counted as one :-)       */
  display: flex;
  align-items: center;
}

.scale {
  width: 60%;
  position: relative;
}

.smooth {
  transition: 0.3s ease;
  cursor: pointer;
}

.med {
  float: left;
}

.med-moveright:hover {
  transform: translate(50px);
}

.fre {
  float: right;
  text-align: right;
}

.fre-moveleft:hover {
  transform: translate(-50px);
}

/* new stuff */

body::before,
body::after {
  transition: opacity .25s;
  z-index: -1;
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.out::after,
.out::before {
  opacity: 0;
}

[data-bg="med"]::before {
  background-image: url("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
}

[data-bg="fre"]::after {
  background-image: url("https://www.purinamills.com/2.purinamills.com/media/Images/MasterBrand/Lifestages/horse_lifestage_any-life-stage.png?ext=.png");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div class="container">
    <div class="row vertical-center">
      <div class="col-md-6">
        <div class="fre">
          <h3>Howdy</h3>
          <a href="http://www.google.com">
            <div class="fre-moveleft smooth" id="fre">
              <img src="http://www.logospike.com/wp-content/uploads/2015/11/Logo_Image_03.png" class="scale">
            </div>
          </a>
          <div class="caption">
            <p>Lorem ipsum dolor sit
              <br> consectetur adipiscing elit. Aliquam</p>
          </div>
        </div>
      </div>
      <div class="col-md-6">
        <div class="med">
          <h3>Partner</h3>
          <a href="http://www.google.com">
            <div class="med-moveright smooth" id="med">
              <img src="http://www.logospike.com/wp-content/uploads/2015/11/Logo_Image_03.png" class="scale">
            </div>
          </a>
          <div class="caption">
            <p>Lorem ipsum dolor sit
              <br> consectetur adipiscing elit. Aliquam</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>


问:
javafx - how to bind service result to form fields?
In the following example, how do I bind the service result to the textfield, so if i call service.restart() it would update the field?

Is the the correct way to do this, or the usual is to have the properties on the service class?

```<code>public class FormData {
    private StringProperty description = new SimpleStringProperty();

    public String getDescription() {
        return description.get();
    }

    public StringProperty descriptionProperty() {
        return description;
    }

    public void setDescription(String description) {
        this.description.set(description);
    }
}

public class FormDataService extends Service<FormData> {

    @Override
    protected Task<FormData> createTask() {
        return new Task<FormData>() {
            protected FormData call() throws Exception {
                //database query here
                FormData data = new FormData();
                data.setDescription("Test Description");

                return data;
            }
        };
    }
}

public class Controller {
    @FXML
    private TextField textField;

    @FXML
    public void initialize() {
        FormDataService service = new FormDataService();

        //HOW DO I BIND THE SERVICE RESULT TO THE TEXTFIELD?
    }
}
</code>```

答:
Probably FormData may have many fields and for each one you should have the corresponding TextField control, correct?
May be the listening of service property will be suitable for your case:</p>

```<code>service.valueProperty().addListener((o, oldValue, newValue) -> {
    if (newValue != null) {
        textField.setText(newValue.getDescription());
        textField2.setText(newValue.getOtherData());
        // etc
    } else {
        // reset your fields
    }
});
</code>```

Body:
In the following example, how do I bind the service result to the textfield, so if i call service.restart() it would update the field?

Is the the correct way to do this, or the usual is to have the properties on the service class?

public class FormData {
    private StringProperty description = new SimpleStringProperty();

    public String getDescription() {
        return description.get();
    }

    public StringProperty descriptionProperty() {
        return description;
    }

    public void setDescription(String description) {
        this.description.set(description);
    }
}

public class FormDataService extends Service<FormData> {

    @Override
    protected Task<FormData> createTask() {
        return new Task<FormData>() {
            protected FormData call() throws Exception {
                //database query here
                FormData data = new FormData();
                data.setDescription("Test Description");

                return data;
            }
        };
    }
}

public class Controller {
    @FXML
    private TextField textField;

    @FXML
    public void initialize() {
        FormDataService service = new FormDataService();

        //HOW DO I BIND THE SERVICE RESULT TO THE TEXTFIELD?
    }
}

Body:
Probably FormData may have many fields and for each one you should have the corresponding TextField control, correct?
May be the listening of service property will be suitable for your case:

service.valueProperty().addListener((o, oldValue, newValue) -> {
    if (newValue != null) {
        textField.setText(newValue.getDescription());
        textField2.setText(newValue.getOtherData());
        // etc
    } else {
        // reset your fields
    }
});


问:
Messaging between two angularjs services
I want to realise a communication (by sending and receiving messages) between two services in an angularjs web site. Actually, messaging would be unnecessary if we could merge two services into one service. But the reality is I don't want to merge them for some reason. As mutual dependency of two services is not possible (please correct me if i am wrong), it seems that I have to let them communicate via messaging.

Let me explain... Assume we have two services serA and serB. In serA, we have

```<code>this.startTask1 = function () {
    console.log("B, please do task 1")
    sendMsgFromAtoB("B, please do task 1")
}

this.receiveMsgFromBtoA = function (msg) {
    if (msg === "A, B has done task 1") {
        console.log("A, B has done task 1");
        console.log("task 1 is finally over!!!")
    }
}
</code>```

in serB, we have

```<code>this.receiveMsgFromAtoB = function (msg) {
    if (msg === "B, please do task 1") {
        console.log("B is doing task 1... Done!");
        sendMsgFromBtoA("A, B has done task 1")
    }
}
</code>```

As a result, if a controller runs serA.startTask1(), I expect to see in the console:

```<code>B, please do task 1
B is doing task 1... Done!
A, B has done task 1
task 1 is finally over!!!
</code>```

To this end, I need to make sendMsgFromAtoB and sendMsgFromBtoA, and complete receiveMsgFromAtoB and receiveMsgFromBtoA. However, I don't know by which mean I could implement them.

I have used $window.addEventListener("message", ...) (ie, postMessage) and $window.addEventListener("storage", ...) (ie, StorageEvent). But StorageEvent is not fully cross-platform, I am not sure postMessage is good for messaging inside 1 page.

So does anyone have a good idea?

答:
You've already got event bus in Angular 1.x app, $rootScope. Unless you're willing to introduce third-party libraries to the project (RxJS, EventEmitter3 or other pub/sub implementations), there's no reason to look any further.

```<code>$rootScope.$on('foo', (e, arg1, arg2) => { ... });
...
$rootScope.$emit('foo', arg1, arg2);
</code>```

Body:
I want to realise a communication (by sending and receiving messages) between two services in an angularjs web site. Actually, messaging would be unnecessary if we could merge two services into one service. But the reality is I don't want to merge them for some reason. As mutual dependency of two services is not possible (please correct me if i am wrong), it seems that I have to let them communicate via messaging.

Let me explain... Assume we have two services serA and serB. In serA, we have

this.startTask1 = function () {
    console.log("B, please do task 1")
    sendMsgFromAtoB("B, please do task 1")
}

this.receiveMsgFromBtoA = function (msg) {
    if (msg === "A, B has done task 1") {
        console.log("A, B has done task 1");
        console.log("task 1 is finally over!!!")
    }
}

in serB, we have

this.receiveMsgFromAtoB = function (msg) {
    if (msg === "B, please do task 1") {
        console.log("B is doing task 1... Done!");
        sendMsgFromBtoA("A, B has done task 1")
    }
}

As a result, if a controller runs serA.startTask1(), I expect to see in the console:

B, please do task 1
B is doing task 1... Done!
A, B has done task 1
task 1 is finally over!!!

To this end, I need to make sendMsgFromAtoB and sendMsgFromBtoA, and complete receiveMsgFromAtoB and receiveMsgFromBtoA. However, I don't know by which mean I could implement them.

I have used $window.addEventListener("message", ...) (ie, postMessage) and $window.addEventListener("storage", ...) (ie, StorageEvent). But StorageEvent is not fully cross-platform, I am not sure postMessage is good for messaging inside 1 page.

So does anyone have a good idea?

Body:
You've already got event bus in Angular 1.x app, $rootScope. Unless you're willing to introduce third-party libraries to the project (RxJS, EventEmitter3 or other pub/sub implementations), there's no reason to look any further.

$rootScope.$on('foo', (e, arg1, arg2) => { ... });
...
$rootScope.$emit('foo', arg1, arg2);


问:
Simple JavaScript URL Routing RegEx
I'm trying to write a very basic URL router. I define a "routes" object that contains location paths and corresponding "module names."

Upon a full page load (no hash or pushState needed in this scenario), I want to look at the routes and find the corresponding module value, if it exists.

I'm having some trouble with my code.

```<code>(function() {

    return {

        routes: {
            '/': 'home',
            '/about': 'about',
            '/about/team': 'aboutTeam',
            '/about/team/:member': 'aboutMember'
        },

        init: function() {

            var url = location.pathname;

            for (var route in this.routes) {

                if (this.routes.hasOwnProperty(route)) {

                    if (url.match(this.regex(route))) {

                        // return & load module
                    }
                }
            }
        },

        regex: function(route) {

            return new RegExp(route.replace(/:[^\s/]+/g, '([\\w-]+)'));
        }

    }.init();

})();
</code>```

The above code doesn't work well at all. (Obviously.) Landing on the page /about/team/jim will return all four pre-defined routes in this example. (And I can see why, just struggling with a solution.)

I'm not great with regular expressions. I snagged what I have above from here: Javascript routing regex. I'm looking for advice and guidance. Am I even taking the right approach, overall?

答:
You might be interested by Frontexpress router. I coded this library.

```<code>const app = frontexpress();

app.get('/', (req, res) => {});
app.get('/about', (req, res) => {});
app.get('/about/team', (req, res) => {});
app.get('/about/team/:member', (req, res) => {
   const member = req.params.member;
   // your front-end logic here
});

app.listen();
</code>```

More code samples here

Title: Simple JavaScript URL Routing RegEx

Body:
I'm trying to write a very basic URL router. I define a "routes" object that contains location paths and corresponding "module names."

Upon a full page load (no hash or pushState needed in this scenario), I want to look at the routes and find the corresponding module value, if it exists.

I'm having some trouble with my code.

(function() {

    return {

        routes: {
            '/': 'home',
            '/about': 'about',
            '/about/team': 'aboutTeam',
            '/about/team/:member': 'aboutMember'
        },

        init: function() {

            var url = location.pathname;

            for (var route in this.routes) {

                if (this.routes.hasOwnProperty(route)) {

                    if (url.match(this.regex(route))) {

                        // return & load module
                    }
                }
            }
        },

        regex: function(route) {

            return new RegExp(route.replace(/:[^\s/]+/g, '([\\w-]+)'));
        }

    }.init();

})();

The above code doesn't work well at all. (Obviously.) Landing on the page /about/team/jim will return all four pre-defined routes in this example. (And I can see why, just struggling with a solution.)

I'm not great with regular expressions. I snagged what I have above from here: Javascript routing regex. I'm looking for advice and guidance. Am I even taking the right approach, overall?

Body:
You might be interested by Frontexpress router. I coded this library.

const app = frontexpress();

app.get('/', (req, res) => {});
app.get('/about', (req, res) => {});
app.get('/about/team', (req, res) => {});
app.get('/about/team/:member', (req, res) => {
   const member = req.params.member;
   // your front-end logic here
});

app.listen();

More code samples here


问:
Facebook sdk LikeView. How to ignore the installed Facebook app
I want to ignore official Facebook app when perform like/login/share actions as if the application is not installed.

For ShareDialog I can do this:

```<code>dialog.show(content, ShareDialog.Mode.WEB);
</code>```

But how can I forbid facebook app for the LikeView's following confirmation dialog (and login dialog, if not authorized)?

答:
Try something like this:                    </p>

```<code>LoginManager.getInstance().setLoginBehavior(LoginBehavior.WEB_ONLY);
</code>```

Body:
I want to ignore official Facebook app when perform like/login/share actions as if the application is not installed.

For ShareDialog I can do this:

dialog.show(content, ShareDialog.Mode.WEB);

But how can I forbid facebook app for the LikeView's following confirmation dialog (and login dialog, if not authorized)?

Body:
Try something like this:

LoginManager.getInstance().setLoginBehavior(LoginBehavior.WEB_ONLY);