问:
How can I show text in the ActionBar in my apps Preference screen?
I am using an Activity and Fragment as a Preferences screen in my app, as per Google's recommended format. I am wondering how I can get the action bar in this activity to say "Settings". Also, how can I include a back arrow to return to the calling activity? Is this a built-in function in Android, or would I need some extra drawable resource for the arrow?

Currently, with the following code I am getting the error android.view.InflateException: Binary XML file line #9: Error inflating class android.support.v7.widget.Toolbar

Here is my preferences Activity and Fragment:

```<code>public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //setContentView(R.layout.activity_settings);
        //setupActionBar();

        // Display the fragment as the main content.
        getSupportFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {

        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            super.onActivityCreated(savedInstanceState);

            // Load the preferences from an XML resource
            setPreferencesFromResource(R.xml.preferences, rootKey);

            Toolbar toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
            ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
        }
    }

}
</code>```

This is my preferences.xml:

```<code><?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:title="@string/settings_title"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <PreferenceCategory
        android:key="settings_game_mode"
        android:title="@string/settings_game_mode">

        <ListPreference
            android:key="game_mode_list"
            android:title="Select Rule Mode"
            android:summary="%s"
            android:entries="@array/game_mode_list_entries"
            android:entryValues="@array/game_mode_list_entries_values"
            android:defaultValue="FIRST_TO_21" />

    </PreferenceCategory>

</PreferenceScreen>
</code>```

And this is the style that my SettingsActivity is using:

```<code><style name="SettingsTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="preferenceTheme">@style/PreferenceThemeOverlay.v14.Material</item>
</style>
</code>```

答:
There are a couple of errors with your setup:

if you are using Toolbar to set up your own appbar, you need to use NoActionBar variant of the theme

Toolbar cannot be part of your preferences.xml as that's strictly for the preferences

PreferenceScreen has no layout_width and layout_height attributes as it is not a layout element

The main problem is that you are replacing android.R.id.content with the preferences fragment. This means that you cannot use custom layout elements so this leaves you with two options:

Option 1 - Normal layout

Use a normal layout that you set with setContentView(...). This layout should contain the Toolbar and a container (e.g. a FrameLayout) for the fragment, then you "replace" that container with the prefs fragment. The Toolbar can be set to be the action bar by calling setSupportActionBar(...). Note that you must use Theme.AppCompat.Light.NoActionBar as your theme's parent in this case.

Option 2 - Replacing android.R.id.content

If you want to stick with the base content container replacement method, you'll need to keep using Theme.AppCompat.Light.DarkActionBar as your theme's parent, then use the usual methods to control the toolbar:

set the label attribute in the manifest for SettingsActivity (or if you want to set it programmatically, call setTitle(...) in your onCreate(...))

get the ActionBar by calling getSupportActionBar()

you can call setDisplayHomeAsUpEnabled(true) on the returned instance to enable the back arrow

The back arrow click can be handled in your Activity's onOptionsItemSelected(...), for example:

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
</code>```

Note that this should be handled manually only if you don't have a parent activity set up in the manifest. Check the Adding an Up Action guide for more details.

As a last point, let me introduce you to my support preferences v7 fix lib that solves a lot of problem you might face using the official lib. The v26-beta branch contains a nice README (the master is a bit of a mess now) but both the master (based on 25.4.0) and the v26-beta (based on 26.0.0-beta2) have sample apps (the "app" folder) that should be easy to copy / follow to create your own settings screen. The sample app shows you option 1.

Body:
I am using an Activity and Fragment as a Preferences screen in my app, as per Google's recommended format. I am wondering how I can get the action bar in this activity to say "Settings". Also, how can I include a back arrow to return to the calling activity? Is this a built-in function in Android, or would I need some extra drawable resource for the arrow?

Currently, with the following code I am getting the error android.view.InflateException: Binary XML file line #9: Error inflating class android.support.v7.widget.Toolbar

Here is my preferences Activity and Fragment:

public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //setContentView(R.layout.activity_settings);
        //setupActionBar();

        // Display the fragment as the main content.
        getSupportFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {

        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            super.onActivityCreated(savedInstanceState);

            // Load the preferences from an XML resource
            setPreferencesFromResource(R.xml.preferences, rootKey);

            Toolbar toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
            ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
        }
    }

}

This is my preferences.xml:

<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:title="@string/settings_title"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <PreferenceCategory
        android:key="settings_game_mode"
        android:title="@string/settings_game_mode">

        <ListPreference
            android:key="game_mode_list"
            android:title="Select Rule Mode"
            android:summary="%s"
            android:entries="@array/game_mode_list_entries"
            android:entryValues="@array/game_mode_list_entries_values"
            android:defaultValue="FIRST_TO_21" />

    </PreferenceCategory>

</PreferenceScreen>

And this is the style that my SettingsActivity is using:

Body:
There are a couple of errors with your setup:

if you are using Toolbar to set up your own appbar, you need to use NoActionBar variant of the theme

Toolbar cannot be part of your preferences.xml as that's strictly for the preferences

PreferenceScreen has no layout_width and layout_height attributes as it is not a layout element

The main problem is that you are replacing android.R.id.content with the preferences fragment. This means that you cannot use custom layout elements so this leaves you with two options:

Option 1 - Normal layout

Use a normal layout that you set with setContentView(...). This layout should contain the Toolbar and a container (e.g. a FrameLayout) for the fragment, then you "replace" that container with the prefs fragment. The Toolbar can be set to be the action bar by calling setSupportActionBar(...). Note that you must use Theme.AppCompat.Light.NoActionBar as your theme's parent in this case.

Option 2 - Replacing android.R.id.content

If you want to stick with the base content container replacement method, you'll need to keep using Theme.AppCompat.Light.DarkActionBar as your theme's parent, then use the usual methods to control the toolbar:

set the label attribute in the manifest for SettingsActivity (or if you want to set it programmatically, call setTitle(...) in your onCreate(...))

get the ActionBar by calling getSupportActionBar()

you can call setDisplayHomeAsUpEnabled(true) on the returned instance to enable the back arrow

The back arrow click can be handled in your Activity's onOptionsItemSelected(...), for example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Note that this should be handled manually only if you don't have a parent activity set up in the manifest. Check the Adding an Up Action guide for more details.

As a last point, let me introduce you to my support preferences v7 fix lib that solves a lot of problem you might face using the official lib. The v26-beta branch contains a nice README (the master is a bit of a mess now) but both the master (based on 25.4.0) and the v26-beta (based on 26.0.0-beta2) have sample apps (the "app" folder) that should be easy to copy / follow to create your own settings screen. The sample app shows you option 1.


来源: stackexchange

问:
Python - Best way to integrate Java GUI and python code
I want to make a desktop GUI that interacts with the user's files (with permission of course). My code to download files and put it in the user's choice of directory is all written in python. There is much more to this code, but everything is written in python.

I want the GUI part to be a desktop app, so the client can easily interact and function the program.

I want to make this GUI in java and have it interact with the python code once someone presses a button.

What are the best approaches to make this happen?

答:
You might be interested in jython

http://www.jython.org

Also, you might think about running Python using JNI - this way, you will be able to keep the state of Python process while still being inside Java:

https://github.com/mkopsnc/keplerhacks/tree/master/python

Everything heavily depends on what you really want to achieve.

ContentLicense: CC BY-SA 3.0


问:
Measuring the blocking part of Garbage Collection time
Java's garbage collector (GC) does not always stop the main thread. It may block all threads, or just run in parallel without pausing the other threads.

I can measure the total garbage collection time either by using
 garbageCollectorMXBean.getCollectionTime(); at the end of the program, or by running the VM with -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -verbose:gc.

However, I want to measure the portion of GCs during which the main thread is blocked (i.e. paused), so that I can measure the exact time that the main thread has been running. Is it possible to measure it?

答:
Besides GC logs and MBean, there also JVM's perf counter exposing relevant information.

jcmd.exe PID PerfCounter.print | grep "sun.rt.safepointTime" command would show your cumulative elapsed time JVM was in Stop-the-World state since its start.


问:
Error:Could not find com.google.gms:google-services:3.0.0
I have searched for a solution to this problem everywhere, but could not find a satisfying answer.

I am trying to set up a sign-in page on my already built application by using firebase, but I came across with the error in the title in the first phase of set up. Even though I went through all steps on this link, I still got the error as shown below:

```<code>Error:Could not find com.google.gms:google-services:3.0.0.
Searched in the following locations:
    file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/google/gms/google-services/3.0.0/google-services-3.0.0.pom
    file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/google/gms/google-services/3.0.0/google-services-3.0.0.jar
Required by:
    project :
</code>```

I also downloaded all the necessary SDK tools as explained in the firebase instructions, but still cannot locate any folder under the name /gms (looks like it was not downloaded).

Any help is appreciated, thanks.

答:
Step 0
Instead of 3.0.0, make it 3.1.0

change this classpath 'com.google.gms:google-services:3.0.0' to classpath 'com.google.gms:google-services:3.1.0'

Step 1
To solve this problem, go to
"C:\Program Files\Android\Android Studio\gradle\m2repository\com\google\gms\google-services\3.1.0"

If you do not find any folder, create it.

Step 2
Download two files,

google-services-3.1.0.jar
(http://central.maven.org/maven2/com/google/gms/google-services/3.1.0/google-services-3.1.0.jar)

google-services-3.1.0.pom
(https://repo1.maven.org/maven2/com/google/gms/google-services/3.1.0/google-services-3.1.0.pom)
,paste them into the folder.

Hope it helps.

Body:
I have searched for a solution to this problem everywhere, but could not find a satisfying answer.

I am trying to set up a sign-in page on my already built application by using firebase, but I came across with the error in the title in the first phase of set up. Even though I went through all steps on this link, I still got the error as shown below:

Error:Could not find com.google.gms:google-services:3.0.0.
Searched in the following locations:
    file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/google/gms/google-services/3.0.0/google-services-3.0.0.pom
    file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/google/gms/google-services/3.0.0/google-services-3.0.0.jar
Required by:
    project :

I also downloaded all the necessary SDK tools as explained in the firebase instructions, but still cannot locate any folder under the name /gms (looks like it was not downloaded).

Any help is appreciated, thanks.


问:
Combine or merge recursively two list in R
I had this two lists:

```<code>firstList <- list(a = list(a_1 = 1:5,
                           a_2 = 5:10),
                  b = 10,
                  c = list(c_1 = 10:20,
                           c_2 = 20:30))

secondList <- list(b = 9999,
                   c = list(c_2 = 500:505))
</code>```

I wonder to find an elegant function (few lines of code, no loops) such:

```<code>thirdList <- awesomeFx(firstList, secondList)
</code>```

Gives me:

```<code>$a
$a$a_1
[1] 1 2 3 4 5

$a$a_2
[1]  5  6  7  8  9 10

$b
[1] 9999

$c
$c$c_1
 [1] 10 11 12 13 14 15 16 17 18 19 20

$c$c_2
 [1] 500 501 502 503 504 505
</code>```

In other words, a function (o some way) that recursively replace elements within two lists.

Body:
I had this two lists:

firstList <- list(a = list(a_1 = 1:5,
                           a_2 = 5:10),
                  b = 10,
                  c = list(c_1 = 10:20,
                           c_2 = 20:30))

secondList <- list(b = 9999,
                   c = list(c_2 = 500:505))

I wonder to find an elegant function (few lines of code, no loops) such:

thirdList <- awesomeFx(firstList, secondList)

Gives me:

$a
$a$a_1
[1] 1 2 3 4 5

$a$a_2
[1]  5  6  7  8  9 10

$b
[1] 9999

$c
$c$c_1
 [1] 10 11 12 13 14 15 16 17 18 19 20

$c$c_2
 [1] 500 501 502 503 504 505

In other words, a function (o some way) that recursively replace elements within two lists.

Body:
modifyList(firstList, secondList)

$a
$a$a_1
[1] 1 2 3 4 5

$a$a_2
[1]  5  6  7  8  9 10

$b
[1] 9999

$c
$c$c_1
 [1] 10 11 12 13 14 15 16 17 18 19 20

$c$c_2
[1] 500 501 502 503 504 505


问:
Make Bootstrap columns to take 100% of the row width
I think it is something simple, but as i'm new to bootstrap I don't know how to do it, I searched and didn't find anything about it.

I want the columns to take 100% the width of the row, I marked the row with a red border in the example below.

I know it's the padding of the columns that give this spacing but I have not figured out a way to remove the padding keeping the spacing between the columns and making them fill the row.

JSFiddle

.box {
  height: 100px;
  margin-bottom: 20px;
  border: 1px solid rgba(0,0,0,0.2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row" style="margin-top:40px;margin-bottom:40px;border-right: 1px solid red;border-left: 1px solid red;">
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
     </div>
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
    </div>
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
    </div>
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
    </div>
   </div>
  </div></code>```

答: remove class "container.  and then try you will get full width row.  </p>

Body:
I think it is something simple, but as i'm new to bootstrap I don't know how to do it, I searched and didn't find anything about it.

I want the columns to take 100% the width of the row, I marked the row with a red border in the example below.

I know it's the padding of the columns that give this spacing but I have not figured out a way to remove the padding keeping the spacing between the columns and making them fill the row.

JSFiddle

.box {
  height: 100px;
  margin-bottom: 20px;
  border: 1px solid rgba(0,0,0,0.2);
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>


问:
NHibernate ID Private Setter (any workaround)
Here is a "simplified" class that can be mapped using NHibernate;

```<code>public class Template
{
  public virtual int Id { get; private set; }
  public virtual string Name { get; set; }
}
</code>```

As the ID field has a private setter we can no longer have code like this in our application where we manually set the ID field;

```<code>var DefaultTemplate = new Template { ID = (int)TemplateEnum.Default, Name = "Default" }
</code>```

Here we are manually creating a DefaultTemplate object that we can assign to anything. Other Templates are manually created by users and saved to the database.

Any ideas how we can still achieve this kind of functionality?

Please note: C# Winforms, .NET 3.5 and we don't want to use Reflection for this.

答:
Use protected instead of private.

Edit: Wait, I miss-read your question, you want it public so you can set it?

Why do you want to manually assign the value?

You could have a constructor that takes the Id. Then do:

```<code>var DefaultTemplate = new Template((int)TemplateEnum.Default) { Name = "Default" }</code>```

But still, it's either public, or reflection. Why do you need to manually set the value?

ContentLicense: CC BY-SA 2.5

Body:
Here is a "simplified" class that can be mapped using NHibernate;

public class Template
{
  public virtual int Id { get; private set; }
  public virtual string Name { get; set; }
}

As the ID field has a private setter we can no longer have code like this in our application where we manually set the ID field;

var DefaultTemplate = new Template { ID = (int)TemplateEnum.Default, Name = "Default" }

Here we are manually creating a DefaultTemplate object that we can assign to anything. Other Templates are manually created by users and saved to the database.

Any ideas how we can still achieve this kind of functionality?

Please note: C# Winforms, .NET 3.5 and we don't want to use Reflection for this.

Body:
Use protected instead of private.

Edit: Wait, I miss-read your question, you want it public so you can set it?

Why do you want to manually assign the value?

You could have a constructor that takes the Id. Then do:

var DefaultTemplate = new Template((int)TemplateEnum.Default) { Name = "Default" }

But still, it's either public, or reflection. Why do you need to manually set the value?


问:
Size of string in message function in R
There seems to be a limit on the size of the string used in message. The following only prints until number 1859 (Using R v3.1.3 on 64 bit Win7 machine)

```<code>message(paste(seq(1,2000),collapse = "-"))
</code>```

while

```<code>cat(paste(seq(1,2000),collapse = "-"))
</code>```

prints it all. Is this a bug?

答:
There's a good solution in this question:

avoid string printed to console getting truncated (in RStudio)

As it suggests, if you're using RStudio, just go to Global Options -> Code -> Display -> Limit length of lines displayed in the console to:

And change the value to zero. It works for me.

Title: Size of string in message function in R

Body:
There seems to be a limit on the size of the string used in message. The following only prints until number 1859 (Using R v3.1.3 on 64 bit Win7 machine)

message(paste(seq(1,2000),collapse = "-"))

while

cat(paste(seq(1,2000),collapse = "-"))

prints it all. Is this a bug?


问:
send data AJAX to @RequestBody Spring
I use response entity and request body for inserting data in spring java but I found an error. 404 not found.

my controller:

```<code>@RequestMapping(value = "insertuserlogin/", method = RequestMethod.POST)
public ResponseEntity<?> createUser(@Valid @RequestBody UserLogin user, BindingResult bindingResult,
        Validation validation, Errors error) {
    Map<?, ?> result = new HashMap<Object, Object>();
    if (bindingResult.hasErrors()) {
        String errorMessage = bindingResult.getFieldErrors().iterator().next().getDefaultMessage();
        System.out.println(errorMessage);
        return new ResponseEntity<>(errorMessage, HttpStatus.UNPROCESSABLE_ENTITY);
    } else {
        uls.saveUser(user);
        return new ResponseEntity<>(result, HttpStatus.ACCEPTED);
    }
}
</code>```

ajax:

```<code>    var data = { "description": "string", "id": 10, "username": "barubanget"}
    $.ajax({
        data: JSON.stringify(data),
        dataType: 'json',
        url : "http://localhost:8085/TaspenNCBSpring/insertuserlogin",
        type : 'POST',
        success : function(data) {
            console.log("success post!");
        },
        error : function(e) {
            console.log("error: " + e);
        }
    });
</code>```

How to fix this problem? what a format data from request body? Thanks. Bobby

答:
I think that your @RequestMapping value is malformed. Please try to put your slash as the first character.

```<code>@RequestMapping(value = "/insertuserlogin", method = RequestMethod.POST)
</code>```

Please let me know if it is useful for you.

Title: send data AJAX to @RequestBody Spring

Body:
I use response entity and request body for inserting data in spring java but I found an error. 404 not found.

my controller:

@RequestMapping(value = "insertuserlogin/", method = RequestMethod.POST)
public ResponseEntity<?> createUser(@Valid @RequestBody UserLogin user, BindingResult bindingResult,
        Validation validation, Errors error) {
    Map<?, ?> result = new HashMap<Object, Object>();
    if (bindingResult.hasErrors()) {
        String errorMessage = bindingResult.getFieldErrors().iterator().next().getDefaultMessage();
        System.out.println(errorMessage);
        return new ResponseEntity<>(errorMessage, HttpStatus.UNPROCESSABLE_ENTITY);
    } else {
        uls.saveUser(user);
        return new ResponseEntity<>(result, HttpStatus.ACCEPTED);
    }
}

ajax:

    var data = { "description": "string", "id": 10, "username": "barubanget"}
    $.ajax({
        data: JSON.stringify(data),
        dataType: 'json',
        url : "http://localhost:8085/TaspenNCBSpring/insertuserlogin",
        type : 'POST',
        success : function(data) {
            console.log("success post!");
        },
        error : function(e) {
            console.log("error: " + e);
        }
    });

How to fix this problem? what a format data from request body? Thanks. Bobby

Body:
I think that your @RequestMapping value is malformed. Please try to put your slash as the first character.

@RequestMapping(value = "/insertuserlogin", method = RequestMethod.POST)

Please let me know if it is useful for you.


问:
laravel 5.4 Undefined property: stdClass::$id
I have two models artists and songs which have one-many relations, an Artist can have multiple songs. song belongs to one artist.

```<code>$artists = DB::table('artists')->join('songs', 'artists.id', '=', 'songs.artist_id')->select('artists.*, songs.id, songs.title, songs.artist_id, songs.week_hits, songs.created_at')
            ->SELECT(DB::raw('sum(songs.week_hits) as WEEKHITS'))->groupBy('songs.artist_id')->orderBy('WEEKHITS', 'DESC')->take(7)->get();
 return return view('front.home', compact('videos', 'songs', 'artists', 'played', 'uploads', 'albums'));
</code>```

this is my Controller code. as u can see I added all artists songs week_hits and grouped by songs.artist_id

and this is my view.

```<code> @foreach($artists as $artist)
            <div class="artist-grid">
                <div class="art-img">
                    <a href="{{route('artist',['id' => $artist->id, 'slug' => $artist->slug])}}">
                        <img  src="image/small/{{$artist->image}}">
                    </a>
                </div>
                <div class="name">
                    <h3>{{$artist->name}}</h3>
                </div>
            </div>
             @endforeach
</code>```

but when i dd($artists) i can see all collection returned but when i send to the view iam getting this error message.

```<code>(2/2) ErrorException
Undefined property: stdClass::$id (View: C:\xampp\htdocs\laravel\resources\views\front\home.blade.php)
</code>```

but when I dd($artists) this is the output.

```<code>Collection {#293 ▼
  #items: array:4 [▼
    0 => {#307 ▼
      +"WEEKHITS": "39"
    }
    1 => {#292 ▼
      +"WEEKHITS": "9"
    }
    2 => {#278 ▼
      +"WEEKHITS": "4"
    }
    3 => {#308 ▼
      +"WEEKHITS": "1"
    }
  ]
}
</code>```

please really appreciate your help.

答:
Try return view as follow:

```<code>return view('front.home')->with($artists, compact('artists'));
</code>```

EDIT
To pass multiple variables there are many solutions. Like:

```<code>return view('front.home')->with(compact('videos', 'songs', 'artists', 'played', 'uploads', 'albums'));
</code>```

Body:
I have two models artists and songs which have one-many relations, an Artist can have multiple songs. song belongs to one artist.

$artists = DB::table('artists')->join('songs', 'artists.id', '=', 'songs.artist_id')->select('artists.*, songs.id, songs.title, songs.artist_id, songs.week_hits, songs.created_at')
            ->SELECT(DB::raw('sum(songs.week_hits) as WEEKHITS'))->groupBy('songs.artist_id')->orderBy('WEEKHITS', 'DESC')->take(7)->get();
 return return view('front.home', compact('videos', 'songs', 'artists', 'played', 'uploads', 'albums'));

this is my Controller code. as u can see I added all artists songs week_hits and grouped by songs.artist_id

and this is my view.

 @foreach($artists as $artist)

                     $artist->id, 'slug' => $artist->slug])}}">
                        image}}">

{{$artist->name}}

             @endforeach

but when i dd($artists) i can see all collection returned but when i send to the view iam getting this error message.

(2/2) ErrorException
Undefined property: stdClass::$id (View: C:\xampp\htdocs\laravel\resources\views\front\home.blade.php)

but when I dd($artists) this is the output.

Collection {#293 ▼
  #items: array:4 [▼
    0 => {#307 ▼
      +"WEEKHITS": "39"
    }
    1 => {#292 ▼
      +"WEEKHITS": "9"
    }
    2 => {#278 ▼
      +"WEEKHITS": "4"
    }
    3 => {#308 ▼
      +"WEEKHITS": "1"
    }
  ]
}

please really appreciate your help.

Body:
Try return view as follow:

return view('front.home')->with($artists, compact('artists'));

EDIT
To pass multiple variables there are many solutions. Like:

return view('front.home')->with(compact('videos', 'songs', 'artists', 'played', 'uploads', 'albums'));


问:
Merge new array to state in componentWillReceiveProps
I was trying to do an infinite scrolling logic, I do this in componentWillReceiveProps, but did not see my list render correctly?

```<code>componentWillReceiveProps(nextProps) {
    if(!isEqual(nextProps.listItems, this.state.listItems)){ //user scrolled, call next offset using the API
        this.setState({
            listItems: this.state.listItems.push(...nextProps.listItems)
        })
    }
}
</code>```

答:
Spread both the current listItems and the next set of listItems in a new array to avoid mutating state.

componentWillReceiveProps(nextProps) {
    if(!isEqual(nextProps.listItems, this.state.listItems)){ //user scrolled, call next offset using the API
        this.setState({
            listItems: [...this.state.listItems, ...nextProps.listItems]
        })
    }
}```

Body:
I was trying to do an infinite scrolling logic, I do this in componentWillReceiveProps, but did not see my list render correctly?

componentWillReceiveProps(nextProps) {
    if(!isEqual(nextProps.listItems, this.state.listItems)){ //user scrolled, call next offset using the API
        this.setState({
            listItems: this.state.listItems.push(...nextProps.listItems)
        })
    }
}


问:
React input value to array not working when using onClick
I have an array that I'd like to add a new name from the user's input.  In my component I have:

```<code><div>
  <h4>Add A Player</h4>
  <input
    type="text"
    placeholder="Enter a new name"
    value={this.state.newPlayerName}
  />
  <button onClick={this.handleAddPlayer}>
     Press to Add Player
  </button>
</div>
</code>```

Which works with this function except for the name:

```<code>handleAddPlayer = e => {
  const players = this.state.players.slice(0);
  players.push({
    name: '',
    id: getRandomInt(20, 55)
  });
  this.setState({
    players: players,
    newPlayerName: e.target.value
  });
};
</code>```

I'm trying to get when a user inputs a name and submits it, it updates in the function which updates the array (if this makes sense, apologies as this is still pretty new to me).

In my state I have:

```<code>this.state = {
  id: players.id,
  totalScore: 0,
  countInfo: [],
  evilName: '',
  color: '#6E68C5',
  scoreColor: '#74D8FF',
  fontAwe: 'score-icon',
  incrementcolor: '',
  scoreNameColor: 'white',
  glow: '',
  buttonStyle: 'count-button-start',
  newPlayerName: '',
  players
};
</code>```

I'm not sure how to get the input to pass the name (or string) to the array, can anyone help?

答:
First of all, you added bound input-updating handler to the wrong element! You currently have it attached to a button, you have to have it attached to the input! Add an onChange handler to your input to update the value every time you change the input:

```<code><input
  type="text"
  placeholder="Enter a new name"
  value={this.state.newPlayerName}
  onChange={this.handleChange}
/>
</code>```

Then create a new method that handles the change:

```<code>handleChange = e => {
  this.setState({
    newPlayerName: e.target.value
  });
}
</code>```

This will let React control the input, and set the input value in state so you can use it when adding a new player. Then, set up the handler to add a new player on click. Instead of slicing, pushing, the resetting, just use array spread syntax:

```<code>handleAddPlayer = e => {
  this.setState(prevState => ({
    players: [...prevState.players, {
      name: this.state.newPlayerName
      id: getRandomInt(20, 55)
    }]
  }));
}
</code>```

This will set players to the previous state's players property plus the new player object with a name that's the input's value and a random id.

Body:
I have an array that I'd like to add a new name from the user's input.  In my component I have:

Add A Player

  <input
    type="text"
    placeholder="Enter a new name"
    value={this.state.newPlayerName}
  />
  <button onClick={this.handleAddPlayer}>
     Press to Add Player
  </button>

Which works with this function except for the name:

handleAddPlayer = e => {
  const players = this.state.players.slice(0);
  players.push({
    name: '',
    id: getRandomInt(20, 55)
  });
  this.setState({
    players: players,
    newPlayerName: e.target.value
  });
};

I'm trying to get when a user inputs a name and submits it, it updates in the function which updates the array (if this makes sense, apologies as this is still pretty new to me).

In my state I have:

this.state = {
  id: players.id,
  totalScore: 0,
  countInfo: [],
  evilName: '',
  color: '#6E68C5',
  scoreColor: '#74D8FF',
  fontAwe: 'score-icon',
  incrementcolor: '',
  scoreNameColor: 'white',
  glow: '',
  buttonStyle: 'count-button-start',
  newPlayerName: '',
  players
};

I'm not sure how to get the input to pass the name (or string) to the array, can anyone help?

Body:
First of all, you added bound input-updating handler to the wrong element! You currently have it attached to a button, you have to have it attached to the input! Add an onChange handler to your input to update the value every time you change the input:

<input
  type="text"
  placeholder="Enter a new name"
  value={this.state.newPlayerName}
  onChange={this.handleChange}
/>

Then create a new method that handles the change:

handleChange = e => {
  this.setState({
    newPlayerName: e.target.value
  });
}

This will let React control the input, and set the input value in state so you can use it when adding a new player. Then, set up the handler to add a new player on click. Instead of slicing, pushing, the resetting, just use array spread syntax:

handleAddPlayer = e => {
  this.setState(prevState => ({
    players: [...prevState.players, {
      name: this.state.newPlayerName
      id: getRandomInt(20, 55)
    }]
  }));
}

This will set players to the previous state's players property plus the new player object with a name that's the input's value and a random id.


问:
How to check if page is postback within reserved function pageLoad on ASP.NET AJAX
I'm looking for a way to check within pageLoad() if this method is raised during load event because of a postback/async postback or because of being loaded and access the first time.

This is similar to Page.IsPostback property within code behind page.

TIA,
Ricky

答: Application.Init is probably a more appropriate event to use, if you only want the code to execute on the first load.</p>

OwnerDisplayName: Ricky Supit

OwnerDisplayName: Dave Ward


问:
LINQ to SQL using GROUP BY and COUNT(DISTINCT)
I have to perform the following SQL query:

```<code>select answer_nbr, count(distinct user_nbr)
from tpoll_answer
where poll_nbr = 16
group by answer_nbr
</code>```

The LINQ to SQL query

```<code>from a in tpoll_answer
where a.poll_nbr = 16 select a.answer_nbr, a.user_nbr distinct
</code>```

maps to the following SQL query:

```<code>select distinct answer_nbr, distinct user_nbr
from tpoll_answer
where poll_nbr = 16
</code>```

So far, so good. However the problem raises when trying to GROUP the results, as I'm not being able to find a LINQ to SQL query that maps to the first query I wrote here (thank you LINQPad for making this process a lot easier). The following is the only one that I've found that gives me the desired result:

```<code>from answer in tpoll_answer where answer.poll_nbr = 16 _
group by a_id = answer.answer_nbr into votes = count(answer.user_nbr)
</code>```

Which in turns produces the follwing ugly and non-optimized at all SQL query:

```<code>SELECT [t1].[answer_nbr] AS [a_id], (
    SELECT COUNT(*)
    FROM (
        SELECT CONVERT(Bit,[t2].[user_nbr]) AS [value], [t2].[answer_nbr], [t2].[poll_nbr]
        FROM [TPOLL_ANSWER] AS [t2]
        ) AS [t3]
    WHERE ([t3].[value] = 1) AND ([t1].[answer_nbr] = [t3].[answer_nbr]) AND ([t3].[poll_nbr] = @p0)
    ) AS [votes]
FROM (
    SELECT [t0].[answer_nbr]
    FROM [TPOLL_ANSWER] AS [t0]
    WHERE [t0].[poll_nbr] = @p0
    GROUP BY [t0].[answer_nbr]
    ) AS [t1]
-- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [16]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1
</code>```

Any help will be more than appreciated.

答:
There isn't direct support for COUNT(DISTINCT {x})), but you can simulate it from an IGrouping<,> (i.e. what group by returns); I'm afraid I only "do" C#, so you'll have to translate to VB...

```<code> select new
 {
     Foo= grp.Key,
     Bar= grp.Select(x => x.SomeField).Distinct().Count()
 };
</code>```

Here's a Northwind example:

```<code>    using(var ctx = new DataClasses1DataContext())
    {
        ctx.Log = Console.Out; // log TSQL to console
        var qry = from cust in ctx.Customers
                  where cust.CustomerID != ""
                  group cust by cust.Country
                  into grp
                  select new
                  {
                      Country = grp.Key,
                      Count = grp.Select(x => x.City).Distinct().Count()
                  };

        foreach(var row in qry.OrderBy(x=>x.Country))
        {
            Console.WriteLine("{0}: {1}", row.Country, row.Count);
        }
    }
</code>```

The TSQL isn't quite what we'd like, but it does the job:

```<code>SELECT [t1].[Country], (
    SELECT COUNT(*)
    FROM (
        SELECT DISTINCT [t2].[City]
        FROM [dbo].[Customers] AS [t2]
        WHERE ((([t1].[Country] IS NULL) AND ([t2].[Country] IS NULL)) OR (([t1]
.[Country] IS NOT NULL) AND ([t2].[Country] IS NOT NULL) AND ([t1].[Country] = [
t2].[Country]))) AND ([t2].[CustomerID] <> @p0)
        ) AS [t3]
    ) AS [Count]
FROM (
    SELECT [t0].[Country]
    FROM [dbo].[Customers] AS [t0]
    WHERE [t0].[CustomerID] <> @p0
    GROUP BY [t0].[Country]
    ) AS [t1]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1
</code>```

The results, however, are correct- verifyable by running it manually:

```<code>        const string sql = @"
SELECT c.Country, COUNT(DISTINCT c.City) AS [Count]
FROM Customers c
WHERE c.CustomerID != ''
GROUP BY c.Country
ORDER BY c.Country";
        var qry2 = ctx.ExecuteQuery<QueryResult>(sql);
        foreach(var row in qry2)
        {
            Console.WriteLine("{0}: {1}", row.Country, row.Count);
        }
</code>```

With definition:

```<code>class QueryResult
{
    public string Country { get; set; }
    public int Count { get; set; }
}
</code>```

OwnerDisplayName: Leandro López

Body:
I have to perform the following SQL query:

select answer_nbr, count(distinct user_nbr)
from tpoll_answer
where poll_nbr = 16
group by answer_nbr

The LINQ to SQL query

from a in tpoll_answer
where a.poll_nbr = 16 select a.answer_nbr, a.user_nbr distinct

maps to the following SQL query:

select distinct answer_nbr, distinct user_nbr
from tpoll_answer
where poll_nbr = 16

So far, so good. However the problem raises when trying to GROUP the results, as I'm not being able to find a LINQ to SQL query that maps to the first query I wrote here (thank you LINQPad for making this process a lot easier). The following is the only one that I've found that gives me the desired result:

from answer in tpoll_answer where answer.poll_nbr = 16 _
group by a_id = answer.answer_nbr into votes = count(answer.user_nbr)

Which in turns produces the follwing ugly and non-optimized at all SQL query:

SELECT [t1].[answer_nbr] AS [a_id], (
    SELECT COUNT(*)
    FROM (
        SELECT CONVERT(Bit,[t2].[user_nbr]) AS [value], [t2].[answer_nbr], [t2].[poll_nbr]
        FROM [TPOLL_ANSWER] AS [t2]
        ) AS [t3]
    WHERE ([t3].[value] = 1) AND ([t1].[answer_nbr] = [t3].[answer_nbr]) AND ([t3].[poll_nbr] = @p0)
    ) AS [votes]
FROM (
    SELECT [t0].[answer_nbr]
    FROM [TPOLL_ANSWER] AS [t0]
    WHERE [t0].[poll_nbr] = @p0
    GROUP BY [t0].[answer_nbr]
    ) AS [t1]
-- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [16]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

Any help will be more than appreciated.

Body:
There isn't direct support for COUNT(DISTINCT {x})), but you can simulate it from an IGrouping<,> (i.e. what group by returns); I'm afraid I only "do" C#, so you'll have to translate to VB...

 select new
 {
     Foo= grp.Key,
     Bar= grp.Select(x => x.SomeField).Distinct().Count()
 };

Here's a Northwind example:

    using(var ctx = new DataClasses1DataContext())
    {
        ctx.Log = Console.Out; // log TSQL to console
        var qry = from cust in ctx.Customers
                  where cust.CustomerID != ""
                  group cust by cust.Country
                  into grp
                  select new
                  {
                      Country = grp.Key,
                      Count = grp.Select(x => x.City).Distinct().Count()
                  };

        foreach(var row in qry.OrderBy(x=>x.Country))
        {
            Console.WriteLine("{0}: {1}", row.Country, row.Count);
        }
    }

The TSQL isn't quite what we'd like, but it does the job:

SELECT [t1].[Country], (
    SELECT COUNT(*)
    FROM (
        SELECT DISTINCT [t2].[City]
        FROM [dbo].[Customers] AS [t2]
        WHERE ((([t1].[Country] IS NULL) AND ([t2].[Country] IS NULL)) OR (([t1]
.[Country] IS NOT NULL) AND ([t2].[Country] IS NOT NULL) AND ([t1].[Country] = [
t2].[Country]))) AND ([t2].[CustomerID] <> @p0)
        ) AS [t3]
    ) AS [Count]
FROM (
    SELECT [t0].[Country]
    FROM [dbo].[Customers] AS [t0]
    WHERE [t0].[CustomerID] <> @p0
    GROUP BY [t0].[Country]
    ) AS [t1]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

The results, however, are correct- verifyable by running it manually:

        const string sql = @"
SELECT c.Country, COUNT(DISTINCT c.City) AS [Count]
FROM Customers c
WHERE c.CustomerID != ''
GROUP BY c.Country
ORDER BY c.Country";
        var qry2 = ctx.ExecuteQuery<QueryResult>(sql);
        foreach(var row in qry2)
        {
            Console.WriteLine("{0}: {1}", row.Country, row.Count);
        }

With definition:

class QueryResult
{
    public string Country { get; set; }
    public int Count { get; set; }
}

OwnerDisplayName: Marc Gravell

LastEditorDisplayName: Marc Gravell


问:
What exactly are Static Constructor in C#?
I have couple of question regarding Static Constructor in C#.

What exactly are Static Constructor and how they are different from non-static Constructor.

How can we use them in our application ?

**Edited

```<code>public class Test
{
    // Static constructor:
    static Test()
    {
        Console.WriteLine("Static constructor invoked.");
    }

    public static void TestMethod()
    {
       Console.WriteLine("TestMethod invoked.");
    }
}

class Sample
{
    static void Main()
    {
        Test.TestMethod();
    }
}
</code>```

Output :
Static constructor invoked.
TestMethod invoked.
So, this means that static constructor will be called once. if we again call  Test.TestMethod(); static constructor won't invoke.

Any pointer or suggestion would be appreciated
 '

Thanks

答:
Static constructors are constructors that are executed only ONCE when the class is loaded. Regular (non-static) constructors are executed every time an object is created.

Take a look at this example:

```<code>public class A
{
     public static int aStaticVal;
     public int aVal;

     static A() {
         aStaticVal = 50;
     }

     public A() {
         aVal = aStaticVal++;
     }
}
</code>```

And consider this code:

```<code>A a1 = new A();
A a2 = new A();
A a3 = new A();
</code>```

Here, static constructor will be called first and only once during the execution of the program. While regular constructor will be called three times (once for each object instantiation).

static constructors are usually used to do initialization of static fields for example, assigning an initial value to static fields.. Do keep in mind that you will only be able to access static members (methods, properties and fields) on static constructors.

If you need to "execute the static constructor multiple times", you can't do that. Instead, you can put the code you want to run "multiple times" in a static method and call it whenever you need. Something like:

```<code>public class A {
    public static int a, b;
    static A() {
         A.ResetStaticVariables();
    }
    public static void ResetStaticVariables() {
        a = b = 0;
    }
}
</code>```

Body:
I have couple of question regarding Static Constructor in C#.

What exactly are Static Constructor and how they are different from non-static Constructor.

How can we use them in our application ?

**Edited

public class Test
{
    // Static constructor:
    static Test()
    {
        Console.WriteLine("Static constructor invoked.");
    }

    public static void TestMethod()
    {
       Console.WriteLine("TestMethod invoked.");
    }
}

class Sample
{
    static void Main()
    {
        Test.TestMethod();
    }
}

Output :
Static constructor invoked.
TestMethod invoked.
So, this means that static constructor will be called once. if we again call  Test.TestMethod(); static constructor won't invoke.

Any pointer or suggestion would be appreciated
 '

Thanks

Body:
Static constructors are constructors that are executed only ONCE when the class is loaded. Regular (non-static) constructors are executed every time an object is created.

Take a look at this example:

public class A
{
     public static int aStaticVal;
     public int aVal;

     static A() {
         aStaticVal = 50;
     }

     public A() {
         aVal = aStaticVal++;
     }
}

And consider this code:

A a1 = new A();
A a2 = new A();
A a3 = new A();

Here, static constructor will be called first and only once during the execution of the program. While regular constructor will be called three times (once for each object instantiation).

static constructors are usually used to do initialization of static fields for example, assigning an initial value to static fields.. Do keep in mind that you will only be able to access static members (methods, properties and fields) on static constructors.

If you need to "execute the static constructor multiple times", you can't do that. Instead, you can put the code you want to run "multiple times" in a static method and call it whenever you need. Something like:

public class A {
    public static int a, b;
    static A() {
         A.ResetStaticVariables();
    }
    public static void ResetStaticVariables() {
        a = b = 0;
    }
}


问:
How can i get the network Cell ID while i am on CDMA connection?
I can get my network cell id using GsmCellLocation object. but when i am on CDMA, 3G, HSDPA, or UMTS.....I cant get the Cell ID. using the GsmCellLocation.getCid() with 3G connection retrieves something called LCID (Logical Channel ID) which is not the Cid. The code i used to get the Gsm Cell ID shown below:

```<code>private PhoneStateListener mPhoneLocationListener = new PhoneStateListener() {
    public void onCellLocationChanged(CellLocation location) {
                    TelephonyManager tm  = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
           GsmCellLocation location2 = (GsmCellLocation) tm.getCellLocation();
           cellId = location2.getCid();
    }
}
</code>```

but when i change the line:

```<code>GsmCellLocation location2 = (GsmCellLocation) tm.getCellLocation();
</code>```

to :

```<code>CdmaCellLocation location2 = (CdmaCellLocation) tm.getCellLocation();
</code>```

even when i am forcing my device to connect only to CDMA, exception is thrown with CastException saying cannot cast GsmCellLocation to CdmaCellLocation.

So how can i get the 3g cell id info ?

答:
CDMA dosen't have Cell ID . Instead it has 3 identifier :

SID - System ID

NID - Network ID

BID - Basestation ID

For more information see this page from OpenCellID wiki :
http://wiki.opencellid.org/wiki/Public:CDMA

Body:
I can get my network cell id using GsmCellLocation object. but when i am on CDMA, 3G, HSDPA, or UMTS.....I cant get the Cell ID. using the GsmCellLocation.getCid() with 3G connection retrieves something called LCID (Logical Channel ID) which is not the Cid. The code i used to get the Gsm Cell ID shown below:

private PhoneStateListener mPhoneLocationListener = new PhoneStateListener() {
    public void onCellLocationChanged(CellLocation location) {
                    TelephonyManager tm  = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
           GsmCellLocation location2 = (GsmCellLocation) tm.getCellLocation();
           cellId = location2.getCid();
    }
}

but when i change the line:

GsmCellLocation location2 = (GsmCellLocation) tm.getCellLocation();

to :

CdmaCellLocation location2 = (CdmaCellLocation) tm.getCellLocation();

even when i am forcing my device to connect only to CDMA, exception is thrown with CastException saying cannot cast GsmCellLocation to CdmaCellLocation.

So how can i get the 3g cell id info ?


问:
How to set active class on ng-click?
I have this:

```<code><div class="account-item">
    <div class="account-heading" ng-class="active">
        <h4 class="account-title">
            <a href="#/Messages"  onclick="SetActiveAccountHeading(this);">
            7.    @Translate("SYSTEM_MESSAGES")</a>
        </h4>
    </div>
    </div>
    <div class="account-item">
       <div class="account-heading" ng-class="active">
           <h4 class="account-title">
              <a href="#/Info"  onclick="SetActiveAccountHeading(this);">
              7.    @Translate("SYSTEM_INFO")</a>
           </h4>
      </div>
   </div>
</code>```

In angular i have this:

```<code>$scope.active = "active";
</code>```

but how can i change this on click so if user click on menu once it would be active if again click it would be NOT active?

答:
Angular4:

```<code><a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>

<a [routerLink]="['calendar']" routerLinkActive="active">
</code>```

Documentation: https://angular.io/api/router/RouterLinkActive

Title: How to set active class on ng-click?

Body:
I have this:

            7.    @Translate("SYSTEM_MESSAGES")

              7.    @Translate("SYSTEM_INFO")

In angular i have this:

$scope.active = "active";

but how can i change this on click so if user click on menu once it would be active if again click it would be NOT active?

Body:
Angular4:

<a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>

<a [routerLink]="['calendar']" routerLinkActive="active">

Documentation: https://angular.io/api/router/RouterLinkActive


问:
How to bitshift an array of ints?
I have an int array of size 50 and the first 49 'slots' are filled and I want to move each of the 49 elements of the array one position along so that the first element in the array is now free.

Is there a way to bit shift the entire array 32 bits? like:

array[0] >(49)> 32;

some random made up notation... but I hope it conveys what I am looking for

答:
As @COLDSPEED suggested in the comments, memmove does very close to what you are expecting.

void *memmove(void *str1, const void *str2, size_t n)

NOTE: n is the total size in bytes to move. From moving 32 bits you might want to make space for 1 int I guess. (size of int is machine dependent). So, with memmove you can shift 1 byte. Not 1 bit.

And the main purpose of memmove is just to copy. Hence it should not be any better than straight forward copying. Both should take O(n) times.

Conventional method:

```<code>for (i = 5; i > 0; i--)
    arr[i] = arr[i-1];
arr[0] = 5;
</code>```

Here is a sample code, using memmove doing the same thing:

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

int main ()
{
    int i;
    int arr[5] = {1, 2, 3, 4};

    // Printing before state
    for (i = 0; i < 4; i++)
        printf ("%d ", arr[i]);
    printf ("\n");

    // The shift operation
    memmove(arr+1, arr, 4*sizeof(int));

    // Inserting at the beginning
    arr[0] = 5;

   // Printing after state
   printf("After memmove:\n");
   for (i = 0; i < 5; i++)
        printf ("%d ", arr[i]);
    printf ("\n");

   return 0;
}
</code>```

Output:

```<code>1 2 3 4
After memmove:
5 1 2 3 4
</code>```

Here is an article if you want to learn more about mmove: memmove-in-c/c++

Title: How to bitshift an array of ints?

Body:
As @COLDSPEED suggested in the comments, memmove does very close to what you are expecting.

void *memmove(void *str1, const void *str2, size_t n)

NOTE: n is the total size in bytes to move. From moving 32 bits you might want to make space for 1 int I guess. (size of int is machine dependent). So, with memmove you can shift 1 byte. Not 1 bit.

And the main purpose of memmove is just to copy. Hence it should not be any better than straight forward copying. Both should take O(n) times.

Conventional method:

for (i = 5; i > 0; i--)
    arr[i] = arr[i-1];
arr[0] = 5;

Here is a sample code, using memmove doing the same thing:

#include <stdio.h>
#include <string.h>

int main ()
{
    int i;
    int arr[5] = {1, 2, 3, 4};

    // Printing before state
    for (i = 0; i < 4; i++)
        printf ("%d ", arr[i]);
    printf ("\n");

    // The shift operation
    memmove(arr+1, arr, 4*sizeof(int));

    // Inserting at the beginning
    arr[0] = 5;

   // Printing after state
   printf("After memmove:\n");
   for (i = 0; i < 5; i++)
        printf ("%d ", arr[i]);
    printf ("\n");

   return 0;
}

Output:

1 2 3 4
After memmove:
5 1 2 3 4

Here is an article if you want to learn more about mmove: memmove-in-c/c++


Title: Python Pandas Calc Column

Body:
I have two Pandas dataframes and I am trying to join the right table on the left table where Inclination closest matches the Left tables 'Depth' from the Right Tables 'MeasuredDepth'?

Example left table  (main table)

index     Date_Time         Depth
6659    4/25/2017 1:26       2073.02
6660    4/25/2017 1:26       2073.287
6661    4/25/2017 1:26       2073.916
6662    4/25/2017 1:26       2074.64
6663    4/25/2017 1:26       2075.335
6664    4/25/2017 1:26       2076.044

Example Right table (Reference table)

index   MeasuredDepth   Inclination
16      1844           1.42
17      1939           1.69
18      2034           1.43
19      2128           1.39
20      2223           1.12
21      2317           1.22
22      2412           1.1
23      2600           0.56
24      2695           1.97

Example Result Table

index   DATETIME        Depth        Inclination
6659    4/25/2017 1:26      2073.02          1.43
6660    4/25/2017 1:26      2073.287         1.43
6661    4/25/2017 1:26      2073.916         1.43
...
26704   5/3/2017 23:23      2625.316         0.56
26705   5/3/2017 23:23      2626.143         0.56
26706   5/3/2017 23:24       2627.08         0.56
26707   5/3/2017 23:24      2628.056         0.56

Any help would be appreciated!

Body:
Let's use pd.merge_asof:

ref_df['MeasuredDepth'] = ref_df['MeasuredDepth'].astype(float)

df_out = pd.merge_asof(main_df, ref_df, left_on='Depth',right_on='MeasuredDepth')

Output:

     index_x Date_Time     Depth  index_y  MeasuredDepth  Inclination
0  4/25/2017      1:26  2073.020       18         2034.0         1.43
1  4/25/2017      1:26  2073.287       18         2034.0         1.43
2  4/25/2017      1:26  2073.916       18         2034.0         1.43
3  4/25/2017      1:26  2074.640       18         2034.0         1.43
4  4/25/2017      1:26  2075.335       18         2034.0         1.43
5  4/25/2017      1:26  2076.044       18         2034.0         1.43


Title: Resampling dataframe by hours and date

Body:
I have a dataframe like this:

                 Maximum Demand (KVA)  Consumption (KVAh)  Power Factor
Timestamp
2017-04-01 01:00:00                 127.0               261.0          0.81
2017-04-01 02:00:00                 133.0               268.0          0.79
2017-04-01 03:00:00                 119.0               273.0          0.92
2017-04-01 04:00:00                 118.0               263.0          0.78
2017-04-01 05:00:00                 135.0               271.0          0.86
2017-04-01 06:00:00                 130.0               257.0          0.82
2017-04-01 23:00:00                 120.0               261.0          0.78
2017-04-02 00:00:00                 121.0               272.0          0.83
2017-04-02 01:00:00                 126.0               263.0          0.90
2017-04-02 02:00:00                 132.0               266.0          0.83
2017-04-02 03:00:00                 132.0               275.0          0.90
2017-04-02 04:00:00                 122.0               259.0          0.77
2017-04-02 05:00:00                 119.0               271.0          0.78
2017-04-02 06:00:00                 122.0               259.0          0.81
2017-04-02 23:00:00                 115.0               264.0          0.87
2017-04-03 00:00:00                 129.0               273.0          0.86

I want to resample data by the time of 01:00 - 0:00 of another date:

I tried this:

off_sum = offpeak_hist.resample('h', base=8).sum().dropna()

But the desired output is not achieved. Please help me on this.

Body:
I think you need first shift by one hour and then resample by days:

print (offpeak_hist.shift(-1, freq='H'))
                     Maximum Demand (KVA)  Consumption (KVAh)  Power Factor
Timestamp
2017-04-01 00:00:00                 127.0               261.0          0.81
2017-04-01 01:00:00                 133.0               268.0          0.79
2017-04-01 02:00:00                 119.0               273.0          0.92
2017-04-01 03:00:00                 118.0               263.0          0.78
2017-04-01 04:00:00                 135.0               271.0          0.86
2017-04-01 05:00:00                 130.0               257.0          0.82
2017-04-01 22:00:00                 120.0               261.0          0.78
2017-04-01 23:00:00                 121.0               272.0          0.83
2017-04-02 00:00:00                 126.0               263.0          0.90
2017-04-02 01:00:00                 132.0               266.0          0.83
2017-04-02 02:00:00                 132.0               275.0          0.90
2017-04-02 03:00:00                 122.0               259.0          0.77
2017-04-02 04:00:00                 119.0               271.0          0.78
2017-04-02 05:00:00                 122.0               259.0          0.81
2017-04-02 22:00:00                 115.0               264.0          0.87
2017-04-02 23:00:00                 129.0               273.0          0.86

df = offpeak_hist.shift(-1, freq='H').resample('D').sum().dropna()
print (df)
            Maximum Demand (KVA)  Consumption (KVAh)  Power Factor
Timestamp
2017-04-01                1003.0              2126.0          6.59
2017-04-02                 997.0              2130.0          6.72


问:
Align Check Boxes CSS
I want to align some check boxes with labels such that the check boxes are in a vertical row to the right side and the labels are aligned with the starting edges in a vertical row on the left side.</p>

答:
.row {
  display: flex;
}
.row label { flex: 1; max-width: 25%; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <label>Label</label><input type="checkbox" />
  </div>
  <div class="row">
    <label>Label 2</label><input type="checkbox" />
  </div>
  <div class="row">
    <label>Label 3</label><input type="checkbox" />
  </div>
</div></code>```

Title: Align Check Boxes CSS

Body:
.row {
  display: flex;
}
.row label { flex: 1; max-width: 25%; }

<div class="container">
  <div class="row">
    <label>Label</label><input type="checkbox" />
  </div>
  <div class="row">
    <label>Label 2</label><input type="checkbox" />
  </div>
  <div class="row">
    <label>Label 3</label><input type="checkbox" />
  </div>
</div>


问:
Value of type String cannot be converted to JSONObject
I'm struggling with an error that tells me that it cannot convert a String value to JSONObject. I'm trying to pass a CSRFToken as a parameter to my JSONObjectRequest. I have no clue if this is the right way to even go about it.

I'm getting the error message: org.json.JSONException: Value inz9J9w0N5qASdJO8soWFBZ4UrEpdnjnpmxvFbJ2 of type java.lang.String cannot be converted to JSONObject

Relevant code is below.

HashMap<String, String> params = new HashMap<>();
params.put("_token", ((TestApplication) getApplication()).getCSRFToken());

JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).create();
        alertDialog.setTitle("Alert");
        Log.i("response", response.toString());
        alertDialog.setMessage(response.toString());
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).create();
        alertDialog.setTitle("Alert");
        alertDialog.setMessage(error.getMessage());
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }
});

queue.add(stringRequest);
```

Does anyone know what I may have done wrong and how to rectify the issue?

答:
The following should be valid.

```<code>{
    "_token": "inz9J9w0N5qASdJO8soWFBZ4UrEpdnjnpmxvFbJ2"
}
</code>```

Can you try

```<code>String tokenString = (String) ((TestApplication) getApplication()).getCSRFToken();
JSONObject params = new JSONObject();
params.put("_token", tokenString);

JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
// ...
}
</code>```

Body:
I'm struggling with an error that tells me that it cannot convert a String value to JSONObject. I'm trying to pass a CSRFToken as a parameter to my JSONObjectRequest. I have no clue if this is the right way to even go about it.

I'm getting the error message: org.json.JSONException: Value inz9J9w0N5qASdJO8soWFBZ4UrEpdnjnpmxvFbJ2 of type java.lang.String cannot be converted to JSONObject

Relevant code is below.

HashMap<String, String> params = new HashMap<>();
params.put("_token", ((TestApplication) getApplication()).getCSRFToken());

JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).create();
        alertDialog.setTitle("Alert");
        Log.i("response", response.toString());
        alertDialog.setMessage(response.toString());
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).create();
        alertDialog.setTitle("Alert");
        alertDialog.setMessage(error.getMessage());
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }
});

queue.add(stringRequest);

Does anyone know what I may have done wrong and how to rectify the issue?

Body:
The following should be valid.

{
    "_token": "inz9J9w0N5qASdJO8soWFBZ4UrEpdnjnpmxvFbJ2"
}

Can you try

String tokenString = (String) ((TestApplication) getApplication()).getCSRFToken();
JSONObject params = new JSONObject();
params.put("_token", tokenString);

JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
// ...
}


问:
How to get jQuery to submit a form to a post
I have a form that I am validating with jQuery.

```<code><form id="target" class="center-block" action="/" method="POST">
    <textarea class="form-control" id="name" rows="3" name="name" placeholder="Enter a burger you would like to devour!"></textarea>
    <button type="button" id="submit" class="center-block btn btn-default top">Submit</button>
</form>
</code>```

After validation I am also trying to submit the form via jQuery.

```<code>if (validateForm() == true) {
   $("#target").submit();
}
</code>```

The validation is working however, it doesn't seem like the form is submitting to the post route.  I was able to get the form to post using ajax, but the post wouldn't redirect after finishing.  Was hoping this method would give the desired effect.

The app is running on Express and using MySQL.

答:
I might have a typo in there, but the idea is:</p>

```<code>$('#target').submit(function(event){
    event.preventDefault();
}).validate({
    rules: { ... },
    submitHandler: function(form){
        $.ajax{
            type: 'POST',
            data: $(form).serialize(),
            url: '/',
            success: function(result){
                console.log(result);
            }
            error: function(err){
                console.log(err.message);
            }
        }
    });
});
</code>```

Body:
I have a form that I am validating with jQuery.

<form id="target" class="center-block" action="/" method="POST">
    <textarea class="form-control" id="name" rows="3" name="name" placeholder="Enter a burger you would like to devour!"></textarea>
    <button type="button" id="submit" class="center-block btn btn-default top">Submit</button>
</form>

After validation I am also trying to submit the form via jQuery.

if (validateForm() == true) {
   $("#target").submit();
}

The validation is working however, it doesn't seem like the form is submitting to the post route.  I was able to get the form to post using ajax, but the post wouldn't redirect after finishing.  Was hoping this method would give the desired effect.

The app is running on Express and using MySQL.

Body:
I might have a typo in there, but the idea is:

$('#target').submit(function(event){
    event.preventDefault();
}).validate({
    rules: { ... },
    submitHandler: function(form){
        $.ajax{
            type: 'POST',
            data: $(form).serialize(),
            url: '/',
            success: function(result){
                console.log(result);
            }
            error: function(err){
                console.log(err.message);
            }
        }
    });
});


问:
Change a Public Float Value within a Menu [Android]
 Basically I am making an app where there is a Ball On the screen and the size of the ball is determined by this code

private static final float sBallDiameter = 0.011f;

Is there any way i could create a menu system for the user , For example Like a pop up menu shown here

http://i.stack.imgur.com/WsHJX.png

That would change the size of the ball , For example where on the menu above it says Map , Traffic , Street View etc. - I could use Small, Medium, Large

Small, changing the sBallDiameter to something like 0.009f
and large changing it to something like 0.018f

I hope you get what i mean , but if someone could assist me on creating this menu type thing it would be great !

```<code>             **UPDATE :**
</code>```

Here is the current Menu

```<code>private static final int Small= 1;

     public boolean onCreateOptionsMenu(Menu menu) {
        ((Activity) menu).onCreateOptionsMenu(menu);

        menu.add(0, Small, 0, "Small");

       return true;

    }
     public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case Small:

                   // here i want it to change the size down to something like 0.009f

                    return true;
            }
            return false;
     }

    public   float sBallDiameter = 0.013f;
</code>```

Basically - What i want to do is make it so when the case "Small" is selected - it decreases the size of "sBallDiameter"

I hope that clears things up a bit more -

答:
Use Enum instead of fixed size

```<code>public Enum BallSize{

  SMALL(0.09f),MEDIUM(0.11f),LARGE(0.018f);

  BallSize(float size)
  {
    this.size=size;
  }

  private final float size;
}
</code>```

And after user changes menu compare the menu item with Ballsize

Body:
 Basically I am making an app where there is a Ball On the screen and the size of the ball is determined by this code

private static final float sBallDiameter = 0.011f;

Is there any way i could create a menu system for the user , For example Like a pop up menu shown here

http://i.stack.imgur.com/WsHJX.png

That would change the size of the ball , For example where on the menu above it says Map , Traffic , Street View etc. - I could use Small, Medium, Large

Small, changing the sBallDiameter to something like 0.009f
and large changing it to something like 0.018f

I hope you get what i mean , but if someone could assist me on creating this menu type thing it would be great !

             **UPDATE :**

Here is the current Menu

private static final int Small= 1;

     public boolean onCreateOptionsMenu(Menu menu) {
        ((Activity) menu).onCreateOptionsMenu(menu);

        menu.add(0, Small, 0, "Small");

       return true;

    }
     public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case Small:

                   // here i want it to change the size down to something like 0.009f

                    return true;
            }
            return false;
     }

    public   float sBallDiameter = 0.013f;

Basically - What i want to do is make it so when the case "Small" is selected - it decreases the size of "sBallDiameter"

I hope that clears things up a bit more -

Body:
Use Enum instead of fixed size

public Enum BallSize{

  SMALL(0.09f),MEDIUM(0.11f),LARGE(0.018f);

  BallSize(float size)
  {
    this.size=size;
  }

  private final float size;
}

And after user changes menu compare the menu item with Ballsize


问:
CSS Background-color works bottom half only
I'm trying to make a social media button using an a tag and a fontawesome icon. I want to make the entire background color to be black by using css, but when I tried it only the bottom half turned black.

Html:

```<code><div class="social-media">
    <a class="social-media-icon">
        <i class="fa fa-instagram fa-4x" aria-hidden="true"></i>
    </a>
</div>
</code>```

Css (less):

```<code>.social-media{
    .social-media-icon{
        color: red;
        background-color: black;
    }
}
</code>```

What should I do?

答:
Make the icon an (inline-)block element.

.social-media-icon {
  color: red;
  background-color: black;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<div class="social-media">

    <i class="fa fa-instagram fa-4x" aria-hidden="true"></i>

</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a social media button using an a tag and a fontawesome icon. I want to make the entire background color to be black by using css, but when I tried it only the bottom half turned black.

Html:

Css (less):

.social-media{
    .social-media-icon{
        color: red;
        background-color: black;
    }
}

What should I do?

Body:
Make the icon an (inline-)block element.

.social-media-icon {
  color: red;
  background-color: black;
  display: inline-block;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<div class="social-media">
  <a class="social-media-icon">
    <i class="fa fa-instagram fa-4x" aria-hidden="true"></i>
  </a>
</div>


问:
Why C++ doesn't allow derived class to use base class member in initialization list?
I've got following program:

```<code>#include<iostream>
using namespace std;
struct Base01{
    int m;
    Base01():m(2){}
    void p(){cout<<m<<endl;}
};
struct Derived01:public Base01{
    Derived01():m(3){}
};
struct Derived02:virtual public Base01{
    Derived01():m(4){}
};
struct my: Derived01,Derived02{
    my():m(5){}
};
int main(){
    return 0;
}
</code>```

Both gcc/clang reports compilation error.

I just wish to know what's the language design consideration here, why derived class can only call base class ctor in initialization list, but cannot use base class members directly?

答:
The proper way to do this in C++ is to pass that value to the base class constructor.  Your Base01 class needs an additional constructor that takes the desired value for m.  Something like this:

```<code>struct Base01{
    int m;
    Base01():m(2){}

    // Added this:
    Base01(int mVal) : m(mVal) {}

    void p(){cout<<m<<endl;}
};

struct Derived01:public Base01{
    Derived01() : Base01(3) {}   // Calling base constructor rather than
                                 // initializing base member
};

struct Derived02:virtual public Base01{
    Derived01() : Base01(4){}    // Same here
};

struct my: Derived01,Derived02{
    my(): Base01(5){}            // And here.
};
</code>```

As AnT said, you can't initialize twice--but you can set it up so that things are initialized the way you want in the first place by doing as above.

Body:
I've got following program:

#include<iostream>
using namespace std;
struct Base01{
    int m;
    Base01():m(2){}
    void p(){cout<<m<<endl;}
};
struct Derived01:public Base01{
    Derived01():m(3){}
};
struct Derived02:virtual public Base01{
    Derived01():m(4){}
};
struct my: Derived01,Derived02{
    my():m(5){}
};
int main(){
    return 0;
}

Both gcc/clang reports compilation error.

I just wish to know what's the language design consideration here, why derived class can only call base class ctor in initialization list, but cannot use base class members directly?

Body:
The proper way to do this in C++ is to pass that value to the base class constructor.  Your Base01 class needs an additional constructor that takes the desired value for m.  Something like this:

struct Base01{
    int m;
    Base01():m(2){}

    // Added this:
    Base01(int mVal) : m(mVal) {}

    void p(){cout<<m<<endl;}
};

struct Derived01:public Base01{
    Derived01() : Base01(3) {}   // Calling base constructor rather than
                                 // initializing base member
};

struct Derived02:virtual public Base01{
    Derived01() : Base01(4){}    // Same here
};

struct my: Derived01,Derived02{
    my(): Base01(5){}            // And here.
};

As AnT said, you can't initialize twice--but you can set it up so that things are initialized the way you want in the first place by doing as above.


问:
Compile all Opened FLA files in Flash IDE using JSFL
Is there is a JSFL script to compile all opened fla in the Flash IDE?</p>

答:
This snippet will compile all open files according to their export settings:

```<code>function export_all(){
    var docs=fl.documents;
    var docs_length=docs.length;
    for (var i=0; i<docs_length; i++) {
        var doc=docs[i];
        doc.publish();
    }
}
export_all();
</code>```

Source: http://www.agileflash.com/2010/04/publish-all-opened-fla-files-using-jsfl/

Body:
This snippet will compile all open files according to their export settings:

function export_all(){
    var docs=fl.documents;
    var docs_length=docs.length;
    for (var i=0; i<docs_length; i++) {
        var doc=docs[i];
        doc.publish();
    }
}
export_all();

Source: http://www.agileflash.com/2010/04/publish-all-opened-fla-files-using-jsfl/


问:
Getting File Metadata from Google API V3 in Python
I am trying to retrieve file metadata from Google drive API V3 in Python. I did it in API V2, but failed in V3.
I tried to get metadata by this line:

```<code>data = DRIVE.files().get(fileId=file['id']).execute()
</code>```

but all I got was a dict of 'id', 'kind', 'name', and 'mimeType'. How can I get 'md5Checksum', 'fileSize', and so on?

I read the documentation.
I  am supposed to get all the metadata by get() methods, but all I got was a small part of it.

Here is my code:

```<code>from __future__ import print_function
import os

from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/drive.metadata
https://www.googleapis.com/auth/drive'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('storage.json', scope=SCOPES)
    creds = tools.run_flow(flow, store)
DRIVE = build('drive','v3', http=creds.authorize(Http()))

files = DRIVE.files().list().execute().get('files',[])

for file in files:
    print('\n',file['name'],file['id'])
    data = DRIVE.files().get(fileId=file['id']).execute()
    print('\n',data)

print('Done')
</code>```

I tried this answer:
Google Drive API v3 Migration

List

Files returned by service.files().list() do not contain information now, i.e. every field is null. If you want list on v3 to behave like in v2, call it like this:

```<code>service.files().list().setFields("nextPageToken, files");
</code>```

but I get a Traceback:

```<code>DRIVE.files().list().setFields("nextPageToken, files")
AttributeError: 'HttpRequest' object has no attribute 'setFields'
</code>```

答:
There is a library PyDrive that provide easy interactions with google drive

https://googledrive.github.io/PyDrive/docs/build/html/filelist.html

Their example:

```<code>from pydrive.drive import GoogleDrive

drive = GoogleDrive(gauth) # Create GoogleDrive instance with authenticated GoogleAuth instance

# Auto-iterate through all files in the root folder.
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
  print('title: %s, id: %s' % (file1['title'], file1['id']))
</code>```

All you need is file1['your key']

Body:
I am trying to retrieve file metadata from Google drive API V3 in Python. I did it in API V2, but failed in V3.
I tried to get metadata by this line:

data = DRIVE.files().get(fileId=file['id']).execute()

but all I got was a dict of 'id', 'kind', 'name', and 'mimeType'. How can I get 'md5Checksum', 'fileSize', and so on?

I read the documentation.
I  am supposed to get all the metadata by get() methods, but all I got was a small part of it.

Here is my code:

from __future__ import print_function
import os

from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/drive.metadata
https://www.googleapis.com/auth/drive'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('storage.json', scope=SCOPES)
    creds = tools.run_flow(flow, store)
DRIVE = build('drive','v3', http=creds.authorize(Http()))

files = DRIVE.files().list().execute().get('files',[])

for file in files:
    print('\n',file['name'],file['id'])
    data = DRIVE.files().get(fileId=file['id']).execute()
    print('\n',data)

print('Done')

I tried this answer:
Google Drive API v3 Migration

List

Files returned by service.files().list() do not contain information now, i.e. every field is null. If you want list on v3 to behave like in v2, call it like this:

service.files().list().setFields("nextPageToken, files");

but I get a Traceback:

DRIVE.files().list().setFields("nextPageToken, files")
AttributeError: 'HttpRequest' object has no attribute 'setFields'

Body:
There is a library PyDrive that provide easy interactions with google drive

https://googledrive.github.io/PyDrive/docs/build/html/filelist.html

Their example:

from pydrive.drive import GoogleDrive

drive = GoogleDrive(gauth) # Create GoogleDrive instance with authenticated GoogleAuth instance

# Auto-iterate through all files in the root folder.
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
  print('title: %s, id: %s' % (file1['title'], file1['id']))

All you need is file1['your key']


问:
Typeerror: Tuple Indices when iterating over cells
Quick run down; I'm trying to iterate over all cells in column "A" and output the value of the color used in the cell. This works fine when iterating over the first cell, but when it tries again I get the following error;

```<code>Traceback (most recent call last):
  File "C:\Users\Luke\Desktop\test.py", line 24, in <module>
    main(sys.argv[1])
  File "C:\Users\Luke\Desktop\test.py", line 11, in main
    color_dict[cell] = styles.colors.COLOR_INDEX[cell.fill.start_color.index]
TypeError: tuple indices must be integers or slices, not str
</code>```

I'm lost and unsure on why this keeps occurring, any pointers on this one?

Code:

```<code>import sys
from openpyxl import load_workbook, styles

def main(fileName):
    color_dict = {}
    workbook = load_workbook(fileName)
    ltm = workbook.get_sheet_names()[7]
    ws = workbook.get_sheet_by_name(ltm)
    for row in ws.iter_rows("A{}:A{}".format(ws.min_row,ws.max_row)):
        for cell in row:
            color_dict[cell] = styles.colors.COLOR_INDEX[cell.fill.start_color.index]

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Bad Syntax")
    main(sys.argv[1])
</code>```

答: You're getting a type error because cell.fill.start_color.index is a string while styles.colors.COLOR_INDEX() accepts an integer as a parameter. Check the type and contents of  cell.fill.start_color.index and explicitly convert it into int.

Body:
Quick run down; I'm trying to iterate over all cells in column "A" and output the value of the color used in the cell. This works fine when iterating over the first cell, but when it tries again I get the following error;

Traceback (most recent call last):
  File "C:\Users\Luke\Desktop\test.py", line 24, in <module>
    main(sys.argv[1])
  File "C:\Users\Luke\Desktop\test.py", line 11, in main
    color_dict[cell] = styles.colors.COLOR_INDEX[cell.fill.start_color.index]
TypeError: tuple indices must be integers or slices, not str

I'm lost and unsure on why this keeps occurring, any pointers on this one?

Code:

import sys
from openpyxl import load_workbook, styles

def main(fileName):
    color_dict = {}
    workbook = load_workbook(fileName)
    ltm = workbook.get_sheet_names()[7]
    ws = workbook.get_sheet_by_name(ltm)
    for row in ws.iter_rows("A{}:A{}".format(ws.min_row,ws.max_row)):
        for cell in row:
            color_dict[cell] = styles.colors.COLOR_INDEX[cell.fill.start_color.index]

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Bad Syntax")
    main(sys.argv[1])


问:
How can I make Rails ActiveRecord automatically truncate values set to attributes with maximum length?
Assuming that I have a class such as the following:

```<code>class Book < ActiveRecord::Base

  validates :title, :length => {:maximum => 10}

end
</code>```

Is there a way (gem to install?) that I can have ActiveRecord automatically truncate values according to maximum length?

For instance, when I write:

```<code>b = Book.new
b.title = "123456789012345" # this is longer than maximum length of title 10
b.save
</code>```

should save and return true?

If there is not such a way, how would you suggest that I proceed facing such a problem more generally?

答:
This may not have been an option in 2011, but now there's a before_validation callback that will work.

```<code>class Book < ApplicationRecord
  before_validation do
    if self.params && self.params.length > 1000
      self.params = self.title[0...10]
    end
  end

  validate :title, length: { maximum: 10 }, allow_nil: true
end
</code>```

Body:
Assuming that I have a class such as the following:

class Book < ActiveRecord::Base

  validates :title, :length => {:maximum => 10}

end

Is there a way (gem to install?) that I can have ActiveRecord automatically truncate values according to maximum length?

For instance, when I write:

b = Book.new
b.title = "123456789012345" # this is longer than maximum length of title 10
b.save

should save and return true?

If there is not such a way, how would you suggest that I proceed facing such a problem more generally?

Body:
This may not have been an option in 2011, but now there's a before_validation callback that will work.

class Book < ApplicationRecord
  before_validation do
    if self.params && self.params.length > 1000
      self.params = self.title[0...10]
    end
  end

  validate :title, length: { maximum: 10 }, allow_nil: true
end


问:
Excel- Change Cell string Value based on changeable column in another spreadsheet
I need a dynamic way to change a Cell value " for example : Sheet2!A2 "
whenever a cell column in Sheet1 has changed

For example:
Sheet2!A2= is the cell I want to paste the value

Sheet!B:B= is the column that I insert a string on it.

Whenever I add a value in B:B, this value automatically paste on Sheet2!A2. And when I add another value in B:B or update any cell in B:B, the newest added value automatically pasted on Sheet2!A2. and so on.

Please help me, I think I need to use a VB code or something.

Best

答:
You can enter the following formula in the cell Sheet2!A2, you will get what you wanted.

```<code>=IF(IFERROR(FIND("Sheet1!$B",CELL("address"),1),0)=0,"",CELL("contents"))
</code>```

While pasting this formula if you get any warning or error message, Just press enter or click on Ok.

Body:
You can enter the following formula in the cell Sheet2!A2, you will get what you wanted.

=IF(IFERROR(FIND("Sheet1!$B",CELL("address"),1),0)=0,"",CELL("contents"))

While pasting this formula if you get any warning or error message, Just press enter or click on Ok.


问:
Can Scala classes be used in Java
```<code>class Wish{
    val s = "Hello! User.  Wish you a Great day."
}

object Wish{
    def main(args: Array[String]){
        val w = new Wish()
        println("Value - " + w.s )
   }
}
</code>```

Java classes can be used in Scala.  Similarly,  can Scala classes be used in Java?

答:
Yes, Scala classes can be called from Java and vice versa.

The below text is taken from: Scala FAQs

What does it mean that Scala is compatible with Java?

The standard Scala backend is a Java VM. Scala classes are Java classes, and vice versa. You can call the methods of either language from methods in the other one. You can extend Java classes in Scala, and vice versa. The main limitation is that some Scala features do not have equivalents in Java, for example traits.

The following post also could be helpful to you: how to call Scala from Java

Title: Can Scala classes be used in Java

Body:
class Wish{
    val s = "Hello! User.  Wish you a Great day."
}

object Wish{
    def main(args: Array[String]){
        val w = new Wish()
        println("Value - " + w.s )
   }
}

Java classes can be used in Scala.  Similarly,  can Scala classes be used in Java?


问:
How to get get the "shareable link" of a Google Drive file via Google Apps Script?
I thought it would be easy to get the shareable link for a file, like file.getShareableLink() but it seems that things are not so simple.

I've come across similar posts here but nothing that I can understand (alternativeLink and Shareable link for Google Drive file).

Is there really no straightforward way to do this? I've got hundreds of images to extract a shareable link for so they can be displayed online.

答:
How about following sample script? In this sample, it retrieves shared URLs of images in a specific folder.

Sample Script :

```<code>function myFunction() {
  var folderId = "### Specific folder ID ###";
  var files = DriveApp.getFolderById(folderId).getFiles();
  var result = [];
  while (files.hasNext()) {
      var file = files.next();
      file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
      var temp = {
        file_name: file.getName(),
        url: "http://drive.google.com/uc?export=view&id=" + file.getId(),
      };
      result.push(temp);
  };
  Logger.log(JSON.stringify(result))
}
</code>```

Result :

```<code>[
  {
    "file_name": "filename1",
    "url": "http://drive.google.com/uc?export=view&id=### file ID 1###"
  },
  {
    "file_name": "filename2",
    "url": "http://drive.google.com/uc?export=view&id=### file ID 2###"
  }
]
</code>```

Flow :

Retrieve files in a folder which was set by folderId.

Modify the permission of files. By this, users who don't login can also see the files. Only users who know the URLs can see them.

Retrieve filename and file ID. And Retrieve file URLs using file ID. The URLs are the direct links for images.

In this sample, folders in the folder cannot be checked. If you also want to check folders in the folder which was set by folderId, please tell me.

If I misunderstand your question, I'm sorry.

Body:
How about following sample script? In this sample, it retrieves shared URLs of images in a specific folder.

Sample Script :

function myFunction() {
  var folderId = "### Specific folder ID ###";
  var files = DriveApp.getFolderById(folderId).getFiles();
  var result = [];
  while (files.hasNext()) {
      var file = files.next();
      file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
      var temp = {
        file_name: file.getName(),
        url: "http://drive.google.com/uc?export=view&id=" + file.getId(),
      };
      result.push(temp);
  };
  Logger.log(JSON.stringify(result))
}

Result :

[
  {
    "file_name": "filename1",
    "url": "http://drive.google.com/uc?export=view&id=### file ID 1###"
  },
  {
    "file_name": "filename2",
    "url": "http://drive.google.com/uc?export=view&id=### file ID 2###"
  }
]

Flow :

Retrieve files in a folder which was set by folderId.

Modify the permission of files. By this, users who don't login can also see the files. Only users who know the URLs can see them.

Retrieve filename and file ID. And Retrieve file URLs using file ID. The URLs are the direct links for images.

In this sample, folders in the folder cannot be checked. If you also want to check folders in the folder which was set by folderId, please tell me.

If I misunderstand your question, I'm sorry.


问:
Open Contact information in Contact List using Phone Number of Contact Android Studio
I am making a little app that has to do with phone numbers.

My question is I have a phone number that is in my Contact List in my phone.
Example: 0877777777

I would like to open that Contacts information using that phone number.

Just to clarify the when I say contact list I mean the Contacts saved on my Phone.

If anyone could help me out I would appreciate it.

答:
The PhoneLookup api is meant just for this.

```<code>String number = "0877777777";
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] projection = new String[]{ PhoneLookup._ID, PhoneLookup.DISPLAY_NAME };

Cursor cur = getContentresolver().query(uri, projection, null, null, null);

if (cur != null) {
   while (cur.moveToNext()) {
      Long id = cur.getLong(0);
      String name = cur.getString(1);
      Log.d("My Contacts", "found: " + id + " - " + name);
   }
   cur.close();
}
</code>```

UPDATE

To open the contact's profile in the stock contacts app, you need to first get the contact's CONTACT_ID, and then use it in an Intent to the external app:

```<code>String number = "0877777777";
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] projection = new String[]{ PhoneLookup._ID };

Cursor cur = getContentresolver().query(uri, projection, null, null, null);

// if other contacts have that phone as well, we simply take the first contact found.
if (cur != null && cur.moveToNext()) {
    Long id = cur.getLong(0);

    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, String.valueOf(id));
    intent.setData(contactUri);
    context.startActivity(intent);

    cur.close();
}
</code>```

Body:
The PhoneLookup api is meant just for this.

String number = "0877777777";
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] projection = new String[]{ PhoneLookup._ID, PhoneLookup.DISPLAY_NAME };

Cursor cur = getContentresolver().query(uri, projection, null, null, null);

if (cur != null) {
   while (cur.moveToNext()) {
      Long id = cur.getLong(0);
      String name = cur.getString(1);
      Log.d("My Contacts", "found: " + id + " - " + name);
   }
   cur.close();
}

UPDATE

To open the contact's profile in the stock contacts app, you need to first get the contact's CONTACT_ID, and then use it in an Intent to the external app:

String number = "0877777777";
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] projection = new String[]{ PhoneLookup._ID };

Cursor cur = getContentresolver().query(uri, projection, null, null, null);

// if other contacts have that phone as well, we simply take the first contact found.
if (cur != null && cur.moveToNext()) {
    Long id = cur.getLong(0);

    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, String.valueOf(id));
    intent.setData(contactUri);
    context.startActivity(intent);

    cur.close();
}


答:
You certainly can use a base class member in the ctor-initializer list:

```<code>struct Base
{
    int x;
    Base(int x) : x(x) {}
};

struct Derived
{
    int y;
    Derived() : Base(7), y(x) {}
}
</code>```

Here, the base member x appears in the initializer for the derived member y; its value will be used.

AnT has done a very nice job explaining why the ctor-initializer list can't be used to (re-)initialize members of base subobjects.

Title: Why C++ doesn't allow derived class to use base class member in initialization list?

Body:
You certainly can use a base class member in the ctor-initializer list:

struct Base
{
    int x;
    Base(int x) : x(x) {}
};

struct Derived
{
    int y;
    Derived() : Base(7), y(x) {}
}

Here, the base member x appears in the initializer for the derived member y; its value will be used.

AnT has done a very nice job explaining why the ctor-initializer list can't be used to (re-)initialize members of base subobjects.