问:
Gradle Project Sync Failed, Kotlin
I am using a beta Kotlin and Android-Studio channel. After update to the latest version i got some gradle sync error.

Below are the log i copied from Event Log:

```<code>Error:Could not find org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.0-rc-39.
Searched in the following locations:
    file:/home/yourpc/Android/android/gradle/m2repository/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2.0-rc-39/kotlin-gradle-plugin-1.2.0-rc-39.pom
    file:/home/yourpc/Android/android/gradle/m2repository/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2.0-rc-39/kotlin-gradle-plugin-1.2.0-rc-39.jar
    https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2.0-rc-39/kotlin-gradle-plugin-1.2.0-rc-39.pom
    https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2.0-rc-39/kotlin-gradle-plugin-1.2.0-rc-39.jar
    https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2.0-rc-39/kotlin-gradle-plugin-1.2.0-rc-39.pom
    https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2.0-rc-39/kotlin-gradle-plugin-1.2.0-rc-39.jar
Required by:
    project :
</code>```

below is the build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.2.0-rc-39'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0-alpha04'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

below is the app build.gradle:

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

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.udebest.myapplication"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            postprocessing {
                removeUnusedCode false
                removeUnusedResources false
                obfuscate false
                optimizeCode false
                proguardFile 'proguard-rules.pro'
            }
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

Please, anyone has an idea about this? I don't really know how can I solve this? I could not find any solutions out there.

答:
check your Kotlin version in build.gradle.
I got the same issue when the version was 1.1.0 which was added by default.
changed to recent version 1.3.21 then it is working fine. </p>

Title: Gradle Project Sync Failed, Kotlin

Body:
I am using a beta Kotlin and Android-Studio channel. After update to the latest version i got some gradle sync error.

Below are the log i copied from Event Log:

Error:Could not find org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.0-rc-39.
Searched in the following locations:
    file:/home/yourpc/Android/android/gradle/m2repository/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2.0-rc-39/kotlin-gradle-plugin-1.2.0-rc-39.pom
    file:/home/yourpc/Android/android/gradle/m2repository/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2.0-rc-39/kotlin-gradle-plugin-1.2.0-rc-39.jar
    https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2.0-rc-39/kotlin-gradle-plugin-1.2.0-rc-39.pom
    https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2.0-rc-39/kotlin-gradle-plugin-1.2.0-rc-39.jar
    https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2.0-rc-39/kotlin-gradle-plugin-1.2.0-rc-39.pom
    https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2.0-rc-39/kotlin-gradle-plugin-1.2.0-rc-39.jar
Required by:
    project :

below is the build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.2.0-rc-39'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0-alpha04'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

below is the app build.gradle:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.udebest.myapplication"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            postprocessing {
                removeUnusedCode false
                removeUnusedResources false
                obfuscate false
                optimizeCode false
                proguardFile 'proguard-rules.pro'
            }
        }
    }
}

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

Please, anyone has an idea about this? I don't really know how can I solve this? I could not find any solutions out there.


来源: stackexchange

问:
How to open search/find dialog in jqGrid from an external button?
I have a jqGrid which has a "find" button - this brings up the jqGrid's filter dialog where I can filter stuff - cool. How can I trigger that dialog to open from a button that is not a part of the jqGrid control?

I've found that I can do this: $("#id").trigger('reloadGrid'); to tell the grid to go get the data again and rebuild the jqGrid UI. Is there something similar, like $("#id").trigger('openFindDialog');?

答:
jqGrid has searchGrid method which you need to use. To open the searching dialog you should call the method and use any parameters or events which you probably knows from the previous usage of navGrid:

```<code>$("#id").jqGrid ('searchGrid', {multipleSearch:true, overlay: false});
</code>```

How you can see here the code which are running on click on the "Search" button of the navigator is not much more as this.

ContentLicense: CC BY-SA 3.0

Body:
jqGrid has searchGrid method which you need to use. To open the searching dialog you should call the method and use any parameters or events which you probably knows from the previous usage of navGrid:

$("#id").jqGrid ('searchGrid', {multipleSearch:true, overlay: false});

How you can see here the code which are running on click on the "Search" button of the navigator is not much more as this.


问:
How do I insert headers in Internet Explorer?
How do I insert headers names and values such as access tokens and its values in IE?.Just like this one on the left with Edge. It has a storage tab and session tab on the left to which I could put the necessary headers to override the login and OTP. This is also available in Chrome

It's just that I want to override our apps OTP function and login by inserting the values needed for it to skip the OTP and login. It just so happen that I need to test our apps compatibility with IE , but then I'm stuck on our very own login to which I could not do and bypass the security. Where do I find or insert the tokens needed to. TIA

答:
Got a help from a colleague.

Turns out. In the console, you should type

sessionStorage.setItem("accessToken","valueOfToken");

then press enter to insert the header.

After entering the value, when you type sessionStorage and press enter. You'd then finally be able to see the header that's going to be sent by IE. In my case its the accessToken header and its value.

ContentLicense: CC BY-SA 4.0


问:
Python: find previous and next `True` element in circular list
What is the best way to find the previous True element given current index in circular list.

For example given the data like these

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
my_list_condition = [0, 0, 1, 1, 0, 1, 1]
```

<ol>
<li>Find the previous element</li>
</ol>

<pre class="lang-py prettyprint-override"><code>before_e = find_prev('e', my_list, my_list_condition)
# before_e should be 'd'
before_c = find_prev('c', my_list, my_list_condition)
# before_c should be 'g' because it's circular list and the first True element before c is g
</code>```

Find the next element

after_e = find_next('e', my_list, my_list_condition)
# after_e should output 'f'

after_g = find_next('g', my_list, my_list_condition)
# after_g should output 'c' because it's circular list and the first True element after c is g
```

答:
You could use itertools.cycle And itertools.compress to find the next element ensuring circular looping and only looping needed items but ensure the element in conditions is kept, once that’s done, then finding the previous is just finding the next in reverse:

```<code>from itertools import cycle, compress

def find_next(c, lst, lst_condition):
    condition = lst_condition[:]
    condition[lst.index(c)] = 1
    elems = cycle(compress(lst, condition))
    for elem in elems:
        if elem == c:
            return next(elems)

def find_prev(c, lst, lst_condition):
    return find_next(c, list(reversed(lst)), list(reversed(lst_condition)))
</code>```

Test:

```<code>my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
my_list_condition = [0, 0, 1, 1, 0, 1, 1]

find_prev('e', my_list, my_list_condition) #d
find_prev('c', my_list, my_list_condition) #g

find_next('e', my_list, my_list_condition) # f
find_next('g', my_list, my_list_condition) #c
</code>```

Body:
What is the best way to find the previous True element given current index in circular list.

For example given the data like these

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
my_list_condition = [0, 0, 1, 1, 0, 1, 1]

Find the previous element

before_e = find_prev('e', my_list, my_list_condition)
# before_e should be 'd'
before_c = find_prev('c', my_list, my_list_condition)
# before_c should be 'g' because it's circular list and the first True element before c is g

Find the next element

after_e = find_next('e', my_list, my_list_condition)
# after_e should output 'f'

after_g = find_next('g', my_list, my_list_condition)
# after_g should output 'c' because it's circular list and the first True element after c is g

Body:
You could use itertools.cycle And itertools.compress to find the next element ensuring circular looping and only looping needed items but ensure the element in conditions is kept, once that’s done, then finding the previous is just finding the next in reverse:

from itertools import cycle, compress

def find_next(c, lst, lst_condition):
    condition = lst_condition[:]
    condition[lst.index(c)] = 1
    elems = cycle(compress(lst, condition))
    for elem in elems:
        if elem == c:
            return next(elems)

def find_prev(c, lst, lst_condition):
    return find_next(c, list(reversed(lst)), list(reversed(lst_condition)))

Test:

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
my_list_condition = [0, 0, 1, 1, 0, 1, 1]

find_prev('e', my_list, my_list_condition) #d
find_prev('c', my_list, my_list_condition) #g

find_next('e', my_list, my_list_condition) # f
find_next('g', my_list, my_list_condition) #c


问:
502 gateway error while deploying React v16.7 application in Google GCP app engine
hi I recently upgraded my React App from React v15.x to React v16.7.0 using create-react-application
I did couple of changes as below

After upgrading my app start failing because my previous app setup has both client and server part in same app. hence I compiled client part separately using
create-react-application project

then I merged my server part package.json with app created using create-react-application and brought my server part into same project

I setup proxy for my server as suggested in facebook help page

everything working fine in local machine, however when I tried deploying to google GCP app engine, got error 'invalid host header' , then I setup HOST: 'localhost' in app.yml file after that I am getting 502 Gateway error

any idea what needs to be done ?

My observations : create-react-application will run app at 3000 port, but for google gcp app should be running on 8080 port, hence I setup PORT=8080 in package.json as follows

```<code>"scripts": {
    "start": "PORT=8080 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
</code>```

Even with port 8080 I am still facing 502 gateway

答: Add HOST=your-appengine-domain to env file

Body:
hi I recently upgraded my React App from React v15.x to React v16.7.0 using create-react-application
I did couple of changes as below

After upgrading my app start failing because my previous app setup has both client and server part in same app. hence I compiled client part separately using
create-react-application project

then I merged my server part package.json with app created using create-react-application and brought my server part into same project

I setup proxy for my server as suggested in facebook help page

everything working fine in local machine, however when I tried deploying to google GCP app engine, got error 'invalid host header' , then I setup HOST: 'localhost' in app.yml file after that I am getting 502 Gateway error

any idea what needs to be done ?

My observations : create-react-application will run app at 3000 port, but for google gcp app should be running on 8080 port, hence I setup PORT=8080 in package.json as follows

"scripts": {
    "start": "PORT=8080 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

Even with port 8080 I am still facing 502 gateway


问:
How to identify compiler before defining cython extensions?
I'm building a platform independent cython project where I want to pass compiler args based on the compiler being used. I can guess the compiler based on platform or assume it's the same compiler used for Python but it's not guaranteed to match. Normally I inject into the cmdclass arg to setuptool's setup method and wrap the install or build_ext commands to check internal state. But in this case I have to cythonize the extension modules before I reach the wrappers.

Is there any way to determine the compiler inside setup.py before cythonizing the extension modules?

答:
A simple variation of the first answer:

from setuptools import setup, Extension
from distutils.command.build_ext import build_ext

myextension = Extension(
    name = 'packagename',
    sources = [
        'source/debugger.cpp',
    ],
    include_dirs = [ 'source' ],
)

class build_ext_compiler_check(build_ext):
    def build_extensions(self):
        compiler = self.compiler.compiler_type

        # print('\n\ncompiler', compiler)
        if not 'msvc' in compiler:

            for extension in self.extensions:

                if extension == myextension:
                    extension.extra_compile_args.append( '-O0' )
                    extension.extra_compile_args.append( '-std=c++11' )

        super().build_extensions()

setup(
        name = 'packagename',
        version = __version__,
        ext_modules= [ myextension ],
    )
```


问:
php variable scope
i'm confused about the php variable scope.
such as:

```<code>while(true){
    $var = "yes , it is a test!";
  }
  printf($var)
</code>```

the $var is defined in while statement scope , how could we get it outside it's scope ? and i can't find explanation on the document .

i wonder how php deal with it's scope .

答:
For the complete answer check the documentation:

http://php.net/manual/en/language.variables.scope.php

Title: php variable scope

Body:
i'm confused about the php variable scope.
such as:

while(true){
    $var = "yes , it is a test!";
  }
  printf($var)

the $var is defined in while statement scope , how could we get it outside it's scope ? and i can't find explanation on the document .

i wonder how php deal with it's scope .


问:
jquery row.siblings not working correctly
I have hide and show siblings js function, Here mainly I have 3 Teams

Malabar

Pazhassi

Travancore

Here when click on Malabar div Pazhassi and Travancore will disappear (ie: I need only Malabar div details with a show button.)

And when I click show button it will back to its first view, means I need all div's

my jquery

```<code>function clickInline(id)
 {

 $('#row'+id).siblings().show('');
 }
</code>```

But bad luck it's not working. here is my js fiddle
fiddle

Any help would be really appreciated

答:
The show button will trigger both functions because of bubbling,
you need to trigger the first function if the clicked element is not the show button

```<code> <div class="row" id="row1" onclick="cc(event,1)">

 function cc(event,id) {
   if(!$(event.target).is('.btn-dis')) {
     $('#row' + id).siblings().hide('slow');
     $(".btn-dis").css("display", "block")
    }
 }
</code>```

demo

Body:
I have hide and show siblings js function, Here mainly I have 3 Teams

Malabar

Pazhassi

Travancore

Here when click on Malabar div Pazhassi and Travancore will disappear (ie: I need only Malabar div details with a show button.)

And when I click show button it will back to its first view, means I need all div's

my jquery

function clickInline(id)
 {

 $('#row'+id).siblings().show('');
 }

But bad luck it's not working. here is my js fiddle
fiddle

Any help would be really appreciated

Body:
The show button will trigger both functions because of bubbling,
you need to trigger the first function if the clicked element is not the show button

 <div class="row" id="row1" onclick="cc(event,1)">

 function cc(event,id) {
   if(!$(event.target).is('.btn-dis')) {
     $('#row' + id).siblings().hide('slow');
     $(".btn-dis").css("display", "block")
    }
 }

demo


问:
Is there a way to make RecyclerView requiresFadingEdge unaffected by paddingTop and paddingBottom
Currently, I need to use paddingTop and paddingBottom of RecyclerView, as I want to avoid complex space calculation, in my first RecyclerView item and last item.

However, I notice that, requiresFadingEdge effect will be affected as well.

This is my XML

```<code><androidx.recyclerview.widget.RecyclerView
    android:requiresFadingEdge="vertical"
    android:paddingTop="0dp"
    android:paddingBottom="0dp"

    android:overScrollMode="always"
    android:background="?attr/recyclerViewBackground"
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false" />
</code>```

When paddingTop and paddingBottom is 40dp

As you can see, the fading effect shift down by 40dp, which is not what I want.

When paddingTop and paddingBottom is 0dp

Fading effect looks fine. But, I need to have non-zero paddingTop and paddingBottom, for my RecyclerView.

Is there a way to make RecyclerView's requiresFadingEdge unaffected by paddingTop and paddingBottom?

答:
There are many ways to achieve that but I preferred below solution that works for me.
You can use a third-party library called Android-FadingEdgeLayout checkout here

Here is a dependency.

```<code>implementation 'com.github.bosphere.android-fadingedgelayout:fadingedgelayout:1.0.0'
</code>```

In yours.xml

```<code><com.bosphere.fadingedgelayout.FadingEdgeLayout
    android:id="@+id/fading_edge_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:fel_edge="top|left|bottom|right"
    app:fel_size_top="40dp"
    app:fel_size_bottom="40dp"
    app:fel_size_left="0dp"
    app:fel_size_right="0dp">

    <androidx.recyclerview.widget.RecyclerView
        android:paddingTop="0dp"
        android:paddingBottom="0dp"
        android:overScrollMode="always"
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false" />

</com.bosphere.fadingedgelayout.FadingEdgeLayout>
</code>```

Change your ReacyclerView property according to your need. below is example image with all sided sades. I hope that will help you.

Credits Android-FadingEdgeLayout

Body:
Currently, I need to use paddingTop and paddingBottom of RecyclerView, as I want to avoid complex space calculation, in my first RecyclerView item and last item.

However, I notice that, requiresFadingEdge effect will be affected as well.

This is my XML

<androidx.recyclerview.widget.RecyclerView
    android:requiresFadingEdge="vertical"
    android:paddingTop="0dp"
    android:paddingBottom="0dp"

    android:overScrollMode="always"
    android:background="?attr/recyclerViewBackground"
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false" />

When paddingTop and paddingBottom is 40dp

As you can see, the fading effect shift down by 40dp, which is not what I want.

When paddingTop and paddingBottom is 0dp

Fading effect looks fine. But, I need to have non-zero paddingTop and paddingBottom, for my RecyclerView.

Is there a way to make RecyclerView's requiresFadingEdge unaffected by paddingTop and paddingBottom?

Body:
There are many ways to achieve that but I preferred below solution that works for me.
You can use a third-party library called Android-FadingEdgeLayout checkout here

Here is a dependency.

implementation 'com.github.bosphere.android-fadingedgelayout:fadingedgelayout:1.0.0'

In yours.xml

<com.bosphere.fadingedgelayout.FadingEdgeLayout
    android:id="@+id/fading_edge_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:fel_edge="top|left|bottom|right"
    app:fel_size_top="40dp"
    app:fel_size_bottom="40dp"
    app:fel_size_left="0dp"
    app:fel_size_right="0dp">

    <androidx.recyclerview.widget.RecyclerView
        android:paddingTop="0dp"
        android:paddingBottom="0dp"
        android:overScrollMode="always"
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false" />

</com.bosphere.fadingedgelayout.FadingEdgeLayout>

Change your ReacyclerView property according to your need. below is example image with all sided sades. I hope that will help you.

Credits Android-FadingEdgeLayout


问:
How do I use if-else statement with python pandas dataframe isna() function?
I'm new to working with pandas dataframes and was trying to figure out a way to locate NaN values inside a cell of a dataframe. I'm using an if condition with isna() function.

My approach is that if the value is NaN, print "value empty" instead of returning a Boolean "True". This is my approach:

```<code>import pandas as pd

x= pd.read_csv("mdata_short.csv", header =[0])
print(x["retail_price"].iloc[12:13])
if x["retail_price"].iloc[12:13].isna() == True:
    print("value empty")
</code>```

I expected a "value empty output", but I'm getting an error saying:

"ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."

I tried removing "== True" part in the IF statement, still getting the same error. I did a google search but couldn't find anything related to this issue. I don't understand where I'm going wrong.

Thank you in advance for your help.

答:
There is problem if select by indexing 12:13 get one element Series, so for scalar use Series.item:

```<code>if x["retail_price"].iloc[12:13].isna().item():
    print("value empty")
</code>```

Another solution is convert values to numpy array and select first value:

```<code>if x["retail_price"].iloc[2:3].isna().values[0]:
    print("value empty")
</code>```

Better is select by scalar value for scalar in output:

```<code>if pd.isna(x["retail_price"].iloc[12]):
    print("value empty")
</code>```

Sample:

```<code>x = pd.DataFrame({
    'retail_price': [1,2,np.nan]
})
print (x)
   retail_price
0           1.0
1           2.0
2           NaN

print (x["retail_price"].iloc[2:3].isna())
2    True
Name: retail_price, dtype: bool

print (x["retail_price"].iloc[2:3].isna().item())
True

print (x["retail_price"].iloc[2:3].isna().values[0])
True

print (pd.isna(x["retail_price"].iloc[2]))
True
</code>```

For comparing in boolean Series (same working for one element Series) check Using If/Truth Statements with pandas.

Body:
I'm new to working with pandas dataframes and was trying to figure out a way to locate NaN values inside a cell of a dataframe. I'm using an if condition with isna() function.

My approach is that if the value is NaN, print "value empty" instead of returning a Boolean "True". This is my approach:

import pandas as pd

x= pd.read_csv("mdata_short.csv", header =[0])
print(x["retail_price"].iloc[12:13])
if x["retail_price"].iloc[12:13].isna() == True:
    print("value empty")

I expected a "value empty output", but I'm getting an error saying:

"ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."

I tried removing "== True" part in the IF statement, still getting the same error. I did a google search but couldn't find anything related to this issue. I don't understand where I'm going wrong.

Thank you in advance for your help.

Body:
There is problem if select by indexing 12:13 get one element Series, so for scalar use Series.item:

if x["retail_price"].iloc[12:13].isna().item():
    print("value empty")

Another solution is convert values to numpy array and select first value:

if x["retail_price"].iloc[2:3].isna().values[0]:
    print("value empty")

Better is select by scalar value for scalar in output:

if pd.isna(x["retail_price"].iloc[12]):
    print("value empty")

Sample:

x = pd.DataFrame({
    'retail_price': [1,2,np.nan]
})
print (x)
   retail_price
0           1.0
1           2.0
2           NaN

print (x["retail_price"].iloc[2:3].isna())
2    True
Name: retail_price, dtype: bool

print (x["retail_price"].iloc[2:3].isna().item())
True

print (x["retail_price"].iloc[2:3].isna().values[0])
True

print (pd.isna(x["retail_price"].iloc[2]))
True

For comparing in boolean Series (same working for one element Series) check Using If/Truth Statements with pandas.


问:
Is it possible to use a bean generated from the same class
I'm trying to use a bean generated from the same class. E.g:

public class Test {
  ...

  @Bean
  public Dog dog() {
    ...
    return dog;
  }

  @Bean
  public DogHouse dogHouse() {
    Dog d = dog(); // Is this right? Can I inject dog bean here?
    ...
    return dogHouse;
  }
}
```

Two requirements I got to obey:

Use the result of dog() in dogHouse()

Keep dog() and dogHouse() in the same java class

Is this possible? If it is, how should I inject the dog Bean in Test class? Thanks.

答:
You can use an argument injection to let spring know that the DogHouse bean requires the Dog bean.

```<code>@Bean
public DogHouse dogHouse(Dog d) {
  ...
  return dogHouse;
}
</code>```

Spring will inject the Dog bean into the method while constructing the DogHouse bean.

Body:
I'm trying to use a bean generated from the same class. E.g:

public class Test {
  ...

  @Bean
  public Dog dog() {
    ...
    return dog;
  }

  @Bean
  public DogHouse dogHouse() {
    Dog d = dog(); // Is this right? Can I inject dog bean here?
    ...
    return dogHouse;
  }
}

Two requirements I got to obey:

Use the result of dog() in dogHouse()

Keep dog() and dogHouse() in the same java class

Is this possible? If it is, how should I inject the dog Bean in Test class? Thanks.

Body:
You can use an argument injection to let spring know that the DogHouse bean requires the Dog bean.

@Bean
public DogHouse dogHouse(Dog d) {
  ...
  return dogHouse;
}

Spring will inject the Dog bean into the method while constructing the DogHouse bean.


问:
Bootstrap in sharepoint web part
Does anyone know of a good way to use Bootstrap styles for a SharePoint web part? I don't want to restyle the entire SharePoint site with bootstrap styles. I just want to be able to use bootstrap elements like buttons and forms and modals within a SharePoint web part without interfering with the regular SharePoint styles on the rest of the site. So with that in mind looking at the example below should give a good picture of what I want. Basically I want to reset the styles and then apply bootstrap styling within the div with ID BootstrapContent but everything outside of that div should be unaffected and just use the normal SharePoint styles. Thanks for the help.</p>

```<code><html>
 <body>
  STANDARD SHAREPOINT STYLES
  <div id='BootstrapContent'>
    HTML CONTENT WITH BOOTSTRAP STYLES
  </div>
  STANDARD SHAREPOINT STYLES
 </body>
</html>
</code>```

答:
There's no good way to isolate one part of your html without using iFrames.  If you went that way you could put your html into a doc lib, then call it from an iframe.  That html file would reference bootstrap and only affect the iframe.  You can use the Page Viewer web part to create the iframe for you.

Another option which isn't quite what you are asking, is you could get a cut down (customized) version of bootstrap customized.  If you only need the grid system for example, only get that option.  You might be able to exclude a lot of the generic things that interfere with SP.  However, you'd likely lose things you want.

Title: Bootstrap in sharepoint web part

Body:
Does anyone know of a good way to use Bootstrap styles for a SharePoint web part? I don't want to restyle the entire SharePoint site with bootstrap styles. I just want to be able to use bootstrap elements like buttons and forms and modals within a SharePoint web part without interfering with the regular SharePoint styles on the rest of the site. So with that in mind looking at the example below should give a good picture of what I want. Basically I want to reset the styles and then apply bootstrap styling within the div with ID BootstrapContent but everything outside of that div should be unaffected and just use the normal SharePoint styles. Thanks for the help.

  STANDARD SHAREPOINT STYLES

    HTML CONTENT WITH BOOTSTRAP STYLES

  STANDARD SHAREPOINT STYLES


问:
Accessing Ext Designer JsonStore from another file
I want to access an JsonStore created from the ext designer from another panels user js file.
The file store file generated from the designer looks like this

```<code>myJsonStore = Ext.extend(Ext.data.JsonStore, {
 constructor: function(cfg) {
    cfg = cfg || {};
    CoaJsonStore.superclass.constructor.call(this, Ext.apply({
        storeId: 'myJsonStore',
        url: '/server.json',
        restful: true,
        autoLoad: true,
        autoSave: false,
        fields: [
            {
                name: 'id'
            },
            {
                name: 'code'
            },
            {
                name: 'name'
            }

        ]
    }, cfg));
}
});
new myJsonStore();
</code>```

what i am doing right now is using a hidden combo and assign the store to the combo, this allows me to access it via autoRef (with. combo.getStore(), it gives me an object type of Store). Ideally i want to be able to do it without the hidden combo.

i have tried referring to it with storeId, but it doesn't work, if i log the storeId to the console this is what i get.

```<code> function (cfg) {
    cfg = cfg || {};
    CoaJsonStore.superclass.constructor.call(this, Ext.apply({
        storeId: 'myJsonStore',
        url: '/coas.json',
        restful: true,
........
</code>```

so i was just wondering whether this is even possible. if so some direction on how to get it done would be greatly appreciated . thanks

答:
The new myJsonStore(); only creates a new store. In order to reference the store elsewhere in your code ( same file or another file) you need to use a variable. Create the store like this:

```<code> var myStore = new myJsonStore();
</code>```

And to bind it to the comobobox use the variable name myStore with the store property.

Body:
I want to access an JsonStore created from the ext designer from another panels user js file.
The file store file generated from the designer looks like this

myJsonStore = Ext.extend(Ext.data.JsonStore, {
 constructor: function(cfg) {
    cfg = cfg || {};
    CoaJsonStore.superclass.constructor.call(this, Ext.apply({
        storeId: 'myJsonStore',
        url: '/server.json',
        restful: true,
        autoLoad: true,
        autoSave: false,
        fields: [
            {
                name: 'id'
            },
            {
                name: 'code'
            },
            {
                name: 'name'
            }

        ]
    }, cfg));
}
});
new myJsonStore();

what i am doing right now is using a hidden combo and assign the store to the combo, this allows me to access it via autoRef (with. combo.getStore(), it gives me an object type of Store). Ideally i want to be able to do it without the hidden combo.

i have tried referring to it with storeId, but it doesn't work, if i log the storeId to the console this is what i get.

 function (cfg) {
    cfg = cfg || {};
    CoaJsonStore.superclass.constructor.call(this, Ext.apply({
        storeId: 'myJsonStore',
        url: '/coas.json',
        restful: true,
........

so i was just wondering whether this is even possible. if so some direction on how to get it done would be greatly appreciated . thanks

Body:
The new myJsonStore(); only creates a new store. In order to reference the store elsewhere in your code ( same file or another file) you need to use a variable. Create the store like this:

 var myStore = new myJsonStore();

And to bind it to the comobobox use the variable name myStore with the store property.


问:
onblur disables clicks (outside input and clicking other input) on iOS and Mac Safari also force opens the keypad and it wont close - (Jquery )
I have an input field and a currency formatter jquery function to be called on input onkeyup and onblur/onfocusout of
 the field with data-type="currency"

Using onfocusout or onblur always disables page clicks and keyboard force open and wont close (by clicking anywhere outside the input or another input) in some Browsers on iOS if not all and safari on mac (check my little list for browsers i've tested)

I've tried both onblur and onfocus and none seems to work on iOS safari and chrome . I also tried to bind the input like this . It works fine on other browsers like chrome and Firefox on android, windows, mac etc. i have a short list of browsers and OS affected .

AFFECTED / MISBEHAVE

-iOS 12

 ---Safari

 ---Chrome

 ---Firefox

 ---UC Browser (this one works if i try to close the kepad and i can filing form)

note: almost all browsers on ios and safari on mac')

-Mac

 --Safari

IT WORKS FINE ON

-Android, Windows and Mac

 ---Firefox

 ---Chrome

 ---IE

 ---Edge

I reproduced the exact issue on codepen - link below

https://codepen.io/anon/pen/eaMmzb

Here is my html form

```<code><form>
<label for="price">Price</label>
<input type="text" id="price" name="price" required="required" data-type="currency" >

<br />

<label for="test">test</label>
<input type="text">
</form>
</code>```

And Jquery (version 3.4.1)

```<code>// .format all input with data-type="currency" to currency
$("input[data-type='currency']").on({
    keyup: function() {
      formatCurrency($(this));
    },
    blur: function() {
      formatCurrency($(this), "blur");
    }
});

//.format all input with data-type="currency" to currency

function formatNumber(n) {
  return n.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
} // format number 1000000 to 1,234,567

function formatCurrency(input, blur) {
  var input_currency = ""; //the currency symbol that shows beofore the amount

  var input_val = input.val();
  if (input_val === "") { return; }
  var original_len = input_val.length;
  var caret_pos = input.prop("selectionStart");
  if (input_val.indexOf(".") >= 0) {
    var decimal_pos = input_val.indexOf(".");
    var left_side = input_val.substring(0, decimal_pos);
    var right_side = input_val.substring(decimal_pos);
    left_side = formatNumber(left_side);
    right_side = formatNumber(right_side);
    if (blur === "blur") {
      right_side += "00";
    }
    right_side = right_side.substring(0, 2);
    input_val = input_currency + left_side + "." + right_side;
  } else {
    input_val = formatNumber(input_val);
    input_val = input_currency + input_val;
    if (blur === "blur") {
      input_val += ".00";
    }
  }

  input.val(input_val);
  var updated_len = input_val.length;
  caret_pos = updated_len - original_len + caret_pos;
  input[0].setSelectionRange(caret_pos, caret_pos);
}
</code>```

I expect the input field to format the field immediately onfocusout and onkeyup .

答:
Have you tried just setting the input value on blur, but not setting a selection range? I’d guess that the latter has something to do with the keyboard showing up again. Setting the range might be necessary to get the correct caret position again while the user is typing - but in the blur case there should be no need for that to begin with, right? After blurring/unfocusing the field, there doesn’t need to be a caret set to any position.

So don’t set a selection range in case you are handling the blur event:

```<code>  input.val(input_val);

  if (blur !== "blur") {
    var updated_len = input_val.length;
    caret_pos = updated_len - original_len + caret_pos;
    input[0].setSelectionRange(caret_pos, caret_pos);
  }
}
</code>```

Body:
I have an input field and a currency formatter jquery function to be called on input onkeyup and onblur/onfocusout of
 the field with data-type="currency"

Using onfocusout or onblur always disables page clicks and keyboard force open and wont close (by clicking anywhere outside the input or another input) in some Browsers on iOS if not all and safari on mac (check my little list for browsers i've tested)

I've tried both onblur and onfocus and none seems to work on iOS safari and chrome . I also tried to bind the input like this . It works fine on other browsers like chrome and Firefox on android, windows, mac etc. i have a short list of browsers and OS affected .

AFFECTED / MISBEHAVE

-iOS 12

 ---Safari

 ---Chrome

 ---Firefox

 ---UC Browser (this one works if i try to close the kepad and i can filing form)

note: almost all browsers on ios and safari on mac')

-Mac

 --Safari

IT WORKS FINE ON

-Android, Windows and Mac

 ---Firefox

 ---Chrome

 ---IE

 ---Edge

I reproduced the exact issue on codepen - link below

https://codepen.io/anon/pen/eaMmzb

Here is my html form

<form>
Price
<input type="text" id="price" name="price" required="required" data-type="currency" >

test
<input type="text">
</form>

And Jquery (version 3.4.1)

// .format all input with data-type="currency" to currency
$("input[data-type='currency']").on({
    keyup: function() {
      formatCurrency($(this));
    },
    blur: function() {
      formatCurrency($(this), "blur");
    }
});

//.format all input with data-type="currency" to currency

function formatNumber(n) {
  return n.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
} // format number 1000000 to 1,234,567

function formatCurrency(input, blur) {
  var input_currency = ""; //the currency symbol that shows beofore the amount

  var input_val = input.val();
  if (input_val === "") { return; }
  var original_len = input_val.length;
  var caret_pos = input.prop("selectionStart");
  if (input_val.indexOf(".") >= 0) {
    var decimal_pos = input_val.indexOf(".");
    var left_side = input_val.substring(0, decimal_pos);
    var right_side = input_val.substring(decimal_pos);
    left_side = formatNumber(left_side);
    right_side = formatNumber(right_side);
    if (blur === "blur") {
      right_side += "00";
    }
    right_side = right_side.substring(0, 2);
    input_val = input_currency + left_side + "." + right_side;
  } else {
    input_val = formatNumber(input_val);
    input_val = input_currency + input_val;
    if (blur === "blur") {
      input_val += ".00";
    }
  }

  input.val(input_val);
  var updated_len = input_val.length;
  caret_pos = updated_len - original_len + caret_pos;
  input[0].setSelectionRange(caret_pos, caret_pos);
}

I expect the input field to format the field immediately onfocusout and onkeyup .

Body:
Have you tried just setting the input value on blur, but not setting a selection range? I’d guess that the latter has something to do with the keyboard showing up again. Setting the range might be necessary to get the correct caret position again while the user is typing - but in the blur case there should be no need for that to begin with, right? After blurring/unfocusing the field, there doesn’t need to be a caret set to any position.

So don’t set a selection range in case you are handling the blur event:

  input.val(input_val);

  if (blur !== "blur") {
    var updated_len = input_val.length;
    caret_pos = updated_len - original_len + caret_pos;
    input[0].setSelectionRange(caret_pos, caret_pos);
  }
}


答:
Another example:</p>

```<code>from functools import partial

my_list = ["a", "b", "c", "d", "e", "f", "g"]
my_list_condition = [0, 0, 1, 1, 0, 1, 1]

def find_next(element, element_list, condition_list, backward=False):
    step = -1 if backward else 1
    next_index = element_list.index(element) + step
    length = len(element_list)
    while True:
        if next_index < 0 or next_index >= length:
            next_index = (next_index + length) % length
        if condition_list[next_index]:
            return element_list[next_index]
        next_index += step

find_prev = partial(find_next, backward=True)

print(find_prev("e", my_list, my_list_condition))
# d
print(find_prev("c", my_list, my_list_condition))
# g
print(find_next("e", my_list, my_list_condition))
# f
print(find_next("g", my_list, my_list_condition))
# c
</code>```

Title: Python: find previous and next `True` element in circular list

Body:
What is the best way to find the previous True element given current index in circular list.

For example given the data like these

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
my_list_condition = [0, 0, 1, 1, 0, 1, 1]

Find the previous element

before_e = find_prev('e', my_list, my_list_condition)
# before_e should be 'd'
before_c = find_prev('c', my_list, my_list_condition)
# before_c should be 'g' because it's circular list and the first True element before c is g

Find the next element

after_e = find_next('e', my_list, my_list_condition)
# after_e should output 'f'

after_g = find_next('g', my_list, my_list_condition)
# after_g should output 'c' because it's circular list and the first True element after c is g

Body:
Another example:

from functools import partial

my_list = ["a", "b", "c", "d", "e", "f", "g"]
my_list_condition = [0, 0, 1, 1, 0, 1, 1]

def find_next(element, element_list, condition_list, backward=False):
    step = -1 if backward else 1
    next_index = element_list.index(element) + step
    length = len(element_list)
    while True:
        if next_index < 0 or next_index >= length:
            next_index = (next_index + length) % length
        if condition_list[next_index]:
            return element_list[next_index]
        next_index += step

find_prev = partial(find_next, backward=True)

print(find_prev("e", my_list, my_list_condition))
# d
print(find_prev("c", my_list, my_list_condition))
# g
print(find_next("e", my_list, my_list_condition))
# f
print(find_next("g", my_list, my_list_condition))
# c


问:
Why does an input iterator invalidate itself after incrementing?
I've read that input iterators are used to read in input streams like cin, which can contain something like "abc". If we have two iterators, let's say of typestd::istream_iterator that both point to 'a', and we increment one of them, the other one will become invalidated.

I'm wondering why that's the case. It seems like incrementing one iterator would cause it to read in 'b', but I'm not sure why incrementing the other one wouldn't allow that to work either. I've read that this does happen, but I'm a little confused as to why it's the case. Is it how the input streams are structured, or something else?

答:
InputIterator is not a specific class, it is a concept, which allows efficient implementation of certain constructs. For example, suppose you have a file with lines, max line length is 128 bytes, and you have to provide an iterable interface: with the input iterator concept, you can simply allocate a buffer for a single line, and simply read the next line into this buffer, whenever an input iterator is incremented.

An other example: suppose you have a generator function, which produces the fibonacchi sequence. A BidirectionalIterator based implementation would need to store the generated number somewhere, while an InputIterator based solution can simply ask the generator for the next number, and drop the current one - no additional storage is needed.


问:
Share mongo models across multiple apps
I'm building an app and as it grows, i learn more and grow with it.

At the moment i've split my app into 3 seperate pieces

Web - front end

API  - data

Worker - data processing

each of these seperate nodejs apps have a function to perform while being on different servers.

I started another little package/app that includes shared code and then included it in the dependancies as such :

```<code>"shared": "file:../shared",
</code>```

so that i can access my models from any app whenever i please as such :

```<code>let User = require('shared/models/user')
</code>```

I find my self running the following command to upgrade to latest models while in development mode ALOT

```<code>yarn upgrade shared
</code>```

I'm still learning about best practices and all that...is this really the best way of doing this? Should i be doing something else to save some more time?

Any help would be greatly appreciated!

答:
Sharing the same model across the microservices is not a very good architectural decision. A Microservice should own its models and sharing is the opposite of owning.

This doesn't mean that one cannot have Users in multiple microservices but not the same model. You can use a integration pattern, i.e. Anti-corruption layer. Long-story short, the canonical model contains all the fields but remote models contain only the needed subset of fields.

Title: Share mongo models across multiple apps

Body:
I'm building an app and as it grows, i learn more and grow with it.

At the moment i've split my app into 3 seperate pieces

Web - front end

API  - data

Worker - data processing

each of these seperate nodejs apps have a function to perform while being on different servers.

I started another little package/app that includes shared code and then included it in the dependancies as such :

"shared": "file:../shared",

so that i can access my models from any app whenever i please as such :

let User = require('shared/models/user')

I find my self running the following command to upgrade to latest models while in development mode ALOT

yarn upgrade shared

I'm still learning about best practices and all that...is this really the best way of doing this? Should i be doing something else to save some more time?

Any help would be greatly appreciated!


问:
How to check if all array values are blank in Javascript
I have an array like:

```<code>["", "", "", "1", "", ""]
</code>```

I want to alert when all the array values are blanks, i.e, when the array is like this:

```<code>["", "", "", "", "", ""]
</code>```

How can I achieve this.

答:
function isEmpty (arr){
  return arr.every(e => e === "")
};
let a = ["", "", "", "1", "", ""];
let b = ["", "", "", "", "", ""]
console.log(isEmpty(a));
console.log(isEmpty(b));```

Body:
I have an array like:

["", "", "", "1", "", ""]

I want to alert when all the array values are blanks, i.e, when the array is like this:

["", "", "", "", "", ""]

How can I achieve this.


问:
Wheelchair accessibility in Directions API
I'd like to retrieve directions for wheelchair-bound users, allowing me to provide wheelchair accessible routes. My Google Maps app allows this, but there's nothing about it in the API documentation.
Does the Directions API support this? If not, how do Google Maps do it?</p>

答:
Currently, this feature is not available in Google Maps API. If you would like this feature to be added, you may file a Feature Request in our public issue tracker to include this feature in the Directions API.

Issue Tracker is a tool used internally at Google to track bugs and feature requests during product development.[5] It is available outside of Google for use by external public and partner users who need to collaborate with Google teams on specific projects. You can learn more here [1].

[1] https://developers.google.com/issue-tracker/


问:
How to sum columns without using Loop in VBA
I am trying to reformat a report so it can feed into my system like below:

```<code>wbOutput.Sheets(1).Range("B" & O_lrow + 1 & ":B" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("F1:F" & lRow).Value
</code>```

One issue I encounter is column F needs to be the sum of two source column and below doesn't work:

```<code>wbOutput.Sheets(1).Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("N1:N" & lRow).Value + wbSource.Sheets(1).Range("O1:O" & lRow).Value
</code>```

I am trying to avoid using loop as there are many rows and I don't want the marco slow down too much.

Is there any simple way to achieve this without using a loop?

答:
This is a way, using the Application.Sum function:

```<code>Option Explicit
Sub SumTest()

    Dim SumA As Range
    Dim SumB As Range

    With wbSource.Sheets(1)
        Set SumA = .Range("N1:N" & lRow)
        Set SumB = .Range("O1:O" & lRow)
    End With

    wbOutput.Sheets(1).Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow) = Application.Sum(SumA, SumB)

End Sub
</code>```

Body:
I am trying to reformat a report so it can feed into my system like below:

wbOutput.Sheets(1).Range("B" & O_lrow + 1 & ":B" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("F1:F" & lRow).Value

One issue I encounter is column F needs to be the sum of two source column and below doesn't work:

wbOutput.Sheets(1).Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("N1:N" & lRow).Value + wbSource.Sheets(1).Range("O1:O" & lRow).Value

I am trying to avoid using loop as there are many rows and I don't want the marco slow down too much.

Is there any simple way to achieve this without using a loop?

Body:
This is a way, using the Application.Sum function:

Option Explicit
Sub SumTest()

    Dim SumA As Range
    Dim SumB As Range

    With wbSource.Sheets(1)
        Set SumA = .Range("N1:N" & lRow)
        Set SumB = .Range("O1:O" & lRow)
    End With

    wbOutput.Sheets(1).Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow) = Application.Sum(SumA, SumB)

End Sub


问:
Left JOIN issuedevices AS sm ON sd.DeviceID = sm.DeviceID' at line 1
I want to take data from two tables.

Table one deviceadd has these columns

```<code>DeviceID (primary key), DeviceName, SerialNumber, ModelNumber, Make
</code>```

and the other table issuedevices has these columns:

```<code>Device_ID (Unique), Employee_id, Employee_Name, Employee_Ext, Issue_Date
</code>```

I get this error:

java.sql.SQLSyntaxErrorException: You have an error in your SQL
  syntax; check the manual that corresponds to your MariaDB server
  version for the right syntax to use near 'Left JOIN issuedevices AS sm
  ON sd.DeviceID = sm.DeviceID' at line 1

```<code>PreparedStatement ps=con.prepareStatement("Selectsd.DeviceID,sd.DeviceName,sd.SerialNumber,sd.ModelNumber,sd.Make,sm.DeviceID,sm.Employee_Name,sm.Employee_Ext,sm.Issue_Date From deviceadd AS sd,Left JOIN issuedevices AS sm ON sd.DeviceID = sm.DeviceID");

        ResultSet rs=ps.executeQuery();

        ResultSetMetaData rsmd=rs.getMetaData();
        int cols=rsmd.getColumnCount();
        column=new String[cols];
        for(int i=1;i<=cols;i++)
        {
            column[i-1]=rsmd.getColumnName(i);
        }

        rs.last();
        int rows=rs.getRow();
        rs.beforeFirst();

        data=new String[rows][cols];
        int count=0;
        while(rs.next()){
            for(int i=1;i<=cols;i++)
            {
                data[count][i-1]=rs.getString(i);
            }
            count++;
        }
        con.close();
    }catch(Exception e){System.out.println(e);}

    table = new JTable(data,column);
    JScrollPane sp=new JScrollPane(table);

    contentPane.add(sp, BorderLayout.CENTER);
</code>```

答:
One possible reason is that there is no space here:

```<code>Selectsd.DeviceID
</code>```

It should be

```<code>Select sd.DeviceID
</code>```

Also, there shouldn't be a comma here:

```<code>sd,Left JOIN
</code>```

Body:
I want to take data from two tables.

Table one deviceadd has these columns

DeviceID (primary key), DeviceName, SerialNumber, ModelNumber, Make

and the other table issuedevices has these columns:

Device_ID (Unique), Employee_id, Employee_Name, Employee_Ext, Issue_Date

I get this error:

java.sql.SQLSyntaxErrorException: You have an error in your SQL
  syntax; check the manual that corresponds to your MariaDB server
  version for the right syntax to use near 'Left JOIN issuedevices AS sm
  ON sd.DeviceID = sm.DeviceID' at line 1

PreparedStatement ps=con.prepareStatement("Selectsd.DeviceID,sd.DeviceName,sd.SerialNumber,sd.ModelNumber,sd.Make,sm.DeviceID,sm.Employee_Name,sm.Employee_Ext,sm.Issue_Date From deviceadd AS sd,Left JOIN issuedevices AS sm ON sd.DeviceID = sm.DeviceID");

        ResultSet rs=ps.executeQuery();

        ResultSetMetaData rsmd=rs.getMetaData();
        int cols=rsmd.getColumnCount();
        column=new String[cols];
        for(int i=1;i<=cols;i++)
        {
            column[i-1]=rsmd.getColumnName(i);
        }

        rs.last();
        int rows=rs.getRow();
        rs.beforeFirst();

        data=new String[rows][cols];
        int count=0;
        while(rs.next()){
            for(int i=1;i<=cols;i++)
            {
                data[count][i-1]=rs.getString(i);
            }
            count++;
        }
        con.close();
    }catch(Exception e){System.out.println(e);}

    table = new JTable(data,column);
    JScrollPane sp=new JScrollPane(table);

    contentPane.add(sp, BorderLayout.CENTER);

Body:
One possible reason is that there is no space here:

Selectsd.DeviceID

It should be

Select sd.DeviceID

Also, there shouldn't be a comma here:

sd,Left JOIN


问:
How to add custom PHP files in Typo3 9 LTS
I want to show advanced search page which includes PHP, HTML and CSS code. Its work is to get User inputs and process/execute a query to get results from Oracle DB. There are multiple PHP files which are linked to each other and index.php is root point. All custom files are in a folder named "prod". So the problem is I want to redirect to index.php after User login in Typo3 9 LTS CMS. But do not know how to achieve this. Please help me what is the best and easy way to do this in Typo3 9 LTS version. Is there any extension which can help me. And which files I have to configure to achieve this. I am using Fluid template extension.</p>

答:
As this are individual PHP scripts unrelated to TYPO3 you can consider them external pages to TYPO3. if you want to have a link inside of your installation to that pages use a page with type Link to External URL. After FE-login you can forward to this TYPO3 page, which redirects to the external URL.

Be aware that the external script (your script) has no login validation from TYPO3 and that the URL, once known, can be called without a login.


问:
Making a folder directory from a text file using a python script
I have a text file with hundreds of lines, each line contains a number to represent the level the folder/file should be on and a folder/file name. Because the  hierarchy is too large I want to make a script to automate making this directory/sub directory.

Example text file

```<code> .0.  Folder Name a
  .1. Folder Name b
   .2. Folder Name c
   .2. Folder Name c2
  .1. Folder Name d
   .2. Folder Name e
   .2. Folder Name e2
    .3. Folder Name f
</code>```

I assume I need to read line by line and use os.mkdir, but I don't know how to step down a directory level.

```<code>#path of file
import os

with open('Tree.txt', 'r') as t:
 for line in t:
  readline(.{Level}. {FolderName})
    if Level == '0'
     os.mkdir(FolderName)
    else if Level == '1'
     # go down and os.mkdir(FolderName)
</code>```

答:
You can use os.mkdir(path) to create a directory.

You can also use the following regex to parse your string:

```<code>"\.(\d+)\. Folder Name ([a-zA-Z\d]+)"
</code>```

Then you can use recursion to create the directory tree:

```<code>import os
import re

regex = r"\.([\d+])\. Folder Name ([a-zA-Z\d]+)"

def create_dir_tree(dir_list, current_level, current_path):
    for idx, line in enumerate(dir_list):
        matcher = re.match(regex, line)
        if not matcher:
            return
        level = int(matcher.group(1))
        dir_name = matcher.group(2)

        if level <= current_level:
            return
        if level != current_level + 1:
            continue

        new_path = os.path.join(current_path, dir_name)
        os.mkdir(new_path)

        create_dir_tree(dir_list[idx + 1:], level, new_path)

list = [".0. Folder Name a",
        ".1. Folder Name b",
        ".2. Folder Name c",
        ".2. Folder Name c2",
        ".1. Folder Name d",
        ".2. Folder Name e",
        ".2. Folder Name e2",
        ".3. Folder Name f"]

create_dir_tree(list, -1, os.path.expanduser("~/Desktop/untitled folder"))
</code>```

Now it's only a matter of reading the file to a list

Body:
I have a text file with hundreds of lines, each line contains a number to represent the level the folder/file should be on and a folder/file name. Because the  hierarchy is too large I want to make a script to automate making this directory/sub directory.

Example text file

 .0.  Folder Name a
  .1. Folder Name b
   .2. Folder Name c
   .2. Folder Name c2
  .1. Folder Name d
   .2. Folder Name e
   .2. Folder Name e2
    .3. Folder Name f

I assume I need to read line by line and use os.mkdir, but I don't know how to step down a directory level.

#path of file
import os

with open('Tree.txt', 'r') as t:
 for line in t:
  readline(.{Level}. {FolderName})
    if Level == '0'
     os.mkdir(FolderName)
    else if Level == '1'
     # go down and os.mkdir(FolderName)

Body:
You can use os.mkdir(path) to create a directory.

You can also use the following regex to parse your string:

"\.(\d+)\. Folder Name ([a-zA-Z\d]+)"

Then you can use recursion to create the directory tree:

import os
import re

regex = r"\.([\d+])\. Folder Name ([a-zA-Z\d]+)"

def create_dir_tree(dir_list, current_level, current_path):
    for idx, line in enumerate(dir_list):
        matcher = re.match(regex, line)
        if not matcher:
            return
        level = int(matcher.group(1))
        dir_name = matcher.group(2)

        if level <= current_level:
            return
        if level != current_level + 1:
            continue

        new_path = os.path.join(current_path, dir_name)
        os.mkdir(new_path)

        create_dir_tree(dir_list[idx + 1:], level, new_path)

list = [".0. Folder Name a",
        ".1. Folder Name b",
        ".2. Folder Name c",
        ".2. Folder Name c2",
        ".1. Folder Name d",
        ".2. Folder Name e",
        ".2. Folder Name e2",
        ".3. Folder Name f"]

create_dir_tree(list, -1, os.path.expanduser("~/Desktop/untitled folder"))

Now it's only a matter of reading the file to a list


问:
Pre-order to post-order traversal
If the pre-order traversal of a binary search tree is 6, 2, 1, 4, 3, 7, 10, 9, 11, how to get the post-order traversal?</p>

答:
Here is full code )</p>

```<code>class Tree:
    def __init__(self, data = None):
        self.left = None
        self.right = None
        self.data = data

    def add(self, data):
        if self.data is None:
            self.data = data
        else:
            if data < self.data:
                if self.left is None:
                    self.left = Tree(data)
                else:
                    self.left.add(data)
            elif data > self.data:
                if self.right is None:
                    self.right = Tree(data)
                else:
                    self.right.add(data)
    def inOrder(self):
        if self.data:
            if self.left is not None:
                self.left.inOrder()
            print(self.data)
            if self.right is not None:
                self.right.inOrder()

    def postOrder(self):
        if self.data:
            if self.left is not None:
                self.left.postOrder()
            if self.right is not None:
                self.right.postOrder()
            print(self.data)

    def preOrder(self):
        if self.data:
            print(self.data)
            if self.left is not None:
                self.left.preOrder()
            if self.right is not None:
                self.right.preOrder()
arr = [6, 2, 1, 4, 3, 7, 10, 9, 11]
root = Tree()
for i in range(len(arr)):
    root.add(arr[i])
print(root.inOrder())
</code>```

ContentLicense: CC BY-SA 2.5

Title: Pre-order to post-order traversal

Body:
Here is full code )

class Tree:
    def __init__(self, data = None):
        self.left = None
        self.right = None
        self.data = data

    def add(self, data):
        if self.data is None:
            self.data = data
        else:
            if data < self.data:
                if self.left is None:
                    self.left = Tree(data)
                else:
                    self.left.add(data)
            elif data > self.data:
                if self.right is None:
                    self.right = Tree(data)
                else:
                    self.right.add(data)
    def inOrder(self):
        if self.data:
            if self.left is not None:
                self.left.inOrder()
            print(self.data)
            if self.right is not None:
                self.right.inOrder()

    def postOrder(self):
        if self.data:
            if self.left is not None:
                self.left.postOrder()
            if self.right is not None:
                self.right.postOrder()
            print(self.data)

    def preOrder(self):
        if self.data:
            print(self.data)
            if self.left is not None:
                self.left.preOrder()
            if self.right is not None:
                self.right.preOrder()
arr = [6, 2, 1, 4, 3, 7, 10, 9, 11]
root = Tree()
for i in range(len(arr)):
    root.add(arr[i])
print(root.inOrder())


问:
How to set TextInputLayout error message colour?
How can I change the colour of the error message that can be set to appear below the text field in a TextInputLayout (via setError(...) – see error state here)?

It normally shows as a red colour, which I want to change. Which item names/keys should I use in my styles.xml file to target the colour?

**Edit:**

Added app:errorTextAppearance key to my TextInputLayout:

```<code><android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:id="@+id/welcome_current_week_container"
        app:errorTextAppearance="@style/WelcomeErrorAppearance">
        <EditText
            ..../>
    </android.support.design.widget.TextInputLayout>
</LinearLayout>
</code>```

and the error appearance (set to green for testing):

```<code><style name="WelcomeErrorAppearance" parent="@android:style/TextAppearance">
    <item name="android:textColor">@android:color/holo_green_dark</item>
</style>
</code>```

The result is that the hint as well as the error message is coloured (screenshots from scaled Android Emulator):

Regular (no error):

Error state:

Edit 2/Outcome:

When the error message appears, the hint above the field changes to the same colour as the error message, overriding hint colour – this is by design.

答:
If you are using com.google.android.material.textfield.TextInputLayout this input layout than you just set one style

```<code><com.google.android.material.textfield.TextInputLayout
                        android:id="@+id/textInputLayoutPassword"
                        style="@style/LoginTextInputLayoutStyle"

<style name="LoginTextInputLayoutStyle" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">
        <item name="boxStrokeColor">@color/text_input_box</item>
        <item name="errorTextColor">@color/colorRed</item>
    </style>
</code>```

Body:
How can I change the colour of the error message that can be set to appear below the text field in a TextInputLayout (via setError(...) – see error state here)?

It normally shows as a red colour, which I want to change. Which item names/keys should I use in my styles.xml file to target the colour?

**Edit:**

Added app:errorTextAppearance key to my TextInputLayout:

<android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:id="@+id/welcome_current_week_container"
        app:errorTextAppearance="@style/WelcomeErrorAppearance">
        <EditText
            ..../>
    </android.support.design.widget.TextInputLayout>
</LinearLayout>

and the error appearance (set to green for testing):

The result is that the hint as well as the error message is coloured (screenshots from scaled Android Emulator):

Regular (no error):

Error state:

Edit 2/Outcome:

When the error message appears, the hint above the field changes to the same colour as the error message, overriding hint colour – this is by design.

Body:
If you are using com.google.android.material.textfield.TextInputLayout this input layout than you just set one style

<com.google.android.material.textfield.TextInputLayout
                        android:id="@+id/textInputLayoutPassword"
                        style="@style/LoginTextInputLayoutStyle"

<style name="LoginTextInputLayoutStyle" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">
        <item name="boxStrokeColor">@color/text_input_box</item>
        <item name="errorTextColor">@color/colorRed</item>
    </style>


问:
Remove the Open and close brackets from the string
I want to remove the [ ] brackets from list1 variable in python

```<code>list1 = ['Order No','Item']
</code>```

Expected :

```<code>>>> print (list1)
'Order No', 'Item'
</code>```

Actual :

```<code>>>> print (list1)
['Order No', 'Item']
</code>```

答:
Try:

```<code>for i in list1:
 print("'" + i + "'")
</code>```

if you don't want the braces:

```<code>for i in list1:
 print(i)
</code>```

Body:
I want to remove the [ ] brackets from list1 variable in python

list1 = ['Order No','Item']

Expected :

>>> print (list1)
'Order No', 'Item'

Actual :

>>> print (list1)
['Order No', 'Item']

Body:
Try:

for i in list1:
 print("'" + i + "'")

if you don't want the braces:

for i in list1:
 print(i)


问:
How do you minimize the performance hit when upgrading to EF 4.1 from LINQ to SQL?
I recently updated an app with LINQ to SQL and SQL Server CE 3.5 to Entity Framework 4.1 Code First and SQL Server CE 4.0, and it's now running noticeably slower. I did some before vs. after stopwatch testing, and most major operations of my app appear to be running about 40% slower on average.

I'm using all default strategies and configurations for EF Code First except for disabling cascading deletes.

When I originally posted this question, I was focused on one query that seemed to be taking particularly long, but I've since realized that it was only particularly slow on first run (see the comment thread below).

What I now think I'm seeing is that most queries are running slower--not dramatically slower, but slow enough to quickly add up as most operations the app performs involve several queries.

This app has a very small database. The SQL CE (.sdf) file is only 458 KB, and the largest table has less than 250 records.

Here's an example POCO class:

```<code>public class Target
{
    public int Id { get; set; }
    public int TrialDefinitionId { get; set; }
    public int Number { get; set; }
    public int X { get; set; }
    public int Y { get; set; }
    public string Phase { get; set; }
    public virtual TrialDefinition TrialDefinition { get; set; }
}
</code>```

All my classes follow this basic pattern (simple types + virtual properties to obtain objects linked by foreign keys). I have one class that uses an ICollection to obtain a listing for a many-to-one relationship.

Final note: I'm using a repository pattern as a mediator, and each usage of a repository is placed in a using block. For "get" operations, this results in entities becoming detached once I've obtained the data I need from the database.

Does anyone have any specific strategies for improving the performance of my EF Code First app? Please keep in mind that I haven't had a chance yet to read up on EF in much detail. I'm mostly just trying to migrate as quickly and painlessly as possible from LINQ to SQL to EF. The most useful answer for me would be one that consists of changing specific strategies or configurations or other settings.

答:
Final note: I'm using a repository pattern as a mediator, and each usage of a repository is placed in a using block. For "get" operations, this results in entities becoming detached once I've obtained the data I need from the database.

Well this is not required...

Entity Framework's default architecture already implements repository pattern.

Keeping ObjectContext alive does not mean you are keeping your connection to database alive.

Only when you are loading from or saving changes to database, a new connection from connection pool is grabbed and operation is performed.

Ofcourse, using block will slow down because each using block will do following,

Initialize Context (requires loading metadata from resources)

Validate few things

Open connection to DB

Perform your tasks

Clean up and close DB

Now first two steps sure will take lot of time, and you will have multiple objects of same type living longer in your app because each new context will create a new copy of same object for every query.

Entity Framework already implements Identity Map, that means that it will keep the object alive and only one copy of object for same primary key throughout the lifetime of context, that will not only save memory but will also perform faster.

I would advise to not use Using blocks for every query or smaller steps but rather, you should keep your ObjectContext alive throughout lifetime of your application. And you do not need to implement caching or repository at all.

Body:
I recently updated an app with LINQ to SQL and SQL Server CE 3.5 to Entity Framework 4.1 Code First and SQL Server CE 4.0, and it's now running noticeably slower. I did some before vs. after stopwatch testing, and most major operations of my app appear to be running about 40% slower on average.

I'm using all default strategies and configurations for EF Code First except for disabling cascading deletes.

When I originally posted this question, I was focused on one query that seemed to be taking particularly long, but I've since realized that it was only particularly slow on first run (see the comment thread below).

What I now think I'm seeing is that most queries are running slower--not dramatically slower, but slow enough to quickly add up as most operations the app performs involve several queries.

This app has a very small database. The SQL CE (.sdf) file is only 458 KB, and the largest table has less than 250 records.

Here's an example POCO class:

public class Target
{
    public int Id { get; set; }
    public int TrialDefinitionId { get; set; }
    public int Number { get; set; }
    public int X { get; set; }
    public int Y { get; set; }
    public string Phase { get; set; }
    public virtual TrialDefinition TrialDefinition { get; set; }
}

All my classes follow this basic pattern (simple types + virtual properties to obtain objects linked by foreign keys). I have one class that uses an ICollection to obtain a listing for a many-to-one relationship.

Final note: I'm using a repository pattern as a mediator, and each usage of a repository is placed in a using block. For "get" operations, this results in entities becoming detached once I've obtained the data I need from the database.

Does anyone have any specific strategies for improving the performance of my EF Code First app? Please keep in mind that I haven't had a chance yet to read up on EF in much detail. I'm mostly just trying to migrate as quickly and painlessly as possible from LINQ to SQL to EF. The most useful answer for me would be one that consists of changing specific strategies or configurations or other settings.


问:
How do I capture a single image from webcam and process it further in OpenCV?
I want my code to capture a single image from webcam and process it further, like later detect colours and sobel edges and a lot more.
In short, I want to do image acquisition.</p>

答:
```<code>import cv2
cap = cv2.VideoCapture(0) # Usually if u have only 1 camera, then it's 0, if u have multiple camera then it's may be 0,1,2 ...
ret, frame = cap.read() # ret is True or False status which shows if you are success reading frame from web cam, frame is an array
# If u want to loop to read continously
ret = True
while ret:
    ret, frame = cap.read()
    if frame is None:
        continue # this will stop the loop if we failed to read frame, because ret will be False
</code>```

If this is the answer that u wanted, then it have been asked multiple times. Make sure you have tried to search the answer before you asked

Body:
import cv2
cap = cv2.VideoCapture(0) # Usually if u have only 1 camera, then it's 0, if u have multiple camera then it's may be 0,1,2 ...
ret, frame = cap.read() # ret is True or False status which shows if you are success reading frame from web cam, frame is an array
# If u want to loop to read continously
ret = True
while ret:
    ret, frame = cap.read()
    if frame is None:
        continue # this will stop the loop if we failed to read frame, because ret will be False

If this is the answer that u wanted, then it have been asked multiple times. Make sure you have tried to search the answer before you asked


问:
array is returning null and crashing
I have an array of objects in a class and trying to reference that array to a UIPickerView, but when the UITextField is tapped it crashes and comes back nil. When tapped on the countryInput text field it should show a pickerview with "Monaco, Japan" and so on...Any ideas on what I'm doing wrong? thank you in advance.

```<code>class SelectionViewController: UIViewController {

var lifeArr : [LifeClass] = []

let picker = UIPickerView()

    override func viewDidLoad() {
    super.viewDidLoad()

    let Monaco = LifeClass()
    Monaco.country = "Monaco"
    Monaco.male = 85.6
    Monaco.female = 93.5

    let Japan = LifeClass()
    Japan.country = "Japan"
    Japan.male = 81.9
    Japan.female = 88.8

    lifeArr = [Monaco, Japan]
  }

}

class SetupViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

@IBOutlet weak var birthDayInput: UITextField!
@IBOutlet weak var countryInput: UITextField!

var selectionData : SelectionViewController!
var picker = UIPickerView()

    override func viewDidLoad() {
    super.viewDidLoad()

        picker.dataSource = self
        picker.delegate = self

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return selectionData.lifeArr.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return selectionData.lifeArr[row].country
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    countryInput.text = selectionData.lifeArr[row].country
}

}
</code>```

答:
You just declare selectionData but not instantiateViewController that's why it's happening.

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    selectionData = self.storyboard?.instantiateViewController(withIdentifier: "SelectionViewController") as! SelectionViewController
    picker.dataSource = self
    picker.delegate = self
}
</code>```

Title: array is returning null and crashing

Body:
I have an array of objects in a class and trying to reference that array to a UIPickerView, but when the UITextField is tapped it crashes and comes back nil. When tapped on the countryInput text field it should show a pickerview with "Monaco, Japan" and so on...Any ideas on what I'm doing wrong? thank you in advance.

class SelectionViewController: UIViewController {

var lifeArr : [LifeClass] = []

let picker = UIPickerView()

    override func viewDidLoad() {
    super.viewDidLoad()

    let Monaco = LifeClass()
    Monaco.country = "Monaco"
    Monaco.male = 85.6
    Monaco.female = 93.5

    let Japan = LifeClass()
    Japan.country = "Japan"
    Japan.male = 81.9
    Japan.female = 88.8

    lifeArr = [Monaco, Japan]
  }

}

class SetupViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

@IBOutlet weak var birthDayInput: UITextField!
@IBOutlet weak var countryInput: UITextField!

var selectionData : SelectionViewController!
var picker = UIPickerView()

    override func viewDidLoad() {
    super.viewDidLoad()

        picker.dataSource = self
        picker.delegate = self

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return selectionData.lifeArr.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return selectionData.lifeArr[row].country
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    countryInput.text = selectionData.lifeArr[row].country
}

}

Body:
You just declare selectionData but not instantiateViewController that's why it's happening.

override func viewDidLoad() {
    super.viewDidLoad()
    selectionData = self.storyboard?.instantiateViewController(withIdentifier: "SelectionViewController") as! SelectionViewController
    picker.dataSource = self
    picker.delegate = self
}


问:
Getting maximum of multiple arrays in amibroker
I am trying to get the maximum of 6 amibroker arrays A, B, C, D, E, F.

Below is my code;

```<code>maximum = Max(Max(A, B), Max(C, D) );
maximum = Max(Max(maximum, E), F);
</code>```

I find the code somewhat ugly.
What are some other ways to code this?

I am using Amibroker ver6.3

答:
You may have a look at Highest (if you need the highest value in the whole array), HighestSince (if you need the highest since a certain condition) or HHV (if you need the highest value in x bars).</p>

```<code>MaxA = Highest(A);
MaxB = Highest(B);
MaxC = Highest(C);
MaxD = Highest(D);
MaxE = Highest(E);
MaxF = Highest(F);
Max = Max(MaxA,Max(MaxB,Max(MaxC,Max(MaxD,Max(MaxE, MaxF)))));
</code>```

Body:
I am trying to get the maximum of 6 amibroker arrays A, B, C, D, E, F.

Below is my code;

maximum = Max(Max(A, B), Max(C, D) );
maximum = Max(Max(maximum, E), F);

I find the code somewhat ugly.
What are some other ways to code this?

I am using Amibroker ver6.3

Body:
You may have a look at Highest (if you need the highest value in the whole array), HighestSince (if you need the highest since a certain condition) or HHV (if you need the highest value in x bars).

MaxA = Highest(A);
MaxB = Highest(B);
MaxC = Highest(C);
MaxD = Highest(D);
MaxE = Highest(E);
MaxF = Highest(F);
Max = Max(MaxA,Max(MaxB,Max(MaxC,Max(MaxD,Max(MaxE, MaxF)))));


问:
How do I get the rendered content of a post created with Divi in wordpress
I have a wordpress site and the Divi plugin used to create pages with the visual editor. I am developing a plugin that needs to get the content of some pages. I know that the page content created with Divi is stored on the database with shortcodes.

When I access the page content using wordpress functions I get the content full of shortcodes, but whenever you open the page built with Divi we can see the rendered HTML generated by these shortcodes. I want to be able to render the pages as rendered when you visit the site. I do not want to strip the shortcodes of the post.

Is there a wordpress function that renders the content as rendered when you open the page or is there a Divi function that already does it that I can use?

I already tried using both methods

```<code>$post = get_post(1);

//Method 1
echo do_shortcode( $post->post_content) ;

//Method 2
echo apply_filters('the_content', $post->post_content);
</code>```

but none of these rendered the Divi shortcodes to html.

答:
Try to use something like this</p>

```<code>$content = apply_filters( 'the_content', get_the_content() );
</code>```

Body:
I have a wordpress site and the Divi plugin used to create pages with the visual editor. I am developing a plugin that needs to get the content of some pages. I know that the page content created with Divi is stored on the database with shortcodes.

When I access the page content using wordpress functions I get the content full of shortcodes, but whenever you open the page built with Divi we can see the rendered HTML generated by these shortcodes. I want to be able to render the pages as rendered when you visit the site. I do not want to strip the shortcodes of the post.

Is there a wordpress function that renders the content as rendered when you open the page or is there a Divi function that already does it that I can use?

I already tried using both methods

$post = get_post(1);

//Method 1
echo do_shortcode( $post->post_content) ;

//Method 2
echo apply_filters('the_content', $post->post_content);

but none of these rendered the Divi shortcodes to html.

Body:
Try to use something like this

$content = apply_filters( 'the_content', get_the_content() );


问:
Kendo Grid MVC Open Context Menu on Left Click
I am using MVC Kendo Grid. First column has an icon which opens a right click context menu.  I want to left click this icon and open a context menu / menu.

Please note on individual row I want to perform some operation when selecting some operation.

答: You can specify the event to show the context menu: .ShowOn("click"). See https://docs.telerik.com/aspnet-mvc/api/Kendo.Mvc.UI.Fluent/ContextMenuBuilder#showonsystemstring for documentation and https://docs.telerik.com/kendo-ui/api/javascript/ui/contextmenu/configuration/showon for an example.


问:
How to stop default link click behavior with jQuery
I have a link on a web page.  When a user clicks it, a widget on the page should update.  However, I am doing something, because the default functionality (navigating to a different page) occurs before the event fires.

This is what the link looks like:

```<code><a href="store/cart/" class="update-cart">Update Cart</a>
</code>```

This is what the jQuery looks like:

```<code>$('.update-cart').click(function(e) {
  e.stopPropagation();
  updateCartWidget();
});
</code>```

What is the problem?

答:
You want e.preventDefault() to prevent the default functionality from occurring.

Or have return false from your method.

preventDefault prevents the default functionality and stopPropagation prevents the event from bubbling up to container elements.

Body:
I have a link on a web page.  When a user clicks it, a widget on the page should update.  However, I am doing something, because the default functionality (navigating to a different page) occurs before the event fires.

This is what the link looks like:

Update Cart

This is what the jQuery looks like:

$('.update-cart').click(function(e) {
  e.stopPropagation();
  updateCartWidget();
});

What is the problem?