问:
EF DefaultIfEmpty where statement
I have three tables and I am trying to get the Customer Response. This Customer has not Answer the question so in the MeetingPollingResponseValues CustomerId is null as well as MeetingPollingPartsValuesId. But I need to have that where (mppss.MeetingPollingPartsId == MeetingPollingPartsId && mppvs.CustomerId == CustomerId) for when Customer has data in that table. I have a the DefaultIfEmpty so I  not sure if I need to add or to the where statement?

DB Tables

```<code>CREATE TABLE [dbo].[MeetingPollingParts](
    [MeetingPollingPartsId] [int] IDENTITY(1,1) NOT NULL,
    [MeetingPollingQuestionId] [int] NULL,
    [MeetingPollingPartsTypeId] [int] NULL
  )

CREATE TABLE [dbo].[MeetingPollingPartsValues](
    [MeetingPollingPartsValuesId] [int] IDENTITY(1,1) NOT NULL,
    [QuestionValue] [nvarchar](max) NULL,
    [MeetingPollingPartsValuesTypeId] [int] NULL,
    [MeetingPollingPartsId] [int] NULL
    )

CREATE TABLE [dbo].[MeetingPollingResponseValues](
    [MeetingPollingResponseValuesId] [int] IDENTITY(1,1) NOT NULL,
    [MeetingPollingPartsValuesId] [int] NULL,
    [CustomerId] [int] NULL
)
</code>```

DB

```<code>  QuestionValue| MeetingPollingPartsId| MeetingPollingPartsValuesId| CustomerId
  --------------------------------------------------------------------------------
    Yes        | 588                  | NULL                       | NULL
    No         | 588                  | NULL                       | NULL
</code>```

EF

```<code>var MeetingPollingParticipantsAnswers = (from mppss in db.MeetingPollingParts
        join mppv in db.MeetingPollingPartsValues on mppss.MeetingPollingPartsId equals mppv.MeetingPollingPartsId
        join mppvs in db.MeetingPollingResponseValues on mppv.MeetingPollingPartsValuesId equals mppvs.MeetingPollingPartsValuesId into actualAnswers
        from mppvs in actualAnswers.DefaultIfEmpty()
        where (mppss.MeetingPollingPartsId == MeetingPollingPartsId && mppvs.CustomerId == CustomerId)
                select new Model.MeetingPollingParticipantsAnswers
                {
                Question = mppv.QuestionValue,
                Selected = aa.MeetingPollingPartsValuesId == aa.MeetingPollingPartsValuesId ? true : false,
                MeetingPollingPartsValuesId = aa.MeetingPollingPartsValuesId
                }).ToList();
</code>```

Title: EF DefaultIfEmpty where statement

Body:
I have three tables and I am trying to get the Customer Response. This Customer has not Answer the question so in the MeetingPollingResponseValues CustomerId is null as well as MeetingPollingPartsValuesId. But I need to have that where (mppss.MeetingPollingPartsId == MeetingPollingPartsId && mppvs.CustomerId == CustomerId) for when Customer has data in that table. I have a the DefaultIfEmpty so I  not sure if I need to add or to the where statement?

DB Tables

CREATE TABLE [dbo].[MeetingPollingParts](
    [MeetingPollingPartsId] [int] IDENTITY(1,1) NOT NULL,
    [MeetingPollingQuestionId] [int] NULL,
    [MeetingPollingPartsTypeId] [int] NULL
  )

CREATE TABLE [dbo].[MeetingPollingPartsValues](
    [MeetingPollingPartsValuesId] [int] IDENTITY(1,1) NOT NULL,
    [QuestionValue] [nvarchar](max) NULL,
    [MeetingPollingPartsValuesTypeId] [int] NULL,
    [MeetingPollingPartsId] [int] NULL
    )

CREATE TABLE [dbo].[MeetingPollingResponseValues](
    [MeetingPollingResponseValuesId] [int] IDENTITY(1,1) NOT NULL,
    [MeetingPollingPartsValuesId] [int] NULL,
    [CustomerId] [int] NULL
)

DB

  QuestionValue| MeetingPollingPartsId| MeetingPollingPartsValuesId| CustomerId
  --------------------------------------------------------------------------------
    Yes        | 588                  | NULL                       | NULL
    No         | 588                  | NULL                       | NULL

EF

var MeetingPollingParticipantsAnswers = (from mppss in db.MeetingPollingParts
        join mppv in db.MeetingPollingPartsValues on mppss.MeetingPollingPartsId equals mppv.MeetingPollingPartsId
        join mppvs in db.MeetingPollingResponseValues on mppv.MeetingPollingPartsValuesId equals mppvs.MeetingPollingPartsValuesId into actualAnswers
        from mppvs in actualAnswers.DefaultIfEmpty()
        where (mppss.MeetingPollingPartsId == MeetingPollingPartsId && mppvs.CustomerId == CustomerId)
                select new Model.MeetingPollingParticipantsAnswers
                {
                Question = mppv.QuestionValue,
                Selected = aa.MeetingPollingPartsValuesId == aa.MeetingPollingPartsValuesId ? true : false,
                MeetingPollingPartsValuesId = aa.MeetingPollingPartsValuesId
                }).ToList();


来源: stackexchange

问:
Benchmarking of the CPU overhead introduced by .so library or Linux executable
I'm looking for a reliable way to measure quantitatively the CPU overhead introduced by my shared library. The library is loaded in the context of php-fpm process (as a PHP extension). Ultimately, I'd like to run a series of tests for two versions of the .so library, collect stats and compare it, to see that to what extent the current version of library is better/worse than the previous one.

I have already tried a few approaches.

"perf stat" connected to PHP-FPM process and measuring cpu-cycles, instructions, and cpu-time

"perf record" connected to PHP-FPM process and collecting CPU cycles. Then I extract data from the collected perf.data. I consider only data related to my .so file and all-inclusive invocations (itself + related syscalls and kernel). So I can get CPU overhead for .so (inclusively).

valgrind on a few scripts running from CLI measuring "instruction requests".

All three options work but don't provide a reliable way for overhead comparison due to deviations (it might be up to 30% error, which is not applicable). It tried to do multiple runs and calculate the average, but the accuracy of that is also questionable.

Valgrind is the most accurate among all, but it provides only the "instructions" which do not give actual CPU overhead. Perf is better (considering the cycles, cpu-time, and instructions), but it gives too high errors from run to run.

Have anyone got experience in similar tasks? Could you recommend other approaches or Linux profilers to measure overhead accurately and quantitatively?
Thanks!

ContentLicense: CC BY-SA 4.0


问:
Get Account Telegram bot telethon
Can I get information about a user in telegrams by phone number? That is, the logic is as follows: Send the phone number to the bot for processing, it will check if there is an account, if yes, it will display the message "yes", if not, then no.

I tried but could not figure out the telegram API, namely, I could not find a use.

Title: Get Account Telegram bot telethon


问:
PIL ImageOps equalize function damages the image pixels
I am working on a mammography dataset and while trying different filters that might help the model to learn better, I came across this error.
(images are screenshots from the mammography images because it is a private dataset!)

PIL.ImageOps.equalize() function distort the image from left to right.

How to prevent the function to mess the image?
Or how can I pick images that may cause this problem before give them to model in preprocess stage( What kind of operation or function may help to split this image from others)?


问:
Override MSTest Parameters in RunSettings file
I have a .runsettings file that contains the following.

```<code>    <?xml version="1.0" encoding="utf-8" ?>
<RunSettings>
    <!-- MSTest adapter -->
    <MSTest>
        <Parallelize>
            <Workers>1</Workers>
            <Scope>ClassLevel</Scope>
        </Parallelize>
    </MSTest>
</RunSettings>
</code>```

Is it possible to override the Workers and Scope settings from the VsTest@2 task in an Azure DevOps pipeline?

The documentation for the VsTest@2 task only mentions overriding TestRunParameters.

Body:
I have a .runsettings file that contains the following.

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

    <MSTest>
        <Parallelize>
            <Workers>1</Workers>
            <Scope>ClassLevel</Scope>
        </Parallelize>
    </MSTest>
</RunSettings>

Is it possible to override the Workers and Scope settings from the VsTest@2 task in an Azure DevOps pipeline?

The documentation for the VsTest@2 task only mentions overriding TestRunParameters.


问:
Is there a way to make Pyreverse display arrows for lists?
I noticed that when a class has a single instance of another class that the arrow between the two classes is being displayed without any problems. But Pyreverse doesn't display arrows between classes if the instance variable is a list. Is there any way to display the arrow between two classes in that case?

Given is the following Python code:

class Class1:
    def __init__(self):
        self.attribute: str

class Class2:
    def __init__(self):
        self.attribute: str

class Class3:
    def __init__(self):
        self.class1_single_instance: Class1
        self.class2_list_instance: list[Class2]
```

The following UML diagram is produced by Pyreverse:

However I would like to have an output like this:

As you can see in the ideal output there is an arrow between Class1 and Class2 and the cardinality * is given in order to differentiate between instance variables with cardinality 1 and instance variables with arbitrary cardinality.

I appreciate your help!

Body:
I noticed that when a class has a single instance of another class that the arrow between the two classes is being displayed without any problems. But Pyreverse doesn't display arrows between classes if the instance variable is a list. Is there any way to display the arrow between two classes in that case?

Given is the following Python code:

class Class1:
    def __init__(self):
        self.attribute: str

class Class2:
    def __init__(self):
        self.attribute: str

class Class3:
    def __init__(self):
        self.class1_single_instance: Class1
        self.class2_list_instance: list[Class2]

The following UML diagram is produced by Pyreverse:

However I would like to have an output like this:

As you can see in the ideal output there is an arrow between Class1 and Class2 and the cardinality * is given in order to differentiate between instance variables with cardinality 1 and instance variables with arbitrary cardinality.

I appreciate your help!


问:
When would you use Java Native Interface, excluding interfacing with libraries in other languages or to access platform dependent functionality?
I understand using JNI for language bindings to libraries written in C/C++ or to access platform specific functionality unavailable to Java. I'm thinking along the lines of making a GUI or using Java for file management, basically the things that are difficult to do in a cross platform manner, and then send complicated data crunching as a batch job to functions written in C/C++ using only standard libraries. This would allow the same program to be used across Windows, Linux, and Mac while having the speed of a native compiled language.

Is this something that is actually done or is the Java Virtual Machine and JIT compiling good enough to make any performance improvement from using JNI negligible?

The project I had in mind was to make a printed circuit board (PCB) design software and sometimes tasks in it are computationally intense. This includes auto-routing the traces if you don't want to run them yourself and design rule checks which basically ensure your PCB is electrically identical to your schematic and also compliant with what the PCB manufacturer can do. These seem like batch tasks that you could send to a C/C++ function for processing.


问:
Redux redux getServerSideProps items are re-rendered after returning to the page
I pass a series of items to redux in getServerSideProps and it works well. But the problem is that when the user goes to another address on the site (without refreshing the page), when he returns to the main page, the redux items are executed again, and I don't want it to be like this, I want it to be executed only the first time and by changing the address. Don't run redux getServerSideProps again!

What is the solution? Should I use getServerSideProps here or something else?

Thankful

I read somewhere that I should use getInitialProps, but I'm not sure and does using it have a negative impact on SEO?


问:
Getting a TypeScript error in Declaration or statement expected. TS1128
trying to use the dialog sample progect and I am getting the following error: @mui/base/FormControlUnstyled/index.d.ts(3,1):
Declaration or statement expected.  TS1128

```<code>1 | export { default } from './FormControlUnstyled';
2 | export { default as FormControlUnstyledContext } from './FormControlUnstyledContext';
</code>```

3 | export type { FormControlUnstyledProps, FormControlUnstyledComponentsPropsOverrides, FormControlUnstyledState, } from './FormControlUnstyled.types';
| ^

I am expecting the dialog sample to work

Body:
trying to use the dialog sample progect and I am getting the following error: @mui/base/FormControlUnstyled/index.d.ts(3,1):
Declaration or statement expected.  TS1128

1 | export { default } from './FormControlUnstyled';
2 | export { default as FormControlUnstyledContext } from './FormControlUnstyledContext';

3 | export type { FormControlUnstyledProps, FormControlUnstyledComponentsPropsOverrides, FormControlUnstyledState, } from './FormControlUnstyled.types';
| ^

I am expecting the dialog sample to work


问:
A java.lang.NullPointerException exception has occurred

A java.lang.NullPointerException exception has occurred.
However, the system should continue working without further problems.
When I create a class, I get this error.
Can you help me fix this error?


问:
add_filter public function
How can I create a filter for public function?
I want to change a function in the plugin, for example:

public function display_plugin_page() { require_once OCDI_PATH . 'views/import.php'; }

Title: add_filter public function


问:
CSS `overflow-wrap: break-word;` applied to sequence of whitespaces
I struggle to understand what's the expected behavior of overflow-wrap: break-word; when applied to a long sequence of whitespaces, and specifically Ideographic Space (U+3000).

So far I've actually tested on all kind of whitespaces (Unicode Category “Zs - Space Separator”). In Chrome, all of other whitespaces wrap except Ideographic Space. But in Safari, Ideographic Space also wraps like others. See demo:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Ideographic Space</title>

```

I've gone through related CSS Specs, but fail to understand how to interpret it on this specific point. And since two popular browsers behave differently, I guess this could be a bug in one of them, I'm just not sure which (but intuitively, I guess Chrome is to blame).

I want to make Ideographic Space wrap like other whitespaces in Chrome, but I don't really want to use white-space: break-spaces, which does work, but it also comes with other undesired behaviors like preserving unwanted whitespaces.

Here's the svelte page I used to experiment on the problem.

Hope someone familiar with the subject can shed some light on it. Thanks.

Body:
I struggle to understand what's the expected behavior of overflow-wrap: break-word; when applied to a long sequence of whitespaces, and specifically Ideographic Space (U+3000).

So far I've actually tested on all kind of whitespaces (Unicode Category “Zs - Space Separator”). In Chrome, all of other whitespaces wrap except Ideographic Space. But in Safari, Ideographic Space also wraps like others. See demo:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Ideographic Space</title>

I've gone through related CSS Specs, but fail to understand how to interpret it on this specific point. And since two popular browsers behave differently, I guess this could be a bug in one of them, I'm just not sure which (but intuitively, I guess Chrome is to blame).

I want to make Ideographic Space wrap like other whitespaces in Chrome, but I don't really want to use white-space: break-spaces, which does work, but it also comes with other undesired behaviors like preserving unwanted whitespaces.

Here's the svelte page I used to experiment on the problem.

Hope someone familiar with the subject can shed some light on it. Thanks.


问:
SQL Server 2014 : Merge replication and transactional on same database
We currently have merge replication setup between Server 1 and Server 2. Server 2 is in a different geographic location. The merge replication is there so that users in the same region as Server 2 hit the database on Server 2 and those closest to Server 1 will hit the DB on Server 1.

Server 1 is SQL Server 2014 and also acts as the distributor. We are a bit tied down in terms of how many servers we can have hence not having a separate server to be the distributor.

We've also got a database on the same SQL Server instance of Server 1, that we have set up purely for reporting purposes. The idea being that when budget allows this will be moved to a separate server to separate the load.

Our reporting tables are currently populated nightly through SSIS which isn't ideal as some reports need to be more live. Because of this we're considering setting the reporting DB up as a transactional replication subscriber to the main DB.

My questions are:

Is this possible? i.e. Can a DB be distributing in both a merge replication environment and a transactional replication environment?


问:
html2canvas moving location of polyline
I've trying to create a pdf from html that includes a map with a polyline. The map is rendered correctly in the pdf but the polyline has been moved. This is what the map should look like original image but this is how it is shown in the pdf incorrect saved image.

This is my code. Note the element I am exporting contains many other parts besides the map.

```<code>`  exportProcedure(){
    var element=document.getElementById('divToExport');
    var outputName= this.submission.requestId + '.pdf';

    var opt = {
      margin:       [1,0,1,0],
      filename:     outputName,
      image:        {type: 'jpeg',quality:1},
      html2canvas:  {scale: 1, useCORS: true, allowTaint:true},
      pagebreak:    {mode: 'avoid-all'},
      jspdf:        {unit: 'in',format: 'letter', orientation: 'portrait',precision: '12'}
     };

    let doc = html2pdf().set(opt).from(element).toPdf()
}`
</code>```

What do I need to add to get the polyline in the correct place?

Title: html2canvas moving location of polyline

Body:
I've trying to create a pdf from html that includes a map with a polyline. The map is rendered correctly in the pdf but the polyline has been moved. This is what the map should look like original image but this is how it is shown in the pdf incorrect saved image.

This is my code. Note the element I am exporting contains many other parts besides the map.

`  exportProcedure(){
    var element=document.getElementById('divToExport');
    var outputName= this.submission.requestId + '.pdf';

    var opt = {
      margin:       [1,0,1,0],
      filename:     outputName,
      image:        {type: 'jpeg',quality:1},
      html2canvas:  {scale: 1, useCORS: true, allowTaint:true},
      pagebreak:    {mode: 'avoid-all'},
      jspdf:        {unit: 'in',format: 'letter', orientation: 'portrait',precision: '12'}
     };

    let doc = html2pdf().set(opt).from(element).toPdf()
}`

What do I need to add to get the polyline in the correct place?


问:
Why import "*.css" not working in vite vue3
I am building vue3 application with vite.
My dependencies:
"devDependencies": {
"@quasar/vite-plugin": "^1.0.4",
"@types/leaflet": "^1.9.0",
"@types/lodash": "^4.14.189",
"@vitejs/plugin-vue": "^2.0.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"leaflet": "^1.9.3",
"sass": "1.32.0",
"typescript": "^4.4.4",
"vite": "^2.7.2",
"vue-tsc": "^0.29.8"
}

I made leaflet map on my component but it looks very strange.
I thought that it's style issue, so imported leaflet style but it's not working.

```<code>import L from "leaflet";
import "leaflet/dist/leaflet.css";
</code>```

What's the reason?

Body:
I am building vue3 application with vite.
My dependencies:
"devDependencies": {
"@quasar/vite-plugin": "^1.0.4",
"@types/leaflet": "^1.9.0",
"@types/lodash": "^4.14.189",
"@vitejs/plugin-vue": "^2.0.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"leaflet": "^1.9.3",
"sass": "1.32.0",
"typescript": "^4.4.4",
"vite": "^2.7.2",
"vue-tsc": "^0.29.8"
}

I made leaflet map on my component but it looks very strange.
I thought that it's style issue, so imported leaflet style but it's not working.

import L from "leaflet";
import "leaflet/dist/leaflet.css";

What's the reason?


问:
Accessing initial page request status
I am using Tampermonkey to inject scripts into sites I am using so I don't have access to the server. I am open to Tampermonkey-specific solutions if they exist

I want to access the HTTP-request for the current page to check the HTTP status on it, sending a new HTTP-request to the same URL would take too long in my case. I can't find any resources on how to do this, so I don't know if this is even possible.

I am currently checking the document.title for known "page not found"-messages to work around this, but this is obviously sub-optimal as these vary from site to site.

Is there a way to access the page request/request-status like I described?

Title: Accessing initial page request status


问:
react beautiful dnd horizontal scroll breaks item selection in dnd
when dragging an item inside container with horizontal scroll using react-beautiful-dnd, selection of item inside  bugs and I can't select anything until I delete one item from the list

code from component with DnD

<ScrollBox>
    <Droppable droppableId={droppableId} direction={direction}>
         ...
    </Droppable>
</ScrollBox>
```
<p>ScrollBox component</p>
<pre class="lang-js prettyprint-override"><code> <div
        ref={listContainerRef}
        className={`max-w-full ${
          showOnlyOnMobile
            ? 'overflow-x-hidden xl:overflow-x-auto'
            : 'overflow-x-hidden'
        } relative mt-4`}
      >
        <div ref={listRef} className="whitespace-nowrap w-full flex flex-col">
          {children}
        </div>
      </div>
</code>```

I have no idea what to try so if anyone ran into this problem, I would appreciate your help so much!

Body:
when dragging an item inside container with horizontal scroll using react-beautiful-dnd, selection of item inside  bugs and I can't select anything until I delete one item from the list

code from component with DnD

<ScrollBox>
    <Droppable droppableId={droppableId} direction={direction}>
         ...
    </Droppable>
</ScrollBox>

ScrollBox component

          {children}

I have no idea what to try so if anyone ran into this problem, I would appreciate your help so much!


问:
Os.walk function gives None value to path
I tried to use os.walk function to retreive some data (tsv files) from different folders. The folder names are in a list. This is my code:

```<code>import os

def find_folders(folders):
    for folder in folders:
       return folder

def find_directories(search_path,folder):
    for root, dirs, files in os.walk(search_path):
        for dir in dirs:
            if dir == folder:
                open_dir = os.path.join(root,dir)
                return open_dir
def find_abundance_files(directory):
    for root,dirs,files in os.walk(directory):
        for file in files:
            if file.endswith(".tsv"):
                return file
def main():
    search_path = r"/mnt/e/Thesis/Parasponia_RNAseq/kal_out/"
    folders=["Medtru_BUD","Medtru_FLOWER","Medtru_LEAF","Medtru_NODULE","Medtru_ROOT","Medtru_SEED"]
    folder = find_folders(folders)
    directory = find_directories(search_path,folder)
    abundance_file = find_abundance_files(directory)

if __name__=="__main__":
    main()
</code>```

The problem is that the os.walk refuses to read the search_path as a path and returns "None".
I also thought the problem occurs because the path is linux related, I used windows path and still I faced the same issue. Do you know why it does that?
This is the error:

```<code>Traceback (most recent call last):
  File "C:\Users\gidio\PycharmProjects\flask_blog\CalculateRPK_paired_end.py", line 105, in <module>
    main()
  File "C:\Users\gidio\PycharmProjects\flask_blog\CalculateRPK_paired_end.py", line 100, in main
    abundance_file = find_abundance_files(directory)
  File "C:\Users\gidio\PycharmProjects\flask_blog\CalculateRPK_paired_end.py", line 81, in find_abundance_files
    for root,dirs,files in os.walk(directory):
  File "C:\ProgramData\Anaconda3\lib\os.py", line 342, in walk
    return _walk(fspath(top), topdown, onerror, followlinks)
TypeError: expected str, bytes or os.PathLike object, not NoneType
</code>```

Body:
I tried to use os.walk function to retreive some data (tsv files) from different folders. The folder names are in a list. This is my code:

import os

def find_folders(folders):
    for folder in folders:
       return folder

def find_directories(search_path,folder):
    for root, dirs, files in os.walk(search_path):
        for dir in dirs:
            if dir == folder:
                open_dir = os.path.join(root,dir)
                return open_dir
def find_abundance_files(directory):
    for root,dirs,files in os.walk(directory):
        for file in files:
            if file.endswith(".tsv"):
                return file
def main():
    search_path = r"/mnt/e/Thesis/Parasponia_RNAseq/kal_out/"
    folders=["Medtru_BUD","Medtru_FLOWER","Medtru_LEAF","Medtru_NODULE","Medtru_ROOT","Medtru_SEED"]
    folder = find_folders(folders)
    directory = find_directories(search_path,folder)
    abundance_file = find_abundance_files(directory)

if __name__=="__main__":
    main()

The problem is that the os.walk refuses to read the search_path as a path and returns "None".
I also thought the problem occurs because the path is linux related, I used windows path and still I faced the same issue. Do you know why it does that?
This is the error:

Traceback (most recent call last):
  File "C:\Users\gidio\PycharmProjects\flask_blog\CalculateRPK_paired_end.py", line 105, in <module>
    main()
  File "C:\Users\gidio\PycharmProjects\flask_blog\CalculateRPK_paired_end.py", line 100, in main
    abundance_file = find_abundance_files(directory)
  File "C:\Users\gidio\PycharmProjects\flask_blog\CalculateRPK_paired_end.py", line 81, in find_abundance_files
    for root,dirs,files in os.walk(directory):
  File "C:\ProgramData\Anaconda3\lib\os.py", line 342, in walk
    return _walk(fspath(top), topdown, onerror, followlinks)
TypeError: expected str, bytes or os.PathLike object, not NoneType


问:
Trouble signing in to visual studio 2019 while using Microsoft 365 from GoDaddy
I am trying to sign in to visual studio using the email myname@mydomain.com while using Microsoft 365 from GoDaddy. All I get is a script error message as per the attached screenshot. The dialogue doesn't go away despite clicking Yes or No, I have to turn off the PC altogether. The domain name is registered with GoDaddy.

I have tried re-installing visual studio, disabled third-party extensions and logged in as administrator with no change.

All help is appreciated to solve this problem.


问:
PgAdmin for the connection I got error lost ssh-agent error
I've configured connection, but I always get lost ssh-agent. The database can only through proxy connected.

Can I somewhere see the detailed error, what does it means really lost ssh-agent.


问:
Is there a way to embed applied CSS within a URL?
Is there a way to embed CSS within a URL?

My intent is to provide a URL to my users that formats content--it's pretty simple CSS to accomplish my goal.  Can this be done and, if so, how?


问:
Add edges by verticies
Helloo,
I am trying to create a graph where I have a list of nodes and perform a calculation to get the distance between the nodes. Between the nodes where the calculation returns true, I want to add edges and print this edges as a adj-list, but this does not work. My edge list is empty. What can be the reason? Below is my code.

thanks

```<code>      for (Ladestation verticies: dataList)
        {
            myGraphi.addVertex(verticies);

           }
            for(int j= 1; j< myGraphi.getVertices().size()+1;j++) {
                myHavarsine.haversine(myGraphi.getVertices().get(j-1).getPosition().getBreitengrad(),
                        myGraphi.getVertices().get(j-1).getPosition().getLaengengrad(), myGraphi.getVertices()
                                .get(j).getPosition().getBreitengrad(), myGraphi.getVertices().get(j).getPosition().getLaengengrad());
                if (myHavarsine.getResult() <= userEingabeMaxabstand) {

                    myGraphi.addEdgebyVertices(myGraphi.getVertices().get(j-1), myGraphi.getVertices().get(j));

                    System.out.println("Von "+ myGraphi.getVertex(j-1).getPosition().getPostleitzahl() +" ausgehende Kanten: "+myGraphi.getEdgesFromVertex(myGraphi.getVertex(j-1)));

                }

            }

            System.out.println("Die Anzahl von Knoten: "+myGraphi.getVertices().size());

Graph class
public class Graph<T>
{
    private Map<Integer, T> vertices;
    private List<Edge> edges;
    private int maxIndex = 0;

    /**
     * Konstruktur initialisiert Knoten- und Kantenliste als leer.
     */
    public Graph()
    {
        this.vertices = new HashMap<>();
        this.edges = new ArrayList<>();
    }

    /**
     * alle Kanten auslesen
     * @return Liste der Kanten
     */
    public List<Edge> getEdges()
    {
        return this.edges;
    }

    /**
     * alle Knoten auslesen
     * @return Map der Knoten
     */
    public Map<Integer, T> getVertices()
    {
        return this.vertices;
    }

    /**
     * einen Knoten anhand seines Index ermitteln
     * @param index Index des gewünschten Knotens
     * @return Knoten mit dem eingegebenen Index oder null, falls nicht vorhanden
     */

    public T getVertex (int index)
    {
        if(this.vertices.containsKey(index))
        {
             return this.vertices.get(index);
        }
        return null;
    }

    /**
     * Einen neue Knoten hinzufügen.
     * @param vertex Knoten
     * @return nächster freier Index
     */
    public int addVertex (T vertex)
    {
        if(!this.vertices.containsValue(vertex))
        {
            int index = this.maxIndex;
            this.vertices.put(this.maxIndex++, vertex);
            return index;
        }
        /*
         *Kein Knoten hinzugefügt
         */
        return -1;
    }
    /**
     * Eine Kante anhand von Knoten-Index hinzufügen.
     * Die Kante wird stets in beide Richtungen angelegt
     * @param from Index des Startknotens
     * @param to Index des Zielknotens
     */

    public void addEdge (int from, int to)
    {
        Edge fromEdge = new Edge(from, to);
        Edge toEdge = new Edge(to, from);
        if(!this.edges.contains(fromEdge)){
            this.edges.add(fromEdge);
        }
        if(!this.edges.contains(toEdge))
        {
            this.edges.add(toEdge);
        }
    }

    /***
     * Eine Kante anhand von Knotenwerten hinzufügen
     * Falls noch nicht vorhanden füg auch die Knoten hinzu.
     * @param fromVertex Startknoten
     * @param toVertex Zielknoten
     */

    public void addEdgebyVertices (T fromVertex, T toVertex)
    {
        int from = this.getIndexForVertex(fromVertex);
       if(from == -1)
        {
            from = this.addVertex(fromVertex);
        }
        int to = this.getIndexForVertex(toVertex);
       if(to ==-1)
        {
            to = this.addVertex(toVertex);
        }

        this.addEdge(from, to);
    }

    /**
     * den Index eines Knotens ermitteln.
     *
     * @param vertex Gesuchter Knoten
     * @return Index oder -1, falls der Knoten nicht existiert
     */

    public int getIndexForVertex (T vertex)
    {
        if(!this.vertices.containsKey(vertex))
        {
            return -1;
        }
       for (Map.Entry<Integer, T> entry:this.vertices.entrySet())
       {
           if (entry.getValue().equals(vertex))
           {
               return entry.getKey();
           }
       }

        return -1;
    }

    /**
     * alle von einem Knoten ausgehenden Kanten ermitteln.
     * @param vertex Der Knoten, dessen Kanten gesucht sind
     *
     * @return Liste der Kanten
     */
    public List<Edge> getEdgesFromVertex (T vertex)
    {
        List<Edge> result = new ArrayList<>();
        int index = this.getIndexForVertex(vertex);
        if (index > -1)
        {
            for (Edge edge: this.edges)
            {
                if(edge.getFrom() == index)
                {
                    result.add(edge);
                    return result;
                }
            }
        }
        return result;
    }

</code>```

Title: Add edges by verticies

Body:
Helloo,
I am trying to create a graph where I have a list of nodes and perform a calculation to get the distance between the nodes. Between the nodes where the calculation returns true, I want to add edges and print this edges as a adj-list, but this does not work. My edge list is empty. What can be the reason? Below is my code.

thanks

      for (Ladestation verticies: dataList)
        {
            myGraphi.addVertex(verticies);

           }
            for(int j= 1; j< myGraphi.getVertices().size()+1;j++) {
                myHavarsine.haversine(myGraphi.getVertices().get(j-1).getPosition().getBreitengrad(),
                        myGraphi.getVertices().get(j-1).getPosition().getLaengengrad(), myGraphi.getVertices()
                                .get(j).getPosition().getBreitengrad(), myGraphi.getVertices().get(j).getPosition().getLaengengrad());
                if (myHavarsine.getResult() <= userEingabeMaxabstand) {

                    myGraphi.addEdgebyVertices(myGraphi.getVertices().get(j-1), myGraphi.getVertices().get(j));

                    System.out.println("Von "+ myGraphi.getVertex(j-1).getPosition().getPostleitzahl() +" ausgehende Kanten: "+myGraphi.getEdgesFromVertex(myGraphi.getVertex(j-1)));

                }

            }

            System.out.println("Die Anzahl von Knoten: "+myGraphi.getVertices().size());

Graph class
public class Graph<T>
{
    private Map<Integer, T> vertices;
    private List<Edge> edges;
    private int maxIndex = 0;

    /**
     * Konstruktur initialisiert Knoten- und Kantenliste als leer.
     */
    public Graph()
    {
        this.vertices = new HashMap<>();
        this.edges = new ArrayList<>();
    }

    /**
     * alle Kanten auslesen
     * @return Liste der Kanten
     */
    public List<Edge> getEdges()
    {
        return this.edges;
    }

    /**
     * alle Knoten auslesen
     * @return Map der Knoten
     */
    public Map<Integer, T> getVertices()
    {
        return this.vertices;
    }

    /**
     * einen Knoten anhand seines Index ermitteln
     * @param index Index des gewünschten Knotens
     * @return Knoten mit dem eingegebenen Index oder null, falls nicht vorhanden
     */

    public T getVertex (int index)
    {
        if(this.vertices.containsKey(index))
        {
             return this.vertices.get(index);
        }
        return null;
    }

    /**
     * Einen neue Knoten hinzufügen.
     * @param vertex Knoten
     * @return nächster freier Index
     */
    public int addVertex (T vertex)
    {
        if(!this.vertices.containsValue(vertex))
        {
            int index = this.maxIndex;
            this.vertices.put(this.maxIndex++, vertex);
            return index;
        }
        /*
         *Kein Knoten hinzugefügt
         */
        return -1;
    }
    /**
     * Eine Kante anhand von Knoten-Index hinzufügen.
     * Die Kante wird stets in beide Richtungen angelegt
     * @param from Index des Startknotens
     * @param to Index des Zielknotens
     */

    public void addEdge (int from, int to)
    {
        Edge fromEdge = new Edge(from, to);
        Edge toEdge = new Edge(to, from);
        if(!this.edges.contains(fromEdge)){
            this.edges.add(fromEdge);
        }
        if(!this.edges.contains(toEdge))
        {
            this.edges.add(toEdge);
        }
    }

    /***
     * Eine Kante anhand von Knotenwerten hinzufügen
     * Falls noch nicht vorhanden füg auch die Knoten hinzu.
     * @param fromVertex Startknoten
     * @param toVertex Zielknoten
     */

    public void addEdgebyVertices (T fromVertex, T toVertex)
    {
        int from = this.getIndexForVertex(fromVertex);
       if(from == -1)
        {
            from = this.addVertex(fromVertex);
        }
        int to = this.getIndexForVertex(toVertex);
       if(to ==-1)
        {
            to = this.addVertex(toVertex);
        }

        this.addEdge(from, to);
    }

    /**
     * den Index eines Knotens ermitteln.
     *
     * @param vertex Gesuchter Knoten
     * @return Index oder -1, falls der Knoten nicht existiert
     */

    public int getIndexForVertex (T vertex)
    {
        if(!this.vertices.containsKey(vertex))
        {
            return -1;
        }
       for (Map.Entry<Integer, T> entry:this.vertices.entrySet())
       {
           if (entry.getValue().equals(vertex))
           {
               return entry.getKey();
           }
       }

        return -1;
    }

    /**
     * alle von einem Knoten ausgehenden Kanten ermitteln.
     * @param vertex Der Knoten, dessen Kanten gesucht sind
     *
     * @return Liste der Kanten
     */
    public List<Edge> getEdgesFromVertex (T vertex)
    {
        List<Edge> result = new ArrayList<>();
        int index = this.getIndexForVertex(vertex);
        if (index > -1)
        {
            for (Edge edge: this.edges)
            {
                if(edge.getFrom() == index)
                {
                    result.add(edge);
                    return result;
                }
            }
        }
        return result;
    }


问:
Reseting the value of auto_increment field of a django model with `_set_next_value()`
MyModel Definition

class MyModel(models.Model):
    name = models.CharField(max_length=50)
```
<p>To reset the auto increment to a new value</p>
<pre class="lang-py prettyprint-override"><code>from django.db import migrations

def set_id(apps, schema_editor):
    MyModel = apps.get_model('myapp', 'MyModel')
    max_id = MyModel.objects.all().aggregate(max_id=Max('id'))['max_id']
    MyModel._meta.get_field('id').auto_created = True
    MyModel._meta.get_field('id').auto_created = False
    MyModel._meta.get_field('id')._set_next_value(max_id + 1)

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '<your previous migration>'),
    ]

    operations = [
        migrations.RunPython(set_id),
    ]
</code>```

Line

MyModel._meta.get_field('id')._set_next_value(max_id + 1)
```
<p>Giving Error</p>
```AttributeError: 'AutoField' object has no attribute '_set_next_value'

```

Trying to reset the AutoField to a specific value so that new entries id would start from that id.

However I'm getting this error.

Body:
MyModel Definition

class MyModel(models.Model):
    name = models.CharField(max_length=50)

To reset the auto increment to a new value

from django.db import migrations

def set_id(apps, schema_editor):
    MyModel = apps.get_model('myapp', 'MyModel')
    max_id = MyModel.objects.all().aggregate(max_id=Max('id'))['max_id']
    MyModel._meta.get_field('id').auto_created = True
    MyModel._meta.get_field('id').auto_created = False
    MyModel._meta.get_field('id')._set_next_value(max_id + 1)

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '<your previous migration>'),
    ]

    operations = [
        migrations.RunPython(set_id),
    ]

Line

MyModel._meta.get_field('id')._set_next_value(max_id + 1)

Giving Error

AttributeError: 'AutoField' object has no attribute '_set_next_value'

Trying to reset the AutoField to a specific value so that new entries id would start from that id.

However I'm getting this error.


问:
Audio and video not going to the other user after implementing Screen Share
After implementing the screen share, the audio and video did not go to the opposite user on video internets. What could be the reason for this?

Before implementing screen share, there was no problem with transmitting audio and video. But in some cases, after turning screen sharing on and off, I noticed that the problem of transmitting audio and video was solved. This does not happen in all cases.

```<code>class AgoraUploader {

    private static let videoDimension : CGSize = {
        guard let screenSize = UIScreen.main.currentMode?.size else { return .zero }
        var boundingSize = CGSize(width: 720, height: 1280)
        let mW = boundingSize.width / screenSize.width
        let mH = boundingSize.height / screenSize.height
        if( mH < mW ) {
            boundingSize.width = boundingSize.height / screenSize.height * screenSize.width
        }
        else if( mW < mH ) {
            boundingSize.height = boundingSize.width / screenSize.width * screenSize.height
        }
        return boundingSize
    }()

    private static let audioSampleRate: UInt = 48000
    private static let audioChannels: UInt = 2

    private static let sharedAgoraEngine: AgoraRtcEngineKit = {
        let kit = AgoraRtcEngineKit.sharedEngine(withAppId: KeyCenter.appId, delegate: nil)
        kit.setChannelProfile(.liveBroadcasting)
        kit.setClientRole(.broadcaster)

        kit.enableVideo()
        kit.setExternalVideoSource(true, useTexture: true, pushMode: true)
        let videoConfig = AgoraVideoEncoderConfiguration(size: videoDimension,
                                                         frameRate: .fps30,
                                                         bitrate: 910,
                                                         orientationMode: .adaptative)
        kit.setVideoEncoderConfiguration(videoConfig)

        kit.setAudioProfile(.musicStandardStereo, scenario: .default)
        kit.setRecordingAudioFrameParametersWithSampleRate(Int(audioSampleRate),
                                                           channel: Int(audioChannels),
                                                           mode: .readWrite,
                                                           samplesPerCall: 1024)
        kit.setParameters("{\"che.audio.external_device\":true}")
        kit.setParameters("{\"che.hardware_encoding\":1}")
        kit.setParameters("{\"che.video.enc_auto_adjust\":0}")

        kit.muteAllRemoteVideoStreams(true)
        kit.muteAllRemoteAudioStreams(true)

        return kit
    }()

    static func startBroadcast(to channel: String, to token: String) {
        sharedAgoraEngine.joinChannel(byToken: token, channelId: channel, info: nil, uid: 1000, joinSuccess: nil)
    }

    static func sendVideoBuffer(_ sampleBuffer: CMSampleBuffer) {
        guard let videoFrame = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }

        var rotation : Int32 = 0
        if let orientationAttachment = CMGetAttachment(sampleBuffer, key: RPVideoSampleOrientationKey as CFString, attachmentModeOut: nil) as? NSNumber {
            if let orientation = CGImagePropertyOrientation(rawValue: orientationAttachment.uint32Value) {
                switch orientation {
                case .up,    .upMirrored:    rotation = 0
                case .down,  .downMirrored:  rotation = 180
                case .left,  .leftMirrored:  rotation = 90
                case .right, .rightMirrored: rotation = 270
                default:   break
                }
            }
        }

        let time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
        let frame = AgoraVideoFrame()
        frame.format = 12
        frame.time = time
        frame.textureBuf = videoFrame
        frame.rotation = rotation
        sharedAgoraEngine.pushExternalVideoFrame(frame)
    }

    static func stopBroadcast() {
        sharedAgoraEngine.leaveChannel(nil)
        AgoraRtcEngineKit.destroy()
    }
}

class SampleHandler: RPBroadcastSampleHandler {

    let pref = UserDefaults.init(suiteName: "group.ai.ekos.global")
    var bufferCopy: CMSampleBuffer?
    var lastSendTs: Int64 = Int64(Date().timeIntervalSince1970 * 1000)
    var timer: Timer?

    override func broadcastStarted(withSetupInfo setupInfo: [String : NSObject]?) {
        if let channelName = pref?.string(forKey: "screen_share_channel"), let token = pref?.string(forKey: "screen_share_token") {
            print("channelName: ", channelName)
            AgoraUploader.startBroadcast(to: channelName, to: token)
            pref?.set("1", forKey: "screen_share_isstart")
            DispatchQueue.main.async {
                self.timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) {[weak self] (timer:Timer) in
                    guard let weakSelf = self else {return}
                    let elapse = Int64(Date().timeIntervalSince1970 * 1000) - weakSelf.lastSendTs
                    print("elapse: \(elapse)")
                    if(elapse > 300) {
                        if let buffer = weakSelf.bufferCopy {
                            weakSelf.processSampleBuffer(buffer, with: .video)
                        }
                    }
                }
            }
        }
        else {
            print("channelName not found")
            pref?.set("0", forKey: "screen_share_isstart")
        }
        pref?.synchronize()
    }

    override func broadcastPaused() {
        // User has requested to pause the broadcast. Samples will stop being delivered.
        pref?.set("0", forKey: "screen_share_isstart")
        pref?.synchronize()
    }

    override func broadcastResumed() {
        // User has requested to resume the broadcast. Samples delivery will resume.
        pref?.set("1", forKey: "screen_share_isstart")
        pref?.synchronize()
    }

    override func broadcastFinished() {
        // User has requested to finish the broadcast.
        timer?.invalidate()
        timer = nil
        pref?.set("0", forKey: "screen_share_isstart")
        pref?.synchronize()
        AgoraUploader.stopBroadcast()
    }

    override func finishBroadcastWithError(_ error: Error) {
        pref?.set("0", forKey: "screen_share_isstart")
        pref?.synchronize()
    }

    override func processSampleBuffer(_ sampleBuffer: CMSampleBuffer, with sampleBufferType: RPSampleBufferType) {
        DispatchQueue.main.async { [weak self] in
            switch sampleBufferType {
            case .video:
                if let weakSelf = self {
                    weakSelf.bufferCopy = sampleBuffer
                    weakSelf.lastSendTs = Int64(Date().timeIntervalSince1970 * 1000)
                }
                AgoraUploader.sendVideoBuffer(sampleBuffer)
            case .audioApp, .audioMic:
                break
            @unknown default:
                break
            }
        }
    }
}
</code>```

Body:
After implementing the screen share, the audio and video did not go to the opposite user on video internets. What could be the reason for this?

Before implementing screen share, there was no problem with transmitting audio and video. But in some cases, after turning screen sharing on and off, I noticed that the problem of transmitting audio and video was solved. This does not happen in all cases.

class AgoraUploader {

    private static let videoDimension : CGSize = {
        guard let screenSize = UIScreen.main.currentMode?.size else { return .zero }
        var boundingSize = CGSize(width: 720, height: 1280)
        let mW = boundingSize.width / screenSize.width
        let mH = boundingSize.height / screenSize.height
        if( mH < mW ) {
            boundingSize.width = boundingSize.height / screenSize.height * screenSize.width
        }
        else if( mW < mH ) {
            boundingSize.height = boundingSize.width / screenSize.width * screenSize.height
        }
        return boundingSize
    }()

    private static let audioSampleRate: UInt = 48000
    private static let audioChannels: UInt = 2

    private static let sharedAgoraEngine: AgoraRtcEngineKit = {
        let kit = AgoraRtcEngineKit.sharedEngine(withAppId: KeyCenter.appId, delegate: nil)
        kit.setChannelProfile(.liveBroadcasting)
        kit.setClientRole(.broadcaster)

        kit.enableVideo()
        kit.setExternalVideoSource(true, useTexture: true, pushMode: true)
        let videoConfig = AgoraVideoEncoderConfiguration(size: videoDimension,
                                                         frameRate: .fps30,
                                                         bitrate: 910,
                                                         orientationMode: .adaptative)
        kit.setVideoEncoderConfiguration(videoConfig)

        kit.setAudioProfile(.musicStandardStereo, scenario: .default)
        kit.setRecordingAudioFrameParametersWithSampleRate(Int(audioSampleRate),
                                                           channel: Int(audioChannels),
                                                           mode: .readWrite,
                                                           samplesPerCall: 1024)
        kit.setParameters("{\"che.audio.external_device\":true}")
        kit.setParameters("{\"che.hardware_encoding\":1}")
        kit.setParameters("{\"che.video.enc_auto_adjust\":0}")

        kit.muteAllRemoteVideoStreams(true)
        kit.muteAllRemoteAudioStreams(true)

        return kit
    }()

    static func startBroadcast(to channel: String, to token: String) {
        sharedAgoraEngine.joinChannel(byToken: token, channelId: channel, info: nil, uid: 1000, joinSuccess: nil)
    }

    static func sendVideoBuffer(_ sampleBuffer: CMSampleBuffer) {
        guard let videoFrame = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }

        var rotation : Int32 = 0
        if let orientationAttachment = CMGetAttachment(sampleBuffer, key: RPVideoSampleOrientationKey as CFString, attachmentModeOut: nil) as? NSNumber {
            if let orientation = CGImagePropertyOrientation(rawValue: orientationAttachment.uint32Value) {
                switch orientation {
                case .up,    .upMirrored:    rotation = 0
                case .down,  .downMirrored:  rotation = 180
                case .left,  .leftMirrored:  rotation = 90
                case .right, .rightMirrored: rotation = 270
                default:   break
                }
            }
        }

        let time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
        let frame = AgoraVideoFrame()
        frame.format = 12
        frame.time = time
        frame.textureBuf = videoFrame
        frame.rotation = rotation
        sharedAgoraEngine.pushExternalVideoFrame(frame)
    }

    static func stopBroadcast() {
        sharedAgoraEngine.leaveChannel(nil)
        AgoraRtcEngineKit.destroy()
    }
}

class SampleHandler: RPBroadcastSampleHandler {

    let pref = UserDefaults.init(suiteName: "group.ai.ekos.global")
    var bufferCopy: CMSampleBuffer?
    var lastSendTs: Int64 = Int64(Date().timeIntervalSince1970 * 1000)
    var timer: Timer?

    override func broadcastStarted(withSetupInfo setupInfo: [String : NSObject]?) {
        if let channelName = pref?.string(forKey: "screen_share_channel"), let token = pref?.string(forKey: "screen_share_token") {
            print("channelName: ", channelName)
            AgoraUploader.startBroadcast(to: channelName, to: token)
            pref?.set("1", forKey: "screen_share_isstart")
            DispatchQueue.main.async {
                self.timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) {[weak self] (timer:Timer) in
                    guard let weakSelf = self else {return}
                    let elapse = Int64(Date().timeIntervalSince1970 * 1000) - weakSelf.lastSendTs
                    print("elapse: \(elapse)")
                    if(elapse > 300) {
                        if let buffer = weakSelf.bufferCopy {
                            weakSelf.processSampleBuffer(buffer, with: .video)
                        }
                    }
                }
            }
        }
        else {
            print("channelName not found")
            pref?.set("0", forKey: "screen_share_isstart")
        }
        pref?.synchronize()
    }

    override func broadcastPaused() {
        // User has requested to pause the broadcast. Samples will stop being delivered.
        pref?.set("0", forKey: "screen_share_isstart")
        pref?.synchronize()
    }

    override func broadcastResumed() {
        // User has requested to resume the broadcast. Samples delivery will resume.
        pref?.set("1", forKey: "screen_share_isstart")
        pref?.synchronize()
    }

    override func broadcastFinished() {
        // User has requested to finish the broadcast.
        timer?.invalidate()
        timer = nil
        pref?.set("0", forKey: "screen_share_isstart")
        pref?.synchronize()
        AgoraUploader.stopBroadcast()
    }

    override func finishBroadcastWithError(_ error: Error) {
        pref?.set("0", forKey: "screen_share_isstart")
        pref?.synchronize()
    }

    override func processSampleBuffer(_ sampleBuffer: CMSampleBuffer, with sampleBufferType: RPSampleBufferType) {
        DispatchQueue.main.async { [weak self] in
            switch sampleBufferType {
            case .video:
                if let weakSelf = self {
                    weakSelf.bufferCopy = sampleBuffer
                    weakSelf.lastSendTs = Int64(Date().timeIntervalSince1970 * 1000)
                }
                AgoraUploader.sendVideoBuffer(sampleBuffer)
            case .audioApp, .audioMic:
                break
            @unknown default:
                break
            }
        }
    }
}


问:
Plotly works in R Script, but does not work when using source in RMarkdown
I am working on a dashboard. I wrote a script to break up my rmarkdown file (flexdashboard). When I run the script in R it works fine. However when I use source, and try to render the document. I get the error "At least one layer must contain all faceting variables, Name").

I have done this before with similar types of data. I was expecting the dashboard to load.

```<code>structure(list(Date = structure(c(19368, 19368, 19368, 19368,
19368, 19368, 19368, 19368, 19369, 19369, 19369, 19369, 19369,
19369, 19369, 19366, 19366, 19366, 19366, 19366, 19366, 19366,
19366), class = "Date"), Name = c("Player 1", "Player 2", "Player 3",
"Player 5", "Player 7", "Player 10", "Player 11", "Player 12",
"Player 11", "Player 7", "Player 10", "Player 3", "Player 2",
"Player 1", "Player 12", "Player 10", "Player 12", "Player 3",
"Player 5", "Player 7", "Player 2", "Player 1", "Player 11"),
RPE = c(6, 5, 6, 5, 5, 4, 5, 6, 4, 6, 6, 7, 6, 7, 5, 5, 5,
4, 4, 5, 5, 6, 4), Legginess = c(7, 6, 6, 6, 4, 5, 8, 5,
8, 5, 5, 7, 6, 6, 5, 4, 4, 4, 4, 3, 2, 5, 4), Breathlessness = c(5,
5, 5, 4, 5, 3, 6, 6, 3, 4, 6, 3, 6, 5, 4, 5, 6, 5, 4, 4,
6, 6, 6)), row.names = c(NA, -23L), class = c("tbl_df", "tbl",
"data.frame"))

rpe_plot <- rpe %>%
  ggplot(aes(Date, RPE)) +
  geom_col() +
  labs(title = "RPE for the Week",
   x = "",
   y = "") +
  facet_wrap(~Name, scales = "free")

plot_1 <- ggplotly(rpe_plot)
</code>```

I then load this on my rmarkdown document using source.

```<code>---
title: "RPE_Dashboard"
output:
  flexdashboard::flex_dashboard:
    vertical_layout: fill
editor_options:
  chunk_output_type: console
---
</code>```
```<code>library(flexdashboard)
library(tidyverse)
library(janitor)
library(plotly)
library(here)
library(data.table)
</code>```
```<code># RPE Summary {data-orientation=rows}

## Row

### Individual RPE
</code>```
```<code>source(here("RPE_Dashboard/RPE_Script.R"))

plot_1
</code>```

Body:
I am working on a dashboard. I wrote a script to break up my rmarkdown file (flexdashboard). When I run the script in R it works fine. However when I use source, and try to render the document. I get the error "At least one layer must contain all faceting variables, Name").

I have done this before with similar types of data. I was expecting the dashboard to load.

structure(list(Date = structure(c(19368, 19368, 19368, 19368,
19368, 19368, 19368, 19368, 19369, 19369, 19369, 19369, 19369,
19369, 19369, 19366, 19366, 19366, 19366, 19366, 19366, 19366,
19366), class = "Date"), Name = c("Player 1", "Player 2", "Player 3",
"Player 5", "Player 7", "Player 10", "Player 11", "Player 12",
"Player 11", "Player 7", "Player 10", "Player 3", "Player 2",
"Player 1", "Player 12", "Player 10", "Player 12", "Player 3",
"Player 5", "Player 7", "Player 2", "Player 1", "Player 11"),
RPE = c(6, 5, 6, 5, 5, 4, 5, 6, 4, 6, 6, 7, 6, 7, 5, 5, 5,
4, 4, 5, 5, 6, 4), Legginess = c(7, 6, 6, 6, 4, 5, 8, 5,
8, 5, 5, 7, 6, 6, 5, 4, 4, 4, 4, 3, 2, 5, 4), Breathlessness = c(5,
5, 5, 4, 5, 3, 6, 6, 3, 4, 6, 3, 6, 5, 4, 5, 6, 5, 4, 4,
6, 6, 6)), row.names = c(NA, -23L), class = c("tbl_df", "tbl",
"data.frame"))

rpe_plot <- rpe %>%
  ggplot(aes(Date, RPE)) +
  geom_col() +
  labs(title = "RPE for the Week",
   x = "",
   y = "") +
  facet_wrap(~Name, scales = "free")

plot_1 <- ggplotly(rpe_plot)

I then load this on my rmarkdown document using source.

---
title: "RPE_Dashboard"
output:
  flexdashboard::flex_dashboard:
    vertical_layout: fill
editor_options:
  chunk_output_type: console
---

library(flexdashboard)
library(tidyverse)
library(janitor)
library(plotly)
library(here)
library(data.table)

# RPE Summary {data-orientation=rows}

## Row

### Individual RPE

source(here("RPE_Dashboard/RPE_Script.R"))

plot_1


问:
WOOCOMMERCE - Order status automatically goes to Completed (code not working)
When getting an order in Woocommerce paid by card, the order status goes directly to Completed. I can't make it go to Processing first, as are the orders not paid online.
The products are not set as virtual/downloadable.

I've tried adding snippets of code found online to the functions.php of the child theme, nothing's working. This is the latest snippet I've tried:

```<code>
add_action( 'woocommerce_payment_complete_order_status', 'wc_auto_complete_paid_order', 10, 3 );
function wc_auto_complete_paid_order( $status, $order_id, $order ) {
    return 'processing';
}
</code>```

Anyone has other suggestions?

thanks!

Body:
When getting an order in Woocommerce paid by card, the order status goes directly to Completed. I can't make it go to Processing first, as are the orders not paid online.
The products are not set as virtual/downloadable.

I've tried adding snippets of code found online to the functions.php of the child theme, nothing's working. This is the latest snippet I've tried:

add_action( 'woocommerce_payment_complete_order_status', 'wc_auto_complete_paid_order', 10, 3 );
function wc_auto_complete_paid_order( $status, $order_id, $order ) {
    return 'processing';
}

Anyone has other suggestions?

thanks!


问:
Flutter firebase messaging - message after 5 minutes
My first post was: "I don't receive a message from Firebase messaging"

After I waited a couple of minutes, the message appeared on my physical device, where I build the app in release mode. So my new topic is: "I receive it but after 5 minutes and not in debug mode - does anybody know why?"

The old topic is below:

["solved"]

I created a brand-new project, did everything exactly like in several tutorials: https://www.youtube.com/watch?v=hJA09GwURtk
or: https://firebase.flutter.dev/docs/messaging/usage/

and I still don't recieve any messages when I create a campaign inside my console (Engage -> Cloud Messaging -> Compose notification) and no errors (expect:

```<code>E/SurfaceSyncer(13521): Failed to find sync for id=1
D/FLTFireMsgReceiver(13521): broadcast received for message
I/flutter (13521): onMessage:
[log] W/FirebaseMessaging(13521): Unable to log event: analytics library is missing
onMessage: Instance of 'RemoteMessage'
W/FirebaseMessaging(13521): Unable to log event: analytics library is missing
D/EGL_emulation(13521): app_time_stats: avg=73722.07ms min=283.28ms max=147160.86ms count=2
</code>```

but I receive this error even I don't send a notification). It's just silent.

This is my main.dart:

```<code> Future<void> _firebaseMessagingBackgroundHandler(message) async {
      await Firebase.initializeApp();
      print('Handling a background message ${message.messageId}');
    }

    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      FirebaseMessaging messaging = FirebaseMessaging.instance;

      NotificationSettings settings = await messaging.requestPermission(
        alert: true,
        announcement: false,
        badge: true,
        carPlay: false,
        criticalAlert: false,
        provisional: false,
        sound: true,
      );

      if (settings.authorizationStatus == AuthorizationStatus.authorized) {
        print('User granted permission');
      } else if (settings.authorizationStatus == AuthorizationStatus.provisional) {
        print('User granted provisional permission');
      } else {
        print('User declined or has not accepted permission');
      }
      FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
      runApp(const MyApp());
    }
</code>```

I tried it with the initializing-flutterfire  (https://firebase.flutter.dev/docs/overview/#initializing-flutterfire) steps and without it. In both scenarios it doesn't work. I also tried different emulators and my physical phone. Still no notification and no errors.

When I start the app for the first time, this messages appear:

```<code>Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: D:\Installationsdatei\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_messaging-14.2.1\android\src\main\java\io\flutter\plugins\firebase\messaging\FlutterFirebaseMessagingPlugin.java uses unchecked or unsafe operations

Note: Recompile with -Xlint:unchecked for details.
</code>```

Is this the problem? :D

Body:
My first post was: "I don't receive a message from Firebase messaging"

After I waited a couple of minutes, the message appeared on my physical device, where I build the app in release mode. So my new topic is: "I receive it but after 5 minutes and not in debug mode - does anybody know why?"

The old topic is below:

["solved"]

I created a brand-new project, did everything exactly like in several tutorials: https://www.youtube.com/watch?v=hJA09GwURtk
or: https://firebase.flutter.dev/docs/messaging/usage/

and I still don't recieve any messages when I create a campaign inside my console (Engage -> Cloud Messaging -> Compose notification) and no errors (expect:

E/SurfaceSyncer(13521): Failed to find sync for id=1
D/FLTFireMsgReceiver(13521): broadcast received for message
I/flutter (13521): onMessage:
[log] W/FirebaseMessaging(13521): Unable to log event: analytics library is missing
onMessage: Instance of 'RemoteMessage'
W/FirebaseMessaging(13521): Unable to log event: analytics library is missing
D/EGL_emulation(13521): app_time_stats: avg=73722.07ms min=283.28ms max=147160.86ms count=2

but I receive this error even I don't send a notification). It's just silent.

This is my main.dart:

 Future<void> _firebaseMessagingBackgroundHandler(message) async {
      await Firebase.initializeApp();
      print('Handling a background message ${message.messageId}');
    }

    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      FirebaseMessaging messaging = FirebaseMessaging.instance;

      NotificationSettings settings = await messaging.requestPermission(
        alert: true,
        announcement: false,
        badge: true,
        carPlay: false,
        criticalAlert: false,
        provisional: false,
        sound: true,
      );

      if (settings.authorizationStatus == AuthorizationStatus.authorized) {
        print('User granted permission');
      } else if (settings.authorizationStatus == AuthorizationStatus.provisional) {
        print('User granted provisional permission');
      } else {
        print('User declined or has not accepted permission');
      }
      FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
      runApp(const MyApp());
    }

I tried it with the initializing-flutterfire  (https://firebase.flutter.dev/docs/overview/#initializing-flutterfire) steps and without it. In both scenarios it doesn't work. I also tried different emulators and my physical phone. Still no notification and no errors.

When I start the app for the first time, this messages appear:

Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: D:\Installationsdatei\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_messaging-14.2.1\android\src\main\java\io\flutter\plugins\firebase\messaging\FlutterFirebaseMessagingPlugin.java uses unchecked or unsafe operations

Note: Recompile with -Xlint:unchecked for details.

Is this the problem? :D


问:
Decrypting a file with Fernet in Python is returning an empty string
I was testing creating a function to decrypt files within a directory using cryptography.fernet, but all I'm getting back is an empty string. I have looked elsewhere but could not find an answer.

My current file is as such:

import os
from cryptography.fernet import Fernet

fileDirectory = input('Please specfy directory to decrypt\n > ')

os.chdir(fileDirectory)

f = open('key.txt', 'rb')
red = f.read()
print(red)
fernet = Fernet(red)
f.close()

dirContain = os.listdir()
print(dirContain)
dirContain.pop(dirContain.index('key.txt'))

print(dirContain)

for i in range(len(dirContain)):
    print(dirContain[i])
    f = open(dirContain[i], 'rb')
    rend = f.read()
    print(rend)
    data = fernet.decrypt(rend)
    print(data)
    f.close()
```
<p>And I get this as the output:</p>
```Please specfy directory to decrypt
 > test
uKPMID0YwQD0dneykrCkrUEnSwbFTRs-eDvXpF7KSi4=
['jibberish.txt', 'key.txt', 'otherJibberish.txt']
['jibberish.txt', 'otherJibberish.txt']
jibberish.txt
b'gAAAAABjwVrevzkZQoITAbDXYI2MlXgyBQIpTrYvwUnj0978KZxtrlZ46SUREyo3Zfg0S4c8kIDRQ2Qn59JSjVAlQ6RmYgg4yw=='
b''
otherJibberish.txt
b'gAAAAABjwVre4cpnG6Zn1iAZv6VcaUQt5-8sDtjQzj5PBd4F2aIeze_ka_MRmHwnhJP5WwSyQUOskF3--X-19DD9dUIRw-jIFw=='
b''

```

Any ideas as to what is going on? Also, the only difference between me reading the files as binary or text is that, while reading as text, printing the f.read() doesn't have the b'' around the content.

Body:
I was testing creating a function to decrypt files within a directory using cryptography.fernet, but all I'm getting back is an empty string. I have looked elsewhere but could not find an answer.

My current file is as such:

import os
from cryptography.fernet import Fernet

fileDirectory = input('Please specfy directory to decrypt\n > ')

os.chdir(fileDirectory)

f = open('key.txt', 'rb')
red = f.read()
print(red)
fernet = Fernet(red)
f.close()

dirContain = os.listdir()
print(dirContain)
dirContain.pop(dirContain.index('key.txt'))

print(dirContain)

for i in range(len(dirContain)):
    print(dirContain[i])
    f = open(dirContain[i], 'rb')
    rend = f.read()
    print(rend)
    data = fernet.decrypt(rend)
    print(data)
    f.close()

And I get this as the output:

Please specfy directory to decrypt
 > test
uKPMID0YwQD0dneykrCkrUEnSwbFTRs-eDvXpF7KSi4=
['jibberish.txt', 'key.txt', 'otherJibberish.txt']
['jibberish.txt', 'otherJibberish.txt']
jibberish.txt
b'gAAAAABjwVrevzkZQoITAbDXYI2MlXgyBQIpTrYvwUnj0978KZxtrlZ46SUREyo3Zfg0S4c8kIDRQ2Qn59JSjVAlQ6RmYgg4yw=='
b''
otherJibberish.txt
b'gAAAAABjwVre4cpnG6Zn1iAZv6VcaUQt5-8sDtjQzj5PBd4F2aIeze_ka_MRmHwnhJP5WwSyQUOskF3--X-19DD9dUIRw-jIFw=='
b''

Any ideas as to what is going on? Also, the only difference between me reading the files as binary or text is that, while reading as text, printing the f.read() doesn't have the b'' around the content.


问:
How to populate a list of objects from another object in Kotlin
I have the following code which is part of mapping the ouput of two rest apis to an object. The ownershipHistory is a List of objects and OwnerHolderReplies is a single class

```<code>   val ownerHolderReplies = OwnerHolderReplies()
   val ownerHolderReplyType = OwnerHolderReplyType()
   if (ownershipHistory != null) {
     for( obj in ownershipHistory) {
         ownerHolderReplyType.date = fromDate
         ownerHolderReplyType.vehicleHolder = getVehicleHolderData()
         ownerHolderReplyType.vehicleOwner = getVehicleOwnerData()

         ownerHolderReplies.vehOwnerHolderReply.add(ownerHolderReplyType)
     }
    }
    // code for using the next object. nothing to
</code>```

OwnerHolderReplies:

```<code>public class OwnerHolderReplyType implements Serializable {
    protected TechnicalData technicalData;
    protected VehicleHolder vehicleHolder;
    protected VehicleOwner vehicleOwner;
   ....
}
</code>```

is there a nicer way to do this?

cheers,

es.

Body:
I have the following code which is part of mapping the ouput of two rest apis to an object. The ownershipHistory is a List of objects and OwnerHolderReplies is a single class

   val ownerHolderReplies = OwnerHolderReplies()
   val ownerHolderReplyType = OwnerHolderReplyType()
   if (ownershipHistory != null) {
     for( obj in ownershipHistory) {
         ownerHolderReplyType.date = fromDate
         ownerHolderReplyType.vehicleHolder = getVehicleHolderData()
         ownerHolderReplyType.vehicleOwner = getVehicleOwnerData()

         ownerHolderReplies.vehOwnerHolderReply.add(ownerHolderReplyType)
     }
    }
    // code for using the next object. nothing to

OwnerHolderReplies:

public class OwnerHolderReplyType implements Serializable {
    protected TechnicalData technicalData;
    protected VehicleHolder vehicleHolder;
    protected VehicleOwner vehicleOwner;
   ....
}

is there a nicer way to do this?

cheers,

es.


问:
How to convert String to JSON in Kotlin
How to convert given string:

[1:["price":100, "dataAmount":0.5], 3:["price":300, "dataAmount":1], 5:["price":500, "dataAmount":2], 7:["price":700, "dataAmount":3], 10:["price":1000, "dataAmount":5], 31:["price":3100, "dataAmount":15], 365:["price":36000, "dataAmount":1024], 39:["price":3900, "dataAmount":20, "daysValid":31], 93:["price":9000, "dataAmount":150]]

to JSON in Kotlin ?

I tried to aply JSONObject()

Title: How to convert String to JSON in Kotlin


问:
Visual Studio Installer stuck at Windows SDK
my Visual Studio Installer has been stuck on this screen for a long time. I tried to install "Desktop Development with C++" and its tools but it's stuck on Windows SDK (package 426 out of 427). .
I looked on Google and one solution told to check for windows update. So I did, and my Windows is fully updated.
Any help will be appreciated.
Thanks in advance!


问:
Google Sheets Image Link Change as per Reference
Can I ask for help, please? I am using Excel as letter generator (I have a doc template linked to it). I want to add a link (it varies per person) to the letter. Is there a possibility that the URL (that changes) can be linked to an image automatically? So that they can just click on the photo and they'll be redirected to the URL.

I tried to add «URL» to the letter template so that it will automatically capture the links under the URL column in Google Sheets. It actually works. Howevery, I want to try to embed the URL to the photo automatically.


问:
Android got ForegroundServiceStartNotAllowedException in onResume()?
I see an exception from my google play console :

```<code>Exception java.lang.RuntimeException:
  at android.app.ActivityThread.performResumeActivity (ActivityThread.java:5365)
  at android.app.ActivityThread.handleResumeActivity (ActivityThread.java:5431)
  at android.app.servertransaction.TransactionExecutor.performLifecycleSequence (TransactionExecutor.java:225)
  at android.app.servertransaction.TransactionExecutor.cycleToPath (TransactionExecutor.java:201)
  at android.app.servertransaction.TransactionExecutor.executeLifecycleState (TransactionExecutor.java:173)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:97)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2571)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loopOnce (Looper.java:226)
  at android.os.Looper.loop (Looper.java:313)
  at android.app.ActivityThread.main (ActivityThread.java:8741)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:571)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1067)
Caused by android.app.ForegroundServiceStartNotAllowedException:
  at android.app.ForegroundServiceStartNotAllowedException$1.createFromParcel (ForegroundServiceStartNotAllowedException.java:54)
  at android.app.ForegroundServiceStartNotAllowedException$1.createFromParcel (ForegroundServiceStartNotAllowedException.java:50)
  at android.os.Parcel.readParcelableInternal (Parcel.java:4784)
  at android.os.Parcel.readParcelable (Parcel.java:4752)
  at android.os.Parcel.createExceptionOrNull (Parcel.java:3018)
  at android.os.Parcel.createException (Parcel.java:3007)
  at android.os.Parcel.readException (Parcel.java:2990)
  at android.os.Parcel.readException (Parcel.java:2932)
  at android.app.IActivityManager$Stub$Proxy.startService (IActivityManager.java:6201)
  at android.app.ContextImpl.startServiceCommon (ContextImpl.java:1967)
  at android.app.ContextImpl.startForegroundService (ContextImpl.java:1933)
  at android.content.ContextWrapper.startForegroundService (ContextWrapper.java:839)
  at androidx.core.content.ContextCompat$Api26Impl.startForegroundService (ContextCompat.java:931)
  at androidx.core.content.ContextCompat.startForegroundService (ContextCompat.java:703)
  at myPackage.myApplication.myFragment.onResume (myFragment.java:445)
  at androidx.fragment.app.Fragment.performResume (Fragment.java:3039)
  at androidx.fragment.app.FragmentStateManager.resume (FragmentStateManager.java:607)
  at androidx.fragment.app.FragmentStateManager.moveToExpectedState (FragmentStateManager.java:306)
  at androidx.fragment.app.FragmentStore.moveToExpectedState (FragmentStore.java:112)
  at androidx.fragment.app.FragmentManager.moveToState (FragmentManager.java:1647)
  at androidx.fragment.app.FragmentManager.dispatchStateChange (FragmentManager.java:3128)
  at androidx.fragment.app.FragmentManager.dispatchResume (FragmentManager.java:3086)
  at androidx.fragment.app.Fragment.performResume (Fragment.java:3048)
  at androidx.fragment.app.FragmentStateManager.resume (FragmentStateManager.java:607)
  at androidx.fragment.app.FragmentStateManager.moveToExpectedState (FragmentStateManager.java:306)
  at androidx.fragment.app.FragmentStore.moveToExpectedState (FragmentStore.java:112)
  at androidx.fragment.app.FragmentManager.moveToState (FragmentManager.java:1647)
  at androidx.fragment.app.FragmentManager.dispatchStateChange (FragmentManager.java:3128)
  at androidx.fragment.app.FragmentManager.dispatchResume (FragmentManager.java:3086)
  at androidx.fragment.app.FragmentController.dispatchResume (FragmentController.java:273)
  at androidx.fragment.app.FragmentActivity.onResumeFragments (FragmentActivity.java:458)
  at androidx.fragment.app.FragmentActivity.onPostResume (FragmentActivity.java:447)
  at android.app.Activity.performResume (Activity.java:8746)
  at android.app.ActivityThread.performResumeActivity (ActivityThread.java:5338)
</code>```

I amend the error message that showing my app name to:

```<code>    at myPackage.myApplication.myFragment.onResume (myFragment.java:445)
</code>```

As this error is from an android 13 samsung device, so I created an android 13 device in emulator, but cannot simulate the error...
I read the developer document about this excption, it is to prevent starting foreground service from background, I dont understand how starting a service in onResume() is deemed as from background?

Below is the onResume() method in myFragment.java

sc is ServiceConnection.class

This error is from the 2nd last line ContextCompat.startForegroundService()

```<code>@Override
public void onResume() {
    super.onResume();
    iFilter = new IntentFilter( "" + someId ) ;
    LocalBroadcastManager.getInstance(getContext()).registerReceiver(
                localBroadcastReceiver,
                iFilter);

    Intent bindIntent = new Intent(getActivity(), myService.class);
    ContextCompat.startForegroundService( getActivity(), bindIntent );
    getActivity().bindService(bindIntent, sc, Context.BIND_AUTO_CREATE);
}
</code>```

I suspect that this is a bug?

Body:
I see an exception from my google play console :

Exception java.lang.RuntimeException:
  at android.app.ActivityThread.performResumeActivity (ActivityThread.java:5365)
  at android.app.ActivityThread.handleResumeActivity (ActivityThread.java:5431)
  at android.app.servertransaction.TransactionExecutor.performLifecycleSequence (TransactionExecutor.java:225)
  at android.app.servertransaction.TransactionExecutor.cycleToPath (TransactionExecutor.java:201)
  at android.app.servertransaction.TransactionExecutor.executeLifecycleState (TransactionExecutor.java:173)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:97)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2571)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loopOnce (Looper.java:226)
  at android.os.Looper.loop (Looper.java:313)
  at android.app.ActivityThread.main (ActivityThread.java:8741)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:571)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1067)
Caused by android.app.ForegroundServiceStartNotAllowedException:
  at android.app.ForegroundServiceStartNotAllowedException$1.createFromParcel (ForegroundServiceStartNotAllowedException.java:54)
  at android.app.ForegroundServiceStartNotAllowedException$1.createFromParcel (ForegroundServiceStartNotAllowedException.java:50)
  at android.os.Parcel.readParcelableInternal (Parcel.java:4784)
  at android.os.Parcel.readParcelable (Parcel.java:4752)
  at android.os.Parcel.createExceptionOrNull (Parcel.java:3018)
  at android.os.Parcel.createException (Parcel.java:3007)
  at android.os.Parcel.readException (Parcel.java:2990)
  at android.os.Parcel.readException (Parcel.java:2932)
  at android.app.IActivityManager$Stub$Proxy.startService (IActivityManager.java:6201)
  at android.app.ContextImpl.startServiceCommon (ContextImpl.java:1967)
  at android.app.ContextImpl.startForegroundService (ContextImpl.java:1933)
  at android.content.ContextWrapper.startForegroundService (ContextWrapper.java:839)
  at androidx.core.content.ContextCompat$Api26Impl.startForegroundService (ContextCompat.java:931)
  at androidx.core.content.ContextCompat.startForegroundService (ContextCompat.java:703)
  at myPackage.myApplication.myFragment.onResume (myFragment.java:445)
  at androidx.fragment.app.Fragment.performResume (Fragment.java:3039)
  at androidx.fragment.app.FragmentStateManager.resume (FragmentStateManager.java:607)
  at androidx.fragment.app.FragmentStateManager.moveToExpectedState (FragmentStateManager.java:306)
  at androidx.fragment.app.FragmentStore.moveToExpectedState (FragmentStore.java:112)
  at androidx.fragment.app.FragmentManager.moveToState (FragmentManager.java:1647)
  at androidx.fragment.app.FragmentManager.dispatchStateChange (FragmentManager.java:3128)
  at androidx.fragment.app.FragmentManager.dispatchResume (FragmentManager.java:3086)
  at androidx.fragment.app.Fragment.performResume (Fragment.java:3048)
  at androidx.fragment.app.FragmentStateManager.resume (FragmentStateManager.java:607)
  at androidx.fragment.app.FragmentStateManager.moveToExpectedState (FragmentStateManager.java:306)
  at androidx.fragment.app.FragmentStore.moveToExpectedState (FragmentStore.java:112)
  at androidx.fragment.app.FragmentManager.moveToState (FragmentManager.java:1647)
  at androidx.fragment.app.FragmentManager.dispatchStateChange (FragmentManager.java:3128)
  at androidx.fragment.app.FragmentManager.dispatchResume (FragmentManager.java:3086)
  at androidx.fragment.app.FragmentController.dispatchResume (FragmentController.java:273)
  at androidx.fragment.app.FragmentActivity.onResumeFragments (FragmentActivity.java:458)
  at androidx.fragment.app.FragmentActivity.onPostResume (FragmentActivity.java:447)
  at android.app.Activity.performResume (Activity.java:8746)
  at android.app.ActivityThread.performResumeActivity (ActivityThread.java:5338)

I amend the error message that showing my app name to:

    at myPackage.myApplication.myFragment.onResume (myFragment.java:445)

As this error is from an android 13 samsung device, so I created an android 13 device in emulator, but cannot simulate the error...
I read the developer document about this excption, it is to prevent starting foreground service from background, I dont understand how starting a service in onResume() is deemed as from background?

Below is the onResume() method in myFragment.java

sc is ServiceConnection.class

This error is from the 2nd last line ContextCompat.startForegroundService()

@Override
public void onResume() {
    super.onResume();
    iFilter = new IntentFilter( "" + someId ) ;
    LocalBroadcastManager.getInstance(getContext()).registerReceiver(
                localBroadcastReceiver,
                iFilter);

    Intent bindIntent = new Intent(getActivity(), myService.class);
    ContextCompat.startForegroundService( getActivity(), bindIntent );
    getActivity().bindService(bindIntent, sc, Context.BIND_AUTO_CREATE);
}

I suspect that this is a bug?


问:
Flutter iOS override swipe back
Using Navigator 2.0, I managed to override back button presses on Android with popRoute override, but it doesn't works for iOS swipe back. Is there a way to override it ?

Title: Flutter iOS override swipe back


问:
How to fix typeError using crypto in nodejs
I am creating an endpoint for a sign up/login system and password encryption I chose to use hash method. However, I get the error.

```<code>TypeError [ERR_INVALID_ARG_TYPE]: The "password" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView. Received undefined.
</code>```

Code to create the hash method.

const getHash = function (password, salt) {
 return crypto
  .pbkdf2Sync(password, salt, 100000, 256, 'sha256')
  .toString('hex')
}
```
<p>Code to create a new user and call the has method to encrypt password.</p>
<pre class="lang-js prettyprint-override"><code>const addNewUser = function(user, done) {
    const salt = crypto.randomBytes(64);
    const hash = getHash(user.password, salt);

    const sql = 'INSERT INTO users (first_name, last_name, email, password, salt) VALUES (?,?,?,?,?)'

    let values = [user.first_name, user.last_name, user.email, hash, salt.toString('hex')];

    db.run(
        sql,
        values,
        function(err){

        if(err) return done(err,null);

        return done(null, this.lastID);
    })
}
</code>```

Body:
I am creating an endpoint for a sign up/login system and password encryption I chose to use hash method. However, I get the error.

TypeError [ERR_INVALID_ARG_TYPE]: The "password" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView. Received undefined.

Code to create the hash method.

const getHash = function (password, salt) {
 return crypto
  .pbkdf2Sync(password, salt, 100000, 256, 'sha256')
  .toString('hex')
}

Code to create a new user and call the has method to encrypt password.

const addNewUser = function(user, done) {
    const salt = crypto.randomBytes(64);
    const hash = getHash(user.password, salt);

    const sql = 'INSERT INTO users (first_name, last_name, email, password, salt) VALUES (?,?,?,?,?)'

    let values = [user.first_name, user.last_name, user.email, hash, salt.toString('hex')];

    db.run(
        sql,
        values,
        function(err){

        if(err) return done(err,null);

        return done(null, this.lastID);
    })
}


问:
Request method 'GET' is not supported
have two controllers, that should give Form (html +Thymeleaf) to Update entity and post new data, after redirect to List Entities;

My Controllers

```<code>@GetMapping ("/fromUpdate")
public String updateInstructor (Model model, Long instructorId) {
    Instructor instructor = instructorService.loadInstructorById(instructorId);
    model.addAttribute("instructor", instructor);
    return "views/updateInstructor";
}

@PostMapping ("/update")
public String update (Instructor instructor) {
    instructorService.updateInstructor(instructor);
    return "redirect:/instructors/index";
}
</code>```

Html form + Thymeleaf

```<code><div class="col-md-6 offset-3 mt-3">
        <form class="form-control" method="post"
            th:action="@{/instructors/update}" th:object="${instructor}">
            <div class="mb-3 mt-3">

                <label class="form-label"> Instructor Id :</label>
                <input type="number" name="instructorId" class="form-control"
                    th:value="${instructor.getInstructorId()}">
            </div>

            <div class="mb-3 mt-3">
                <label for="firstName" class="form-label"> First Name :</label>
                <input id="firstName" type="text" name="firstName" class="form-control"
                    th:value="${instructor.getInstructorFirstName()}">
            </div>
            <div class="mb-3 mt-3">

                <label for ="lastName" class="form-label"> Last Name :</label>
                <input id="lastName" type="text" name="lastName" class="form-control"
                    th:value="${instructor.getInstructorLastName()}">
            </div>

            <div class="mb-3 mt-3">
                <label for="instructorSummary" class="form-label"> Summary :</label>
                <input id="instructorSummary" type="text" name="instructorSummary" class="form-control"
                    th:value="${instructor.getInstructorSummary()}">
            </div>

            <div class="mb-3 mt-3" th:each ="course: ${instructor.getCourses()}">
                <input name="courses" class="form-control"
                    th:value="${instructor.courses[courseStat.index].getCourseId()}">
            </div>

            <div class ="mb-3 mt-3">
            <input name ="user" class="form-control" th:field="${instructor.user}">
            </div>

            <button type ="submit" class ="btn btn-primary"> Update </button>
        </form>

    </div>
</code>```

When i load update form i give next exception

```<code>80 --- [nio-8071-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' is not supported]
</code>```

Must say, when i set in first controller @GetMapping (value =/update) analogical Url with Post my form load  with all data.

If you know where my problem, please say me, tnx!!!

Title: Request method 'GET' is not supported

Body:
have two controllers, that should give Form (html +Thymeleaf) to Update entity and post new data, after redirect to List Entities;

My Controllers

@GetMapping ("/fromUpdate")
public String updateInstructor (Model model, Long instructorId) {
    Instructor instructor = instructorService.loadInstructorById(instructorId);
    model.addAttribute("instructor", instructor);
    return "views/updateInstructor";
}

@PostMapping ("/update")
public String update (Instructor instructor) {
    instructorService.updateInstructor(instructor);
    return "redirect:/instructors/index";
}

Html form + Thymeleaf

        <form class="form-control" method="post"
            th:action="@{/instructors/update}" th:object="${instructor}">

                 Instructor Id :
                <input type="number" name="instructorId" class="form-control"
                    th:value="${instructor.getInstructorId()}">

                 First Name :
                <input id="firstName" type="text" name="firstName" class="form-control"
                    th:value="${instructor.getInstructorFirstName()}">

                 Last Name :
                <input id="lastName" type="text" name="lastName" class="form-control"
                    th:value="${instructor.getInstructorLastName()}">

                 Summary :
                <input id="instructorSummary" type="text" name="instructorSummary" class="form-control"
                    th:value="${instructor.getInstructorSummary()}">

                <input name="courses" class="form-control"
                    th:value="${instructor.courses[courseStat.index].getCourseId()}">

            <input name ="user" class="form-control" th:field="${instructor.user}">

            <button type ="submit" class ="btn btn-primary"> Update </button>
        </form>

When i load update form i give next exception

80 --- [nio-8071-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' is not supported]

Must say, when i set in first controller @GetMapping (value =/update) analogical Url with Post my form load  with all data.

If you know where my problem, please say me, tnx!!!


问:
Micro service communication solution in the Azure service fabric
Recently I started working on an old Azure cloud based micro service project, which is running on Azure Service Fabric platform.

(I'm new to this platform, also I don't have team members for discussion. I can read the code and document to understand this project.)

I roughly understand how Service Fabric works. But one question confuses me a lot about inter service communications. I want to know which inter service communication solution my project is using.

Here are some useful information about this point:

Suppose the Azure Service Fabric cluster endpoint is as follows: myTestCluster.westus.cloudapp.azure.com:19000

The project use Consul for service discovery. In the codebase, before sending request to other services, first need to get the registered URL from consul. And the URL resolved from Consul is something as follows: myTestCluster.westus.cloudapp.azure.com:23333, which is another service deployed and run on the cluster. The code for sending request is something like:

            using (var client = new HttpClient())
            {
                var response = await client.PostAsync(uri); // uri is resolved from Consul
                return await response.Content.ReadAsStringAsync();
            }
```

I read some article and know that the potential inter-service communication methods are:

Service Fabric's Naming service: based on the method I shown above, I think it's not this one.

Reverse proxy

DNS service

But I can't tell out method 2 or 3, which one is used. Or any other ones?

Body:
Recently I started working on an old Azure cloud based micro service project, which is running on Azure Service Fabric platform.

(I'm new to this platform, also I don't have team members for discussion. I can read the code and document to understand this project.)

I roughly understand how Service Fabric works. But one question confuses me a lot about inter service communications. I want to know which inter service communication solution my project is using.

Here are some useful information about this point:

Suppose the Azure Service Fabric cluster endpoint is as follows: myTestCluster.westus.cloudapp.azure.com:19000

The project use Consul for service discovery. In the codebase, before sending request to other services, first need to get the registered URL from consul. And the URL resolved from Consul is something as follows: myTestCluster.westus.cloudapp.azure.com:23333, which is another service deployed and run on the cluster. The code for sending request is something like:

            using (var client = new HttpClient())
            {
                var response = await client.PostAsync(uri); // uri is resolved from Consul
                return await response.Content.ReadAsStringAsync();
            }

I read some article and know that the potential inter-service communication methods are:

Service Fabric's Naming service: based on the method I shown above, I think it's not this one.

Reverse proxy

DNS service

But I can't tell out method 2 or 3, which one is used. Or any other ones?


问:
How can I solve this problem in installing vue/cli
I am trying to install vue/cli by this order : npm install -g @vue/cli,
but this error always occuers :

npm WARN deprecated source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated subscriptions-transport-ws@0.11.0: The subscriptions-transport-ws package is no longer maintained. We recommend you use graphql-ws instead. For help migrating Apollo software to graphql-ws, see https://www.apollographql.com/docs/apollo-server/data/subscriptions/#switching-from-subscriptions-transport-ws    For general help using graphql-ws, see https://github.com/enisdenjo/graphql-ws/blob/master/README.md
npm ERR! code ERR_SOCKET_TIMEOUT
npm ERR! network Socket timeout
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\hp\AppData\Local\npm-cache_logs\2023-01-13T14_00_02_889Z-debug-0.log

How can I install ?

I tried to download several times but it didn't work and this error always occuers.


问:
My SQL SELECT STATEMENT returns an empty table instead of an error
My SELECT count function returns the number of kids in a specific profile that has in id (secte = id_profile). When I input an invalid profile, the select statement returns an empty table insead of an error that I can solve. Any tips? (The tables are created by me);

```<code>
CREATE OR REPLACE FUNCTION bursieri(sectie profile.id_profile%type)
return number IS
numar number(3) := 0;
BEGIN
select count(s.first_name) into numar
from student s, profile p,class c
where s.id_class = c.id_class and c.id_profile = p.id_profile
and p.id_profile=sectie;
return numar;
END bursieri;

/
--profilul 71

BEGIN
dbms_output.put_line('Exista ' || bursieri(9100) || ' studenti bursieri');
END;
</code>```

I tried to give an invalid profile id and expected an error, but instead I got an empty table

Body:
My SELECT count function returns the number of kids in a specific profile that has in id (secte = id_profile). When I input an invalid profile, the select statement returns an empty table insead of an error that I can solve. Any tips? (The tables are created by me);

CREATE OR REPLACE FUNCTION bursieri(sectie profile.id_profile%type)
return number IS
numar number(3) := 0;
BEGIN
select count(s.first_name) into numar
from student s, profile p,class c
where s.id_class = c.id_class and c.id_profile = p.id_profile
and p.id_profile=sectie;
return numar;
END bursieri;

/
--profilul 71

BEGIN
dbms_output.put_line('Exista ' || bursieri(9100) || ' studenti bursieri');
END;

I tried to give an invalid profile id and expected an error, but instead I got an empty table


问:
How can I adjuste the width of column in the Django Admin
I'm try edit the width of my column in the django admin and let editable, but i don't know how to...

When I add this column "nome_short_oficina" in list_editable, show me an error:

enter image description here

Could you help me?

For exemplo:

 def nome_short_oficina(self):
return u"%s" % self.oficina
nome_short_oficina.short_description = _(u"Oficina")
nome_short_oficina.allow_tags = True
I'm try edit the width of my column in the django admin and let editable, but i don't know how to...

When I add this column "nome_short_oficina" in list_editable, show me an error.


问:
Assign value to a variable using Kivy button
I'm developing a program that uses two calculation formulas, one for hours and one for minutes, so I have to pass the value 1 or 2 to the "formula" variable. I'm using the Kivy button to select one of the two options, the value is passed to the variable, but it always returns the initially declared value.

I've tried declaring the variable elsewhere, but to no avail.