问:
My Python code pass simple tests but not extended ones due to performance constrains
I'm teaching myself to code with Python and I've been completing kata's (mainly 7 kyu for now) on Codewars for a while. While trying to level up stumbled on following 6 kyu kata, that looked to be achievable with my knowledge:

Complete the function that takes a string as an input, and return a list of all the unpaired characters (i.e. they show up an odd number of times in the string), in the order they were encountered as an array.

In case of multiple appearances to choose from, take the last occurence of the unpaired character.

Notes:

A wide range of characters is used, and some of them may not render properly in your browser.
  Your solution should be linear in terms of string length to pass the last test.
  Examples:

"Hello World"   -->  ["H", "e", " ", "W", "r", "l", "d"]

"Codewars"      -->  ["C", "o", "d", "e", "w", "a", "r", "s"]

"woowee"        -->  []

"wwoooowweeee"  -->  []

"racecar"       -->  ["e"]

"Mamma"         -->  ["M"]

"Mama"          -->  ["M", "m"]

The following Python 3.6.0 code pass sample tests:

def function_name(s):
    result = []
    lengthS = len(s)
    dictResult = {}

    for item in s[-1:(-1 * lengthS - 1):-1]:
        numLetters = 0
        for number in range(lengthS):
            if item == s[number]:
                numLetters = numLetters + 1
        if numLetters % 2 != 0:
            dictResult[item] = numLetters

    for key in list(dictResult.keys())[-1:(-1 * (len(list(dictResult))) - 1):-1]:
        result.append(key)

    return result
```

Running a full round of tests fails due to :

Execution Timed Out (12000 ms)

Commenting some parts of code allows me to fail full round of tests quicker so I could see tests use very long strings.

It is clear that my code is not performance optimised. Read some articles on algorithms and I suspect my code lacks in performance due to for loop within another for loop, which is O(n²) complexity operation. And this is where I've stuck for a while. I'm not sure if this is the only piece of code that needs to be changed and if it is - just cannot get around understanding how this could be done.

Note. Please do not post answers with complete solution to this problem. I'd rather wish to figure the final code myself. So I would be glad if you could point to sections of my code that requires attention with suggestions, example code or further reading.

答:
Here I give a compact solution using a little bit of knowledge of python and his standard library:

This works for python>=3.7 because before it Counter wasn't defined as ordered

from collections import Counter
def function_name(s):
    count = Counter(s)
    answer = [c for c, num in count.items() if num % 2]
    return answer
```

<p>For other versions a little change taking characters in order from the string:</p>

<pre class="lang-py prettyprint-override"><code>from collections import Counter
def function_name(s):
    count = Counter(s)
    answer = [c for c in s if count[c] % 2]
    return answer
</code>```

Body:
I'm teaching myself to code with Python and I've been completing kata's (mainly 7 kyu for now) on Codewars for a while. While trying to level up stumbled on following 6 kyu kata, that looked to be achievable with my knowledge:

Complete the function that takes a string as an input, and return a list of all the unpaired characters (i.e. they show up an odd number of times in the string), in the order they were encountered as an array.

In case of multiple appearances to choose from, take the last occurence of the unpaired character.

Notes:

A wide range of characters is used, and some of them may not render properly in your browser.
  Your solution should be linear in terms of string length to pass the last test.
  Examples:

"Hello World"   -->  ["H", "e", " ", "W", "r", "l", "d"]

"Codewars"      -->  ["C", "o", "d", "e", "w", "a", "r", "s"]

"woowee"        -->  []

"wwoooowweeee"  -->  []

"racecar"       -->  ["e"]

"Mamma"         -->  ["M"]

"Mama"          -->  ["M", "m"]

The following Python 3.6.0 code pass sample tests:

def function_name(s):
    result = []
    lengthS = len(s)
    dictResult = {}

    for item in s[-1:(-1 * lengthS - 1):-1]:
        numLetters = 0
        for number in range(lengthS):
            if item == s[number]:
                numLetters = numLetters + 1
        if numLetters % 2 != 0:
            dictResult[item] = numLetters

    for key in list(dictResult.keys())[-1:(-1 * (len(list(dictResult))) - 1):-1]:
        result.append(key)

    return result

Running a full round of tests fails due to :

Execution Timed Out (12000 ms)

Commenting some parts of code allows me to fail full round of tests quicker so I could see tests use very long strings.

It is clear that my code is not performance optimised. Read some articles on algorithms and I suspect my code lacks in performance due to for loop within another for loop, which is O(n²) complexity operation. And this is where I've stuck for a while. I'm not sure if this is the only piece of code that needs to be changed and if it is - just cannot get around understanding how this could be done.

Note. Please do not post answers with complete solution to this problem. I'd rather wish to figure the final code myself. So I would be glad if you could point to sections of my code that requires attention with suggestions, example code or further reading.

Body:
Here I give a compact solution using a little bit of knowledge of python and his standard library:

This works for python>=3.7 because before it Counter wasn't defined as ordered

from collections import Counter
def function_name(s):
    count = Counter(s)
    answer = [c for c, num in count.items() if num % 2]
    return answer

For other versions a little change taking characters in order from the string:

from collections import Counter
def function_name(s):
    count = Counter(s)
    answer = [c for c in s if count[c] % 2]
    return answer


来源: stackexchange

问:
cant display html element using yajra data table
good day,
iam new in laravel i traying to use yajra data tabel  i have easy question  when i want to show my data tabel i get this error
"DataTables warning: table id=all_data - Ajax error. For more information about this error, please see http://datatables.net/tn/7"
 my controller  is

public function indexUsingYajra()
    {

```<code>    $dataView['allCategories']=Category::where('deleted',1)->get();
    return Datatables::of($dataView['allCategories'])
        ->setRowId('{{$id}}')

        //image coulmn
        ->addColumn('image', function(Category $category) {
            return '<img src="/upload/'.$category->image.'"  data-id="'.$category->id.'" data-toggle="modal" data-target="#update-img"  alt="" title="Edit Image" class="img-rounded img-responsive center-block img-edit imagenumber'.$category->id.'" />';
        })
        // totalproduct
        ->addColumn('Total Product', function(Category $category) {
            return  $category->getCategoryReportData->total_orders;
        })
        //status column
        ->addColumn('status', function(Category $category) {
            if ($category->status==1)
            {
                return '<span data-id="'.$category->id.'" title="update Status" data-target="on" class="status on ">on</span>';
            }else{
                return '<span data-id="'.$category->id.'" title="update Status"  data-target="off" class="status off">off</span>';
            }

        })
        // active column
        ->addColumn('action', function(Category $category) {
            return'<ul class="actions">
                    <li><a href="'. route('category.edit', $category->id) .'">'.$category->name.'</a></li>
                </ul>';
        })

        //render html element in page
        ->rawColumns(['image', 'status','action'])
        ->make(true);
}
</code>```

my js code
    $('#all_data').DataTable({

```<code>            "responsive": true,
            "processing": true,
            "serverSide": true,
            "ajax": "{!!route('category.indexUsingYajra')!!}",
            "columns": [
                {data: 'id',       name: 'id'},
                {data: 'name',       name: 'name'},
                {data: 'image',       name: 'image'},
                {data: 'Total Product',       name: 'Total Product'},
                {data: 'status',       name: 'status'},
                {data: 'action',       name: 'action'},

            ]
        });
</code>```

my html code

```<code> <table id="all_data" class="table-striped table-bordered dt-responsive nowrap tableData  table_for_data" cellspacing="0" width="100%">
                                <thead>
                                    <tr>
                                        <th>Id</th>
                                        <th>Name</th>
                                        <th>Image</th>
                                        <th>Total Product</th>
                                        <th>status</th>
                                        <th>action</th>
                                    </tr>
                                </thead>

                            </table>
</code>```

my this problem happen if i want to view links in column (action)  if i remove it data table work correctly and if i remove  any column that contain any html element like (image) or (status)  action column work correctly .
how can i solve it
thnaks

答:
public function opdAllPatient(OpdModel $request){</p>

```<code>        return DataTables::of(OpdModel::select('orderId','patientName','regNum','consultant','gender','regDate','address')
                            ->where('dltStatus','<>','N'))
        ->addColumn('action', function($data){
        return sprintf(' <div class="btn-group btn-sm">
                <button data-toggle="tooltip modal" data-placement="auto" title="%s" data-order_id="%s" class="btn-sm %s btn btn-info btn-group  ">%s</button>
         <a href="%s"data-toggle="tooltip" data-placement="auto" title="update" class="btn-sm btn-success">%s</a>
        <button data-toggle="tooltip modal" data-placement="auto" title="%s" data-order_id="%s" class="btn-sm %s btn  ">%s</button>
         <button data-toggle="tooltip modal" data-placement="auto" title="%s" data-order_id="%s" class="btn-sm %s btn btn-danger" >%s</button></div>',
         "view",$data['orderId'],'opdview','<i class="fa fa-eye"></i>',
         route('opd.edit',['id'=>$data['orderId']]),'<i class="fa fa-pencil"></i>',
         "add",$data['orderId'],'addpatient','<i class="fa fa-plus"></i>',
         "delete", $data['orderId'],'opd-delete','<i class="fa fa-trash"></i>');

            })->addColumn('id',function($data){
                    static $i=1;
                    return $i++;

            })->editColumn('consultant',function($data){
                return $data->getConsultant->name;
            })->filterColumn('consultant', function($q, $keyword) {
                $q->whereHas('getConsultant',function($q) use ($keyword) {
                    $q->where('name','LIKE',["%{$keyword}%"]);
                });
            })->editColumn('regDate', function ($data){
                return \Carbon\Carbon::parse($data->regDate)->format('d/m/Y') ;})

        ->make(true);

 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
good day,
iam new in laravel i traying to use yajra data tabel  i have easy question  when i want to show my data tabel i get this error
"DataTables warning: table id=all_data - Ajax error. For more information about this error, please see http://datatables.net/tn/7"
 my controller  is

public function indexUsingYajra()
    {

    $dataView['allCategories']=Category::where('deleted',1)->get();
    return Datatables::of($dataView['allCategories'])
        ->setRowId('{{$id}}')

        //image coulmn
        ->addColumn('image', function(Category $category) {
            return 'image.'"  data-id="'.$category->id.'" data-toggle="modal" data-target="#update-img"  alt="" title="Edit Image" class="img-rounded img-responsive center-block img-edit imagenumber'.$category->id.'" />';
        })
        // totalproduct
        ->addColumn('Total Product', function(Category $category) {
            return  $category->getCategoryReportData->total_orders;
        })
        //status column
        ->addColumn('status', function(Category $category) {
            if ($category->status==1)
            {
                return 'id.'" title="update Status" data-target="on" class="status on ">on';
            }else{
                return 'id.'" title="update Status"  data-target="off" class="status off">off';
            }

        })
        // active column
        ->addColumn('action', function(Category $category) {
            return'

id) .'">'.$category->name.'

';
        })

        //render html element in page
        ->rawColumns(['image', 'status','action'])
        ->make(true);
}

my js code
    $('#all_data').DataTable({

            "responsive": true,
            "processing": true,
            "serverSide": true,
            "ajax": "{!!route('category.indexUsingYajra')!!}",
            "columns": [
                {data: 'id',       name: 'id'},
                {data: 'name',       name: 'name'},
                {data: 'image',       name: 'image'},
                {data: 'Total Product',       name: 'Total Product'},
                {data: 'status',       name: 'status'},
                {data: 'action',       name: 'action'},

            ]
        });

my html code

                                        Id
                                        Name
                                        Image
                                        Total Product
                                        status
                                        action

my this problem happen if i want to view links in column (action)  if i remove it data table work correctly and if i remove  any column that contain any html element like (image) or (status)  action column work correctly .
how can i solve it
thnaks

Body:
public function opdAllPatient(OpdModel $request){

        return DataTables::of(OpdModel::select('orderId','patientName','regNum','consultant','gender','regDate','address')
                            ->where('dltStatus','<>','N'))
        ->addColumn('action', function($data){
        return sprintf(' <div class="btn-group btn-sm">
                <button data-toggle="tooltip modal" data-placement="auto" title="%s" data-order_id="%s" class="btn-sm %s btn btn-info btn-group  ">%s</button>
         <a href="%s"data-toggle="tooltip" data-placement="auto" title="update" class="btn-sm btn-success">%s</a>
        <button data-toggle="tooltip modal" data-placement="auto" title="%s" data-order_id="%s" class="btn-sm %s btn  ">%s</button>
         <button data-toggle="tooltip modal" data-placement="auto" title="%s" data-order_id="%s" class="btn-sm %s btn btn-danger" >%s</button></div>',
         "view",$data['orderId'],'opdview','<i class="fa fa-eye"></i>',
         route('opd.edit',['id'=>$data['orderId']]),'<i class="fa fa-pencil"></i>',
         "add",$data['orderId'],'addpatient','<i class="fa fa-plus"></i>',
         "delete", $data['orderId'],'opd-delete','<i class="fa fa-trash"></i>');

            })->addColumn('id',function($data){
                    static $i=1;
                    return $i++;

            })->editColumn('consultant',function($data){
                return $data->getConsultant->name;
            })->filterColumn('consultant', function($q, $keyword) {
                $q->whereHas('getConsultant',function($q) use ($keyword) {
                    $q->where('name','LIKE',["%{$keyword}%"]);
                });
            })->editColumn('regDate', function ($data){
                return \Carbon\Carbon::parse($data->regDate)->format('d/m/Y') ;})

        ->make(true);

 }


问:
Is there a way to temporarily remove PyInstaller's nonconsole option?
I build my code using the nonconsole option when distributing my tools to users:

```<code>pyinstaller test.py --noconsole
</code>```

Because without a console the look is simpler and more beautiful.

However, when an error occurs in the user's environment, there is no way to know the content of the error if it is a nonconsole.

I want to switch between console and non-console after building code.

I want to hide the console normally, so that the console can be displayed only when switching to error checking mode.

Isn't that possible?

答:
I am not sure this is possible - hiding/showing the console is a compile/build option, rather than a run time one.

Have you considered using the logging module?
This will give you an easy way to log messages to a file, which you can inspect if something goes wrong.

Body:
I build my code using the nonconsole option when distributing my tools to users:

pyinstaller test.py --noconsole

Because without a console the look is simpler and more beautiful.

However, when an error occurs in the user's environment, there is no way to know the content of the error if it is a nonconsole.

I want to switch between console and non-console after building code.

I want to hide the console normally, so that the console can be displayed only when switching to error checking mode.

Isn't that possible?


问:
Android: Dagger 2 interferes with Immutables?
Getting a really strange issue; hopefully you guys can help.

I have been using Immutables library in my android project since a long time and had no issues. The auto-generated files for Immutable objects are located in (as example) build/generated/source/apt/debug/com/package/name/ImmutableClass.java and the project compiles and works fine.

I recently decided to use Dependency Injection in the same project and started using Dagger 2. I have used Guice in another Java project (non-Android), but never used Dagger before. All of a sudden, I am starting to get weird errors saying that the Immutables class could not be found.

Error: error: cannot find symbol class ImmutableClass.

I tried removing the @Component and @Module that I created and the errors went away. The funny thing is that the file ImmutableClass.java is still there in the same location as earlier.

Please let me know your thoughts. Thanks.

答:
Please consider <annotationÅrocessorPath> usage. By edit the pom.xml file that refers to my current module, the following approach worked for me:

```<code>            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.immutables</groupId>
                        <artifactId>value</artifactId>
                        <version>${dependency.version.immutables}</version>
                    </path>
                    <path>
                        <groupId>com.google.dagger</groupId>
                        <artifactId>dagger-compiler</artifactId>
                        <version>2.16</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
</code>```

Important to mention: the sorting order of the paths DOES NOT matter. I'm using maven version 3.6.0.

Body:
Please consider <annotationÅrocessorPath> usage. By edit the pom.xml file that refers to my current module, the following approach worked for me:

            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.immutables</groupId>
                        <artifactId>value</artifactId>
                        <version>${dependency.version.immutables}</version>
                    </path>
                    <path>
                        <groupId>com.google.dagger</groupId>
                        <artifactId>dagger-compiler</artifactId>
                        <version>2.16</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>

Important to mention: the sorting order of the paths DOES NOT matter. I'm using maven version 3.6.0.


问:
Conditional where clause in Oracle
I have database table as below

```<code>+----------+----------+------------+
| emp_code | emp_name | emp_status |
+----------+----------+------------+
|   01     |   aaa    |     A      |
|   02     |   bbb    |     A      |
|   03     |   ccc    |     A      |
|   04     |   ddd    |     I      |
|   05     |   eee    |     I      |
|   06     |   fff    |     R      |
+----------+----------+------------+
</code>```

I want to pick values based on the emp_status which will be passed dynamically

```<code> 1. If emp_status='A' it should fetch emp_codes with emp_status='A'
 2. If emp_status='I' it should fetch all emp_codes except emp_status='I'
 3. If emp_status is null then fetch all emp_codes.
</code>```

How to write single sql query with all the conditions?

答:
You can use conditional WHERE clause using OR and AND operator as follows:

```<code>SELECT EMP_CODE FROM YOUR_TABLE
WHERE ('&INPUT_STATUS' = 'A' AND emp_status='A')
   OR ('&INPUT_STATUS' = 'I' AND emp_status<>'I')
   OR ('&INPUT_STATUS' IS NULL)
</code>```

Cheers!!

Title: Conditional where clause in Oracle

Body:
I have database table as below

+----------+----------+------------+
| emp_code | emp_name | emp_status |
+----------+----------+------------+
|   01     |   aaa    |     A      |
|   02     |   bbb    |     A      |
|   03     |   ccc    |     A      |
|   04     |   ddd    |     I      |
|   05     |   eee    |     I      |
|   06     |   fff    |     R      |
+----------+----------+------------+

I want to pick values based on the emp_status which will be passed dynamically

 1. If emp_status='A' it should fetch emp_codes with emp_status='A'
 2. If emp_status='I' it should fetch all emp_codes except emp_status='I'
 3. If emp_status is null then fetch all emp_codes.

How to write single sql query with all the conditions?

Body:
You can use conditional WHERE clause using OR and AND operator as follows:

SELECT EMP_CODE FROM YOUR_TABLE
WHERE ('&INPUT_STATUS' = 'A' AND emp_status='A')
   OR ('&INPUT_STATUS' = 'I' AND emp_status<>'I')
   OR ('&INPUT_STATUS' IS NULL)

Cheers!!


问:
Use of ReflectionTestUtils.setField() in Junit testing
I am new in JUnittesting so i have a question. Can anyone please tell me why we use ReflectionTestUtils.setField() in our Junit testing with example.

答:
One more Use Case:

We externalised many properties Such as: URL's , endpoint and many other properties in application properties like below:

```<code>kf.get.profile.endpoint=/profile
kf.get.clients.endpoint=clients
</code>```

and then use it in application like below:

```<code>  @Value("${kf.get.clients.endpoint}")
  private String getClientEndpoint
</code>```

and whenever when we write unit test , we get NullPointerException because Spring cannot inject @value similarly as @Autowired does. ( at least at the moment , I dont know alternative. ) so to avoid that we can use ReflectionTestUtils to inject externalised properties. like below:

```<code>ReflectionTestUtils.setField(targetObject,"getClientEndpoint","lorem");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
One more Use Case:

We externalised many properties Such as: URL's , endpoint and many other properties in application properties like below:

kf.get.profile.endpoint=/profile
kf.get.clients.endpoint=clients

and then use it in application like below:

  @Value("${kf.get.clients.endpoint}")
  private String getClientEndpoint

and whenever when we write unit test , we get NullPointerException because Spring cannot inject @value similarly as @Autowired does. ( at least at the moment , I dont know alternative. ) so to avoid that we can use ReflectionTestUtils to inject externalised properties. like below:

ReflectionTestUtils.setField(targetObject,"getClientEndpoint","lorem");


问:
how to set display member to a concatenated expression? datasource is linq query
i'm trying to set the display member of my listbox to a concatenated value from a linq query:

```<code>var query =
     from a in db.Customers
     select a;

listBox1.DataSouce = query;
</code>```

I was hoping to be able to set the display member by doing something like this:

```<code>listBox1.DisplayMember = "FirstName" + "LastName";
</code>```

but obviously that doesn't work.

how do i do this? I guess the tricky part is the fact that the datasource is a linq query result object. But its indexable so there's gotta be some way.

答:
Figured it out by accident:

```<code>var query =
                from a in db.LUT_Employees
                where a.position == "Supervisor" && a.department == "Production"
                select new { a, Names = a.lastName + ", " + a.firstName };

            cboProductionSupervisor.DataSource = query;
            cboProductionSupervisor.DisplayMember = "Names";
</code>```

basically what I did was create a new field on the fly just like you would in sql. then use that as the display member

Body:
i'm trying to set the display member of my listbox to a concatenated value from a linq query:

var query =
     from a in db.Customers
     select a;

listBox1.DataSouce = query;

I was hoping to be able to set the display member by doing something like this:

listBox1.DisplayMember = "FirstName" + "LastName";

but obviously that doesn't work.

how do i do this? I guess the tricky part is the fact that the datasource is a linq query result object. But its indexable so there's gotta be some way.

Body:
Figured it out by accident:

var query =
                from a in db.LUT_Employees
                where a.position == "Supervisor" && a.department == "Production"
                select new { a, Names = a.lastName + ", " + a.firstName };

            cboProductionSupervisor.DataSource = query;
            cboProductionSupervisor.DisplayMember = "Names";

basically what I did was create a new field on the fly just like you would in sql. then use that as the display member


问:
Maven - jenkins pipeline not using pom
I have a problem running a maven deploy through Jenkins. When run locally, the correct URL is contacted, but via Jenkins(in the middle of a pipeline), it does not. It also states that it is using a different plugin to do so. How do I get Jenkins to contact MY_URL like my command line does?

(I've cleaned up the output a bit)

Running the following through the command line gives me:

mvn clean deploy -DaltDeploymentRepository=nexus::default::https://MY_URL/ -DskipTests  -P nexus -X -s ./settings.xml

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.8.2:deploy (default-deploy) on project MY_PROJECT: Failed to deploy artifacts: Could not transfer artifact from/to nexus (https://MY_URL): Failed to transfer file 20200217.092316-15.jar with status code 401 -> [Help 1]

This is what I want (I'm waiting on credentials - but it is hitting the correct URL)

Running via Jenkins gives me:
[ERROR] Failed to execute goal org.sonatype.plugins:nexus-staging-maven-plugin:1.5.1:deploy (default-deploy) on project : Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter -> [Help 1]

I have done a "diff" on the pom files in use by jenkins and locally and they are identical; likewise with the settings.xml I suspect this is a plugin problem but do not know where to go with it.

Items I have tried:

mvn clean beforehand

reinstalling mvn

echoing the settings.xml and pom.xml into the jenkins output

Specifying altDeploymentRepository in    the settings.xml and/or
commandline

Specifying    altDeploymentRepository using the -Dproperties= flag

Combinations of    altDeploymentRepository, altDeploymentDirectory,

altSnapshotDeploymentRepository

Endless research

Hopeful reruns

Banging head on desk

答:
Your Jenkins runs the org.sonatype.plugins:nexus-staging-maven-plugin:1.5.1:deploy goal.

It is either specified in the POM or given on command line. So first of all, check whether the nexus-staging-maven-plugin is configured in your POM or in one of the parent POMs. If so, check if it run conditionally or is part of a profile.

Secondly, look at the command line call in Jenkins and see if it is exactly the same as the one you ran locally.

The third possibility is that you run a Jenkins plugin from Sonatype that implicitly tries to deploy artifacts. So watch out for Sonatype specific Jenkins plugins.

One of the three strategies should lead to the source of the problem.

Title: Maven - jenkins pipeline not using pom


问:
react native modal: Button on press calls a prop function and resets the state?
in parent screen:

```<code><CoolName add={function} />
</code>```

in CoolName modal:

```<code>state={ a: 'some string a', b: 'some string b'}

<Button title="Add" onPress={this.props.add.bind(this, this.state)}/>
</code>```

how can I do this and reset the state (this.setState({a: '', b: ''})) at the same time inside the onPress prop??

答:
found it, I just needed to delete the first (this) in the bind when using a callback function because its not the same scope :)

```<code><Button title="Add" onPress={() => {
                                this.props.add.bind(this.state);
                                this.setState({a: '', b: ''});
                               }
                        }
</code>```

/>

Body:
in parent screen:

<CoolName add={function} />

in CoolName modal:

state={ a: 'some string a', b: 'some string b'}

<Button title="Add" onPress={this.props.add.bind(this, this.state)}/>

how can I do this and reset the state (this.setState({a: '', b: ''})) at the same time inside the onPress prop??

Body:
found it, I just needed to delete the first (this) in the bind when using a callback function because its not the same scope :)

<Button title="Add" onPress={() => {
                                this.props.add.bind(this.state);
                                this.setState({a: '', b: ''});
                               }
                        }

/>


问:
How do I output a variable in a rspec test?
Is there a quick way to output the value of variable in a rspec test? Something like this for example, in a controller to output a variable, I do:

```<code>raise variable.to_yaml
</code>```

Is there something similar I can do in a rspec test to see the contents of a variable?

答:
If you want the output to go into the log file (i.e. logs/test.log), you can use the rails logger.

```<code>Rails.logger.debug variable.inspect
Rails.logger.debug variable.to_yaml
</code>```

If you want to see the output in the console, you can use the pretty printer 'pp'.

```<code>require 'pp'

it 'does something'
  thing = Factory(:something)
  pp thing
end
</code>```

Or you can use good 'ol puts

```<code>puts thing.to_yaml
</code>```

Body:
Is there a quick way to output the value of variable in a rspec test? Something like this for example, in a controller to output a variable, I do:

raise variable.to_yaml

Is there something similar I can do in a rspec test to see the contents of a variable?

Body:
If you want the output to go into the log file (i.e. logs/test.log), you can use the rails logger.

Rails.logger.debug variable.inspect
Rails.logger.debug variable.to_yaml

If you want to see the output in the console, you can use the pretty printer 'pp'.

require 'pp'

it 'does something'
  thing = Factory(:something)
  pp thing
end

Or you can use good 'ol puts

puts thing.to_yaml


问:
How can I check out a GitHub pull request with git?
I'd like to check out a previously created pull request (created via GitHub web interface). I searched and found different places where a refs/pull or refs/pull/pr

But when I add fetch = +refs/pull/*/head:refs/remotes/origin/pr/* to the git config file and do a git fetch

What I'm doing wrong? Should GitHub create automatically the pull/xyz stuff, or do I have to configure something?

答:
Suppose your origin and upstream info is like below

```<code>   $ git remote -v
   origin  git@github.com:<yourname>/<repo_name>.git (fetch)
   origin  git@github.com:<yourname>/<repo_name>.git (push)
   upstream   git@github.com:<repo_owner>/<repo_name>.git (fetch)
   upstream   git@github.com:<repo_owner>/<repo_name>.git (push)
</code>```

and your branch name is like

```<code>   <repo_owner>:<BranchName>
</code>```

then

```<code>   git pull origin <BranchName>
</code>```

shall do the job

Body:
Suppose your origin and upstream info is like below

   $ git remote -v
   origin  git@github.com:<yourname>/<repo_name>.git (fetch)
   origin  git@github.com:<yourname>/<repo_name>.git (push)
   upstream   git@github.com:<repo_owner>/<repo_name>.git (fetch)
   upstream   git@github.com:<repo_owner>/<repo_name>.git (push)

and your branch name is like

   <repo_owner>:<BranchName>

then

   git pull origin <BranchName>

shall do the job


问:
How to correctly setup azure queue trigger after update to Microsoft.Net.Functions 3.0.3?
This is my original format of a azure storage queue trigger function, it use to work, however after I updated the Microsoft.Net.Functions NuGet package from 1.0.24 to 3.0.3, changed zip deployment to web deployment, and did a publish, this setup have stopped working.

```<code>[FunctionName("FunctionEmailQueueTrigger")]
public static async Task Run([QueueTrigger("%emailqueue%")]string myQueueItem, ILogger log)
{
        //....Actions
}```
```

<p>So, I thought it is the setup format changed from 1.0.24 to 3.0.3 so I changed to this format:
This is my update storage Queue trigger setup which is also not fire</p>

```public static async Task Run([QueueTrigger("emailqueue", Connection = "DefaultEndpointsProtocol=https;AccountName=name;AccountKey=XXXXXXX;EndpointSuffix=core.windows.net")]string myQueueItem, ILogger log)
{
        //....Actions
}```
</code>```

When I check the function and click at it on azure, it throws me an error:

Error: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

it deployed on azure with a standard plan so I assume there should not have cold start, I have chacked the queue name, its match.

Thank you for the help.

答:
For now the problem I could get from your code is your Connection, this should be your storage account connection name not the connection string, if in your local it should be the connection in local.settings.json, if on the azure go to Configuration check your storage account setting key.

And in my test v3 function still could use the bind expression with %%, however if you use 3.0.3 function package, not set the version in the .csproj file like this doc shows:Visual Studio runtime versions, it will run without logs.

After following the doc setting your function, you still get the problem, you could try to catch the exception to get the detail information with this answer:How to retrieve the LoaderException property?  and share your full code to let me have a test.

Hope this could help you, if you still have other problem please feel free to let me know.

Body:
This is my original format of a azure storage queue trigger function, it use to work, however after I updated the Microsoft.Net.Functions NuGet package from 1.0.24 to 3.0.3, changed zip deployment to web deployment, and did a publish, this setup have stopped working.

[FunctionName("FunctionEmailQueueTrigger")]
public static async Task Run([QueueTrigger("%emailqueue%")]string myQueueItem, ILogger log)
{
        //....Actions
}```
</code></pre>

<p>So, I thought it is the setup format changed from 1.0.24 to 3.0.3 so I changed to this format:
This is my update storage Queue trigger setup which is also not fire</p>

<pre><code>public static async Task Run([QueueTrigger("emailqueue", Connection = "DefaultEndpointsProtocol=https;AccountName=name;AccountKey=XXXXXXX;EndpointSuffix=core.windows.net")]string myQueueItem, ILogger log)
{
        //....Actions
}```

When I check the function and click at it on azure, it throws me an error:

Error: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

it deployed on azure with a standard plan so I assume there should not have cold start, I have chacked the queue name, its match.

Thank you for the help.


问:
Changing the target version of TypeScript Code causes the TypeScript Compiler to no find the module anymore
I have signalr installed via npm in Visual Studio 2019.
When i have target on ES6 in my compiler options I get the error TS2307 (TS) Cannot find mogule '@microsoft/signalr. When I change the target toES5 I dont get an error, but in the browser I get then the exception Uncaught ReferenceError: exports is not defined

This is my tsconfig:

```<code>{
  "compilerOptions": {
    "target": "ES6",
    "sourceMap": true,
  },

  "compileOnSave": true,
}
</code>```

答:
The module option has a different default based on target and the moduleResolution option has a different default value based on the module option. From docs:

--module target === "ES3" or "ES5" ? "CommonJS" : "ES6"

--moduleResolution  module === "AMD" or "System" or "ES6" ? "Classic" : "Node"

This is what lead to the change in behavior. You should probably specify these options explicitly. What will probably work for your case:

```<code>{
  "compilerOptions": {
    "target": "ES6",
    "sourceMap": true,
    "module": "CommonJS",
    "moduleResolution": "node"
  },

  "compileOnSave": true,
}

</code>```

Body:
I have signalr installed via npm in Visual Studio 2019.
When i have target on ES6 in my compiler options I get the error TS2307 (TS) Cannot find mogule '@microsoft/signalr. When I change the target toES5 I dont get an error, but in the browser I get then the exception Uncaught ReferenceError: exports is not defined

This is my tsconfig:

{
  "compilerOptions": {
    "target": "ES6",
    "sourceMap": true,
  },

  "compileOnSave": true,
}

Body:
The module option has a different default based on target and the moduleResolution option has a different default value based on the module option. From docs:

--module target === "ES3" or "ES5" ? "CommonJS" : "ES6"

--moduleResolution  module === "AMD" or "System" or "ES6" ? "Classic" : "Node"

This is what lead to the change in behavior. You should probably specify these options explicitly. What will probably work for your case:

{
  "compilerOptions": {
    "target": "ES6",
    "sourceMap": true,
    "module": "CommonJS",
    "moduleResolution": "node"
  },

  "compileOnSave": true,
}


问:
How to instantiate a materializer for AkkaStreams when I have a reference to the typed actor system?
The code below does not compile, it says that ActorMaterializer is missing an implicit ActorRefFactory. How should I provide one?</p>

```<code>val guardian: Behavior[Done] = Behaviors.setup(_ => {
  Behaviors.receiveMessage{
    case Done => Behaviors.stopped
  }
})
implicit val sys = ActorSystem(guardian, "sys")
implicit val materializer: Materializer = ActorMaterializer()
</code>```

答:
Previous answers are halfways to the indended new API.

The typed ActorSystem can be implicitly transformed to provide the system materialiser as well, so just having it available as an implicit should be enough.

For example:

```<code>Behaviors.setup { ctx =>
 implicit val system = ctx.system

 Source(1 to 10).runForeach(println)

 ...
}
</code>```

The inner working of this is an implicit conversion available from the Materializer companion object that extracts the system materializer of a ClassicActorSystemProvider into a Materializer. Both the typed and the classic ActorSystem implements ClassicActorSystemProvider.

Body:
The code below does not compile, it says that ActorMaterializer is missing an implicit ActorRefFactory. How should I provide one?

val guardian: Behavior[Done] = Behaviors.setup(_ => {
  Behaviors.receiveMessage{
    case Done => Behaviors.stopped
  }
})
implicit val sys = ActorSystem(guardian, "sys")
implicit val materializer: Materializer = ActorMaterializer()

Body:
Previous answers are halfways to the indended new API.

The typed ActorSystem can be implicitly transformed to provide the system materialiser as well, so just having it available as an implicit should be enough.

For example:

Behaviors.setup { ctx =>
 implicit val system = ctx.system

 Source(1 to 10).runForeach(println)

 ...
}

The inner working of this is an implicit conversion available from the Materializer companion object that extracts the system materializer of a ClassicActorSystemProvider into a Materializer. Both the typed and the classic ActorSystem implements ClassicActorSystemProvider.


问:
What is the more correct position for the error argument in a javascript callback?
I am writing a javascript function that takes a callback. The callback will be passed an error argument if something goes wrong.

What are the best / most standard calling conventions?

Should the callback's error argument be first or last?

Should I pass an 'errorMsg' string, or a new Error('errorMsg') object?

Ie, what is more correct - this code:

```<code>foo = function(bar, callback) {
  ...
  if (error) {
    callback('troz not found');
  } else {
    callback(null, result);
  }
}
</code>```

or this code:

```<code>foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, 'troz not found');
  } else {
    callback(result);
  }
}
</code>```

or this:

```<code>foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, new Error('troz not found'));
  } else {
    callback(result);
  }
}
</code>```

If its relevant, my code will be used as both as a NodeJS module and as a browser-based javascript library.

答:
You could specify two callbacks, one for success and one for error, and both encapsulated in a single "callbacks" argument. This is how many Javascript libraries handle your requirement.

```<code>var fooFn = function(bar, callbacks) {
  callbacks = callbacks || {}; //make callbacks argument optional
  ...
  if (error) {
    if (callbacks.error) {
      callbacks.error('troz not found'); //pass the error message as a string
    }
  } else if (callbacks.success) {
    callbacks.success(result);
  }
}
</code>```

The success and error functions are optional. To specify both, call it like this:

```<code>fooFn("some bar", {
  success: function(result) {
    //success :-)
  },
  error: function(errorMsg) {
    //error :-(
  }
});
</code>```

You can also do this:

```<code>fooFn("some other bar");
</code>```

If you like, you can expand the callbacks object to support other scenarios, like "complete".

Body:
I am writing a javascript function that takes a callback. The callback will be passed an error argument if something goes wrong.

What are the best / most standard calling conventions?

Should the callback's error argument be first or last?

Should I pass an 'errorMsg' string, or a new Error('errorMsg') object?

Ie, what is more correct - this code:

foo = function(bar, callback) {
  ...
  if (error) {
    callback('troz not found');
  } else {
    callback(null, result);
  }
}

or this code:

foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, 'troz not found');
  } else {
    callback(result);
  }
}

or this:

foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, new Error('troz not found'));
  } else {
    callback(result);
  }
}

If its relevant, my code will be used as both as a NodeJS module and as a browser-based javascript library.

Body:
You could specify two callbacks, one for success and one for error, and both encapsulated in a single "callbacks" argument. This is how many Javascript libraries handle your requirement.

var fooFn = function(bar, callbacks) {
  callbacks = callbacks || {}; //make callbacks argument optional
  ...
  if (error) {
    if (callbacks.error) {
      callbacks.error('troz not found'); //pass the error message as a string
    }
  } else if (callbacks.success) {
    callbacks.success(result);
  }
}

The success and error functions are optional. To specify both, call it like this:

fooFn("some bar", {
  success: function(result) {
    //success :-)
  },
  error: function(errorMsg) {
    //error :-(
  }
});

You can also do this:

fooFn("some other bar");

If you like, you can expand the callbacks object to support other scenarios, like "complete".


问:
Load Server URL dicom files inside Imebra in iOS?
I am using https://imebra.com/  in my application, when I load a local files it reading the DICOM file and I am able to see the Image. when, I am  sending Cloud url path to imebra It is showing an error and below I shared sample code.I want to send a single or multiple url to Imebra. I don't know how to proceed.

```<code> let filePath = Bundle.main.path(forResource: fileName, ofType: "dcm") // i want to send url(https://raw.githubusercontent.com/ivmartel/dwv/master/tests/data/bbmri-53323851.dcm) here
 let dataSet = try ImebraCodecFactory.load(fromFile: filepath)

  _ = try dataSet.getString(ImebraTagId(group: 0x10, tag: 0x10), elementNumber: 0, defaultValue: "")

  _ = try dataSet.getString(ImebraTagId(group: 0x10, tag: 0x10), elementNumber: 1, defaultValue: "")
</code>```

thanks in advance.

答:
Imebra can load local DICOM files or from remote PACS (using the DIMSE protocol).

Imebra cannot load an image directly from an URL because it uses a posix call to open the local file.

To open a file from an URL you should first load the remote file. See this answer Simple Swift file download with URL to see how to load a file to a local temporary file.

Alternatively, you could load the file to a NSData object and pass its content to an Imebra Memory object, then pass to ImebraCodecFactory a StreamReader using a MemoryStreamInput.

Disclaimer: I'm the author of Imebra

Body:
I am using https://imebra.com/  in my application, when I load a local files it reading the DICOM file and I am able to see the Image. when, I am  sending Cloud url path to imebra It is showing an error and below I shared sample code.I want to send a single or multiple url to Imebra. I don't know how to proceed.

 let filePath = Bundle.main.path(forResource: fileName, ofType: "dcm") // i want to send url(https://raw.githubusercontent.com/ivmartel/dwv/master/tests/data/bbmri-53323851.dcm) here
 let dataSet = try ImebraCodecFactory.load(fromFile: filepath)

  _ = try dataSet.getString(ImebraTagId(group: 0x10, tag: 0x10), elementNumber: 0, defaultValue: "")

  _ = try dataSet.getString(ImebraTagId(group: 0x10, tag: 0x10), elementNumber: 1, defaultValue: "")

thanks in advance.


答:
You can use a case..when expression like this :

```<code>SELECT *
  FROM tab
 WHERE CASE
       WHEN :emp_status='A' THEN 'A'
       WHEN :emp_status='I' THEN emp_status
       WHEN :emp_status is null THEN emp_status
        END = emp_status
   AND ( emp_status != 'I' OR :emp_status is null )
</code>```

where :emp_status is bind variable to be passed into the query.

Alternatively, you can also use DECODE() function

```<code>SELECT *
  FROM tab
 WHERE DECODE( :emp_status, 'A', 'A', 'I', emp_status, null , emp_status ) = emp_status
   AND ( emp_status != 'I' OR :emp_status is null )
</code>```

Title: Conditional where clause in Oracle

Body:
I have database table as below

+----------+----------+------------+
| emp_code | emp_name | emp_status |
+----------+----------+------------+
|   01     |   aaa    |     A      |
|   02     |   bbb    |     A      |
|   03     |   ccc    |     A      |
|   04     |   ddd    |     I      |
|   05     |   eee    |     I      |
|   06     |   fff    |     R      |
+----------+----------+------------+

I want to pick values based on the emp_status which will be passed dynamically

 1. If emp_status='A' it should fetch emp_codes with emp_status='A'
 2. If emp_status='I' it should fetch all emp_codes except emp_status='I'
 3. If emp_status is null then fetch all emp_codes.

How to write single sql query with all the conditions?

Body:
You can use a case..when expression like this :

SELECT *
  FROM tab
 WHERE CASE
       WHEN :emp_status='A' THEN 'A'
       WHEN :emp_status='I' THEN emp_status
       WHEN :emp_status is null THEN emp_status
        END = emp_status
   AND ( emp_status != 'I' OR :emp_status is null )

where :emp_status is bind variable to be passed into the query.

Alternatively, you can also use DECODE() function

SELECT *
  FROM tab
 WHERE DECODE( :emp_status, 'A', 'A', 'I', emp_status, null , emp_status ) = emp_status
   AND ( emp_status != 'I' OR :emp_status is null )


问:
How to get all buttons at once?
```<code>Button button = findViewById(R.id.button1);
</code>```

That's the only way I know to get the button, but I have 45 buttons and it's too hard for me to get the buttons one by one.

Is there is any way to get all the buttons at once?

答:
You can try something like

```<code>val root = findViewById<ViewGroup>(android.R.id.content)

val buttons =  (0 until root.childCount)
                    .mapNotNull { root.getChildAt(it) as? Button }
                    .toList()
</code>```

in onCreate of your activity

Title: How to get all buttons at once?

Body:
Button button = findViewById(R.id.button1);

That's the only way I know to get the button, but I have 45 buttons and it's too hard for me to get the buttons one by one.

Is there is any way to get all the buttons at once?

Body:
You can try something like

val root = findViewById<ViewGroup>(android.R.id.content)

val buttons =  (0 until root.childCount)
                    .mapNotNull { root.getChildAt(it) as? Button }
                    .toList()

in onCreate of your activity


问:
AuthorizeRouteView Not working for logged out users
We are starting to migrate a project to blazor, and are having some issues with restricting content to only logged in users.

For this test, we have used a standard Visual Studio 2019 Blazor Server-Side project template, with local users and accounts authentication enabled.

We have then changed the App.razor file to the following:

```<code><Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
    <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
        <NotAuthorized>
            NOT AUTHORIZED!!!!!
        </NotAuthorized>
        <Authorizing>
            AUTHORIZING!!!!!
        </Authorizing>
        </AuthorizeRouteView>
</Found>
<NotFound>
    <CascadingAuthenticationState>
        <LayoutView Layout="@typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </CascadingAuthenticationState>
</NotFound>
</code>```

The code in <NotAuthorized> never gets hit, I have confirmed no cookies on the browser, and even tried in a private browser window as well.

I have in a different component injected the HTTPContext to see what is going on with the current user. Current user is not null, it has an identity, but is showing an unauthenticated, and has no claims as expected.

Is there something i am missing here?

答:
I have the same problem with the current Blazor version in a WebAssembly (client) project.

It would be nice if the Blazor team could tell us what we do wrong, because you use exactly the code they suggest to use.

I found a workaround by using an <AuthorizeView> in my MainLayout. There the <NotAuthorized> part is executed correctly and you can use the code they suggested to force a redirect to log on:

<AuthorizeView>
    <Authorized>

    </Authorized>
    <NotAuthorized>
        <RedirectToLogin />
    </NotAuthorized>
</AuthorizeView>
```

Body:
We are starting to migrate a project to blazor, and are having some issues with restricting content to only logged in users.

For this test, we have used a standard Visual Studio 2019 Blazor Server-Side project template, with local users and accounts authentication enabled.

We have then changed the App.razor file to the following:

<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
    <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
        <NotAuthorized>
            NOT AUTHORIZED!!!!!
        </NotAuthorized>
        <Authorizing>
            AUTHORIZING!!!!!
        </Authorizing>
        </AuthorizeRouteView>
</Found>
<NotFound>
    <CascadingAuthenticationState>
        <LayoutView Layout="@typeof(MainLayout)">

Sorry, there's nothing at this address.

        </LayoutView>
    </CascadingAuthenticationState>
</NotFound>

The code in <NotAuthorized> never gets hit, I have confirmed no cookies on the browser, and even tried in a private browser window as well.

I have in a different component injected the HTTPContext to see what is going on with the current user. Current user is not null, it has an identity, but is showing an unauthenticated, and has no claims as expected.

Is there something i am missing here?

Body:
I have the same problem with the current Blazor version in a WebAssembly (client) project.

It would be nice if the Blazor team could tell us what we do wrong, because you use exactly the code they suggest to use.

I found a workaround by using an <AuthorizeView> in my MainLayout. There the <NotAuthorized> part is executed correctly and you can use the code they suggested to force a redirect to log on:

<AuthorizeView>
    <Authorized>
        <!-- Markup of your MainLayout -->
    </Authorized>
    <NotAuthorized>
        <RedirectToLogin />
    </NotAuthorized>
</AuthorizeView>


问:
Join two dataframes to get cartesian product
How to join two dataframes and get the cartesian product of all rows in both dataframes.

df1:

```<code>   values
0       4
1       5
2       6
</code>```

df2:

```<code>   values
0       7
1       8
2       9
</code>```

Expected Output:

```<code>   values_x  values_y
0         4         7
1         4         8
2         4         9
3         5         7
4         5         8
5         5         9
6         6         7
7         6         8
8         6         9
</code>```

答:
Try this:</p>

```<code>pd.merge(df1, df2, how = 'outer', left_on = 'value1', right_on = 'value2')
</code>```

Body:
How to join two dataframes and get the cartesian product of all rows in both dataframes.

df1:

   values
0       4
1       5
2       6

df2:

   values
0       7
1       8
2       9

Expected Output:

   values_x  values_y
0         4         7
1         4         8
2         4         9
3         5         7
4         5         8
5         5         9
6         6         7
7         6         8
8         6         9

Body:
Try this:

pd.merge(df1, df2, how = 'outer', left_on = 'value1', right_on = 'value2')


问:
How to set the right permissions of my private ssh_key on start of my docker container?
At Each start of my docker container i got the error message:

```<code>Permissions 0644 for '/root/.ssh/id_rsa' are too open.
</code>```

So i set the right permissions at each start with the following command:

```<code>chmod 400 ~/.ssh/id_rsa
</code>```

But i want to make it automatic,
so i tried to set the permissions in the Dockerfile at the RUN instruction and directly in the docker run command but it didn't work.
I added this in the Dockerfile:

```<code>RUN chmod 400 ~/.ssh/id_rsa
</code>```

and this in the docker run command:

```<code>docker run [...] ; docker run chmod 400 ~/.ssh/id_rsa
</code>```

Can you help me to run a command directly in my docker container ?

答:
When you have changed your Dockerfile, have you tried to rebuild the image ?

The command used to rebuild image from Dockerfile is the following: docker build -t name . where the dot is the path with the Dockerfile, and name is the name of your container :)

Body:
At Each start of my docker container i got the error message:

Permissions 0644 for '/root/.ssh/id_rsa' are too open.

So i set the right permissions at each start with the following command:

chmod 400 ~/.ssh/id_rsa

But i want to make it automatic,
so i tried to set the permissions in the Dockerfile at the RUN instruction and directly in the docker run command but it didn't work.
I added this in the Dockerfile:

RUN chmod 400 ~/.ssh/id_rsa

and this in the docker run command:

docker run [...] ; docker run chmod 400 ~/.ssh/id_rsa

Can you help me to run a command directly in my docker container ?


问:
How do you install something directly from the GitHub repo?
I am a beginner, and tried to install PyDictionary with pip. It installed, but I had the same issue as this thread - it did not work:
    How to get rid of the BeautifulSoup html parser error when I'm not using BeautifulSoup
Someone on here suggested installing if directly from the GitHub repo, but I'm not sure which file to download and what to do next.

UPDATE 1

I've updated pip, and used:

python3 -m pip install PyDictionary

(I needed python3 for some reason). I then used this program:

```<code>from PyDictionary import PyDictionary
dictionary = PyDictionary()
print (dictionary.synonym("Life"))
</code>```

But got:

Warning (from warnings module): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PyDictionary/utils.py", line 5 return BeautifulSoup(requests.get(url).text) UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 5 of the file /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PyDictionary/utils.py.

To get rid of this warning, pass the additional argument 'features="lxml"' to the BeautifulSoup constructor. Life has no Synonyms in the API None –

UPDATE 2

```<code>python3 -m pip install git+https://github.com/geekpradd/PyDictionary
</code>```

returns:

Collecting git+github.com/geekpradd/PyDictionary Cloning github.com/geekpradd/PyDictionary to /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt Running command git clone -q github.com/geekpradd/PyDictionary /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxtERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/setup.py'"'"'; file__='"'"'/private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/pip-egg-info cwd: /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/ Complete output (5 lines): Traceback (most recent call last):
  File "", line 1, in  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tokenize.py", line 392, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: '/private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/setup.py'
  ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output

答:
See VCS, from the pip docs

pip currently supports cloning over git, git+http, git+https, git+ssh, git+git and git+file:

Here are the supported forms:

git://git.example.com/MyProject#egg=MyProject
  git+http://git.example.com/MyProject#egg=MyProject
  git+https://git.example.com/MyProject#egg=MyProject
  git+ssh://git.example.com/MyProject#egg=MyProject
  git+git://git.example.com/MyProject#egg=MyProject
  git+file:///home/user/projects/MyProject#egg=MyProject

Body:
I am a beginner, and tried to install PyDictionary with pip. It installed, but I had the same issue as this thread - it did not work:
    How to get rid of the BeautifulSoup html parser error when I'm not using BeautifulSoup
Someone on here suggested installing if directly from the GitHub repo, but I'm not sure which file to download and what to do next.

UPDATE 1

I've updated pip, and used:

python3 -m pip install PyDictionary

(I needed python3 for some reason). I then used this program:

from PyDictionary import PyDictionary
dictionary = PyDictionary()
print (dictionary.synonym("Life"))

But got:

Warning (from warnings module): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PyDictionary/utils.py", line 5 return BeautifulSoup(requests.get(url).text) UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 5 of the file /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PyDictionary/utils.py.

To get rid of this warning, pass the additional argument 'features="lxml"' to the BeautifulSoup constructor. Life has no Synonyms in the API None –

UPDATE 2

python3 -m pip install git+https://github.com/geekpradd/PyDictionary

returns:

Collecting git+github.com/geekpradd/PyDictionary Cloning github.com/geekpradd/PyDictionary to /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt Running command git clone -q github.com/geekpradd/PyDictionary /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxtERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/setup.py'"'"'; file__='"'"'/private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/pip-egg-info cwd: /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/ Complete output (5 lines): Traceback (most recent call last):
  File "", line 1, in  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tokenize.py", line 392, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: '/private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/setup.py'
  ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output


问:
Abaqus Python getByBoundingBox command
I have a 2D part in Abaqus with many partitions and I therefore want to select many edges with the getByBoundingBox command to create a surface set. This is the bit of code I have:

```<code>p = mdb.models['Model-1'].parts['Plate']
s = p.edges
edges = s.getByBoundingBox((0,0.02,0,0.003,0.04,0))
p.Surface(side1Edges=edges, name='r1')
</code>```

But it gives me the following error: "edges = s.getByBoundingBox((0,0.02,0,0.003,0.04,0)) TypeError: arg1; found tuple, expecting float".

Any advice much appreciated.

答:
this comes quite late but in case anyone enters and has the same doubt:

When telling to Abaqus which edge/face/element you are actually selecting, sometimes you need to specify the "ID" of that object, that's why it's asking for a float instead of a tuple in the error message. This can be solved as:

You select the edge/face/node/element you want:

```<code>   edge = s.getByBoundingBox((0,0.02,0,0.003,0.04,0))
</code>```

Create a intermediate variable to know the "ID" of the element:

```<code>   edge_id = edge.id
</code>```

You now can refenciate it in the dialog for creating surfaces:

```<code>   p.Surface(side1Edges=p.edges[edge_id], name='r1')
</code>```

In this case, you're telling Abaqus to select the edge with the id "edge_id" from all the edges that your part "p" has.

This happens many times and you've to be aware what Abaqus is expecting from the code. Sometimes can be the object itselft, a tuple of elements or simply a float expressed as a tupple e.g: edge = (number, )

Regards

Title: Abaqus Python getByBoundingBox command

Body:
I have a 2D part in Abaqus with many partitions and I therefore want to select many edges with the getByBoundingBox command to create a surface set. This is the bit of code I have:

p = mdb.models['Model-1'].parts['Plate']
s = p.edges
edges = s.getByBoundingBox((0,0.02,0,0.003,0.04,0))
p.Surface(side1Edges=edges, name='r1')

But it gives me the following error: "edges = s.getByBoundingBox((0,0.02,0,0.003,0.04,0)) TypeError: arg1; found tuple, expecting float".

Any advice much appreciated.

Body:
this comes quite late but in case anyone enters and has the same doubt:

When telling to Abaqus which edge/face/element you are actually selecting, sometimes you need to specify the "ID" of that object, that's why it's asking for a float instead of a tuple in the error message. This can be solved as:

You select the edge/face/node/element you want:

   edge = s.getByBoundingBox((0,0.02,0,0.003,0.04,0))

Create a intermediate variable to know the "ID" of the element:

   edge_id = edge.id

You now can refenciate it in the dialog for creating surfaces:

   p.Surface(side1Edges=p.edges[edge_id], name='r1')

In this case, you're telling Abaqus to select the edge with the id "edge_id" from all the edges that your part "p" has.

This happens many times and you've to be aware what Abaqus is expecting from the code. Sometimes can be the object itselft, a tuple of elements or simply a float expressed as a tupple e.g: edge = (number, )

Regards


问:
k-means analysis: how to convert data into numeric?
I want to perform a k-means analysis in R. For that I need numeric data. I tried the following

```<code>unlist(pca)
as.numeric(pca)

lapply(pca,as.numeric(pca))
</code>```

pca is just "normal" Principal Component Analysis data, showed in a plot (with fviz_pca_ind() function).

By the way, when I try to run the k-means analysis, it gives me "list object cannot be coerced to type double". That is why I thought to turn everything into numeric.

How to convert the pca-data into numeric?

Thank you ;)

答:
You're almost correct

```<code>lapply(pca,as.numeric)
</code>```

as.numeric is a function and therefore an object. You need to pass it to lapply() as an object and therefore without the quotation marks.

Body:
I want to perform a k-means analysis in R. For that I need numeric data. I tried the following

unlist(pca)
as.numeric(pca)

lapply(pca,as.numeric(pca))

pca is just "normal" Principal Component Analysis data, showed in a plot (with fviz_pca_ind() function).

By the way, when I try to run the k-means analysis, it gives me "list object cannot be coerced to type double". That is why I thought to turn everything into numeric.

How to convert the pca-data into numeric?

Thank you ;)

Body:
You're almost correct

lapply(pca,as.numeric)

as.numeric is a function and therefore an object. You need to pass it to lapply() as an object and therefore without the quotation marks.


问:
How to detect Pivot View using MVVM in WP7?
basically I have a pivot control in my WP7 app that contains 3 views. On each view I'm calling 1 of my 3 different web services that I run. What I'm trying to do is call the service only when they navigate to that particular view.

It's pretty simple using the code behind because all you do is use selected index with a switch statement and you can fire certain methods accordingly. Any idea on how to accomplish this from a view model?

NOTE: I'm using MVVM Light.

UPDATE: Here's my code that I would normally use:

```<code>private void PivotItem_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        int currentPivot = ResultsPivot.SelectedIndex;
        switch (currentPivot)
        {
            case 0:
                //Fire Method 1
                break;
            case 1:
                //Fire Method 2
                break;
            case 2:
                //Fire Method 3
                break;
            default:
                //Fire default method
                break;
        }
    }
</code>```

答:
The standard approach with MVVMLight is the split your view-model into data and commands.  Most things you use databinding related, properties, etc. but commands actually do something.

In this case what you are calling "Fire Method 1" is an ordinary method that to conform to the pattern you have to convert to a command.  If you already have commands you know what I am talking about.

The glue for events like SelectionChanged that you would have wired up with code-behind in MVVMLight is EventToCommand which is a XAML fragment that you put in the XAML with the pivot item instead of in the event hander.

So this is the pattern: EventToCommand is your key to hooking up XAML events to view-model commands without any code-behind.  The best thing to do is use the MVVMLight samples to see how EventToCommand works because there are lots of ways to use it.

But here is the bare-bones version:

```<code><controls:PivotItem Name="pivotItem">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <cmd:EventToCommand Command="{Binding SelectServiceCommand}"
                                CommandParameter="{Binding SelectedIndex, ElementName=pivotItem}"/>
        </i:EventTrigger>
        <!-- other stuff  -->
    </i:Interaction.Triggers>
</controls:PivotItem>
</code>```

and to make this work the SelectServiceCommand has to actually exist in the view-model and it has to take a parameter and do the right thing for 0, 1, 2, 3, etc.

Body:
basically I have a pivot control in my WP7 app that contains 3 views. On each view I'm calling 1 of my 3 different web services that I run. What I'm trying to do is call the service only when they navigate to that particular view.

It's pretty simple using the code behind because all you do is use selected index with a switch statement and you can fire certain methods accordingly. Any idea on how to accomplish this from a view model?

NOTE: I'm using MVVM Light.

UPDATE: Here's my code that I would normally use:

private void PivotItem_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        int currentPivot = ResultsPivot.SelectedIndex;
        switch (currentPivot)
        {
            case 0:
                //Fire Method 1
                break;
            case 1:
                //Fire Method 2
                break;
            case 2:
                //Fire Method 3
                break;
            default:
                //Fire default method
                break;
        }
    }

Body:
The standard approach with MVVMLight is the split your view-model into data and commands.  Most things you use databinding related, properties, etc. but commands actually do something.

In this case what you are calling "Fire Method 1" is an ordinary method that to conform to the pattern you have to convert to a command.  If you already have commands you know what I am talking about.

The glue for events like SelectionChanged that you would have wired up with code-behind in MVVMLight is EventToCommand which is a XAML fragment that you put in the XAML with the pivot item instead of in the event hander.

So this is the pattern: EventToCommand is your key to hooking up XAML events to view-model commands without any code-behind.  The best thing to do is use the MVVMLight samples to see how EventToCommand works because there are lots of ways to use it.

But here is the bare-bones version:

<controls:PivotItem Name="pivotItem">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <cmd:EventToCommand Command="{Binding SelectServiceCommand}"
                                CommandParameter="{Binding SelectedIndex, ElementName=pivotItem}"/>
        </i:EventTrigger>
        <!-- other stuff  -->
    </i:Interaction.Triggers>
</controls:PivotItem>

and to make this work the SelectServiceCommand has to actually exist in the view-model and it has to take a parameter and do the right thing for 0, 1, 2, 3, etc.


问:
Why is c# ReadXml returning wrong data?
I am caching data to decrease SQL Server activity.

When I fetch data from SQL Server the first time it is requested, I then use WriteXml to store it on disk.

Then second time it is requested (i.e. a file called cacheName exists), I fetch the data with ReadXml.

The data in SQL Server has only one row with utcDT value of '2012-03-25 02:01' and when I write the DataTable at Code point 1 Test1() shows there is only one row. When I manually inspect Xml file on disk I also see only 1 row.

However, after reading with ReadXml at code point 2 Test1() shows 2 such rows!

How is this happening?

```<code>public static DataTable FetchCache()
{
    var cacheName = @"C:\MyCache.xml";

    if (File.Exists(cacheName))
    {
        var ds = new DataSet();
        var fs = new FileStream(cacheName, FileMode.Open, FileAccess.Read, FileShare.Read);

        using (var sr = new StreamReader(fs))
        {
            ds.ReadXml(sr, XmlReadMode.ReadSchema);
        }

        table = ds.Tables[0];
        Test1(table);  //Code point 2
    }
    else
    {
        table = FetchDataTable(connectionString, sqlCommand, nullOnError: nullOnError);
        Test1(table); //Code point 1
        table.WriteXml(cacheName, XmlWriteMode.WriteSchema);
    }

    return table;
}

public static void Test1(DataTable table)
{
    var rows = table.AsEnumerable()
                    .Where(x => x.Field<DateTime>("utcDT").Equals(new DateTime(2012, 03, 25, 02, 01, 00)))
                    .ToArray();
}

public static DataTable FetchDataTable(string connectionString, string sqlCommand, bool nullOnError= false)
{
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();

    try
    {
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();

            SqlDataAdapter da = new SqlDataAdapter(sqlCommand, conn);
            da.SelectCommand.CommandTimeout = 600;
            ds.Reset();

            da.Fill(ds);
            dt = ds.Tables[0];
        }
    }
    catch (Exception err)
    {
        if (nullOnError)
            return dt;

        throw new Exception("[Utils.MsSQLS.FetchDataTable] Could not get data: " + err.Message);
    }

    return dt;
}
</code>```

答:
Just in case anyone else has same issue. I found the answer.

My SQL table DateTime columns were originally specified as UnspecifiedLocal, but the data they contain is actually UTC.

In order to save to cache as Xml, I have to create a new DataTable clone from table I fetch from SQL, and change DateTimeMode to UTC , then I copy from the old table to the new (row by row using ItemArray copy).

This is cumbersome but gets rid of the issue.

Title: Why is c# ReadXml returning wrong data?

Body:
I am caching data to decrease SQL Server activity.

When I fetch data from SQL Server the first time it is requested, I then use WriteXml to store it on disk.

Then second time it is requested (i.e. a file called cacheName exists), I fetch the data with ReadXml.

The data in SQL Server has only one row with utcDT value of '2012-03-25 02:01' and when I write the DataTable at Code point 1 Test1() shows there is only one row. When I manually inspect Xml file on disk I also see only 1 row.

However, after reading with ReadXml at code point 2 Test1() shows 2 such rows!

How is this happening?

public static DataTable FetchCache()
{
    var cacheName = @"C:\MyCache.xml";

    if (File.Exists(cacheName))
    {
        var ds = new DataSet();
        var fs = new FileStream(cacheName, FileMode.Open, FileAccess.Read, FileShare.Read);

        using (var sr = new StreamReader(fs))
        {
            ds.ReadXml(sr, XmlReadMode.ReadSchema);
        }

        table = ds.Tables[0];
        Test1(table);  //Code point 2
    }
    else
    {
        table = FetchDataTable(connectionString, sqlCommand, nullOnError: nullOnError);
        Test1(table); //Code point 1
        table.WriteXml(cacheName, XmlWriteMode.WriteSchema);
    }

    return table;
}

public static void Test1(DataTable table)
{
    var rows = table.AsEnumerable()
                    .Where(x => x.Field<DateTime>("utcDT").Equals(new DateTime(2012, 03, 25, 02, 01, 00)))
                    .ToArray();
}

public static DataTable FetchDataTable(string connectionString, string sqlCommand, bool nullOnError= false)
{
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();

    try
    {
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();

            SqlDataAdapter da = new SqlDataAdapter(sqlCommand, conn);
            da.SelectCommand.CommandTimeout = 600;
            ds.Reset();

            da.Fill(ds);
            dt = ds.Tables[0];
        }
    }
    catch (Exception err)
    {
        if (nullOnError)
            return dt;

        throw new Exception("[Utils.MsSQLS.FetchDataTable] Could not get data: " + err.Message);
    }

    return dt;
}


问:
Factorial static method
I am making a factorial calc with static methods I've been able to make it work with one int at a time but the scanner needs to be able to take two ints (N and M) where the code executes the factorial of all numbers from N up to M.

import java.util.Scanner;
public class Factorial {

  public static long Factorialcalc(int n) {
    long fact = 1;
    for (int i = 1; i <= n; i++) {
      fact *= i;
    }
    return fact;
  }
  public static void main(String args[]) {
    System.out.println("Enter first int N");
    Scanner sc = new Scanner(System.in);
    int n;
    long fact = 1;
    n = sc.nextInt();
    System.out.println("Enter second int M");
    int m;
    m = sc.nextInt();
    if (n < 0) {
      System.out.println("Not Valid!");
    } else {
      for (int i = n; i <= m; i++) {
        fact = Factorialcalc(i);
      }
      fact = Factorialcalc(n);
      System.out.println("the factorial for " + n + " is " + fact + ".");
    }
  }
}```

I'm not sure how I should go about adding in the M int for it to calculate the factorial from N upwards.

答:
in main method following changes required:

int m = sc.nextInt()

in else block:

```<code>for (int i=n;i<=m;i++){
    fact = Factorial.Factorialcalc(i);

}
</code>```

Tip: Always add your code as a Code Sample or Snippet (HTML/CSS/JS)

Title: Factorial static method

Body:
I am making a factorial calc with static methods I've been able to make it work with one int at a time but the scanner needs to be able to take two ints (N and M) where the code executes the factorial of all numbers from N up to M.

import java.util.Scanner;
public class Factorial {

  public static long Factorialcalc(int n) {
    long fact = 1;
    for (int i = 1; i <= n; i++) {
      fact *= i;
    }
    return fact;
  }
  public static void main(String args[]) {
    System.out.println("Enter first int N");
    Scanner sc = new Scanner(System.in);
    int n;
    long fact = 1;
    n = sc.nextInt();
    System.out.println("Enter second int M");
    int m;
    m = sc.nextInt();
    if (n < 0) {
      System.out.println("Not Valid!");
    } else {
      for (int i = n; i <= m; i++) {
        fact = Factorialcalc(i);
      }
      fact = Factorialcalc(n);
      System.out.println("the factorial for " + n + " is " + fact + ".");
    }
  }
}

I'm not sure how I should go about adding in the M int for it to calculate the factorial from N upwards.

Body:
in main method following changes required:

int m = sc.nextInt()

in else block:

for (int i=n;i<=m;i++){
    fact = Factorial.Factorialcalc(i);

}

Tip: Always add your code as a Code Sample or Snippet (HTML/CSS/JS)


问:
Proper way to initialize a C# dictionary with values
I am creating a dictionary in a C# file with the following code:

```<code>private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT
        = new Dictionary<string, XlFileFormat>
        {
            {"csv", XlFileFormat.xlCSV},
            {"html", XlFileFormat.xlHtml}
        };
</code>```

There is a red line under new with the error:

Feature 'collection initilializer' cannot be used because it is not part of the ISO-2 C# language specification

What is going on here?

I am using .NET version 2.

答:
With С# 6.0</p>
```<code>var myDict = new Dictionary<string, string>
{
    ["Key1"] = "Value1",
    ["Key2"] = "Value2"
};
</code>```

Body:
I am creating a dictionary in a C# file with the following code:

private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT
        = new Dictionary<string, XlFileFormat>
        {
            {"csv", XlFileFormat.xlCSV},
            {"html", XlFileFormat.xlHtml}
        };

There is a red line under new with the error:

Feature 'collection initilializer' cannot be used because it is not part of the ISO-2 C# language specification

What is going on here?

I am using .NET version 2.

Body:
With С# 6.0

var myDict = new Dictionary<string, string>
{
    ["Key1"] = "Value1",
    ["Key2"] = "Value2"
};


问:
Convert javascript from minified to uncompressed?

Possible Duplicate:

  Can compressed javascript be uncompressed

How can I convert my javascript from mifified to uncompressed? Thanks

答:
http://jsbeautifier.org/

This is probably your best chance at making sense of minified code.  Good luck brave one!


问:
universal linking (deeplinking) for unity IOS
Has anyone worked with unity deeplinking. I am following all the documentation and able to trigger the application using urlschemes or universal links. But my unity application is not able to receive the intents.

I even tried Application.absoluteurl but it still returns empty.

Some help here please.

答:
In Unity 2019.3 they have introduced Application.deepLinkingActivated and Application.AbsoluteURL which check if the app is opened using deeplink. The problem i had was a null exception. Once that was cleared the app worked.

Thanks for the suggestion guys.


问:
CakePHP: upgrade from 3.6.x to 4.0 "Missing Template Exception"
I followed the upgrade guide (after I upgraded from 3.6 to 3.8) but I get this error:

Error: [Cake\View\Exception\MissingTemplateException] Template file "Error\error500.ctp" is missing

....

If you want to customize this error message, create src\Template\Error\fatal_error.ctp

After the upgrade procedure my templates moved to app_name\templates directory and renamed to *.php instead of *.ctp . I updated the app.php and app.default.php with the new paths:

```<code>'App' => [
        'namespace' => 'App',
        'encoding' => env('APP_ENCODING', 'UTF-8'),
        'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
        'defaultTimezone' => env('APP_DEFAULT_TIMEZONE', 'UTC'),
        'base' => false,
        'dir' => 'src',
        'webroot' => 'webroot',
        'wwwRoot' => WWW_ROOT,
        //'baseUrl' => env('SCRIPT_NAME'),
        'fullBaseUrl' => false,
        'imageBaseUrl' => 'img/',
        'cssBaseUrl' => 'css/',
        'jsBaseUrl' => 'js/',
        'paths' => [
            'plugins' => [ROOT . DS . 'plugins' . DS],
            'templates' => [ROOT . DS . 'templates' . DS],
            'locales' => [ROOT . DS  . 'Locale' . DS],
        ],
    ],
</code>```

But still the application is looking for the template files with .ctp extension and under src\Template\...

What am I missing?

答:
From my experience:

Upgrade CakePHP 3.x to 4.x

composer update

run phpstan from --level 0 to 2 and fix your code or test in scrutinizer

read 4.0 Migration Guide : https://book.cakephp.org/4/en/appendices/4-0-migration-guide.html

read 4.0 Upgrade Guide : https://book.cakephp.org/4/en/appendices/4-0-upgrade-guide.html
Steps:

Install the upgrade tool

Rename locale files

Rename template files

Once you've renamed your template and locale files, make sure you update App.paths.locales and App.paths.templates paths to be correct.

From your app composer file remove all cakephp/*  (cakephp3) packages, also phpstan, code  standards, phpunit,.. run composer update

Applying Rector Refactorings

composer require --update-with-dependencies "phpunit/phpunit:^8.0"

composer require --update-with-dependencies "cakephp/cakephp:4.0.*"

Install fresh cakephp4 inside your app folder. Example: mkdir cakephp4  && cd cakeph4; and run composer create-project --prefer-dist cakephp/app:4.*  .;

compare your old  cakephp files with files from cakephp4 folder, update all and copy missing files

delete cakephp4 and upgrade folders

don't forget at top of you php files to add <?php declare(strict_types=1);

composer cs-check then composer cs-fix

Body:
I followed the upgrade guide (after I upgraded from 3.6 to 3.8) but I get this error:

Error: [Cake\View\Exception\MissingTemplateException] Template file "Error\error500.ctp" is missing

....

If you want to customize this error message, create src\Template\Error\fatal_error.ctp

After the upgrade procedure my templates moved to app_name\templates directory and renamed to *.php instead of *.ctp . I updated the app.php and app.default.php with the new paths:

'App' => [
        'namespace' => 'App',
        'encoding' => env('APP_ENCODING', 'UTF-8'),
        'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
        'defaultTimezone' => env('APP_DEFAULT_TIMEZONE', 'UTC'),
        'base' => false,
        'dir' => 'src',
        'webroot' => 'webroot',
        'wwwRoot' => WWW_ROOT,
        //'baseUrl' => env('SCRIPT_NAME'),
        'fullBaseUrl' => false,
        'imageBaseUrl' => 'img/',
        'cssBaseUrl' => 'css/',
        'jsBaseUrl' => 'js/',
        'paths' => [
            'plugins' => [ROOT . DS . 'plugins' . DS],
            'templates' => [ROOT . DS . 'templates' . DS],
            'locales' => [ROOT . DS  . 'Locale' . DS],
        ],
    ],

But still the application is looking for the template files with .ctp extension and under src\Template\...

What am I missing?


问:
How to specify the FROM tables in SQLAlchemy subqueries?
I am trying to fetch in a single query a fixed set of rows, plus some other rows found by a subquery. My problem is that the query generated by my SQLAlchemy code is incorrect.

The problem is that the query generated by SQLAlchemy is as follows:

```<code>SELECT tbl.id AS tbl_id
FROM tbl
WHERE tbl.id IN
(
SELECT t2.id AS t2_id
FROM tbl AS t2, tbl AS t1
WHERE t2.id =
(
SELECT t3.id AS t3_id
FROM tbl AS t3, tbl AS t1
WHERE t3.id < t1.id ORDER BY t3.id DESC LIMIT 1 OFFSET 0
)
AND t1.id IN (4, 8)
)
OR tbl.id IN (0, 8)
</code>```

while the correct query should not have the second tbl AS t1 (the goal from this query is to select IDs 0 and 8, as well as the IDs just before 4 and 8).

Unfortunately, I can't find how to get SQLAlchemy to generate the correct one (see the code below).

Suggestions to also achieve the same result with a simpler query are also welcome (they need to be efficient though -- I tried a few variants and some were a lot slower on my real use case).

The code producing the query:

```<code>from sqlalchemy import create_engine, or_
from sqlalchemy import Column, Integer, MetaData, Table
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///:memory:', echo=True)
meta = MetaData(bind=engine)
table = Table('tbl', meta, Column('id', Integer))
session = sessionmaker(bind=engine)()
meta.create_all()

# Insert IDs 0, 2, 4, 6, 8.
i = table.insert()
i.execute(*[dict(id=i) for i in range(0, 10, 2)])
print session.query(table).all()
# output: [(0,), (2,), (4,), (6,), (8,)]

# Subquery of interest: look for the row just before IDs 4 and 8.
sub_query_txt = (
        'SELECT t2.id '
        'FROM tbl t1, tbl t2 '
        'WHERE t2.id = ( '
        ' SELECT t3.id from tbl t3 '
        ' WHERE t3.id < t1.id '
        ' ORDER BY t3.id DESC '
        ' LIMIT 1) '
        'AND t1.id IN (4, 8)')
print session.execute(sub_query_txt).fetchall()
# output: [(2,), (6,)]

# Full query of interest: get the rows mentioned above, as well as more rows.
query_txt = (
        'SELECT * '
        'FROM tbl '
        'WHERE ( '
        ' id IN (%s) '
        'OR id IN (0, 8))'
        ) % sub_query_txt
print session.execute(query_txt).fetchall()
# output: [(0,), (2,), (6,), (8,)]

# Attempt at an SQLAlchemy translation (from innermost sub-query to full query).
t1 = table.alias('t1')
t2 = table.alias('t2')
t3 = table.alias('t3')
q1 = session.query(t3.c.id).filter(t3.c.id < t1.c.id).order_by(t3.c.id.desc()).\
             limit(1)
q2 = session.query(t2.c.id).filter(t2.c.id == q1, t1.c.id.in_([4, 8]))
q3 = session.query(table).filter(
                               or_(table.c.id.in_(q2), table.c.id.in_([0, 8])))
print list(q3)
# output: [(0,), (6,), (8,)]
</code>```

答:
The responses here helped me fix my issue but in my case I had to use both correlate() and subquery():

# ...
subquery = subquery.correlate(OuterCorrelationTable).subquery()
filter_query = db.session.query(func.sum(subquery.c.some_count_column))
filter = filter_query.as_scalar() == as_many_as_some_param
# ...
final_query = db.session.query(OuterCorrelationTable).filter(filter)
```

Body:
I am trying to fetch in a single query a fixed set of rows, plus some other rows found by a subquery. My problem is that the query generated by my SQLAlchemy code is incorrect.

The problem is that the query generated by SQLAlchemy is as follows:

SELECT tbl.id AS tbl_id
FROM tbl
WHERE tbl.id IN
(
SELECT t2.id AS t2_id
FROM tbl AS t2, tbl AS t1
WHERE t2.id =
(
SELECT t3.id AS t3_id
FROM tbl AS t3, tbl AS t1
WHERE t3.id < t1.id ORDER BY t3.id DESC LIMIT 1 OFFSET 0
)
AND t1.id IN (4, 8)
)
OR tbl.id IN (0, 8)

while the correct query should not have the second tbl AS t1 (the goal from this query is to select IDs 0 and 8, as well as the IDs just before 4 and 8).

Unfortunately, I can't find how to get SQLAlchemy to generate the correct one (see the code below).

Suggestions to also achieve the same result with a simpler query are also welcome (they need to be efficient though -- I tried a few variants and some were a lot slower on my real use case).

The code producing the query:

from sqlalchemy import create_engine, or_
from sqlalchemy import Column, Integer, MetaData, Table
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///:memory:', echo=True)
meta = MetaData(bind=engine)
table = Table('tbl', meta, Column('id', Integer))
session = sessionmaker(bind=engine)()
meta.create_all()

# Insert IDs 0, 2, 4, 6, 8.
i = table.insert()
i.execute(*[dict(id=i) for i in range(0, 10, 2)])
print session.query(table).all()
# output: [(0,), (2,), (4,), (6,), (8,)]

# Subquery of interest: look for the row just before IDs 4 and 8.
sub_query_txt = (
        'SELECT t2.id '
        'FROM tbl t1, tbl t2 '
        'WHERE t2.id = ( '
        ' SELECT t3.id from tbl t3 '
        ' WHERE t3.id < t1.id '
        ' ORDER BY t3.id DESC '
        ' LIMIT 1) '
        'AND t1.id IN (4, 8)')
print session.execute(sub_query_txt).fetchall()
# output: [(2,), (6,)]

# Full query of interest: get the rows mentioned above, as well as more rows.
query_txt = (
        'SELECT * '
        'FROM tbl '
        'WHERE ( '
        ' id IN (%s) '
        'OR id IN (0, 8))'
        ) % sub_query_txt
print session.execute(query_txt).fetchall()
# output: [(0,), (2,), (6,), (8,)]

# Attempt at an SQLAlchemy translation (from innermost sub-query to full query).
t1 = table.alias('t1')
t2 = table.alias('t2')
t3 = table.alias('t3')
q1 = session.query(t3.c.id).filter(t3.c.id < t1.c.id).order_by(t3.c.id.desc()).\
             limit(1)
q2 = session.query(t2.c.id).filter(t2.c.id == q1, t1.c.id.in_([4, 8]))
q3 = session.query(table).filter(
                               or_(table.c.id.in_(q2), table.c.id.in_([0, 8])))
print list(q3)
# output: [(0,), (6,), (8,)]


问:
Efficient way for maximum medians from triangle polygons
Objective

I have a soup of triangle polygons. I want to retrieve the largest median as vector for each triangle.

State of work

Starting point:

Array of points (n,3) , e.g. [x,y,z]

Array of triangle point indices (n, 3) referencing the array of points above, e.g. [[0,1,2],[2,3,4]...]

I combine both two one single matrix containing the real 3D point coordinates. Then I calculate the median vectors and their lengths.

/Edit : I updated the code to my current version of it

```<code>def calcMedians(polygon):
    # C -> AB = C-(A + 0.5(B-A))
    # B -> AC = B - (A + 0.5(C-A))
    # A -> BC = A - (B
    dim = np.shape(polygon)

    medians = np.zeros((dim[0],3,2,dim[1]))

    medians[:,0,0] = polygon[:,2]
    medians[:,0,1] = polygon[:,0] + 0.5*(polygon[:,1]-polygon[:,0])
    medians[:,1,0] = polygon[:,1]
    medians[:,1,1] = polygon[:,0] + 0.5*(polygon[:,2]-polygon[:,0])
    medians[:,2,0] = polygon[:,0]
    medians[:,2,1] = polygon[:,1] + 0.5*(polygon[:,2]-polygon[:,1])

    m1 = np.linalg.norm(medians[:,0,0]-medians[:,0,1],axis=1)
    m2 = np.linalg.norm(medians[:,1,0]-medians[:,1,1],axis=1)
    m3 = np.linalg.norm(medians[:,2,0]-medians[:,2,1],axis=1)

    medianlengths = np.vstack((m1,m2,m3)).T
    maxlengths = np.argmax(medianlengths,axis=1)

    final = np.zeros((dim[0],2,dim[1]))
    dim = np.shape(medians)
    for i in range(0,dim[0]):
        idx = maxlengths[i]
        final[i] = medians[i,idx]

    return final
</code>```

Now I am creating the final median vector matrix using an empty matrix first. The lengths are calculated using np.linalg.norm and collected in a matrix. For this matrix, the argmax method is used to identify to target median vector.

Problem

Old:However, I am somehow confused by the dimensionality and currently not able to get this to work or to understand if the result is correct.
Does somebody know how to do this correctly and/or if this approach is efficient?

My target would be a construct of the 3 medians in form of [n_polygons, 3( due to 3 medians), 2 (start and end point), 3 (xyz)]

Using the max lengths information, i would like to reduce it to [n_polygons, 2 (start and end point), 3 (xyz)]

Using this improvised for loop in the function, I can create the output. But there has to be a more "clean" matrix method to it. Using medians[:,maxlengths,:,:] leads to a shape of [4,n_polygons,2,3] instead of [n_polygons,2,3] and I do not understand why.

Example image for medians of two triangles:

Unfortunately, I don't have a large exemplary data set but I guess that this can be generated quite quickly. The example data set from the picture shown above is:

```<code>polygons = np.array([[0,1,2],[0,3,2]])
points = np.array([[0,0],
          [1,0],
          [1,1],
          [0,1]])
polygons3d = points[polygons[:,:]]
</code>```

答:
The longest median is for the shortest triangle side. Look here and rewrite median length formula as

```<code>M[i] = Sqrt(2(a^2+b^2+c^2)-3*side[i]^2) / 2
</code>```

So you can simplify calculations a bit using only side lengths (perhaps you already have them)

Concerning 3D coordinates - just use projection on any coordinate plane not perpendicular to your point plane - ignore one dimension (choose dimension with the lowest value range)

Body:
Objective

I have a soup of triangle polygons. I want to retrieve the largest median as vector for each triangle.

State of work

Starting point:

Array of points (n,3) , e.g. [x,y,z]

Array of triangle point indices (n, 3) referencing the array of points above, e.g. [[0,1,2],[2,3,4]...]

I combine both two one single matrix containing the real 3D point coordinates. Then I calculate the median vectors and their lengths.

/Edit : I updated the code to my current version of it

def calcMedians(polygon):
    # C -> AB = C-(A + 0.5(B-A))
    # B -> AC = B - (A + 0.5(C-A))
    # A -> BC = A - (B
    dim = np.shape(polygon)

    medians = np.zeros((dim[0],3,2,dim[1]))

    medians[:,0,0] = polygon[:,2]
    medians[:,0,1] = polygon[:,0] + 0.5*(polygon[:,1]-polygon[:,0])
    medians[:,1,0] = polygon[:,1]
    medians[:,1,1] = polygon[:,0] + 0.5*(polygon[:,2]-polygon[:,0])
    medians[:,2,0] = polygon[:,0]
    medians[:,2,1] = polygon[:,1] + 0.5*(polygon[:,2]-polygon[:,1])

    m1 = np.linalg.norm(medians[:,0,0]-medians[:,0,1],axis=1)
    m2 = np.linalg.norm(medians[:,1,0]-medians[:,1,1],axis=1)
    m3 = np.linalg.norm(medians[:,2,0]-medians[:,2,1],axis=1)

    medianlengths = np.vstack((m1,m2,m3)).T
    maxlengths = np.argmax(medianlengths,axis=1)

    final = np.zeros((dim[0],2,dim[1]))
    dim = np.shape(medians)
    for i in range(0,dim[0]):
        idx = maxlengths[i]
        final[i] = medians[i,idx]

    return final

Now I am creating the final median vector matrix using an empty matrix first. The lengths are calculated using np.linalg.norm and collected in a matrix. For this matrix, the argmax method is used to identify to target median vector.

Problem

Old:However, I am somehow confused by the dimensionality and currently not able to get this to work or to understand if the result is correct.
Does somebody know how to do this correctly and/or if this approach is efficient?

My target would be a construct of the 3 medians in form of [n_polygons, 3( due to 3 medians), 2 (start and end point), 3 (xyz)]

Using the max lengths information, i would like to reduce it to [n_polygons, 2 (start and end point), 3 (xyz)]

Using this improvised for loop in the function, I can create the output. But there has to be a more "clean" matrix method to it. Using medians[:,maxlengths,:,:] leads to a shape of [4,n_polygons,2,3] instead of [n_polygons,2,3] and I do not understand why.

Example image for medians of two triangles:

Unfortunately, I don't have a large exemplary data set but I guess that this can be generated quite quickly. The example data set from the picture shown above is:

polygons = np.array([[0,1,2],[0,3,2]])
points = np.array([[0,0],
          [1,0],
          [1,1],
          [0,1]])
polygons3d = points[polygons[:,:]]

Body:
The longest median is for the shortest triangle side. Look here and rewrite median length formula as

M[i] = Sqrt(2(a^2+b^2+c^2)-3*side[i]^2) / 2

So you can simplify calculations a bit using only side lengths (perhaps you already have them)

Concerning 3D coordinates - just use projection on any coordinate plane not perpendicular to your point plane - ignore one dimension (choose dimension with the lowest value range)