问:
How to use gradient descent for cosine similarity optimization?
so I have a vector A with 1508 dimensions that is defined, I have another list of n vectors in a list called C. Each of the n vectors is attributed a weight, and a vector B is defined by the following for each dimension : The weight times the first dimension of it's vector + the second weight times the first dimension of it's vector etc.... and all that divided by the sum of the weights. Basically I want to find the best combination of the n vectors to form a goal vector A. But the combination is done by averaging the dimensions of the vectors. Also the weights can only take 1 or 0 as a value. I tried to use Tensorflow's gradient descent in the following way :

```<code>import tensorflow as tf
tf.compat.v1.disable_eager_execution()

# Define the dimensions of the vectors
d = 1508
import numpy as np
import random
import math
# Define the variables
A = [random.uniform(0, 1) for _ in range(d)]
C = [[random.uniform(0, 1) for k in range(d)] for _ in range(4)]
a0 = a1 = a2 = a3 = 1
variables = [a0,a1,a2,a3]

# Define B as a linear combination of the vectors in C
B = []
for l in range(d):
    value = 0
    for i in range(4):
        value = value + variables[i] * C[i][l]
    B.append(value/sum(variables))

# Use a sigmoid activation to squash the variables to the range [0, 1]
variables = [1 / (1 + math.exp(-v)) for v in variables]

# Round the variables to 0 or 1
variables = [tf.round(v) for v in variables]
variables = [tf.Variable(v) for v in variables]

def loss(A,B):

    return 1 - tf.keras.losses.cosine_similarity(A, B)
    # Define the loss function

# Use an optimizer to minimize the loss
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)

num_steps = 100
import sys
# Run the training loop
for _ in range(num_steps):
  with tf.GradientTape() as tape:
    B = []
    for l in range(d):
      value = 0
      for i in range(4):
          value = value + variables[i] * C[i][l]
      B.append(value/sum(variables))
    loss_value = loss(A, B)
    grads = tape.gradient(loss_value, variables)

  print(loss_value)
  print(grads)
  print(len(grads))
  optimizer.apply_gradients(zip(grads, variables))
  variables = [tf.clip_by_value(v, 0, 1) for v in variables]
  variables = [tf.Variable(v) for v in variables]
</code>```

In this example I used 4 weights. But for some reason I can ever get the value of the variables to be printed out and I have no clue if this is working.

That's what I've tried, I was wondering if anyone had ideas on finding best combination of vectors to reach goal vector and what they used. Also will gradient descent work for this? Also I can't get the values from the variables, .numpy doesn't work tf. print doesn't work etc... Thanks! Here is what I get from running it for a bit :

```<code>[<tf.Tensor 'AddN_1:0' shape=() dtype=float32>, <tf.Tensor 'AddN_2:0' shape=() dtype=float32>, <tf.Tensor 'AddN_3:0' shape=() dtype=float32>, <tf.Tensor 'AddN_4:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_6:0' shape=() dtype=float32>, <tf.Tensor 'AddN_7:0' shape=() dtype=float32>, <tf.Tensor 'AddN_8:0' shape=() dtype=float32>, <tf.Tensor 'AddN_9:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_11:0' shape=() dtype=float32>, <tf.Tensor 'AddN_12:0' shape=() dtype=float32>, <tf.Tensor 'AddN_13:0' shape=() dtype=float32>, <tf.Tensor 'AddN_14:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_16:0' shape=() dtype=float32>, <tf.Tensor 'AddN_17:0' shape=() dtype=float32>, <tf.Tensor 'AddN_18:0' shape=() dtype=float32>, <tf.Tensor 'AddN_19:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_21:0' shape=() dtype=float32>, <tf.Tensor 'AddN_22:0' shape=() dtype=float32>, <tf.Tensor 'AddN_23:0' shape=() dtype=float32>, <tf.Tensor 'AddN_24:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_26:0' shape=() dtype=float32>, <tf.Tensor 'AddN_27:0' shape=() dtype=float32>, <tf.Tensor 'AddN_28:0' shape=() dtype=float32>, <tf.Tensor 'AddN_29:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_31:0' shape=() dtype=float32>, <tf.Tensor 'AddN_32:0' shape=() dtype=float32>, <tf.Tensor 'AddN_33:0' shape=() dtype=float32>, <tf.Tensor 'AddN_34:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_36:0' shape=() dtype=float32>, <tf.Tensor 'AddN_37:0' shape=() dtype=float32>, <tf.Tensor 'AddN_38:0' shape=() dtype=float32>, <tf.Tensor 'AddN_39:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_41:0' shape=() dtype=float32>, <tf.Tensor 'AddN_42:0' shape=() dtype=float32>, <tf.Tensor 'AddN_43:0' shape=() dtype=float32>, <tf.Tensor 'AddN_44:0' shape=() dtype=float32>]
4
</code>```

Thanks for the help!!!!

Body:
so I have a vector A with 1508 dimensions that is defined, I have another list of n vectors in a list called C. Each of the n vectors is attributed a weight, and a vector B is defined by the following for each dimension : The weight times the first dimension of it's vector + the second weight times the first dimension of it's vector etc.... and all that divided by the sum of the weights. Basically I want to find the best combination of the n vectors to form a goal vector A. But the combination is done by averaging the dimensions of the vectors. Also the weights can only take 1 or 0 as a value. I tried to use Tensorflow's gradient descent in the following way :

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

# Define the dimensions of the vectors
d = 1508
import numpy as np
import random
import math
# Define the variables
A = [random.uniform(0, 1) for _ in range(d)]
C = [[random.uniform(0, 1) for k in range(d)] for _ in range(4)]
a0 = a1 = a2 = a3 = 1
variables = [a0,a1,a2,a3]

# Define B as a linear combination of the vectors in C
B = []
for l in range(d):
    value = 0
    for i in range(4):
        value = value + variables[i] * C[i][l]
    B.append(value/sum(variables))

# Use a sigmoid activation to squash the variables to the range [0, 1]
variables = [1 / (1 + math.exp(-v)) for v in variables]

# Round the variables to 0 or 1
variables = [tf.round(v) for v in variables]
variables = [tf.Variable(v) for v in variables]

def loss(A,B):

    return 1 - tf.keras.losses.cosine_similarity(A, B)
    # Define the loss function

# Use an optimizer to minimize the loss
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)

num_steps = 100
import sys
# Run the training loop
for _ in range(num_steps):
  with tf.GradientTape() as tape:
    B = []
    for l in range(d):
      value = 0
      for i in range(4):
          value = value + variables[i] * C[i][l]
      B.append(value/sum(variables))
    loss_value = loss(A, B)
    grads = tape.gradient(loss_value, variables)

  print(loss_value)
  print(grads)
  print(len(grads))
  optimizer.apply_gradients(zip(grads, variables))
  variables = [tf.clip_by_value(v, 0, 1) for v in variables]
  variables = [tf.Variable(v) for v in variables]

In this example I used 4 weights. But for some reason I can ever get the value of the variables to be printed out and I have no clue if this is working.

That's what I've tried, I was wondering if anyone had ideas on finding best combination of vectors to reach goal vector and what they used. Also will gradient descent work for this? Also I can't get the values from the variables, .numpy doesn't work tf. print doesn't work etc... Thanks! Here is what I get from running it for a bit :

[<tf.Tensor 'AddN_1:0' shape=() dtype=float32>, <tf.Tensor 'AddN_2:0' shape=() dtype=float32>, <tf.Tensor 'AddN_3:0' shape=() dtype=float32>, <tf.Tensor 'AddN_4:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_6:0' shape=() dtype=float32>, <tf.Tensor 'AddN_7:0' shape=() dtype=float32>, <tf.Tensor 'AddN_8:0' shape=() dtype=float32>, <tf.Tensor 'AddN_9:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_11:0' shape=() dtype=float32>, <tf.Tensor 'AddN_12:0' shape=() dtype=float32>, <tf.Tensor 'AddN_13:0' shape=() dtype=float32>, <tf.Tensor 'AddN_14:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_16:0' shape=() dtype=float32>, <tf.Tensor 'AddN_17:0' shape=() dtype=float32>, <tf.Tensor 'AddN_18:0' shape=() dtype=float32>, <tf.Tensor 'AddN_19:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_21:0' shape=() dtype=float32>, <tf.Tensor 'AddN_22:0' shape=() dtype=float32>, <tf.Tensor 'AddN_23:0' shape=() dtype=float32>, <tf.Tensor 'AddN_24:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_26:0' shape=() dtype=float32>, <tf.Tensor 'AddN_27:0' shape=() dtype=float32>, <tf.Tensor 'AddN_28:0' shape=() dtype=float32>, <tf.Tensor 'AddN_29:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_31:0' shape=() dtype=float32>, <tf.Tensor 'AddN_32:0' shape=() dtype=float32>, <tf.Tensor 'AddN_33:0' shape=() dtype=float32>, <tf.Tensor 'AddN_34:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_36:0' shape=() dtype=float32>, <tf.Tensor 'AddN_37:0' shape=() dtype=float32>, <tf.Tensor 'AddN_38:0' shape=() dtype=float32>, <tf.Tensor 'AddN_39:0' shape=() dtype=float32>]
4
[<tf.Tensor 'AddN_41:0' shape=() dtype=float32>, <tf.Tensor 'AddN_42:0' shape=() dtype=float32>, <tf.Tensor 'AddN_43:0' shape=() dtype=float32>, <tf.Tensor 'AddN_44:0' shape=() dtype=float32>]
4

Thanks for the help!!!!


来源: stackexchange

问:
How to disable CORS in Azure Function App
I have a function app running on Linux (Consumption plan) with custom handler (GoLang). I have deliberately never enabled CORS, nor added any allowed origins. However OPTIONS requests are still being captured and handled and don't reach the application code. I need the OPTIONS requests to be handled by my application code. How can I disable Azure from capturing and handling those requests?

One more weird thing - if there is no Origin header present in the request, the request does actually reach my application code and respond with correct response and response headers (set by my app code). If however the Origin header is present in the request, the request never reaches the application code.

There seem to be some related issues, for instance:

https://github.com/Azure/azure-functions-host/issues/5200

Disable CORS middleware of Azure app service

https://social.msdn.microsoft.com/Forums/en-US/56ff3564-bb8c-4ff7-8920-90403cec38f6/how-to-disable-the-cors-policy-in-the-portal-overview

However none of the answers in these are particularly helpful.

How to prevent Azure from handling the CORS, if I've never enabled it in the first place?

Since this is a Linux app, there is very limited (virtually no) information available in Kudu, but here is my terraform code for the Linux Function:

```<code>resource "azurerm_service_plan" "ttAPIServicePlan" {
    name                = "tt-v2-${lower(var.ENV)}-service-plan-api"
    os_type             = "Linux"
    sku_name            = "Y1"
    resource_group_name = azurerm_resource_group.ttResourceGroup.name
    location            = azurerm_resource_group.ttResourceGroup.location
}

resource "azurerm_linux_function_app" "ttAPIFunctionApp" {
    name                       = "tt-v2-${lower(var.ENV)}-function-app-api"
    resource_group_name        = azurerm_resource_group.ttResourceGroup.name
    location                   = azurerm_resource_group.ttResourceGroup.location
    service_plan_id            = azurerm_service_plan.ttAPIServicePlan.id
    storage_account_name       = azurerm_storage_account.ttAPIStorageAccount.name
    storage_account_access_key = azurerm_storage_account.ttAPIStorageAccount.primary_access_key

    site_config {}

    app_settings = {
        # Infrastructure variables
        "FUNCTIONS_WORKER_RUNTIME"       = "custom"
        "APPINSIGHTS_INSTRUMENTATIONKEY" = azurerm_application_insights.ttAPIApplicationInsights.instrumentation_key

        # Runtime variables
        "ENV"                   = var.ENV
        "JWT_SECRET"            = var.JWT_SECRET
        "AZURE_CREDENTIAL_TYPE" = var.AZURE_CREDENTIAL_TYPE
        "CDN_BASE_URL"          = var.CDN_BASE_URL
        "CDN_ACCOUNT_URL"       = var.CDN_ACCOUNT_URL
        "CDN_CONTAINER_NAME"    = var.CDN_CONTAINER_NAME
        "MONGO_CONNECTION_URI"  = var.MONGO_CONNECTION_URI
        "MONGO_DATABASE"        = var.MONGO_DATABASE
    }
}
</code>```

And here is my host.json file:

    {
        "version": "2.0",
        "logging": {
            "applicationInsights": {
                "samplingSettings": {
                    "isEnabled": true,
                    "excludedTypes": "Request"
                }
            }
        },
        "extensionBundle": {
            "id": "Microsoft.Azure.Functions.ExtensionBundle",
            "version": "[4.0.0, 5.0.0)"
        },
        "extensions": {
            "http": {
                "routePrefix": "",
                "customHeaders": {
                    "Access-Control-Expose-Headers": "*"
                }
            }
        },
        "customHandler": {
            "enableForwardingHttpRequest": true,
            "description": {
                "defaultExecutablePath": "handler",
                "arguments": []
            }
        }
    }
```
<p>And my function.json file:</p>
<pre class="lang-json prettyprint-override"><code>{
    "bindings": [{
        "authLevel": "anonymous",
        "type": "httpTrigger",
        "direction": "in",
        "name": "req",
        "methods": [
            "options",
            "get",
            "post",
            "put",
            "patch",
            "delete"
        ],
        "route": "{*route}"
    }, {
        "type": "http",
        "direction": "out",
        "name": "res"
    }]
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a function app running on Linux (Consumption plan) with custom handler (GoLang). I have deliberately never enabled CORS, nor added any allowed origins. However OPTIONS requests are still being captured and handled and don't reach the application code. I need the OPTIONS requests to be handled by my application code. How can I disable Azure from capturing and handling those requests?

One more weird thing - if there is no Origin header present in the request, the request does actually reach my application code and respond with correct response and response headers (set by my app code). If however the Origin header is present in the request, the request never reaches the application code.

There seem to be some related issues, for instance:

https://github.com/Azure/azure-functions-host/issues/5200

Disable CORS middleware of Azure app service

https://social.msdn.microsoft.com/Forums/en-US/56ff3564-bb8c-4ff7-8920-90403cec38f6/how-to-disable-the-cors-policy-in-the-portal-overview

However none of the answers in these are particularly helpful.

How to prevent Azure from handling the CORS, if I've never enabled it in the first place?

Since this is a Linux app, there is very limited (virtually no) information available in Kudu, but here is my terraform code for the Linux Function:

resource "azurerm_service_plan" "ttAPIServicePlan" {
    name                = "tt-v2-${lower(var.ENV)}-service-plan-api"
    os_type             = "Linux"
    sku_name            = "Y1"
    resource_group_name = azurerm_resource_group.ttResourceGroup.name
    location            = azurerm_resource_group.ttResourceGroup.location
}

resource "azurerm_linux_function_app" "ttAPIFunctionApp" {
    name                       = "tt-v2-${lower(var.ENV)}-function-app-api"
    resource_group_name        = azurerm_resource_group.ttResourceGroup.name
    location                   = azurerm_resource_group.ttResourceGroup.location
    service_plan_id            = azurerm_service_plan.ttAPIServicePlan.id
    storage_account_name       = azurerm_storage_account.ttAPIStorageAccount.name
    storage_account_access_key = azurerm_storage_account.ttAPIStorageAccount.primary_access_key

    site_config {}

    app_settings = {
        # Infrastructure variables
        "FUNCTIONS_WORKER_RUNTIME"       = "custom"
        "APPINSIGHTS_INSTRUMENTATIONKEY" = azurerm_application_insights.ttAPIApplicationInsights.instrumentation_key

        # Runtime variables
        "ENV"                   = var.ENV
        "JWT_SECRET"            = var.JWT_SECRET
        "AZURE_CREDENTIAL_TYPE" = var.AZURE_CREDENTIAL_TYPE
        "CDN_BASE_URL"          = var.CDN_BASE_URL
        "CDN_ACCOUNT_URL"       = var.CDN_ACCOUNT_URL
        "CDN_CONTAINER_NAME"    = var.CDN_CONTAINER_NAME
        "MONGO_CONNECTION_URI"  = var.MONGO_CONNECTION_URI
        "MONGO_DATABASE"        = var.MONGO_DATABASE
    }
}

And here is my host.json file:

    {
        "version": "2.0",
        "logging": {
            "applicationInsights": {
                "samplingSettings": {
                    "isEnabled": true,
                    "excludedTypes": "Request"
                }
            }
        },
        "extensionBundle": {
            "id": "Microsoft.Azure.Functions.ExtensionBundle",
            "version": "[4.0.0, 5.0.0)"
        },
        "extensions": {
            "http": {
                "routePrefix": "",
                "customHeaders": {
                    "Access-Control-Expose-Headers": "*"
                }
            }
        },
        "customHandler": {
            "enableForwardingHttpRequest": true,
            "description": {
                "defaultExecutablePath": "handler",
                "arguments": []
            }
        }
    }

And my function.json file:

{
    "bindings": [{
        "authLevel": "anonymous",
        "type": "httpTrigger",
        "direction": "in",
        "name": "req",
        "methods": [
            "options",
            "get",
            "post",
            "put",
            "patch",
            "delete"
        ],
        "route": "{*route}"
    }, {
        "type": "http",
        "direction": "out",
        "name": "res"
    }]
}


问:
Mongodb connection working on local failing on server
I am able to connect to mongodb using mongoose library in nodejs.

```<code>mongoose.connect(URL, mongoConfig);
</code>```

This code is working on local but it shows following error in k8s server.

```<code>"ok": 0,
"code": 13,
"codeName": "Unauthorized"
</code>```

Body:
I am able to connect to mongodb using mongoose library in nodejs.

mongoose.connect(URL, mongoConfig);

This code is working on local but it shows following error in k8s server.

"ok": 0,
"code": 13,
"codeName": "Unauthorized"


问:
Unity: List<> OrderBy - inherited property
I have a class:

```<code>public class ItemObject : ScriptableObject
{
    int id;
    string name;
}
</code>```

and I can sort them by their id like this:

```<code>sortedItems = new List<GameObject>(allItems.OrderBy(x => x.GetComponent<InventorySlotItem>().item.id));
</code>```

but I also have the child class:

```<code>public class EquipmentObject : ItemObject
{
    int power;
    int def;
    int spDef;
}
</code>```

is there a way to use the OrderBy method for sorting them by "power" ? I was hoping for some downcasting like:

```<code>sortedItems = new List<GameObject>(allItems.OrderBy(x => (EquipmentObject)x.GetComponent<InventorySlotItem>().item.power));
</code>```

I tried to downcast in many different ways but nothing worked.

Body:
I have a class:

public class ItemObject : ScriptableObject
{
    int id;
    string name;
}

and I can sort them by their id like this:

sortedItems = new List<GameObject>(allItems.OrderBy(x => x.GetComponent<InventorySlotItem>().item.id));

but I also have the child class:

public class EquipmentObject : ItemObject
{
    int power;
    int def;
    int spDef;
}

is there a way to use the OrderBy method for sorting them by "power" ? I was hoping for some downcasting like:

sortedItems = new List<GameObject>(allItems.OrderBy(x => (EquipmentObject)x.GetComponent<InventorySlotItem>().item.power));

I tried to downcast in many different ways but nothing worked.


问:
How can I solve "Cannot find module" using Yarn?
I'm trying to deploy a nextjs project that I've updated to version 13.when I deploy the following error occurs:

```<code>> Build error occurred
Error: Cannot find module 'picocolors'
Require stack:
- C:\Users\Arotiana's\portfolio-react\node_modules\next\node_modules\postcss\lib\css-syntax-
error.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\node_modules\postcss\lib\postcss.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\dist\build\webpack\plugins\font-
stylesheet-gathering-plugin.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\dist\build\webpack-config.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\dist\build\index.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\dist\cli\next-build.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\dist\lib\commands.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\dist\bin\next
    at Module._resolveFilename (node:internal/modules/cjs/loader:995:15)
    at mod._resolveFilename (C:\Users\Arotiana's\portfolio-
    react\node_modules\next\dist\build\webpack\require-hook.js:23:32)
    at Module._load (node:internal/modules/cjs/loader:841:27)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (C:\Users\Arotiana's\portfolio-
    react\node_modules\next\node_modules\postcss\lib\css-syntax-error.js:3:12)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    "C:\\Users\\Arotiana's\\portfolio-
     react\\node_modules\\next\\node_modules\\postcss\\lib\\css-syntax-error.js",
    "C:\\Users\\Arotiana's\\portfolio-
    react\\node_modules\\next\\node_modules\\postcss\\lib\\postcss.js",
    "C:\\Users\\Arotiana's\\portfolio-
    react\\node_modules\\next\\dist\\build\\webpack\\plugins\\font-stylesheet-gathering-
    plugin.js",
    "C:\\Users\\Arotiana's\\portfolio-react\\node_modules\\next\\dist\\build\\webpack-
    config.js",
    "C:\\Users\\Arotiana's\\portfolio-react\\node_modules\\next\\dist\\build\\index.js",
    "C:\\Users\\Arotiana's\\portfolio-react\\node_modules\\next\\dist\\cli\\next-build.js",
    "C:\\Users\\Arotiana's\\portfolio-react\\node_modules\\next\\dist\\lib\\commands.js",
    "C:\\Users\\Arotiana's\\portfolio-react\\node_modules\\next\\dist\\bin\\next"
  ]
}
</code>```

I've already try tried to install picocolors but when I deploy this error alwais comes. How can I solve it?

Body:
I'm trying to deploy a nextjs project that I've updated to version 13.when I deploy the following error occurs:

> Build error occurred
Error: Cannot find module 'picocolors'
Require stack:
- C:\Users\Arotiana's\portfolio-react\node_modules\next\node_modules\postcss\lib\css-syntax-
error.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\node_modules\postcss\lib\postcss.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\dist\build\webpack\plugins\font-
stylesheet-gathering-plugin.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\dist\build\webpack-config.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\dist\build\index.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\dist\cli\next-build.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\dist\lib\commands.js
- C:\Users\Arotiana's\portfolio-react\node_modules\next\dist\bin\next
    at Module._resolveFilename (node:internal/modules/cjs/loader:995:15)
    at mod._resolveFilename (C:\Users\Arotiana's\portfolio-
    react\node_modules\next\dist\build\webpack\require-hook.js:23:32)
    at Module._load (node:internal/modules/cjs/loader:841:27)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (C:\Users\Arotiana's\portfolio-
    react\node_modules\next\node_modules\postcss\lib\css-syntax-error.js:3:12)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    "C:\\Users\\Arotiana's\\portfolio-
     react\\node_modules\\next\\node_modules\\postcss\\lib\\css-syntax-error.js",
    "C:\\Users\\Arotiana's\\portfolio-
    react\\node_modules\\next\\node_modules\\postcss\\lib\\postcss.js",
    "C:\\Users\\Arotiana's\\portfolio-
    react\\node_modules\\next\\dist\\build\\webpack\\plugins\\font-stylesheet-gathering-
    plugin.js",
    "C:\\Users\\Arotiana's\\portfolio-react\\node_modules\\next\\dist\\build\\webpack-
    config.js",
    "C:\\Users\\Arotiana's\\portfolio-react\\node_modules\\next\\dist\\build\\index.js",
    "C:\\Users\\Arotiana's\\portfolio-react\\node_modules\\next\\dist\\cli\\next-build.js",
    "C:\\Users\\Arotiana's\\portfolio-react\\node_modules\\next\\dist\\lib\\commands.js",
    "C:\\Users\\Arotiana's\\portfolio-react\\node_modules\\next\\dist\\bin\\next"
  ]
}

I've already try tried to install picocolors but when I deploy this error alwais comes. How can I solve it?


问:
Capture still images with UWP MediaCapture (PIN_CATEGORY_STILL)
An alternative title could be: What happened to PIN_CATEGORY_STILL?

I am currently comparing images that were captured using DirectShow and PIN_CATEGORY_STILL with images that were captured using UWP MediaCapture.

On the device I am testing/playing around with DirectShow and MediaCapture, DirectShow detects a PIN_CATEGORY_STILL but I am not able to initialize an instance of MediaCapture with anything other than PhotoCaptureSource.VideoPreview.

MediaCaptureInitializationSettings settings = new()
{
    VideoDeviceId = someDeviceId,
    PhotoCaptureSource = PhotoCaptureSource.Photo
};

MediaCapture capture = new();

// this throws an exception
// "The capture source does not have an independent photo stream."
await capture.InitializeAsync(settings);
```
<p>At this point I'm not even sure if <code>PhotoCaptureSource.Photo</code> is meant to be used as an equivalent to <code>PIN_CATEGORY_STILL</code>.</p>
<p>Images captured with <code>PIN_CATEGORY_STILL</code> are way brighter in a dark environment and have a much better quality (in file size and resolution) (which is clear to me, since I am using <code>PhotoCaptureSource.VideoPreview</code> for MediaCapture).</p>
<p>Considering this resource Win32 and COM for UWP apps, it seems like UWP MediaCapture does not use DirectShow underneath but MediaFoundation (which is meant to be a successor for DirectShow).</p>
<p>This article led me to this StackOverflow question Media Foundation is incorrectly marking still image capture stream descriptors as video capture, which basically states that MediaFoundation has no <code>PIN_CATEGORY_STILL</code> but returns 1 FPS as video capability for such devices (or profiles).</p>
<p>Since I am not directly using MediaFoundation nor C++, I tried testing this by querying <code>GetAvailableMediaStreamProperties</code>:</p>
<pre class="lang-cs prettyprint-override"><code>private void Foo()
{
    var videoPreviewProperties = GetEncodingProperties(MediaStreamType.VideoRecord);
    var photoProperties = GetEncodingProperties(MediaStreamType.Photo);
    var videoRecordProperties = GetEncodingProperties(MediaStreamType.VideoPreview);
}

private List<VideoEncodingProperties> GetEncodingProperties(MediaStreamType streamType)
{
    // MediaCapture was previously initialized with PhotoCaptureSource.VideoPreview
    return MediaCapture.VideoDeviceController
        .GetAvailableMediaStreamProperties(streamType)
        .OfType<VideoEncodingProperties>()
        .ToList();
}
</code>```

None of these returns a VideoEncodingProperties with only 1 FPS.

To test MediaCapture any further I tried some of the sample applications from here UWP sample. I tried CameraAdvancedCapture, CameraOpenCV and CameraManualControls, but the results were not nearly as good as good old PIN_CATEGORY_STILL.

What happened to PIN_CATEGORY_STILL?
Is there any way to capture images without DirectShow/PIN_CATEGORY_STILL and still keeping this level of quality?

Any enlightenment is much appricated.

Body:
An alternative title could be: What happened to PIN_CATEGORY_STILL?

I am currently comparing images that were captured using DirectShow and PIN_CATEGORY_STILL with images that were captured using UWP MediaCapture.

On the device I am testing/playing around with DirectShow and MediaCapture, DirectShow detects a PIN_CATEGORY_STILL but I am not able to initialize an instance of MediaCapture with anything other than PhotoCaptureSource.VideoPreview.

MediaCaptureInitializationSettings settings = new()
{
    VideoDeviceId = someDeviceId,
    PhotoCaptureSource = PhotoCaptureSource.Photo
};

MediaCapture capture = new();

// this throws an exception
// "The capture source does not have an independent photo stream."
await capture.InitializeAsync(settings);

At this point I'm not even sure if PhotoCaptureSource.Photo is meant to be used as an equivalent to PIN_CATEGORY_STILL.

Images captured with PIN_CATEGORY_STILL are way brighter in a dark environment and have a much better quality (in file size and resolution) (which is clear to me, since I am using PhotoCaptureSource.VideoPreview for MediaCapture).

Considering this resource Win32 and COM for UWP apps, it seems like UWP MediaCapture does not use DirectShow underneath but MediaFoundation (which is meant to be a successor for DirectShow).

This article led me to this StackOverflow question Media Foundation is incorrectly marking still image capture stream descriptors as video capture, which basically states that MediaFoundation has no PIN_CATEGORY_STILL but returns 1 FPS as video capability for such devices (or profiles).

Since I am not directly using MediaFoundation nor C++, I tried testing this by querying GetAvailableMediaStreamProperties:

private void Foo()
{
    var videoPreviewProperties = GetEncodingProperties(MediaStreamType.VideoRecord);
    var photoProperties = GetEncodingProperties(MediaStreamType.Photo);
    var videoRecordProperties = GetEncodingProperties(MediaStreamType.VideoPreview);
}

private List<VideoEncodingProperties> GetEncodingProperties(MediaStreamType streamType)
{
    // MediaCapture was previously initialized with PhotoCaptureSource.VideoPreview
    return MediaCapture.VideoDeviceController
        .GetAvailableMediaStreamProperties(streamType)
        .OfType<VideoEncodingProperties>()
        .ToList();
}

None of these returns a VideoEncodingProperties with only 1 FPS.

To test MediaCapture any further I tried some of the sample applications from here UWP sample. I tried CameraAdvancedCapture, CameraOpenCV and CameraManualControls, but the results were not nearly as good as good old PIN_CATEGORY_STILL.

What happened to PIN_CATEGORY_STILL?
Is there any way to capture images without DirectShow/PIN_CATEGORY_STILL and still keeping this level of quality?

Any enlightenment is much appricated.


问:
Running Test Runner is not running stepDefination file in cucumber-java junit in Eclipse
Expected-- stepDefination code should run.

Eclipse IDE Version: 2021-12 (4.22.0)

Below is my POM.xml file configuration

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>bdd</groupId>
  <artifactId>API_Projects</artifactId>
  <version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

  <name>API_Projects</name>
  <url>http://maven.apache.org</url>

<properties>
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  </properties>
 <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>

                <configuration>
                    <testFailureIgnore>true</testFailureIgnore>
                </configuration>
            </plugin>
</plugins>
 </build>

 <dependencies>

<dependency>

 <groupId>io.cucumber</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>7.0.0</version>

</dependency>

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>7.0.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest</artifactId>
    <version>2.2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.14.1</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.14.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.14.0</version>
</dependency>

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10</version>
</dependency>

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version>
</dependency>

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.19.0</version>
</dependency>

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
</dependency>

</dependencies>

</project>
</code>```

I have run TestRunner.java file using run As>> JUnit Test having below code--

```<code>@RunWith(Cucumber.class)
@CucumberOptions(features="src/test/java/features",
                 glue={"stepDefinations"},monochrome=true)
public class TestRunner {

}
</code>```

Below output is coming---

```<code>?????????????????????????????????????????????????????????????????????????????????????
? Share your Cucumber Report with your team at https://reports.cucumber.io          ?
? Activate publishing with one of the following:                                    ?
?                                                                                ?
? src/test/resources/cucumber.properties:          cucumber.publish.enabled=true    ?
? src/test/resources/junit-platform.properties:    cucumber.publish.enabled=true    ?
? Environment variable:                            CUCUMBER_PUBLISH_ENABLED=true    ?
? JUnit:                                           @CucumberOptions(publish = true) ?
?                                                                                ?
? More information at https://cucumber.io/docs/cucumber/environment-variables/      ?
?                                                                                ?
? Disable this message with one of the following:                                   ?
?                                                                                ?
? src/test/resources/cucumber.properties:          cucumber.publish.quiet=true      ?
? src/test/resources/junit-platform.properties:    cucumber.publish.quiet=true      ?
?????????????????????????????????????????????????????????????????????????????????????
</code>```

Body:
Expected-- stepDefination code should run.

Eclipse IDE Version: 2021-12 (4.22.0)

Below is my POM.xml file configuration

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>bdd</groupId>
  <artifactId>API_Projects</artifactId>
  <version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

  <name>API_Projects</name>
  <url>http://maven.apache.org</url>

<properties>
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  </properties>
 <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>

                <configuration>
                    <testFailureIgnore>true</testFailureIgnore>
                </configuration>
            </plugin>
</plugins>
 </build>

 <dependencies>

<dependency>

 <groupId>io.cucumber</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>7.0.0</version>

</dependency>

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>7.0.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest</artifactId>
    <version>2.2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.14.1</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.14.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.14.0</version>
</dependency>

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10</version>
</dependency>

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version>
</dependency>

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.19.0</version>
</dependency>

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
</dependency>

</dependencies>

</project>

I have run TestRunner.java file using run As>> JUnit Test having below code--

@RunWith(Cucumber.class)
@CucumberOptions(features="src/test/java/features",
                 glue={"stepDefinations"},monochrome=true)
public class TestRunner {

}

Below output is coming---

?????????????????????????????????????????????????????????????????????????????????????
? Share your Cucumber Report with your team at https://reports.cucumber.io          ?
? Activate publishing with one of the following:                                    ?
?                                                                                ?
? src/test/resources/cucumber.properties:          cucumber.publish.enabled=true    ?
? src/test/resources/junit-platform.properties:    cucumber.publish.enabled=true    ?
? Environment variable:                            CUCUMBER_PUBLISH_ENABLED=true    ?
? JUnit:                                           @CucumberOptions(publish = true) ?
?                                                                                ?
? More information at https://cucumber.io/docs/cucumber/environment-variables/      ?
?                                                                                ?
? Disable this message with one of the following:                                   ?
?                                                                                ?
? src/test/resources/cucumber.properties:          cucumber.publish.quiet=true      ?
? src/test/resources/junit-platform.properties:    cucumber.publish.quiet=true      ?
?????????????????????????????????????????????????????????????????????????????????????


问:
GUI Tool for creating a POS receipt
do you know of any simple tools to create a custom POS58 / thermal printer receipt design?

The tool should be able to print ASCII characters, as well as set header/footer images and print CODE128 barcodes. Choosing a custom font is also necessary.

The printer is installed as a usual printer in Windows 10.

Thank you for your favorite tools.

Title: GUI Tool for creating a POS receipt


问:
RecyclerView shows a list of copies of activity screen instead of data from database table
I am simply trying to setup the ClickListener for changing the user name. Google's tutorials emphasize fragments, which I will do later. Based on what I've seen in other examples and the Android documentation, I thought I had the View Binding set up properly. I don't have enough information to understand why I see a list of copies of the activity screen inside the RecyclerView.

UserListAdapter.kt

```<code>package com.neillbarrett.debitsandcredits

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.neillbarrett.debitsandcredits.database.UsersTable
import com.neillbarrett.debitsandcredits.databinding.ActivityManageUsersBinding

val inAdapter: String = "In UserListAdapter "

class UserListAdapter(private val userSelect: (UsersTable?) -> Unit) :
    ListAdapter<UsersTable, UserListAdapter.UserViewHolder>(UsersComparator()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserListAdapter.UserViewHolder {

        Log.w(inAdapter,"OnCreateViewHolder started")

        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.activity_manage_users, parent, false)
        return UserViewHolder.create(parent)
    }

    class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bind(usersTable: UsersTable?, userSelect: (UsersTable?) -> Unit) {

            Log.w(inAdapter,"UserViewHolder started")

            itemView.setOnClickListener { View.OnClickListener {
/*                if (View.) { }*/

                val nameSelected = userSelect(usersTable)
                //userSelect(usersTable)
                //need to assign the result of the clicklistener to the editText
                //binding.etEditName.setText(R.layout.activity_list_of_users.toString())
            }}
        }

        companion object {
            fun create(parent: ViewGroup) : UserViewHolder {

                Log.w(inAdapter,"Companion object 'Create' function started")

                val view: View = LayoutInflater.from(parent.context)
                    .inflate(R.layout.activity_manage_users, parent, false)
                return UserViewHolder(view)
            }
        }
    }

    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
        Log.w(inAdapter,"OnBindViewHolder started")

        val current = getItem(position)
        holder.bind(current, userSelect)
    }

    class UsersComparator : DiffUtil.ItemCallback<UsersTable>() {
        override fun areItemsTheSame(oldItem: UsersTable, newItem: UsersTable): Boolean {
            Log.w(inAdapter,"areItemsTheSame function started")
            return oldItem == newItem
        }

        override fun areContentsTheSame(oldItem: UsersTable, newItem: UsersTable): Boolean {
            Log.w(inAdapter,"areContentsTheSame function started")
            return oldItem.userName == newItem.userName
        }
    }
}
</code>```

ManageUsers.kt

```<code>package com.neillbarrett.debitsandcredits

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.neillbarrett.debitsandcredits.database.CreditsAndDebitsApp
import com.neillbarrett.debitsandcredits.database.UsersTable
import com.neillbarrett.debitsandcredits.databinding.ActivityManageUsersBinding

class ManageUsers : AppCompatActivity() {

    lateinit var binding: ActivityManageUsersBinding
    lateinit var recyclerView: RecyclerView
    lateinit var editTextAddUser: EditText
    lateinit var editTextChangeUser: EditText
    lateinit var newUser: String
    var userSelect: ((UsersTable?) -> Unit) = {}
    var position: Long = 0
    val inWhichActivity: String = "In ManageUsers"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityManageUsersBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        //setContentView(R.layout.activity_manage_users)

        Log.w(inWhichActivity, "Setting up userViewModel & repository")
        val userViewModel: UserViewModel by viewModels {
            UserViewModelFactory((application as CreditsAndDebitsApp).repository)
        }

        recyclerView = findViewById(R.id.rec_view_userList)
        editTextAddUser = findViewById(R.id.et_AddUser)
        editTextChangeUser = findViewById(R.id.et_Edit_Name)

        val adapter = UserListAdapter(userSelect)
        binding.recViewUserList.adapter = adapter
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

        userViewModel.allUsers.observe(this, Observer() {user ->
            Log.w(inWhichActivity,"Starting Observer")
            user?.let { adapter.submitList(it) }
            Log.w(inWhichActivity, "Started Observer")
        })

        val btnAddUser = findViewById<Button>(R.id.btn_AddUser)
        btnAddUser.setOnClickListener {
            Log.w(inWhichActivity,"Started btnAddUser.setOnClickListener")
            if (TextUtils.isEmpty(editTextAddUser.text)) {
                Toast.makeText(this, "User name cannot be empty", Toast.LENGTH_SHORT).show()
            } else {
                newUser = editTextAddUser.text.toString()
//                Log.w("Add user button", "Username put into newUser")
                userViewModel.insertUser(UsersTable(0, newUser))
//                Toast.makeText(this, "Username added to table", Toast.LENGTH_SHORT).show()
//                Log.w("Add user button", "Username added to table")
            }
        }

        val btnChangeUser = findViewById<Button>(R.id.btn_ChangeUserName)
        btnChangeUser.setOnClickListener {
            Log.w(inWhichActivity,"Started btnChangeUser.setOnClickListener")
            Toast.makeText(this, "Selected position is ${recyclerView.getChildAdapterPosition(it)}", Toast.LENGTH_SHORT).show()
/*            if (recyclerView.getChildAdapterPosition(it) == -1) {
                Toast.makeText(this, "Select a name.", Toast.LENGTH_SHORT).show()
            } else {
                if (editTextChangeUser.text.toString() == recyclerView.adapter.toString()) {
                    Toast.makeText(this, "Name has not been changed.", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "Name would have been changed.", Toast.LENGTH_SHORT).show()
                    val rvItemRecId: Long
                    rvItemRecId = adapter.getItemId(position.toInt())
                    userViewModel.updateUser(UsersTable(rvItemRecId.toInt(), adapter.toString()))
                }
            }*/
        }
    }
}

</code>```

UserViewModel.kt

```<code>package com.neillbarrett.debitsandcredits

import android.util.Log
import androidx.lifecycle.*
import com.neillbarrett.debitsandcredits.database.UsersTable
import kotlinx.coroutines.launch
import java.lang.IllegalArgumentException

val inViewModel: String = "In UserViewModel "

class UserViewModel(private val repository: UserRepository) : ViewModel() {

    // Using LiveData and caching what allWords returns has several benefits:
    // - We can put an observer on the data (instead of polling for changes) and only update the
    //   the UI when the data actually changes.
    // - Repository is completely separated from the UI through the ViewModel.
    val allUsers: LiveData<List<UsersTable>> = repository.allUsers.asLiveData()
    /**
     * Launching a new coroutine to insert the data in a non-blocking way
     */

    fun insertUser(user: UsersTable) = viewModelScope.launch {
        repository.insertUser(user)
        Log.w(inViewModel,"insertUser called")
    //repository.insertUser(usersTable = List<UsersTable>())
    //repository.insertUser(UsersTable(0, userName = user.userName))
    }

    fun updateUser(user: UsersTable) = viewModelScope.launch {
        repository.updateUser(user)
        Log.w(inViewModel, "updateUser called")
    }

    fun deleteUser(user: UsersTable) = viewModelScope.launch {
        repository.deleteUser(user)
        Log.w(inViewModel, "deteUser called")
    }
}

class UserViewModelFactory(private val repository: UserRepository) : ViewModelProvider.Factory{
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        Log.w(inViewModel,"UserViewModelFactory called")
        if (modelClass.isAssignableFrom(UserViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return UserViewModel(repository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}
</code>```

Body:
I am simply trying to setup the ClickListener for changing the user name. Google's tutorials emphasize fragments, which I will do later. Based on what I've seen in other examples and the Android documentation, I thought I had the View Binding set up properly. I don't have enough information to understand why I see a list of copies of the activity screen inside the RecyclerView.

UserListAdapter.kt

package com.neillbarrett.debitsandcredits

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.neillbarrett.debitsandcredits.database.UsersTable
import com.neillbarrett.debitsandcredits.databinding.ActivityManageUsersBinding

val inAdapter: String = "In UserListAdapter "

class UserListAdapter(private val userSelect: (UsersTable?) -> Unit) :
    ListAdapter<UsersTable, UserListAdapter.UserViewHolder>(UsersComparator()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserListAdapter.UserViewHolder {

        Log.w(inAdapter,"OnCreateViewHolder started")

        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.activity_manage_users, parent, false)
        return UserViewHolder.create(parent)
    }

    class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bind(usersTable: UsersTable?, userSelect: (UsersTable?) -> Unit) {

            Log.w(inAdapter,"UserViewHolder started")

            itemView.setOnClickListener { View.OnClickListener {
/*                if (View.) { }*/

                val nameSelected = userSelect(usersTable)
                //userSelect(usersTable)
                //need to assign the result of the clicklistener to the editText
                //binding.etEditName.setText(R.layout.activity_list_of_users.toString())
            }}
        }

        companion object {
            fun create(parent: ViewGroup) : UserViewHolder {

                Log.w(inAdapter,"Companion object 'Create' function started")

                val view: View = LayoutInflater.from(parent.context)
                    .inflate(R.layout.activity_manage_users, parent, false)
                return UserViewHolder(view)
            }
        }
    }

    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
        Log.w(inAdapter,"OnBindViewHolder started")

        val current = getItem(position)
        holder.bind(current, userSelect)
    }

    class UsersComparator : DiffUtil.ItemCallback<UsersTable>() {
        override fun areItemsTheSame(oldItem: UsersTable, newItem: UsersTable): Boolean {
            Log.w(inAdapter,"areItemsTheSame function started")
            return oldItem == newItem
        }

        override fun areContentsTheSame(oldItem: UsersTable, newItem: UsersTable): Boolean {
            Log.w(inAdapter,"areContentsTheSame function started")
            return oldItem.userName == newItem.userName
        }
    }
}

ManageUsers.kt

package com.neillbarrett.debitsandcredits

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.neillbarrett.debitsandcredits.database.CreditsAndDebitsApp
import com.neillbarrett.debitsandcredits.database.UsersTable
import com.neillbarrett.debitsandcredits.databinding.ActivityManageUsersBinding

class ManageUsers : AppCompatActivity() {

    lateinit var binding: ActivityManageUsersBinding
    lateinit var recyclerView: RecyclerView
    lateinit var editTextAddUser: EditText
    lateinit var editTextChangeUser: EditText
    lateinit var newUser: String
    var userSelect: ((UsersTable?) -> Unit) = {}
    var position: Long = 0
    val inWhichActivity: String = "In ManageUsers"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityManageUsersBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        //setContentView(R.layout.activity_manage_users)

        Log.w(inWhichActivity, "Setting up userViewModel & repository")
        val userViewModel: UserViewModel by viewModels {
            UserViewModelFactory((application as CreditsAndDebitsApp).repository)
        }

        recyclerView = findViewById(R.id.rec_view_userList)
        editTextAddUser = findViewById(R.id.et_AddUser)
        editTextChangeUser = findViewById(R.id.et_Edit_Name)

        val adapter = UserListAdapter(userSelect)
        binding.recViewUserList.adapter = adapter
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

        userViewModel.allUsers.observe(this, Observer() {user ->
            Log.w(inWhichActivity,"Starting Observer")
            user?.let { adapter.submitList(it) }
            Log.w(inWhichActivity, "Started Observer")
        })

        val btnAddUser = findViewById<Button>(R.id.btn_AddUser)
        btnAddUser.setOnClickListener {
            Log.w(inWhichActivity,"Started btnAddUser.setOnClickListener")
            if (TextUtils.isEmpty(editTextAddUser.text)) {
                Toast.makeText(this, "User name cannot be empty", Toast.LENGTH_SHORT).show()
            } else {
                newUser = editTextAddUser.text.toString()
//                Log.w("Add user button", "Username put into newUser")
                userViewModel.insertUser(UsersTable(0, newUser))
//                Toast.makeText(this, "Username added to table", Toast.LENGTH_SHORT).show()
//                Log.w("Add user button", "Username added to table")
            }
        }

        val btnChangeUser = findViewById<Button>(R.id.btn_ChangeUserName)
        btnChangeUser.setOnClickListener {
            Log.w(inWhichActivity,"Started btnChangeUser.setOnClickListener")
            Toast.makeText(this, "Selected position is ${recyclerView.getChildAdapterPosition(it)}", Toast.LENGTH_SHORT).show()
/*            if (recyclerView.getChildAdapterPosition(it) == -1) {
                Toast.makeText(this, "Select a name.", Toast.LENGTH_SHORT).show()
            } else {
                if (editTextChangeUser.text.toString() == recyclerView.adapter.toString()) {
                    Toast.makeText(this, "Name has not been changed.", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "Name would have been changed.", Toast.LENGTH_SHORT).show()
                    val rvItemRecId: Long
                    rvItemRecId = adapter.getItemId(position.toInt())
                    userViewModel.updateUser(UsersTable(rvItemRecId.toInt(), adapter.toString()))
                }
            }*/
        }
    }
}

UserViewModel.kt

package com.neillbarrett.debitsandcredits

import android.util.Log
import androidx.lifecycle.*
import com.neillbarrett.debitsandcredits.database.UsersTable
import kotlinx.coroutines.launch
import java.lang.IllegalArgumentException

val inViewModel: String = "In UserViewModel "

class UserViewModel(private val repository: UserRepository) : ViewModel() {

    // Using LiveData and caching what allWords returns has several benefits:
    // - We can put an observer on the data (instead of polling for changes) and only update the
    //   the UI when the data actually changes.
    // - Repository is completely separated from the UI through the ViewModel.
    val allUsers: LiveData<List<UsersTable>> = repository.allUsers.asLiveData()
    /**
     * Launching a new coroutine to insert the data in a non-blocking way
     */

    fun insertUser(user: UsersTable) = viewModelScope.launch {
        repository.insertUser(user)
        Log.w(inViewModel,"insertUser called")
    //repository.insertUser(usersTable = List<UsersTable>())
    //repository.insertUser(UsersTable(0, userName = user.userName))
    }

    fun updateUser(user: UsersTable) = viewModelScope.launch {
        repository.updateUser(user)
        Log.w(inViewModel, "updateUser called")
    }

    fun deleteUser(user: UsersTable) = viewModelScope.launch {
        repository.deleteUser(user)
        Log.w(inViewModel, "deteUser called")
    }
}

class UserViewModelFactory(private val repository: UserRepository) : ViewModelProvider.Factory{
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        Log.w(inViewModel,"UserViewModelFactory called")
        if (modelClass.isAssignableFrom(UserViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return UserViewModel(repository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}


问:
Mongodb not starting up after installation
I installed mongodb 5.0.14 on ec2 instance

I followed this tutorial

```<code>sudo apt install -y software-properties-common gnupg apt-transport-https ca-certificates

wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list

sudo apt update

sudo apt install -y mongodb-org

sudo systemctl start mongod

sudo systemctl status mongod
</code>```

But I get this error on the picture below

Body:
I installed mongodb 5.0.14 on ec2 instance

I followed this tutorial

sudo apt install -y software-properties-common gnupg apt-transport-https ca-certificates

wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list

sudo apt update

sudo apt install -y mongodb-org

sudo systemctl start mongod

sudo systemctl status mongod

But I get this error on the picture below


问:
Connect Android app to Firebase Auth emulator without allowing cleartext HTTP traffic
I have a Flutter application that uses Firebase as its back-end. I use Firebase emulators to test my app in debug mode.

In order to allow physical devices to connect to the emulators I run on my development machine, I've changed the configuration so that the emulators run using that machine's local IP on my local network. (I specify this IP via a Dart environment variable.)

firebase.json

{
  // ...
  "emulators": {
    "auth": {
      "host": "0.0.0.0",  // this is to avoid having to hard-code my local IP, which might change
      "port": 9099
    },
    "firestore": {
      "host": "0.0.0.0",
      "port": 8080
    },
    // ...
  }
}

```
<p><code>main.dart</code></p>
<pre class="lang-dart prettyprint-override"><code>if (kDebugMode) {
  const emulatorHost =
      String.fromEnvironment("EMULATOR_HOST", defaultValue: "localhost");
  FirebaseAuth.instance.useAuthEmulator(emulatorHost, 9099);
  FirebaseFirestore.instance.useFirestoreEmulator(emulatorHost, 8080);
}
</code>```

To test the web version on my app, I start the emulators and run the web app through Android Studio, all on the same app. The app is able to communicate with the Auth emulator, no problem.

However, when I run the app in debug mode on my physical Android device or on an Android emulator, whenever it tries to communicate to the Auth emulator (namely in the sign-in screen, which is given by firebase_ui_auth), I get this error:

```<code>com.google.firebase.FirebaseException: An internal error has occurred. [ Cleartext HTTP traffic to <my local ip> not permitted ]
</code>```

(Curiously, this only happens with the Auth emulator, because if I bypass any auth functionality, the Android app connects without problems to the Firestore emulator.)

As far as I understand, this means the app is trying to communicate to the emulator via non-encrypted HTTP traffic, which Android doesn't allow (for this app configuration).

The suggested solutions I've seen (Error connecting to local Firebase functions emulator from Flutter app, Flutter Cleartext HTTP traffic not permitted) all involve removing this restriction, either by allowing clear-text HTTP traffic app-wide

<application android:usesCleartextTraffic="true" />
```
<p>or by just allowing clear text traffic to the specific IP the emulators are running on</p>
<pre class="lang-xml prettyprint-override"><code><network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain>10.0.2.2</domain>
    </domain-config>
</network-security-config>
</code>```

I do not want to use either of these solutions, because I don't want to enable clear-text HTTP just because I need it for local testing with Firebase emulators, and I don't want to have to hard-code my local IP, which might change, in an Android xml file somewhere.

Is there an alternative solution that doesn't have these issues? Can I make the SDK connect to the emulator via HTTPS, for example?

As a temporary solution/band-aid, for now I'm enabling clear-text HTTP app-wide but only for the debug flavour of the app, by applying the solution mentioned above to the Android manifest in android/app/src/debug instead of android/app/src/main.

Body:
I have a Flutter application that uses Firebase as its back-end. I use Firebase emulators to test my app in debug mode.

In order to allow physical devices to connect to the emulators I run on my development machine, I've changed the configuration so that the emulators run using that machine's local IP on my local network. (I specify this IP via a Dart environment variable.)

firebase.json

{
  // ...
  "emulators": {
    "auth": {
      "host": "0.0.0.0",  // this is to avoid having to hard-code my local IP, which might change
      "port": 9099
    },
    "firestore": {
      "host": "0.0.0.0",
      "port": 8080
    },
    // ...
  }
}

main.dart

if (kDebugMode) {
  const emulatorHost =
      String.fromEnvironment("EMULATOR_HOST", defaultValue: "localhost");
  FirebaseAuth.instance.useAuthEmulator(emulatorHost, 9099);
  FirebaseFirestore.instance.useFirestoreEmulator(emulatorHost, 8080);
}

To test the web version on my app, I start the emulators and run the web app through Android Studio, all on the same app. The app is able to communicate with the Auth emulator, no problem.

However, when I run the app in debug mode on my physical Android device or on an Android emulator, whenever it tries to communicate to the Auth emulator (namely in the sign-in screen, which is given by firebase_ui_auth), I get this error:

com.google.firebase.FirebaseException: An internal error has occurred. [ Cleartext HTTP traffic to <my local ip> not permitted ]

(Curiously, this only happens with the Auth emulator, because if I bypass any auth functionality, the Android app connects without problems to the Firestore emulator.)

As far as I understand, this means the app is trying to communicate to the emulator via non-encrypted HTTP traffic, which Android doesn't allow (for this app configuration).

The suggested solutions I've seen (Error connecting to local Firebase functions emulator from Flutter app, Flutter Cleartext HTTP traffic not permitted) all involve removing this restriction, either by allowing clear-text HTTP traffic app-wide

<application android:usesCleartextTraffic="true" />

or by just allowing clear text traffic to the specific IP the emulators are running on

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain>10.0.2.2</domain>
    </domain-config>
</network-security-config>

I do not want to use either of these solutions, because I don't want to enable clear-text HTTP just because I need it for local testing with Firebase emulators, and I don't want to have to hard-code my local IP, which might change, in an Android xml file somewhere.

Is there an alternative solution that doesn't have these issues? Can I make the SDK connect to the emulator via HTTPS, for example?

As a temporary solution/band-aid, for now I'm enabling clear-text HTTP app-wide but only for the debug flavour of the app, by applying the solution mentioned above to the Android manifest in android/app/src/debug instead of android/app/src/main.


问:
How to host an express API on hostinger
How do I host an API on Hostinger, because upon me uploading the file it just shows the raw text of the API and doesn't do the supposed actions</p>

Title: How to host an express API on hostinger


问:
How can I know where are Reads Writes in firebase
I am a new subscriber to Firebase, and I have unexpected reads in my database. And I'd like to know where the readings are done, specifically in which document or collection to identify the problem.
Is there a way to access this information?</p>


问:
WCF or ASP.NET Web API AJAX Duplex Service with Callback and One Way Communications
I'd like an ASP.NET C# WCF or Web API AJAX Web Service with full duplex communications with a callback for one way operations that works over AJAX.

```<code>(IsOneWay = true)
</code>```

and

```<code>(CallbackContract = typeof(IServiceCallback))
</code>```

I've read that WCF webHttpBinding can't support Duplex communications, but this is the default for creating a WCF AJAX enabled web service in Visual Studio. I've also read that ASP.NET Web API is replacing WCF. However, Web API is only request/response communications and is not duplex.

Is there a way for an AJAX Duplex web service or a way for the server can block communications until a server event happens or a function is called?

webHttpBinding with  in the endpoint behavior didn't work. wsDualHttpBinding didn't work for javascript

Body:
I'd like an ASP.NET C# WCF or Web API AJAX Web Service with full duplex communications with a callback for one way operations that works over AJAX.

(IsOneWay = true)

and

(CallbackContract = typeof(IServiceCallback))

I've read that WCF webHttpBinding can't support Duplex communications, but this is the default for creating a WCF AJAX enabled web service in Visual Studio. I've also read that ASP.NET Web API is replacing WCF. However, Web API is only request/response communications and is not duplex.

Is there a way for an AJAX Duplex web service or a way for the server can block communications until a server event happens or a function is called?

webHttpBinding with  in the endpoint behavior didn't work. wsDualHttpBinding didn't work for javascript


问:
Error with the E/libEGL cant make a get request
im a begginer Android Developer, trying to make an APP, but
My app is giving an error:
E/libEGL: call to OpenGL ES API with no current context (logged once per thread)

when i try to make a get REQUEST, so it sometimes can make that get go trought, but many times, just get stuck there and cant do anything.

my GET request is here:

```<code> StringRequest request = new StringRequest(Request.Method.GET, url_assets, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.e("AssetPlant", response);
                List<Feature> featuresListSN = new ArrayList<>();
                fc = FeatureCollection.fromJson(response);
                Log.e("AssetPlantFC", fc.toString());
                List<Feature> featuresListAll = null;
                List<Feature> featuresListWITHSN = null;

                for (int i = 0; i < fc.features().size(); i++){
                    String moduleID = fc.features().get(i).getStringProperty("id");
                    String moduleName = fc.features().get(i).getStringProperty("name");
                    String modulePVM = fc.features().get(i).getStringProperty("pvm");
                    String moduleFinalName = moduleName + "_" + modulePVM;
                    String moduleSN = fc.features().get(i).getStringProperty("sn");
                }

                featuresListAll = fc.features();
                featuresListWITHSN = fc.features();

                if(featuresListAll != null){
                    fSize = featuresListAll.size();
                    for(int i = 0; i < fSize; i++){
                        if(!Objects.equals(featuresListAll.get(i).getStringProperty("sn"), "")){
                            featuresListSN.add(featuresListAll.get(i));
                            String barcode_string = featuresListAll.get(i).getStringProperty("sn");
                            serial_number_list.add(barcode_string);
                        }
                        if (i+1 == fSize){
                            Log.e("FOR LOOP", "ENDED");
                            FeatureCollection fc_SN = FeatureCollection.fromFeatures(featuresListSN);
                            fc = FeatureCollection.fromFeatures(featuresListAll);
                            all_barcodes_list = serial_number_list;
                            arrayAsString_SN = new Gson().toJson(fc_SN);
                            arrayAsString = new Gson().toJson(fc);
                            goNext(feature);
                        }
                    }

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if(error.networkResponse.statusCode == 403 || error.networkResponse.statusCode == 401){
                    Toast.makeText(LoadingMapActivity.this, "Session ended", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(LoadingMapActivity.this, "Failed to gather info" + error.networkResponse.statusCode, Toast.LENGTH_SHORT).show();
                }
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("Authorization", "Bearer " + token);
                return headers;
            }
        };
        Log.e("ADDED GET PLANT", "TO THE QUEUE:");

        request.setRetryPolicy(new DefaultRetryPolicy(
                6000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES*2,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        VolleySingleton.getInstance(LoadingMapActivity.this).addToRequestQueue(request);
</code>```

I've already tryed many things, like making it run in another thread and give a call back when it get the response, but it get stuck anyway, and i cant figure out why this is happening.

Body:
im a begginer Android Developer, trying to make an APP, but
My app is giving an error:
E/libEGL: call to OpenGL ES API with no current context (logged once per thread)

when i try to make a get REQUEST, so it sometimes can make that get go trought, but many times, just get stuck there and cant do anything.

my GET request is here:

 StringRequest request = new StringRequest(Request.Method.GET, url_assets, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.e("AssetPlant", response);
                List<Feature> featuresListSN = new ArrayList<>();
                fc = FeatureCollection.fromJson(response);
                Log.e("AssetPlantFC", fc.toString());
                List<Feature> featuresListAll = null;
                List<Feature> featuresListWITHSN = null;

                for (int i = 0; i < fc.features().size(); i++){
                    String moduleID = fc.features().get(i).getStringProperty("id");
                    String moduleName = fc.features().get(i).getStringProperty("name");
                    String modulePVM = fc.features().get(i).getStringProperty("pvm");
                    String moduleFinalName = moduleName + "_" + modulePVM;
                    String moduleSN = fc.features().get(i).getStringProperty("sn");
                }

                featuresListAll = fc.features();
                featuresListWITHSN = fc.features();

                if(featuresListAll != null){
                    fSize = featuresListAll.size();
                    for(int i = 0; i < fSize; i++){
                        if(!Objects.equals(featuresListAll.get(i).getStringProperty("sn"), "")){
                            featuresListSN.add(featuresListAll.get(i));
                            String barcode_string = featuresListAll.get(i).getStringProperty("sn");
                            serial_number_list.add(barcode_string);
                        }
                        if (i+1 == fSize){
                            Log.e("FOR LOOP", "ENDED");
                            FeatureCollection fc_SN = FeatureCollection.fromFeatures(featuresListSN);
                            fc = FeatureCollection.fromFeatures(featuresListAll);
                            all_barcodes_list = serial_number_list;
                            arrayAsString_SN = new Gson().toJson(fc_SN);
                            arrayAsString = new Gson().toJson(fc);
                            goNext(feature);
                        }
                    }

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if(error.networkResponse.statusCode == 403 || error.networkResponse.statusCode == 401){
                    Toast.makeText(LoadingMapActivity.this, "Session ended", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(LoadingMapActivity.this, "Failed to gather info" + error.networkResponse.statusCode, Toast.LENGTH_SHORT).show();
                }
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("Authorization", "Bearer " + token);
                return headers;
            }
        };
        Log.e("ADDED GET PLANT", "TO THE QUEUE:");

        request.setRetryPolicy(new DefaultRetryPolicy(
                6000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES*2,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        VolleySingleton.getInstance(LoadingMapActivity.this).addToRequestQueue(request);

I've already tryed many things, like making it run in another thread and give a call back when it get the response, but it get stuck anyway, and i cant figure out why this is happening.


问:
why my project is trying tu add to the commit other folders?
I'm trying to push my changes as always I did but this time is trying to push all the folders that are outside the project and I don't know why

[Directories that is trying to add to the push] (https://i.stack.imgur.com/Edfc9.png)

[Directory where is all folders] (https://i.stack.imgur.com/5vQxR.png)

I deleted the repository and created a new one but it has the same problems

I used git remote -v to know if I'm in the right repository and yes I am.

What it tells me when I want to push

part of above picture ben then as TEXT:

```<code>PS C:\ecommercejib> git push --set-upstream origin main
To https://github.can/JuanIgnacioBe11avitis/ecommercejib
! [rejected]   main -Y main (non-fast-forward)
error: failed to push some refs to 'https://github.com/JuanIgnacioBe11avitis/ecommercejib'
hint : Updates were rejected because the tip of your current branch is behind
hint : its remote counterpart. Integrate the remote changes (e.g.
hint : 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
PS C:\ecommerjic>
</code>```

Body:
I'm trying to push my changes as always I did but this time is trying to push all the folders that are outside the project and I don't know why

[Directories that is trying to add to the push] (https://i.stack.imgur.com/Edfc9.png)

[Directory where is all folders] (https://i.stack.imgur.com/5vQxR.png)

I deleted the repository and created a new one but it has the same problems

I used git remote -v to know if I'm in the right repository and yes I am.

What it tells me when I want to push

part of above picture ben then as TEXT:

PS C:\ecommercejib> git push --set-upstream origin main
To https://github.can/JuanIgnacioBe11avitis/ecommercejib
! [rejected]   main -Y main (non-fast-forward)
error: failed to push some refs to 'https://github.com/JuanIgnacioBe11avitis/ecommercejib'
hint : Updates were rejected because the tip of your current branch is behind
hint : its remote counterpart. Integrate the remote changes (e.g.
hint : 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
PS C:\ecommerjic>


问:
How to edit the Dokani theme to add random vendor section
The Dokani theme comes with a section on the front page with NEW vendors,

I am unable to find the function, but i´d like to modify it to give me a random vendor from the id, maybe?

```<code><?php
                $new_sellers = dokan()->vendor->all( array( 'order' => 'DESC', 'number' => 8 ) );

                if ( $new_sellers ) { ?>
                    <input type="radio" name="tabs" id="latest-store">
                    <label for="latest-store"><?php esc_html_e( 'New', 'dokani' ); ?></label>

                    <div class="tab">
                        <?php
                        $image_size    = 'single-vendor-thumb';
                        $template_args = array(
                            'sellers'    => $new_sellers,
                            'per_row'    => 4,
                            'image_size' => $image_size,
                        );

                        dokan_get_template_part( 'new-store-lists-loop', false, $template_args );
                        ?>
                    </div>
                <?php } ?>
</code>```

I was thinking in modifying this:

```<code>$new_sellers = dokan()->vendor->all( array( 'order' => 'DESC', 'number' => 8 ) );
</code>```

But I don´t know if this will be enough :(

Body:
The Dokani theme comes with a section on the front page with NEW vendors,

I am unable to find the function, but i´d like to modify it to give me a random vendor from the id, maybe?

<?php
                $new_sellers = dokan()->vendor->all( array( 'order' => 'DESC', 'number' => 8 ) );

                if ( $new_sellers ) { ?>
                    <input type="radio" name="tabs" id="latest-store">
                    <?php esc_html_e( 'New', 'dokani' ); ?>

                        <?php
                        $image_size    = 'single-vendor-thumb';
                        $template_args = array(
                            'sellers'    => $new_sellers,
                            'per_row'    => 4,
                            'image_size' => $image_size,
                        );

                        dokan_get_template_part( 'new-store-lists-loop', false, $template_args );
                        ?>

                <?php } ?>

I was thinking in modifying this:

$new_sellers = dokan()->vendor->all( array( 'order' => 'DESC', 'number' => 8 ) );

But I don´t know if this will be enough :(


问:
macOS: copying a file on a SMB filesystem
I have a RAID disk which makes its files available over CIFS/SMB. If I copy a large file (600MB) from one location on the volume to another location on the same volume using Finder (i.e., option-drag the file), it only takes a second or two.

If I try to do the same operation programmatically using the code below, it takes upwards of a minute.

```<code>let source = URL(filePath: "/Volumes/media/tmp/bigfile.dat")
let dest = URL(filePath: "/Volumes/media/finaldest/file.dat")
try FileManager.default.copyItem(at: source, to: dest)
</code>```

My theory is that Finder can detect that the source and destination are on the same network volume and uses a special SMB API to do the copying server side, without having to move a bunch of bytes back and forth over the network. FileManager does not have this same optimization.

Does anybody have suggestions on how I can make my program behave like the Finder does?

Body:
I have a RAID disk which makes its files available over CIFS/SMB. If I copy a large file (600MB) from one location on the volume to another location on the same volume using Finder (i.e., option-drag the file), it only takes a second or two.

If I try to do the same operation programmatically using the code below, it takes upwards of a minute.

let source = URL(filePath: "/Volumes/media/tmp/bigfile.dat")
let dest = URL(filePath: "/Volumes/media/finaldest/file.dat")
try FileManager.default.copyItem(at: source, to: dest)

My theory is that Finder can detect that the source and destination are on the same network volume and uses a special SMB API to do the copying server side, without having to move a bunch of bytes back and forth over the network. FileManager does not have this same optimization.

Does anybody have suggestions on how I can make my program behave like the Finder does?


问:
win32 c++ how to make a window resizable by dragging the sides but with no frame, or border
The only way I can have a window with no borders is by using no style, just using WS_POPUP. If I use WS_THICKFRAME I have the resize functionality but it adds a gray bar at the top (not the title bar, it is just a gray bar about 5px height).

This code here is supposed to show the sizing arrows but it is not working:

```<code>case WM_NCHITTEST:
{

    POINTS pt = MAKEPOINTS(lParam);

    RECT rc;
    GetWindowRect(hwnd, &rc);

    if (pt.x >= rc.left && pt.x < rc.left + 5)
    {
        return HTLEFT;
    }
    else if (pt.x < rc.right && pt.x >= rc.right - 5)
    {
        return HTRIGHT;
    }
    else if (pt.y >= rc.top && pt.y < rc.top + 5)
    {
        return HTTOP;
    }
    else if (pt.y < rc.bottom && pt.y >= rc.bottom - 5)
    {
        return HTBOTTOM;
    }
    return HTCLIENT;
}
</code>```

Body:
The only way I can have a window with no borders is by using no style, just using WS_POPUP. If I use WS_THICKFRAME I have the resize functionality but it adds a gray bar at the top (not the title bar, it is just a gray bar about 5px height).

This code here is supposed to show the sizing arrows but it is not working:

case WM_NCHITTEST:
{

    POINTS pt = MAKEPOINTS(lParam);

    RECT rc;
    GetWindowRect(hwnd, &rc);

    if (pt.x >= rc.left && pt.x < rc.left + 5)
    {
        return HTLEFT;
    }
    else if (pt.x < rc.right && pt.x >= rc.right - 5)
    {
        return HTRIGHT;
    }
    else if (pt.y >= rc.top && pt.y < rc.top + 5)
    {
        return HTTOP;
    }
    else if (pt.y < rc.bottom && pt.y >= rc.bottom - 5)
    {
        return HTBOTTOM;
    }
    return HTCLIENT;
}


问:
Jest Twilio Mock
I would like to know how do I mock a Twilio function inside a lib.

I need help taking the test

If anyone has any ideas thanks

I have this method:

```<code>joinSession(data: ICallConfig) {
    const token = data.providerData.Token.toString();
    this._sessionId = data.sessionId;
    this._localConnectionId = data.providerData.CustomerId;

    const videoCallOptions = {
      name: data.providerData.RoomName,
      tracks: this._stream.getTracks(),
    };

    try {
      this._room = await connect(token, videoCallOptions);
    } catch (e) {
      console.log('Twilio video error: ' + e);
    }
</code>```
```<code>I need to mock twilio's connect() function
</code>```

My test:

```<code>describe('joinSession', () => {
  test('connect user in room', () => {
    // Create object
    const data: ICallConfig = {
      providerData: {
        Token: '',
        CustomerId: '',
        RoomName: 'Room Test',
      },
      sessionId: '',
    };

    mockMediaStream.addTrack(new MockTrack('audio'));
    mockMediaStream.addTrack(new MockTrack('video'));

    twilioService.setMediaStream(mockMediaStream);

    twilioService.joinSession(data);
  });
</code>```

Title: Jest Twilio Mock

Body:
I would like to know how do I mock a Twilio function inside a lib.

I need help taking the test

If anyone has any ideas thanks

I have this method:

joinSession(data: ICallConfig) {
    const token = data.providerData.Token.toString();
    this._sessionId = data.sessionId;
    this._localConnectionId = data.providerData.CustomerId;

    const videoCallOptions = {
      name: data.providerData.RoomName,
      tracks: this._stream.getTracks(),
    };

    try {
      this._room = await connect(token, videoCallOptions);
    } catch (e) {
      console.log('Twilio video error: ' + e);
    }

I need to mock twilio's connect() function

My test:

describe('joinSession', () => {
  test('connect user in room', () => {
    // Create object
    const data: ICallConfig = {
      providerData: {
        Token: '',
        CustomerId: '',
        RoomName: 'Room Test',
      },
      sessionId: '',
    };

    mockMediaStream.addTrack(new MockTrack('audio'));
    mockMediaStream.addTrack(new MockTrack('video'));

    twilioService.setMediaStream(mockMediaStream);

    twilioService.joinSession(data);
  });


问:
Duplicate Resources for strings.xml and values.xml in app build
While adding default_web_client_id as a string resource in strings.xml, I encountered an error Duplicate Resources with build generated values.xml. I tried to delete the build generated default_web_client_id but the Duplicate Resouces error won't go away. I don't want to delete the strings.xml of default_web_clients_id as I reference it on my app. I tried to clean and build. I tried restarting Android Studio. How can I solve this?</p>
```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="default_web_client_id" translatable="false">xxxxxxxxxx</string>
    <string name="gcm_defaultSenderId" translatable="false">xxxxxxx</string>
    <string name="google_api_key" translatable="false">xxxxxx</string>
    <string name="google_app_id" translatable="false">1:xxxxxxxxxx</string>
    <string name="google_crash_reporting_api_key" translatable="false">xxxxxx</string>
    <string name="google_storage_bucket" translatable="false">x.appspot.com</string>
    <string name="project_id" translatable="false">bdmd</string>
</resources>
</code>```

Body:
While adding default_web_client_id as a string resource in strings.xml, I encountered an error Duplicate Resources with build generated values.xml. I tried to delete the build generated default_web_client_id but the Duplicate Resouces error won't go away. I don't want to delete the strings.xml of default_web_clients_id as I reference it on my app. I tried to clean and build. I tried restarting Android Studio. How can I solve this?

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="default_web_client_id" translatable="false">xxxxxxxxxx</string>
    <string name="gcm_defaultSenderId" translatable="false">xxxxxxx</string>
    <string name="google_api_key" translatable="false">xxxxxx</string>
    <string name="google_app_id" translatable="false">1:xxxxxxxxxx</string>
    <string name="google_crash_reporting_api_key" translatable="false">xxxxxx</string>
    <string name="google_storage_bucket" translatable="false">x.appspot.com</string>
    <string name="project_id" translatable="false">bdmd</string>
</resources>


问:
Angular HTTP POST to ASP.NET Core 6 complex parameter null
When Angular 14 does this HTTP POST call:

```<code> this.http.post<ProjectDto>(baseUrl + 'Projects/CreateProject', this.projectCreateInitDto).subscribe({
</code>```

to the controller (ASP.NET Core 6):

```<code>[Route("CreateProject")]
[HttpPost("{dto}")]
public ActionResult<ProjectAPIDto> CreateProject(ProjectAPICreateInitDto dto)
{
    var x = dto;
}
</code>```

The controller dto is always null.

Things I've tried (and failed):

Added [FromBody], which shouldn't be necessary since the dto is a complex argument; I've used the above structure to pass integers and that works.

Converted the Angular argument to JSON string and passed that as a string. Since 'string' is technically a simple argument, I added [FromBody] to the controller where the argument was just [FromBody] string dto. Also fails, without FromBody.

I don't understand:

if/when {dto} is needed in the HttpPost attribute, but is seems to me that it should be there to indicate what the CreateProject argument is.

how to add argument(s) to the Route attribute - if/when that should be used.

Researched a lot and still failing.

Thanks.

Body:
When Angular 14 does this HTTP POST call:

 this.http.post<ProjectDto>(baseUrl + 'Projects/CreateProject', this.projectCreateInitDto).subscribe({

to the controller (ASP.NET Core 6):

[Route("CreateProject")]
[HttpPost("{dto}")]
public ActionResult<ProjectAPIDto> CreateProject(ProjectAPICreateInitDto dto)
{
    var x = dto;
}

The controller dto is always null.

Things I've tried (and failed):

Added [FromBody], which shouldn't be necessary since the dto is a complex argument; I've used the above structure to pass integers and that works.

Converted the Angular argument to JSON string and passed that as a string. Since 'string' is technically a simple argument, I added [FromBody] to the controller where the argument was just [FromBody] string dto. Also fails, without FromBody.

I don't understand:

if/when {dto} is needed in the HttpPost attribute, but is seems to me that it should be there to indicate what the CreateProject argument is.

how to add argument(s) to the Route attribute - if/when that should be used.

Researched a lot and still failing.

Thanks.


Title: Error while calculating an x12 of a time series in R

Body:
I have a monthly time serie that I am trying to seasonnally adjust via the x12 package, but I get the following error that I find not very self explanatory although I have ckecked my serie is indeed a time series :

Error in readx12Out(file, freq_series = frequency(tso), start_series = start_series,  :
  An error occured when running x12! Program halted!

Here is my MWE with a dput table

library(x12)

MWE <- structure(c(69.3, 69.4, 69.5, 69.7, 69.9, 70.2, 70.5, 70.7, 70.8,
                   71.1, 71.4, 71.6, 72.1, 72.2, 72.2, 72.5, 72.7, 72.9, 73.3, 73.4,
                   73.5, 73.8, 74.1, 74.3, 74.5, 74.8, 74.9, 75.1, 75.3, 75.5, 75.8,
                   76, 76.2, 76.3, 76.5, 76.7, 76.8, 76.9, 77.1, 77.2, 77.3, 77.4,
                   77.5, 77.6, 77.7, 77.8, 78, 78, 78.1, 78.1, 78.2, 78.3, 78.4,
                   78.4, 78.6, 78.6, 78.7, 78.8, 78.9, 79, 79.1, 79.2, 79.2, 79.3,
                   79.3, 79.4, 79.5, 79.2, 79.4, 79.5, 79.6, 79.6, 79.6, 79.7, 80,
                   80, 80.1, 80.2, 80.2, 80.3, 80.3, 80.3, 80.2, 80.3, 80.3, 80.5,
                   80.6, 80.6, 80.6, 80.6, 80.7, 80.8, 80.8, 80.7, 80.8, 81, 80.8,
                   81, 81, 81, 81.1, 81.2, 81.2, 81.4, 81.4, 81.5, 81.5, 81.6, 81.4,
                   81.6, 81.7, 81.7, 81.8, 81.8, 81.8, 81.9, 81.9, 82, 82.1, 82.2,
                   81.967713693352, 81.9418220384609, 82.3993576586313, 82.2876428111403,
                   82.3456059356801, 82.4205473741361, 82.0691236017988, 82.4479526807796,
                   82.6400867112465, 82.7205407635895, 82.7368903166171, 82.8089046961582,
                   82.5365526060594, 82.6841351814674, 83.1197678625341, 83.3466704153293,
                   83.4777453528701, 83.5602014681842, 83.2708677364797, 83.7502397063261,
                   84.0023389512661, 84.1216688651068, 84.0651448930737, 84.2678682619126,
                   84.2259772723727, 84.3473288744301, 84.7901359985743, 84.9800179942922,
                   85.1188044179191, 85.1945892389009, 84.9720135129594, 85.2878398527536,
                   85.5671558902957, 85.6192117956492, 85.6027962020017, 85.7530211675084,
                   85.2677042648555, 85.8800143219216, 86.1465699422324, 86.275085986105,
                   86.4190188757462, 86.4633274382677, 86.1555810212674, 86.4548937006074,
                   86.9047828591269, 87.0459891725197, 86.9656330707877, 87.1430947037948,
                   86.6560380655989, 87.3006837013218, 87.5766890943358, 87.7327651928149,
                   87.8731938048199, 87.892603588013, 87.5833257833822, 88.070883884196,
                   88.2262252963144, 88.2303357674243, 88.194203944594, 88.356765677173,
                   87.7793554255549, 88.2609332400678, 88.6737044173788, 88.7757063887179,
                   88.8838119545325, 88.8791083826275, 88.3305104433586, 88.88858078423,
                   89.1510623060071, 89.0585889157837, 89.0343972653786, 89.1834980352787,
                   88.811139907244, 89.1215670038501, 89.619923356461, 89.8321770631727,
                   89.925415572456, 89.8824134054159, 89.3646846746944, 89.8520712930934,
                   90.0334010766246, 90.1102493143106, 90.2204739937508, 90.5147070696261,
                   89.9956586022078, 90.2637523502633, 90.7497281844847, 90.9858332350394,
                   91.1156809717273, 91.1352920891032, 90.6116121376265, 91.2123823929658,
                   91.3544847738102, 91.527750625589, 91.7486363753003, 92.0995381311276,
                   91.6728516219216, 92.0050010121024, 92.7533251844954, 92.8934337638814,
                   92.9805057571971, 93.0414379223554, 92.3941792776343, 93.0843873212318,
                   93.2888322734847, 93.4589510918919, 93.5244315978018, 93.711698189504,
                   93.1542366374934, 93.5508570751034, 94.1510286410448, 94.2411576577069,
                   94.3876747872554, 94.3876124675403, 93.7978245678662, 94.574031683045,
                   94.4589544656395, 94.4278861211887, 94.3460631610389, 94.6556002628982,
                   93.7636918141619, 94.568118673329, 94.9949819667414, 95.0354225430243,
                   95.0250925498424, 95.0861250344015, 94.534749665857, 95.1310389697224,
                   95.2136746492863, 95.2406704304976, 95.1195820424686, 95.3658363209663,
                   94.6486749316272, 95.0472443538106, 95.8003534041235, 96.1004321415555,
                   96.1867234067476, 96.3328533752031, 95.4794144273198, 96.3200788737589,
                   96.3537498102384, 96.5312133733721, 96.6715942430409, 97.1476096489329,
                   96.3452457453394, 96.6442226096376, 97.6389816111808, 97.7283705577389,
                   97.8028551383237, 97.9558913317198, 97.034363963525, 97.6956514461773,
                   97.7563490984791, 97.6540795695839, 97.6515106135986, 97.9828587148281,
                   97.0997338381585, 97.3088444901448, 98.317102002123, 98.2152945486512,
                   98.3093675514843, 98.4165530440598, 97.6555752820642, 98.3075230845746,
                   98.4288045567158, 98.3969450709763, 98.5082465238513, 98.6985323682939,
                   97.5611201553781, 98.353508613676, 99.1016962240937, 99.1222647142353,
                   99.042868365113, 99.0182520731131, 98.5371842556533, 99.4917594064962,
                   98.9243109786632, 98.9045678984094, 98.7330816664243, 99.1862680057582,
                   97.7177512245616, 98.4063243006257, 99.3151652235298, 99.4434538312378,
                   99.5894305688091, 99.6193157715815, 99.1588375939513, 99.963607883394,
                   99.5246016473716, 99.5945674471323, 99.4402242264222, 99.9466028218794,
                   98.5399253454016, 99.0569898631983, 99.9353749007514, 100.031592897129,
                   100.153664575076, 100.227541642224, 99.6711301588894, 100.368081190845,
                   100.111152444148, 100.045529458878, 99.8966064679175, 100.242779629019,
                   99.0665858544122, 99.1122415566879, 100.252412143228, 100.492367490972,
                   100.503019460831, 100.656252379047, 100.126478895711, 100.79250404894,
                   100.558607856437, 100.525643346908, 100.424533861527, 100.832375246272,
                   99.884702193794, 99.9032762429129, 101.097533908735, 101.261134796911,
                   101.474423105356, 101.44754065964, 101.029324418162, 101.762921704062,
                   101.311624885324, 101.340303026902, 101.154772431222, 101.536222485788,
                   100.631707853325, 100.618645621669, 101.633127323424, 102.05977365584,
                   102.028388782376, 102.360945956225, 101.902974269494, 102.508963376252,
                   102.186577964604, 102.297260315903, 102.077921258066, 102.538701762914,
                   101.656957282898, 101.913120067157, 102.335821458819, 102.366153273144,
                   102.678482131186, 102.782672029059, 103.32463614954, 103.040520095229,
                   102.670208330987, 102.529678833559, 102.463579462258, 102.639905722883,
                   102.669849375064, 102.365056655234, 103.129523284383, 103.256625892897,
                   103.422511809107, 103.697544076187, 103.298096571774, 104.065964401499,
                   103.93832652736, 103.993395948694, 104.209378680309, 104.51937548687,
                   104.410969018222, 104.981800853972, 105.822241166773, 106.534388230208,
                   107.275029063193, 107.504481707471, 107.855965181766, 109.128111043433,
                   108.673688612285, 109.128014351595, 109.439207690093, 109.912313381578,
                   109.702942136744, 110.391496664454, 111.437196831362, 112.240601968719,
                   112.862279751352, 112.981888392966, 113.058910345135, 114.300261455799,
                   113.659188689588, 113.847707807461, 113.910171663303, 114.047778326909,
                   113.511090345461, 113.856120602028, 114.599059653279, 115.088944155289,
                   115.481588088273, 115.424002262942, 115.332190612272, 116.469889283374,
                   115.644844136021, 115.692248024515, 115.626653680739, 115.704799425145
), .Tsp = c(1990, 2024.91666666667, 12), class = "ts")

x12(MWE)