问:
How can I get reports from Google Cloud Storage using the Google's API
I have to create a program that get informations on a daily basis about installations of a group of apps on the AppStore and the PlayStore.

For the PlayStore, using Google Cloud Storage I followed the instructions on this page using the client library and a Service Account method and the Python code example :
https://support.google.com/googleplay/android-developer/answer/6135870?hl=en&ref_topic=7071935

I slightly changed the given code to make it work since documentation looks not up-to-date. I made it possible to connect to the API and it seems to connect correctly.

My problem is that I don't understand what object I get and how to use it. It's not a report it just looks like files properties in a dict.

This is my code (private data "hidden") :

```<code>import json
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build

client_email = '************.iam.gserviceaccount.com'
json_file = 'PATH/TO/MY/JSON/FILE'
cloud_storage_bucket = 'pubsite_prod_rev_**********'
report_to_download = 'stats/installs/installs_****************_202005_app_version.csv'
private_key = json.loads(open(json_file).read())['private_key']

credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file, scopes='https://www.googleapis.com/auth/devstorage.read_only')

storage = build('storage', 'v1', http=credentials.authorize(Http()))

supposed_to_be_report = storage.objects().get(bucket=cloud_storage_bucket, object=report_to_download).execute()
</code>```

When I print the supposed_to_be_report - which is a dictionary-  I only get what I understand as Metadata about he report like this:

```<code>{'kind': 'storage#object', 'id': 'pubsite_prod_rev_***********/stats/installs/installs_****************_202005_app_version.csv/1591077412052716',
'selfLink': 'https://www.googleapis.com/storage/v1/b/pubsite_prod_rev_***********/o/stats%2Finstalls%2Finstalls_*************_202005_app_version.csv',
'mediaLink': 'https://storage.googleapis.com/download/storage/v1/b/pubsite_prod_rev_***********/o/stats%2Finstalls%2Finstalls_****************_202005_app_version.csv?generation=1591077412052716&alt=media',
'name': 'stats/installs/installs_***********_202005_app_version.csv',
'bucket': 'pubsite_prod_rev_***********',
'generation': '1591077412052716',
'metageneration': '1',
'contentType': 'text/csv;
charset=utf-16le', 'storageClass': 'STANDARD', 'size': '378', 'md5Hash': '*****==', 'contentEncoding': 'gzip'......
</code>```

I am not sure I'm using it correctly. Could you please explain me where am I wrong and/or how to get installs reports correctly ?
Thanks.

答:
I can see that you are using googleapiclient.discovery client, this is not an issue, but the recommended way to access Google Cloud APIs programmatically is by using the client libraries.

Second, you are just retrieving the object's metadata. You can download the object to have access to the file contents, this is a sample using the client library.

```<code>from google.cloud import storage

def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    # bucket_name = "your-bucket-name"
    # source_blob_name = "storage-object-name"
    # destination_file_name = "local/path/to/file"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print(
        "Blob {} downloaded to {}.".format(
            source_blob_name, destination_file_name
        )
    )
</code>```

Sample taken from official docs.

Body:
I have to create a program that get informations on a daily basis about installations of a group of apps on the AppStore and the PlayStore.

For the PlayStore, using Google Cloud Storage I followed the instructions on this page using the client library and a Service Account method and the Python code example :
https://support.google.com/googleplay/android-developer/answer/6135870?hl=en&ref_topic=7071935

I slightly changed the given code to make it work since documentation looks not up-to-date. I made it possible to connect to the API and it seems to connect correctly.

My problem is that I don't understand what object I get and how to use it. It's not a report it just looks like files properties in a dict.

This is my code (private data "hidden") :

import json
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build

client_email = '************.iam.gserviceaccount.com'
json_file = 'PATH/TO/MY/JSON/FILE'
cloud_storage_bucket = 'pubsite_prod_rev_**********'
report_to_download = 'stats/installs/installs_****************_202005_app_version.csv'
private_key = json.loads(open(json_file).read())['private_key']

credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file, scopes='https://www.googleapis.com/auth/devstorage.read_only')

storage = build('storage', 'v1', http=credentials.authorize(Http()))

supposed_to_be_report = storage.objects().get(bucket=cloud_storage_bucket, object=report_to_download).execute()

When I print the supposed_to_be_report - which is a dictionary-  I only get what I understand as Metadata about he report like this:

{'kind': 'storage#object', 'id': 'pubsite_prod_rev_***********/stats/installs/installs_****************_202005_app_version.csv/1591077412052716',
'selfLink': 'https://www.googleapis.com/storage/v1/b/pubsite_prod_rev_***********/o/stats%2Finstalls%2Finstalls_*************_202005_app_version.csv',
'mediaLink': 'https://storage.googleapis.com/download/storage/v1/b/pubsite_prod_rev_***********/o/stats%2Finstalls%2Finstalls_****************_202005_app_version.csv?generation=1591077412052716&alt=media',
'name': 'stats/installs/installs_***********_202005_app_version.csv',
'bucket': 'pubsite_prod_rev_***********',
'generation': '1591077412052716',
'metageneration': '1',
'contentType': 'text/csv;
charset=utf-16le', 'storageClass': 'STANDARD', 'size': '378', 'md5Hash': '*****==', 'contentEncoding': 'gzip'......

I am not sure I'm using it correctly. Could you please explain me where am I wrong and/or how to get installs reports correctly ?
Thanks.

Body:
I can see that you are using googleapiclient.discovery client, this is not an issue, but the recommended way to access Google Cloud APIs programmatically is by using the client libraries.

Second, you are just retrieving the object's metadata. You can download the object to have access to the file contents, this is a sample using the client library.

from google.cloud import storage

def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    # bucket_name = "your-bucket-name"
    # source_blob_name = "storage-object-name"
    # destination_file_name = "local/path/to/file"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print(
        "Blob {} downloaded to {}.".format(
            source_blob_name, destination_file_name
        )
    )

Sample taken from official docs.


来源: stackexchange

问:
Why is semicolon allowed in this Python snippet?
Python does not warrant the use of semicolons to end statements.

So why is this (below) allowed?

```<code>import pdb; pdb.set_trace()
</code>```

答:
Related to the Matplotlib library:

```<code>import numpy as np
import matplotlib as plt

%matplotlib notebook
linear_data = np.array([1, 2, 3, 4, 5, 6, 7, 8])
quadratic_data = linear_data**2
plt.figure()
xvals = range(len(linear_data))
plt.barh(xvals, linear_data, height = 0.3, color='b')
plt.barh(xvals, quadratic_data, height = 0.3, left=linear_data, color='r')
</code>```

If you don't provide a semicolon at the end of the barh (horizontal bar), the output is a plot + a function address.
But if you use semicolons at the end of both barh lines, then it only shows the plot and suppresses the output for the function address.

Something like this:
Comparison

ContentLicense: CC BY-SA 4.0

Body:
Python does not warrant the use of semicolons to end statements.

So why is this (below) allowed?

import pdb; pdb.set_trace()

Body:
Related to the Matplotlib library:

import numpy as np
import matplotlib as plt

%matplotlib notebook
linear_data = np.array([1, 2, 3, 4, 5, 6, 7, 8])
quadratic_data = linear_data**2
plt.figure()
xvals = range(len(linear_data))
plt.barh(xvals, linear_data, height = 0.3, color='b')
plt.barh(xvals, quadratic_data, height = 0.3, left=linear_data, color='r')

If you don't provide a semicolon at the end of the barh (horizontal bar), the output is a plot + a function address.
But if you use semicolons at the end of both barh lines, then it only shows the plot and suppresses the output for the function address.

Something like this:
Comparison


问:
Cannot remove bootstrap button border
I have a custom bootstrap button and I cannot remove its border after click. I was able to change its background color but there is an insistent blue border boring me.

I click on it, it opens a modal window and after closing the modal the border is still there until I click on another part of the page even if I change values in :active and :focus.

html:

```<code><button id="openPopup" type="button" class="btn btn-primary btn-lg text-uppercase" data-toggle="modal" data-target="#myModal">
    some text here
</button>
</code>```

css:

```<code>#openPopup {
  padding: 20px 30px;
  background-color: #a2238e;
  border-color: #a2238e;
  box-shadow: 1px 1px 1px #999;
  white-space: normal;
  font-size: smaller;
  letter-spacing: 0.2px;
}

#openPopup:hover, #openPopup:active, #openPopup:focus {
  background-color: #912284 !important;
  border-color: #912284 !important;
}
</code>```

答:
Try This

```<code><button type="button" class="btn btn-link">Link</button>
</code>```

Bootstrap

ContentLicense: CC BY-SA 3.0

Title: Cannot remove bootstrap button border

Body:
I have a custom bootstrap button and I cannot remove its border after click. I was able to change its background color but there is an insistent blue border boring me.

I click on it, it opens a modal window and after closing the modal the border is still there until I click on another part of the page even if I change values in :active and :focus.

html:

<button id="openPopup" type="button" class="btn btn-primary btn-lg text-uppercase" data-toggle="modal" data-target="#myModal">
    some text here
</button>

css:

#openPopup {
  padding: 20px 30px;
  background-color: #a2238e;
  border-color: #a2238e;
  box-shadow: 1px 1px 1px #999;
  white-space: normal;
  font-size: smaller;
  letter-spacing: 0.2px;
}

#openPopup:hover, #openPopup:active, #openPopup:focus {
  background-color: #912284 !important;
  border-color: #912284 !important;
}

Body:
Try This

<button type="button" class="btn btn-link">Link</button>

Bootstrap


问:
Shouldn't this fail without the use of locking? Simple producer consumer
I have a queue, a list with producer threads and a list with consumer threads.

My code looks like this

```<code>    public class Runner
{
    List<Thread> Producers;
    List<Thread> Consumers;
    Queue<int> queue;
    Random random;

    public Runner()
    {
        Producers = new List<Thread>();
        Consumers = new List<Thread>();

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Produce);
            Producers.Add(thread);
        }

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Consume);
            Consumers.Add(thread);
        }

        queue = new Queue<int>();
        random = new Random();

        Producers.ForEach(( thread ) => { thread.Start(); });
        Consumers.ForEach(( thread ) => { thread.Start(); });
    }

    protected void Produce()
    {
        while (true)
        {
                int number = random.Next(0, 99);
                queue.Enqueue(number);
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Produce: " + number);
        }
    }

    protected void Consume()
    {
        while (true)
        {
                if (queue.Any())
                {
                    int number = queue.Dequeue();
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Consume: " + number);
                }
                else
                {
                    Console.WriteLine("No items to consume");
                }
        }
    }
}
</code>```

Shouldn't this fail miserable cause of the missing use of the lock keyword?
It failed once because it tried to dequeue when the queue was empty, using the lock keyword will fix that right?

If the lock keyword is not needed for the above code, when is it needed then?

Thank you in advance! =)

答:
Yep, you would definitely to synchronize access to the Queue to make it thread-safe. But, you have another problem. There is no mechanism which keeps the consumers from spinning wildly around the loop. Synchronizing access to the Queue or using ConcurrentQueue will not fix that problem.

The simplest way to implement the producer-consumer pattern is to use a blocking queue. Fortunately, .NET 4.0 provides the BlockingCollection which is, despite the name, an implementation of a blocking queue.

```<code>public class Runner
{
    private BlockingCollection<int> queue = new BlockingCollection<int>();
    private Random random = new Random();

    public Runner()
    {
        for (int i = 0; i < 2; i++)
        {
            var thread = new Thread(Produce);
            thread.Start();
        }

        for (int i = 0; i < 2; i++)
        {
            var thread = new Thread(Consume);
            thread.Start();
        }
    }

    protected void Produce()
    {
        while (true)
        {
            int number = random.Next(0, 99);
            queue.Add(number);
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Produce: " + number);
        }
    }

    protected void Consume()
    {
        while (true)
        {
            int number = queue.Take();
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Consume: " + number);
        }
    }
}
</code>```

Body:
I have a queue, a list with producer threads and a list with consumer threads.

My code looks like this

    public class Runner
{
    List<Thread> Producers;
    List<Thread> Consumers;
    Queue<int> queue;
    Random random;

    public Runner()
    {
        Producers = new List<Thread>();
        Consumers = new List<Thread>();

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Produce);
            Producers.Add(thread);
        }

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Consume);
            Consumers.Add(thread);
        }

        queue = new Queue<int>();
        random = new Random();

        Producers.ForEach(( thread ) => { thread.Start(); });
        Consumers.ForEach(( thread ) => { thread.Start(); });
    }

    protected void Produce()
    {
        while (true)
        {
                int number = random.Next(0, 99);
                queue.Enqueue(number);
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Produce: " + number);
        }
    }

    protected void Consume()
    {
        while (true)
        {
                if (queue.Any())
                {
                    int number = queue.Dequeue();
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Consume: " + number);
                }
                else
                {
                    Console.WriteLine("No items to consume");
                }
        }
    }
}

Shouldn't this fail miserable cause of the missing use of the lock keyword?
It failed once because it tried to dequeue when the queue was empty, using the lock keyword will fix that right?

If the lock keyword is not needed for the above code, when is it needed then?

Thank you in advance! =)

Body:
Yep, you would definitely to synchronize access to the Queue to make it thread-safe. But, you have another problem. There is no mechanism which keeps the consumers from spinning wildly around the loop. Synchronizing access to the Queue or using ConcurrentQueue will not fix that problem.

The simplest way to implement the producer-consumer pattern is to use a blocking queue. Fortunately, .NET 4.0 provides the BlockingCollection which is, despite the name, an implementation of a blocking queue.

public class Runner
{
    private BlockingCollection<int> queue = new BlockingCollection<int>();
    private Random random = new Random();

    public Runner()
    {
        for (int i = 0; i < 2; i++)
        {
            var thread = new Thread(Produce);
            thread.Start();
        }

        for (int i = 0; i < 2; i++)
        {
            var thread = new Thread(Consume);
            thread.Start();
        }
    }

    protected void Produce()
    {
        while (true)
        {
            int number = random.Next(0, 99);
            queue.Add(number);
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Produce: " + number);
        }
    }

    protected void Consume()
    {
        while (true)
        {
            int number = queue.Take();
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Consume: " + number);
        }
    }
}


问:
Manifest merger failed with multiple errors, see logs (PayUMoney integration)
I am trying to integrate PayUMoney payment gateway in my app. The very first line of the integration documentation says to add -

compile 'com.payumoney.sdkui:plug-n-play:1.0.0'

in my app-level build.gradle file dependecies. But as soon as I do this i encounter an error -

Manifest merger failed with multiple errors, see logs also the line -

implementation 'com.android.support:appcompat-v7:26.1.0'

show the following error -

```<code>All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 26.1.0, 23.2.1. Examples include com.android.support:animated-vector-drawable:26.1.0 and com.android.support:cardview-v7:23.2.1 less... (Ctrl+F1)
There are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion.)
</code>```

Help me resolve this issue.

Below is my build.gradle(Module:app) code -

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

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.learnturtle.payucheck"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    compile 'com.payumoney.sdkui:plug-n-play:1.0.0'
}
</code>```

答:
Use the latest dependency

```<code>compile 'com.payumoney.sdkui:plug-n-play:1.6.0'
</code>```

and change minSdkversion

```<code>minSdkVersion 20
</code>```

and in Manifest add this

```<code>tools:replace="android:allowBackup,android:usesCleartextTraffic"
</code>```

Body:
I am trying to integrate PayUMoney payment gateway in my app. The very first line of the integration documentation says to add -

compile 'com.payumoney.sdkui:plug-n-play:1.0.0'

in my app-level build.gradle file dependecies. But as soon as I do this i encounter an error -

Manifest merger failed with multiple errors, see logs also the line -

implementation 'com.android.support:appcompat-v7:26.1.0'

show the following error -

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 26.1.0, 23.2.1. Examples include com.android.support:animated-vector-drawable:26.1.0 and com.android.support:cardview-v7:23.2.1 less... (Ctrl+F1)
There are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion.)

Help me resolve this issue.

Below is my build.gradle(Module:app) code -

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.learnturtle.payucheck"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    compile 'com.payumoney.sdkui:plug-n-play:1.0.0'
}

Body:
Use the latest dependency

compile 'com.payumoney.sdkui:plug-n-play:1.6.0'

and change minSdkversion

minSdkVersion 20

and in Manifest add this

tools:replace="android:allowBackup,android:usesCleartextTraffic"


问:
Self hosted Build Agent taking too much time to run Job successfully
Our self-hosted build agent fails on publishing the test results to Azure DevOps (MS Cloud, not on-premise) sometimes.

We configured the agent according to the documentation on https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/proxy?view=azure-devops&tabs=windows by passing the proxy settings in the config.cmd.

We have the following task description:

```<code>steps:
- task: PublishTestResults@2
  displayName: 'Publish Test Results **/junit*.xml'
  inputs:
    testResultsFiles: '**/junit*.xml'
    testRunTitle: 'Jest unit tests'
  continueOnError: true
  condition: succeededOrFailed()
  timeoutInMinutes: 2
</code>```

In most cases the build agent takes round about 15minutes to run the "Publish Test Results */junit.xml" job. (Pipeline in Azure DevOps).
Since it sometimes took less time (only 6 seconds) i am thinking that something goes wrong in this task. Really shouldn't take that much time for this task.

Task returns following warning:

##[warning]Failed to upload file junit.xml to Blob Transfer exception with errorcode Unknown, exception message Microsoft.Azure.Storage.DataMovement.TransferException: The transfer failed. ---> Microsoft.Azure.Storage.StorageException: Fehler beim Senden der Anforderung. ---> System.Net.Http.HttpRequestException: Fehler beim Senden der Anforderung. ---> System.Net.WebException: Der Remoteserver hat einen Fehler zurückgegeben: (407) Proxyauthentifizierung erforderlich.

Sorry for the warning message being in German! Can try to get in English if necessary.

Does somebody know where the error/warning comes from? Grateful for any help, and sorry if this issue is not being created in perfection, i promise i will do better next time. I am learning!

For those who suggest using environment variables for the proxy configuration - unfortunately this is not a option.
Thanks in advance!

答:
Problem solved!
The problem was that there were some URLs that needed to be whitelisted. The firewall blocked them before.

Works fine now.

Body:
Our self-hosted build agent fails on publishing the test results to Azure DevOps (MS Cloud, not on-premise) sometimes.

We configured the agent according to the documentation on https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/proxy?view=azure-devops&tabs=windows by passing the proxy settings in the config.cmd.

We have the following task description:

steps:
- task: PublishTestResults@2
  displayName: 'Publish Test Results **/junit*.xml'
  inputs:
    testResultsFiles: '**/junit*.xml'
    testRunTitle: 'Jest unit tests'
  continueOnError: true
  condition: succeededOrFailed()
  timeoutInMinutes: 2

In most cases the build agent takes round about 15minutes to run the "Publish Test Results */junit.xml" job. (Pipeline in Azure DevOps).
Since it sometimes took less time (only 6 seconds) i am thinking that something goes wrong in this task. Really shouldn't take that much time for this task.

Task returns following warning:

##[warning]Failed to upload file junit.xml to Blob Transfer exception with errorcode Unknown, exception message Microsoft.Azure.Storage.DataMovement.TransferException: The transfer failed. ---> Microsoft.Azure.Storage.StorageException: Fehler beim Senden der Anforderung. ---> System.Net.Http.HttpRequestException: Fehler beim Senden der Anforderung. ---> System.Net.WebException: Der Remoteserver hat einen Fehler zurückgegeben: (407) Proxyauthentifizierung erforderlich.

Sorry for the warning message being in German! Can try to get in English if necessary.

Does somebody know where the error/warning comes from? Grateful for any help, and sorry if this issue is not being created in perfection, i promise i will do better next time. I am learning!

For those who suggest using environment variables for the proxy configuration - unfortunately this is not a option.
Thanks in advance!


问:
Angular Unit Testing: Observable variable value not updating in the data service
I have a data service that is used by a component.

For example:

BookService:

```<code>...
private book: Book;
private bookSubject = new BehaviorSubject<Book>(this.book);
bookChanged = this.bookSubject.asObservable();
...
</code>```

BookComponent:

```<code>...
book: Book;
ngOnInit() {
  this.bookService.bookChanged.subscribe(
    (book: Book) => this.book = book;
  )
}
...
</code>```

Spec (test file) for the component:

```<code>describe('BookComponent', () => {
  let component: BookComponent;
  let fixture: ComponentFixture<BookComponent>;
  let bookServiceStub: Partial<BookService>;

  bookServiceStub = {
    bookChanged: of({id: 123, name: 'Book 1'})
  };
  beforeEach(async(() => {
    TestBed
      .configureTestingModule({
        declarations: [BookComponent],
        providers: [
          {provide: BookService, useValue: bookServiceStub},
          ...
        ]
      })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BookComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should change the book with a new one', fakeAsync(() => {
    const newBook = {
      id: 769,
      name: 'Book 2'
    };
    bookServiceStub.bookChanged = of(newBook);
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      fixture.detectChanges();
      expect(component.book.id).toBe(newBook.id); // FAILS (still has old value)
      expect(component.book).toBe(newBook); // FAILS (still has old value)
    });
  }));
});

</code>```

So the tests fail because the "book" variable does not update with the new values.

What am I doing wrong here?

NOTE: I actually wanted to test if the subscriptions in the component are working as expected or not!

REASON: I would like to check-in further tests that when the value in service is updated, does the DOM changes automatically or not

答:
Adding component.ngOnInit(); makes my test run successfully.

```<code>it('should change the book with a new one', fakeAsync(() => {
    const newBook = {
      id: 769,
      name: 'Book 2'
    };
    bookServiceStub.bookChanged = of(newBook);
    component.ngOnInit(); // ADDED HERE
    fixture.detectChanges();
    expect(component.book.id).toBe(newBook.id);
    expect(component.book).toBe(newBook);
  }));
</code>```

Is this a good practice though. or should I create a spy, etc. ?

Body:
I have a data service that is used by a component.

For example:

BookService:

...
private book: Book;
private bookSubject = new BehaviorSubject<Book>(this.book);
bookChanged = this.bookSubject.asObservable();
...

BookComponent:

...
book: Book;
ngOnInit() {
  this.bookService.bookChanged.subscribe(
    (book: Book) => this.book = book;
  )
}
...

Spec (test file) for the component:

describe('BookComponent', () => {
  let component: BookComponent;
  let fixture: ComponentFixture<BookComponent>;
  let bookServiceStub: Partial<BookService>;

  bookServiceStub = {
    bookChanged: of({id: 123, name: 'Book 1'})
  };
  beforeEach(async(() => {
    TestBed
      .configureTestingModule({
        declarations: [BookComponent],
        providers: [
          {provide: BookService, useValue: bookServiceStub},
          ...
        ]
      })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BookComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should change the book with a new one', fakeAsync(() => {
    const newBook = {
      id: 769,
      name: 'Book 2'
    };
    bookServiceStub.bookChanged = of(newBook);
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      fixture.detectChanges();
      expect(component.book.id).toBe(newBook.id); // FAILS (still has old value)
      expect(component.book).toBe(newBook); // FAILS (still has old value)
    });
  }));
});

So the tests fail because the "book" variable does not update with the new values.

What am I doing wrong here?

NOTE: I actually wanted to test if the subscriptions in the component are working as expected or not!

REASON: I would like to check-in further tests that when the value in service is updated, does the DOM changes automatically or not

Body:
Adding component.ngOnInit(); makes my test run successfully.

it('should change the book with a new one', fakeAsync(() => {
    const newBook = {
      id: 769,
      name: 'Book 2'
    };
    bookServiceStub.bookChanged = of(newBook);
    component.ngOnInit(); // ADDED HERE
    fixture.detectChanges();
    expect(component.book.id).toBe(newBook.id);
    expect(component.book).toBe(newBook);
  }));

Is this a good practice though. or should I create a spy, etc. ?


问:
How to mention MYSQLDialect for hibernate 5.4.17 and MySQL 8.0?
I'm using Hibernate 5.4.17 in the hibernate.cfg.xml file. I have the dialect property like this:

<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
```

<p>Is this fine to use or Should I change it to:</p>

<pre class="lang-xml prettyprint-override"><code> <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
</code>```

答:
The version of your hibernate dialect should be as closer as possible to your database version. But should not be higher than database version. So for your case the org.hibernate.dialect.MySQL8Dialect will be the best choice.

See also this section of the hibernate documentation for further details.

Body:
I'm using Hibernate 5.4.17 in the hibernate.cfg.xml file. I have the dialect property like this:

<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

Is this fine to use or Should I change it to:

 <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>


问:
ComboBox SelectedIndexChanged event: how to get the previously selected index?
I have a user control which has a ComboBox and a SelectedIndexChanged event handler.  In the event handler, I need to be able to tell what was the previously selected index... can anyone point me in the right direction?</p>

```<code>private void cboTargetMode_SelectedIndexChanged(object sender, EventArgs e)
{
    // need to get the previously selected index and do some handling here...
    // ... some handler code here ...

    switch (cboTargetMode.SelectedIndex)
    {
        case 1:  // ..... some code here...
            break;
        case 2:  // ..... some code here...
            break;
        case 3:  // ..... some code here...
            break;
        default: // ..... some code here...
            break;
    }
}
</code>```

答: You can grab & store the old value in the DropDown event. Then revert to that old value in the SelectionChangeCommitted event (if warranted).

ContentLicense: CC BY-SA 2.5

Body:
I have a user control which has a ComboBox and a SelectedIndexChanged event handler.  In the event handler, I need to be able to tell what was the previously selected index... can anyone point me in the right direction?

private void cboTargetMode_SelectedIndexChanged(object sender, EventArgs e)
{
    // need to get the previously selected index and do some handling here...
    // ... some handler code here ...

    switch (cboTargetMode.SelectedIndex)
    {
        case 1:  // ..... some code here...
            break;
        case 2:  // ..... some code here...
            break;
        case 3:  // ..... some code here...
            break;
        default: // ..... some code here...
            break;
    }
}


问:
Compilers and argument order of evaluation in C++
Okay, I'm aware that the standard dictates that a C++ implementation may choose in which order arguments of a function are evaluated, but are there any implementations that actually 'take advantage' of this in a scenario where it would actually affect the program?

Classic Example:

```<code>int i = 0;
foo(i++, i++);
</code>```

Note: I'm not looking for someone to tell me that the order of evaluation can't be relied on, I'm well aware of that. I'm only interested in whether any compilers actually do evaluate out of a left-to-right order because my guess would be that if they did lots of poorly written code would break (rightly so, but they would still probably complain).

答:
It depends on the argument type, the called function's calling convention, the archtecture and the compiler. On an x86, the Pascal calling convention evaluates arguments left to right whereas in the C calling convention (__cdecl) it is right to left. Most programs which run on multiple platforms do take into account the calling conventions to skip surprises.

There is a nice article on Raymond Chen' blog if you are interested. You may also want to take a look at the Stack and Calling section of the GCC manual.

Edit: So long as we are splitting hairs: My answer treats this not as a language question but as a platform one. The language standard does not gurantee or prefer one over the other and leaves it as unspecified. Note the wording. It does not say this is undefined. Unspecified in this sense means something you cannot count on, non-portable behavior. I don't have the C spec/draft handy but it should be similar to that from my n2798 draft (C++)

Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, order of evaluation of arguments to a function). Where possible, this International Standard defines a set of allowable behaviors. These define the nondeterministic aspects of the abstract machine. An instance of the abstract machine can thus have more than one possible execution sequence for a given program and a given input.

OwnerDisplayName: Cypherjb

Body:
Okay, I'm aware that the standard dictates that a C++ implementation may choose in which order arguments of a function are evaluated, but are there any implementations that actually 'take advantage' of this in a scenario where it would actually affect the program?

Classic Example:

int i = 0;
foo(i++, i++);

Note: I'm not looking for someone to tell me that the order of evaluation can't be relied on, I'm well aware of that. I'm only interested in whether any compilers actually do evaluate out of a left-to-right order because my guess would be that if they did lots of poorly written code would break (rightly so, but they would still probably complain).

OwnerDisplayName: dirkgently

LastEditorDisplayName: dirkgently


问:
NodeJS: Can't return a result from a function
I'm trying to return the result from this function :

var YouTube = require('youtube-node');
var youTube = new YouTube();

youTube.setKey('XXXXXXXXXXXX');

var result = youTube.search('World War z Trailer', 2,
    function(error, result) {
        if (error) {
            console.log(error);
        } else {
            return result
        }})

console.log(result)
```

But then I only get undefined as a result in console.

答:
You need to wait for the response.

This simple answer is to place the console.log(result) inside the callback.

Or you can wrap the search method in a promise:

var promise = new Promise((resolve, reject) => {
    youTube.search('World War z Trailer', 2, function (error, result) {
        if (error) {
            reject(error);
        }
        else {
            resolve(result);
        }
    })
});
```

<p>Then you can wait for the response using <code>.then()</code> like this:</p>

<pre class="lang-js prettyprint-override"><code>promise.then((result) => {
    console.log(result);
}).catch((err) => {
    console.error(err);
});
</code>```

Or using await/async:

(async () => {
    try {
        const result = await promise;
        console.log(result);
    } catch (err) {
        console.error(err)
    }
})();
```

Body:
I'm trying to return the result from this function :

var YouTube = require('youtube-node');
var youTube = new YouTube();

youTube.setKey('XXXXXXXXXXXX');

var result = youTube.search('World War z Trailer', 2,
    function(error, result) {
        if (error) {
            console.log(error);
        } else {
            return result
        }})

console.log(result)

But then I only get undefined as a result in console.

Body:
You need to wait for the response.

This simple answer is to place the console.log(result) inside the callback.

Or you can wrap the search method in a promise:

var promise = new Promise((resolve, reject) => {
    youTube.search('World War z Trailer', 2, function (error, result) {
        if (error) {
            reject(error);
        }
        else {
            resolve(result);
        }
    })
});

Then you can wait for the response using .then() like this:

promise.then((result) => {
    console.log(result);
}).catch((err) => {
    console.error(err);
});

Or using await/async:

(async () => {
    try {
        const result = await promise;
        console.log(result);
    } catch (err) {
        console.error(err)
    }
})();


问:
Lambda Python - Print Formatting Improvements
I have a lambda

This lambda goes off and reports on anyones access key older than a specific number of days.

import boto3, json, time, datetime, sys

```<code>sns = boto3.client('sns')
usernames = []
mylist = []

sts_client = boto3.client('sts')
assumed_role_object=sts_client.assume_role(
    RoleArn="arn:aws:iam::999999999:role/role",
    RoleSessionName="AssumedRoleSession4"
)
credentials=assumed_role_object['Credentials']
client=boto3.client(
    'iam',
    aws_access_key_id=credentials['AccessKeyId'],
    aws_secret_access_key=credentials['SecretAccessKey'],
    aws_session_token=credentials['SessionToken'],
    )
def lambda_handler(event, context):
    users = client.list_users()
    for key in users['Users']:
        a = str(key['UserName'])
        usernames.append(a)
    for username in usernames:
        try:
            res = client.list_access_keys(UserName=username)
            accesskeydate = res['AccessKeyMetadata'][0]['CreateDate']
            accesskeydate = accesskeydate.strftime("%Y-%m-%d %H:%M:%S")
            currentdate = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
            accesskeyd = time.mktime(datetime.datetime.strptime(accesskeydate, "%Y-%m-%d %H:%M:%S").timetuple())
            currentd = time.mktime(datetime.datetime.strptime(currentdate, "%Y-%m-%d %H:%M:%S").timetuple())
            active_days = (currentd - accesskeyd)/60/60/24 ### We get the data in seconds. converting it to days

            if 90 < active_days:
                a = str(username)
                c = int(int(round(active_days)))

                mylist.append(a)
                mylist.append(c)
        except:
                f = str('')

    print(mylist)
    finallist = ''.join(str(mylist))
    finallist = finallist

    sns_message = (finallist)
    response = sns.publish(
        TopicArn='arn:aws:sns:eu-west-2:111111111:sns',
        Message= sns_message,
        Subject='Access Keys which need rotating',
    )
</code>```

This returns

```<code>['David.Jim', 123, 'Dav.Jimmy', 469, 'David.Jimmy', 480, 'Jim.Dave', 103, 'Dave.Jimmy', 102, 'Jimmy.Dave', 179]
</code>```

And with over 100 users with Access Keys older than 90 days, this becomes very difficult to review.  How can i improve my output?

Thanks
Nick

答:
Why not just format the output in your code?  For example:

```<code>mylist = ""
</code>```

...

```<code>if 90 < active_days:
    a = str(username)
    c = int(int(round(active_days)))

    mylist += "User: " + a
    mylist += ", days: " + str(a)
    mylist += "\n"
</code>```

And then use the string mylist to print and send.  There are other ways of doing this with a format method too but this should get you started.

Body:
I have a lambda

This lambda goes off and reports on anyones access key older than a specific number of days.

import boto3, json, time, datetime, sys

sns = boto3.client('sns')
usernames = []
mylist = []

sts_client = boto3.client('sts')
assumed_role_object=sts_client.assume_role(
    RoleArn="arn:aws:iam::999999999:role/role",
    RoleSessionName="AssumedRoleSession4"
)
credentials=assumed_role_object['Credentials']
client=boto3.client(
    'iam',
    aws_access_key_id=credentials['AccessKeyId'],
    aws_secret_access_key=credentials['SecretAccessKey'],
    aws_session_token=credentials['SessionToken'],
    )
def lambda_handler(event, context):
    users = client.list_users()
    for key in users['Users']:
        a = str(key['UserName'])
        usernames.append(a)
    for username in usernames:
        try:
            res = client.list_access_keys(UserName=username)
            accesskeydate = res['AccessKeyMetadata'][0]['CreateDate']
            accesskeydate = accesskeydate.strftime("%Y-%m-%d %H:%M:%S")
            currentdate = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
            accesskeyd = time.mktime(datetime.datetime.strptime(accesskeydate, "%Y-%m-%d %H:%M:%S").timetuple())
            currentd = time.mktime(datetime.datetime.strptime(currentdate, "%Y-%m-%d %H:%M:%S").timetuple())
            active_days = (currentd - accesskeyd)/60/60/24 ### We get the data in seconds. converting it to days

            if 90 < active_days:
                a = str(username)
                c = int(int(round(active_days)))

                mylist.append(a)
                mylist.append(c)
        except:
                f = str('')

    print(mylist)
    finallist = ''.join(str(mylist))
    finallist = finallist

    sns_message = (finallist)
    response = sns.publish(
        TopicArn='arn:aws:sns:eu-west-2:111111111:sns',
        Message= sns_message,
        Subject='Access Keys which need rotating',
    )

This returns

['David.Jim', 123, 'Dav.Jimmy', 469, 'David.Jimmy', 480, 'Jim.Dave', 103, 'Dave.Jimmy', 102, 'Jimmy.Dave', 179]

And with over 100 users with Access Keys older than 90 days, this becomes very difficult to review.  How can i improve my output?

Thanks
Nick

Body:
Why not just format the output in your code?  For example:

mylist = ""

...

if 90 < active_days:
    a = str(username)
    c = int(int(round(active_days)))

    mylist += "User: " + a
    mylist += ", days: " + str(a)
    mylist += "\n"

And then use the string mylist to print and send.  There are other ways of doing this with a format method too but this should get you started.


问:
How Can I fix a header of a specified height in the top without adding top property to the sibling section to make it visible?
I have a small problem, I am working on a project, in this project everything is separated literally, I am working only on a header section without touching anything else, I can how the header is displayed in all the project after deploying the header only, meaning ? I don't have access to touch the body, only the heeader.

I have to set the Header to fixed, I was doing this before already but they were my personnal projects, I give the header a height and then the section next to it I positionate it relatively and add top property to it so the header and section can be both visible, the header does not have to cover the sectiion or part of it.

let's put some code :

```<code><body>

    <header></header>
    <section class="first_section"></section>
    <section></section>

</body>
</code>```

and the css like that :

```<code>header {  position :fixed; height: 40px; }
section { position : relative; }
.first_section { top: 40px }
</code>```

Now, I can't do that, I can't touch the section or add style to them, why ? because they are very dynamic, the header can be included in multiple sites, that means that it is not proper to touch all sections or cover them one by one.

So to fix this, I tried this in html :

```<code><body>

    <header>
       <div class="header"></div>
    </header>
    <section class="first_section"></section>
    <section></section>

</body>
</code>```

Now, I have passed all the css properties from header to the div with header classname, and header now is like this :

```<code>header {  position :relative; width: 100%; height: 40px; }
.header { position: fixed; // many others properties }
section { position : relative; }
.first_section { top: 40px }
</code>```

But it is not working ? why ? I don't know, but when inspecting the height property in the header, it is not set, the header have width and height properties in css file, but when I Inspect I see that the height is 0, I think because it has a fixed child, but I don't know how to fix it.

Any help would be much appreciated.

答:
I know the answer has already been selected but a simple solution would be using position: sticky like so...

body {
  margin: 0;
  padding: 0;
}
header {
  position: sticky;
  top: 0;
  height: 50px;
  background-color: red;
}
section {
  height: 750px;
  background-color: white;
}
footer {
  height: 50px;
  background-color: green;
}
.someClass {
  padding: 10px;
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header></header>
<section>
 <p class="someClass">
  scroll down..
 </p>
</section>
<footer></footer></code>```

Body:
I have a small problem, I am working on a project, in this project everything is separated literally, I am working only on a header section without touching anything else, I can how the header is displayed in all the project after deploying the header only, meaning ? I don't have access to touch the body, only the heeader.

I have to set the Header to fixed, I was doing this before already but they were my personnal projects, I give the header a height and then the section next to it I positionate it relatively and add top property to it so the header and section can be both visible, the header does not have to cover the sectiion or part of it.

let's put some code :

and the css like that :

header {  position :fixed; height: 40px; }
section { position : relative; }
.first_section { top: 40px }

Now, I can't do that, I can't touch the section or add style to them, why ? because they are very dynamic, the header can be included in multiple sites, that means that it is not proper to touch all sections or cover them one by one.

So to fix this, I tried this in html :

Now, I have passed all the css properties from header to the div with header classname, and header now is like this :

header {  position :relative; width: 100%; height: 40px; }
.header { position: fixed; // many others properties }
section { position : relative; }
.first_section { top: 40px }

But it is not working ? why ? I don't know, but when inspecting the height property in the header, it is not set, the header have width and height properties in css file, but when I Inspect I see that the height is 0, I think because it has a fixed child, but I don't know how to fix it.

Any help would be much appreciated.

Body:
I know the answer has already been selected but a simple solution would be using position: sticky like so...

body {
  margin: 0;
  padding: 0;
}
header {
  position: sticky;
  top: 0;
  height: 50px;
  background-color: red;
}
section {
  height: 750px;
  background-color: white;
}
footer {
  height: 50px;
  background-color: green;
}
.someClass {
  padding: 10px;
  margin: 0;
}

<header></header>
<section>
 <p class="someClass">
  scroll down..
 </p>
</section>
<footer></footer>


问:
how to prevent user to update a post after 24 hours django
i want to prevent the user to update the post after 24 hours from the post date

```<code>class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title= models.CharField(max_length=50)
    post = models.TextField(max_length=400)
    date = models.DateTimeField(auto_now_add=True)
    edit = models.DateTimeField(auto_now=True)

class PostForm(forms.ModelForm):
    class Meta:
       model = Post
       fields = '__all__'

class PostUpdateView(LoginRequiredMixin,SuccessMessageMixin,UpdateView):
    model = Post
    form_class = PostForm
    success_message = "updated successfully"
    template_name = 'store/create.html'
    success_url = reverse_lazy('lists')
    def form_valid(self,form):
        return super().form_valid(form)
</code>```

i want to let the user only be able to update the post before 24 hours during the Post date
thanks

答:
You can filter the queryset such that only the posts that it only contains Posts that are written within the last 24 hours:

```<code>from datetime import timedelta
from django.utils.timezone import now

class PostUpdateView(LoginRequiredMixin,SuccessMessageMixin,UpdateView):
    model = Post
    form_class = PostForm
    success_message = "updated successfully"
    template_name = 'store/create.html'
    success_url = reverse_lazy('lists')

    def <b>get_queryset</b>(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(
            <b>date__gte=now() - timedelta(days=1)</b>
        )

    def form_valid(self,form):
        return super().form_valid(form)</code>```

This will return a HTTP 404 response in case the update period has been "expired".

Body:
i want to prevent the user to update the post after 24 hours from the post date

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title= models.CharField(max_length=50)
    post = models.TextField(max_length=400)
    date = models.DateTimeField(auto_now_add=True)
    edit = models.DateTimeField(auto_now=True)

class PostForm(forms.ModelForm):
    class Meta:
       model = Post
       fields = '__all__'

class PostUpdateView(LoginRequiredMixin,SuccessMessageMixin,UpdateView):
    model = Post
    form_class = PostForm
    success_message = "updated successfully"
    template_name = 'store/create.html'
    success_url = reverse_lazy('lists')
    def form_valid(self,form):
        return super().form_valid(form)

i want to let the user only be able to update the post before 24 hours during the Post date
thanks

Body:
You can filter the queryset such that only the posts that it only contains Posts that are written within the last 24 hours:

from datetime import timedelta
from django.utils.timezone import now

class PostUpdateView(LoginRequiredMixin,SuccessMessageMixin,UpdateView):
    model = Post
    form_class = PostForm
    success_message = "updated successfully"
    template_name = 'store/create.html'
    success_url = reverse_lazy('lists')

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(
            date__gte=now() - timedelta(days=1)
        )

    def form_valid(self,form):
        return super().form_valid(form)

This will return a HTTP 404 response in case the update period has been "expired".


问:
md5 a string multiple times
md5 a string multiple times in Python:

```<code>def md5(i):
    return hashlib.md5(i).hexdigest().upper()

def md5x3(src):
    f = hashlib.md5(src).digest()
    s = hashlib.md5(f).digest()
    t = md5(s)
    return t
</code>```

how to implement above in C with OpenSSL on MacOS/iOS or in Objective-C without OpenSSL on MacOS/iOS ?

I'm try following, but its result is different from python's.

```<code>#import <Foundation/Foundation.h>

#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

static char* hextostr(const unsigned char* in , int len)
{
    char* res = (char*)malloc(len * 2 + 1);
    int i = 0;
    memset(res , 0 , len * 2 + 1);
    while(i < len)
    {
        sprintf(res + i * 2 , "%02x" , in[i]);
        i ++;
    };
//  i = 0;
//  int reslength;
//  reslength=(int)strlen(res);
//  while(i < reslength)
//  {
//      res[i] = toupper(res[i]);
//      i ++;
//  };
    return res;
}

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString * foo = @"abcdefghij";

    NSData * buf1 = [foo dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result1[CC_MD5_DIGEST_LENGTH];
    CC_MD5([buf1 bytes], (unsigned int)[buf1 length], result1);

    NSData * buf2 = [[[NSString alloc] initWithFormat:@"%s", result1] dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result2[CC_MD5_DIGEST_LENGTH];
    CC_MD5(result1, (unsigned int)strlen(result1), result2);

    NSData * buf3 = [[[NSString alloc] initWithFormat:@"%s", result2] dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result3[CC_MD5_DIGEST_LENGTH];
    CC_MD5(result2, (unsigned int)strlen(result2), result3);

    NSString * res = [[NSString alloc] initWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result3[0], result3[1], result3[2], result3[3], result3[4], result3[5], result3[6], result3[7],
            result3[8], result3[9], result3[10], result3[11], result3[12], result3[13], result3[14], result3[15]
            ];

    NSLog(@"%s", hextostr(result1, CC_MD5_DIGEST_LENGTH));
    NSLog(@"%s", hextostr(result2, CC_MD5_DIGEST_LENGTH));
    NSLog(@"%s", hextostr(result3, CC_MD5_DIGEST_LENGTH));

    [pool drain];
    return 0;
}
</code>```

答: Use  a digest library, such as OpenSSL, which you probably have installed already. See http://www.openssl.org/docs/crypto/md5.html. Source code for MD5 is available at http://userpages.umbc.edu/~mabzug1/cs/md5/md5.html.</p>

OwnerDisplayName: shuge

LastEditorDisplayName: shuge

Title: md5 a string multiple times

Body:
md5 a string multiple times in Python:

def md5(i):
    return hashlib.md5(i).hexdigest().upper()

def md5x3(src):
    f = hashlib.md5(src).digest()
    s = hashlib.md5(f).digest()
    t = md5(s)
    return t

how to implement above in C with OpenSSL on MacOS/iOS or in Objective-C without OpenSSL on MacOS/iOS ?

I'm try following, but its result is different from python's.

#import <Foundation/Foundation.h>

#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

static char* hextostr(const unsigned char* in , int len)
{
    char* res = (char*)malloc(len * 2 + 1);
    int i = 0;
    memset(res , 0 , len * 2 + 1);
    while(i < len)
    {
        sprintf(res + i * 2 , "%02x" , in[i]);
        i ++;
    };
//  i = 0;
//  int reslength;
//  reslength=(int)strlen(res);
//  while(i < reslength)
//  {
//      res[i] = toupper(res[i]);
//      i ++;
//  };
    return res;
}

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString * foo = @"abcdefghij";

    NSData * buf1 = [foo dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result1[CC_MD5_DIGEST_LENGTH];
    CC_MD5([buf1 bytes], (unsigned int)[buf1 length], result1);

    NSData * buf2 = [[[NSString alloc] initWithFormat:@"%s", result1] dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result2[CC_MD5_DIGEST_LENGTH];
    CC_MD5(result1, (unsigned int)strlen(result1), result2);

    NSData * buf3 = [[[NSString alloc] initWithFormat:@"%s", result2] dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result3[CC_MD5_DIGEST_LENGTH];
    CC_MD5(result2, (unsigned int)strlen(result2), result3);

    NSString * res = [[NSString alloc] initWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result3[0], result3[1], result3[2], result3[3], result3[4], result3[5], result3[6], result3[7],
            result3[8], result3[9], result3[10], result3[11], result3[12], result3[13], result3[14], result3[15]
            ];

    NSLog(@"%s", hextostr(result1, CC_MD5_DIGEST_LENGTH));
    NSLog(@"%s", hextostr(result2, CC_MD5_DIGEST_LENGTH));
    NSLog(@"%s", hextostr(result3, CC_MD5_DIGEST_LENGTH));

    [pool drain];
    return 0;
}


问:
How can I create and load a second database in ddev?
I have a Drupal multisite that needs to have one database for each site, and want it to run in ddev, but ddev just has the one database by default, named 'db'. How can I get a second database?</p>

答:
In addition to rfay answer, The trick used in the last link was exactly what I wanted to propose and what I'm currently using:

Add this hook to the config.yml file

```<code>hooks:
  post-start:
  - exec: mysql -uroot -proot -hdb -e "CREATE DATABASE IF NOT EXISTS second_db; GRANT
      ALL ON second_db.* TO 'db'@'%';"
</code>```

And load data to the second database by using the param --target-db:

ddev import-db --target-db=second-db --src=second-db.sql

Body:
In addition to rfay answer, The trick used in the last link was exactly what I wanted to propose and what I'm currently using:

Add this hook to the config.yml file

hooks:
  post-start:
  - exec: mysql -uroot -proot -hdb -e "CREATE DATABASE IF NOT EXISTS second_db; GRANT
      ALL ON second_db.* TO 'db'@'%';"

And load data to the second database by using the param --target-db:

ddev import-db --target-db=second-db --src=second-db.sql


问:
Extracting a value from an XML column in SQL Server
I am trying to extract the data values present in the FirstName and LastName from the below XML which is present as a string in a column in a SQL Server table.

```<code><ns6:Account xmlns="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel" xmlns:ns2="http://example.com/pc/gx/abc.pc.dm.gx.shared.location.addressmodel" xmlns:ns4="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.officialidmodel" xmlns:ns3="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactaddressmodel" xmlns:ns6="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns5="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.accountcontactmodel" xmlns:ns8="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.usermodel" xmlns:ns7="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.historymodel" xmlns:ns13="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns9="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.activitymodel" xmlns:ns12="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.industrycodemodel" xmlns:ns11="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.documentmodel" xmlns:ns10="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.groupmodel" xmlns:ns17="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.producercodemodel" xmlns:ns16="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.accountproducercodemodel" xmlns:ns15="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.notemodel" xmlns:ns14="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc">
    <ns6:AccountHolderContact>
        <entity-Person>
            <DateOfBirth>999-01-02T12:00:00-05:00</DateOfBirth>
            <FirstName>ABC</FirstName>
            <Gender>F</Gender>
            <LastName>ABC</LastName>
            <LicenseNumber>9999-9999-9999</LicenseNumber>
            <LicenseState>AA</LicenseState>
            <MaritalStatus>S</MaritalStatus>
            <OrganizationType_IC>individual</OrganizationType_IC>
        </entity-Person>
        <HomePhone>9999999999</HomePhone>
        <PrimaryAddress>
            <ns2:AddressLine1>99 ABC St</ns2:AddressLine1>
            <ns2:AddressType>home</ns2:AddressType>
            <ns2:City>AAA</ns2:City>
            <ns2:Country>AA</ns2:Country>
            <ns2:PostalCode>ABC MMM</ns2:PostalCode>
            <ns2:State>AA</ns2:State>
            <ns2:Subtype>Address</ns2:Subtype>
        </PrimaryAddress>
        <PublicID>1</PublicID>
        <Subtype>person</Subtype>
    </ns6:AccountHolderContact>
</ns6:Account>
</code>```

This is the query I tried:

```<code>select
    application_id, accountID,
    cast(payload as xml).value('(//*:Account//*:AccountHolderContact)[1]', 'varchar(max)') as FirstName
from
    [test1].[dbo].[test2]
</code>```

This query returns the data in all the sub-nodes from the XML node <AccountHolderContact>.

```<code>999-01-02T12:00:00-05:00ABCFABC9999-9999-9999AASIndividual999999999999 ABC SthomeAAAAAABC MMMAAAddress1Person
</code>```

When I change my query to the below, I get no data in my output column FirstName:

```<code>select
    application_id, accountID,
    cast(payload as xml).value('(//*:Account//*:AccountHolderContact/entity-Person/FirstName)[1]','varchar(max)') as FirstName
from
    [test1].[dbo].[test2]
</code>```

Is there a reason why I cannot extract from the sub-nodes of AccountHolderContact? If not, what is the easiest way to do this?

答:
Your XML has multiple namespaces - 17 total. Just two of them should be taken into account. It is better not to use namespace wildcards due to performance reasons.

Here is how to shred your XML and retrieve what you need.

SQL

```<code>-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, payload NVARCHAR(MAX));
INSERT INTO @tbl (payload) VALUES
(N'<?xml version="1.0"?>
<ns6:Account xmlns="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel"
             xmlns:ns2="http://example.com/pc/gx/abc.pc.dm.gx.shared.location.addressmodel"
             xmlns:ns4="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.officialidmodel"
             xmlns:ns3="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactaddressmodel"
             xmlns:ns6="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc"
             xmlns:ns5="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.accountcontactmodel"
             xmlns:ns8="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.usermodel"
             xmlns:ns7="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.historymodel"
             xmlns:ns13="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc"
             xmlns:ns9="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.activitymodel"
             xmlns:ns12="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.industrycodemodel"
             xmlns:ns11="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.documentmodel"
             xmlns:ns10="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.groupmodel"
             xmlns:ns17="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.producercodemodel"
             xmlns:ns16="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.accountproducercodemodel"
             xmlns:ns15="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.notemodel"
             xmlns:ns14="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc">
    <ns6:AccountHolderContact>
        <entity-Person>
            <DateOfBirth>999-01-02T12:00:00-05:00</DateOfBirth>
            <FirstName>ABC</FirstName>
            <Gender>F</Gender>
            <LastName>ABC</LastName>
            <LicenseNumber>9999-9999-9999</LicenseNumber>
            <LicenseState>AA</LicenseState>
            <MaritalStatus>S</MaritalStatus>
            <OrganizationType_IC>individual</OrganizationType_IC>
        </entity-Person>
        <HomePhone>9999999999</HomePhone>
        <PrimaryAddress>
            <ns2:AddressLine1>99 ABC St</ns2:AddressLine1>
            <ns2:AddressType>home</ns2:AddressType>
            <ns2:City>AAA</ns2:City>
            <ns2:Country>AA</ns2:Country>
            <ns2:PostalCode>ABC MMM</ns2:PostalCode>
            <ns2:State>AA</ns2:State>
            <ns2:Subtype>Address</ns2:Subtype>
        </PrimaryAddress>
        <PublicID>1</PublicID>
        <Subtype>person</Subtype>
    </ns6:AccountHolderContact>
</ns6:Account>');
-- DDL and sample data population, end

;WITH XMLNAMESPACES (DEFAULT 'http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel'
    , 'http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc' AS ns14) ,rs AS
(
   SELECT id, TRY_CAST(payload AS XML) AS xmldata
   FROM @tbl
)
SELECT ID
   , c.value('(FirstName/text())[1]','VARCHAR(50)') AS FirstName
   , c.value('(LastName/text())[1]','VARCHAR(50)') AS LastName
FROM rs CROSS APPLY rs.xmldata.nodes('/ns14:Account/ns14:AccountHolderContact/entity-Person') AS t(c);
</code>```

Output

```<code>+----+-----------+----------+
| ID | FirstName | LastName |
+----+-----------+----------+
|  1 | ABC       | ABC      |
+----+-----------+----------+
</code>```

Body:
I am trying to extract the data values present in the FirstName and LastName from the below XML which is present as a string in a column in a SQL Server table.

<ns6:Account xmlns="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel" xmlns:ns2="http://example.com/pc/gx/abc.pc.dm.gx.shared.location.addressmodel" xmlns:ns4="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.officialidmodel" xmlns:ns3="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactaddressmodel" xmlns:ns6="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns5="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.accountcontactmodel" xmlns:ns8="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.usermodel" xmlns:ns7="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.historymodel" xmlns:ns13="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns9="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.activitymodel" xmlns:ns12="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.industrycodemodel" xmlns:ns11="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.documentmodel" xmlns:ns10="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.groupmodel" xmlns:ns17="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.producercodemodel" xmlns:ns16="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.accountproducercodemodel" xmlns:ns15="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.notemodel" xmlns:ns14="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc">
    <ns6:AccountHolderContact>
        <entity-Person>
            <DateOfBirth>999-01-02T12:00:00-05:00</DateOfBirth>
            <FirstName>ABC</FirstName>
            <Gender>F</Gender>
            <LastName>ABC</LastName>
            <LicenseNumber>9999-9999-9999</LicenseNumber>
            <LicenseState>AA</LicenseState>
            <MaritalStatus>S</MaritalStatus>
            <OrganizationType_IC>individual</OrganizationType_IC>
        </entity-Person>
        <HomePhone>9999999999</HomePhone>
        <PrimaryAddress>
            <ns2:AddressLine1>99 ABC St</ns2:AddressLine1>
            <ns2:AddressType>home</ns2:AddressType>
            <ns2:City>AAA</ns2:City>
            <ns2:Country>AA</ns2:Country>
            <ns2:PostalCode>ABC MMM</ns2:PostalCode>
            <ns2:State>AA</ns2:State>
            <ns2:Subtype>Address</ns2:Subtype>
        </PrimaryAddress>
        <PublicID>1</PublicID>
        <Subtype>person</Subtype>
    </ns6:AccountHolderContact>
</ns6:Account>

This is the query I tried:

select
    application_id, accountID,
    cast(payload as xml).value('(//*:Account//*:AccountHolderContact)[1]', 'varchar(max)') as FirstName
from
    [test1].[dbo].[test2]

This query returns the data in all the sub-nodes from the XML node <AccountHolderContact>.

999-01-02T12:00:00-05:00ABCFABC9999-9999-9999AASIndividual999999999999 ABC SthomeAAAAAABC MMMAAAddress1Person

When I change my query to the below, I get no data in my output column FirstName:

select
    application_id, accountID,
    cast(payload as xml).value('(//*:Account//*:AccountHolderContact/entity-Person/FirstName)[1]','varchar(max)') as FirstName
from
    [test1].[dbo].[test2]

Is there a reason why I cannot extract from the sub-nodes of AccountHolderContact? If not, what is the easiest way to do this?

Body:
Your XML has multiple namespaces - 17 total. Just two of them should be taken into account. It is better not to use namespace wildcards due to performance reasons.

Here is how to shred your XML and retrieve what you need.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, payload NVARCHAR(MAX));
INSERT INTO @tbl (payload) VALUES
(N'<?xml version="1.0"?>
<ns6:Account xmlns="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel"
             xmlns:ns2="http://example.com/pc/gx/abc.pc.dm.gx.shared.location.addressmodel"
             xmlns:ns4="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.officialidmodel"
             xmlns:ns3="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactaddressmodel"
             xmlns:ns6="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc"
             xmlns:ns5="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.accountcontactmodel"
             xmlns:ns8="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.usermodel"
             xmlns:ns7="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.historymodel"
             xmlns:ns13="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc"
             xmlns:ns9="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.activitymodel"
             xmlns:ns12="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.industrycodemodel"
             xmlns:ns11="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.documentmodel"
             xmlns:ns10="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.groupmodel"
             xmlns:ns17="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.producercodemodel"
             xmlns:ns16="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.accountproducercodemodel"
             xmlns:ns15="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.notemodel"
             xmlns:ns14="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc">
    <ns6:AccountHolderContact>
        <entity-Person>
            <DateOfBirth>999-01-02T12:00:00-05:00</DateOfBirth>
            <FirstName>ABC</FirstName>
            <Gender>F</Gender>
            <LastName>ABC</LastName>
            <LicenseNumber>9999-9999-9999</LicenseNumber>
            <LicenseState>AA</LicenseState>
            <MaritalStatus>S</MaritalStatus>
            <OrganizationType_IC>individual</OrganizationType_IC>
        </entity-Person>
        <HomePhone>9999999999</HomePhone>
        <PrimaryAddress>
            <ns2:AddressLine1>99 ABC St</ns2:AddressLine1>
            <ns2:AddressType>home</ns2:AddressType>
            <ns2:City>AAA</ns2:City>
            <ns2:Country>AA</ns2:Country>
            <ns2:PostalCode>ABC MMM</ns2:PostalCode>
            <ns2:State>AA</ns2:State>
            <ns2:Subtype>Address</ns2:Subtype>
        </PrimaryAddress>
        <PublicID>1</PublicID>
        <Subtype>person</Subtype>
    </ns6:AccountHolderContact>
</ns6:Account>');
-- DDL and sample data population, end

;WITH XMLNAMESPACES (DEFAULT 'http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel'
    , 'http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc' AS ns14) ,rs AS
(
   SELECT id, TRY_CAST(payload AS XML) AS xmldata
   FROM @tbl
)
SELECT ID
   , c.value('(FirstName/text())[1]','VARCHAR(50)') AS FirstName
   , c.value('(LastName/text())[1]','VARCHAR(50)') AS LastName
FROM rs CROSS APPLY rs.xmldata.nodes('/ns14:Account/ns14:AccountHolderContact/entity-Person') AS t(c);

Output

+----+-----------+----------+
| ID | FirstName | LastName |
+----+-----------+----------+
|  1 | ABC       | ABC      |
+----+-----------+----------+


问:
C - How scanf inputs work and how it iterates in loops?
I know the basics of scanf(); requiring a conversion specifier % and an address to the variable to store the input value &.

While doing an assignment, there was a task that involved inputting an arbitrary number of values, one example would be:
5 4 3 2 1

Into scanf, and then print out number of symbols corresponding to the integer typed (eg. '?'), so it would display the terminal as:

```<code>5 4 3 2 1
?????
????
???
??
?
</code>```

In this case I had put the scanf in a while loop as so:

```<code>int i, num;
while(scanf("%d",&num)==1){
   printf("%d",num);
   for (i=0; i<num; i++){
      printf("?");
   }
   printf("/n");
}
</code>```

I am totally confused how scanf reads multiple integers in one input line (5 4 3 2 1) when many sources has specified that scanf only takes one integer until it reads a whitespace. From looking at this, my understanding is that the whitespace separating the integers indicate a new iteration following the previous integer?
When I tried to trace how printing works, it printed as:

```<code>5 4 3 2 1
5?????
4????
3???
2??
1?
</code>```

...So my question is how does scanf 'save' all these integers in one line to 'num' and print EACH of the corresponding symbols to the values given AFTER input? Wouldn't integers be replacing the previous in the variable without an array?

Sorry if this question does not make sense - still quite new to coding. Thank you!

答:
Wouldn't integers be replacing the previous in the variable without an array?

There's no array required here at all.

The scanf() function takes the value (assuming white spaces included) and all of them are saved one by one into the variable num. If you use a debugger (suppose using GDB) and set a breakpoint in while(), you'll get to know by stepping into that the variable num is changed in each iteration and the for loop runs till num is reached.

An example of two iterations using a debugger is provided below (focus on num on the left corner):

Iteration 1:

Iteration 2:

Body:
I know the basics of scanf(); requiring a conversion specifier % and an address to the variable to store the input value &.

While doing an assignment, there was a task that involved inputting an arbitrary number of values, one example would be:
5 4 3 2 1

Into scanf, and then print out number of symbols corresponding to the integer typed (eg. '?'), so it would display the terminal as:

5 4 3 2 1
?????
????
???
??
?

In this case I had put the scanf in a while loop as so:

int i, num;
while(scanf("%d",&num)==1){
   printf("%d",num);
   for (i=0; i<num; i++){
      printf("?");
   }
   printf("/n");
}

I am totally confused how scanf reads multiple integers in one input line (5 4 3 2 1) when many sources has specified that scanf only takes one integer until it reads a whitespace. From looking at this, my understanding is that the whitespace separating the integers indicate a new iteration following the previous integer?
When I tried to trace how printing works, it printed as:

5 4 3 2 1
5?????
4????
3???
2??
1?

...So my question is how does scanf 'save' all these integers in one line to 'num' and print EACH of the corresponding symbols to the values given AFTER input? Wouldn't integers be replacing the previous in the variable without an array?

Sorry if this question does not make sense - still quite new to coding. Thank you!


问:
jsonpCallback function not working
UPDATE 1:

I've just upgraded from jquery 1.4.4 to 1.6.1.  How does that effect the script in the original question?

ORIGINAL QUESTION:

Just as I test, I did:

```<code>$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }

    function jsonpCallback(data){
        alert("jsonpCallback");
    }
});
</code>```

I was expecting to get 2 alerts, the first showing success and the second showing jsonpCallback.  But I am only getting the first alert success.  Why is the second alert not showing up?

答: I think you need to change the jsonpCallBack:'jsonpCallback' bit to jsonpCallBack: function() { alert('boo'); }

Title: jsonpCallback function not working

Body:
UPDATE 1:

I've just upgraded from jquery 1.4.4 to 1.6.1.  How does that effect the script in the original question?

ORIGINAL QUESTION:

Just as I test, I did:

$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }

    function jsonpCallback(data){
        alert("jsonpCallback");
    }
});

I was expecting to get 2 alerts, the first showing success and the second showing jsonpCallback.  But I am only getting the first alert success.  Why is the second alert not showing up?


问:
how do i get a specific attribute from an inherited class when using an array from another class?
I am new to Java programming and have encountered a slight problem.

I wrote tow Classes the first named Human and the second called Student which extends Human

So, in short, I created an array with the type Human and now I want to output a specific  attribute of Student and I want to check if the value of the array entered is a Student. The problem is that the array type  is Human, I can't ask for an exclusive Student attribute.

Thanks for your answers in advance.

The Code:

```<code>for (int i = 0; i < 4; i++) {
    if (Menschen[i] instanceof Student) {
        System.out.println("Name: " + Menschen[i].getName() + ", Geschlecht"
                           + Menschen[i].getGeschlecht() + ", Matrikelnummer: "
                           + ", Typ: " + Menschen[i].getTyp());
    } else {
        System.out.println("Name; " + Menschen[i].getName() + ", Geschlecht"
                       + Menschen[i].getGeschlecht()+", Typ: "+Menschen[i].getTyp() + ".");
    }
}
</code>```

答:
From what I gather from your question, I think you could solve this problem by casting your Human to Student.

So, inside your if:

Student s = (Student) Menschen[i] ;

And then you can access the Student's attribute corresponding to your Menschen[i] by using the Student s reference. Is that what you were asking?

Body:
I am new to Java programming and have encountered a slight problem.

I wrote tow Classes the first named Human and the second called Student which extends Human

So, in short, I created an array with the type Human and now I want to output a specific  attribute of Student and I want to check if the value of the array entered is a Student. The problem is that the array type  is Human, I can't ask for an exclusive Student attribute.

Thanks for your answers in advance.

The Code:

for (int i = 0; i < 4; i++) {
    if (Menschen[i] instanceof Student) {
        System.out.println("Name: " + Menschen[i].getName() + ", Geschlecht"
                           + Menschen[i].getGeschlecht() + ", Matrikelnummer: "
                           + ", Typ: " + Menschen[i].getTyp());
    } else {
        System.out.println("Name; " + Menschen[i].getName() + ", Geschlecht"
                       + Menschen[i].getGeschlecht()+", Typ: "+Menschen[i].getTyp() + ".");
    }
}


问:
Activity not stopping when finished froim thread
I have a Splashscreen where I am running an animation. Following is my logic regarding moving from Splash screen to MainActivity.

Minimum visible time for Splash screen = minTime

Maximum visible time for Splash screen = maxTime

API is called which gets response in some time - apiTime

1. Show Splash screen for at least minTime.

2. Call an API. If the API's response is received in less than maxtime,
    move to next screen immediately otherwise, move to next screen in
    maxtime

Following is my code:

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

private ImageView container;
private AnimationDrawable animationDrawable;
int apiTime = 2000, minTime = 1000, maxTime = 5000;

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

    container = findViewById(R.id.iv_icons);
    container.setBackgroundResource(R.drawable.splash_animation);

    animationDrawable = (AnimationDrawable) container.getBackground();
}

@Override
protected void onResume() {
    super.onResume();
    animationDrawable.start();
    final long start = System.currentTimeMillis();

    //calling api in thread simultaneously. As soon as response is received, move to next screen.
    //Thread.sleep is just dummy for api response time
    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(apiTime);
                //if apiTime is less than minTime, then we wait till minTime
                long time = minTime - (System.currentTimeMillis() - start);
                if (time > 0) {
                    Thread.sleep(time);
                }
                moveToNextScreen();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    t1.start();

    hardMoveToNextScreen();
}

private void moveToNextScreen() {
    Intent i = new Intent(SplashActivity.this, MainActivity.class);
    startActivity(i);
    finish();
}

private void hardMoveToNextScreen () {
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            moveToNextScreen();
        }
    }, maxTime);
}

}
</code>```

Now, according to the time values I have used, the thread t1 calls method moveToNextScreen() before method hardMoveToNextScreen() calls the same method. So, once the activity is finished, I should move to MainActivity.

The problem that I am facing is that MainActivity is opening twice. Once from the thread and then from hardMoveToNextScreen() method. But, this should not happen as I am already calling finish() which means that once I move to MainActivity, any method from SplashActivity should not be called anymore.

What am I doing wrong?

答:
You are calling moveToNextScreen() twice. First time in thread and second time in hardMoveToNextScreen().

If you remove hardMoveToNextScreen(); after t1.start(); it should work fine for you.

Or even better option is to remove Thread and have hardMoveToNextScreen() method with handler.

UPDATED ANSWER:

If you want to keep double logic declare global variable:

```<code>private boolean activityFinished = false;
</code>```

and then change moveToNextScreen() method to this:

```<code>private void moveToNextScreen() {
    if( !activityFinished ) {
        Intent i = new Intent( SplashActivity.this, MainActivity.class );
        startActivity( i );
        finish();
        activityFinished = true;
    }
}
</code>```

Body:
I have a Splashscreen where I am running an animation. Following is my logic regarding moving from Splash screen to MainActivity.

Minimum visible time for Splash screen = minTime

Maximum visible time for Splash screen = maxTime

API is called which gets response in some time - apiTime

1. Show Splash screen for at least minTime.

2. Call an API. If the API's response is received in less than maxtime,
    move to next screen immediately otherwise, move to next screen in
    maxtime

Following is my code:

public class SplashActivity extends AppCompatActivity {

private ImageView container;
private AnimationDrawable animationDrawable;
int apiTime = 2000, minTime = 1000, maxTime = 5000;

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

    container = findViewById(R.id.iv_icons);
    container.setBackgroundResource(R.drawable.splash_animation);

    animationDrawable = (AnimationDrawable) container.getBackground();
}

@Override
protected void onResume() {
    super.onResume();
    animationDrawable.start();
    final long start = System.currentTimeMillis();

    //calling api in thread simultaneously. As soon as response is received, move to next screen.
    //Thread.sleep is just dummy for api response time
    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(apiTime);
                //if apiTime is less than minTime, then we wait till minTime
                long time = minTime - (System.currentTimeMillis() - start);
                if (time > 0) {
                    Thread.sleep(time);
                }
                moveToNextScreen();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    t1.start();

    hardMoveToNextScreen();
}

private void moveToNextScreen() {
    Intent i = new Intent(SplashActivity.this, MainActivity.class);
    startActivity(i);
    finish();
}

private void hardMoveToNextScreen () {
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            moveToNextScreen();
        }
    }, maxTime);
}

}

Now, according to the time values I have used, the thread t1 calls method moveToNextScreen() before method hardMoveToNextScreen() calls the same method. So, once the activity is finished, I should move to MainActivity.

The problem that I am facing is that MainActivity is opening twice. Once from the thread and then from hardMoveToNextScreen() method. But, this should not happen as I am already calling finish() which means that once I move to MainActivity, any method from SplashActivity should not be called anymore.

What am I doing wrong?

Body:
You are calling moveToNextScreen() twice. First time in thread and second time in hardMoveToNextScreen().

If you remove hardMoveToNextScreen(); after t1.start(); it should work fine for you.

Or even better option is to remove Thread and have hardMoveToNextScreen() method with handler.

UPDATED ANSWER:

If you want to keep double logic declare global variable:

private boolean activityFinished = false;

and then change moveToNextScreen() method to this:

private void moveToNextScreen() {
    if( !activityFinished ) {
        Intent i = new Intent( SplashActivity.this, MainActivity.class );
        startActivity( i );
        finish();
        activityFinished = true;
    }
}


问:
For each out of bounds because of changes to the List while running
There is a base class that contains a subclass as a member.
in said subclass, I've got a method where there is a for each loop where I run over a list and run a method on each of the vars in the said list.
In said list there are two objects that may or may not remove objects from the base class's list.
Problem is for some reason the loop crashes whenever said two objects remove an element from the list. Interesting thing is for some reason only if the second object removes an element from the list the program crashes. I've tried adding more variables like this and for some reason only the second to last object can remove elements from the list without having the program crash.
Would love some help on the matter. added some base code:</p>

```<code>public class Game {
private SpriteCollection sprites;
public void initialize() {
    sprites.addelement(e1);
    sprites.addelement(e2);
    sprites.addelement(remover removerElement1);
    sprites.addelement(remover removerElement2);
    }
public class spriteCollection {
public java.util.List<Sprite> sprites;
    public void notifyAllTimePassed() {
            for (Sprite c : sprites) {  // for each sprite
                c.timePassed(); // move it
            }
        }
    }
public class remover {
public void timePassed() {
removesprite(e1, game) // removing the element from the game which
 // contains the sprite collection the remover element is a part of
    }
}
</code>```

答:
I found a rather convenient solution while trying to debug the thing.
Instead of working with a for each loop, I, instead, choose to use iterators, and found it far simpler. all that was needed was the:

```<code>for (Sprite c : sprites) {  // for each sprite
            c.timePassed(); // move it
        }
</code>```

with a

```<code>for (int i = 0; i < sprites.size(); i++) {
        Sprite tempSprite = sprites.get(i);
        tempSprite.timePassed();
    }
</code>```

so that if the size decreases, the whole thing would immediately stop thus, not running an empty index.
Solution is rather banal, surprised I've been stuck at this for so long honestly.

Body:
There is a base class that contains a subclass as a member.
in said subclass, I've got a method where there is a for each loop where I run over a list and run a method on each of the vars in the said list.
In said list there are two objects that may or may not remove objects from the base class's list.
Problem is for some reason the loop crashes whenever said two objects remove an element from the list. Interesting thing is for some reason only if the second object removes an element from the list the program crashes. I've tried adding more variables like this and for some reason only the second to last object can remove elements from the list without having the program crash.
Would love some help on the matter. added some base code:

public class Game {
private SpriteCollection sprites;
public void initialize() {
    sprites.addelement(e1);
    sprites.addelement(e2);
    sprites.addelement(remover removerElement1);
    sprites.addelement(remover removerElement2);
    }
public class spriteCollection {
public java.util.List<Sprite> sprites;
    public void notifyAllTimePassed() {
            for (Sprite c : sprites) {  // for each sprite
                c.timePassed(); // move it
            }
        }
    }
public class remover {
public void timePassed() {
removesprite(e1, game) // removing the element from the game which
 // contains the sprite collection the remover element is a part of
    }
}

Body:
I found a rather convenient solution while trying to debug the thing.
Instead of working with a for each loop, I, instead, choose to use iterators, and found it far simpler. all that was needed was the:

for (Sprite c : sprites) {  // for each sprite
            c.timePassed(); // move it
        }

with a

for (int i = 0; i < sprites.size(); i++) {
        Sprite tempSprite = sprites.get(i);
        tempSprite.timePassed();
    }

so that if the size decreases, the whole thing would immediately stop thus, not running an empty index.
Solution is rather banal, surprised I've been stuck at this for so long honestly.


问:
pandas printing maximum value found in a column with an f string
If I have some made up data... How do I print just the index (date & time stamp) of the maximum value found in a column named Temperature?

```<code>import numpy as np
import pandas as pd
np.random.seed(11)

rows,cols = 50000,2
data = np.random.rand(rows,cols)
tidx = pd.date_range('2019-01-01', periods=rows, freq='H')
df = pd.DataFrame(data, columns=['Temperature','Value'], index=tidx)

maxy = df.Temperature.max()
maxDate = df.loc[df['Temperature'].idxmax()]
</code>```

If I print maxDate there is alot of unwanted info..

```<code>print(maxy)
print(maxDate)
</code>```

This outputs:

```<code>0.9999949674183947
Temperature    0.999995
Value          0.518413
Name: 2023-01-06 02:00:00, dtype: float64
</code>```

Ultimately I am hoping to create an f string that just prints maximum temperature recorded in the dataset is 0.999995 found on 2023-01-06 02:00:00, Without the extra information such as Name: and , dtype: float64 and the Value          0.518413 column... Thanks for any tips & tricks

答:
You f string could be:

```<code>f'maximum temperature recoded in the dataset is {maxy} found on {maxDate.name}'
</code>```

Or without maxy:

```<code>f'maximum temperature recoded in the dataset is {maxDate.Temperature} found on {maxDate.name}'
</code>```

Output:

```<code>'maximum temperature recoded in the dataset is 0.9999949674183947 found on 2023-01-06 02:00:00'
</code>```

Body:
If I have some made up data... How do I print just the index (date & time stamp) of the maximum value found in a column named Temperature?

import numpy as np
import pandas as pd
np.random.seed(11)

rows,cols = 50000,2
data = np.random.rand(rows,cols)
tidx = pd.date_range('2019-01-01', periods=rows, freq='H')
df = pd.DataFrame(data, columns=['Temperature','Value'], index=tidx)

maxy = df.Temperature.max()
maxDate = df.loc[df['Temperature'].idxmax()]

If I print maxDate there is alot of unwanted info..

print(maxy)
print(maxDate)

This outputs:

0.9999949674183947
Temperature    0.999995
Value          0.518413
Name: 2023-01-06 02:00:00, dtype: float64

Ultimately I am hoping to create an f string that just prints maximum temperature recorded in the dataset is 0.999995 found on 2023-01-06 02:00:00, Without the extra information such as Name: and , dtype: float64 and the Value          0.518413 column... Thanks for any tips & tricks

Body:
You f string could be:

f'maximum temperature recoded in the dataset is {maxy} found on {maxDate.name}'

Or without maxy:

f'maximum temperature recoded in the dataset is {maxDate.Temperature} found on {maxDate.name}'

Output:

'maximum temperature recoded in the dataset is 0.9999949674183947 found on 2023-01-06 02:00:00'


问:
Can run Tensorflow within conda env, but then cannot access other anacona modules (matplotlib, pandas etc)
I have created a conda environment named tensorflow, and installed tensorflow within this environment following the official install guide (https://www.tensorflow.org/install/install_linux#installing_with_anaconda)

When I activate the virtual environment I can import tensorflow, but cannot import other modules from anaconda such as pandas or matplotlib.

Do I need to re-install all the modules that I want again within the tensorflow environment?

If so, should I use conda rather than pip to install them?

Is there an easier way to do this?

Thanks for the help, I'm quite new to virtual environments.

答:
I had the same issue, and I solved it by following steps (on mac):

(1) go to Anaconda Navigator (I installed Python via Anaconda)

(2) create a new environment called tensorflow;

 - See this video for detailed steps

- I had issues with creating a new environment and solved it thanks to this post ("conda update conda")

(3) under "Environment", select the new "tensorflow" environment; on the right panel, filter "Not installed", search and install the missing modules

(4) Stay in Tensorflow environment - Go to "Home", install and launch jupyter notebook

(5) Go to jupyter and try import both tensorflow and any previously missing modules - should work this time.