问:
ButterKnife Bind not found after migrating to AndroidX
After migrating to AndroidX, I updated ButterKnife to latest version 10.2.0

But when building,

I am getting this error

```<code>error: cannot find symbol class Bind
</code>```

I tried by adding

```<code>compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
</code>```

But it also didn't help.

I saw an answer to make the minSdkVersion at least 15, it is already 16 in my case.

Here is my build.gradle

```<code>
android {
    compileSdkVersion 29
    buildToolsVersion '29.0.2'
    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 12
        versionName "2.2"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        incremental true
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

repositories {
    jcenter()
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    androidTestImplementation('androidx.test.espresso:espresso-core:3.2.0', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

    implementation 'com.valdesekamdem.library:md-toast:0.9.0'
    implementation 'com.jakewharton:butterknife:10.2.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'

    implementation 'androidx.annotation:annotation:1.1.0'
    annotationProcessor 'androidx.annotation:annotation:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'

    implementation 'com.github.badoualy:stepper-indicator:1.0.7'

    testImplementation 'junit:junit:4.12'
}

</code>```

答:
In my case as suggested in this comment I have just added these dependencies in the app-level build.gradle file

```<code>implementation 'com.jakewharton:butterknife:10.2.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'
</code>```

And in project-level build.gradle file declare the following

```<code>allprojects {
    repositories {
        jcenter()
        google()
        maven { url "https://jitpack.io" }
        maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
    }
}
</code>```

Body:
After migrating to AndroidX, I updated ButterKnife to latest version 10.2.0

But when building,

I am getting this error

error: cannot find symbol class Bind

I tried by adding

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}

But it also didn't help.

I saw an answer to make the minSdkVersion at least 15, it is already 16 in my case.

Here is my build.gradle

android {
    compileSdkVersion 29
    buildToolsVersion '29.0.2'
    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 12
        versionName "2.2"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        incremental true
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

repositories {
    jcenter()
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    androidTestImplementation('androidx.test.espresso:espresso-core:3.2.0', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

    implementation 'com.valdesekamdem.library:md-toast:0.9.0'
    implementation 'com.jakewharton:butterknife:10.2.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'

    implementation 'androidx.annotation:annotation:1.1.0'
    annotationProcessor 'androidx.annotation:annotation:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'

    implementation 'com.github.badoualy:stepper-indicator:1.0.7'

    testImplementation 'junit:junit:4.12'
}

Body:
In my case as suggested in this comment I have just added these dependencies in the app-level build.gradle file

implementation 'com.jakewharton:butterknife:10.2.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'

And in project-level build.gradle file declare the following

allprojects {
    repositories {
        jcenter()
        google()
        maven { url "https://jitpack.io" }
        maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
    }
}


来源: stackexchange

问:
Need help (VBA or formula?) returning only specific instances of a partial number string
Background: A 66k+ row Excel table contains all customer ID #'s and business names. Most CID's have 5-8 digits, but a few thousand are from several legacy systems which used leading zeros -one, two, or even three.  So the table has many instances of different clients with extremely similar CID's like 4212, 04212, 004212, etc. In this table to make all clients searchable, the CID's are all stored as text -to keep leading zeros.

Help: I have to create a lookup like below where a user can enter a CID, and a table will populate all similar CIDs and business names. I assume this will be some sort of array formula. It will need to filter out all CIDs that contain the entered CID as only part of the full # (ie: 4212 would NOT return 14212 but would return 4212 and 04212).  I have no idea how to achieve this.  HELP!

答:
If you know the largest length of a CID, then you can filter based on the padded CID. For example, if the largest length were 7 digits such as 1234567, then you could pad three zeros to the left with =TEXT([CID],"000000000") which would produce 0001234567. This technique can be used to force all of your CID's to the same padding.

That can be used as your lookup value in an Excel 365 (or 2021) formula like this:

```<code>=FILTER(F2:F3997,ISNUMBER(FIND(TEXT(B4,"0000000000"),TEXT(F2:F3997,"0000000000"))))
</code>```

that searches for the padded version of B4 within the padded CID#s (cells F2:F3997 in this example).

So, for example, if your CID's were in F2:F3997 and your account names were in G2:G3997, you could put the above formula in your cell C4 and this formula in cell D4:

```<code>=XLOOKUP(C4#,F2:F3997,G2:G3997,,0)
</code>```

Each of these formulas will spill the result below.

I made up account names by simply taking the padded DEC2HEX of the CID
so that I could check the results.

ContentLicense: CC BY-SA 4.0

Body:
If you know the largest length of a CID, then you can filter based on the padded CID. For example, if the largest length were 7 digits such as 1234567, then you could pad three zeros to the left with =TEXT([CID],"000000000") which would produce 0001234567. This technique can be used to force all of your CID's to the same padding.

That can be used as your lookup value in an Excel 365 (or 2021) formula like this:

=FILTER(F2:F3997,ISNUMBER(FIND(TEXT(B4,"0000000000"),TEXT(F2:F3997,"0000000000"))))

that searches for the padded version of B4 within the padded CID#s (cells F2:F3997 in this example).

So, for example, if your CID's were in F2:F3997 and your account names were in G2:G3997, you could put the above formula in your cell C4 and this formula in cell D4:

=XLOOKUP(C4#,F2:F3997,G2:G3997,,0)

Each of these formulas will spill the result below.

I made up account names by simply taking the padded DEC2HEX of the CID
so that I could check the results.


问:
React Uncaught TypeError: canvas.toDataURL is not a function
I'm trying to save my canvas using .toDataURL() but I keep getting the error mentioned in the title.

The canvas and context are initialized as follows:

```<code>const canvas = useRef();
let ctx = null;
</code>```

This is the main function that previews the canvas based on user input:

```<code>const onFinish = () => {
    ctx?.clearRect(0, 0, canvas.width, canvas.height); //to reset canvas after input update
    const canvasEle = canvas.current;
    canvasEle.width = canvasEle.clientWidth;
    canvasEle.height = canvasEle.clientHeight;

    // get context of the canvas
    ctx = canvasEle.getContext("2d");

    //function that writes text on an image
    writeText({
      text: textA,
      x: 350,
      y: 100,
      text2: textB,
      x2: 350,
      y2: 200,
    });

//code breaks here
var dataURL = canvas?.toDataURL();
console.log(dataURL);
};
</code>```

The canvas element is called as follows:

```<code>return(
<>

      <div className="App">
        <h3>Design Ecard</h3>
        <canvas ref={canvas}></canvas>
      </div>
</>

)
</code>```

Update Tried using canvas.current.toDataURL() but that returned the URL of an empty canvas. I can also save the image properly by simply right-clicking and selecting Save Image

Update 2 The writeText function

```<code>const writeText = async (info) => {
    const { text, x, y, text2, x2, y2 } = info;
    var imageObj = new Image();
    imageObj.onload = function () {
      ctx?.drawImage(imageObj, 10, 10);
      ctx?.beginPath();
      ctx.font = fontSize + "px " + fontFamily;
      ctx.textAlign = textAlign;
      ctx.textBaseline = "top";
      ctx.fillStyle = colorCode;
      ctx.fillText(text, x, y);
      ctx.fillText(text2, x2, y2);
      ctx.stroke();
    };
    imageObj.src = bgImage;
    imageObj.width = "600px";
    imageObj.height = "550px";
};
</code>```

答:
useRef gives you a plain object whose reference is stable. If you put something in the ref with ref={canvas}, that value doesn't replace the ref, but gets assigned to a property of the ref.

```<code>var dataURL = canvas?.toDataURL();
</code>```

should be

```<code>const dataURL = canvas.current?.toDataURL();
</code>```

I'd also suggest changing the name of the ref from canvas to canvasRef to avoid confusing yourself - it's a ref that holds the canvas, not the canvas itself.

You also need to wait for the image to load before extracting from the canvas. Either call toDataURL inside writeText, or have writeText return a Promise.

```<code>const writeText = (info) => new Promise((resolve) => {
    const { text, x, y, text2, x2, y2 } = info;
    var imageObj = new Image();
    imageObj.onload = function () {
        ctx?.drawImage(imageObj, 10, 10);
        ctx?.beginPath();
        ctx.font = fontSize + "px " + fontFamily;
        ctx.textAlign = textAlign;
        ctx.textBaseline = "top";
        ctx.fillStyle = colorCode;
        ctx.fillText(text, x, y);
        ctx.fillText(text2, x2, y2);
        ctx.stroke();
        resolve();
    };
    imageObj.src = bgImage;
    imageObj.width = "600px";
    imageObj.height = "550px";
});
</code>```
```<code>writeText({
  // ...
})
  .then(() => {
    var dataURL = canvas?.toDataURL();
    console.log(dataURL);
  });
</code>```

Body:
I'm trying to save my canvas using .toDataURL() but I keep getting the error mentioned in the title.

The canvas and context are initialized as follows:

const canvas = useRef();
let ctx = null;

This is the main function that previews the canvas based on user input:

const onFinish = () => {
    ctx?.clearRect(0, 0, canvas.width, canvas.height); //to reset canvas after input update
    const canvasEle = canvas.current;
    canvasEle.width = canvasEle.clientWidth;
    canvasEle.height = canvasEle.clientHeight;

    // get context of the canvas
    ctx = canvasEle.getContext("2d");

    //function that writes text on an image
    writeText({
      text: textA,
      x: 350,
      y: 100,
      text2: textB,
      x2: 350,
      y2: 200,
    });

//code breaks here
var dataURL = canvas?.toDataURL();
console.log(dataURL);
};

The canvas element is called as follows:

return(
<>

Design Ecard

        <canvas ref={canvas}></canvas>

</>

)

Update Tried using canvas.current.toDataURL() but that returned the URL of an empty canvas. I can also save the image properly by simply right-clicking and selecting Save Image

Update 2 The writeText function

const writeText = async (info) => {
    const { text, x, y, text2, x2, y2 } = info;
    var imageObj = new Image();
    imageObj.onload = function () {
      ctx?.drawImage(imageObj, 10, 10);
      ctx?.beginPath();
      ctx.font = fontSize + "px " + fontFamily;
      ctx.textAlign = textAlign;
      ctx.textBaseline = "top";
      ctx.fillStyle = colorCode;
      ctx.fillText(text, x, y);
      ctx.fillText(text2, x2, y2);
      ctx.stroke();
    };
    imageObj.src = bgImage;
    imageObj.width = "600px";
    imageObj.height = "550px";
};

Body:
useRef gives you a plain object whose reference is stable. If you put something in the ref with ref={canvas}, that value doesn't replace the ref, but gets assigned to a property of the ref.

var dataURL = canvas?.toDataURL();

should be

const dataURL = canvas.current?.toDataURL();

I'd also suggest changing the name of the ref from canvas to canvasRef to avoid confusing yourself - it's a ref that holds the canvas, not the canvas itself.

You also need to wait for the image to load before extracting from the canvas. Either call toDataURL inside writeText, or have writeText return a Promise.

const writeText = (info) => new Promise((resolve) => {
    const { text, x, y, text2, x2, y2 } = info;
    var imageObj = new Image();
    imageObj.onload = function () {
        ctx?.drawImage(imageObj, 10, 10);
        ctx?.beginPath();
        ctx.font = fontSize + "px " + fontFamily;
        ctx.textAlign = textAlign;
        ctx.textBaseline = "top";
        ctx.fillStyle = colorCode;
        ctx.fillText(text, x, y);
        ctx.fillText(text2, x2, y2);
        ctx.stroke();
        resolve();
    };
    imageObj.src = bgImage;
    imageObj.width = "600px";
    imageObj.height = "550px";
});

writeText({
  // ...
})
  .then(() => {
    var dataURL = canvas?.toDataURL();
    console.log(dataURL);
  });


问:
Strange behaviour insert_one mongocxx 3.6
Working with mongocxx I am trying to retrieve the object id assigned by mongodb when I insert a new object in a collection(insert_one method), and convert this id into a string. This is the code:

```<code>  const mongocxx::database& db = _pClient->database(_dbName.c_str());
  mongocxx::collection& collection = db.collection(collectionName.c_str());
  auto retval = collection.insert_one(view);
  bsoncxx::oid oid = retval->inserted_id().get_oid().value;
  std::string str = oid.to_string()
</code>```

Unfortunately it looks like when I try to convert the object id to a string the string is unreadable (corrupted like). I am using mongocxx version 3.4 and mongodb 4.0.28 (the two versions should be compatible according to the mongodb website). Do you know what could be the problem here?

Here what I can see through the debugger: visual studio debugger

Here what I can see thorugh the mongodb client: mongodb client

答:
The debugger is showing you the individual bytes in decimal.

I used the mongo shell to convert these to hex, you can see that it is indeed the ObjectID you were looking for, it just looks strange in decimal

```<code>mongos> [98,3,-24,41,-88,89,0,0,-93,0,88,-78].map(n=>("0" +((n & 255).toString(16))).slice(-2)).join("")
6203e829a8590000a30058b2
</code>```

Body:
Working with mongocxx I am trying to retrieve the object id assigned by mongodb when I insert a new object in a collection(insert_one method), and convert this id into a string. This is the code:

  const mongocxx::database& db = _pClient->database(_dbName.c_str());
  mongocxx::collection& collection = db.collection(collectionName.c_str());
  auto retval = collection.insert_one(view);
  bsoncxx::oid oid = retval->inserted_id().get_oid().value;
  std::string str = oid.to_string()

Unfortunately it looks like when I try to convert the object id to a string the string is unreadable (corrupted like). I am using mongocxx version 3.4 and mongodb 4.0.28 (the two versions should be compatible according to the mongodb website). Do you know what could be the problem here?

Here what I can see through the debugger: visual studio debugger

Here what I can see thorugh the mongodb client: mongodb client

Body:
The debugger is showing you the individual bytes in decimal.

I used the mongo shell to convert these to hex, you can see that it is indeed the ObjectID you were looking for, it just looks strange in decimal

mongos> [98,3,-24,41,-88,89,0,0,-93,0,88,-78].map(n=>("0" +((n & 255).toString(16))).slice(-2)).join("")
6203e829a8590000a30058b2


问:
Get readable text only from clipboard
I already know how to get plain text from the clipboard in Java, but sometimes the text is encoded in some weird DataFlavor, like when copying from Microsoft Word or from a website or even source code from Eclipse.

How to extract pure plain text from these DataFlavors?

答:
```<code>import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

String data = (String) Toolkit.getDefaultToolkit()
                .getSystemClipboard().getData(DataFlavor.stringFlavor);
</code>```

with the getData() Method and the stringFlavor you should get plain text from the clipboard.

If there are weird text in the clipboard, I think, this should be a problem of the program which puts the data in the clipboard.

ContentLicense: CC BY-SA 3.0

Title: Get readable text only from clipboard

Body:
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

String data = (String) Toolkit.getDefaultToolkit()
                .getSystemClipboard().getData(DataFlavor.stringFlavor);

with the getData() Method and the stringFlavor you should get plain text from the clipboard.

If there are weird text in the clipboard, I think, this should be a problem of the program which puts the data in the clipboard.


问:
How do I choose a default React Native debugging tool when I `Open the Dev Tools`
I am using both the Flipper and React Native Debugger on a React Native project.

I find JavaScript logging by React Native Debugger to be much richer given JSON formatting than Flipper (logs dumped as serialized strings). I however love the additional log tooling(especially for native logs) that Flipper provides.

Is it possible to setup choose the default Dev tool?

Opening the dev tools on the iOS simulator, all logs open with Flipper even if it was quit and the React Native Debugger was already open.

I have tried to configure a different port listened to by the debugger and dev tools but a flipper is still given the lead.

Has anyone tried to you both successfully?

答:
Not tried but seems like this article can help you out:

Medium

Already given on React-Native official doc to setup default debugging tool.

If nothing messed up with your local setting then simple disabling can help.


问:
Setting up React environment variables for dev and local
I am new to react and setting up environment variables for my project. Here is what I did..

added .env-cmdrc.json as follows

```<code>{
 "development":{
 "REACT_APP_BASE_URL": "https://servername:port/"
 },
 "staging":{
 "REACT_APP_BASE_URL": "http://servername:port/"
 },
  "local":{
  "REACT_APP_BASE_URL": "http://localhost:port/"
  }
 }
</code>```

installed npm

npm install env-cmd or npm install -g env-cmd

edited package.json as follows:

```<code> "start:development": "env-cmd -e development react-scripts start",
 "start:staging": "env-cmd -e staging react-scripts start",
 "start:local": "env-cmd -e local react-scripts start",
 "build:development": "env-cmd -e development react-scripts build",
 "build:staging": "env-cmd -e staging react-scripts build",
</code>```

tried - npm run start:development

was giving me env-cmd error

again ran

npm install env-cmd

Now tried - npm run start:development

Failed to find .rc file at default paths: [./.env-cmdrc,./.env-cmdrc.js,./.env-cmdrc.json] at getRCFile

I am doing it first time and would appreciate any help..what am I missing here..

答:
I would suggest using dotenv package instead of env-cmd.

install the package - npm i dotenv

Create a environment file in your root directory - .env

Declare a variable - REACT_APP_URL=http://localhost/....

Use the variable - process.env.REACT_APP_URL

In order to start the React application you need to check your package.json file and make sure it contains something like this:

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

If that's in place you can run the following command: npm start

Now you can start coding :)

Body:
I am new to react and setting up environment variables for my project. Here is what I did..

added .env-cmdrc.json as follows

{
 "development":{
 "REACT_APP_BASE_URL": "https://servername:port/"
 },
 "staging":{
 "REACT_APP_BASE_URL": "http://servername:port/"
 },
  "local":{
  "REACT_APP_BASE_URL": "http://localhost:port/"
  }
 }

installed npm

npm install env-cmd or npm install -g env-cmd

edited package.json as follows:

 "start:development": "env-cmd -e development react-scripts start",
 "start:staging": "env-cmd -e staging react-scripts start",
 "start:local": "env-cmd -e local react-scripts start",
 "build:development": "env-cmd -e development react-scripts build",
 "build:staging": "env-cmd -e staging react-scripts build",

tried - npm run start:development

was giving me env-cmd error

again ran

npm install env-cmd

Now tried - npm run start:development

Failed to find .rc file at default paths: [./.env-cmdrc,./.env-cmdrc.js,./.env-cmdrc.json] at getRCFile

I am doing it first time and would appreciate any help..what am I missing here..

Body:
I would suggest using dotenv package instead of env-cmd.

install the package - npm i dotenv

Create a environment file in your root directory - .env

Declare a variable - REACT_APP_URL=http://localhost/....

Use the variable - process.env.REACT_APP_URL

In order to start the React application you need to check your package.json file and make sure it contains something like this:

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

If that's in place you can run the following command: npm start

Now you can start coding :)


问:
How to pass Redux Reducer pointer to React Context?
So in short I am trying to pass a reducer to a context file and have it so that if the state of reducer is updated then I can view that new state in the context file.

Here is my reducer:

```<code>function StillUploadReducer(state = true, action){
switch (action.type){
  case 'stillUpload':
    return action.payloadData

  default:
    return state
  }
}
</code>```

Heres how im passing it to a firebase context file:

```<code>const addData = await firebase.addExercise(
      Data,
      props.StillUploadReducer
    );
</code>```

In the context file i do a console.log of the value and i get the original value passed in. The main issue with this is I want the ability for the user to change the state of the reducer while I await on a video being uploaded so that if the state has changed then it is reflected in the context file.
The user changes the reducer using the action:

```<code>const StillUpload = (dataToPass) => {
  return{
    type: 'stillUpload',
    payloadData: dataToPass,
  }
 }
</code>```

I have console logged the value of the reducer outside the context file and i can see it is being updated I just dont know how to see that change reflected in the context file. Does anyone have any ideas? Thx ahead of time.

答:
A reducer is just a pure function. It has no state, so passing the reducer as an argument to another function cannot achieve what you want.
I'm not sure what you mean by "context file" or what firebase.addExercise does, but you should most likely instead use the useSelector hook which is exactly designed for a component to rerender every time the corresponding part of the state changes.
You should also not use mapStateToProps anymore which is a legacy API for the legacy class components.

Body:
So in short I am trying to pass a reducer to a context file and have it so that if the state of reducer is updated then I can view that new state in the context file.

Here is my reducer:

function StillUploadReducer(state = true, action){
switch (action.type){
  case 'stillUpload':
    return action.payloadData

  default:
    return state
  }
}

Heres how im passing it to a firebase context file:

const addData = await firebase.addExercise(
      Data,
      props.StillUploadReducer
    );

In the context file i do a console.log of the value and i get the original value passed in. The main issue with this is I want the ability for the user to change the state of the reducer while I await on a video being uploaded so that if the state has changed then it is reflected in the context file.
The user changes the reducer using the action:

const StillUpload = (dataToPass) => {
  return{
    type: 'stillUpload',
    payloadData: dataToPass,
  }
 }

I have console logged the value of the reducer outside the context file and i can see it is being updated I just dont know how to see that change reflected in the context file. Does anyone have any ideas? Thx ahead of time.


问:
Is there any equivalent property to ButtonTintList in Xamarin.Forms Android API level 19
In API level 28 I am using BackgroundTintList property,but when using it in Anroid API level 19, getting exception.

Exception Detail:
Java.Lang.NoSuchMethodError: no method with name='setButtonTintList' signature='(Landroid/content/res/ColorStateList;)V' in class Landroid/widget/CompoundButton;

Is there any equivalent property to ButtonTintList in Xamarin.Forms Android API level 19

答:
You could use setColorFilter instead. It is used to specify a color and Porter-Duff mode to be the color filter for this drawable. This method was deprecated in API level 29.

setColorFilter:https://developer.android.com/reference/android/graphics/drawable/Drawable#setColorFilter(int,%20android.graphics.PorterDuff.Mode)


问:
Could not reach Cloud Firestore backend - React native Firebase v9
I saw many questions on SO regarding this issue and none of them was answered (or the solution doesn't work), I don't know why. People are having this error continuously but no solution is being provided. And from past few days even I'm encountering this error (Note: It seems to be working fine on my physical device (not while debugging, it works on only if I release it), but not on android emulator, so I'm pretty sure my internet is working fine):

Setting a timer for a long period of time, i.e. multiple minutes, is a performance and correctness issue on Android as it keeps the timer module awake, and timers can only be called when the app is in the foreground. See https://github.com/facebook/react-native/issues/12981 for more info.
(Saw setTimeout with duration 3052257ms)
Authorization status: 1

[2022-02-09T07:05:26.500Z]  @firebase/firestore: Firestore (9.6.5): Could not reach Cloud Firestore backend. Backend
didn't respond within 10 seconds.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will
operate in offline mode until it is able to successfully connect to the backend.
Authorization status: 1

[2022-02-09T07:08:44.688Z]  @firebase/firestore: Firestore (9.6.5): Connection WebChannel transport errored: me {
  "defaultPrevented": false,
  "g": Y {
    "A": true,
    "J": null,
    "R": [Circular],
    "g": $d {
      "$": true,
      "$a": 2,
      "A": 3,
      "B": null,
      "Ba": 12,
      "C": 0,
      "D": "gsessionid",
      "Da": false,
      "Ea": Dd {
        "g": Cd {},
      },
      ... & so on...
```
<p>Package.json:</p>
<pre class="lang-js prettyprint-override"><code>"@react-native-firebase/app": "^14.3.1",
"@react-native-firebase/messaging": "^14.3.1",
"@react-native-google-signin/google-signin": "^7.0.4",
"expo": "~44.0.0",
"firebase": "^9.6.3",
</code>```

The authentication & messaging seems to be working fine, but I think the db from firestore is having this issue.
Following is some of the code from my firebase.tsx config file:

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: "",
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);

export { auth, db };
```
<p><strong>What I tried so far</strong>:</p>
<ol>
<li><p>Changing the firestore database rules as mentioned in this answer: https://stackoverflow.com/a/70980383/11685381</p>
</li>
<li><p>Using this workaround: https://github.com/firebase/firebase-js-sdk/issues/5667#issuecomment-952079600</p>
</li>
<li><p>I'm not using any <code>.env</code> variables according to this answer: https://stackoverflow.com/a/69095824/11685381</p>
</li>
<li><p>Wiped android emulator data, then Cold Boot. Didn't work.</p>
</li>
<li><p>Upgraded <code>firebase-9.6.3</code> to <code>firebase-9.6.6</code>. Didn't work.</p>
</li>
<li><p>cleaned the build folder, yarn installed all the packages again. Didn't work.</p>
</li>
</ol>
<p>Can anyone provide any working solution to this problem?
Thank you!</p>
<p><strong>EDIT-1</strong>:</p>
<p>The code where I'm calling firestore db especially:</p>
<p>In my HomeScreen.tsx:</p>
<pre class="lang-js prettyprint-override"><code>import { doc, setDoc, onSnapshot, collection } from "firebase/firestore";
import { db } from "../../../firebase";

// inside functional component
useEffect(() => {
    const addUser = () => {
      const path = doc(db, "Users", user.uid);
      const data = {
        _id: user.uid,
        name: user.displayName,
        email: user.email,
      };
      setDoc(path, data)
        .then(() => {
          console.log("User added to db");
        })
        .catch((err) => {
          console.log("Error while adding user to firestore: ", err);
        });
    };
    addUser();
  }, []);

useEffect(() => {
    const unsub = onSnapshot(collection(db, "Items"), (snapshot) =>
      setItems(snapshot.docs.map((doc) => doc.data()))
    );
    return () => unsub();
  }, []);

// so nothing is being displayed here as firestore is not working.
</code>```

答:
Found out the solution on my own after a lot of search. Although I had to make a new bare react native project from scratch, and even then I was encountering that error, I had literally lost hope with firebase at that point. Then after sometime I changed my firebase config to the below code and it worked:

```<code>import {initializeApp} from 'firebase/app';
import {getAuth} from 'firebase/auth';
import {initializeFirestore} from 'firebase/firestore';

const firebaseConfig = {
  apiKey: '',
  authDomain: '',
  projectId: '',
  storageBucket: '',
  messagingSenderId: '',
  appId: '',
  measurementId: '',
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = initializeFirestore(app, {
  experimentalForceLongPolling: true,
});

export {auth, db};
</code>```

I had to change the initialization of db as mentioned above, hope it works for everyone out there who's stuck on this weird error.

Thank you all for your help!

Body:
I saw many questions on SO regarding this issue and none of them was answered (or the solution doesn't work), I don't know why. People are having this error continuously but no solution is being provided. And from past few days even I'm encountering this error (Note: It seems to be working fine on my physical device (not while debugging, it works on only if I release it), but not on android emulator, so I'm pretty sure my internet is working fine):

Setting a timer for a long period of time, i.e. multiple minutes, is a performance and correctness issue on Android as it keeps the timer module awake, and timers can only be called when the app is in the foreground. See https://github.com/facebook/react-native/issues/12981 for more info.
(Saw setTimeout with duration 3052257ms)
Authorization status: 1

[2022-02-09T07:05:26.500Z]  @firebase/firestore: Firestore (9.6.5): Could not reach Cloud Firestore backend. Backend
didn't respond within 10 seconds.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will
operate in offline mode until it is able to successfully connect to the backend.
Authorization status: 1

[2022-02-09T07:08:44.688Z]  @firebase/firestore: Firestore (9.6.5): Connection WebChannel transport errored: me {
  "defaultPrevented": false,
  "g": Y {
    "A": true,
    "J": null,
    "R": [Circular],
    "g": $d {
      "$": true,
      "$a": 2,
      "A": 3,
      "B": null,
      "Ba": 12,
      "C": 0,
      "D": "gsessionid",
      "Da": false,
      "Ea": Dd {
        "g": Cd {},
      },
      ... & so on...

Package.json:

"@react-native-firebase/app": "^14.3.1",
"@react-native-firebase/messaging": "^14.3.1",
"@react-native-google-signin/google-signin": "^7.0.4",
"expo": "~44.0.0",
"firebase": "^9.6.3",

The authentication & messaging seems to be working fine, but I think the db from firestore is having this issue.
Following is some of the code from my firebase.tsx config file:

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: "",
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);

export { auth, db };

What I tried so far:

Changing the firestore database rules as mentioned in this answer: https://stackoverflow.com/a/70980383/11685381

Using this workaround: https://github.com/firebase/firebase-js-sdk/issues/5667#issuecomment-952079600

I'm not using any .env variables according to this answer: https://stackoverflow.com/a/69095824/11685381

Wiped android emulator data, then Cold Boot. Didn't work.

Upgraded firebase-9.6.3 to firebase-9.6.6. Didn't work.

cleaned the build folder, yarn installed all the packages again. Didn't work.

Can anyone provide any working solution to this problem?
Thank you!

EDIT-1:

The code where I'm calling firestore db especially:

In my HomeScreen.tsx:

import { doc, setDoc, onSnapshot, collection } from "firebase/firestore";
import { db } from "../../../firebase";

// inside functional component
useEffect(() => {
    const addUser = () => {
      const path = doc(db, "Users", user.uid);
      const data = {
        _id: user.uid,
        name: user.displayName,
        email: user.email,
      };
      setDoc(path, data)
        .then(() => {
          console.log("User added to db");
        })
        .catch((err) => {
          console.log("Error while adding user to firestore: ", err);
        });
    };
    addUser();
  }, []);

useEffect(() => {
    const unsub = onSnapshot(collection(db, "Items"), (snapshot) =>
      setItems(snapshot.docs.map((doc) => doc.data()))
    );
    return () => unsub();
  }, []);

// so nothing is being displayed here as firestore is not working.

Body:
Found out the solution on my own after a lot of search. Although I had to make a new bare react native project from scratch, and even then I was encountering that error, I had literally lost hope with firebase at that point. Then after sometime I changed my firebase config to the below code and it worked:

import {initializeApp} from 'firebase/app';
import {getAuth} from 'firebase/auth';
import {initializeFirestore} from 'firebase/firestore';

const firebaseConfig = {
  apiKey: '',
  authDomain: '',
  projectId: '',
  storageBucket: '',
  messagingSenderId: '',
  appId: '',
  measurementId: '',
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = initializeFirestore(app, {
  experimentalForceLongPolling: true,
});

export {auth, db};

I had to change the initialization of db as mentioned above, hope it works for everyone out there who's stuck on this weird error.

Thank you all for your help!


问:
Using geom_raster to visualise a dataframe of datatypes in R
I am putting together a workflow in R that will ultimately be used to assist in migrating a series of very large databases that are similar, but frustratingly different in minor ways.

One of the things I need to be able to visualise is which variable names are present in each database, and what datatype they are.

I have reached the point where I have a summary dataframe that looks very similar to the example below.

```<code>category <- c("Location", "Date", "Time", "Number")
species1 <- c("character", "character", "character", "integer")
species2 <- c("integer", "integer", NA, "character")
species3 <- c("character", "posix", "posix", "integer")
species4 <- c(NA, NA, "posix", "integer")

comparison_table <- data.frame(category, species1, species2, species3, species4)
</code>```

The NA values denote that this variable is not present within a specific database.

My ultimate goal was to construct a plot of coloured squares to easily identify inconsistent datatypes between the databases (for example, where dates have been recorded as integers instead of POSIX, or where latitude recorded as a character instead of an integer).

My gut tells me that the geom_raster in ggplot2 should be the simplest way to achieve this, but I keep coming up short. I know that I need to define the fill in the aesthetic, but every attempt is met with a different error.

```<code>comparison_table %>%
  ggplot(aes(x = colnames(comparison_table), y = rownames(comparison_table))) +
  geom_raster()
</code>```

A fresh pair of eyes and a less tired brain would be deeply appreciated.

答:
You'll need to re-structure your data to fit in the grammar of ggplot.

In aes(x, y, fill), we should supply a column from data, which essentially tells which variable should the subsequent geom_function() use to display the data.

In your case, you want:

x-asix to be "Location", "Date", "Time", "Number", which I grouped them into the Category column.

Similarly, your y-axis would be species, where species1, species2, species3, species4 are grouped in this column, with it's corresponding value grouped into the type column.

Moreover, since you wish to visualise your data using geom_raster(), you should also tell ggplot to use which variable to fill the squares (remember to use fill inside aes() if your fill comes from a column).

```<code>library(tidyverse)

comparison_table %>% pivot_longer(!Category, names_to = "species", values_to = "type") %>%
  ggplot(aes(x = Category, y = species, fill = type)) +
  geom_raster()
</code>```

Body:
I am putting together a workflow in R that will ultimately be used to assist in migrating a series of very large databases that are similar, but frustratingly different in minor ways.

One of the things I need to be able to visualise is which variable names are present in each database, and what datatype they are.

I have reached the point where I have a summary dataframe that looks very similar to the example below.

category <- c("Location", "Date", "Time", "Number")
species1 <- c("character", "character", "character", "integer")
species2 <- c("integer", "integer", NA, "character")
species3 <- c("character", "posix", "posix", "integer")
species4 <- c(NA, NA, "posix", "integer")

comparison_table <- data.frame(category, species1, species2, species3, species4)

The NA values denote that this variable is not present within a specific database.

My ultimate goal was to construct a plot of coloured squares to easily identify inconsistent datatypes between the databases (for example, where dates have been recorded as integers instead of POSIX, or where latitude recorded as a character instead of an integer).

My gut tells me that the geom_raster in ggplot2 should be the simplest way to achieve this, but I keep coming up short. I know that I need to define the fill in the aesthetic, but every attempt is met with a different error.

comparison_table %>%
  ggplot(aes(x = colnames(comparison_table), y = rownames(comparison_table))) +
  geom_raster()

A fresh pair of eyes and a less tired brain would be deeply appreciated.

Body:
You'll need to re-structure your data to fit in the grammar of ggplot.

In aes(x, y, fill), we should supply a column from data, which essentially tells which variable should the subsequent geom_function() use to display the data.

In your case, you want:

x-asix to be "Location", "Date", "Time", "Number", which I grouped them into the Category column.

Similarly, your y-axis would be species, where species1, species2, species3, species4 are grouped in this column, with it's corresponding value grouped into the type column.

Moreover, since you wish to visualise your data using geom_raster(), you should also tell ggplot to use which variable to fill the squares (remember to use fill inside aes() if your fill comes from a column).

library(tidyverse)

comparison_table %>% pivot_longer(!Category, names_to = "species", values_to = "type") %>%
  ggplot(aes(x = Category, y = species, fill = type)) +
  geom_raster()


问:
How can I test LDAP connection using JNDI
I get an exception javax.naming.NameNotFountException: [LDAP: error code 32 - No Such Object]; remaining name = 'DC=my-company, DC=group'

The cause of it could be, that the DN 'DC=my-company, DC=group' is invalid. But such exception occurs also then if I set ldapAdServer, ldapUsername, ldapPassword to unvalid values. So, I suppose my LDAP connection was not properly set.

How can I test LDAP connection whether it was created successfully?

答:
But such exception occurs also then if I set ldapAdServer,
  ldapUsername, ldapPassword to unvalid values.

No it doesn't. You get a different exception.


问:
Target-typed new expressions and implicit arrays
I can write the following to initialize a List<KeyValuePair<string, string>> in a field initializer:

List<KeyValuePair<string, string>> lst = new() {
    new("Key1", "Value1"),
    new("Key2", "Value2")
}
```
<p>leveraging target-typed <code>new</code> expressions for both the containing <code>List<></code> and the individual <code>KeyValuePair<></code> structs.</p>
<p>Is it possible to similarly initialize an array? Target-typed <code>new</code> expressions can't be used for the array itself, because an array has to be initialized.</p>
<p>But the following -- using implictly-typed arrays -- doesn't compile:</p>
<pre class="lang-cs prettyprint-override"><code>KeyValuePair<string, string>[] arr = new [] {
    new("Key1", "Value1"),
    new("Key2", "Value2")
}
</code>```

with:

CS0826 No best type found for implicitly-typed array

答:
You can remove the new[] part:

using System.Collections.Generic;

KeyValuePair<string, string>[] arr =
{
    new("Key1", "Value1"),
    new("Key2", "Value2")
};
```
<p>That's <em>only</em> valid as part of a variable declaration though, which allow an <em>array_initializer</em> as the initial value, without the need for an <em>array_creation_expression</em>. Variable declarations include fields, of course:</p>
<pre class="lang-cs prettyprint-override"><code>public class Test
{
    private readonly KeyValuePair<string, string>[] arr =
    {
        new("Key1", "Value1"),
        new("Key2", "Value2")
    };
}
</code>```

Body:
I can write the following to initialize a List<KeyValuePair<string, string>> in a field initializer:

List<KeyValuePair<string, string>> lst = new() {
    new("Key1", "Value1"),
    new("Key2", "Value2")
}

leveraging target-typed new expressions for both the containing List<> and the individual KeyValuePair<> structs.

Is it possible to similarly initialize an array? Target-typed new expressions can't be used for the array itself, because an array has to be initialized.

But the following -- using implictly-typed arrays -- doesn't compile:

KeyValuePair<string, string>[] arr = new [] {
    new("Key1", "Value1"),
    new("Key2", "Value2")
}

with:

CS0826 No best type found for implicitly-typed array

Body:
You can remove the new[] part:

using System.Collections.Generic;

KeyValuePair<string, string>[] arr =
{
    new("Key1", "Value1"),
    new("Key2", "Value2")
};

That's only valid as part of a variable declaration though, which allow an array_initializer as the initial value, without the need for an array_creation_expression. Variable declarations include fields, of course:

public class Test
{
    private readonly KeyValuePair<string, string>[] arr =
    {
        new("Key1", "Value1"),
        new("Key2", "Value2")
    };
}


问:
Django - how to correctly install library without pip in venv to work after deployment
According to this guide I successfully connected to Sybase database in my django project in virtual environment.

After deployment in Apache the web writes this error message

```<code>Environment:

Request Method: GET
Request URL: http://localhost:8080/

Django Version: 1.8
Python Version: 3.6.9
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog',
 'sybase_app')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')

Traceback:
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
  51.             with self._recreate_cm():
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/transaction.py" in __enter__
  150.             if not connection.get_autocommit():
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in get_autocommit
  286.         self.ensure_connection()
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  130.                 self.connect()
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/utils.py" in __exit__
  97.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/utils/six.py" in reraise
  658.             raise value.with_traceback(tb)
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  130.                 self.connect()
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in connect
  118.         conn_params = self.get_connection_params()
File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlany_django/base.py" in get_connection_params
  517.         root = Database.Root('PYTHON')
File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlanydb.py" in __init__
  466.                                 'libdbcapi_r.dylib')
File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlanydb.py" in load_library
  458.     raise InterfaceError("Could not load dbcapi.  Tried: " + ','.join(map(str, names)))

Exception Type: InterfaceError at /
Exception Value: Could not load dbcapi.  Tried: None,dbcapi.dll,libdbcapi_r.so,libdbcapi_r.dylib
</code>```

I edited /etc/apache2/envvars and appended a line
export LD_LIBRARY_PATH=/opt/sqlanywhere17/lib64:/opt/sqlanywhere17/lib32:$LD_LIBRARY_PATH

The error message changed to:

```<code>Environment:

Request Method: GET
Request URL: http://localhost:8080/

Django Version: 1.8
Python Version: 3.6.9
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog',
 'sybase_app')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')

Traceback:
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
  51.             with self._recreate_cm():
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/transaction.py" in __enter__
  150.             if not connection.get_autocommit():
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in get_autocommit
  286.         self.ensure_connection()
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  130.                 self.connect()
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/utils.py" in __exit__
  97.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/utils/six.py" in reraise
  658.             raise value.with_traceback(tb)
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  130.                 self.connect()
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in connect
  118.         conn_params = self.get_connection_params()
File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlany_django/base.py" in get_connection_params
  517.         root = Database.Root('PYTHON')
File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlanydb.py" in __init__
  480.                         API_VERSION_EX)

Exception Type: InterfaceError at /
Exception Value: Failed to initalize dbcapi context, dbcapi version 2 required. Perhaps you are missing some sqlanywhere libaries?
</code>```

How can I fix it?

答: I solved it, so that I appended the file /opt/sqlanywhere17/bin64/sa_config.sh to /etc/apache2/envvars and restarted apache2.

Body:
According to this guide I successfully connected to Sybase database in my django project in virtual environment.

After deployment in Apache the web writes this error message

Environment:

Request Method: GET
Request URL: http://localhost:8080/

Django Version: 1.8
Python Version: 3.6.9
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog',
 'sybase_app')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')

Traceback:
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
  51.             with self._recreate_cm():
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/transaction.py" in __enter__
  150.             if not connection.get_autocommit():
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in get_autocommit
  286.         self.ensure_connection()
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  130.                 self.connect()
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/utils.py" in __exit__
  97.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/utils/six.py" in reraise
  658.             raise value.with_traceback(tb)
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  130.                 self.connect()
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in connect
  118.         conn_params = self.get_connection_params()
File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlany_django/base.py" in get_connection_params
  517.         root = Database.Root('PYTHON')
File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlanydb.py" in __init__
  466.                                 'libdbcapi_r.dylib')
File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlanydb.py" in load_library
  458.     raise InterfaceError("Could not load dbcapi.  Tried: " + ','.join(map(str, names)))

Exception Type: InterfaceError at /
Exception Value: Could not load dbcapi.  Tried: None,dbcapi.dll,libdbcapi_r.so,libdbcapi_r.dylib

I edited /etc/apache2/envvars and appended a line
export LD_LIBRARY_PATH=/opt/sqlanywhere17/lib64:/opt/sqlanywhere17/lib32:$LD_LIBRARY_PATH

The error message changed to:

Environment:

Request Method: GET
Request URL: http://localhost:8080/

Django Version: 1.8
Python Version: 3.6.9
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog',
 'sybase_app')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')

Traceback:
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
  51.             with self._recreate_cm():
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/transaction.py" in __enter__
  150.             if not connection.get_autocommit():
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in get_autocommit
  286.         self.ensure_connection()
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  130.                 self.connect()
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/utils.py" in __exit__
  97.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/utils/six.py" in reraise
  658.             raise value.with_traceback(tb)
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  130.                 self.connect()
File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in connect
  118.         conn_params = self.get_connection_params()
File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlany_django/base.py" in get_connection_params
  517.         root = Database.Root('PYTHON')
File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlanydb.py" in __init__
  480.                         API_VERSION_EX)

Exception Type: InterfaceError at /
Exception Value: Failed to initalize dbcapi context, dbcapi version 2 required. Perhaps you are missing some sqlanywhere libaries?

How can I fix it?


问:
How do I install opencv using pip?
I need to install cv2 for a script that has been written for me. I tried  pip install cv2 and pip install open_cv and got the same problem - a warning message from dist.py and complains about zlib being not found. No cv2 installed. I also tried pyopenvc and pip install opencv-python.

So, I went to the opencv site and downloaded the relevant exe. Ran it - generated a heap of subdirectories and a make file and stuff.

What do I do now?

答:
->pip install opencv-python you can use this.

But if this code does not working then you can check python version on cmd and anaconda because they are different. So you type command in anaconda prompt and cmd, it will work. You can check this -> pip list

Title: How do I install opencv using pip?


问:
How to recognize the format of a video stream?
Suppose that a video stream is transmitted over a local network: some VLC clients receive the video stream via RTSP. Could a client identify which format is used to encode the video stream? In other words, how can I recognize the format used to encode the video stream transmitted over the local network? I would be interested to see if the format used to encode the video stream is H.264 or some other format.</p>

答:
Try these commands:

```<code>ffmpeg -i rtsp://localhost:8554/mystream .
</code>```

or

```<code>ffprobe rtspstreamUrl
</code>```

This is the way to get more information about the rtsp stream or any video via ffmpeg.

Body:
Try these commands:

ffmpeg -i rtsp://localhost:8554/mystream .

or

ffprobe rtspstreamUrl

This is the way to get more information about the rtsp stream or any video via ffmpeg.


问:
How to parameterize verilog attribute (* *)?
How can I declare a signal with a verilog attribute depending on module's parameter?

I tried:

```<code>if (KEEP_VERILOG) begin
  (*keep="true"*)reg mysig;
end else begin
  reg mysig;
end

// doing something with mysig
</code>```

I get a synthesis error: mysig is not declared

答:
You cannot reference a signal declared in an unnamed begin/end block from outside that block. Give the block a name (and you have to give both blocks the same name for what you want to do) and use that name in the reference.

```<code>if (KEEP_VERILOG) begin : blockname
    (*keep="true"*)reg mysig;
end else begin : blockname
  reg mysig;
end

// do something with blockname.mysig
</code>```

Body:
How can I declare a signal with a verilog attribute depending on module's parameter?

I tried:

if (KEEP_VERILOG) begin
  (*keep="true"*)reg mysig;
end else begin
  reg mysig;
end

// doing something with mysig

I get a synthesis error: mysig is not declared

Body:
You cannot reference a signal declared in an unnamed begin/end block from outside that block. Give the block a name (and you have to give both blocks the same name for what you want to do) and use that name in the reference.

if (KEEP_VERILOG) begin : blockname
    (*keep="true"*)reg mysig;
end else begin : blockname
  reg mysig;
end

// do something with blockname.mysig


问:
LateError was thrown building Obx(has builder, dirty, state: _ObxState#17527): LateInitializationError: Field 'products' has not been initialized
I am using GetX. I need to display the data from database one the application open. But i get the Exception.

The following LateError was thrown building Obx(has builder, dirty,
state: _ObxState#17527): LateInitializationError: Field 'products' has
not been initialized.

Although, I have initialize the late variable inside onInit.

The Controller Code Is:

```<code>class HomeController extends GetxController {
  HomeController({required this.homeRepository});
  final IHomeRepository homeRepository;
  late Rx<Either<FireStoreServerFailures, List<Product>>> products; //=
  @override
  void onInit() async {
  products.value=  await fetchProductsFromDB();
    super.onInit();
  }
 Future<Either<FireStoreServerFailures, List<Product>>> fetchProductsFromDB() async {
    var _completer=Completer<Either<FireStoreServerFailures, List<Product>>>();
    homeRepository.fetchProducts().listen((event) {
      _completer.complete(event);
    });
    return await _completer.future;
  }
}
</code>```

Home Page Where I Am Used The Late Variable's Code Is:

```<code> Obx(
      () => GridView.builder(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 2 / 2,
          ),
          // TODO Deal with errors
          itemCount: controller.products.value.getOrElse(() => []).length,
          itemBuilder: (context, index) {
            return controller.products.value.fold(
                    (l) => Container(
                          height: double.infinity,
                          width: double.infinity,
                          color: Colors.red,
                          child: Text("Error ${l.msg}"),
                        ),
                    (r) => Card(
                          elevation: 2.0,
                          color: Colors.amber,
                          child: InkWell(
                            onTap: () async =>
                                await controller.goToMoreDetails(),
                            child: Stack(
                              fit: StackFit.expand,
                              clipBehavior: Clip.hardEdge,
                              children: [
                                Image.network(
                                  controller.products.value.fold(
                                      (l) => "",
                                      (r) => r[index]
                                          .pickedImages
                                          .getOrCrash()[0]),
                                  fit: BoxFit.fill,
                                  height: 200,
                                  width: 200,
                                ),
                                OverflowBox(
                                  minHeight: 30,
                                  alignment: Alignment.bottomCenter,
                                  child: Container(
                                    color: Colors.black.withOpacity(0.7),
                                    height: 30,
                                    width: double.infinity,
                                    child: Center(
                                      child: Text(
                                        "${controller.products.value.fold((l) => "", (r) => r[index].price.getOrCrash())}",
                                        style: const TextStyle(
                                          color: Colors.white,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )) ;
          }),
    );
</code>```

答:
You declared late Rx<Either<FireStoreServerFailures, List<Product>>> products; but did not initialise products anywhere. But on your onInit method you tried to access .value on products which is not yet initialised. Setting products.value is not initialising products. Also, your Obx widget tries to access the products field which is not initialised by the time it tries to access.

What you should do is:

```<code>  final products = Rxn<Either<FireStoreServerFailures, List<Product>>>();
</code>```

And in your UI:

```<code> Obx(
  () => controller.products.value == null? CircularProgressIndicator() : GridView.builder(......
</code>```

Body:
I am using GetX. I need to display the data from database one the application open. But i get the Exception.

The following LateError was thrown building Obx(has builder, dirty,
state: _ObxState#17527): LateInitializationError: Field 'products' has
not been initialized.

Although, I have initialize the late variable inside onInit.

The Controller Code Is:

class HomeController extends GetxController {
  HomeController({required this.homeRepository});
  final IHomeRepository homeRepository;
  late Rx<Either<FireStoreServerFailures, List<Product>>> products; //=
  @override
  void onInit() async {
  products.value=  await fetchProductsFromDB();
    super.onInit();
  }
 Future<Either<FireStoreServerFailures, List<Product>>> fetchProductsFromDB() async {
    var _completer=Completer<Either<FireStoreServerFailures, List<Product>>>();
    homeRepository.fetchProducts().listen((event) {
      _completer.complete(event);
    });
    return await _completer.future;
  }
}

Home Page Where I Am Used The Late Variable's Code Is:

 Obx(
      () => GridView.builder(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 2 / 2,
          ),
          // TODO Deal with errors
          itemCount: controller.products.value.getOrElse(() => []).length,
          itemBuilder: (context, index) {
            return controller.products.value.fold(
                    (l) => Container(
                          height: double.infinity,
                          width: double.infinity,
                          color: Colors.red,
                          child: Text("Error ${l.msg}"),
                        ),
                    (r) => Card(
                          elevation: 2.0,
                          color: Colors.amber,
                          child: InkWell(
                            onTap: () async =>
                                await controller.goToMoreDetails(),
                            child: Stack(
                              fit: StackFit.expand,
                              clipBehavior: Clip.hardEdge,
                              children: [
                                Image.network(
                                  controller.products.value.fold(
                                      (l) => "",
                                      (r) => r[index]
                                          .pickedImages
                                          .getOrCrash()[0]),
                                  fit: BoxFit.fill,
                                  height: 200,
                                  width: 200,
                                ),
                                OverflowBox(
                                  minHeight: 30,
                                  alignment: Alignment.bottomCenter,
                                  child: Container(
                                    color: Colors.black.withOpacity(0.7),
                                    height: 30,
                                    width: double.infinity,
                                    child: Center(
                                      child: Text(
                                        "${controller.products.value.fold((l) => "", (r) => r[index].price.getOrCrash())}",
                                        style: const TextStyle(
                                          color: Colors.white,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )) ;
          }),
    );

Body:
You declared late Rx<Either<FireStoreServerFailures, List<Product>>> products; but did not initialise products anywhere. But on your onInit method you tried to access .value on products which is not yet initialised. Setting products.value is not initialising products. Also, your Obx widget tries to access the products field which is not initialised by the time it tries to access.

What you should do is:

  final products = Rxn<Either<FireStoreServerFailures, List<Product>>>();

And in your UI:

 Obx(
  () => controller.products.value == null? CircularProgressIndicator() : GridView.builder(......


问:
parameterizing SQL subquery in golang
Please consider this question.

I need to parameterize a SQL (sub) query in golang. Please consider the pseudo-code below or at https://go.dev/play/p/F-jZGEiDnsd

The hayStack details come to me in an string slice lookIn and can vary. I need to search for %eedl% (needle) in all these haystacks.

The code in the comment is how I currently handle it - I only parameterize the needle I am looking for.

How do I parameterize the hayStacks as well?

package main

import "fmt"

func main() {
    fmt.Println("Hello, 世界")
    lookIn := []string{"hayStack.1", "hayStack.2", "hayStack.3", "hayStack.4", "hayStack.5"}
    needle := "eedl"
    needle = "%" + needle + "%"

    for i := range lookIn {
        fmt.Println("lookIn", lookIn[i])
    }
    fmt.Println("needle", needle)

    /* this is how I currently do
        txt := `select needle,tagTitle,Epoch from ( select needle,tagTitle,Epoch where hayStackName = "hayStack.1" or hayStackName = "hayStack.2" or hayStackName = "hayStack.3" or hayStackName = "hayStack.3" or hayStackName = "hayStack.4" or hayStackName = "hayStack.5" )  where tagTitle like ? order by tagTitle COLLATE NOCASE ASC ;`
        rows, err := sqliteDbPtr.Query(txt, needle)

        if err != nil {
            if err != sql.ErrNoRows {
                checkErr(err)
                panic(err)
            }
            return
        }
        defer rows.Close()
    */

}
```

Any input will be much appreciated.

答:
Using just the standard library you can collect the haystack arguments and the needle argument into a single slice and then pass that to the Query method.

For the SQL itself you can use the IN operator and generate its right hand side operand as a list of ? based on the number of haystacks.

args := make([]interface{}, len(lookIn)+1) // slice of all args
inRHS := "" // string of ?,... for the IN operator's right hand side
for i := range lookIn {
    args[i] = lookIn[i]
    inRHS += "?,"
}
args[len(args)-1] = needle   // add the last arg
inRHS = inRHS[:len(inRHS)-1] // remove last ","
```
<pre class="lang-golang prettyprint-override"><code>query := `SELECT needle,tagTitle,Epoch
FROM some_table
WHERE hayStackName IN (` + inRHS + `)
AND tagTitle LIKE ?
ORDER BY tagTitle COLLATE NOCASE ASC`

rows, err := sqliteDbPtr.Query(query, args...)
if err != nil {
    // handle error
}
defer rows.Close()

for rows.Next() {
    //
}
if err := rows.Err(); err != nil {
    //
}
</code>```

NOTE that I've removed the subquery and added the FROM some_table clause which your question was missing.

Title: parameterizing SQL subquery in golang

Body:
Please consider this question.

I need to parameterize a SQL (sub) query in golang. Please consider the pseudo-code below or at https://go.dev/play/p/F-jZGEiDnsd

The hayStack details come to me in an string slice lookIn and can vary. I need to search for %eedl% (needle) in all these haystacks.

The code in the comment is how I currently handle it - I only parameterize the needle I am looking for.

How do I parameterize the hayStacks as well?

package main

import "fmt"

func main() {
    fmt.Println("Hello, 世界")
    lookIn := []string{"hayStack.1", "hayStack.2", "hayStack.3", "hayStack.4", "hayStack.5"}
    needle := "eedl"
    needle = "%" + needle + "%"

    for i := range lookIn {
        fmt.Println("lookIn", lookIn[i])
    }
    fmt.Println("needle", needle)

    /* this is how I currently do
        txt := `select needle,tagTitle,Epoch from ( select needle,tagTitle,Epoch where hayStackName = "hayStack.1" or hayStackName = "hayStack.2" or hayStackName = "hayStack.3" or hayStackName = "hayStack.3" or hayStackName = "hayStack.4" or hayStackName = "hayStack.5" )  where tagTitle like ? order by tagTitle COLLATE NOCASE ASC ;`
        rows, err := sqliteDbPtr.Query(txt, needle)

        if err != nil {
            if err != sql.ErrNoRows {
                checkErr(err)
                panic(err)
            }
            return
        }
        defer rows.Close()
    */

}

Any input will be much appreciated.

Body:
Using just the standard library you can collect the haystack arguments and the needle argument into a single slice and then pass that to the Query method.

For the SQL itself you can use the IN operator and generate its right hand side operand as a list of ? based on the number of haystacks.

args := make([]interface{}, len(lookIn)+1) // slice of all args
inRHS := "" // string of ?,... for the IN operator's right hand side
for i := range lookIn {
    args[i] = lookIn[i]
    inRHS += "?,"
}
args[len(args)-1] = needle   // add the last arg
inRHS = inRHS[:len(inRHS)-1] // remove last ","

query := `SELECT needle,tagTitle,Epoch
FROM some_table
WHERE hayStackName IN (` + inRHS + `)
AND tagTitle LIKE ?
ORDER BY tagTitle COLLATE NOCASE ASC`

rows, err := sqliteDbPtr.Query(query, args...)
if err != nil {
    // handle error
}
defer rows.Close()

for rows.Next() {
    //
}
if err := rows.Err(); err != nil {
    //
}

NOTE that I've removed the subquery and added the FROM some_table clause which your question was missing.


问:
Iterate enum in definition order in Python 2
I'm using the backported Enum functionality from python 3.4 with python 2.7:

```<code>> python --version
Python 2.7.6
> pip install enum34
# Installs version 1.0...
</code>```

According to the documentation for Enums in python 3 (https://docs.python.org/3/library/enum.html#creating-an-enum), "Enumerations support iteration, in definition order".  However, iteration is not happening in order for me:

```<code>>>> from enum import Enum
>>> class Shake(Enum):
...     vanilla = 7
...     chocolate = 4
...     cookies = 9
...     mint = 3
...
>>> for s in Shake:
...     print(s)
...
Shake.mint
Shake.chocolate
Shake.vanilla
Shake.cookies
</code>```

Am I misunderstanding something, or is iteration in definition order just not supported in the backported versions of Enums yet?  Assuming the latter, is there an easy way to force it to happen in order?

答:
use

```<code>__order__
</code>```

to define the order of enums for python version less than 3 . It is not necessary in python3 but make sure the order which is supplied same as declared order otherwise it will give error:

```<code>TypeError: member order does not match _order_

import enum

class EXCHANGE(enum.Enum):
    __order__ = " EXCHANGE_NSE EXCHANGE_BSE EXCHANGE_NFO EXCHANGE_CDS EXCHANGE_BFO EXCHANGE_MCX EXCHANGE_BCD "
    EXCHANGE_NSE = "NSE"
    EXCHANGE_BSE = "BSE"
    EXCHANGE_NFO = "NFO"
    EXCHANGE_CDS = "CDS"
    EXCHANGE_BFO = "BFO"
    EXCHANGE_MCX = "MCX"
    EXCHANGE_BCD = "BCD"

if __name__ == "__main__":
    for ex in EXCHANGE:
        print(f"{ex.name} : {ex.value}")
</code>```

Output:

```<code>EXCHANGE_NSE : NSE
EXCHANGE_BSE : BSE
EXCHANGE_NFO : NFO
EXCHANGE_CDS : CDS
EXCHANGE_BFO : BFO
EXCHANGE_MCX : MCX
EXCHANGE_BCD : BCD
</code>```

Body:
I'm using the backported Enum functionality from python 3.4 with python 2.7:

> python --version
Python 2.7.6
> pip install enum34
# Installs version 1.0...

According to the documentation for Enums in python 3 (https://docs.python.org/3/library/enum.html#creating-an-enum), "Enumerations support iteration, in definition order".  However, iteration is not happening in order for me:

>>> from enum import Enum
>>> class Shake(Enum):
...     vanilla = 7
...     chocolate = 4
...     cookies = 9
...     mint = 3
...
>>> for s in Shake:
...     print(s)
...
Shake.mint
Shake.chocolate
Shake.vanilla
Shake.cookies

Am I misunderstanding something, or is iteration in definition order just not supported in the backported versions of Enums yet?  Assuming the latter, is there an easy way to force it to happen in order?

Body:
use

__order__

to define the order of enums for python version less than 3 . It is not necessary in python3 but make sure the order which is supplied same as declared order otherwise it will give error:

TypeError: member order does not match _order_

import enum

class EXCHANGE(enum.Enum):
    __order__ = " EXCHANGE_NSE EXCHANGE_BSE EXCHANGE_NFO EXCHANGE_CDS EXCHANGE_BFO EXCHANGE_MCX EXCHANGE_BCD "
    EXCHANGE_NSE = "NSE"
    EXCHANGE_BSE = "BSE"
    EXCHANGE_NFO = "NFO"
    EXCHANGE_CDS = "CDS"
    EXCHANGE_BFO = "BFO"
    EXCHANGE_MCX = "MCX"
    EXCHANGE_BCD = "BCD"

if __name__ == "__main__":
    for ex in EXCHANGE:
        print(f"{ex.name} : {ex.value}")

Output:

EXCHANGE_NSE : NSE
EXCHANGE_BSE : BSE
EXCHANGE_NFO : NFO
EXCHANGE_CDS : CDS
EXCHANGE_BFO : BFO
EXCHANGE_MCX : MCX
EXCHANGE_BCD : BCD


问:
gulp-sass 5 does not have a default Sass compiler; please set one yourself
Error in plugin "gulp-sass"
Message:

gulp-sass 5 does not have a default Sass compiler; please set one yourself.
Both the sass and node-sass packages are permitted.
For example, in your gulpfile:

```<code>var sass = require('gulp-sass')(require('sass'));
</code>```

This is my code below . It says var sass = require('gulp-sass')(require('sass')); in the error but I am using import and none of the solution worked for me
I am new to this and the cli version is 2.3.0 local version is 4.0.2
please give me a solution I am stuck here for days

```<code>import gulp from 'gulp';
import sass from 'gulp-sass';
import yargs from 'yargs';

const PRODUCTION = yargs.argv.prod;

export const styles = () => {
    return gulp.src('src/assets/scss/bundle.scss')
      .pipe(sass().on('error', sass.logError))
      .pipe(gulp.dest('dist/asset/css'));
}
</code>```

答:
if I used gulp-sass

```<code>import dartSass from 'sass';
import gulpSass from 'gulp-sass';
const sass = gulpSass( dartSass );
</code>```

else if I used node-sass

```<code>import gulpSass from "gulp-sass";
import nodeSass from "node-sass";
const sass = gulpSass(nodeSass);
</code>```

on another state when I used required

```<code>var sass = require('gulp-sass')(require('sass'));
</code>```

Body:
Error in plugin "gulp-sass"
Message:

gulp-sass 5 does not have a default Sass compiler; please set one yourself.
Both the sass and node-sass packages are permitted.
For example, in your gulpfile:

var sass = require('gulp-sass')(require('sass'));

This is my code below . It says var sass = require('gulp-sass')(require('sass')); in the error but I am using import and none of the solution worked for me
I am new to this and the cli version is 2.3.0 local version is 4.0.2
please give me a solution I am stuck here for days

import gulp from 'gulp';
import sass from 'gulp-sass';
import yargs from 'yargs';

const PRODUCTION = yargs.argv.prod;

export const styles = () => {
    return gulp.src('src/assets/scss/bundle.scss')
      .pipe(sass().on('error', sass.logError))
      .pipe(gulp.dest('dist/asset/css'));
}

Body:
if I used gulp-sass

import dartSass from 'sass';
import gulpSass from 'gulp-sass';
const sass = gulpSass( dartSass );

else if I used node-sass

import gulpSass from "gulp-sass";
import nodeSass from "node-sass";
const sass = gulpSass(nodeSass);

on another state when I used required

var sass = require('gulp-sass')(require('sass'));


问:
Can't access Kibana remotely
I have installed Elasticsearch and kibana in the same Centos server. When running netstat -nlp | grep :5601 I get the below result:

```<code>tcp        0      0 0.0.0.0:5601            0.0.0.0:*               LISTEN      27244/node
</code>```

But I still can't access kibana remotely from my windows client, when I try to access kibana from my windows client in browser using "http://my_server_ip:5601", I get something like this:

```<code>This page cannot be accessed
...(omitted)
ERR_CONNECTION_RESET
</code>```

However, I can access ES from my windows client in browser using "http://my_server_ip:9200":

```<code>{
  "name" : "VM-251-156-centos",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "FsL8YI1mQAGqx3R0kffxbw",
  "version" : {
    "number" : "7.10.2",
    "build_flavor" : "oss",
    "build_type" : "rpm",
    "build_hash" : "747e1cc71def077253878a59143c1f785afa92b9",
    "build_date" : "2021-01-13T00:42:12.435326Z",
    "build_snapshot" : false,
    "lucene_version" : "8.7.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}
</code>```

I have searched all day long, almost all the answers suggested to edit the kibana.yml, changing server.host to 0.0.0.0, but they don't work in my case.

My kibana.yml is like this (only list uncommented lines):

```<code>server.port: 5601
server.host: "0.0.0.0"
server.name: "http://kibana.example.com"
elasticsearch.hosts: ["http://my_server_ip:9200"]
</code>```

And I have checked the firewall in Centos server using the command "firewall-cmd --state":

```<code>not running
</code>```

And I have also confirmed that kibana is really running in the Centos server using "sudo systemctl status kibana":

```<code>● kibana.service - Kibana
   Loaded: loaded (/etc/systemd/system/kibana.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2022-01-26 13:57:44 CST; 19h ago
 Main PID: 27244 (node)
    Tasks: 11
   Memory: 80.6M
   CGroup: /system.slice/kibana.service
           └─27244 /usr/share/kibana/bin/../node/bin/node /usr/share/kibana/bin/../src/cli/dist
</code>```

Any suggesstions is appreciated.

答:
Solved by changing "server.port: 5601" to "server.port: 5602" in the kibana.yml.

It turns out that the problem was caused by the 5601 port in the centos server was blocked by the server provider for security concerns.

Title: Can't access Kibana remotely

Body:
I have installed Elasticsearch and kibana in the same Centos server. When running netstat -nlp | grep :5601 I get the below result:

tcp        0      0 0.0.0.0:5601            0.0.0.0:*               LISTEN      27244/node

But I still can't access kibana remotely from my windows client, when I try to access kibana from my windows client in browser using "http://my_server_ip:5601", I get something like this:

This page cannot be accessed
...(omitted)
ERR_CONNECTION_RESET

However, I can access ES from my windows client in browser using "http://my_server_ip:9200":

{
  "name" : "VM-251-156-centos",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "FsL8YI1mQAGqx3R0kffxbw",
  "version" : {
    "number" : "7.10.2",
    "build_flavor" : "oss",
    "build_type" : "rpm",
    "build_hash" : "747e1cc71def077253878a59143c1f785afa92b9",
    "build_date" : "2021-01-13T00:42:12.435326Z",
    "build_snapshot" : false,
    "lucene_version" : "8.7.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

I have searched all day long, almost all the answers suggested to edit the kibana.yml, changing server.host to 0.0.0.0, but they don't work in my case.

My kibana.yml is like this (only list uncommented lines):

server.port: 5601
server.host: "0.0.0.0"
server.name: "http://kibana.example.com"
elasticsearch.hosts: ["http://my_server_ip:9200"]

And I have checked the firewall in Centos server using the command "firewall-cmd --state":

not running

And I have also confirmed that kibana is really running in the Centos server using "sudo systemctl status kibana":

● kibana.service - Kibana
   Loaded: loaded (/etc/systemd/system/kibana.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2022-01-26 13:57:44 CST; 19h ago
 Main PID: 27244 (node)
    Tasks: 11
   Memory: 80.6M
   CGroup: /system.slice/kibana.service
           └─27244 /usr/share/kibana/bin/../node/bin/node /usr/share/kibana/bin/../src/cli/dist

Any suggesstions is appreciated.


问:
help in uniquely identifying combine columns
How can I uniquely identify two or more columns, that I have used table named address in the database, now address is has fields like street name, suite name and street num.

strnum   | strnam  |  sutname

1        | xyz     | 32

1        | xyz     | 32

now how can I uniquely these three columns. That is I want to check whether these three column are already inserted or not. If any field valus is changed than its ok, it will insert new one. but in case all three similar field..Help me to combinely identify these three fields.

答:
you can do something like this

```<code> SELECT * FROM table WHERE col1 = $something AND col2 = $something2 AND col3 = $something3
</code>```

(remember about escpaing php variables)
if the record is returned it means it exists. You can also add LIMIT 1 to make it faster.

if your question is about ENSURING that no duplicates occur in the table (for those 3 columns), then probably the best solution is to add UNIQUE index on those three columns.

Body:
you can do something like this

 SELECT * FROM table WHERE col1 = $something AND col2 = $something2 AND col3 = $something3

(remember about escpaing php variables)
if the record is returned it means it exists. You can also add LIMIT 1 to make it faster.

if your question is about ENSURING that no duplicates occur in the table (for those 3 columns), then probably the best solution is to add UNIQUE index on those three columns.


问:
How to change the App icon in a Xamarin Forms iOS App?
I want to change the Icon of my Xamarin Forms App. I already replaced all the AppIcons in the Asset catalog, but it still shows me the default Xamarin Logo. I even specified the Assetcatalog in the info.plist file, and it didn't work either. I still have this Xamarin Forms Logo and I have no ideas what to do. Any help would be nice!</p>

答:
1.Please check the limitations of Hot Restart

Asset Catalogs are currently not supported. When using Hot Restart, your app will show the default icon and launch screen for Xamarin apps. When paired to a Mac, or developing on a Mac, your Asset Catalogs will work.

If you use mac agent to deploy your application on device , the problem should be able to solved.

2.In the Info.plist file, make sure you choose the right asset source for the App Icons.


问:
how to hide onStepContinue button for the last step and onStepCancel for the first step on flutter?
This is my first time on flutter framework and Dart programming I have so manny miss of understanding Dart language.

I want to hide onStepContinue button for the last step and onStepCancel for the first step on flutter? this is my code I'm newbe in flutter any help?

```<code>class _MyHomePageState extends State<MyHomePage> {
  int _currentStep = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Stepper(
          controlsBuilder: (BuildContext context, ControlsDetails details) {
            return Row(
              children: <Widget>[
              TextButton(
                onPressed: details.onStepContinue,
                child: const Text('NEXT'),
              ),
              TextButton(
                onPressed: details.onStepCancel,
                child: const Text('BACK'),
              ),
            ],
            );
          },
          steps: const [
            Step(
              title: Text("Step 1"),
              content: Text("Information for step 1"),
            ),
            Step(
              title: Text("Step 2"),
              content: Text("Information for step 2"),
            ),
            Step(
              title: Text("Step 3"),
              content: Text("Information for step 3"),
            ),
          ],
          onStepTapped: (int newIndex){
            setState(() {
              _currentStep = newIndex;
            });
          },
          currentStep: _currentStep,
          onStepContinue: () {
            if (_currentStep != 2) {
              setState(() {
                _currentStep += 1;
              });
            }
          },
          onStepCancel: () {
            if (_currentStep != 0) {
              setState(() {
                _currentStep -= 1;
              });
            }
          },
        ),
      ),
    );
  }
}
</code>```

答:
Use conditional state to show the buttons.

controlsBuilder: (BuildContext context, ControlsDetails details) {
  return Row(
    children: <Widget>[
      if (_currentStep != 2) // skip on last step
        TextButton(
          onPressed: details.onStepContinue,
          child: const Text('NEXT'),
        ),
      if (_currentStep != 0)// skip on 1st step
         TextButton(
          onPressed: details.onStepCancel,
          child: const Text('BACK'),
        ),
    ],
  );
},
```

Body:
This is my first time on flutter framework and Dart programming I have so manny miss of understanding Dart language.

I want to hide onStepContinue button for the last step and onStepCancel for the first step on flutter? this is my code I'm newbe in flutter any help?

class _MyHomePageState extends State<MyHomePage> {
  int _currentStep = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Stepper(
          controlsBuilder: (BuildContext context, ControlsDetails details) {
            return Row(
              children: <Widget>[
              TextButton(
                onPressed: details.onStepContinue,
                child: const Text('NEXT'),
              ),
              TextButton(
                onPressed: details.onStepCancel,
                child: const Text('BACK'),
              ),
            ],
            );
          },
          steps: const [
            Step(
              title: Text("Step 1"),
              content: Text("Information for step 1"),
            ),
            Step(
              title: Text("Step 2"),
              content: Text("Information for step 2"),
            ),
            Step(
              title: Text("Step 3"),
              content: Text("Information for step 3"),
            ),
          ],
          onStepTapped: (int newIndex){
            setState(() {
              _currentStep = newIndex;
            });
          },
          currentStep: _currentStep,
          onStepContinue: () {
            if (_currentStep != 2) {
              setState(() {
                _currentStep += 1;
              });
            }
          },
          onStepCancel: () {
            if (_currentStep != 0) {
              setState(() {
                _currentStep -= 1;
              });
            }
          },
        ),
      ),
    );
  }
}


问:
why useSelector return undefined?
I can't figure it out why it's returning undefined, when i'm using the useSelector

In console log it showing Uncaught TypeError: movies.results is undefined

error logmovieLising.js(without render movies)
console.log

store.js

```<code>import {configureStore} from '@reduxjs/toolkit';
import moviesReducer from './movies/movieSlice';

export const store = configureStore({
    reducer:{
        movies:moviesReducer
    }
})
</code>```

movieSlice.js

Here is the slice where i defined the initial state reducer and actions

```<code>import {createSlice,createAsyncThunk} from '@reduxjs/toolkit';
import movieApi from '../../common/api/movieApi';

const API_KEY = process.env.REACT_APP_API_KEY;

export const fetchAsyncMovies = createAsyncThunk(
    "movies/fetchAsyncMovies",
    async () => {
            const movieTerm ="harry";
            const response = await
            movieApi.get(`/search/movie?api_key=${API_KEY}&query=${movieTerm}`);
            // console.log(response.data);
            return response.data;
    }
);

const initialState = {
    movies:{},
}

const movieSlice = createSlice({
    name:"movies",
    initialState,
    reducers:{

        addMovies:(state,{payload}) =>{
            state.movies= payload;
        }
    },
    extraReducers:{
        [fetchAsyncMovies.pending]: () => {
        console.log("Pending");
        },
        [fetchAsyncMovies.fulfilled]: (state, { payload }) => {
        console.log("Fetched Successfully!");
        return { ...state, movies: payload };
        },
        [fetchAsyncMovies.rejected]: () => {
        console.log("Rejected!");
        },
    }
});

export const {addMovies} = movieSlice.actions;

export const getAllMovies = (state) => state.movies.movies;

export default movieSlice.reducer
</code>```

Home.js

This is the Home component where i use the useDispatch

```<code>import React, { useEffect } from 'react';
import MovieListing from '../MovieListing/MovieListing';
import {useDispatch} from "react-redux";
import {fetchAsyncMovies} from "../../features/movies/movieSlice"

const Home = () => {
    const dispatch = useDispatch();
    useEffect(()=>{
        dispatch(fetchAsyncMovies());

    },[dispatch]);
    return(
        <div>
            <div className="banner-img"></div>
            <MovieListing/>
        </div>
    ) ;
};

export default Home;
</code>```

MovieListing.js(COMPONENT)

```<code>import React from 'react';
import {useSelector} from 'react-redux';
import {getAllMovies} from '../../features/movies/movieSlice';
import MovieCard from '../MovieCard/MovieCard';
import './movieListing.scss'

const MovieListing = () => {

    const movies = useSelector(getAllMovies);
     let renderMovies ="";

     renderMovies = movies.results.length > 0 ? (movies.results.map((movie,index)=>(
         <MovieCard key={index} data={movie} />
     ))) :(
        <div className="movies-error">
             <h3>{movies.Error}</h3>
         </div>
     );
console.log(movies.results);
    return (
        <div className="movie-wrapper">
            <div className="movie-list">
                <h2>Movies</h2>
                <div className="movie-container">
                    {renderMovies }
                </div>
            </div>

        </div>
    );
};

export default MovieListing;
</code>```

答:
Since you defined your initial state as :

const initialState = { movies:{}, }

In the very first render, movies.results is undefined, so trying to use the length property leads to an error.

try defining your initial state like this:

```<code>const initialState = { movies:{results:[]}, }
</code>```

another solution would be always checking if movies.results is defined, before using its properties:

```<code>renderMovies = movies.results && movies.results.length > 0 ? ...
</code>```

Title: why useSelector return undefined?

Body:
I can't figure it out why it's returning undefined, when i'm using the useSelector

In console log it showing Uncaught TypeError: movies.results is undefined

error logmovieLising.js(without render movies)
console.log

store.js

import {configureStore} from '@reduxjs/toolkit';
import moviesReducer from './movies/movieSlice';

export const store = configureStore({
    reducer:{
        movies:moviesReducer
    }
})

movieSlice.js

Here is the slice where i defined the initial state reducer and actions

import {createSlice,createAsyncThunk} from '@reduxjs/toolkit';
import movieApi from '../../common/api/movieApi';

const API_KEY = process.env.REACT_APP_API_KEY;

export const fetchAsyncMovies = createAsyncThunk(
    "movies/fetchAsyncMovies",
    async () => {
            const movieTerm ="harry";
            const response = await
            movieApi.get(`/search/movie?api_key=${API_KEY}&query=${movieTerm}`);
            // console.log(response.data);
            return response.data;
    }
);

const initialState = {
    movies:{},
}

const movieSlice = createSlice({
    name:"movies",
    initialState,
    reducers:{

        addMovies:(state,{payload}) =>{
            state.movies= payload;
        }
    },
    extraReducers:{
        [fetchAsyncMovies.pending]: () => {
        console.log("Pending");
        },
        [fetchAsyncMovies.fulfilled]: (state, { payload }) => {
        console.log("Fetched Successfully!");
        return { ...state, movies: payload };
        },
        [fetchAsyncMovies.rejected]: () => {
        console.log("Rejected!");
        },
    }
});

export const {addMovies} = movieSlice.actions;

export const getAllMovies = (state) => state.movies.movies;

export default movieSlice.reducer

Home.js

This is the Home component where i use the useDispatch

import React, { useEffect } from 'react';
import MovieListing from '../MovieListing/MovieListing';
import {useDispatch} from "react-redux";
import {fetchAsyncMovies} from "../../features/movies/movieSlice"

const Home = () => {
    const dispatch = useDispatch();
    useEffect(()=>{
        dispatch(fetchAsyncMovies());

    },[dispatch]);
    return(

            <MovieListing/>

    ) ;
};

export default Home;

MovieListing.js(COMPONENT)

import React from 'react';
import {useSelector} from 'react-redux';
import {getAllMovies} from '../../features/movies/movieSlice';
import MovieCard from '../MovieCard/MovieCard';
import './movieListing.scss'

const MovieListing = () => {

    const movies = useSelector(getAllMovies);
     let renderMovies ="";

     renderMovies = movies.results.length > 0 ? (movies.results.map((movie,index)=>(
         <MovieCard key={index} data={movie} />
     ))) :(

{movies.Error}

     );
console.log(movies.results);
    return (

Movies

                    {renderMovies }

    );
};

export default MovieListing;

Body:
Since you defined your initial state as :

const initialState = { movies:{}, }

In the very first render, movies.results is undefined, so trying to use the length property leads to an error.

try defining your initial state like this:

const initialState = { movies:{results:[]}, }

another solution would be always checking if movies.results is defined, before using its properties:

renderMovies = movies.results && movies.results.length > 0 ? ...