问:
Compare elements from 2 singly-linked lists and program (usually) crash
I have the project to do. Assumptions are like that:

From file with words i need to read only alphabetic words (into list called Words - code below) - I did it by use isalpha() function from  lib. Each element of list contain one word

From input file (another file) I need to all read lines (line by line) and save them into another list called Data. (code below) Ofc I needed to split the sentence into words, that's why I used list in list.

Now I need check if words from first file are in the second file. If they exist, I must say in which lines. The result I need to save in output file.

I need to process big amount of data, files are few MB of words (like 250k words).

My problem is such that my program worked on small amount of data, like few words. Idk where the problem is. Maybe with allocation of memory? I'm new in C and have to do this project ._ . I have like 500 lines of functions code. I can share it on something like pastebin, or .zip file, or I can talk on Messenger if you have some time.

Here are fragments (structs):

```<code>struct Words
{
  char* word;
  struct Words* pNext;
};

struct Data
{
  int lineNumber;
  struct Words* words;
  struct Data* pNext;
};

typedef struct Data Data;
typedef struct Words Words;
</code>```

Main:

```<code>  PrintStartMessage();

  const char* ListOfWords = FindArgument(argc, argv, "-l");
  const char* Input = FindArgument(argc, argv, "-i");
  const char* Output = FindArgument(argc, argv, "-o");

  if(!(IsNameWOExtension(ListOfWords) || IsTxtFile(ListOfWords)) || (!(IsNameWOExtension(Input) || IsTxtFile(Input))))
  {
    ErrorNameFileMessage();
    return 0;
  } /* check if parameters are correct (no extension or filename.txt) */

  Data* data = NULL;
  Words* words = NULL;

  FILE* InputWords = NULL;
  FILE* InputFile = NULL;
  FILE* OutputFile = NULL;
  if(ReadWordsToStruct(&InputWords, ListOfWords, "r", &words) == 0)
  {
    DeleteWords(&words);
    DeleteData(&data);
    return 0;
  }

  if(ReadDataToStruct(&InputFile, Input, "r", &data) == 0)
  {
    DeleteWords(&words);
    DeleteData(&data);
    return 0;
  }

  if(SaveInformationToFile(&OutputFile, Output, "w", words, data) == 0)
  {
    DeleteWords(&words);
    DeleteData(&data);
    return 0;
  }

  PrintSuccessMessage();
  DeleteWords(&words);
  DeleteData(&data);
</code>```

Few functions:

```<code>const char* FindArgument(int argc, char* const argv[], char* arg)
{
  int i = 1;
  for (i = 1; i < argc; i++)
  {
    if(strcmp(arg, argv[i]) == 0)
      return argv[i+1];
  }
}

int IsTxtFile(const char* name)
{
  const char* txt = "txt";
  char fileExtension[4] = "";
  int save = 0; /* index of '.' in name */

  int i = 0;
  for(i = 0; i<strlen(name); i++)
  {
    if(name[i] == '.')
    {
      save = i;
      break;
    }
  }

  if(strlen(name) - (save + 1) > 3) /* if after '.' there are more than 3 characters */
    return 0; /* file isn't txt type */

  int counter = 0;
  for(i = save+1; i < save+4; i++)
  {
    if(name[i] != '\0')
    {
      fileExtension[counter] = name[i];
      counter++;
    }
    else
      return 0; /* file isn't txt type */
  }
  if(strcmp(txt,fileExtension) == 0)
    return 1; /* file is txt type */

  return 0; /* file isn't txt type */
}

int OpenFile(FILE** file, const char* filename, char* mode)
{
  if(IsTxtFile(filename) == 1)
    *file = fopen(filename, mode);
  else
  {
    char* something = ConcatenateStrings(filename, ".txt");
    *file = fopen(something, mode);
    free(something);
  }

  if(*file != NULL)
    return 1;
  return 0;
}

void CloseFile(FILE** file)
{
  fclose(*file);
}

char* ConcatenateStrings(const char* string1, char* string2)
{
  char *result = (char *)malloc(strlen(string1) + strlen(string2) + 1);
  strcpy(result, string1);
  strcat(result, string2);

  return result;
}

int IsAlphabetical(char* string)
{
  int i = 0;
  for(i = 0; i < strlen(string); i++)
  {
    if(!isalpha(string[i]))
      return 0; /* isalpha() checks if the passed character is alphabetic */
  }
  return 1;
}

// singly-linked list operations - Words
void AddWords(Words** head, char* word)
{
  Words* temp = *head;
  Words* newWord = (Words *)malloc(sizeof(Words));
  newWord->word = (char *)malloc((strlen(word)+1)*sizeof(char));

  strcpy(newWord->word, word);
  newWord->pNext = NULL;

  if (*head == NULL)
     *head = newWord;
  else
  {
    while(temp->pNext != NULL)
      temp = temp->pNext;

    temp->pNext = newWord;
  }
}

void ReadWordsFromFile(Words** words, FILE* file)
{
  char line[1024];
  char delimiters[] = " \n\0";
  while(fgets(line, sizeof(line), file))
  {
    char* token = strtok(line, delimiters);
    while(token != NULL)
    {
      if((IsAlphabetical(token) == 1) && (SearchInWords(*words, token)) == 0)
      {
        char* string = (char *)malloc((strlen(token)+1)*sizeof(char));
        strcpy(string, token);
        AddWords(words, string);
        free(string);
      }
      token = strtok(NULL, delimiters);
    }
  }
}

int ReadWordsToStruct(FILE** file, const char* filename, char* mode, Words** head)
{
  if(OpenFile(file, filename, mode) == 1)
  {
    ReadWordsFromFile(head, *file);
    CloseFile(file);
    return 1;
  }
  else
  {
    ErrorOpeningFile(filename);
    return 0;
  }
}

// singly-linked list operation - Data
void AddData(Data** head, char* sentence, int number)
{
  Words* words = NULL;
  char delimiters[] = " \n\0";
  char* token = strtok(sentence, delimiters);
  while(token != NULL)
  {
    if(IsAlphabetical(token) == 1)
    {
      char* string = (char *)malloc((strlen(token)+1)*sizeof(char));
      strcpy(string, token);
      AddWords(&words, string);
      free(string);
    }
    token = strtok(NULL, delimiters);
  }

  Data* temp = *head;
  Data* newData = (Data *)malloc(sizeof(Data));

  newData->lineNumber = number;
  newData->words = words;
  newData->pNext = NULL;

  if (*head == NULL)
     *head = newData;
  else
  {
    while(temp->pNext != NULL)
      temp = temp->pNext;

    temp->pNext = newData;
  }
}

void ReadDataFromFile(Data** data, FILE* file)
{
  char line[4096]; /* max-length string */
  int lineCounter = 1;
  while(fgets(line, sizeof(line), file))
  {
    if(IsEmptyString(line) != 1)
    {
      AddData(data, line, lineCounter);
      lineCounter++;
    }
  }
}

int ReadDataToStruct(FILE** file, const char* filename, char* mode, Data** head)
{
  if(OpenFile(file, filename, mode) == 1)
  {
    ReadDataFromFile(head, *file);
    CloseFile(file);
    return 1;
  }
  else
  {
    ErrorOpeningFile(filename);
    return 0;
  }
}

// processing data

int NumberOfWords(Words* head)
{
  int count = 0;
  Words* temp = head;
  while (temp != NULL)
  {
    count++;
    temp = temp->pNext;
  }
  DeleteWords(&temp);
  return count;
}

char* GetWord(Words* head, int wordNumber)
{
  int i = 0;
  for (i = 0; i < wordNumber; i++)
    head = head->pNext;
  return head->word;
}

void FindWordInData(FILE** file, Data* head, char* word)
{
  fprintf(*file, "Word \'%s\' occurs in lines: \n", word);

  Data* temp = head;
  Words* tempWord = temp->words;
  int numberOfOccurrences = 0;
  int j = 0;

  while(temp->pNext != NULL)
 {
   j = 0;
   while(tempWord->pNext != NULL)
   {
     char* wordFromData = GetWord(temp->words, j);
     if(strcmp(word, wordFromData) == 0)
     {
       fprintf(*file, "%d ", temp->lineNumber);
       numberOfOccurrences++;
       break;
     }
     j++;
     tempWord = tempWord->pNext;
     free(wordFromData);
   }
   DeleteWords(&tempWord);
   temp = temp->pNext;
 }
 if(numberOfOccurrences == 0)
  fprintf(*file,"-\n");
 else
  fprintf(*file,"\n");
 DeleteData(&temp);
}

int SaveInformationToFile(FILE** file, const char* filename, char* mode, Words* words, Data* data)
{
  if(OpenFile(file, filename, mode) == 1)
  {
    int i = 0;
    for(i = 0; i < NumberOfWords(words); i++)
    {
      char* tempWord = GetWord(words, i);
      FindWordInData(file, data, tempWord);
      free(tempWord);
    }
    CloseFile(file);
    return 1;
  }
  else
  {
    ErrorCreatingFile();
    return 0;
  }
}

// deleting list

void DeleteData(Data** head)
{
  Data* temp = *head;
  while (temp != NULL)
  {
      Data* next = temp->pNext;
      DeleteWords(&temp->words);
      free(temp);
      temp = next;
  }
  free(temp); /* to check that */
  *head = NULL;
}

void DeleteWords(Words** head)
{
  Words* temp = *head;
  while (temp != NULL)
  {
      Words* next = temp->pNext;
      free(temp->word);
      free(temp);
      temp = next;
  }
  free(temp); /* to check that */
  *head = NULL;
</code>```

}

答:
Solved:

function GetWord returns pointer instead of string.
Solution:

```<code>char* GetWord(Words* head, int wordNumber)
{
  int i = 0;
  for (i = 0; i < wordNumber; i++)
    head = head->pNext;
  char* result = (char *)malloc(sizeof(char)*(strlen(head->word) + 1));
  strcpy(result, head->word);
  return result;
}
</code>```

Body:
I have the project to do. Assumptions are like that:

From file with words i need to read only alphabetic words (into list called Words - code below) - I did it by use isalpha() function from  lib. Each element of list contain one word

From input file (another file) I need to all read lines (line by line) and save them into another list called Data. (code below) Ofc I needed to split the sentence into words, that's why I used list in list.

Now I need check if words from first file are in the second file. If they exist, I must say in which lines. The result I need to save in output file.

I need to process big amount of data, files are few MB of words (like 250k words).

My problem is such that my program worked on small amount of data, like few words. Idk where the problem is. Maybe with allocation of memory? I'm new in C and have to do this project ._ . I have like 500 lines of functions code. I can share it on something like pastebin, or .zip file, or I can talk on Messenger if you have some time.

Here are fragments (structs):

struct Words
{
  char* word;
  struct Words* pNext;
};

struct Data
{
  int lineNumber;
  struct Words* words;
  struct Data* pNext;
};

typedef struct Data Data;
typedef struct Words Words;

Main:

  PrintStartMessage();

  const char* ListOfWords = FindArgument(argc, argv, "-l");
  const char* Input = FindArgument(argc, argv, "-i");
  const char* Output = FindArgument(argc, argv, "-o");

  if(!(IsNameWOExtension(ListOfWords) || IsTxtFile(ListOfWords)) || (!(IsNameWOExtension(Input) || IsTxtFile(Input))))
  {
    ErrorNameFileMessage();
    return 0;
  } /* check if parameters are correct (no extension or filename.txt) */

  Data* data = NULL;
  Words* words = NULL;

  FILE* InputWords = NULL;
  FILE* InputFile = NULL;
  FILE* OutputFile = NULL;
  if(ReadWordsToStruct(&InputWords, ListOfWords, "r", &words) == 0)
  {
    DeleteWords(&words);
    DeleteData(&data);
    return 0;
  }

  if(ReadDataToStruct(&InputFile, Input, "r", &data) == 0)
  {
    DeleteWords(&words);
    DeleteData(&data);
    return 0;
  }

  if(SaveInformationToFile(&OutputFile, Output, "w", words, data) == 0)
  {
    DeleteWords(&words);
    DeleteData(&data);
    return 0;
  }

  PrintSuccessMessage();
  DeleteWords(&words);
  DeleteData(&data);

Few functions:

const char* FindArgument(int argc, char* const argv[], char* arg)
{
  int i = 1;
  for (i = 1; i < argc; i++)
  {
    if(strcmp(arg, argv[i]) == 0)
      return argv[i+1];
  }
}

int IsTxtFile(const char* name)
{
  const char* txt = "txt";
  char fileExtension[4] = "";
  int save = 0; /* index of '.' in name */

  int i = 0;
  for(i = 0; i<strlen(name); i++)
  {
    if(name[i] == '.')
    {
      save = i;
      break;
    }
  }

  if(strlen(name) - (save + 1) > 3) /* if after '.' there are more than 3 characters */
    return 0; /* file isn't txt type */

  int counter = 0;
  for(i = save+1; i < save+4; i++)
  {
    if(name[i] != '\0')
    {
      fileExtension[counter] = name[i];
      counter++;
    }
    else
      return 0; /* file isn't txt type */
  }
  if(strcmp(txt,fileExtension) == 0)
    return 1; /* file is txt type */

  return 0; /* file isn't txt type */
}

int OpenFile(FILE** file, const char* filename, char* mode)
{
  if(IsTxtFile(filename) == 1)
    *file = fopen(filename, mode);
  else
  {
    char* something = ConcatenateStrings(filename, ".txt");
    *file = fopen(something, mode);
    free(something);
  }

  if(*file != NULL)
    return 1;
  return 0;
}

void CloseFile(FILE** file)
{
  fclose(*file);
}

char* ConcatenateStrings(const char* string1, char* string2)
{
  char *result = (char *)malloc(strlen(string1) + strlen(string2) + 1);
  strcpy(result, string1);
  strcat(result, string2);

  return result;
}

int IsAlphabetical(char* string)
{
  int i = 0;
  for(i = 0; i < strlen(string); i++)
  {
    if(!isalpha(string[i]))
      return 0; /* isalpha() checks if the passed character is alphabetic */
  }
  return 1;
}

// singly-linked list operations - Words
void AddWords(Words** head, char* word)
{
  Words* temp = *head;
  Words* newWord = (Words *)malloc(sizeof(Words));
  newWord->word = (char *)malloc((strlen(word)+1)*sizeof(char));

  strcpy(newWord->word, word);
  newWord->pNext = NULL;

  if (*head == NULL)
     *head = newWord;
  else
  {
    while(temp->pNext != NULL)
      temp = temp->pNext;

    temp->pNext = newWord;
  }
}

void ReadWordsFromFile(Words** words, FILE* file)
{
  char line[1024];
  char delimiters[] = " \n\0";
  while(fgets(line, sizeof(line), file))
  {
    char* token = strtok(line, delimiters);
    while(token != NULL)
    {
      if((IsAlphabetical(token) == 1) && (SearchInWords(*words, token)) == 0)
      {
        char* string = (char *)malloc((strlen(token)+1)*sizeof(char));
        strcpy(string, token);
        AddWords(words, string);
        free(string);
      }
      token = strtok(NULL, delimiters);
    }
  }
}

int ReadWordsToStruct(FILE** file, const char* filename, char* mode, Words** head)
{
  if(OpenFile(file, filename, mode) == 1)
  {
    ReadWordsFromFile(head, *file);
    CloseFile(file);
    return 1;
  }
  else
  {
    ErrorOpeningFile(filename);
    return 0;
  }
}

// singly-linked list operation - Data
void AddData(Data** head, char* sentence, int number)
{
  Words* words = NULL;
  char delimiters[] = " \n\0";
  char* token = strtok(sentence, delimiters);
  while(token != NULL)
  {
    if(IsAlphabetical(token) == 1)
    {
      char* string = (char *)malloc((strlen(token)+1)*sizeof(char));
      strcpy(string, token);
      AddWords(&words, string);
      free(string);
    }
    token = strtok(NULL, delimiters);
  }

  Data* temp = *head;
  Data* newData = (Data *)malloc(sizeof(Data));

  newData->lineNumber = number;
  newData->words = words;
  newData->pNext = NULL;

  if (*head == NULL)
     *head = newData;
  else
  {
    while(temp->pNext != NULL)
      temp = temp->pNext;

    temp->pNext = newData;
  }
}

void ReadDataFromFile(Data** data, FILE* file)
{
  char line[4096]; /* max-length string */
  int lineCounter = 1;
  while(fgets(line, sizeof(line), file))
  {
    if(IsEmptyString(line) != 1)
    {
      AddData(data, line, lineCounter);
      lineCounter++;
    }
  }
}

int ReadDataToStruct(FILE** file, const char* filename, char* mode, Data** head)
{
  if(OpenFile(file, filename, mode) == 1)
  {
    ReadDataFromFile(head, *file);
    CloseFile(file);
    return 1;
  }
  else
  {
    ErrorOpeningFile(filename);
    return 0;
  }
}

// processing data

int NumberOfWords(Words* head)
{
  int count = 0;
  Words* temp = head;
  while (temp != NULL)
  {
    count++;
    temp = temp->pNext;
  }
  DeleteWords(&temp);
  return count;
}

char* GetWord(Words* head, int wordNumber)
{
  int i = 0;
  for (i = 0; i < wordNumber; i++)
    head = head->pNext;
  return head->word;
}

void FindWordInData(FILE** file, Data* head, char* word)
{
  fprintf(*file, "Word \'%s\' occurs in lines: \n", word);

  Data* temp = head;
  Words* tempWord = temp->words;
  int numberOfOccurrences = 0;
  int j = 0;

  while(temp->pNext != NULL)
 {
   j = 0;
   while(tempWord->pNext != NULL)
   {
     char* wordFromData = GetWord(temp->words, j);
     if(strcmp(word, wordFromData) == 0)
     {
       fprintf(*file, "%d ", temp->lineNumber);
       numberOfOccurrences++;
       break;
     }
     j++;
     tempWord = tempWord->pNext;
     free(wordFromData);
   }
   DeleteWords(&tempWord);
   temp = temp->pNext;
 }
 if(numberOfOccurrences == 0)
  fprintf(*file,"-\n");
 else
  fprintf(*file,"\n");
 DeleteData(&temp);
}

int SaveInformationToFile(FILE** file, const char* filename, char* mode, Words* words, Data* data)
{
  if(OpenFile(file, filename, mode) == 1)
  {
    int i = 0;
    for(i = 0; i < NumberOfWords(words); i++)
    {
      char* tempWord = GetWord(words, i);
      FindWordInData(file, data, tempWord);
      free(tempWord);
    }
    CloseFile(file);
    return 1;
  }
  else
  {
    ErrorCreatingFile();
    return 0;
  }
}

// deleting list

void DeleteData(Data** head)
{
  Data* temp = *head;
  while (temp != NULL)
  {
      Data* next = temp->pNext;
      DeleteWords(&temp->words);
      free(temp);
      temp = next;
  }
  free(temp); /* to check that */
  *head = NULL;
}

void DeleteWords(Words** head)
{
  Words* temp = *head;
  while (temp != NULL)
  {
      Words* next = temp->pNext;
      free(temp->word);
      free(temp);
      temp = next;
  }
  free(temp); /* to check that */
  *head = NULL;

}

Body:
Solved:

function GetWord returns pointer instead of string.
Solution:

char* GetWord(Words* head, int wordNumber)
{
  int i = 0;
  for (i = 0; i < wordNumber; i++)
    head = head->pNext;
  char* result = (char *)malloc(sizeof(char)*(strlen(head->word) + 1));
  strcpy(result, head->word);
  return result;
}


来源: stackexchange

问:
How to import variables and style rules into one file
I have theme.scss file which contains the style of my website and it's content looks similar to this

```<code>//Direction variable[rtl|ltr]
$direction: ltr;
//Theme style
.selector-1 {
    color: red;
}
.selector-2 {
    color: red;
    @if $direction == ltr {
        right: 9px;
    } @else {
        left: 9px;
    }
}
</code>```

I need to separate the $direction variable from the style. I need to create 2 new files; ltr.scss & rtl.scss. If the locale is ltr then I'll call ltr.scss from my angular component, else I'll call rtl.scss.

What I did so far:

theme.scss

```<code>.selector-1 {
    color: red;
}
.selector-2 {
    color: red;
    @if $direction == ltr {
        right: 9px;
    } @else {
        left: 9px;
    }
}
</code>```

ltr.scss

```<code>$direction: ltr;
@import './theme.scss';
</code>```

rtl.scss

```<code>$direction: rtl;
@import './theme.scss';
</code>```

But I'm getting SassError: Undefined variable. for $direction.

I understand that I should import either ltr.scss or rtl.scss in theme.scss file to remove the error, but In this case I'll have to create another two new files theme-ltr.scss & theme-rtl.scss; each of them has redundant code.

How can I create only two new files which I'll include in my angular component (one for ltr and the other for rtl), and make each one of them declare the direction variable & import the website theme file?

答:
When you replace the @import with @use you can use the with keyword to pass a variables through a configuration to the imported file. It would look like this:

```<code>@use './theme.scss' with (
  $direction: ltr
);
</code>```

For more information about @use and with you can take a look at the official SASS documentation: https://sass-lang.com/documentation/at-rules/use#configuration

ContentLicense: CC BY-SA 4.0

Body:
I have theme.scss file which contains the style of my website and it's content looks similar to this

//Direction variable[rtl|ltr]
$direction: ltr;
//Theme style
.selector-1 {
    color: red;
}
.selector-2 {
    color: red;
    @if $direction == ltr {
        right: 9px;
    } @else {
        left: 9px;
    }
}

I need to separate the $direction variable from the style. I need to create 2 new files; ltr.scss & rtl.scss. If the locale is ltr then I'll call ltr.scss from my angular component, else I'll call rtl.scss.

What I did so far:

theme.scss

.selector-1 {
    color: red;
}
.selector-2 {
    color: red;
    @if $direction == ltr {
        right: 9px;
    } @else {
        left: 9px;
    }
}

ltr.scss

$direction: ltr;
@import './theme.scss';

rtl.scss

$direction: rtl;
@import './theme.scss';

But I'm getting SassError: Undefined variable. for $direction.

I understand that I should import either ltr.scss or rtl.scss in theme.scss file to remove the error, but In this case I'll have to create another two new files theme-ltr.scss & theme-rtl.scss; each of them has redundant code.

How can I create only two new files which I'll include in my angular component (one for ltr and the other for rtl), and make each one of them declare the direction variable & import the website theme file?

Body:
When you replace the @import with @use you can use the with keyword to pass a variables through a configuration to the imported file. It would look like this:

@use './theme.scss' with (
  $direction: ltr
);

For more information about @use and with you can take a look at the official SASS documentation: https://sass-lang.com/documentation/at-rules/use#configuration


问:
Convert audio into raw PCM data of type [Double]
I'm trying to convert a recorded audio file into raw PCM data of type [Double]. I found a way to load and convert audio to PCM data of the type [Float32] like this:

```<code>    // load audio from path
    let file = try! AVAudioFile(forReading: self.soundFileURL)
    // declare format
    let format = AVAudioFormat(commonFormat: .PCMFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: 1, interleaved: false)
    // initialize audiobuffer with the length of the audio file
    let buf = AVAudioPCMBuffer(PCMFormat: format, frameCapacity: UInt32(file.length))
    // write to file
    try! file.readIntoBuffer(buf)
    // copy to array
    let floatArray = Array(UnsafeBufferPointer(start: buf.floatChannelData[0], count:Int(buf.frameLength)))
</code>```

The problem is, I need the data as [Double] and AVAudioPCMBuffer() only knows the .PCMFormatFloat32. Does anybody know a workaround?
Thank you.

答:
updated to Swift 5

```<code>        do {
            let file = try AVAudioFile(forReading: soundFileURL)
            if let format = AVAudioFormat(commonFormat: .pcmFormatFloat64, sampleRate: file.fileFormat.sampleRate, channels: file.fileFormat.channelCount, interleaved: false), let buf = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(file.length)){
                try file.read(into: buf)
                let abl = Array(UnsafeBufferPointer(start: buf.audioBufferList, count: Int(buf.audioBufferList.pointee.mNumberBuffers)))

                let buffer = buf.audioBufferList[0].mBuffers
                let mDataList = Array(UnsafeMutableRawBufferPointer(start: buffer.mData, count: Int(buffer.mDataByteSize)))
            }
        } catch{
            print("Audio Error: \(error)")
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to convert a recorded audio file into raw PCM data of type [Double]. I found a way to load and convert audio to PCM data of the type [Float32] like this:

    // load audio from path
    let file = try! AVAudioFile(forReading: self.soundFileURL)
    // declare format
    let format = AVAudioFormat(commonFormat: .PCMFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: 1, interleaved: false)
    // initialize audiobuffer with the length of the audio file
    let buf = AVAudioPCMBuffer(PCMFormat: format, frameCapacity: UInt32(file.length))
    // write to file
    try! file.readIntoBuffer(buf)
    // copy to array
    let floatArray = Array(UnsafeBufferPointer(start: buf.floatChannelData[0], count:Int(buf.frameLength)))

The problem is, I need the data as [Double] and AVAudioPCMBuffer() only knows the .PCMFormatFloat32. Does anybody know a workaround?
Thank you.

Body:
updated to Swift 5

        do {
            let file = try AVAudioFile(forReading: soundFileURL)
            if let format = AVAudioFormat(commonFormat: .pcmFormatFloat64, sampleRate: file.fileFormat.sampleRate, channels: file.fileFormat.channelCount, interleaved: false), let buf = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(file.length)){
                try file.read(into: buf)
                let abl = Array(UnsafeBufferPointer(start: buf.audioBufferList, count: Int(buf.audioBufferList.pointee.mNumberBuffers)))

                let buffer = buf.audioBufferList[0].mBuffers
                let mDataList = Array(UnsafeMutableRawBufferPointer(start: buffer.mData, count: Int(buffer.mDataByteSize)))
            }
        } catch{
            print("Audio Error: \(error)")
        }


问:
moviepy progress bar in wxPython statusbar
Running on Python 3.x on Windows 10

I'm working on a script to help automate compiling a .tiff image sequence into a video. I'm using wxPython to build the GUI. First I create the window class and set a global variable for the window.

```<code>global main_window
main_window = self
</code>```

Then I have a function I use to write to the statusbar and also print the values to console(occasionally I also add code to write a log file from the text I send to this function).

```<code>def update_status_bar(window, text):
    status = str(text)
    window.statusbar.SetStatusText(status)
    print(status)
    window.Refresh()
    window.Update()
    wx.SafeYield(win=None, onlyIfNeeded=False)
</code>```

This is the moviePy function I wrote to convert the image sequence into ta video.

```<code>def video_from_sequence(image_sequence, video, fps):
    img = []
    update_status_bar(main_window, 'Getting Image Directory')
    path = os.path.dirname(os.path.realpath(image_sequence))
    print(path)
    update_status_bar(main_window, 'Getting List of Image Files')
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith('.tiff'):
                img.append(file)
    os.chdir(path)
    update_status_bar(main_window, 'Creating Video From Image Sequence')
    clip = ImageSequenceClip(img, fps=fps)
    update_status_bar(main_window, clip.write_videofile(video, fps=fps))
</code>```

The print to console does show the progress, however the statusbar is not populating with the current progress of the process. Because I'd like to eventually have this run as a .pyw, where the statusbar shows the progress, it's important to me that I have the progressbar show up in the statusbar, however I'm having trouble finding out a way to do this.

UPDATE (06/01/2020):

I've managed to use 2 functions to start and stop the progress bar, and created the status bar with 2 panels instead of one.

My code within the MainWindow class for the status bar has been changed to:

```<code>self.statusbar = self.CreateStatusBar(2)
self.progress_bar = wx.Gauge(self.statusbar, -1, size=(280,25), style=wx.GA_PROGRESS)
self.progress_bar_active = False
self.Show()
self.progress_bar.SetRange(50)
self.progress_bar.SetValue(0)
</code>```

My function to start the animation:

```<code>def start_busy_statusbar(window):
    window.count = 0
    window.proc = subprocess.Popen(['ping', '127.0.0.1', '-i', '0.2'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    while True:
        wx.Yield()
        try:
            list_data = window.proc.stdout.readline()
            wx.Yield()
        except:
            break
        if len(list_data) == 0:
            break
        window.progress_bar.Pulse()
        wx.Yield()
        window.count += 1
</code>```

And my function to stop the animation:

```<code>def stop_busy_statusbar(window):
    window.progress_bar.Destroy()
    window.progress_bar = wx.Gauge(window.statusbar, -1, size=(280, 25), style=wx.GA_PROGRESS)
</code>```

Which does feel a bit crude, but it works.

So my convert() function that calls the video_from_sequence() function looks like this:

```<code>    def convert(self, event):
        start_busy_statusbar(main_window)
        image_sequence = str(self.text_image_sequence_dir.GetValue())
        original_video = str(self.text_original_video_dir.GetValue())
        if image_sequence.endswith('.tiff') and original_video.endswith('.mkv'):
            try:
                new_video = str(original_video)[:-4] + '_1080p.mkv'
                temp_video = str(original_video)[:-4] + '_temp.mkv'
                print(image_sequence)
                print(original_video)
                print(new_video)
                fps = get_frame_rate(original_video)
                print(fps)
                video_from_sequence(image_sequence, temp_video, fps)

            except FileNotFoundError as e:
                e = str(e).replace('Errno 2] ', '')
                e = e.replace('directory:', 'directory:\n')
                warning(e)
            update_status_bar(self, 'Finished')
        else:
            warning('You must enter valid paths for both a tiff sequence and original video.')
        stop_busy_statusbar(main_window)
</code>```

What I'm running into now, is that the Window locks up while it's processing the image sequence. It's been suggested that I use a seperate thread or utilize the wx.Yield. I'm not quite sure how to execute these things. I've tried CallAfter(function(vars)) but that doesn't seem to work.

I've copied code snippets demonstrating how this works in wxPython, but I don't really understand how it works, and can't get it to work in my script.

答:
Here is a very old example of implementing a progress bar in the statusbar.

It should give you enough to work with.

```<code>import wx
import subprocess
class MainFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Statusbar progress')
        panel = wx.Panel(self)
        self.start_btn = wx.Button(panel, label='Start')
        self.start_btn.Bind(wx.EVT_BUTTON, self.OnStart)
        self.stop_btn = wx.Button(panel, label='Stop')
        self.stop_btn.Bind(wx.EVT_BUTTON, self.OnStop)
        self.Bind(wx.EVT_CLOSE, self.OnExit)
        self.text = wx.TextCtrl(panel, -1, 'Type text here')
        btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
        btn_sizer.Add(self.start_btn)
        btn_sizer.Add(self.stop_btn)
        btn_sizer.Add(self.text)
        panel.SetSizer(btn_sizer)
        self.statusbar = self.CreateStatusBar(3)
        self.text1 = wx.StaticText(self.statusbar,-1,("Static text"))
        self.text2 = wx.StaticText(self.statusbar,-1,("Count Text"))
        self.progress_bar = wx.Gauge(self.statusbar, -1, style=wx.GA_HORIZONTAL|wx.GA_SMOOTH)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.text1, 0, wx.ALL, 5)
        sizer.Add(self.text2, 1, wx.ALL, 5)
        sizer.Add(self.progress_bar, 2, wx.ALL, 5)
        self.statusbar.SetSizer(sizer)
        self.Show()
        self.progress_bar.SetRange(50)
        self.progress_bar.SetValue(0)

    def OnStart(self,event):
        self.start_btn.Enable(False)
        self.text1.SetLabelText("Started")
        self.count = 0
        self.proc = subprocess.Popen(['ping','127.0.0.1','-i','0.2'],stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        while True:
            try:
                list_data = self.proc.stdout.readline()
            except:
                break
            if len(list_data) == 0:
                break
            self.progress_bar.Pulse()
            self.count+=1
            self.text2.SetLabelText("Count "+str(self.count))
            wx.GetApp().Yield()

    def OnStop(self,event):
        self.start_btn.Enable(True)
        self.text1.SetLabelText("Stopped")
        try:
            self.proc.kill()
        except:
            pass

    def OnExit(self,event):
        try:
            self.proc.kill()
        except:
            pass
        self.Destroy()

if __name__ == '__main__':
    app = wx.App()
    frame = MainFrame()
    app.MainLoop()
</code>```

Body:
Running on Python 3.x on Windows 10

I'm working on a script to help automate compiling a .tiff image sequence into a video. I'm using wxPython to build the GUI. First I create the window class and set a global variable for the window.

global main_window
main_window = self

Then I have a function I use to write to the statusbar and also print the values to console(occasionally I also add code to write a log file from the text I send to this function).

def update_status_bar(window, text):
    status = str(text)
    window.statusbar.SetStatusText(status)
    print(status)
    window.Refresh()
    window.Update()
    wx.SafeYield(win=None, onlyIfNeeded=False)

This is the moviePy function I wrote to convert the image sequence into ta video.

def video_from_sequence(image_sequence, video, fps):
    img = []
    update_status_bar(main_window, 'Getting Image Directory')
    path = os.path.dirname(os.path.realpath(image_sequence))
    print(path)
    update_status_bar(main_window, 'Getting List of Image Files')
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith('.tiff'):
                img.append(file)
    os.chdir(path)
    update_status_bar(main_window, 'Creating Video From Image Sequence')
    clip = ImageSequenceClip(img, fps=fps)
    update_status_bar(main_window, clip.write_videofile(video, fps=fps))

The print to console does show the progress, however the statusbar is not populating with the current progress of the process. Because I'd like to eventually have this run as a .pyw, where the statusbar shows the progress, it's important to me that I have the progressbar show up in the statusbar, however I'm having trouble finding out a way to do this.

UPDATE (06/01/2020):

I've managed to use 2 functions to start and stop the progress bar, and created the status bar with 2 panels instead of one.

My code within the MainWindow class for the status bar has been changed to:

self.statusbar = self.CreateStatusBar(2)
self.progress_bar = wx.Gauge(self.statusbar, -1, size=(280,25), style=wx.GA_PROGRESS)
self.progress_bar_active = False
self.Show()
self.progress_bar.SetRange(50)
self.progress_bar.SetValue(0)

My function to start the animation:

def start_busy_statusbar(window):
    window.count = 0
    window.proc = subprocess.Popen(['ping', '127.0.0.1', '-i', '0.2'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    while True:
        wx.Yield()
        try:
            list_data = window.proc.stdout.readline()
            wx.Yield()
        except:
            break
        if len(list_data) == 0:
            break
        window.progress_bar.Pulse()
        wx.Yield()
        window.count += 1

And my function to stop the animation:

def stop_busy_statusbar(window):
    window.progress_bar.Destroy()
    window.progress_bar = wx.Gauge(window.statusbar, -1, size=(280, 25), style=wx.GA_PROGRESS)

Which does feel a bit crude, but it works.

So my convert() function that calls the video_from_sequence() function looks like this:

    def convert(self, event):
        start_busy_statusbar(main_window)
        image_sequence = str(self.text_image_sequence_dir.GetValue())
        original_video = str(self.text_original_video_dir.GetValue())
        if image_sequence.endswith('.tiff') and original_video.endswith('.mkv'):
            try:
                new_video = str(original_video)[:-4] + '_1080p.mkv'
                temp_video = str(original_video)[:-4] + '_temp.mkv'
                print(image_sequence)
                print(original_video)
                print(new_video)
                fps = get_frame_rate(original_video)
                print(fps)
                video_from_sequence(image_sequence, temp_video, fps)

            except FileNotFoundError as e:
                e = str(e).replace('Errno 2] ', '')
                e = e.replace('directory:', 'directory:\n')
                warning(e)
            update_status_bar(self, 'Finished')
        else:
            warning('You must enter valid paths for both a tiff sequence and original video.')
        stop_busy_statusbar(main_window)

What I'm running into now, is that the Window locks up while it's processing the image sequence. It's been suggested that I use a seperate thread or utilize the wx.Yield. I'm not quite sure how to execute these things. I've tried CallAfter(function(vars)) but that doesn't seem to work.

I've copied code snippets demonstrating how this works in wxPython, but I don't really understand how it works, and can't get it to work in my script.

Body:
Here is a very old example of implementing a progress bar in the statusbar.

It should give you enough to work with.

import wx
import subprocess
class MainFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Statusbar progress')
        panel = wx.Panel(self)
        self.start_btn = wx.Button(panel, label='Start')
        self.start_btn.Bind(wx.EVT_BUTTON, self.OnStart)
        self.stop_btn = wx.Button(panel, label='Stop')
        self.stop_btn.Bind(wx.EVT_BUTTON, self.OnStop)
        self.Bind(wx.EVT_CLOSE, self.OnExit)
        self.text = wx.TextCtrl(panel, -1, 'Type text here')
        btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
        btn_sizer.Add(self.start_btn)
        btn_sizer.Add(self.stop_btn)
        btn_sizer.Add(self.text)
        panel.SetSizer(btn_sizer)
        self.statusbar = self.CreateStatusBar(3)
        self.text1 = wx.StaticText(self.statusbar,-1,("Static text"))
        self.text2 = wx.StaticText(self.statusbar,-1,("Count Text"))
        self.progress_bar = wx.Gauge(self.statusbar, -1, style=wx.GA_HORIZONTAL|wx.GA_SMOOTH)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.text1, 0, wx.ALL, 5)
        sizer.Add(self.text2, 1, wx.ALL, 5)
        sizer.Add(self.progress_bar, 2, wx.ALL, 5)
        self.statusbar.SetSizer(sizer)
        self.Show()
        self.progress_bar.SetRange(50)
        self.progress_bar.SetValue(0)

    def OnStart(self,event):
        self.start_btn.Enable(False)
        self.text1.SetLabelText("Started")
        self.count = 0
        self.proc = subprocess.Popen(['ping','127.0.0.1','-i','0.2'],stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        while True:
            try:
                list_data = self.proc.stdout.readline()
            except:
                break
            if len(list_data) == 0:
                break
            self.progress_bar.Pulse()
            self.count+=1
            self.text2.SetLabelText("Count "+str(self.count))
            wx.GetApp().Yield()

    def OnStop(self,event):
        self.start_btn.Enable(True)
        self.text1.SetLabelText("Stopped")
        try:
            self.proc.kill()
        except:
            pass

    def OnExit(self,event):
        try:
            self.proc.kill()
        except:
            pass
        self.Destroy()

if __name__ == '__main__':
    app = wx.App()
    frame = MainFrame()
    app.MainLoop()


问:
Install cassandra 3.10 on windows 10
I am trying to install Cassandra on windows 10 localhost.
I am getting error as Can't detect Python version!

I am trying this way

Downloaded and extracted Cassandra in C:\wamp64\apache-cassandra-3.10

Set Set-ExecutionPolicy Unrestricted in Windows powershell

From Windows CMD

```<code>cd C:\wamp64\apache-cassandra-3.10\bin
C:\wamp64\apache-cassandra-3.10\bin>cassandra.bat -f
</code>```

Cassandra is now running so I stopped it by Control-C

Then I try to run cqlsh by following command

```<code>C:\wamp64\apache-cassandra-3.10\bin>cqlsh.bat
</code>```

But I got errror Can't detect Python version!

So I download and install Python 2.7.13 in C:\wamp64\python

I have added environmental path for python in System Properties C:\wamp64\python\

I extracted Thrift in C:\wamp64\python\thrift-0.10.0

Then I install Python like this

```<code>C:\wamp64\python\thrift-0.10.0>python setup.py install
</code>```

But again I am getting error on running cqlsh as

```<code>C:\wamp64\apache-cassandra-3.10\bin>cqlsh.bat
Can't detect Python version!
</code>```

Please see and suggest what step I have missed in installation of Cassandra for this error.

Thanks

Edit

I reinstall everything from scratch again carefully and now I am getting this error

```<code>C:\wamp64\apache-cassandra-3.10\pylib>python setup.py install
Traceback (most recent call last):
  File "setup.py", line 33, in <module>
    ext_modules=get_extensions(),
  File "setup.py", line 26, in get_extensions
    from Cython.Build import cythonize
ImportError: No module named Cython.Build

C:\wamp64\apache-cassandra-3.10\pylib>cd C:\wamp64\apache-cassandra-3.10\bin

C:\wamp64\apache-cassandra-3.10\bin>python cqlsh localhost 9160
  File "cqlsh", line 20
    python -c 'import sys; sys.exit(not (0x020700b0 < sys.hexversion < 0x03000000))' 2>/dev/null \
                                                                                ^
SyntaxError: invalid syntax

C:\wamp64\apache-cassandra-3.10\bin>
</code>```

Please see and suggest any possible way to resolve these error.

Thanks

答:
I had this issue as I was running Python3 and Python2 on Windows.

It seems like the problem was with missing PATH to Python2.

To check, run in cmd:

```<code>python --version
</code>```

If you get nothing, it means that the PATH is not added.

Note:

To add path when installing Python2 you need to scroll down to Customize Python 2.x.x -> Add python.exe to Path (unlike Python 3 where you have a checkbox)

Title: Install cassandra 3.10 on windows 10

Body:
I am trying to install Cassandra on windows 10 localhost.
I am getting error as Can't detect Python version!

I am trying this way

Downloaded and extracted Cassandra in C:\wamp64\apache-cassandra-3.10

Set Set-ExecutionPolicy Unrestricted in Windows powershell

From Windows CMD

cd C:\wamp64\apache-cassandra-3.10\bin
C:\wamp64\apache-cassandra-3.10\bin>cassandra.bat -f

Cassandra is now running so I stopped it by Control-C

Then I try to run cqlsh by following command

C:\wamp64\apache-cassandra-3.10\bin>cqlsh.bat

But I got errror Can't detect Python version!

So I download and install Python 2.7.13 in C:\wamp64\python

I have added environmental path for python in System Properties C:\wamp64\python\

I extracted Thrift in C:\wamp64\python\thrift-0.10.0

Then I install Python like this

C:\wamp64\python\thrift-0.10.0>python setup.py install

But again I am getting error on running cqlsh as

C:\wamp64\apache-cassandra-3.10\bin>cqlsh.bat
Can't detect Python version!

Please see and suggest what step I have missed in installation of Cassandra for this error.

Thanks

Edit

I reinstall everything from scratch again carefully and now I am getting this error

C:\wamp64\apache-cassandra-3.10\pylib>python setup.py install
Traceback (most recent call last):
  File "setup.py", line 33, in <module>
    ext_modules=get_extensions(),
  File "setup.py", line 26, in get_extensions
    from Cython.Build import cythonize
ImportError: No module named Cython.Build

C:\wamp64\apache-cassandra-3.10\pylib>cd C:\wamp64\apache-cassandra-3.10\bin

C:\wamp64\apache-cassandra-3.10\bin>python cqlsh localhost 9160
  File "cqlsh", line 20
    python -c 'import sys; sys.exit(not (0x020700b0 < sys.hexversion < 0x03000000))' 2>/dev/null \
                                                                                ^
SyntaxError: invalid syntax

C:\wamp64\apache-cassandra-3.10\bin>

Please see and suggest any possible way to resolve these error.

Thanks

Body:
I had this issue as I was running Python3 and Python2 on Windows.

It seems like the problem was with missing PATH to Python2.

To check, run in cmd:

python --version

If you get nothing, it means that the PATH is not added.

Note:

To add path when installing Python2 you need to scroll down to Customize Python 2.x.x -> Add python.exe to Path (unlike Python 3 where you have a checkbox)


问:
SwiftUI and AVPlayer
I'm trying to get an AVPlayer layer in my SwiftUI interface.
Google doesn't have many answers on the subject, in fact, there was a tutorial that looked promising see: https://medium.com/@chris.mash/avplayer-swiftui-b87af6d0553. But it was full of bugs. So, I tried going about this my own way.

The plan: create a UIView subclass and add an AVPlayerLayer to it, then, wrap the UIView for SwiftUI.

The results: nothing.

Here's what I've got so far:

```<code>struct PlayerView : UIViewRepresentable {

    func makeUIView(context: Context) -> UIView {
        return PlayerViewSwift()
    }

    func updateUIView(_ uiView: UIView, context: Context) {

    }
}
</code>```

And then the PlayerViewSwift class:

```<code>class PlayerViewSwift : UIView {
   private let playerLayer = AVPlayerLayer()

    init() {
        super.init(frame: .infinite)

    }

    override init(frame: CGRect) {
      super.init(frame: frame)

    }

    // This attribute hides `init(coder:)` from subclasses
    @available(*, unavailable)
    required init?(coder aDecoder: NSCoder) {
        fatalError("NSCoding not supported")
    }

    override func layoutSubviews() {
         super.layoutSubviews()
      //  playerLayer.player =

        print("hmmm")

               let player = AVPlayer(url: URL(string: "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u80")!)
               player.play()

               playerLayer.player = player
               layer.addSublayer(playerLayer)

     }

}
</code>```

答:
Swift 5.1, iOS 13.

I read Chris Mash tutorials too [there for 4 of them] and put this together. I certainly don't recall them being full of bugs, maybe a few typos.

It plays either an embedded video or a streaming one in SwiftUI navigation controller managed page.

```<code>import Foundation
import SwiftUI
import AVFoundation
import Combine

let timePublisher = PassthroughSubject<TimeInterval, Never>()
let videoFinished = PassthroughSubject<Void, Never>()
let nextFrame = PassthroughSubject<Void, Never>()

 struct PlayerTimeView: View {
 @State private var currentTime: TimeInterval = 0

var body: some View {
Text("\(currentTime)")
.onReceive(timePublisher) { time in
  self.currentTime = time
}.statusBar(hidden: true)
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
}
}

class PlayerUIView: UIView {
private var timeObservation: Any?
private let playerLayer = AVPlayerLayer()
override init(frame: CGRect) {
super.init(frame: .zero)
let url = Bundle.main.url(forResource: "AppDemo", withExtension: "mov")
//    let url = URL(string: "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8")!
//    let url = URL(string: "https://www.youtube.com/watch?v=XK8METRgK_U")!
let player = AVPlayer(url: url!)
player.play()

  timeObservation = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.5, preferredTimescale: 600), queue: nil) { [weak self] time in
  guard let self = self else { return }
  // Publish the new player time
  print("time.seconds ", time.seconds)
  timePublisher.send(time.seconds)

  NotificationCenter.default.addObserver(self, selector: #selector(self.finishVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}

playerLayer.player = player
layer.addSublayer(playerLayer)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
  super.layoutSubviews()
  playerLayer.frame = CGRect(x: 0, y: -115, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
 }

 @objc func finishVideo() {
    print("Video Finished")
      NotificationCenter.default.removeObserver(NSNotification.Name.AVPlayerItemDidPlayToEndTime)
     videoFinished.send()
     nextFrame.send()
  }

}

struct PlayerView: UIViewRepresentable {
 func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PlayerView>) {
 }
 func makeUIView(context: Context) -> UIView {
     PlayerUIView(frame: .zero)
 }
}

struct PlayerPage: View {
 @EnvironmentObject var env: MyAppEnvironmentData
 @Environment(\.presentationMode) var presentation

 var body: some View {
   VStack {
     PlayerView().onReceive(videoFinished) { (_) in
       self.presentation.wrappedValue.dismiss()
     }
   HStack {
     Spacer()
     PlayerTimeView()
     Spacer()
   }
  }
}
}
</code>```

Title: SwiftUI and AVPlayer

Body:
I'm trying to get an AVPlayer layer in my SwiftUI interface.
Google doesn't have many answers on the subject, in fact, there was a tutorial that looked promising see: https://medium.com/@chris.mash/avplayer-swiftui-b87af6d0553. But it was full of bugs. So, I tried going about this my own way.

The plan: create a UIView subclass and add an AVPlayerLayer to it, then, wrap the UIView for SwiftUI.

The results: nothing.

Here's what I've got so far:

struct PlayerView : UIViewRepresentable {

    func makeUIView(context: Context) -> UIView {
        return PlayerViewSwift()
    }

    func updateUIView(_ uiView: UIView, context: Context) {

    }
}

And then the PlayerViewSwift class:

class PlayerViewSwift : UIView {
   private let playerLayer = AVPlayerLayer()

    init() {
        super.init(frame: .infinite)

    }

    override init(frame: CGRect) {
      super.init(frame: frame)

    }

    // This attribute hides `init(coder:)` from subclasses
    @available(*, unavailable)
    required init?(coder aDecoder: NSCoder) {
        fatalError("NSCoding not supported")
    }

    override func layoutSubviews() {
         super.layoutSubviews()
      //  playerLayer.player =

        print("hmmm")

               let player = AVPlayer(url: URL(string: "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u80")!)
               player.play()

               playerLayer.player = player
               layer.addSublayer(playerLayer)

     }

}

Body:
Swift 5.1, iOS 13.

I read Chris Mash tutorials too [there for 4 of them] and put this together. I certainly don't recall them being full of bugs, maybe a few typos.

It plays either an embedded video or a streaming one in SwiftUI navigation controller managed page.

import Foundation
import SwiftUI
import AVFoundation
import Combine

let timePublisher = PassthroughSubject<TimeInterval, Never>()
let videoFinished = PassthroughSubject<Void, Never>()
let nextFrame = PassthroughSubject<Void, Never>()

 struct PlayerTimeView: View {
 @State private var currentTime: TimeInterval = 0

var body: some View {
Text("\(currentTime)")
.onReceive(timePublisher) { time in
  self.currentTime = time
}.statusBar(hidden: true)
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
}
}

class PlayerUIView: UIView {
private var timeObservation: Any?
private let playerLayer = AVPlayerLayer()
override init(frame: CGRect) {
super.init(frame: .zero)
let url = Bundle.main.url(forResource: "AppDemo", withExtension: "mov")
//    let url = URL(string: "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8")!
//    let url = URL(string: "https://www.youtube.com/watch?v=XK8METRgK_U")!
let player = AVPlayer(url: url!)
player.play()

  timeObservation = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.5, preferredTimescale: 600), queue: nil) { [weak self] time in
  guard let self = self else { return }
  // Publish the new player time
  print("time.seconds ", time.seconds)
  timePublisher.send(time.seconds)

  NotificationCenter.default.addObserver(self, selector: #selector(self.finishVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}

playerLayer.player = player
layer.addSublayer(playerLayer)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
  super.layoutSubviews()
  playerLayer.frame = CGRect(x: 0, y: -115, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
 }

 @objc func finishVideo() {
    print("Video Finished")
      NotificationCenter.default.removeObserver(NSNotification.Name.AVPlayerItemDidPlayToEndTime)
     videoFinished.send()
     nextFrame.send()
  }

}

struct PlayerView: UIViewRepresentable {
 func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PlayerView>) {
 }
 func makeUIView(context: Context) -> UIView {
     PlayerUIView(frame: .zero)
 }
}

struct PlayerPage: View {
 @EnvironmentObject var env: MyAppEnvironmentData
 @Environment(\.presentationMode) var presentation

 var body: some View {
   VStack {
     PlayerView().onReceive(videoFinished) { (_) in
       self.presentation.wrappedValue.dismiss()
     }
   HStack {
     Spacer()
     PlayerTimeView()
     Spacer()
   }
  }
}
}


问:
express throws error as `body-parser deprecated undefined extended`
In my node app, I am using express. all works fine, But i am getting error in the cmd. I use all are updated modules...

my code :

```<code>var express = require('express');
var bodyParser = require('body-parser');
var jade = require('jade');
var app = express();
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));

app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded()); // to support URL-encoded bodies

app.get('/',function(req,res){
    res.render('index.jade');
});

app.get('/login',function(req,res){
    res.render('index.jade');
});

app.post('/login',function(req,res){
    console.log(req.body);
});

app.get('/signup',function(req,res){
    res.render('signup.jade');
});

var env = process.env.PORT || 3000;

app.listen(env, function(req, res){
    console.log('i am working!');
});
</code>```

Error:

```<code>D:\myLogin>node app
body-parser deprecated undefined extended: provide extended option app.js:11:20 //why i am getting this?
i am working!
{ username: 'jbarif@gmail.com', password: 'pass' } // i am getting response
</code>```

Can any help me to understand this issue please?

答:
If you are using node version v13.12.0:</p>
```<code>app.use(express.urlencoded({ extended: true }))
</code>```

Body:
In my node app, I am using express. all works fine, But i am getting error in the cmd. I use all are updated modules...

my code :

var express = require('express');
var bodyParser = require('body-parser');
var jade = require('jade');
var app = express();
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));

app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded()); // to support URL-encoded bodies

app.get('/',function(req,res){
    res.render('index.jade');
});

app.get('/login',function(req,res){
    res.render('index.jade');
});

app.post('/login',function(req,res){
    console.log(req.body);
});

app.get('/signup',function(req,res){
    res.render('signup.jade');
});

var env = process.env.PORT || 3000;

app.listen(env, function(req, res){
    console.log('i am working!');
});

Error:

D:\myLogin>node app
body-parser deprecated undefined extended: provide extended option app.js:11:20 //why i am getting this?
i am working!
{ username: 'jbarif@gmail.com', password: 'pass' } // i am getting response

Can any help me to understand this issue please?

Body:
If you are using node version v13.12.0:

app.use(express.urlencoded({ extended: true }))


问:
Pass file into jar
I have jar file that contains this code

```<code>import java.io.File
import java.nio.file.Paths

import org.cassandraunit.utils.EmbeddedCassandraServerHelper

object CassandraMockBootable extends App {
  println("Running embedded Cassandra.........")
  val file = Paths.get("/target/classes/cassandra.yaml").toFile
  assert(file.exists())
  EmbeddedCassandraServerHelper.startEmbeddedCassandra(file, 50000)
}
</code>```

This jar is used in another application by a maven plugin that run a java process

```<code> <plugin>
        <groupId>com.bazaarvoice.maven.plugins</groupId>
        <artifactId>process-exec-maven-plugin</artifactId>
        <version>0.8</version>
        <executions>
          <execution>
            <id>Embedded-Cassandra</id>
            <phase>pre-integration-test</phase>
            <goals>
              <goal>start</goal>
            </goals>
            <configuration>
              <name>Embedded-Cassandra</name>
              <skip>${skipStartService}</skip>
              <arguments>
                <argument>java</argument>
                <argument>-XX:+HeapDumpOnOutOfMemoryError</argument>
                <argument>-Xss1M</argument>
                <argument>-XX:+UseParallelGC</argument>
                <argument>-cp</argument>
                <argument>../../mock-service/target/lib/*</argument>
                <argument>mocks.bootables.CassandraMockBootable</argument>
              </arguments>
            </configuration>
          </execution>
    </executions>
</plugin>
</code>```

I dont know how, but I've been unable to pass the cassandra.yaml to that process, and the assert never works.

I tried to put that file into the resources of src and test in the generated jar project, and the consumer project but nothing. The assert always fail.

Any idea what I'm doing wrong here?

Regards

答:
Create a resource folder and place yaml file in that, don't place in target folder path because target folder always gets refreshed when ever build happens this makes file to be unavailable.

So please create separate resource folder and keep yaml file, then try accessing

Title: Pass file into jar

Body:
I have jar file that contains this code

import java.io.File
import java.nio.file.Paths

import org.cassandraunit.utils.EmbeddedCassandraServerHelper

object CassandraMockBootable extends App {
  println("Running embedded Cassandra.........")
  val file = Paths.get("/target/classes/cassandra.yaml").toFile
  assert(file.exists())
  EmbeddedCassandraServerHelper.startEmbeddedCassandra(file, 50000)
}

This jar is used in another application by a maven plugin that run a java process

 <plugin>
        <groupId>com.bazaarvoice.maven.plugins</groupId>
        <artifactId>process-exec-maven-plugin</artifactId>
        <version>0.8</version>
        <executions>
          <execution>
            <id>Embedded-Cassandra</id>
            <phase>pre-integration-test</phase>
            <goals>
              <goal>start</goal>
            </goals>
            <configuration>
              <name>Embedded-Cassandra</name>
              <skip>${skipStartService}</skip>
              <arguments>
                <argument>java</argument>
                <argument>-XX:+HeapDumpOnOutOfMemoryError</argument>
                <argument>-Xss1M</argument>
                <argument>-XX:+UseParallelGC</argument>
                <argument>-cp</argument>
                <argument>../../mock-service/target/lib/*</argument>
                <argument>mocks.bootables.CassandraMockBootable</argument>
              </arguments>
            </configuration>
          </execution>
    </executions>
</plugin>

I dont know how, but I've been unable to pass the cassandra.yaml to that process, and the assert never works.

I tried to put that file into the resources of src and test in the generated jar project, and the consumer project but nothing. The assert always fail.

Any idea what I'm doing wrong here?

Regards


问:
delete session of a specific user in django?
I am trying to delete the session of some specific user in Django.The code seems to run perfectly fine but I believe session is not deleted as the user is still logged in.
The code I am using to delete session is:-</p>

```<code>user = User.objects.get(id=id)
for s in Session.objects.all():
            if s.get_decoded().get('_auth_user_id') == user.id:
                s.delete()
</code>```

答:
//type cast to same type else they will always return False

user = User.objects.get(id=id)
 for s in Session.objects.all():
            if int(s.get_decoded().get('_auth_user_id')) == int(user.id):
                s.delete()

Body:
I am trying to delete the session of some specific user in Django.The code seems to run perfectly fine but I believe session is not deleted as the user is still logged in.
The code I am using to delete session is:-

user = User.objects.get(id=id)
for s in Session.objects.all():
            if s.get_decoded().get('_auth_user_id') == user.id:
                s.delete()


问:
asp.net mvc Globalization. How do you do it?
Learning asp.net mvc and whenever I worked we had to localize our application. Looked at few articles eg

http://afana.me/post/aspnet-mvc-internationalization.aspx  (Creates a view for each language) No for me

http://www.codeproject.com/KB/aspnet/BilingualMvc3Part1.aspx (uses Broswer default language which will never work for me. Can you imagine I am English speaker on holiday in Spain and need to use the website and i have not got a clue about how to change the settings) NO

http://geekswithblogs.net/shaunxu/archive/2010/05/06/localization-in-asp.net-mvc-ndash-3-days-investigation-1-day.aspx  ( this one via URL but looking at his baseController sort of hardcode the application name in the cookie)

I am CONFUSED. Mainly because my knowledge is not great!!
What is the recommended way to do it? Have you done in real world app? Would you share code? A snippet of how you tackled the problem will do?

I am looking for a neat way like you can do in asp.net .I need to give the ability to user to change languages at run time by clicking a flag or something.

Is there a base method to override?
Is there a proper example somewhere? Do you have to write some sort of baseController class?

thanks a lot for your time

答:
You should use resource files to handle localisation. With that you have the ability to get a language the user has choosen before or he has choosen right now. Here is a good blog how to do that http://adamyan.blogspot.com/2010/02/aspnet-mvc-2-localization-complete.html

IF the user has no active session, means no cookie that identifies him you should use the browser language or a maybe a geotracking service to determine the sitelanguage. It is up to you to present a easy way to change the current language... And as mentioned above resourcefiles will help you here.


答:
There is no match, because pandas cannot by default convert list of datetimes to datetimes, so is necessary converting first:</p>

```<code>print(test_data.loc[pd.to_datetime(['2019-06-06','2019-06-10'])])
2019-06-06    1
2019-06-10    2
dtype: int64
</code>```

Body:
Below gives error KeyError: "None of [Index(['2019-06-06', '2019-06-10'], dtype='object')] are in the [index]" what's the problem?

test_data = pd.Series([1,2,3,4,5,6], index=['20190606','20190610','20190708','20190805','20190909','20190930'])
test_data.index=pd.to_datetime(test_data.index)

print(test_data.loc[['2019-06-06','2019-06-10']])

Body:
There is no match, because pandas cannot by default convert list of datetimes to datetimes, so is necessary converting first:

print(test_data.loc[pd.to_datetime(['2019-06-06','2019-06-10'])])
2019-06-06    1
2019-06-10    2
dtype: int64


答:
I believe that the best way is to write a function generalizing the VAR/linearHypothesis code, and call that function with the required arguments.

Step 1: the function

```<code>library(vars)
library(car)

customVAR <- function(DF, Select, Regr, p, type = "const"){
  n <- nrow(DF)
  instru <- DF[[Regr]][seq.int(n - p)]
  var_fit <- VAR(DF[, Select], p = p, type = type)
  r <- resid(var_fit$varresult[[1]])
  lm_fit <- lm(r ~ instru)
  smry <- summary(lm_fit)
  lh <- linearHypothesis(lm_fit, "instru = 0", test = "F", vcov = vcovHAC, type = "HC1")
  list(Summary = smry, linearHyp = lh)
}
</code>```

Step 2: test it for one model

```<code>customVAR(df, Select = c(1:4, 10), Regr = 'X7', p = 3)
</code>```

Step 3: fit several models, varying the regressors

```<code>Regr_vec <- paste0('X', 7:9)
var_list <- lapply(Regr_vec, function(R){
  customVAR(df, Select = c(1:4, 10), Regr = R, p = 3)
})

var_list[[2]]$Summary
var_list[[2]]$linearHyp
</code>```

Step 4: vary the responses

```<code>Select_list <- list(c(1:4, 10), c(1:4, 5), c(1:4, 6))
var_list2 <- lapply(Select_list, function(S){
  customVAR(df, Select = S, Regr = 'X7', p = 3)
})

var_list2[[3]]$Summary
var_list2[[3]]$linearHyp
</code>```

Title: How to make a loop for these regressions?

Body:
I have a dataframe with 10 columns like this:

df = structure(list(X1 = c(-0.158841494166799, 1.74997712540787,
-0.603638753496694, -0.253379995687274, -1.13536828104642, -2.72698649676692,
0.0243826193956672, 3.21776393858788, -2.3633921387719, 0.0305028420399468,
-4.26940546325382, 1.55584592541131, -1.05118869595721, -2.84985861365441,
0.729293004856561, -3.80058253179317, 1.31191742952459, 2.33589025288871,
-0.315014740930705, 2.92302109498542, 2.26246357678861, 1.37039290089958,
0.0582396621450368, -0.902295561314538, 2.14889801735908, 0.391493314141552,
2.33280118206325, -0.0490864536654898, 0.068965431468872, 1.24553936025063
), X2 = c(0.428917030889186, 1.38179284926331, 2.83063848525283,
-0.926689840680047, -1.3903457418351, 0.708618895316463, -0.750232095654876,
0.894660121671367, 0.124277732759992, -1.98558522788821, 2.34165530946135,
2.85945910959032, 2.36563560772223, 0.0185741299096399, -2.48859548768527,
-1.26592501904523, -0.790849261930494, -0.828149152178906, 3.2014616981455,
-0.15442363719638, -0.516775154465199, -0.176649448869891, -1.41825025459806,
2.17806157731774, -0.44973481848562, 2.24655423722927, 2.47628395430464,
1.91613790409017, -0.393928617864301, -0.148584327095393), X3 = c(-0.430287082709084,
-0.625327045828844, -0.514958706302276, 0.751266821352889, 1.18006572060265,
-0.802136052260364, 0, 0.105706401868772, 0.442778243504233,
0.905950590121364, -1.26899829497004, 0.745801518841586, -0.978033251950966,
0.113286791573796, 1.20968420311602, -0.635010679093886, 0.858274389205649,
-1.009308286611, 0, 0.167623720006668, -0.720624475890533, -0.443172067136528,
-0.0181650919153045, -0.818017257660172, 1.18137870264753, -0.0566121497554404,
0.572314218120067, -1.01361737919216, 0.637155618813563, 0.00507063594816648
), X4 = c(1.05105923858325, -0.808507106602501, 1.01063388325313,
-0.363828197971125, -0.889357817262751, 0.0808507106602501, 0,
0.4851042639615, 0.687231040612125, -1.53616350254475, 2.02126776650625,
-1.09148459391338, -0.929783172592876, 0.323402842641, 0.768081751272376,
0.444678908631375, -1.53616350254475, 0.970208527923, 0, 0.646805685282001,
-1.01063388325313, 0.40425355330125, -0.323402842641, -0.202126776650625,
1.09148459391338, -0.970208527923, -0.606380329951876, 0, 0.606380329951876,
0.161701421320499), X5 = c(-1.68622583629267, -2.11651291900176,
-2.7418399648306, -3.25679867113288, -2.50553184977999, -1.32546612917734,
-2.12760218143771, -2.12760218143771, -2.02189577956894, -1.5791175360647,
-0.67316694594334, -1.94216524091338, -1.19636372207179, -2.17439697402276,
-2.06111018244896, -0.85142597933294, -1.48643665842683, -0.628162269221177,
-1.63747055583218, -1.63747055583218, -1.46984683582551, -2.19047131171604,
-2.63364337885257, -2.65180847076788, -3.46982572842805, -2.28844702578052,
-2.34505917553596, -1.77274495741589, -2.78636233660805, -2.14920671779449
), X6 = c(-3.52265292326337, -2.47159368468012, -3.28010079128262,
-2.26946690802949, -2.63329510600062, -3.52265292326337, -3.44180221260312,
-3.44180221260312, -2.95669794864162, -2.26946690802949, -3.80563041057424,
-1.78436264406799, -2.87584723798137, -3.80563041057424, -3.48222756793324,
-2.71414581666087, -2.26946690802949, -3.80563041057424, -2.83542188265124,
-2.83542188265124, -2.18861619736924, -3.19925008062237, -2.79499652732112,
-3.11839936996212, -3.32052614661274, -2.22904155269937, -3.19925008062237,
-3.80563041057424, -3.80563041057424, -3.19925008062237), X7 = c(1,
0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 1, 0, 0), X8 = c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0),
    X9 = c(1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0), X10 = c(3.2936,
    3.283, 3.264, 3.3162, 3.31, 3.3485, 3.3017, 3.2927, 3.3186,
    3.3004, 3.3043, 3.0945, 2.7868, 2.7635, 2.749, 2.5605, 2.5571,
    2.2133, 2.0783, 2.0981, 2.0209, 2.0148, 1.973, 2.0567, 2.0214,
    2.0315, 2.0057, 2.078, 2.0152, 2.0277)), row.names = c(NA,
30L), class = "data.frame")

What I want to do is be much faster in the implementation of the following code:

p = 3

instru1 = df$X7[1:(30-p)]
instru2 = df$X8[1:(30-p)]
instru3 = df$X9[1:(30-p)]

var <- VAR(df[, c(1:4,10)], p, type = "const")

summary(lm(var$varresult$[# the name of the first variable that appears]$residuals ~ instru1))

linearHypothesis(lm(var$varresult$[# the name of the first variable that appears]$residuals ~ instru1), "instru1 = 0", test = "F", vcov = vcovHAC, type = "HC1")

I did this code only for instru1 and for one column of interest (col 10 in df). I would like to do the same exercise, for instru1, instru2 and instru3 and, in addition to

VAR(df[, c(1:4,10)], p, type = "const")

for

VAR(df[, c(1:4,5)], p, type = "const")

and

VAR(df[, c(1:4,6)], p, type = "const").

In other words, I would like to avoid doing:

p = 3

instru1 = df$X7[1:(30-p)]
instru2 = df$X8[1:(30-p)]
instru3 = df$X9[1:(30-p)]

var1 <- VAR(df[, c(1:4,5)], p, type = "const")

summary(lm(var1$varresult$[# the name of the first variable that appears]$residuals ~ instru1))

linearHypothesis(lm(var1$varresult$[# the name of the first variable that appears]$residuals ~ instru1), "instru1 = 0", test = "F", vcov = vcovHAC, type = "HC1")

var2 <- VAR(df[, c(1:4,6)], p, type = "const")

summary(lm(var2$varresult$[# the name of the first variable that appears]$residuals ~ instru1))

linearHypothesis(lm(var2$varresult$[# the name of the first variable that appears]$residuals ~ instru1), "instru1 = 0", test = "F", vcov = vcovHAC, type = "HC1")

# and then the same but plugging instru2 and instru3 in place of instru1. Is it possible to have all in one loop?

Ideally I would like to have everything in one loop but, if not feasible, it is also fine to have a code for the VAR part and then I will update the 'instru' bit manually.

Can anyone help me?

Thanks a lot!

Body:
I believe that the best way is to write a function generalizing the VAR/linearHypothesis code, and call that function with the required arguments.

Step 1: the function

library(vars)
library(car)

customVAR <- function(DF, Select, Regr, p, type = "const"){
  n <- nrow(DF)
  instru <- DF[[Regr]][seq.int(n - p)]
  var_fit <- VAR(DF[, Select], p = p, type = type)
  r <- resid(var_fit$varresult[[1]])
  lm_fit <- lm(r ~ instru)
  smry <- summary(lm_fit)
  lh <- linearHypothesis(lm_fit, "instru = 0", test = "F", vcov = vcovHAC, type = "HC1")
  list(Summary = smry, linearHyp = lh)
}

Step 2: test it for one model

customVAR(df, Select = c(1:4, 10), Regr = 'X7', p = 3)

Step 3: fit several models, varying the regressors

Regr_vec <- paste0('X', 7:9)
var_list <- lapply(Regr_vec, function(R){
  customVAR(df, Select = c(1:4, 10), Regr = R, p = 3)
})

var_list[[2]]$Summary
var_list[[2]]$linearHyp

Step 4: vary the responses

Select_list <- list(c(1:4, 10), c(1:4, 5), c(1:4, 6))
var_list2 <- lapply(Select_list, function(S){
  customVAR(df, Select = S, Regr = 'X7', p = 3)
})

var_list2[[3]]$Summary
var_list2[[3]]$linearHyp


问:
How to deal with dates in global system
Let's say that I need to create 'chat-like' system. Of course I need to deal with dates somehow.
I read about it a lot and I have some knowledge but I really don't know how to use it.

I would like to store message date in UTC (postgres 12)

Each user should be able to select his time zone and this time zone should be saved into database (standard approach)

When message is retrieved from database I need to convert message date into valid local date based on user selected timezone.

This is really all I need to do and here problem starts:

In postgres date is stored with offset f.e 2020-05-01 00:00:00+02, but I want to store timezone in another table, not here

How can I store user timezone? I should use names like "EST5EDT" or use time offsets as integer?

Where can I find list of all timezones to present user? (Each global website f.e. facebook has list of timezones with offsets, where can I find list of all valid timezones?)

How can I select date with user appropriate timezone? f.e.

```<code>SELECT convert_to_user_date("Date", "timezonename??")
FROM "Messages"
</code>```

Is this correct way to achieve my goal?

答:
These days you don't have to resort to UTC. You can store full timestamps with time zone. This way e.g. you won't lose DST status at the moment the timestamp was recorded in the database.
https://www.postgresql.org/docs/current/datatype-datetime.html

You can easily select the timestamp stored with any time zone shifted to target user's time zone (assuming it's stored somewhere in user preferences). The syntax is SELECT ... AT TIME ZONE
https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT

Title: How to deal with dates in global system

Body:
Let's say that I need to create 'chat-like' system. Of course I need to deal with dates somehow.
I read about it a lot and I have some knowledge but I really don't know how to use it.

I would like to store message date in UTC (postgres 12)

Each user should be able to select his time zone and this time zone should be saved into database (standard approach)

When message is retrieved from database I need to convert message date into valid local date based on user selected timezone.

This is really all I need to do and here problem starts:

In postgres date is stored with offset f.e 2020-05-01 00:00:00+02, but I want to store timezone in another table, not here

How can I store user timezone? I should use names like "EST5EDT" or use time offsets as integer?

Where can I find list of all timezones to present user? (Each global website f.e. facebook has list of timezones with offsets, where can I find list of all valid timezones?)

How can I select date with user appropriate timezone? f.e.

SELECT convert_to_user_date("Date", "timezonename??")
FROM "Messages"

Is this correct way to achieve my goal?


问:
Load H2 source data from custom sql with Spring
Having a problem with H2 set up in Spring. I placed all my sql data into one file named data.sql, however when I change it to anything else - it cannot be identified. Any idea how to set up multiple separate files?

Let's say i have a table User and some data inserted, but aiming to have 2 separate files, e.g. user-schema and user-data, and so on - multiple schema files with same number of insert data files.

My current spring.properties looks as follows:

```<code>spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.h2.console.path=/h2
</code>```

My current data.sql looks as follows:

```<code>DROP TABLE IF EXISTS User;

CREATE TABLE User
(
    id      INT AUTO_INCREMENT PRIMARY KEY,
    name    VARCHAR(20) NOT NULL,
    surname VARCHAR(20) NOT NULL,
    role    VARCHAR(20) NOT NULL,
    email   VARCHAR(30) NOT NULL
);

INSERT INTO User (name, surname, role, email)
VALUES ('Thor', '', 'admin', 'thor@marvel.com'),
       ('Hulk', '', 'user', 'hulk@marvel.com'),
       ('Venom', '', 'user', 'venom@marvel.com'),
       ('Spider', 'Man', 'user', 'spider-man@marvel.com'),
       ('Super', 'Man', 'user', 'super-man@marvel.com');
</code>```

答:
If you want to separate your data input to many files you should provide information to Spring about files location:

```<code>spring.datasource.data=classpath*:sql/mock-*.sql
spring.datasource.initialization-mode=always
</code>```

In my project we keep our .sql files in resource/sql folder and every file name mock-*.sql, like mock-user.sql, mock-role-.sql that why I have wildcard in path. Anyway in spring.datasource.data you have to provide path to file with sql inserts.

spring.datasource.initialization-mode=always tells Spring to always initialize DB from files. You should configure that property since you "create-drop" database each time your tests starts.

Spring documentation about data and schema initialization: https://docs.spring.io/spring-boot/docs/2.1.x/reference/html/howto-database-initialization.html

Body:
Having a problem with H2 set up in Spring. I placed all my sql data into one file named data.sql, however when I change it to anything else - it cannot be identified. Any idea how to set up multiple separate files?

Let's say i have a table User and some data inserted, but aiming to have 2 separate files, e.g. user-schema and user-data, and so on - multiple schema files with same number of insert data files.

My current spring.properties looks as follows:

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.h2.console.path=/h2

My current data.sql looks as follows:

DROP TABLE IF EXISTS User;

CREATE TABLE User
(
    id      INT AUTO_INCREMENT PRIMARY KEY,
    name    VARCHAR(20) NOT NULL,
    surname VARCHAR(20) NOT NULL,
    role    VARCHAR(20) NOT NULL,
    email   VARCHAR(30) NOT NULL
);

INSERT INTO User (name, surname, role, email)
VALUES ('Thor', '', 'admin', 'thor@marvel.com'),
       ('Hulk', '', 'user', 'hulk@marvel.com'),
       ('Venom', '', 'user', 'venom@marvel.com'),
       ('Spider', 'Man', 'user', 'spider-man@marvel.com'),
       ('Super', 'Man', 'user', 'super-man@marvel.com');

Body:
If you want to separate your data input to many files you should provide information to Spring about files location:

spring.datasource.data=classpath*:sql/mock-*.sql
spring.datasource.initialization-mode=always

In my project we keep our .sql files in resource/sql folder and every file name mock-*.sql, like mock-user.sql, mock-role-.sql that why I have wildcard in path. Anyway in spring.datasource.data you have to provide path to file with sql inserts.

spring.datasource.initialization-mode=always tells Spring to always initialize DB from files. You should configure that property since you "create-drop" database each time your tests starts.

Spring documentation about data and schema initialization: https://docs.spring.io/spring-boot/docs/2.1.x/reference/html/howto-database-initialization.html


问:
android studio it's good to use bind service on background service?
I am creating an chat app which is connected to web socket, using a background service. But I should connect it to the activity to show the new messages. Maybe in the main conversations list, or inside the conversation itself.

So, first, I want to check if my service is running, then getting it bound to the opened activity.

And I want the service to tell the activities that there is a new message.

So, is it good to do it using 'bindService'? Because I feel that there's something not right.

答:
You can send messages from the Service to Activities with the BroadcastReceiver class. I would get your information from the following link:

https://developer.android.com/guide/components/broadcasts


问:
getting some values in the table view rows in an iphone app
hii every one

i am new to iphone, i have done a sample data entry project in that i am saving data into the sqlite then displaying the saved data in the table view , & then on click of each row of the table it will go to other page (grouped table view where i am displying detailed data) now i have the table view like this

on click of each row it will go to detailed view like this

then on click of back button it ill come back to data list  screen but it ill add some other data into the screen like this

i am using reload data in view will apear ,, is that causing this problem?it works fine  if i comment that n try,,

can any one help me

thanx in advance

答:
Check your array values in didSelectRowAtIndexPath delegate whether you have different arrays or not.

If yes then use [yourArray objectAtIndex:indexPath.row]


问:
how sockets or communication channels are maintained in distibuted system
I am new to distributed systems, and came to this problem once needed to deploy a gRPC service to kubernetes (GKE). As far as I know, when a client initiate an rpc, it creates a long lasting http2 connection and further calls are multiplexed on it. I like to send/push notifications or similar messages to the client through this connection. If I deploy to multiple pod, then the connections are spread across them, and not sure what is the best way to locate the instance where the channel is registered to the client. A possible solution could be, as soon as user initiate a connection, keep a reference of clientId and pod ip (or some identification) in a centralized service and other pods lookup the pod and forward the message to it. Is something like is advisable or is there an existing solution for this? I am unfamiliar with this space and any suggestion is highly appreciated.

Edit: (response to @mebius99)

While looking at deploying option, I stumbled upon GKE, and other cloud deployment options were limited because of my use of gRPC/http2. Thanks for mentioning service discovery , and that or service mesh might be an option. With gRPC, client maintains a long lived connection to a single pod. So, I want every pod to be able to query, based on unique clientId (clients can do an initial register rpc call), which pod is it connected, so can make use of this connection and also a way pods to forward the message between them. So, something like when I get a registration call from client, I update the central registry about the client and pod ip, then look it up from any pod and forward package to it so it further forward to client through the existing streaming connection.  You guiding me to the right direction, please let me know above is possible in container environment.

thank you.

答:
I just want to add more explanations to the existing answers here.

Since requests in HTTP/2 is multiplexed (multiple requests can be active on the same connection at any point in time), requests will be just pinned to a single Kubernetes pod. Hence, we need to configure a service mesh to shift from connection-based balancing to request-based balancing. Envoy Proxy mentioned here is one example.

I'd recommend everyone to read this good article from Kubernetes blog https://kubernetes.io/blog/2018/11/07/grpc-load-balancing-on-kubernetes-without-tears.


问:
React Native - [Unhandled promise rejection: Error: Signup Error]
I get this intentional error because I'm using the same email to register. It says I'm not handling the rejection; can someone explain why because I have a .catch() which should catch any errors that were thrown

Error code:

```<code>[Unhandled promise rejection: Error: Signup Error]
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:146:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:194:17 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:407:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
</code>```

from this fetch().then().catch() code:

```<code> fetch(
      "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[ API KEY ]",
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password, returnSecureToken: true }),
      }
    )
      .then((res) => {
        if (!res.ok) {
          throw new Error("Signup Error");
        } else {
          const resData = res.json();
          return resData;
        }
      })
      .then((resData) => {
        console.log({ resData });
        dispatch({ type: SIGNUP });
      })
      .catch((err) => {
        console.log({ errHere: err });
        throw err;
      });
</code>```

The try{}catch(){} code that does work:

```<code>try {
      const res = await fetch(
        "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[ API KEY ]",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email, password, returnSecureToken: true }),
        }
      );

      if (!res.ok) {
        throw new Error("Signup Error");
      }

      const resData = await res.json();

      console.log({ resData });
    } catch (err) {
      throw err;
    }
</code>```

I've redone this code with try catch and it works but this puzzles me, so I need to know why it doesn't work with the .then().catch() handlers

The React code is this:

```<code>const signupHandler = useCallback(async () => {
    console.log(formState.inputValues.email, formState.inputValues.password);
    dispatch(
      signup(formState.inputValues.email, formState.inputValues.password)
    )
      .then(() => {
        console.log("OK!");
      })
      .catch((err) => {
        console.log({ errOutside: err });
      });
  }, [dispatch]);
</code>```

and as I said it works with the try catch method.

答:
dispatch is a synchronous method in redux and in try catch you used async await which is asynchronous
what you can do is adding a asynchronous dispatch middleware to your redux store

```<code>const asyncDispatchMiddleware = (store) => (next) => (action) => {
  let syncActivityFinished = false;
  let actionQueue = [];

  function flushQueue() {
    actionQueue.forEach((a) => store.dispatch(a)); // flush queue
    actionQueue = [];
  }

  function asyncDispatch(asyncAction) {
    actionQueue = actionQueue.concat([asyncAction]);

    if (syncActivityFinished) {
      flushQueue();
    }
  }

  const actionWithAsyncDispatch = Object.assign({}, action, { asyncDispatch });

  next(actionWithAsyncDispatch);
  syncActivityFinished = true;
  flushQueue();
};
</code>```

now you can make in promise scheme the asyncDispatch method

Body:
I get this intentional error because I'm using the same email to register. It says I'm not handling the rejection; can someone explain why because I have a .catch() which should catch any errors that were thrown

Error code:

[Unhandled promise rejection: Error: Signup Error]
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:146:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:194:17 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:407:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in callFunctionReturnFlushedQueue

from this fetch().then().catch() code:

 fetch(
      "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[ API KEY ]",
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password, returnSecureToken: true }),
      }
    )
      .then((res) => {
        if (!res.ok) {
          throw new Error("Signup Error");
        } else {
          const resData = res.json();
          return resData;
        }
      })
      .then((resData) => {
        console.log({ resData });
        dispatch({ type: SIGNUP });
      })
      .catch((err) => {
        console.log({ errHere: err });
        throw err;
      });

The try{}catch(){} code that does work:

try {
      const res = await fetch(
        "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[ API KEY ]",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email, password, returnSecureToken: true }),
        }
      );

      if (!res.ok) {
        throw new Error("Signup Error");
      }

      const resData = await res.json();

      console.log({ resData });
    } catch (err) {
      throw err;
    }

I've redone this code with try catch and it works but this puzzles me, so I need to know why it doesn't work with the .then().catch() handlers

The React code is this:

const signupHandler = useCallback(async () => {
    console.log(formState.inputValues.email, formState.inputValues.password);
    dispatch(
      signup(formState.inputValues.email, formState.inputValues.password)
    )
      .then(() => {
        console.log("OK!");
      })
      .catch((err) => {
        console.log({ errOutside: err });
      });
  }, [dispatch]);

and as I said it works with the try catch method.

Body:
dispatch is a synchronous method in redux and in try catch you used async await which is asynchronous
what you can do is adding a asynchronous dispatch middleware to your redux store

const asyncDispatchMiddleware = (store) => (next) => (action) => {
  let syncActivityFinished = false;
  let actionQueue = [];

  function flushQueue() {
    actionQueue.forEach((a) => store.dispatch(a)); // flush queue
    actionQueue = [];
  }

  function asyncDispatch(asyncAction) {
    actionQueue = actionQueue.concat([asyncAction]);

    if (syncActivityFinished) {
      flushQueue();
    }
  }

  const actionWithAsyncDispatch = Object.assign({}, action, { asyncDispatch });

  next(actionWithAsyncDispatch);
  syncActivityFinished = true;
  flushQueue();
};

now you can make in promise scheme the asyncDispatch method


问:
Non-integer constant in GROUP BY
I have the following line of code that is supposed to build a Pandas DataFrame from a SQL query:

```<code>query_epd = pandas.read_sql_query("SELECT 'Department', COUNT('LastName') FROM thestaff.employees GROUP BY 'Department'", engine)
</code>```

Yet when I run my code this line gives me the error:

```<code>SyntaxError: non-integer constant in GROUP BY
LINE 1: ...OUNT('LastName') FROM thestaff.employees GROUP BY 'Departmen...
                                                             ^
</code>```

I don't see where or how I am using constants, integer or not, and this is a very standard query for me on MSSQL, but running under PostgreSQL and Pandas this query is not valid. What is wrong with my query?

答:
The single quotes around the identifiers turn them to literal strings, which is probably not what you want. You should write this query as:

```<code>SELECT department, COUNT(*) no_emp
FROM thestaff.employees
GROUP BY department
</code>```

If your identifiers are case-sensitive, then you need to surround them with double quotes (this is the SQL standard, which Postgres complies to).

Note that I changed COUNT(lastname) to COUNT(*): unless you have null values in the lastname column, this is equivalent, and more efficient. I also gave an alias to this column in the resultset.

Title: Non-integer constant in GROUP BY

Body:
I have the following line of code that is supposed to build a Pandas DataFrame from a SQL query:

query_epd = pandas.read_sql_query("SELECT 'Department', COUNT('LastName') FROM thestaff.employees GROUP BY 'Department'", engine)

Yet when I run my code this line gives me the error:

SyntaxError: non-integer constant in GROUP BY
LINE 1: ...OUNT('LastName') FROM thestaff.employees GROUP BY 'Departmen...
                                                             ^

I don't see where or how I am using constants, integer or not, and this is a very standard query for me on MSSQL, but running under PostgreSQL and Pandas this query is not valid. What is wrong with my query?

Body:
The single quotes around the identifiers turn them to literal strings, which is probably not what you want. You should write this query as:

SELECT department, COUNT(*) no_emp
FROM thestaff.employees
GROUP BY department

If your identifiers are case-sensitive, then you need to surround them with double quotes (this is the SQL standard, which Postgres complies to).

Note that I changed COUNT(lastname) to COUNT(*): unless you have null values in the lastname column, this is equivalent, and more efficient. I also gave an alias to this column in the resultset.


问:
What is the purpose of -p, --project-name option in docker-compose command
What is the purpose of -p or --project-name option in docker-compose command?

What is the use case for it?

I am a newbie and havent yet started docker networking. Is --project-name used there in docker networking?

When I add docker support in Visual Studio 2019, Visual Studio runs some docker compose command which look like below. In each of them, there is a -p option. I am curious about that.

```<code>docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi config
docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi build
docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi up -d --no-build --force-recreate --remove-orphans
</code>```

I have seen the docker docs here and also this, but could not get much from there.

答:
If you run docker-compose multiple times, it uses the project name to keep one directory's containers, networks, and volumes separate from another's.  Compose doesn't keep any filesystem state or run a background daemon, so metadata on the containers is the only way to keep track of this.

Say you have three Compose projects, and project-a/docker-compose.yml, project-b/docker-compose.yml, and project-c/docker-compose.yml all have a service named db:.  Because their project names are different, Compose knows that it shouldn't reuse one db container for another project, it knows which container should be destroyed by docker-compose down, and so on.

A docker-compose -p option is required if you want to run multiple copies of the same Compose stack in the same directory.  Otherwise the directory name is used as the default project name, and they'd conflict with each other.  That's probably what Visual Studio is thinking about.

If you look at docker ps, docker network ls, and docker volume ls output you will see the name included in object names, project-a_db_1.  If you use the detailed inspect forms of these commands you will see some Compose-related labels, and these are what Compose actually looks for.

Body:
What is the purpose of -p or --project-name option in docker-compose command?

What is the use case for it?

I am a newbie and havent yet started docker networking. Is --project-name used there in docker networking?

When I add docker support in Visual Studio 2019, Visual Studio runs some docker compose command which look like below. In each of them, there is a -p option. I am curious about that.

docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi config
docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi build
docker-compose  -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\docker-compose.override.yml" -f "D:\Trials\Docker\VsDokWeb\DokWeb3\obj\Docker\docker-compose.vs.debug.g.yml" -p dockercompose5511081461456614166 --no-ansi up -d --no-build --force-recreate --remove-orphans

I have seen the docker docs here and also this, but could not get much from there.


问:
Unity sprite is missing on the display, but is showing in the editor
In my Unity project sprite is missing on the display, but is showing in the editor.

答:
Well, the only  solution I found was to create new game object with all the same components and settings. I still do not know the reason of my problem, so lets consider it as Unity bug.

Right now it seems to me that Y coordinate was too little.