问:
IBM Watson Speech to Text Service is not giving response in Unity3d
I have an ExampleSstreaming class which actually I got from GitHub of IBM Watson SDK (speech to text service demo). Here it is

```<code>public class ExampleStreaming : MonoBehaviour
{
  private int m_RecordingRoutine = 0;
  private string m_MicrophoneID = null;
  private AudioClip m_Recording = null;
  private int m_RecordingBufferSize = 5;
  private int m_RecordingHZ = 22050;

  private SpeechToText m_SpeechToText = new SpeechToText();

  void Start()
  {
    LogSystem.InstallDefaultReactors();
    Log.Debug("ExampleStreaming", "Start();");

    Active = true;
        Debug.Log("start");
    StartRecording();
  }

    public void Update() {
        Debug.Log(m_SpeechToText.IsListening);
    }

  public bool Active
  {
    get { return m_SpeechToText.IsListening; }
    set
    {
      if (value && !m_SpeechToText.IsListening)
      {
        m_SpeechToText.DetectSilence = true;
        m_SpeechToText.EnableWordConfidence = false;
        m_SpeechToText.EnableTimestamps = false;
        m_SpeechToText.SilenceThreshold = 0.03f;
        m_SpeechToText.MaxAlternatives = 1;
        m_SpeechToText.EnableContinousRecognition = true;
        m_SpeechToText.EnableInterimResults = true;
        m_SpeechToText.OnError = OnError;
        m_SpeechToText.StartListening(OnRecognize);
      }
      else if (!value && m_SpeechToText.IsListening)
      {
        m_SpeechToText.StopListening();
      }
    }
  }

  private void StartRecording()
  {
    if (m_RecordingRoutine == 0)
    {
            Debug.Log("m_RecordingRoutine");
            UnityObjectUtil.StartDestroyQueue();
      m_RecordingRoutine = Runnable.Run(RecordingHandler());
    }
  }

  private void StopRecording()
  {
    if (m_RecordingRoutine != 0)
    {
      Microphone.End(m_MicrophoneID);
      Runnable.Stop(m_RecordingRoutine);
      m_RecordingRoutine = 0;
    }
  }

  private void OnError(string error)
  {
    Active = false;

    Log.Debug("ExampleStreaming", "Error! {0}", error);
  }

  private IEnumerator RecordingHandler()
  {
    Log.Debug("ExampleStreaming", "devices: {0}", Microphone.devices);

        m_MicrophoneID = Microphone.devices[0];
        Debug.Log("m_MicrophoneID : " + m_MicrophoneID);
        m_Recording = Microphone.Start(m_MicrophoneID, true, m_RecordingBufferSize, m_RecordingHZ);
    yield return null;      // let m_RecordingRoutine get set..
        Debug.Log("m_Recording : " + m_Recording.length);
        if (m_Recording == null)
    {
            Debug.Log("m_Recording is null");
            StopRecording();
      yield break;
    }

    bool bFirstBlock = true;
    int midPoint = m_Recording.samples / 2;
    float[] samples = null;

    while (m_RecordingRoutine != 0 && m_Recording != null)
    {
      int writePos = Microphone.GetPosition(m_MicrophoneID);
      if (writePos > m_Recording.samples || !Microphone.IsRecording(m_MicrophoneID))
      {
        Log.Error("MicrophoneWidget", "Microphone disconnected.");

        StopRecording();
        yield break;
      }

      if ((bFirstBlock && writePos >= midPoint)
        || (!bFirstBlock && writePos < midPoint))
      {
        // front block is recorded, make a RecordClip and pass it onto our callback.
        samples = new float[midPoint];
        m_Recording.GetData(samples, bFirstBlock ? 0 : midPoint);

        AudioData record = new AudioData();
        record.MaxLevel = Mathf.Max(samples);
        record.Clip = AudioClip.Create("Recording", midPoint, m_Recording.channels, m_RecordingHZ, false);
        record.Clip.SetData(samples, 0);

        m_SpeechToText.OnListen(record);

        bFirstBlock = !bFirstBlock;
      }
      else
      {
        // calculate the number of samples remaining until we ready for a block of audio,
        // and wait that amount of time it will take to record.
        int remaining = bFirstBlock ? (midPoint - writePos) : (m_Recording.samples - writePos);
        float timeRemaining = (float)remaining / (float)m_RecordingHZ;

        yield return new WaitForSeconds(timeRemaining);
      }

    }

    yield break;
  }

  private void OnRecognize(SpeechRecognitionEvent result)
  {
        Debug.Log("OnRecognize");
        if (result != null && result.results.Length > 0)
    {
      foreach (var res in result.results)
      {
        foreach (var alt in res.alternatives)
        {
          string text = alt.transcript;
                    Debug.Log(text);

          Log.Debug("ExampleStreaming", string.Format("{0} ({1}, {2:0.00})\n", text, res.final ? "Final" : "Interim", alt.confidence));
        }
      }
    }
  }
}
</code>```

and this is the line i add to get microphone. I just edit it to provide Microphone Device at zero index which was actually null (I don't know why, is this intentionally left or an error), in the function RecordingHandler .

```<code> m_MicrophoneID = Microphone.devices[0];
</code>```

but unfortunately it is not showing any output log in EventOnRecognize which i think that it should execute.

Wile it displaying these logs, after some seconds (as i given length 5 of the audio). What i am doing wrong, i am unable to understand that how speech to text.

```<code>[DEBUG] OnListenClosed(), State = DISCONNECTED
[DEBUG] KeepAlive exited.
</code>```

I have also tried IBM Watson Speech To text Scene it is also not showing anything.

答:
I solved Error

I encounter the same issue with Unity 2018.3.14f1.
I just change player settings and then works fine

file -> build settings - > player settings -> Other Settings

Configuration

Scripting runtime version : .Net 4x equivalent

API Compatibility level: .Net 4x

Body:
I have an ExampleSstreaming class which actually I got from GitHub of IBM Watson SDK (speech to text service demo). Here it is

public class ExampleStreaming : MonoBehaviour
{
  private int m_RecordingRoutine = 0;
  private string m_MicrophoneID = null;
  private AudioClip m_Recording = null;
  private int m_RecordingBufferSize = 5;
  private int m_RecordingHZ = 22050;

  private SpeechToText m_SpeechToText = new SpeechToText();

  void Start()
  {
    LogSystem.InstallDefaultReactors();
    Log.Debug("ExampleStreaming", "Start();");

    Active = true;
        Debug.Log("start");
    StartRecording();
  }

    public void Update() {
        Debug.Log(m_SpeechToText.IsListening);
    }

  public bool Active
  {
    get { return m_SpeechToText.IsListening; }
    set
    {
      if (value && !m_SpeechToText.IsListening)
      {
        m_SpeechToText.DetectSilence = true;
        m_SpeechToText.EnableWordConfidence = false;
        m_SpeechToText.EnableTimestamps = false;
        m_SpeechToText.SilenceThreshold = 0.03f;
        m_SpeechToText.MaxAlternatives = 1;
        m_SpeechToText.EnableContinousRecognition = true;
        m_SpeechToText.EnableInterimResults = true;
        m_SpeechToText.OnError = OnError;
        m_SpeechToText.StartListening(OnRecognize);
      }
      else if (!value && m_SpeechToText.IsListening)
      {
        m_SpeechToText.StopListening();
      }
    }
  }

  private void StartRecording()
  {
    if (m_RecordingRoutine == 0)
    {
            Debug.Log("m_RecordingRoutine");
            UnityObjectUtil.StartDestroyQueue();
      m_RecordingRoutine = Runnable.Run(RecordingHandler());
    }
  }

  private void StopRecording()
  {
    if (m_RecordingRoutine != 0)
    {
      Microphone.End(m_MicrophoneID);
      Runnable.Stop(m_RecordingRoutine);
      m_RecordingRoutine = 0;
    }
  }

  private void OnError(string error)
  {
    Active = false;

    Log.Debug("ExampleStreaming", "Error! {0}", error);
  }

  private IEnumerator RecordingHandler()
  {
    Log.Debug("ExampleStreaming", "devices: {0}", Microphone.devices);

        m_MicrophoneID = Microphone.devices[0];
        Debug.Log("m_MicrophoneID : " + m_MicrophoneID);
        m_Recording = Microphone.Start(m_MicrophoneID, true, m_RecordingBufferSize, m_RecordingHZ);
    yield return null;      // let m_RecordingRoutine get set..
        Debug.Log("m_Recording : " + m_Recording.length);
        if (m_Recording == null)
    {
            Debug.Log("m_Recording is null");
            StopRecording();
      yield break;
    }

    bool bFirstBlock = true;
    int midPoint = m_Recording.samples / 2;
    float[] samples = null;

    while (m_RecordingRoutine != 0 && m_Recording != null)
    {
      int writePos = Microphone.GetPosition(m_MicrophoneID);
      if (writePos > m_Recording.samples || !Microphone.IsRecording(m_MicrophoneID))
      {
        Log.Error("MicrophoneWidget", "Microphone disconnected.");

        StopRecording();
        yield break;
      }

      if ((bFirstBlock && writePos >= midPoint)
        || (!bFirstBlock && writePos < midPoint))
      {
        // front block is recorded, make a RecordClip and pass it onto our callback.
        samples = new float[midPoint];
        m_Recording.GetData(samples, bFirstBlock ? 0 : midPoint);

        AudioData record = new AudioData();
        record.MaxLevel = Mathf.Max(samples);
        record.Clip = AudioClip.Create("Recording", midPoint, m_Recording.channels, m_RecordingHZ, false);
        record.Clip.SetData(samples, 0);

        m_SpeechToText.OnListen(record);

        bFirstBlock = !bFirstBlock;
      }
      else
      {
        // calculate the number of samples remaining until we ready for a block of audio,
        // and wait that amount of time it will take to record.
        int remaining = bFirstBlock ? (midPoint - writePos) : (m_Recording.samples - writePos);
        float timeRemaining = (float)remaining / (float)m_RecordingHZ;

        yield return new WaitForSeconds(timeRemaining);
      }

    }

    yield break;
  }

  private void OnRecognize(SpeechRecognitionEvent result)
  {
        Debug.Log("OnRecognize");
        if (result != null && result.results.Length > 0)
    {
      foreach (var res in result.results)
      {
        foreach (var alt in res.alternatives)
        {
          string text = alt.transcript;
                    Debug.Log(text);

          Log.Debug("ExampleStreaming", string.Format("{0} ({1}, {2:0.00})\n", text, res.final ? "Final" : "Interim", alt.confidence));
        }
      }
    }
  }
}

and this is the line i add to get microphone. I just edit it to provide Microphone Device at zero index which was actually null (I don't know why, is this intentionally left or an error), in the function RecordingHandler .

 m_MicrophoneID = Microphone.devices[0];

but unfortunately it is not showing any output log in EventOnRecognize which i think that it should execute.

Wile it displaying these logs, after some seconds (as i given length 5 of the audio). What i am doing wrong, i am unable to understand that how speech to text.

[DEBUG] OnListenClosed(), State = DISCONNECTED
[DEBUG] KeepAlive exited.

I have also tried IBM Watson Speech To text Scene it is also not showing anything.


来源: stackexchange

问:
Is there a function to filter rows that contains a string, but on chosen columns names that contains a given string in R?
i will try to be as specific as possible.
I get chunks of datasets from web application. Number of columns may vary for each dataset i download. I want to filter my data for outliers. So i prepared a list:

```<code>outl <- c("God","Devil","Priest")
</code>```

Now lets assume this is my df:

```<code>ID <- c(1,2,3,4)
Actor1<- c("Driver","","","")
Actor2<- c("President","Zombie","","")
Actor3<- c("CEO","Devil","","")
Actor4<-c("Priest","","Killer","Mayor")
Leng<- c(12,42,42,22)
Genre<-c("horror","criminal","drama","comedy")
df_ex <-data.frame(ID, Actor1, Actor2, Actor3, Actor4, Leng, Genre)
</code>```

i would like to filter for the rows ids that contains names from outlier in ANY column that has "Actor" in name (there could be 100 of them thats why i cant do it with OR operator), so something like:

```<code>df_ex %>%
  filter(*anycolumn that contains string "Actor"* %in% outl)
</code>```

and i would expect to get rows with ids 1 & 2

hope thats clear enough,
thanks in advance

答:
You can use filter_at to specifically filter based on specific selected variables (in this case, those starting with "Actor").

```<code>library(tidyverse)

df_ex %>%
  filter_at(vars(starts_with("Actor")), any_vars(. %in% outl))
</code>```

Output

```<code>  ID Actor1    Actor2 Actor3 Actor4 Leng    Genre
1  1 Driver President    CEO Priest   12   horror
2  2           Zombie  Devil          42 criminal
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i will try to be as specific as possible.
I get chunks of datasets from web application. Number of columns may vary for each dataset i download. I want to filter my data for outliers. So i prepared a list:

outl <- c("God","Devil","Priest")

Now lets assume this is my df:

ID <- c(1,2,3,4)
Actor1<- c("Driver","","","")
Actor2<- c("President","Zombie","","")
Actor3<- c("CEO","Devil","","")
Actor4<-c("Priest","","Killer","Mayor")
Leng<- c(12,42,42,22)
Genre<-c("horror","criminal","drama","comedy")
df_ex <-data.frame(ID, Actor1, Actor2, Actor3, Actor4, Leng, Genre)

i would like to filter for the rows ids that contains names from outlier in ANY column that has "Actor" in name (there could be 100 of them thats why i cant do it with OR operator), so something like:

df_ex %>%
  filter(*anycolumn that contains string "Actor"* %in% outl)

and i would expect to get rows with ids 1 & 2

hope thats clear enough,
thanks in advance

Body:
You can use filter_at to specifically filter based on specific selected variables (in this case, those starting with "Actor").

library(tidyverse)

df_ex %>%
  filter_at(vars(starts_with("Actor")), any_vars(. %in% outl))

Output

  ID Actor1    Actor2 Actor3 Actor4 Leng    Genre
1  1 Driver President    CEO Priest   12   horror
2  2           Zombie  Devil          42 criminal


问:
Angular Error : Type 'void' is not assignable to type 'AbstractControl'
I got an error when setting the default value of my FormControl, but it returns an error like this :

error TS2322: Type 'void' is not assignable to type 'AbstractControl'

This is my .ts file :

```<code>  profileForm  = new FormGroup({
    username   : new FormControl().setValue("a"),
    firstname  : new FormControl().setValue("a"),
    lastname   : new FormControl().setValue("a"),
    email      : new FormControl().setValue("a"),
    password   : new FormControl().setValue("a"),
  });
</code>```

Help me to solve this.

答:
You can use form builder:</p>

```<code>profileForm: FormGroup;

constructor(private _formBuilder: FormBuilder) {}

ngOnInit() {
        this.profileForm  = this._formBuilder.group({
            username: [{ value: 'a' }],
            ...
          });
    }
</code>```

Body:
I got an error when setting the default value of my FormControl, but it returns an error like this :

error TS2322: Type 'void' is not assignable to type 'AbstractControl'

This is my .ts file :

  profileForm  = new FormGroup({
    username   : new FormControl().setValue("a"),
    firstname  : new FormControl().setValue("a"),
    lastname   : new FormControl().setValue("a"),
    email      : new FormControl().setValue("a"),
    password   : new FormControl().setValue("a"),
  });

Help me to solve this.

Body:
You can use form builder:

profileForm: FormGroup;

constructor(private _formBuilder: FormBuilder) {}

ngOnInit() {
        this.profileForm  = this._formBuilder.group({
            username: [{ value: 'a' }],
            ...
          });
    }


问:
How to recognize unknown patterns in data frame by row?
I have a data frame where I have agricultural use codes (1-5) for 15 consecutive years. Each row is a polygon representing a field. Ultimately I need R to loop through the rows and recognize patterns of use and tell me their respective frequency. Unfortunately in my real data set I have over 1 mio. features and thus all possible patterns are not known.

```<code>a <- data.frame(replicate(15, sample(0:5,500,rep=TRUE)))
colnames(a) <- paste0("use",2005:2019)
id <- c(1:500)
a <- cbind(id,a)

id use2005 use2006 use2007 use2008 use2009 use2010 use2011 use2012 use2013 use2014 use2015 ...
1  1       1       1       1       1       2       2       1       4       4       4       ...
2  4       4       4       4       5       5       5       0       5       5       5       ...
3  1       4       3       2       3       2       4       5       1       1       1       ...
4  1       1       1       1       1       2       2       1       4       4       4       ...
5  4       2       2       2       2       5       3       3       3       3       3       ...
</code>```

So in this arbitrary example, the code should recognize that id 1 & 4 have the same pattern.

In the end I imagine the result to be some sort of frequency distribution to see if there are certain patterns in the agricultural use of my fields.

For example:

1 1 1 1 1 2 1 1 1 3 2 4 1 1 1

[50] - occurs 50 times

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

[35] - occurs 35 times

and so forth with all existing combinations...

Unfortunately I have no idea how to approach this. I have no experience with pattern recognition.

Thank you!

答:
maybe this?

```<code>library(tidyverse)
a[, -1] %>% group_by_all %>% count
#  use2005 use2006 use2007 use2008 use2009 use2010 use2011 use2012 use2013 use2014 use2015     n
#     <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int> <int>
# 1       1       1       1       1       1       2       2       1       4       4       4     2
# 2       1       4       3       2       3       2       4       5       1       1       1     1
# 3       4       2       2       2       2       5       3       3       3       3       3     1
# 4       4       4       4       4       5       5       5       0       5       5       5     1
</code>```

or if you want to include fields you could change to group_by_at and exclude id from the grouping and then paste fields together:

```<code>a %>%
  group_by_at(vars(-id)) %>%
  summarise(n = n(), ids = paste(id, collapse= "," ))
#   use2005 use2006 use2007 use2008 use2009 use2010 use2011 use2012 use2013 use2014 use2015     n ids
#     <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int> <int> <chr>
# 1       1       1       1       1       1       2       2       1       4       4       4     2 1,4
# 2       1       4       3       2       3       2       4       5       1       1       1     1 3
# 3       4       2       2       2       2       5       3       3       3       3       3     1 5
# 4       4       4       4       4       5       5       5       0       5       5       5     1 2
</code>```

Body:
I have a data frame where I have agricultural use codes (1-5) for 15 consecutive years. Each row is a polygon representing a field. Ultimately I need R to loop through the rows and recognize patterns of use and tell me their respective frequency. Unfortunately in my real data set I have over 1 mio. features and thus all possible patterns are not known.

a <- data.frame(replicate(15, sample(0:5,500,rep=TRUE)))
colnames(a) <- paste0("use",2005:2019)
id <- c(1:500)
a <- cbind(id,a)

id use2005 use2006 use2007 use2008 use2009 use2010 use2011 use2012 use2013 use2014 use2015 ...
1  1       1       1       1       1       2       2       1       4       4       4       ...
2  4       4       4       4       5       5       5       0       5       5       5       ...
3  1       4       3       2       3       2       4       5       1       1       1       ...
4  1       1       1       1       1       2       2       1       4       4       4       ...
5  4       2       2       2       2       5       3       3       3       3       3       ...

So in this arbitrary example, the code should recognize that id 1 & 4 have the same pattern.

In the end I imagine the result to be some sort of frequency distribution to see if there are certain patterns in the agricultural use of my fields.

For example:

1 1 1 1 1 2 1 1 1 3 2 4 1 1 1

[50] - occurs 50 times

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

[35] - occurs 35 times

and so forth with all existing combinations...

Unfortunately I have no idea how to approach this. I have no experience with pattern recognition.

Thank you!

Body:
maybe this?

library(tidyverse)
a[, -1] %>% group_by_all %>% count
#  use2005 use2006 use2007 use2008 use2009 use2010 use2011 use2012 use2013 use2014 use2015     n
#     <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int> <int>
# 1       1       1       1       1       1       2       2       1       4       4       4     2
# 2       1       4       3       2       3       2       4       5       1       1       1     1
# 3       4       2       2       2       2       5       3       3       3       3       3     1
# 4       4       4       4       4       5       5       5       0       5       5       5     1

or if you want to include fields you could change to group_by_at and exclude id from the grouping and then paste fields together:

a %>%
  group_by_at(vars(-id)) %>%
  summarise(n = n(), ids = paste(id, collapse= "," ))
#   use2005 use2006 use2007 use2008 use2009 use2010 use2011 use2012 use2013 use2014 use2015     n ids
#     <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int>   <int> <int> <chr>
# 1       1       1       1       1       1       2       2       1       4       4       4     2 1,4
# 2       1       4       3       2       3       2       4       5       1       1       1     1 3
# 3       4       2       2       2       2       5       3       3       3       3       3     1 5
# 4       4       4       4       4       5       5       5       0       5       5       5     1 2


问:
Migrate From An IntegerField With Choices To A CharField
In Django I have a model with the following IntegerField.

```<code>GENDER_CHOICES = (
    (0, 'Male'),
    (1, 'Female'),
)
gender = models.IntegerField(choices=GENDER_CHOICES)
</code>```

I would like to altar this model to become a CharField using the choices.

```<code>GENDER_CHOICES = (
    ("MALE", 'Male'),
    ("FEMALE", 'Female'),
    ("NA", 'Id Rather Not Say'),
)
gender = models.CharField(choices=GENDER_CHOICES, max_length=10)
</code>```

If I were to do this by running makemigrations and migrate I would lose the existing data in the database.

How would I make this (and similar) migrations without losing the existing data in the database?

Ideally I would do this in the migration itself that way it will run on the production server the second we use the migrate command.

答:
Migration 1: make a char field like gender_tmp, migrate all the data to it

Migration 2: remove gender and rename gender_tmp to gender

Body:
In Django I have a model with the following IntegerField.

GENDER_CHOICES = (
    (0, 'Male'),
    (1, 'Female'),
)
gender = models.IntegerField(choices=GENDER_CHOICES)

I would like to altar this model to become a CharField using the choices.

GENDER_CHOICES = (
    ("MALE", 'Male'),
    ("FEMALE", 'Female'),
    ("NA", 'Id Rather Not Say'),
)
gender = models.CharField(choices=GENDER_CHOICES, max_length=10)

If I were to do this by running makemigrations and migrate I would lose the existing data in the database.

How would I make this (and similar) migrations without losing the existing data in the database?

Ideally I would do this in the migration itself that way it will run on the production server the second we use the migrate command.


问:
Issue when using PNGs into CToolBar object
I'm trying to insert a CImageList into a CToolBar object called m_wndUtilBar. I add all images using the code below:

```<code>CImageList imageList;
CBitmap bitmap;
COLORREF crMask = RGB(192, 192, 192);

CSize button, button_img;
button.cx = 39;
button.cy = 39;
button_img.cx = 32;
button_img.cy = 32;
m_wndUtilBar.SetSizes(button, button_img);

imageList.Create(button_img.cx, button_img.cy, ILC_COLOR32 | ILC_MASK, 18, 1);

LoadBitmapFromPNG(IDB_PNG_UP, bitmap);
imageList.Add(&bitmap, crMask);
bitmap.Detach();
.
.
. // adding more images into the list
.
</code>```

And then I add the list into the object as below:

```<code>m_wndUtilBar.GetToolBarCtrl().SetImageList(&imageList);
imageList.Detach();
</code>```

All images I used are resources included in the project not as bitmaps but as PNGs (I say it because I think that is the issue is there).

Once I run the application everything works fine. All images are displayed and the buttons work correctly. However, when I disable one of those buttons, the image of this button appears as enabled (without that typical gray disabled mask) and I don't know why.

Can anybody help me? I don't know what to do to apply the disable effect to an image of a disabled button.

UPDATE 1

I see that the disable effect only appears on the borders of the images, so I sopose that the effect is applied, However, this effect is not applied inside the PNG.

答:
You may need to supply a png graphic for the disabled state as well.

From the documentation:

Using Image Lists in a Toolbar Control

you need to use SetDisabledImageList(), and SetHotImageList() for stuff like that.

Body:
I'm trying to insert a CImageList into a CToolBar object called m_wndUtilBar. I add all images using the code below:

CImageList imageList;
CBitmap bitmap;
COLORREF crMask = RGB(192, 192, 192);

CSize button, button_img;
button.cx = 39;
button.cy = 39;
button_img.cx = 32;
button_img.cy = 32;
m_wndUtilBar.SetSizes(button, button_img);

imageList.Create(button_img.cx, button_img.cy, ILC_COLOR32 | ILC_MASK, 18, 1);

LoadBitmapFromPNG(IDB_PNG_UP, bitmap);
imageList.Add(&bitmap, crMask);
bitmap.Detach();
.
.
. // adding more images into the list
.

And then I add the list into the object as below:

m_wndUtilBar.GetToolBarCtrl().SetImageList(&imageList);
imageList.Detach();

All images I used are resources included in the project not as bitmaps but as PNGs (I say it because I think that is the issue is there).

Once I run the application everything works fine. All images are displayed and the buttons work correctly. However, when I disable one of those buttons, the image of this button appears as enabled (without that typical gray disabled mask) and I don't know why.

Can anybody help me? I don't know what to do to apply the disable effect to an image of a disabled button.

UPDATE 1

I see that the disable effect only appears on the borders of the images, so I sopose that the effect is applied, However, this effect is not applied inside the PNG.


问:
extract numerical values from strings in list that come directly after the "@ " symbol
I have a list that looks like this: * I have put each element on a new, numbered line for readability*

```<code>NOVO NORDISK A/S    216757.000 SHS @ 5.15000000 EXDTE-22MAR19 PAYDTE-26MAR19 TAXABLE RECLAIMABLE TAXED AT .270000%,
</code>```

```<code>NOVO NORDISK A/S    205395.000 SHS @ 3.00000000 EXDTE-16AUG19 PAYDTE-20AUG19 TAXABLE RECLAIMABLE TAXED AT .270000%,
</code>```

```<code>NOVO NORDISK A/S    TAX RECLAIM PAID 79000.000 EX-DT:20MAR15 PY-DT:24MAR15 CURRENCY TIP # 1150790014348SIEMENS AG    89789.000 SHS @ 3.80000000 EXDATE-31JAN19 PAYDATE-04FEB19 TAXABLE RECLAIMABLE TAXED AT .263750%,
</code>```

```<code>UNILEVER NV    171208.000 SHS @ 0.38720000 EXDATE-14FEB19 PAYDATE-20MAR19 TAXABLE W/H @ SOURCE TAXED AT .150000%,
</code>```

```<code>ROYAL DUTCH SHELL PLC A SHS   568644.000 SHS @ 0.41810000 EXDTE-14FEB19 PAYDTE-25MAR19 TAXABLE W/H @ SOURCE TAXED AT .150000%,
</code>```

I am trying to write a script that will extract the number that falls directly after the first "@" sign.
how would i go about doing this in Python?

答:
Try:</p>

```<code>my_list = ['NOVO NORDISK A/S    216757.000 SHS @ 5.15000000 EXDTE-22MAR19 PAYDTE-26MAR19 TAXABLE RECLAIMABLE TAXED AT .270000%',
'NOVO NORDISK A/S    205395.000 SHS @ 3.00000000 EXDTE-16AUG19 PAYDTE-20AUG19 TAXABLE RECLAIMABLE TAXED AT .270000%']
result = [re.findall(r'\@ (\d+\.\d+)',s)[0] for s in my_list]
result
['5.15000000', '3.00000000']
</code>```

Body:
I have a list that looks like this: * I have put each element on a new, numbered line for readability*

NOVO NORDISK A/S    216757.000 SHS @ 5.15000000 EXDTE-22MAR19 PAYDTE-26MAR19 TAXABLE RECLAIMABLE TAXED AT .270000%,

NOVO NORDISK A/S    205395.000 SHS @ 3.00000000 EXDTE-16AUG19 PAYDTE-20AUG19 TAXABLE RECLAIMABLE TAXED AT .270000%,

NOVO NORDISK A/S    TAX RECLAIM PAID 79000.000 EX-DT:20MAR15 PY-DT:24MAR15 CURRENCY TIP # 1150790014348SIEMENS AG    89789.000 SHS @ 3.80000000 EXDATE-31JAN19 PAYDATE-04FEB19 TAXABLE RECLAIMABLE TAXED AT .263750%,

UNILEVER NV    171208.000 SHS @ 0.38720000 EXDATE-14FEB19 PAYDATE-20MAR19 TAXABLE W/H @ SOURCE TAXED AT .150000%,

ROYAL DUTCH SHELL PLC A SHS   568644.000 SHS @ 0.41810000 EXDTE-14FEB19 PAYDTE-25MAR19 TAXABLE W/H @ SOURCE TAXED AT .150000%,

I am trying to write a script that will extract the number that falls directly after the first "@" sign.
how would i go about doing this in Python?

Body:
Try:

my_list = ['NOVO NORDISK A/S    216757.000 SHS @ 5.15000000 EXDTE-22MAR19 PAYDTE-26MAR19 TAXABLE RECLAIMABLE TAXED AT .270000%',
'NOVO NORDISK A/S    205395.000 SHS @ 3.00000000 EXDTE-16AUG19 PAYDTE-20AUG19 TAXABLE RECLAIMABLE TAXED AT .270000%']
result = [re.findall(r'\@ (\d+\.\d+)',s)[0] for s in my_list]
result
['5.15000000', '3.00000000']


问:
How to set php executable path php.validate.executablePath in vscode when php is set inside docker container?
I have a development environment based in docker.

Everytime that I open VSCode I get this message:

Cannot validate since no PHP executable is set. Use the setting
  'php.validate.executablePath' to configure the PHP executable.

Somebody know how to set php.validate.executablePath in this case?

I have no idea how to do it.

答:
If you get this on windows in VS code click on the blue 'open settings' button. Near the bottom of the screen this opens there's a link to enter the settings, click this to open the settings.json file. Edit the file to look like this:

```<code>{
    "php.executablePath" : "C:/php-7.4.2-nts-Win32-vc15-x64/php.exe",
    "php.validate.executablePath" : "C:/php-7.4.2-nts-Win32-vc15-x64/php.exe"
}
</code>```

where C:/php-7.4.2-nts-Win32-vc15-x64 is the path to your PHP dir

Body:
If you get this on windows in VS code click on the blue 'open settings' button. Near the bottom of the screen this opens there's a link to enter the settings, click this to open the settings.json file. Edit the file to look like this:

{
    "php.executablePath" : "C:/php-7.4.2-nts-Win32-vc15-x64/php.exe",
    "php.validate.executablePath" : "C:/php-7.4.2-nts-Win32-vc15-x64/php.exe"
}

where C:/php-7.4.2-nts-Win32-vc15-x64 is the path to your PHP dir


问:
How to check programmatically if an application is installed or not in Android?
We have installed applications programmatically.

If the application is already installed in the device the application is open automatically.

Otherwise install the particular application.

Guide Me. I have no idea.
Thanks.

答:
So nicer with Kotlin suger:</p>

```<code>  private fun isSomePackageInstalled(context: Context, packageName: String): Boolean {

    val packageManager = context.packageManager

    return runCatching { packageManager.getPackageInfo(packageName, 0) }.isSuccess
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So nicer with Kotlin suger:

  private fun isSomePackageInstalled(context: Context, packageName: String): Boolean {

    val packageManager = context.packageManager

    return runCatching { packageManager.getPackageInfo(packageName, 0) }.isSuccess
  }


问:
Deferred Shadow doesn't work if detecting Multiple Transparent Planes
In my code, I detect the plane and show shadow for the object above the plane. If there is one plane, it works fine, but if it detects multiple planes, the redundant shadow will show.

As the picture shows, on the plane #1, the shadow is right, but if I add another plane #2, the plane #2 has the wrong shadow, even if I remove the airplane, the shadow on plane #1 disappears, but the shadow on plane #2 is still there. I don't want to remove the plane #2, but how to remove the wrong shadow on plane #2?

Please help me fix it, thanks.

Edit: If I change the plane to floor, it will be much better.

答:
When you use a Plane Detection feature and want to combine two coplanar detected planes into bigger one, the best approach is to update detected planes using renderer(_:didUpdate:for:) instance method to get a united plane with one ARPlaneAnchor in its center.

Here's how your code may look like:

```<code>extension ViewController: ARSCNViewDelegate {

    func renderer(_ renderer: SCNSceneRenderer,
              didUpdate node: SCNNode,
                  for anchor: ARAnchor) {

        guard let planeAnchor = anchor as? ARPlaneAnchor,
              let planeNode = node.childNodes.first,
              let myPlane = planeNode.geometry as? SCNPlane
        else { return }

        let width = CGFloat(planeAnchor.extent.x)
        let height = CGFloat(planeAnchor.extent.z)
        myPlane.width = width
        myPlane.height = height

        let x = CGFloat(planeAnchor.center.x)
        let y = CGFloat(planeAnchor.center.y)
        let z = CGFloat(planeAnchor.center.z)
        planeNode.position = SCNVector3(x, y, z)
    }
}
</code>```

P.S.

The key point of this code is not an update itself but rather the fact that you get a bigger single plane instead of two different coplanar planes. Thus shadows, that this single plane catches, must work as expected.

It's up to you if you wanna use an infinite plane (SCNFloor) but it's not effective if you track a non-infinite surface like a table top.

Body:
When you use a Plane Detection feature and want to combine two coplanar detected planes into bigger one, the best approach is to update detected planes using renderer(_:didUpdate:for:) instance method to get a united plane with one ARPlaneAnchor in its center.

Here's how your code may look like:

extension ViewController: ARSCNViewDelegate {

    func renderer(_ renderer: SCNSceneRenderer,
              didUpdate node: SCNNode,
                  for anchor: ARAnchor) {

        guard let planeAnchor = anchor as? ARPlaneAnchor,
              let planeNode = node.childNodes.first,
              let myPlane = planeNode.geometry as? SCNPlane
        else { return }

        let width = CGFloat(planeAnchor.extent.x)
        let height = CGFloat(planeAnchor.extent.z)
        myPlane.width = width
        myPlane.height = height

        let x = CGFloat(planeAnchor.center.x)
        let y = CGFloat(planeAnchor.center.y)
        let z = CGFloat(planeAnchor.center.z)
        planeNode.position = SCNVector3(x, y, z)
    }
}

P.S.

The key point of this code is not an update itself but rather the fact that you get a bigger single plane instead of two different coplanar planes. Thus shadows, that this single plane catches, must work as expected.

It's up to you if you wanna use an infinite plane (SCNFloor) but it's not effective if you track a non-infinite surface like a table top.


问:
Difference between Keras and TensorFlow Hub Version of MobileNetV2
I am working on a transfer learning approach and got very different results when using the MobileNetV2 from keras.applications and the one available on TensorFlow Hub. This seems strange to me as both versions claim here and here to extract their weights from the same checkpoint mobilenet_v2_1.0_224.
This is how the differences can be reproduced, you can find the Colab Notebook here:

```<code>!pip install tensorflow-gpu==2.1.0
import tensorflow as tf
import numpy as np
import tensorflow_hub as hub
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2

def create_model_keras():
  image_input = tf.keras.Input(shape=(224, 224, 3))
  out = MobileNetV2(input_shape=(224, 224, 3),
                  include_top=True)(image_input)
  model = tf.keras.models.Model(inputs=image_input, outputs=out)
  model.compile(optimizer='adam', loss=["categorical_crossentropy"])
  return model

def create_model_tf():
  image_input = tf.keras.Input(shape=(224, 224 ,3))
  out = hub.KerasLayer("https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4",
                      input_shape=(224, 224, 3))(image_input)
  model = tf.keras.models.Model(inputs=image_input, outputs=out)
  model.compile(optimizer='adam', loss=["categorical_crossentropy"])
  return model
</code>```

When I try to predict on a random batch, the results are not equal:

```<code>keras_model = create_model_keras()
tf_model = create_model_tf()
np.random.seed(42)
data = np.random.rand(32,224,224,3)
out_keras = keras_model.predict_on_batch(data)
out_tf = tf_model.predict_on_batch(data)
np.array_equal(out_keras, out_tf)
</code>```

The output of the version from keras.applications sums up to 1 but the version from TensorFlow Hub does not. Also the shape of the two versions is different: TensorFlow Hub has 1001 labels, keras.applications has 1000.

```<code>np.sum(out_keras[0]), np.sum(out_tf[0])
</code>```

prints (1.0000001, -14.166359)

What is the reason for these differences? Am I missing something?

Edit 18.02.2020

As Szymon Maszke pointed out, the TFHub version returns logits. That's why i added a Softmax layer to the create_model_tf as follows:
out = tf.keras.layers.Softmax()(x)

arnoegw mentioned that the TfHub version requires an image normalized to [0,1], whereas the keras version requires normalization to [-1,1]. When I use the following preprocessing on a test image:

```<code>from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
img = tf.keras.preprocessing.image.load_img("/content/panda.jpeg", target_size=(224,224))
img = tf.keras.preprocessing.image.img_to_array(img)
img = preprocess_input(img)
</code>```

```<code>img = tf.io.read_file("/content/panda.jpeg")
img = tf.image.decode_jpeg(img)
img = tf.image.convert_image_dtype(img, tf.float32)
img = tf.image.resize(img, (224,224))
</code>```

Both correctly predict the same label and the following condition is true: np.allclose(out_keras, out_tf[:,1:], rtol=0.8)

Edit 2 18.02.2020
Before I wrote that it is not possible to convert the formats into each other. This was caused by a bug.

答:
There are several documented differences:

Like Szymon said, the TF Hub version returns logits (before the softmax function that turns them into probabilities), which is a common practice, because the cross-entropy loss can be computed with greater numerical stability from the logits.

The TF Hub model assumes float32 inputs in the range of [0,1], which is what you get from tf.image.decode_jpeg(...) followed by tf.image.convert_image_dtype(..., tf.float32). The Keras code uses a model-specific range (likely [-1,+1]).

The TF Hub model reflects the original SLIM checkpoint more completely in returning all its 1001 output classes. As stated in the ImageNetLabels.txt linked from the documentation, the added class 0 is "background" (aka. "stuff"). That is what object detection uses to indicate image background as opposed to an object of any known class.

Body:
I am working on a transfer learning approach and got very different results when using the MobileNetV2 from keras.applications and the one available on TensorFlow Hub. This seems strange to me as both versions claim here and here to extract their weights from the same checkpoint mobilenet_v2_1.0_224.
This is how the differences can be reproduced, you can find the Colab Notebook here:

!pip install tensorflow-gpu==2.1.0
import tensorflow as tf
import numpy as np
import tensorflow_hub as hub
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2

def create_model_keras():
  image_input = tf.keras.Input(shape=(224, 224, 3))
  out = MobileNetV2(input_shape=(224, 224, 3),
                  include_top=True)(image_input)
  model = tf.keras.models.Model(inputs=image_input, outputs=out)
  model.compile(optimizer='adam', loss=["categorical_crossentropy"])
  return model

def create_model_tf():
  image_input = tf.keras.Input(shape=(224, 224 ,3))
  out = hub.KerasLayer("https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4",
                      input_shape=(224, 224, 3))(image_input)
  model = tf.keras.models.Model(inputs=image_input, outputs=out)
  model.compile(optimizer='adam', loss=["categorical_crossentropy"])
  return model

When I try to predict on a random batch, the results are not equal:

keras_model = create_model_keras()
tf_model = create_model_tf()
np.random.seed(42)
data = np.random.rand(32,224,224,3)
out_keras = keras_model.predict_on_batch(data)
out_tf = tf_model.predict_on_batch(data)
np.array_equal(out_keras, out_tf)

The output of the version from keras.applications sums up to 1 but the version from TensorFlow Hub does not. Also the shape of the two versions is different: TensorFlow Hub has 1001 labels, keras.applications has 1000.

np.sum(out_keras[0]), np.sum(out_tf[0])

prints (1.0000001, -14.166359)

What is the reason for these differences? Am I missing something?

Edit 18.02.2020

As Szymon Maszke pointed out, the TFHub version returns logits. That's why i added a Softmax layer to the create_model_tf as follows:
out = tf.keras.layers.Softmax()(x)

arnoegw mentioned that the TfHub version requires an image normalized to [0,1], whereas the keras version requires normalization to [-1,1]. When I use the following preprocessing on a test image:

from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
img = tf.keras.preprocessing.image.load_img("/content/panda.jpeg", target_size=(224,224))
img = tf.keras.preprocessing.image.img_to_array(img)
img = preprocess_input(img)

img = tf.io.read_file("/content/panda.jpeg")
img = tf.image.decode_jpeg(img)
img = tf.image.convert_image_dtype(img, tf.float32)
img = tf.image.resize(img, (224,224))

Both correctly predict the same label and the following condition is true: np.allclose(out_keras, out_tf[:,1:], rtol=0.8)

Edit 2 18.02.2020
Before I wrote that it is not possible to convert the formats into each other. This was caused by a bug.


问:
Why does my promise chain not run sequentially when I use an exported module, but it does when I don't export the module?
I'm trying to get data as a csv from a URL in one file, and then convert that csv in another javascript file to a JSON object using a promise chain. The problem is, it's trying to convert the csv to json before the callback has actually retrieved the csv.

(Note: I realise I'm using the request library which is now deprecated, and will change it once I have the promise chain working).

File 1 (getting the csv data from the url) is below. I need to poll the url until it's populated with the data (usually takes about 5 mins - there are authentication steps beforehand, but they work fine so I'm omitting them to simplify this.) This returns a promise, which is exported as get_csv(). The promise resolves for a csv string.

```<code>const request = require('request');

const csv_url = foo;

module.exports.get_csv = () => {
  return new Promise ((resolve, reject) => {
    function poll_url () {
      request.get({url: csv_url
      }, (error, response, body) => {
        if (error) console.error(error);
        data_csv = body;
        if (data_csv === ''){
          console.log("data_csv is blank.");
        } else {
          clearInterval(intervalID);
          console.log("data_csv has been populated!");
          resolve(data_csv);
        }
      })
    }

    pollURL()
    var intervalID = setInterval(poll_url, 60000);
  })
};
</code>```

JS file 2 (changing the csv data to json) is below. It's meant to just add a .then() to the promise from file 1, which would transform the data from csv to json and then console.log() the json data.

```<code>const data = require('./get_csv_data');   // File 1
const csv = require('csvtojson');

new Promise ((resolve, reject) => {
  const data_csv_string = data.get_csv()
  resolve(data_csv_string);
})

.then(
  (data_csv_string) => {
    console.log(data_csv_string);                        // for debugging - giving undefined
    csv({output: "json"}).fromString(data_csv_string)    // "Cannot read property 'toString' of undefined"
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)
</code>```

The problem is the .then() of file 2 doesn't wait for the first promise's callback to be completed. The console prints out:

```<code>undefined
(node:10691) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'toString' of undefined
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv has been populated!
</code>```

What I can't wrap my head around is, if I put the .then() clause below at the end of File 1, it does work. What am I doing wrong?

```<code>.then(
  (data_csv_string) => {
    console.log(data_csv_string);
    csv({output: "json"}).fromString(data_csv_string)
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)
</code>```

答:
File 2 needs to be:</p>

```<code>const data = require('./get_csv_data');   // File 1
const csv = require('csvtojson');

data.get_csv().then(
  (data_csv_string) => {
    console.log(data_csv_string);                        // for debugging - giving undefined
    csv({output: "json"}).fromString(data_csv_string)    // "Cannot read property 'toString' of undefined"
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)
</code>```

Body:
I'm trying to get data as a csv from a URL in one file, and then convert that csv in another javascript file to a JSON object using a promise chain. The problem is, it's trying to convert the csv to json before the callback has actually retrieved the csv.

(Note: I realise I'm using the request library which is now deprecated, and will change it once I have the promise chain working).

File 1 (getting the csv data from the url) is below. I need to poll the url until it's populated with the data (usually takes about 5 mins - there are authentication steps beforehand, but they work fine so I'm omitting them to simplify this.) This returns a promise, which is exported as get_csv(). The promise resolves for a csv string.

const request = require('request');

const csv_url = foo;

module.exports.get_csv = () => {
  return new Promise ((resolve, reject) => {
    function poll_url () {
      request.get({url: csv_url
      }, (error, response, body) => {
        if (error) console.error(error);
        data_csv = body;
        if (data_csv === ''){
          console.log("data_csv is blank.");
        } else {
          clearInterval(intervalID);
          console.log("data_csv has been populated!");
          resolve(data_csv);
        }
      })
    }

    pollURL()
    var intervalID = setInterval(poll_url, 60000);
  })
};

JS file 2 (changing the csv data to json) is below. It's meant to just add a .then() to the promise from file 1, which would transform the data from csv to json and then console.log() the json data.

const data = require('./get_csv_data');   // File 1
const csv = require('csvtojson');

new Promise ((resolve, reject) => {
  const data_csv_string = data.get_csv()
  resolve(data_csv_string);
})

.then(
  (data_csv_string) => {
    console.log(data_csv_string);                        // for debugging - giving undefined
    csv({output: "json"}).fromString(data_csv_string)    // "Cannot read property 'toString' of undefined"
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)

The problem is the .then() of file 2 doesn't wait for the first promise's callback to be completed. The console prints out:

undefined
(node:10691) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'toString' of undefined
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv has been populated!

What I can't wrap my head around is, if I put the .then() clause below at the end of File 1, it does work. What am I doing wrong?

.then(
  (data_csv_string) => {
    console.log(data_csv_string);
    csv({output: "json"}).fromString(data_csv_string)
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)

Body:
File 2 needs to be:

const data = require('./get_csv_data');   // File 1
const csv = require('csvtojson');

data.get_csv().then(
  (data_csv_string) => {
    console.log(data_csv_string);                        // for debugging - giving undefined
    csv({output: "json"}).fromString(data_csv_string)    // "Cannot read property 'toString' of undefined"
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)


问:
Select several rows into several variables - Oracle PL/SQL
I have one select statement that returns a query like this:

```<code>SELECT value FROM dummy WHERE condition = 1;

    ROW | value
   -----|-----
    1   | val1
    2   | val2
    3   | val3
    4   | val4
</code>```

I have 4 variables

```<code>r1, r2, r3, r4
</code>```

What is the cleanest way to assign those variables the values of my query?
Can I use a SELECT INTO statement?

答:
You can uae PIVOT as following;

```<code>Select v1, v2, v3, v4
       Into val1, val2, val3, val4
From (SELECT value FROM dummy WHERE condition = 1)
Pivot
(Max(value) for row in (1 as v1, 2 as v2, 3 as v3, 4 as v4))
</code>```

Cheers!!

Body:
I have one select statement that returns a query like this:

SELECT value FROM dummy WHERE condition = 1;

    ROW | value
   -----|-----
    1   | val1
    2   | val2
    3   | val3
    4   | val4

I have 4 variables

r1, r2, r3, r4

What is the cleanest way to assign those variables the values of my query?
Can I use a SELECT INTO statement?

Body:
You can uae PIVOT as following;

Select v1, v2, v3, v4
       Into val1, val2, val3, val4
From (SELECT value FROM dummy WHERE condition = 1)
Pivot
(Max(value) for row in (1 as v1, 2 as v2, 3 as v3, 4 as v4))

Cheers!!


问:
problem with receiving data from Controller using .getJSON() and CodeIgniter
I'm wondering why it doesn't work for me. I followed instructions from here: http://stackoverflow.com/questions/5418179/problem-with-jquery-getjson-retrieve-data-from-controller-code-igniter but maybe I'm doing something wrong. I'm trying to make script that will populate the rest of the fields when user selects a value from select menu.

My jQuery script looks like this:

```<code>$(document).ready(function() {
    $('#selprod-1').change(function() {
        var id = $('#selprod-1 option:selected').val();
        $.post(
            '<?php echo $head['site_link'];?>faktura/pobierzProdukt/'+id,
            function(data){
                alert(data);
                $('#pkwiu').val(data.product_pkwiu);
                $('#netto').val(data.product_netto);
                $('#vat').val(data.product_vat);
                $('#brutto').val(data.product_brutto);
                $('#jedn').val(data.product_jedn);
            },
            'json'
        );
    });
});
</code>```

My HTML form looks like this:

```<code><tr>
<td>1</td>
<td><?php echo form_dropdown('produkt[]',$lista,'','id="selprod-1"');?></td>
<td><?php echo form_input(array('name'=>'pkwiu','class'=>'short','readonly'=>'readonly'));?></td>
<td><?php echo form_input(array('name'=>'netto','class'=>'short','id'=>'netto','readonly'=>'readonly'));?></td>
<td><?php echo form_input(array('name'=>'vat','class'=>'mini','id'=>'vat','readonly'=>'readonly'));?></td>
<td><?php echo form_input(array('name'=>'brutto','class'=>'short','id'=>'brutto','readonly'=>'readonly'));?></td>
<td><?php echo form_input(array('name'=>'jedn','class'=>'mini','id'=>'jedn','readonly'=>'readonly'));?></td>
<td><?php echo form_input(array('name'=>'ilosc','class'=>'short','id'=>'ilosc'));?></td>
<td><?php echo form_input(array('name'=>'knetto','class'=>'short','id'=>'knetto','readonly'=>'readonly'));?></td>
<td><?php echo form_input(array('name'=>'kvat','class'=>'short','id'=>'kvat','readonly'=>'readonly'));?></td>
<td><?php echo form_input(array('name'=>'kbrutto','class'=>'short','id'=>'kbrutto','readonly'=>'readonly'));?></td> </tr>
</code>```

My controller function (which works) looks like this:

```<code>public function pobierzProdukt($id)
    {
        $json = json_encode($this->Faktura_model->getProduct($id));
        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: Mon, 26 Jul 2027 05:00:00 GMT');
        header('Content-type: application/json');
        echo $json;
    }
</code>```

My model function looks like this:

```<code>public function getProduct($id)
    {
        $q = 'SELECT product_vat, product_netto, product_brutto, product_jedn
            FROM products
            WHERE product_id="'.$id.'"';
        $w = $this->db->query($q);
        return json_encode($w->row_array());
    }
</code>```

答: ur encoding it twice, not sure if json_encode deals with that or not but still $json should not be json_encode</p>

Body:
I'm wondering why it doesn't work for me. I followed instructions from here: http://stackoverflow.com/questions/5418179/problem-with-jquery-getjson-retrieve-data-from-controller-code-igniter but maybe I'm doing something wrong. I'm trying to make script that will populate the rest of the fields when user selects a value from select menu.

My jQuery script looks like this:

$(document).ready(function() {
    $('#selprod-1').change(function() {
        var id = $('#selprod-1 option:selected').val();
        $.post(
            '<?php echo $head['site_link'];?>faktura/pobierzProdukt/'+id,
            function(data){
                alert(data);
                $('#pkwiu').val(data.product_pkwiu);
                $('#netto').val(data.product_netto);
                $('#vat').val(data.product_vat);
                $('#brutto').val(data.product_brutto);
                $('#jedn').val(data.product_jedn);
            },
            'json'
        );
    });
});

My HTML form looks like this:

1
<?php echo form_dropdown('produkt[]',$lista,'','id="selprod-1"');?>
<?php echo form_input(array('name'=>'pkwiu','class'=>'short','readonly'=>'readonly'));?>
<?php echo form_input(array('name'=>'netto','class'=>'short','id'=>'netto','readonly'=>'readonly'));?>
<?php echo form_input(array('name'=>'vat','class'=>'mini','id'=>'vat','readonly'=>'readonly'));?>
<?php echo form_input(array('name'=>'brutto','class'=>'short','id'=>'brutto','readonly'=>'readonly'));?>
<?php echo form_input(array('name'=>'jedn','class'=>'mini','id'=>'jedn','readonly'=>'readonly'));?>
<?php echo form_input(array('name'=>'ilosc','class'=>'short','id'=>'ilosc'));?>
<?php echo form_input(array('name'=>'knetto','class'=>'short','id'=>'knetto','readonly'=>'readonly'));?>
<?php echo form_input(array('name'=>'kvat','class'=>'short','id'=>'kvat','readonly'=>'readonly'));?>
<?php echo form_input(array('name'=>'kbrutto','class'=>'short','id'=>'kbrutto','readonly'=>'readonly'));?>

My controller function (which works) looks like this:

public function pobierzProdukt($id)
    {
        $json = json_encode($this->Faktura_model->getProduct($id));
        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: Mon, 26 Jul 2027 05:00:00 GMT');
        header('Content-type: application/json');
        echo $json;
    }

My model function looks like this:

public function getProduct($id)
    {
        $q = 'SELECT product_vat, product_netto, product_brutto, product_jedn
            FROM products
            WHERE product_id="'.$id.'"';
        $w = $this->db->query($q);
        return json_encode($w->row_array());
    }


问:
Arrays.asList returns false
I just wanna check if my String[] array contains "n" or "s".

```<code>String[] coordinatesExample = {"57.8136°s", "28.3496°e"};

private void isContains(String[] coordinates) {

    boolean contains = Arrays.asList(coordinates).contains("s");
        if (contains) {
            System.out.println("It works!");
        }else {
            System.out.println("RAKAMAKAFO");
        }
</code>```

So I expected: "It works!", but
in fact: "RAKAMAKAFO"

What I did wrong?

答: When you do Arrays.asList(coordinates) you get the list containing two items: 57.8136°s and 28.3496°e. So using .contains("s") you test if any of your items is "s" which is obviously not the case.

Title: Arrays.asList returns false

Body:
I just wanna check if my String[] array contains "n" or "s".

String[] coordinatesExample = {"57.8136°s", "28.3496°e"};

private void isContains(String[] coordinates) {

    boolean contains = Arrays.asList(coordinates).contains("s");
        if (contains) {
            System.out.println("It works!");
        }else {
            System.out.println("RAKAMAKAFO");
        }

So I expected: "It works!", but
in fact: "RAKAMAKAFO"

What I did wrong?


问:
How to add SameSite:none in cookies via Web.Config
I am trying to add the samesite:none in all our cookies through web.config. I have tried the following using the rewrite rules but to no avail:</p>

```<code>  <outboundRules>
  <rule name="Add SameSite None">
            <match serverVariable="RESPONSE_Set_Cookie" pattern=".*" negate="true" />
            <action type="Rewrite" value="{R:0}; SameSite=none" />
  </outboundRules>
</code>```

答:
Try the following:</p>

```<code><rewrite>
  <outboundRules>
    <rule name="Add SameSite" preCondition="No SameSite">
      <match serverVariable="RESPONSE_Set_Cookie" pattern=".*" negate="false" />
      <action type="Rewrite" value="{R:0}; SameSite=none" />
      <conditions>
      </conditions>
    </rule>
    <preConditions>
      <preCondition name="No SameSite">
        <add input="{RESPONSE_Set_Cookie}" pattern="." />
        <add input="{RESPONSE_Set_Cookie}" pattern="; SameSite=none" negate="true" />
      </preCondition>
    </preConditions>
  </outboundRules>
</rewrite>
</code>```

Body:
I am trying to add the samesite:none in all our cookies through web.config. I have tried the following using the rewrite rules but to no avail:

  <outboundRules>
  <rule name="Add SameSite None">
            <match serverVariable="RESPONSE_Set_Cookie" pattern=".*" negate="true" />
            <action type="Rewrite" value="{R:0}; SameSite=none" />
  </outboundRules>

Body:
Try the following:

<rewrite>
  <outboundRules>
    <rule name="Add SameSite" preCondition="No SameSite">
      <match serverVariable="RESPONSE_Set_Cookie" pattern=".*" negate="false" />
      <action type="Rewrite" value="{R:0}; SameSite=none" />
      <conditions>
      </conditions>
    </rule>
    <preConditions>
      <preCondition name="No SameSite">
        <add input="{RESPONSE_Set_Cookie}" pattern="." />
        <add input="{RESPONSE_Set_Cookie}" pattern="; SameSite=none" negate="true" />
      </preCondition>
    </preConditions>
  </outboundRules>
</rewrite>


问:
How can I check if code is executed in the IPython notebook?
I have some Python code example I'd like to share that should do something different if executed in the terminal Python / IPython or in the IPython notebook.

How can I check from my Python code if it's running in the IPython notebook?

答:
How about something like this:

import sys

inJupyter = sys.argv[-1].endswith('json')

print(inJupyter);
```


问:
In ReactJS, using array index as key is said to not work well, but I can't make it not work well?
I can't make it not work well if I use index as the key. The only way is if I mutate the array and use index as the key. But since the docs says not to mutate the state (the array), so if that's the case, I can't make it not work well, contrary to what the docs is stating. How can I show that it may break?

function App() {
  const [arr, setArr] = React.useState(["A","B","C"]);

  function toggleSortOrder() {
    let newArr = [...arr];
    newArr.reverse();
    console.log(JSON.stringify(newArr));
    setArr(newArr);
  }

  return (

        { arr.map((e, i) =>
{ e }
) }

      <button onClick={toggleSortOrder} >Toggle Sort Order</button>

  )
}

ReactDOM.render(<App />, document.querySelector("#root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.12.0/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div></code>```

I can make it break if I mutate the state, which the docs says should not be done:

function App() {
  const [arr, setArr] = React.useState(["A","B","C"]);

  function toggleSortOrder() {
    arr.reverse();
    console.log(JSON.stringify(arr));
    setArr(arr);
  }

  return (

        { arr.map((e, i) =>
{ e }
) }

      <button onClick={toggleSortOrder} >Toggle Sort Order</button>

  )
}

ReactDOM.render(<App />, document.querySelector("#root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.12.0/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div></code>```

But I can't even break it if I mutate the state and use index as the key, if it is a class component:

class App extends React.Component {
  state = { arr: ["A","B","C"] };

  toggleSortOrder() {
    this.state.arr.reverse();
    console.log(JSON.stringify(this.state.arr));
    this.setState({ arr: this.state.arr });
  }

  render() {
    return (

          { this.state.arr.map((e, i) =>
{ e }
) }

        <button onClick={this.toggleSortOrder.bind(this)} >Toggle Sort Order</button>

    );
  }
}

ReactDOM.render(<App />, document.querySelector("#root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.12.0/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div></code>```

答:
The reality is that using the index of the map function will work, it is not recommended because it is an anti-pattern:

If the array changes via add or removing an element, or modifying the number of elements in the array, React will assume that the DOM element represents the same component as before. Meaning the impact of using index could be unpredictable, such as two array items containing the same id.

It is therefore recommended that:

If your array elements contain a unique id, or you can form a unique id based on the structure, do so.

Use a global index such as a counter to help create dynamic ids... for example:

```<code>arr.map(elem => {
    counter++;
    return (
        <li key={elem + counter}>{ elem }</li>);
    );
});
</code>```

This way you ensure the key has a unique identifier.

Body:
I can't make it not work well if I use index as the key. The only way is if I mutate the array and use index as the key. But since the docs says not to mutate the state (the array), so if that's the case, I can't make it not work well, contrary to what the docs is stating. How can I show that it may break?

function App() {
  const [arr, setArr] = React.useState(["A","B","C"]);

  function toggleSortOrder() {
    let newArr = [...arr];
    newArr.reverse();
    console.log(JSON.stringify(newArr));
    setArr(newArr);
  }

  return (

        { arr.map((e, i) =>
{ e }
) }

      <button onClick={toggleSortOrder} >Toggle Sort Order</button>

  )
}

ReactDOM.render(<App />, document.querySelector("#root"));

I can make it break if I mutate the state, which the docs says should not be done:

function App() {
  const [arr, setArr] = React.useState(["A","B","C"]);

  function toggleSortOrder() {
    arr.reverse();
    console.log(JSON.stringify(arr));
    setArr(arr);
  }

  return (

        { arr.map((e, i) =>
{ e }
) }

      <button onClick={toggleSortOrder} >Toggle Sort Order</button>

  )
}

ReactDOM.render(<App />, document.querySelector("#root"));

But I can't even break it if I mutate the state and use index as the key, if it is a class component:

class App extends React.Component {
  state = { arr: ["A","B","C"] };

  toggleSortOrder() {
    this.state.arr.reverse();
    console.log(JSON.stringify(this.state.arr));
    this.setState({ arr: this.state.arr });
  }

  render() {
    return (

          { this.state.arr.map((e, i) =>
{ e }
) }

        <button onClick={this.toggleSortOrder.bind(this)} >Toggle Sort Order</button>

    );
  }
}

ReactDOM.render(<App />, document.querySelector("#root"));

Body:
The reality is that using the index of the map function will work, it is not recommended because it is an anti-pattern:

If the array changes via add or removing an element, or modifying the number of elements in the array, React will assume that the DOM element represents the same component as before. Meaning the impact of using index could be unpredictable, such as two array items containing the same id.

It is therefore recommended that:

If your array elements contain a unique id, or you can form a unique id based on the structure, do so.

Use a global index such as a counter to help create dynamic ids... for example:

arr.map(elem => {
    counter++;
    return (
        <li key={elem + counter}>{ elem }</li>);
    );
});

This way you ensure the key has a unique identifier.


答:
Read up on regex module re in python.

import re

l = '''NOVO NORDISK A/S    216757.000 SHS @ 5.15000000 EXDTE-22MAR19 PAYDTE-26MAR19 TAXABLE RECLAIMABLE TAXED AT .270000%,
 NOVO NORDISK A/S    205395.000 SHS @ 3.00000000 EXDTE-16AUG19 PAYDTE-20AUG19 TAXABLE RECLAIMABLE TAXED AT .270000%,
 NOVO NORDISK A/S    TAX RECLAIM PAID 79000.000 EX-DT:20MAR15 PY-DT:24MAR15 CURRENCY TIP # 1150790014348SIEMENS AG    89789.000 SHS @ 3.80000000 EXDATE-31JAN19 PAYDATE-04FEB19 TAXABLE RECLAIMABLE TAXED AT .263750%,
 UNILEVER NV    171208.000 SHS @ 0.38720000 EXDATE-14FEB19 PAYDATE-20MAR19 TAXABLE W/H @ SOURCE TAXED AT .150000%,
 ROYAL DUTCH SHELL PLC A SHS   568644.000 SHS @ 0.41810000 EXDTE-14FEB19 PAYDTE-25MAR19 TAXABLE W/H @ SOURCE TAXED AT .150000%,'''

print(re.findall(r'(?<=@)\s*\d*[.]\d*',l))
```

<p>EDIT: I didn't realize that you have substrings in a list, so here's one for that.</p>

<pre class="lang-py prettyprint-override"><code>import re

mylist = ['NOVO NORDISK A/S    216757.000 SHS @ 5.15000000 EXDTE-22MAR19 PAYDTE-26MAR19 TAXABLE RECLAIMABLE TAXED AT .270000%',
        'NOVO NORDISK A/S    205395.000 SHS @ 3.00000000 EXDTE-16AUG19 PAYDTE-20AUG19 TAXABLE RECLAIMABLE TAXED AT .270000%',
        'NOVO NORDISK A/S    TAX RECLAIM PAID 79000.000 EX-DT:20MAR15 PY-DT:24MAR15 CURRENCY TIP # 1150790014348SIEMENS AG    89789.000 SHS @ 3.80000000 EXDATE-31JAN19 PAYDATE-04FEB19 TAXABLE RECLAIMABLE TAXED AT .263750%',
        'UNILEVER NV    171208.000 SHS @ 0.38720000 EXDATE-14FEB19 PAYDATE-20MAR19 TAXABLE W/H @ SOURCE TAXED AT .150000%',
        'ROYAL DUTCH SHELL PLC A SHS   568644.000 SHS @ 0.41810000 EXDTE-14FEB19 PAYDTE-25MAR19 TAXABLE W/H @ SOURCE TAXED AT .150000%']

results = [re.search(r'(?<=@)\s*\d*[.]\d*',string).group() for string in mylist]

for res in results:
    print(res)
</code>```

Title: extract numerical values from strings in list that come directly after the "@ " symbol

Body:
Read up on regex module re in python.

import re

l = '''NOVO NORDISK A/S    216757.000 SHS @ 5.15000000 EXDTE-22MAR19 PAYDTE-26MAR19 TAXABLE RECLAIMABLE TAXED AT .270000%,
 NOVO NORDISK A/S    205395.000 SHS @ 3.00000000 EXDTE-16AUG19 PAYDTE-20AUG19 TAXABLE RECLAIMABLE TAXED AT .270000%,
 NOVO NORDISK A/S    TAX RECLAIM PAID 79000.000 EX-DT:20MAR15 PY-DT:24MAR15 CURRENCY TIP # 1150790014348SIEMENS AG    89789.000 SHS @ 3.80000000 EXDATE-31JAN19 PAYDATE-04FEB19 TAXABLE RECLAIMABLE TAXED AT .263750%,
 UNILEVER NV    171208.000 SHS @ 0.38720000 EXDATE-14FEB19 PAYDATE-20MAR19 TAXABLE W/H @ SOURCE TAXED AT .150000%,
 ROYAL DUTCH SHELL PLC A SHS   568644.000 SHS @ 0.41810000 EXDTE-14FEB19 PAYDTE-25MAR19 TAXABLE W/H @ SOURCE TAXED AT .150000%,'''

print(re.findall(r'(?<=@)\s*\d*[.]\d*',l))

EDIT: I didn't realize that you have substrings in a list, so here's one for that.

import re

mylist = ['NOVO NORDISK A/S    216757.000 SHS @ 5.15000000 EXDTE-22MAR19 PAYDTE-26MAR19 TAXABLE RECLAIMABLE TAXED AT .270000%',
        'NOVO NORDISK A/S    205395.000 SHS @ 3.00000000 EXDTE-16AUG19 PAYDTE-20AUG19 TAXABLE RECLAIMABLE TAXED AT .270000%',
        'NOVO NORDISK A/S    TAX RECLAIM PAID 79000.000 EX-DT:20MAR15 PY-DT:24MAR15 CURRENCY TIP # 1150790014348SIEMENS AG    89789.000 SHS @ 3.80000000 EXDATE-31JAN19 PAYDATE-04FEB19 TAXABLE RECLAIMABLE TAXED AT .263750%',
        'UNILEVER NV    171208.000 SHS @ 0.38720000 EXDATE-14FEB19 PAYDATE-20MAR19 TAXABLE W/H @ SOURCE TAXED AT .150000%',
        'ROYAL DUTCH SHELL PLC A SHS   568644.000 SHS @ 0.41810000 EXDTE-14FEB19 PAYDTE-25MAR19 TAXABLE W/H @ SOURCE TAXED AT .150000%']

results = [re.search(r'(?<=@)\s*\d*[.]\d*',string).group() for string in mylist]

for res in results:
    print(res)


问:
"Invalid object name" when executing a query from a linked server on SQL
I have created linked servers on SSMS before but I am having trouble with this particular server. The linked server has come back as successfully connected and I can see the available tables, however, when I do a simple select query it's as if it cannot locate any of the tables within the database.

Would anyone have any clue as to why i'm receiving this error ?

```<code>SELECT * FROM [AMP].[default].[Import_records]
</code>```

```<code>Msg 208, Level 16, State 1, Line 4
Invalid object name 'AMP.default.Import_records'.
</code>```

答:
Perhaps you would be better off with OPENQUERY:

```<code>SELECT *
FROM OPENQUERY(N'AMP',N'SELECT * FROM default.Import_records')OQ;
</code>```

You will be able to do this with 4 part naming, however, we're not getting the information we need to able be able to really answer with that solution.

Body:
I have created linked servers on SSMS before but I am having trouble with this particular server. The linked server has come back as successfully connected and I can see the available tables, however, when I do a simple select query it's as if it cannot locate any of the tables within the database.

Would anyone have any clue as to why i'm receiving this error ?

SELECT * FROM [AMP].[default].[Import_records]

Msg 208, Level 16, State 1, Line 4
Invalid object name 'AMP.default.Import_records'.

Body:
Perhaps you would be better off with OPENQUERY:

SELECT *
FROM OPENQUERY(N'AMP',N'SELECT * FROM default.Import_records')OQ;

You will be able to do this with 4 part naming, however, we're not getting the information we need to able be able to really answer with that solution.


问:
Changing data point shape of second y-axis with ggplot
In my example I created a second y-axis in ggplot.
Instead of changing the colour for the data points of the second y-axis I want to change the shape.
But, of course, I get the error Scale for 'shape' is already present. Adding another scale for 'shape', which will replace the existing scale.
In the end I want to have a circle for "Large" and a filled circle for "Small" for "Visits" of the second y-axis.

This is my code:

```<code>Treatment <- c(rep(c("T/T"), times = 6),rep(c("R/R"), times = 6))
Size <- c(rep(c("Large", "Large", "Large", "Small", "Small", "Small"), times = 2))
Areatime <- c(240, 220, 120, 60, 55, 75, 90, 45, 70, 115, 40, 30)
Visits <- c(30, 45, 45, 65, 55, 55, 25, 35, 45, 75, 65, 55)
Counts <- data.frame(Treatment, Size, Areatime, Visits)

Counts$Treatment <- factor(Counts$Treatment, levels=c("T/T","R/R"))
Counts$inter <- interaction(Counts$Treatment, Counts$Size)
str(Counts)

ggplot(Count, aes(x = Treatment, y = Areatime)) +
  geom_jitter(aes(y = Areatime, shape = Size, width = 0.3)) +
  scale_shape_manual(values = c(0, 15), name = "Areatime", breaks = c("Large", "Small"),
    labels = c("Large", "Small")) +
  geom_jitter(aes(y = Counts*3, colour = Size, width = 0.3)) +
  scale_y_continuous(sec.axis = sec_axis(~./3, name = "Relative Visits [%]"))+
  scale_colour_manual(values =c(1, 2), name="Visits", breaks=c("Large", "Small"),
                     labels=c("Large", "Small")) +
  theme(axis.text.x=element_blank(),
                 panel.grid.major = element_blank(),
                 panel.grid.minor = element_blank(),
                 axis.ticks.x = element_blank(),
                 axis.line.x = element_blank(),
                 axis.line.y = element_line("black")) +
  facet_grid(.~Treatment, scales="free", switch = "x") +
  labs(y = "Average Areatime [sec]")
</code>```

Plot of Example

答:
I played a bit around and it is not an elegant hack, but maybe it is good enough. You can use shape = 21 this is a fillable shape. Then you need to match the fill colour with the background color so it looks like it is not filled. There where some typo's in your example code. I hope I fixed them correctly.

```<code>Treatment <- c(rep(c("T/T"), times = 6),rep(c("R/R"), times = 6))
Size <- c(rep(c("Large", "Large", "Large", "Small", "Small", "Small"), times = 2))
Areatime <- c(240, 220, 120, 60, 55, 75, 90, 45, 70, 115, 40, 30) Visits <- c(30, 45, 45, 65, 55, 55, 25, 35, 45, 75, 65, 55)

Counts <- data.frame(Treatment, Size, Areatime, Visits)

Counts$Treatment <- factor(Counts$Treatment, levels=c("T/T","R/R"))
Counts$inter <- interaction(Counts$Treatment, Counts$Size) str(Counts)

ggplot(data = Counts,
       aes(x = Treatment,
           y = Areatime)) +   geom_jitter(aes(y = Areatime,
                  colour = Size,
                  shape = Size),
              size = 3,
              width = 0.3) +   scale_shape_manual(values = c(0, 15),
                     name = "Areatime",
                     breaks = c("Large", "Small"),
                     labels = c("Large", "Small")) +   scale_colour_manual(values = c(1, 2)) +   geom_jitter(aes(y = Visits,
                  fill = Size),
              shape = 21, # this shape we can fill, but will give a border
              size = 3,
              width = 0.3) +   scale_y_continuous(sec.axis = sec_axis(~./3, name = "Relative Visits [%]"))+   scale_fill_manual(values = c("grey95", "red"),
                    name = "Visits",
                    breaks = c("Large", "Small"),
                    labels = c("Large", "Small")) +   guides(colour = guide_legend(title = "Areatime")) +   theme(axis.text.x=element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.ticks.x = element_blank(),
        axis.line.x = element_blank(),
        axis.line.y = element_line("black")) +   facet_grid(. ~Treatment,
             scales="free",
             switch = "x") +   labs(y = "Average Areatime [sec]")
</code>```

This while produce:

Body:
In my example I created a second y-axis in ggplot.
Instead of changing the colour for the data points of the second y-axis I want to change the shape.
But, of course, I get the error Scale for 'shape' is already present. Adding another scale for 'shape', which will replace the existing scale.
In the end I want to have a circle for "Large" and a filled circle for "Small" for "Visits" of the second y-axis.

This is my code:

Treatment <- c(rep(c("T/T"), times = 6),rep(c("R/R"), times = 6))
Size <- c(rep(c("Large", "Large", "Large", "Small", "Small", "Small"), times = 2))
Areatime <- c(240, 220, 120, 60, 55, 75, 90, 45, 70, 115, 40, 30)
Visits <- c(30, 45, 45, 65, 55, 55, 25, 35, 45, 75, 65, 55)
Counts <- data.frame(Treatment, Size, Areatime, Visits)

Counts$Treatment <- factor(Counts$Treatment, levels=c("T/T","R/R"))
Counts$inter <- interaction(Counts$Treatment, Counts$Size)
str(Counts)

ggplot(Count, aes(x = Treatment, y = Areatime)) +
  geom_jitter(aes(y = Areatime, shape = Size, width = 0.3)) +
  scale_shape_manual(values = c(0, 15), name = "Areatime", breaks = c("Large", "Small"),
    labels = c("Large", "Small")) +
  geom_jitter(aes(y = Counts*3, colour = Size, width = 0.3)) +
  scale_y_continuous(sec.axis = sec_axis(~./3, name = "Relative Visits [%]"))+
  scale_colour_manual(values =c(1, 2), name="Visits", breaks=c("Large", "Small"),
                     labels=c("Large", "Small")) +
  theme(axis.text.x=element_blank(),
                 panel.grid.major = element_blank(),
                 panel.grid.minor = element_blank(),
                 axis.ticks.x = element_blank(),
                 axis.line.x = element_blank(),
                 axis.line.y = element_line("black")) +
  facet_grid(.~Treatment, scales="free", switch = "x") +
  labs(y = "Average Areatime [sec]")

Plot of Example

Body:
I played a bit around and it is not an elegant hack, but maybe it is good enough. You can use shape = 21 this is a fillable shape. Then you need to match the fill colour with the background color so it looks like it is not filled. There where some typo's in your example code. I hope I fixed them correctly.

Treatment <- c(rep(c("T/T"), times = 6),rep(c("R/R"), times = 6))
Size <- c(rep(c("Large", "Large", "Large", "Small", "Small", "Small"), times = 2))
Areatime <- c(240, 220, 120, 60, 55, 75, 90, 45, 70, 115, 40, 30) Visits <- c(30, 45, 45, 65, 55, 55, 25, 35, 45, 75, 65, 55)

Counts <- data.frame(Treatment, Size, Areatime, Visits)

Counts$Treatment <- factor(Counts$Treatment, levels=c("T/T","R/R"))
Counts$inter <- interaction(Counts$Treatment, Counts$Size) str(Counts)

ggplot(data = Counts,
       aes(x = Treatment,
           y = Areatime)) +   geom_jitter(aes(y = Areatime,
                  colour = Size,
                  shape = Size),
              size = 3,
              width = 0.3) +   scale_shape_manual(values = c(0, 15),
                     name = "Areatime",
                     breaks = c("Large", "Small"),
                     labels = c("Large", "Small")) +   scale_colour_manual(values = c(1, 2)) +   geom_jitter(aes(y = Visits,
                  fill = Size),
              shape = 21, # this shape we can fill, but will give a border
              size = 3,
              width = 0.3) +   scale_y_continuous(sec.axis = sec_axis(~./3, name = "Relative Visits [%]"))+   scale_fill_manual(values = c("grey95", "red"),
                    name = "Visits",
                    breaks = c("Large", "Small"),
                    labels = c("Large", "Small")) +   guides(colour = guide_legend(title = "Areatime")) +   theme(axis.text.x=element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.ticks.x = element_blank(),
        axis.line.x = element_blank(),
        axis.line.y = element_line("black")) +   facet_grid(. ~Treatment,
             scales="free",
             switch = "x") +   labs(y = "Average Areatime [sec]")

This while produce:


问:
Symfony difference between website-skeleton And framework-standard-edition
I'm a beginner in Symfony and I want to know what the differences between these two commands for creating a new project in Symfony.

using website-skeleton :

```<code>    composer create-project symfony/website-skeleton first-project
</code>```

using framework-standard-edition :

```<code>    composer create-project symfony/framework-standard-edition first-project
</code>```

答:
the composer create-project command looks up the entry on packagist that correlates to the second parameter.

So symfony/website-skeleton points to: https://packagist.org/packages/symfony/website-skeleton while symfony/framework-standard-edition points to: https://packagist.org/packages/symfony/framework-standard-edition which in turn point to their respective repositories on github, which may have different names (as is the case with the framework-standard-edition one)

Those pages contain the version numbers that are being installed. The website-skeleton uses symfony/flex (which adds its own definition to the composer.json in the flex-require section which is not shown on packagist, since it's non-standard stuff), which is not quite informative.

The website-skeleton is the bootstrap for a website on the current version of symfony (which may change in the future, so it may reference a static version at some point in the future or may restrict the version number in some way), which should be symfony 5 right now.

The framework-standard-edition is the bootstrap for a website on the old 3.4.x version of symfony, which probably won't change, since it's already restricted on the version number.

If you're starting on a new project with no restriction to an old php version, you should prefer the website-skeleton.

Body:
I'm a beginner in Symfony and I want to know what the differences between these two commands for creating a new project in Symfony.

using website-skeleton :

    composer create-project symfony/website-skeleton first-project

using framework-standard-edition :

    composer create-project symfony/framework-standard-edition first-project


问:
Using @Resource for Geode region after @EnableClusterDefinedRegions
My spring boot data geode @Controller endpoint sets up an rsocket response which @Autowired a service class from another package:

```<code>@Controller
public class RSocketController {
    private static final Logger log = LogManager.getLogger(RSocketController.class);

    @Autowired
    MyService myService;
</code>```

The myService class contains @Resource regions which were setup by @EnableClusterDefinedRegions from a Geode cluster.

```<code>@Resource
private Region<String, Request> request;
</code>```

When an rsocket request is sent to the endpoint the @Autowired service gives an error:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'request' available

I have some domain objects decorated with @Region that I also decorated with @Controller and @Configuration and these gave errors like:

```<code>Bean named 'request' is expected to be of type 'org.apache.geode.cache.Region' but was actually of type 'region.request'
</code>```

and

```<code>Bean named 'request' is expected to be of type org.apache.geode.cache.Region but was actually of type region.request$$EnhancerBySpringCGLIB$$5e6b7dd1
</code>```

When I turned on debug logs I see that the @EnableClusterDefinedRegions has somehow not triggered and therefore not setup the request region from the Geode cluster. Aaargh.

答: The problem resolved by adding @Component annotation to the @EnableClusterDefinedRegions class which was then seen by Spring Boot bean collector.

Body:
My spring boot data geode @Controller endpoint sets up an rsocket response which @Autowired a service class from another package:

@Controller
public class RSocketController {
    private static final Logger log = LogManager.getLogger(RSocketController.class);

    @Autowired
    MyService myService;

The myService class contains @Resource regions which were setup by @EnableClusterDefinedRegions from a Geode cluster.

@Resource
private Region<String, Request> request;

When an rsocket request is sent to the endpoint the @Autowired service gives an error:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'request' available

I have some domain objects decorated with @Region that I also decorated with @Controller and @Configuration and these gave errors like:

Bean named 'request' is expected to be of type 'org.apache.geode.cache.Region' but was actually of type 'region.request'

and

Bean named 'request' is expected to be of type org.apache.geode.cache.Region but was actually of type region.request$$EnhancerBySpringCGLIB$$5e6b7dd1

When I turned on debug logs I see that the @EnableClusterDefinedRegions has somehow not triggered and therefore not setup the request region from the Geode cluster. Aaargh.


问:
Calculating the silhouette coefficient in python
I run a code taken from this website for calculating Silhouette Coefficient, but the code is running with error

Here is the code

```<code>from sklearn import datasets
from sklearn.metrics import *
iris = datasets.load_iris()
col = iris.feature_names
name = iris.target_names
X = pd.DataFrame(iris.data, columns = col)
y = iris.target
s = silhouette_score(X.values, y, metric='euclidean',sample_size=50)
</code>```

The error is

```<code>---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-2e1432d3b9ce> in <module>
      4 col = iris.feature_names
      5 name = iris.target_names
----> 6 X = pd.DataFrame(iris.data, columns = col)
      7 y = iris.target
      8 s = silhouette_score(X.values, y, metric='euclidean',sample_size=50)

NameError: name 'pd' is not defined
</code>```

Any help?

答:
The pandas library is generally imported as pd.

Install it (if you don't have it already), then add

```<code>import pandas as pd
</code>```

and you're off to the races.

Body:
I run a code taken from this website for calculating Silhouette Coefficient, but the code is running with error

Here is the code

from sklearn import datasets
from sklearn.metrics import *
iris = datasets.load_iris()
col = iris.feature_names
name = iris.target_names
X = pd.DataFrame(iris.data, columns = col)
y = iris.target
s = silhouette_score(X.values, y, metric='euclidean',sample_size=50)

The error is

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-2e1432d3b9ce> in <module>
      4 col = iris.feature_names
      5 name = iris.target_names
----> 6 X = pd.DataFrame(iris.data, columns = col)
      7 y = iris.target
      8 s = silhouette_score(X.values, y, metric='euclidean',sample_size=50)

NameError: name 'pd' is not defined

Any help?

Body:
The pandas library is generally imported as pd.

Install it (if you don't have it already), then add

import pandas as pd

and you're off to the races.


问:
How can I use sprintf() for print to a char *?
I am doing a c program for an university project. I have the nex code:

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

...

int main(int argc, char const *argv[])
{
    ...
    char * resolve = 0;
    sprintf(resolve, "%s,%s\n", HTTP_HEADER, ERR_404);
    printf("%s", resolve);
    return 0;
}
</code>```

I am getting Segmentation Fault in the line of the sprintf, Is somehow manner to get this work.
P.D: HTTP_HEADER and ERR_404 are strings defined.

答:
The pointer resolve points to NULL.  When it is passed to sprintf, the function attempts to dereference that pointer.  Doing so invokes undefined behavior which in this case causes the program to crash.

Define resolve to instead be an array large enough to hold the resulting string.

```<code>char resolve[1000];
sprintf(resolve, "%s,%s\n", HTTP_HEADER, ERR_404);
</code>```

Alternately, you can call snprintf with a NULL pointer and a size of 0.  This will return the number of characters that would be written to the string.  You can then allocate exactly that much space (plus 1 for the null terminating byte) and call snprintf again.

```<code>int len = snprintf(NULL, 0, "%s,%s\n", HTTP_HEADER, ERR_404);
char resolve[len+1];
snprintf(resolve, len, "%s,%s\n", HTTP_HEADER, ERR_404);
</code>```

Body:
I am doing a c program for an university project. I have the nex code:

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

...

int main(int argc, char const *argv[])
{
    ...
    char * resolve = 0;
    sprintf(resolve, "%s,%s\n", HTTP_HEADER, ERR_404);
    printf("%s", resolve);
    return 0;
}

I am getting Segmentation Fault in the line of the sprintf, Is somehow manner to get this work.
P.D: HTTP_HEADER and ERR_404 are strings defined.

Body:
The pointer resolve points to NULL.  When it is passed to sprintf, the function attempts to dereference that pointer.  Doing so invokes undefined behavior which in this case causes the program to crash.

Define resolve to instead be an array large enough to hold the resulting string.

char resolve[1000];
sprintf(resolve, "%s,%s\n", HTTP_HEADER, ERR_404);

Alternately, you can call snprintf with a NULL pointer and a size of 0.  This will return the number of characters that would be written to the string.  You can then allocate exactly that much space (plus 1 for the null terminating byte) and call snprintf again.

int len = snprintf(NULL, 0, "%s,%s\n", HTTP_HEADER, ERR_404);
char resolve[len+1];
snprintf(resolve, len, "%s,%s\n", HTTP_HEADER, ERR_404);


问:
how to listen continuosly for instream or outstrem in sockets
I am making a chat application in android using TCP and has immplemented Sockets. Which is working but in case of receiving or sending only the first msg is considered.
eg. client:hi
server:hi
server:hows u?

so in this case hows u? is not accessible at client / server side. In both cases instream is closed after receiving once. Can any One suggest what could be the issues or how i can solve them???

答:
If it is not listening for server continuously, then there might be a problem with your code. Post your code.

Check if this fits your requirement.
Android chat functionality?


问:
Android Studio failed linking references
I am getting the following error in my Android Studio. This is after the recent update I did. My Android Studio version is 3.4, Gradle version is 5.5.1, plugin version is 3.4.2

Here is the error:

Android resource linking failed

```<code>warn: removing resource com.anirudh.gighub:string/com_facebook_loginview_logged_in_using_facebook_f1gender without required default value.
  F:\gigHub\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1437: error: resource dimen/smallTxtSize (aka com.anirudh.gighub:dimen/smallTxtSize) not found.
  F:\gigHub\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1438: error: resource drawable/facebook_signin_btn (aka com.anirudh.gighub:drawable/facebook_signin_btn) not found.
  error: failed linking references.****
</code>```

Here is the `build.gradle

```<code>//noinspection GradleCompatible
apply plugin: 'com.android.application'
android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.anirudh.gighub"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    testImplementation 'junit:junit:4.13-beta-3'
    implementation 'com.google.firebase:firebase-auth:18.1.0'
    implementation 'com.facebook.android:facebook-login:5.0.1'
    implementation 'com.github.ybq:Android-SpinKit:1.2.0'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation ` enter code here `
    'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code>```

答:
my problem was that when i used refactor to change one of my variables in class named "rating", it changed all the android:rating attributes to android:rate and that caused this problem.
for those who have this problem, check gradle build error exactly for more information. maybe that's because of your undefined xml attributes.</p>

Body:
I am getting the following error in my Android Studio. This is after the recent update I did. My Android Studio version is 3.4, Gradle version is 5.5.1, plugin version is 3.4.2

Here is the error:

Android resource linking failed

warn: removing resource com.anirudh.gighub:string/com_facebook_loginview_logged_in_using_facebook_f1gender without required default value.
  F:\gigHub\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1437: error: resource dimen/smallTxtSize (aka com.anirudh.gighub:dimen/smallTxtSize) not found.
  F:\gigHub\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1438: error: resource drawable/facebook_signin_btn (aka com.anirudh.gighub:drawable/facebook_signin_btn) not found.
  error: failed linking references.****

Here is the `build.gradle

//noinspection GradleCompatible
apply plugin: 'com.android.application'
android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.anirudh.gighub"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    testImplementation 'junit:junit:4.13-beta-3'
    implementation 'com.google.firebase:firebase-auth:18.1.0'
    implementation 'com.facebook.android:facebook-login:5.0.1'
    implementation 'com.github.ybq:Android-SpinKit:1.2.0'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation ` enter code here `
    'com.android.support.test.espresso:espresso-core:3.0.2'
}


问:
Python Check if given multiple substrings are in a list
I need to check if a couple of substrings are in a list. I found the following codes. But it takes only one string.  </p>

```<code>test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
subs = 'Geek'
res = [i for i in test_list if subs in i]
print ("All strings with given substring are : " + str(res))
</code>```

<p>What should I do if I want to find two substrings such as 'Geek' and 'Algo'. </p>

答:
it will get all matches as Geek is two times matches will contain two Geek

```<code>import re
test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
test_list = ' '.join(test_list)
subs = 'Geek,Algo'
matches = re.findall(r'Geek|Algo', test_list, re.IGNORECASE)
print(set(matches)
print(set((matches))
</code>```

if you want to get unique
just add this line

Body:
I need to check if a couple of substrings are in a list. I found the following codes. But it takes only one string.

test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
subs = 'Geek'
res = [i for i in test_list if subs in i]
print ("All strings with given substring are : " + str(res))

What should I do if I want to find two substrings such as 'Geek' and 'Algo'.

Body:
it will get all matches as Geek is two times matches will contain two Geek

import re
test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
test_list = ' '.join(test_list)
subs = 'Geek,Algo'
matches = re.findall(r'Geek|Algo', test_list, re.IGNORECASE)
print(set(matches)
print(set((matches))

if you want to get unique
just add this line


答:
Keys are primarily about performance. The tell react which old component corresponds to which new one, which in turn helps it quickly determine the minimal set of changes needed to update the dom. See documentation on reconciliation.

So the sense in which your code "breaks" is that react thinks it needs to edit the text inside each of the
's, when it was possible to rearrange them instead. You won't really notice any performance issues with your toy example, but you could construct other examples where it matters a lot more. Here's one where i'm rendering 20,000 rows, and moving one row to the end. Performance isn't great at all, but it's better if keys are used correctly instead of based on the index.

const exampleData = [];
for (let i = 0; i < 20000; i++) {
  exampleData[i] = {
    key: i,
    name: "Element " + i,
  }
}

function App() {
  const [useKeysWell, setUseKeysWell] = React.useState(false);
  const [data, setData] = React.useState(exampleData);

  function move() {
    setData(prev => {
      let newData = [...prev.slice(1), prev[0]];
      return newData;
    });
  }

  const before = Date.now();
  setTimeout(() => {
    console.log('reconciling and committing', Date.now() - before, 'ms (approx)');
  }, 0)

  return (

      <button onClick={move}>Move one</button>
      <button onClick={() => setUseKeysWell(prev => !prev)}>Use keys {useKeysWell ? "worse" : "better"} </button>

        { data.map((e, i) =>
{ e.name }
) }

  )
}

ReactDOM.render(<App />, document.querySelector("#root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.12.0/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div></code>```

With more complicated code, you could also cause problems if you have components with lifecycle hooks that you are expecting to run, but due to the incorrect keys the components are not being mounted/unmounted/updated the way you expect.

Title: In ReactJS, using array index as key is said to not work well, but I can't make it not work well?

Body:
Keys are primarily about performance. The tell react which old component corresponds to which new one, which in turn helps it quickly determine the minimal set of changes needed to update the dom. See documentation on reconciliation.

So the sense in which your code "breaks" is that react thinks it needs to edit the text inside each of the <li>'s, when it was possible to rearrange them instead. You won't really notice any performance issues with your toy example, but you could construct other examples where it matters a lot more. Here's one where i'm rendering 20,000 rows, and moving one row to the end. Performance isn't great at all, but it's better if keys are used correctly instead of based on the index.

const exampleData = [];
for (let i = 0; i < 20000; i++) {
  exampleData[i] = {
    key: i,
    name: "Element " + i,
  }
}

function App() {
  const [useKeysWell, setUseKeysWell] = React.useState(false);
  const [data, setData] = React.useState(exampleData);

  function move() {
    setData(prev => {
      let newData = [...prev.slice(1), prev[0]];
      return newData;
    });
  }

  const before = Date.now();
  setTimeout(() => {
    console.log('reconciling and committing', Date.now() - before, 'ms (approx)');
  }, 0)

  return (
    <div>
      <button onClick={move}>Move one</button>
      <button onClick={() => setUseKeysWell(prev => !prev)}>Use keys {useKeysWell ? "worse" : "better"} </button>
      <ul key={useKeysWell}>
        { data.map((e, i) => <li key={useKeysWell ? e.key : i}>{ e.name }</li>) }
      </ul>
    </div>
  )
}

ReactDOM.render(<App />, document.querySelector("#root"));

<script src="https://unpkg.com/react@16.12.0/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div>

With more complicated code, you could also cause problems if you have components with lifecycle hooks that you are expecting to run, but due to the incorrect keys the components are not being mounted/unmounted/updated the way you expect.