问:
Raster R package, points outside the grid
I am working on a spatial simulation and I created spatial points, but when I plot them with raster R package I can see that some points are outside the grid. I would like to know how I could be sure that all my points are inside the grid as I need to dynamically change the grid resolution for the next steps of my simulations. Thank you in advance. This is my code for reproductibility:

```<code>library(raster)
set.seed(100)
tmp = tmp2 = data.frame("x" = rnorm(1000, 10, 10),"y" = rnorm(1000, 10, 10))
coordinates(tmp) <- c("x", "y")
r1 <- raster(tmp, resolution = 10)
r1<-rasterToPolygons(r1)
plot(r1)
for (a in 1:nrow(tmp2)) {
  d = tmp2[a,]
  pts<- d
  coordinates(pts)<-~x+y
  plot(pts,add=T,col=a)
}
</code>```

EDIT 1: Trying to define raster base on min and max values of XY coordinates, but some points are still outside the grid (visible in the plot)

```<code>library(raster)
set.seed(100)
tmp = tmp2 = data.frame("x" = rnorm(1000, 10, 10),"y" = rnorm(1000, 10, 10))
coordinates(tmp) <- c("x", "y")

r1 <- raster(xmn = min(tmp2$x), xmx = max(tmp2$x),
              ymn = min(tmp2$y), ymx = max(tmp2$y),
              resolution = 10)

r1<-rasterToPolygons(r1)
plot(r1)
for (a in 1:nrow(tmp2)) {
  d = tmp2[a,]
  pts<- d
  coordinates(pts)<-~x+y
  plot(pts,add=T,col=a)
}
</code>```

Body:
I am working on a spatial simulation and I created spatial points, but when I plot them with raster R package I can see that some points are outside the grid. I would like to know how I could be sure that all my points are inside the grid as I need to dynamically change the grid resolution for the next steps of my simulations. Thank you in advance. This is my code for reproductibility:

library(raster)
set.seed(100)
tmp = tmp2 = data.frame("x" = rnorm(1000, 10, 10),"y" = rnorm(1000, 10, 10))
coordinates(tmp) <- c("x", "y")
r1 <- raster(tmp, resolution = 10)
r1<-rasterToPolygons(r1)
plot(r1)
for (a in 1:nrow(tmp2)) {
  d = tmp2[a,]
  pts<- d
  coordinates(pts)<-~x+y
  plot(pts,add=T,col=a)
}

EDIT 1: Trying to define raster base on min and max values of XY coordinates, but some points are still outside the grid (visible in the plot)

library(raster)
set.seed(100)
tmp = tmp2 = data.frame("x" = rnorm(1000, 10, 10),"y" = rnorm(1000, 10, 10))
coordinates(tmp) <- c("x", "y")

r1 <- raster(xmn = min(tmp2$x), xmx = max(tmp2$x),
              ymn = min(tmp2$y), ymx = max(tmp2$y),
              resolution = 10)

r1<-rasterToPolygons(r1)
plot(r1)
for (a in 1:nrow(tmp2)) {
  d = tmp2[a,]
  pts<- d
  coordinates(pts)<-~x+y
  plot(pts,add=T,col=a)
}


来源: stackexchange

问:
Sphinxsearch autocomplete implementation
We have millions of search keywords and sphinx (sphinx-2.2.11-1.rhel7.x86_64) not work like google suggestions. For example, "keywor" not find any "keyword" words
There's my config:

```<code>source suggest
{
        type = mysql

        sql_host = ...
        sql_user = ...
        sql_pass = ...
        sql_db   = ...
        sql_port = ...

        sql_query_pre = SET NAMES utf8
        sql_query_pre = SET CHARACTER SET utf8
        sql_query_pre = SELECT @id := 0

        sql_query =  SELECT @id := @id + 1, query, total_docs, total_files, total, UNIX_TIMESTAMP(added_date) as post_date, amount FROM search_keywords where total > 0

        sql_attr_timestamp = post_date
        sql_attr_bigint = total
        sql_attr_bigint = total_docs
        sql_attr_bigint = total_files
        sql_attr_bigint = amount
        sql_field_string = query
}

index xg_suggest
{
        source = suggest
        path = /var/lib/sphinx/suggest
        docinfo = extern
        morphology = stem_enru
        min_word_len        = 2
        min_prefix_len = 2
        index_exact_words = 1
}
</code>```

and php file:

```<code>$sphinx->SetMatchMode (SPH_MATCH_EXTENDED);
$sphinx->SetRankingMode(SPH_RANK_BM25);
$sphinx->SetFieldWeights(array ('query' => 10));
$sphinx->SetSortMode(SPH_SORT_ATTR_DESC, 'amount');

$query = "* ^keywor*";
$result = $sphinx->Query($query, 'xg_suggest');
</code>```

results is:
"keywor abc"
"keywor xyz"
etc, but not any "keyword abc" results

ContentLicense: CC BY-SA 4.0

Body:
We have millions of search keywords and sphinx (sphinx-2.2.11-1.rhel7.x86_64) not work like google suggestions. For example, "keywor" not find any "keyword" words
There's my config:

source suggest
{
        type = mysql

        sql_host = ...
        sql_user = ...
        sql_pass = ...
        sql_db   = ...
        sql_port = ...

        sql_query_pre = SET NAMES utf8
        sql_query_pre = SET CHARACTER SET utf8
        sql_query_pre = SELECT @id := 0

        sql_query =  SELECT @id := @id + 1, query, total_docs, total_files, total, UNIX_TIMESTAMP(added_date) as post_date, amount FROM search_keywords where total > 0

        sql_attr_timestamp = post_date
        sql_attr_bigint = total
        sql_attr_bigint = total_docs
        sql_attr_bigint = total_files
        sql_attr_bigint = amount
        sql_field_string = query
}

index xg_suggest
{
        source = suggest
        path = /var/lib/sphinx/suggest
        docinfo = extern
        morphology = stem_enru
        min_word_len        = 2
        min_prefix_len = 2
        index_exact_words = 1
}

and php file:

$sphinx->SetMatchMode (SPH_MATCH_EXTENDED);
$sphinx->SetRankingMode(SPH_RANK_BM25);
$sphinx->SetFieldWeights(array ('query' => 10));
$sphinx->SetSortMode(SPH_SORT_ATTR_DESC, 'amount');

$query = "* ^keywor*";
$result = $sphinx->Query($query, 'xg_suggest');

results is:
"keywor abc"
"keywor xyz"
etc, but not any "keyword abc" results


问:
Prediction issue using Keras and TransformSpec with PySpark - petastorm
I am trying to get predictions from a Keras model with two inputs: sequence info and a regular covariate.

Using the TransformSpec function, I preprocess sequences so that they have the same length, and for masking values.

The model fits fine, but I have issues getting predictions.

```<code>import pyspark.sql.functions as F
import pyspark.sql.types as T

import tensorflow as tf

from petastorm.spark import SparkDatasetConverter, make_spark_converter
from petastorm import TransformSpec
spark.conf.set(SparkDatasetConverter.PARENT_CACHE_DIR_URL_CONF, 'file:///dbfs/...')

import numpy as np
import pandas as pd

# create data
sequence = [[1, 1, 1, 1, 1], [2, 2, 2, 2], [3, 2, 2], [3, 3, 3], [3, 3, 3, 3, 3], [2, 2, 2, 2, 2]]
y = [0, 1, 1, 2, 2, 1]
x = [0.3, 0.1, 0.3, 0.5, 0.5, 0.1]
df = pd.DataFrame({'y':y, 'x':x, 'sequence':sequence})
sdf = spark.createDataFrame(df)
target='y'
all_features = ['sequence', 'x']

# functions
def preprocess(v, max_length=5):
    vv = list(v)
    vv = [0] * (max_length - len(vv)) + vv
    return np.array(vv)

def format_sequence_data(pd_batch):
    pd_batch['sequence'] = pd_batch['sequence'].map(lambda x: preprocess(x))
    return pd_batch.loc[:,['sequence', 'x', 'y']]

transform_spec_fn = TransformSpec(
  format_sequence_data,
  edit_fields=[
        ('sequence', np.float32, (5,), False),
        ('x', np.float32, (), False),
        ('y', np.int32, (), False)],
  selected_fields=['sequence', 'x', 'y'])

# petastorm
df_converter = make_spark_converter(sdf)

# model
def createModel():

    seq_vec = tf.keras.Input(shape=(5,), name='sequence')
    e = tf.keras.layers.Embedding(input_dim=5, output_dim=5,
        input_length=5, mask_zero=True, name='sequence_embedding')(seq_vec)

    x = tf.keras.Input(shape=(1,), name='x', dtype='float')
    x = tf.keras.layers.Normalization()(x)

    ml = tf.keras.layers.LSTM(10, return_sequences=True)(e)
    ml = tf.keras.layers.LSTM(5)(ml)

    combined = tf.keras.layers.Concatenate()([ml, x])

    mlp = tf.keras.layers.Dense(10)(combined)
    mlp = tf.keras.layers.Dense(5)(mlp)
    mlp = tf.keras.layers.Dense(3, activation='softmax')(mlp)

    model = tf.keras.Model([seq_vec, x], mlp)
    model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics='accuracy')
    return model

model = createModel()

# training
batch_size=1
def train_and_evaluate():
    with df_converter.make_tf_dataset(transform_spec=transform_spec_fn, batch_size=batch_size) as data:
        data = data.map(lambda x: (tuple(getattr(x, col) for col in ['sequence', 'x']), getattr(x, target)))
        steps_per_epoch = int(len(df_converter) / batch_size)

        history = model.fit(data,
            steps_per_epoch=steps_per_epoch,
            epochs=10,
            shuffle=False,
            verbose=2)

    return history

history = train_and_evaluate()
</code>```

For prediction, I use:

```<code># udf function for prediction (pyspark)
def model_prediction_prob_udf(model):
  def predict(input_batch_iter):
    for input_batch in input_batch_iter:
        input_batch['sequence'] = input_batch['sequence'].map(lambda x: preprocess(x))
        preds = model.predict([input_batch.loc[:,c] for c in all_features], batch_size=1000)
        yield pd.Series(preds.tolist())
  return_type = T.ArrayType(T.DoubleType())
  return F.pandas_udf(return_type, F.PandasUDFType.SCALAR_ITER)(predict)

pred_prob_udf = model_prediction_prob_udf(model)

pred = sdf.withColumn('features', F.struct(all_features))
pred = pred.withColumn('prediction_prob', pred_prob_udf(F.col('features')))
display(pred)
</code>```

I get the error:

'ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).'

If I use something like the code below, prediction takes forever:

```<code>with df_converter.make_tf_dataset(transform_spec=transform_spec_fn, batch_size=1) as data:
        data = data.map(lambda x: ((x.sequence, x.x),))
        tt = model.predict(data)
</code>```

Any ideas or suggestions on how to fix this?
Thanks!

Body:
I am trying to get predictions from a Keras model with two inputs: sequence info and a regular covariate.

Using the TransformSpec function, I preprocess sequences so that they have the same length, and for masking values.

The model fits fine, but I have issues getting predictions.

import pyspark.sql.functions as F
import pyspark.sql.types as T

import tensorflow as tf

from petastorm.spark import SparkDatasetConverter, make_spark_converter
from petastorm import TransformSpec
spark.conf.set(SparkDatasetConverter.PARENT_CACHE_DIR_URL_CONF, 'file:///dbfs/...')

import numpy as np
import pandas as pd

# create data
sequence = [[1, 1, 1, 1, 1], [2, 2, 2, 2], [3, 2, 2], [3, 3, 3], [3, 3, 3, 3, 3], [2, 2, 2, 2, 2]]
y = [0, 1, 1, 2, 2, 1]
x = [0.3, 0.1, 0.3, 0.5, 0.5, 0.1]
df = pd.DataFrame({'y':y, 'x':x, 'sequence':sequence})
sdf = spark.createDataFrame(df)
target='y'
all_features = ['sequence', 'x']

# functions
def preprocess(v, max_length=5):
    vv = list(v)
    vv = [0] * (max_length - len(vv)) + vv
    return np.array(vv)

def format_sequence_data(pd_batch):
    pd_batch['sequence'] = pd_batch['sequence'].map(lambda x: preprocess(x))
    return pd_batch.loc[:,['sequence', 'x', 'y']]

transform_spec_fn = TransformSpec(
  format_sequence_data,
  edit_fields=[
        ('sequence', np.float32, (5,), False),
        ('x', np.float32, (), False),
        ('y', np.int32, (), False)],
  selected_fields=['sequence', 'x', 'y'])

# petastorm
df_converter = make_spark_converter(sdf)

# model
def createModel():

    seq_vec = tf.keras.Input(shape=(5,), name='sequence')
    e = tf.keras.layers.Embedding(input_dim=5, output_dim=5,
        input_length=5, mask_zero=True, name='sequence_embedding')(seq_vec)

    x = tf.keras.Input(shape=(1,), name='x', dtype='float')
    x = tf.keras.layers.Normalization()(x)

    ml = tf.keras.layers.LSTM(10, return_sequences=True)(e)
    ml = tf.keras.layers.LSTM(5)(ml)

    combined = tf.keras.layers.Concatenate()([ml, x])

    mlp = tf.keras.layers.Dense(10)(combined)
    mlp = tf.keras.layers.Dense(5)(mlp)
    mlp = tf.keras.layers.Dense(3, activation='softmax')(mlp)

    model = tf.keras.Model([seq_vec, x], mlp)
    model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics='accuracy')
    return model

model = createModel()

# training
batch_size=1
def train_and_evaluate():
    with df_converter.make_tf_dataset(transform_spec=transform_spec_fn, batch_size=batch_size) as data:
        data = data.map(lambda x: (tuple(getattr(x, col) for col in ['sequence', 'x']), getattr(x, target)))
        steps_per_epoch = int(len(df_converter) / batch_size)

        history = model.fit(data,
            steps_per_epoch=steps_per_epoch,
            epochs=10,
            shuffle=False,
            verbose=2)

    return history

history = train_and_evaluate()

For prediction, I use:

# udf function for prediction (pyspark)
def model_prediction_prob_udf(model):
  def predict(input_batch_iter):
    for input_batch in input_batch_iter:
        input_batch['sequence'] = input_batch['sequence'].map(lambda x: preprocess(x))
        preds = model.predict([input_batch.loc[:,c] for c in all_features], batch_size=1000)
        yield pd.Series(preds.tolist())
  return_type = T.ArrayType(T.DoubleType())
  return F.pandas_udf(return_type, F.PandasUDFType.SCALAR_ITER)(predict)

pred_prob_udf = model_prediction_prob_udf(model)

pred = sdf.withColumn('features', F.struct(all_features))
pred = pred.withColumn('prediction_prob', pred_prob_udf(F.col('features')))
display(pred)

I get the error:

'ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).'

If I use something like the code below, prediction takes forever:

with df_converter.make_tf_dataset(transform_spec=transform_spec_fn, batch_size=1) as data:
        data = data.map(lambda x: ((x.sequence, x.x),))
        tt = model.predict(data)

Any ideas or suggestions on how to fix this?
Thanks!


问:
Exclude django-simple-history from a child model
I am actually stuck in a problem where I need to exclude HistoricalRecords (django-simple-history) from a child class without making any changes in the parent class.

Here is my code looks like

```<code>from simple_history.models import HistoricalRecords
class BaseModel(models.Model):
    id = models.UUIDField(...some args...)
    created_at = models.DateTimeField(...some args...)
    created_by = models.ForeignKey(...some args...)
    history = HistoricalRecords(inherit=True)

    class Meta:
        abstract = True
        default_permissions = Constants.STANDARD_ACTIONS

    def save(self, suppress_modified=False, from_publish=False, **kwargs):
        super(BaseModel, self).save(**kwargs)

class CommonWithExtraFieldsWithoutVersioning(BaseModel, CommonWithoutVersioning, models.Model):
    class Meta(CommonWithoutVersioning.Meta):
        abstract = True

class Manager(CommonWithExtraFieldsWithoutVersioning):
    from_branch = models.CharField(...some args...)
    to_branch = models.CharField(...some args...)
    from_version = models.IntegerField(...some args...)
    to_version = models.IntegerField(...some args...)
    history = None # this is also not working for me

    def __init__(self, *args, **kwargs):  # this I have tried but not working
        super(DSLJourneyMergeHistory, self).__init__(*args, **kwargs)
        self.clean_fields('history')
</code>```

But when I try to makemigration it is creating HistoricalRecords for the manager as well and I want HistoricalRecords should not be maintained for the class manager. How do I exclude this as BaseModel and CommonWithExtraFields Models are used across the application and I cannot make any modification in that model

Body:
I am actually stuck in a problem where I need to exclude HistoricalRecords (django-simple-history) from a child class without making any changes in the parent class.

Here is my code looks like

from simple_history.models import HistoricalRecords
class BaseModel(models.Model):
    id = models.UUIDField(...some args...)
    created_at = models.DateTimeField(...some args...)
    created_by = models.ForeignKey(...some args...)
    history = HistoricalRecords(inherit=True)

    class Meta:
        abstract = True
        default_permissions = Constants.STANDARD_ACTIONS

    def save(self, suppress_modified=False, from_publish=False, **kwargs):
        super(BaseModel, self).save(**kwargs)

class CommonWithExtraFieldsWithoutVersioning(BaseModel, CommonWithoutVersioning, models.Model):
    class Meta(CommonWithoutVersioning.Meta):
        abstract = True

class Manager(CommonWithExtraFieldsWithoutVersioning):
    from_branch = models.CharField(...some args...)
    to_branch = models.CharField(...some args...)
    from_version = models.IntegerField(...some args...)
    to_version = models.IntegerField(...some args...)
    history = None # this is also not working for me

    def __init__(self, *args, **kwargs):  # this I have tried but not working
        super(DSLJourneyMergeHistory, self).__init__(*args, **kwargs)
        self.clean_fields('history')

But when I try to makemigration it is creating HistoricalRecords for the manager as well and I want HistoricalRecords should not be maintained for the class manager. How do I exclude this as BaseModel and CommonWithExtraFields Models are used across the application and I cannot make any modification in that model


问:
How can I modify the tableView in the second VC without affecting the related first VC?
the problem is that I have currency flags and currency codes which are used in both of my screens. one is the first screen  showing selected currency and the related flag and in the other screen i have same flags and codes next to each other inside tableview. Whichever i click on tableview i get it in the first screen as selected flag and code. what i want is I want to write a description next to the code like "{emoji} - USD - American Dollars" in the tableview but when i click it i dont want to see the American Dollars explanation in the first screen. how can i do that? this is what I want as a result and below that I m adding my codes

The Result I want

First VC

```<code>import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var amountText: UITextField!

    @IBOutlet weak var amountText2: UITextField!

    @IBOutlet weak var fromLabel: UILabel!

    @IBOutlet weak var fromImage: UIImageView!

    @IBOutlet weak var toImage: UIImageView!

    @IBOutlet weak var toLabel: UILabel!

    var currencyManager = CurrencyManager()

    var from: String = "EUR"
    var to: String = "TRY"
    var amount: String = "0"

    override func viewDidLoad() {
        super.viewDidLoad()

        amountText.delegate = self
        currencyManager.delegate = self

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let currencySelectorViewController = segue.destination as? CurrencySelectorViewController {
            if let sender = sender as? Int {
                if sender == 1 {
                    currencySelectorViewController.fromCurrencySelection = self
                } else {
                    currencySelectorViewController.toCurrencySelection = self
                }
            }
        }
    }

    @IBAction func amountChanged(_ sender: UITextField) {
        amount = sender.text!

        //amountText.endEditing(true)
        currencyManager.fetchRates(from: from, to: to, amount: amount )
    }

    //@IBAction func editingChanged2(_ sender: UITextField) {
    //    amount = sender.text!
    //
    //    //amountText.endEditing(true)
    //    currencyManager.fetchRates(from: to, to: from, amount: amount )
    // }

    @IBAction func didTapView(_ sender: UITapGestureRecognizer) {

        performSegue(withIdentifier: "currencySelector", sender: 1)
    }
    @IBAction func didTapView2(_ sender: UITapGestureRecognizer) {

        performSegue(withIdentifier: "currencySelector", sender: 2)

    }

}

     extension ViewController: UITextFieldDelegate {

     func textFieldShouldReturn(_ textField: UITextField) -> Bool {
     amountText.endEditing(true)
     currencyManager.fetchRates(from: from, to: to, amount: amount )

     return true
     }

         func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
     if textField.text != "" {
     return true
     } else {
     amountText.placeholder = "Enter an amount"
     return false
     }
     }
         func textFieldDidEndEditing(_ textField: UITextField) {
         //amount = amountText.text!
         //amount = amountText2.text!

         amountText.text = ""
         //amountText2.text = ""
         }
          }

     extension ViewController: CurrencyManagerDelegate {

     func didFailWithError(error: Error) {
     print(error)
     }

     func didUpdateCurrency(_ currencyManager: String) {

     DispatchQueue.main.async {

     self.amountText2.text = currencyManager
     }
     }
     }

extension ViewController: FromCurrencySelectorDelegate, ToCurrencySelectorDelegate {
    func didGetCurrencyCode(from: String) {
        fromLabel.text = from
        self.from = from
        }
    func didGetCurrencyCode(to: String) {
        toLabel.text = to
        self.to = to
    }
}
</code>```

Second VC

```<code>import UIKit

protocol FromCurrencySelectorDelegate: AnyObject {
    func didGetCurrencyCode(from: String)

}
protocol ToCurrencySelectorDelegate: AnyObject {
    func didGetCurrencyCode(to: String)
}
class CurrencySelectorViewController: UIViewController {

    weak var fromCurrencySelection: FromCurrencySelectorDelegate!
    weak var toCurrencySelection: ToCurrencySelectorDelegate!

    let reusableCell = "ReusableCell"

    let currencyArray = ["  EUR", "\u{1F1FA}\u{1F1F8}  USD", "\u{1F1F9}\u{1F1F7}  TRY", "\u{1F1EC}\u{1F1E7}  GBP", "\u{1F1EF}\u{1F1F5}  JPY", "\u{1F1E8}\u{1F1E6}  CAD", "\u{1F1E6}\u{1F1FA}  AUD", "\u{1F1E7}\u{1F1EC}  BGN", "\u{1F1F7}\u{1F1FA}  RUB", "\u{1F1F3}\u{1F1F4}  NOK", "\u{1F1E8}\u{1F1F3}  CNY", "\u{1F1E8}\u{1F1ED}  CHF", "\u{1F1F2}\u{1F1FD}  MXN"]

    var filteredData: [String]!

    @IBOutlet weak var tableView: UITableView!

    @IBOutlet weak var searchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        filteredData = currencyArray
        searchBar.delegate = self
        tableView.delegate = self
        tableView.dataSource = self
    }

}

extension CurrencySelectorViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filteredData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: reusableCell, for: indexPath)
        cell.textLabel?.text = filteredData[indexPath.row]
        return cell
    }

}

extension CurrencySelectorViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if fromCurrencySelection != nil {

            fromCurrencySelection.didGetCurrencyCode(from: currencyArray[indexPath.row])

        } else {

            toCurrencySelection.didGetCurrencyCode(to: currencyArray[indexPath.row])

        }
        dismiss(animated: true, completion: nil)
    }
}

//MARK: - Search Bar Methods
extension CurrencySelectorViewController: UISearchBarDelegate {

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        filteredData = []

        if searchText == "" {
            filteredData = currencyArray
        }

        for word in currencyArray {
            if word.uppercased().contains(searchText.uppercased()) {
                filteredData.append(word)
            }
            }
        self.tableView.reloadData()
        }

    }
</code>```

Body:
the problem is that I have currency flags and currency codes which are used in both of my screens. one is the first screen  showing selected currency and the related flag and in the other screen i have same flags and codes next to each other inside tableview. Whichever i click on tableview i get it in the first screen as selected flag and code. what i want is I want to write a description next to the code like "{emoji} - USD - American Dollars" in the tableview but when i click it i dont want to see the American Dollars explanation in the first screen. how can i do that? this is what I want as a result and below that I m adding my codes

The Result I want

First VC

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var amountText: UITextField!

    @IBOutlet weak var amountText2: UITextField!

    @IBOutlet weak var fromLabel: UILabel!

    @IBOutlet weak var fromImage: UIImageView!

    @IBOutlet weak var toImage: UIImageView!

    @IBOutlet weak var toLabel: UILabel!

    var currencyManager = CurrencyManager()

    var from: String = "EUR"
    var to: String = "TRY"
    var amount: String = "0"

    override func viewDidLoad() {
        super.viewDidLoad()

        amountText.delegate = self
        currencyManager.delegate = self

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let currencySelectorViewController = segue.destination as? CurrencySelectorViewController {
            if let sender = sender as? Int {
                if sender == 1 {
                    currencySelectorViewController.fromCurrencySelection = self
                } else {
                    currencySelectorViewController.toCurrencySelection = self
                }
            }
        }
    }

    @IBAction func amountChanged(_ sender: UITextField) {
        amount = sender.text!

        //amountText.endEditing(true)
        currencyManager.fetchRates(from: from, to: to, amount: amount )
    }

    //@IBAction func editingChanged2(_ sender: UITextField) {
    //    amount = sender.text!
    //
    //    //amountText.endEditing(true)
    //    currencyManager.fetchRates(from: to, to: from, amount: amount )
    // }

    @IBAction func didTapView(_ sender: UITapGestureRecognizer) {

        performSegue(withIdentifier: "currencySelector", sender: 1)
    }
    @IBAction func didTapView2(_ sender: UITapGestureRecognizer) {

        performSegue(withIdentifier: "currencySelector", sender: 2)

    }

}

     extension ViewController: UITextFieldDelegate {

     func textFieldShouldReturn(_ textField: UITextField) -> Bool {
     amountText.endEditing(true)
     currencyManager.fetchRates(from: from, to: to, amount: amount )

     return true
     }

         func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
     if textField.text != "" {
     return true
     } else {
     amountText.placeholder = "Enter an amount"
     return false
     }
     }
         func textFieldDidEndEditing(_ textField: UITextField) {
         //amount = amountText.text!
         //amount = amountText2.text!

         amountText.text = ""
         //amountText2.text = ""
         }
          }

     extension ViewController: CurrencyManagerDelegate {

     func didFailWithError(error: Error) {
     print(error)
     }

     func didUpdateCurrency(_ currencyManager: String) {

     DispatchQueue.main.async {

     self.amountText2.text = currencyManager
     }
     }
     }

extension ViewController: FromCurrencySelectorDelegate, ToCurrencySelectorDelegate {
    func didGetCurrencyCode(from: String) {
        fromLabel.text = from
        self.from = from
        }
    func didGetCurrencyCode(to: String) {
        toLabel.text = to
        self.to = to
    }
}

Second VC

import UIKit

protocol FromCurrencySelectorDelegate: AnyObject {
    func didGetCurrencyCode(from: String)

}
protocol ToCurrencySelectorDelegate: AnyObject {
    func didGetCurrencyCode(to: String)
}
class CurrencySelectorViewController: UIViewController {

    weak var fromCurrencySelection: FromCurrencySelectorDelegate!
    weak var toCurrencySelection: ToCurrencySelectorDelegate!

    let reusableCell = "ReusableCell"

    let currencyArray = ["  EUR", "\u{1F1FA}\u{1F1F8}  USD", "\u{1F1F9}\u{1F1F7}  TRY", "\u{1F1EC}\u{1F1E7}  GBP", "\u{1F1EF}\u{1F1F5}  JPY", "\u{1F1E8}\u{1F1E6}  CAD", "\u{1F1E6}\u{1F1FA}  AUD", "\u{1F1E7}\u{1F1EC}  BGN", "\u{1F1F7}\u{1F1FA}  RUB", "\u{1F1F3}\u{1F1F4}  NOK", "\u{1F1E8}\u{1F1F3}  CNY", "\u{1F1E8}\u{1F1ED}  CHF", "\u{1F1F2}\u{1F1FD}  MXN"]

    var filteredData: [String]!

    @IBOutlet weak var tableView: UITableView!

    @IBOutlet weak var searchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        filteredData = currencyArray
        searchBar.delegate = self
        tableView.delegate = self
        tableView.dataSource = self
    }

}

extension CurrencySelectorViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filteredData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: reusableCell, for: indexPath)
        cell.textLabel?.text = filteredData[indexPath.row]
        return cell
    }

}

extension CurrencySelectorViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if fromCurrencySelection != nil {

            fromCurrencySelection.didGetCurrencyCode(from: currencyArray[indexPath.row])

        } else {

            toCurrencySelection.didGetCurrencyCode(to: currencyArray[indexPath.row])

        }
        dismiss(animated: true, completion: nil)
    }
}

//MARK: - Search Bar Methods
extension CurrencySelectorViewController: UISearchBarDelegate {

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        filteredData = []

        if searchText == "" {
            filteredData = currencyArray
        }

        for word in currencyArray {
            if word.uppercased().contains(searchText.uppercased()) {
                filteredData.append(word)
            }
            }
        self.tableView.reloadData()
        }

    }


问:
Is there a shortcut or extension to automatically add image width and height to <source> images inside of <picture> element?
There is a quick way to adding width and height for images on  element using vscode shortcut 1. CMD + Shift + P  2.Emmet update image size. But this trick doesn't work on  inside of  element. Is there a shortcut or vscode extension to make that happen? I mostly work with  element so this would be big productivity boost.

I tried searching through vscode docs and there is no shortcut for picture element or browser extension to my knowledge.


问:
access general class axioms of an ontology via owlready2
Can I access what in Protege is called "general class axioms" of an ontology via owlready2? Those containing named and anonymous classes, like in the screenshot:
enter image description here

I stumbled upon method ontology.general_axioms(), but the output is quite weird: a list of expressions and restrictions. It was not what I was expecting because I could not find how the elements of the list relate to each other. Also, I did not find all the expressions I created in Protege.


问:
Passing schema name as a subdirectory not subdomain
Hi I'am working on multi schema creation task, I have done with apartment gem and schema creation is working fine and now need to pass the schema name on the url as sub-directory not (subdomain) for eg: http://127.0.0.1:3000/schema_name.
If anyone has any suggestions or the way to do it please help me

I have tried with passing schema name as subdomain but can't able to pass it as sub-directory.


Title: How to set search filter in recycler view by Edit Text

Body:
I have a problem in implementing the search functionality on my recycler view by edittext addTextChangeListener. I don't want to use setOnQueryTextListener. Then I implemented some tutorial codes. But still when I insert something it shows blank recycler view.

MainActivity.java

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

   //______________________________ W I D G E T S ______________________________//
    RecyclerView chaptersRV;
    ChaptersAdapter myAdapter;
    ArrayList<ChapterModel> list;
    DatabaseReference chapterRef;
  //______________________________ W I D G E T S ______________________________//

//__________________________________________________________________________________________________________________________________________________
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//______________________________________________________________________________________________________________________________________________________________________________________________________________

      //____________________________________________________________ I D S   C A S T I N G ____________________________________________________________//
        chaptersRV = findViewById(R.id.chapters_posts_view);
        searchView = findViewById(R.id.chapter_search_view);
        chapterRef= Firebase...
      //____________________________________________________________ I D S   C A S T I N G ____________________________________________________________//

//___________________________________________________________// CHAPTERS RECYCLER VIEW SETUP___________________________________________________________________________________________________________________________________________________
        chaptersRV.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        chaptersRV.setLayoutManager(layoutManager);
        list = new ArrayList<>();
        myAdapter = new ChaptersAdapter(this , list);
        chaptersRV.setAdapter(myAdapter);

        chapterRef.addValueEventListener(new ValueEventListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for(DataSnapshot dataSnapshot : snapshot.getChildren()){
                    ChapterModel model = dataSnapshot.getValue(ChapterModel.class);
                    list.add(model);
                }
                myAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

//___________________________________________________________// CHAPTERS SEARCH ACTION SETUP_______________________________________________________________________________________
        searchView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                myAdapter.getFilter().filter(charSequence);
            }

            @Override
            public void afterTextChanged(Editable editable) {
                myAdapter.getFilter().filter(searchView.getText());
            }
        });
//___________________________________________________________// CHAPTERS SEARCH ACTION  SETUP_______________________________________________________________________________________
    }
}

ChaptersAdapter.java

public class ChaptersAdapter extends RecyclerView.Adapter<ChaptersAdapter.MyViewHolder> implements Filterable {

    Context context;
    private ArrayList<ChapterModel> list;
    private ArrayList<ChapterModel> backup;

    public ChaptersAdapter(Context context, ArrayList<ChapterModel> list) {
        this.context = context;
        this.list = list;
        backup = new ArrayList<>(list);
    }

    @NonNull
    @Override
    public ChaptersAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chapters_model, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ChaptersAdapter.MyViewHolder holder, int position) {
        final ChapterModel chapterModel = list.get(position);

        holder.chapterName.setText(chapterModel.getChapter_Name());

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        TextView chapterName;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            chapterName = itemView.findViewById(R.id.chapter_name);

        }
    }

    @Override
    public Filter getFilter() {
        return filter;
    }

    private Filter filter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence keyword) {

            ArrayList<ChapterModel> filtereddata = new ArrayList<>();

            if (keyword.toString().isEmpty() || keyword.length() == 0 || keyword == null) {
                filtereddata.addAll(backup);
            } else {
                for (ChapterModel obj : backup) {
                    if (obj.getChapter_Name().toLowerCase().contains(keyword.toString().toLowerCase()))
                        filtereddata.add(obj);
                }
            }

            FilterResults results = new FilterResults();
            results.values = filtereddata;
            results.count = filtereddata.size();
            return results;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            list.clear();
            list.addAll((ArrayList) filterResults.values);
            notifyDataSetChanged();
        }
    };
}

I want to implement search functionality in recyclerView by editText addTextChangeListener


问:
How do I make it so i can click a row and then if i click delete button it shall delete
I am looking to make a shop and if im on the admin page i click on the row i want to delete i can clock another button and it will delete it. TIA

This is the datacell that has the table in it

```<code> private void datafrm_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            itemidtb.Text = datafrm.SelectedRows[0].Cells[0].Value.ToString();
            cusnametb.Text = datafrm.SelectedRows[0].Cells[1].Value.ToString();
            typetb.Text = datafrm.SelectedRows[0].Cells[2].Value.ToString();
            pricetb.Text = datafrm.SelectedRows[0].Cells[3].Value.ToString();
            quantitytb.Text = datafrm.SelectedRows[0].Cells[4].Value.ToString();
        }
</code>```

this is the delete button code.

```<code> private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (itemidtb.Text == "")
                {
                    MessageBox.Show("Select the product to delete");

                }else
                {
                    con.Open();
                    string query = "delete from tbl_stock where ItemID=" + itemidtb.Text +"";
                    OleDbCommand cmd = new OleDbCommand(query, con);
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Deleted");

                    con.Close();
                    populate();

                }
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
</code>```

I tried what i found online but when i click on the cell i want to delete i go to the delte button and it says please click the cell you want to remove like i implemented

Body:
I am looking to make a shop and if im on the admin page i click on the row i want to delete i can clock another button and it will delete it. TIA

This is the datacell that has the table in it

 private void datafrm_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            itemidtb.Text = datafrm.SelectedRows[0].Cells[0].Value.ToString();
            cusnametb.Text = datafrm.SelectedRows[0].Cells[1].Value.ToString();
            typetb.Text = datafrm.SelectedRows[0].Cells[2].Value.ToString();
            pricetb.Text = datafrm.SelectedRows[0].Cells[3].Value.ToString();
            quantitytb.Text = datafrm.SelectedRows[0].Cells[4].Value.ToString();
        }

this is the delete button code.

 private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (itemidtb.Text == "")
                {
                    MessageBox.Show("Select the product to delete");

                }else
                {
                    con.Open();
                    string query = "delete from tbl_stock where ItemID=" + itemidtb.Text +"";
                    OleDbCommand cmd = new OleDbCommand(query, con);
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Deleted");

                    con.Close();
                    populate();

                }
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

I tried what i found online but when i click on the cell i want to delete i go to the delte button and it says please click the cell you want to remove like i implemented


问:
Flutter how to select multiple days of the week and add to Hive
please support me I want to create an application that can select multiple days of the week. With added to Hive, what can I do?</p>


问:
Why does the SMTP explicitly provide for relaying?
The third paragraph of the Simple Mail Transfer Protocol RFC states that

An important feature of SMTP is its capability to transport mail
across multiple networks, [...]  Using
SMTP, a process can transfer mail to another process on the same
network or to some other network via a relay or gateway process
accessible to both networks.

Do IP/DNS, on which SMTP relies via TCP, not already provide these features? Why does SMTP re-implement them instead of, say, letting the sender directly TCP-connect to the destination mail server?


问:
Service Unavailable Error from APIGATEWAY
I am using multiple lambdas in the step functions. The client hits the API gateway, which invokes a lambda, and that lambda invokes the step function's lambdas to get the response.

The response time is 3-7 seconds when lambdas are already warmed up.
But when it has cold-start, it takes more than 30 seconds for some requests based on input.

As the API gateway has a timeout of 30 seconds, I get a “503- service Unavailable error" for some requests request though the execution is running. Though AWS says, it should give 504 for request time out.

Then I used provisioned concurrency for the latency issue, which will likely solve the timeout issue. But still, sometimes, I get a service Unavailable error.

I checked cloudwatch trace. Interestingly, Each lambda takes an initialization time of 3 seconds even after provisioning. Now I doubt whether provisioned-concurrency is working or I do not understand it.

Any advice?


问:
libbpf: gnu/stub-32.h required on amd64 when building bpf program
I am trying to write some uprobes for tracing nginx and am struggling to build the bpf program. More specifically, when including nginx header files in order to parse data, the build does not register my 64-bit architecture and wants to include gnu/stubs-32.h. Building without ngx_http.h works fine. This may not be specifically a libbpf issue, however I do not have the same problems with bpftrace or BCC where inclusion works without problems.

Any suggestions as to how to fix this is greatly appreciated.

Code

nginx.bpf.c

#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include "ngx_http.h"

char LICENSE[] SEC("license") = "Dual BSD/GPL";

SEC("uprobe//usr/sbin/nginx:ngx_http_finalize_request")
int handle_ngx_http_finalize_request(struct pt_regs* ctx)
{
    int pid = bpf_get_current_pid_tgid() >> 32;
    bpf_printk("Is this getting triggered? %d.\n", pid);
    return 0;
}
```
<p><strong>nginx.c</strong></p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <unistd.h>
#include <sys/resource.h>
#include <bpf/libbpf.h>
#include "nginx.skel.h"

static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
{
    return vfprintf(stderr, format, args);
}

int main(int argc, char **argv)
{
    struct nginx_bpf *skel;
    int err;

    libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
    libbpf_set_print(libbpf_print_fn);

    skel = nginx_bpf__open_and_load();
    if (!skel) {
        fprintf(stderr, "Failed to open and load BPF skeleton\n");
        return 1;
    }

    err = nginx_bpf__attach(skel);
    if (err) {
        fprintf(stderr, "Failed to auto-attach BPF skeleton: %d\n", err);
        goto cleanup;
    }

    printf("Successfully started!\n");

    for (;;) {
        sleep(1);
    }

cleanup:
    nginx_bpf__destroy(skel);
    return -err;
}
</code>```

error message

```<code>❯ make
  BPF      .output/nginx.bpf.o
In file included from nginx.bpf.c:4:
In file included from /home/nela/master/nginx-1.18.0/src/http/ngx_http.h:12:
In file included from /home/nela/master/nginx-1.18.0/src/core/ngx_config.h:26:
In file included from /home/nela/master/nginx-1.18.0/src/os/unix/ngx_linux_config.h:18:
In file included from /usr/include/x86_64-linux-gnu/sys/types.h:25:
In file included from /usr/include/features.h:510:
/usr/include/x86_64-linux-gnu/gnu/stubs.h:7:12: fatal error: 'gnu/stubs-32.h' file not found
 # include <gnu/stubs-32.h>
           ^~~~~~~~~~~~~~~~
1 error generated.
make: *** [Makefile:106: .output/nginx.bpf.o] Error 1
</code>```

System Information

```<code>❯ echo $CPATH
/home/nela/master/nginx-1.18.0/src/http/modules:/home/nela/master/nginx-1.18.0/src/http/v2:/home/nela/master/nginx-1.18.0/src/http:/home/nela/master/nginx-1.18.0/src/event:/home/nela/master/nginx-1.18.0/src/core:/home/nela/master/nginx-1.18.0/src:/home/nela/master/nginx-1.18.0/src/os/unix:/home/nela/master/nginx-1.18.0/objs:/home/nela/master/nginx-1.18.0:/usr/src/linux-headers-5.15.0-56-generic/include:/usr/src/linux-headers-5.15.0-56/include:/usr/include
</code>```
```<code>❯ uname -a
Linux nelasus 5.15.0-53-generic #59-Ubuntu SMP Mon Oct 17 18:53:30 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
</code>```
```<code>❯ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 22.04.1 LTS
Release:        22.04
Codename:       jammy
</code>```

Body:
I am trying to write some uprobes for tracing nginx and am struggling to build the bpf program. More specifically, when including nginx header files in order to parse data, the build does not register my 64-bit architecture and wants to include gnu/stubs-32.h. Building without ngx_http.h works fine. This may not be specifically a libbpf issue, however I do not have the same problems with bpftrace or BCC where inclusion works without problems.

Any suggestions as to how to fix this is greatly appreciated.

Code

nginx.bpf.c

#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include "ngx_http.h"

char LICENSE[] SEC("license") = "Dual BSD/GPL";

SEC("uprobe//usr/sbin/nginx:ngx_http_finalize_request")
int handle_ngx_http_finalize_request(struct pt_regs* ctx)
{
    int pid = bpf_get_current_pid_tgid() >> 32;
    bpf_printk("Is this getting triggered? %d.\n", pid);
    return 0;
}

nginx.c

#include <stdio.h>
#include <unistd.h>
#include <sys/resource.h>
#include <bpf/libbpf.h>
#include "nginx.skel.h"

static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
{
    return vfprintf(stderr, format, args);
}

int main(int argc, char **argv)
{
    struct nginx_bpf *skel;
    int err;

    libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
    libbpf_set_print(libbpf_print_fn);

    skel = nginx_bpf__open_and_load();
    if (!skel) {
        fprintf(stderr, "Failed to open and load BPF skeleton\n");
        return 1;
    }

    err = nginx_bpf__attach(skel);
    if (err) {
        fprintf(stderr, "Failed to auto-attach BPF skeleton: %d\n", err);
        goto cleanup;
    }

    printf("Successfully started!\n");

    for (;;) {
        sleep(1);
    }

cleanup:
    nginx_bpf__destroy(skel);
    return -err;
}

error message

❯ make
  BPF      .output/nginx.bpf.o
In file included from nginx.bpf.c:4:
In file included from /home/nela/master/nginx-1.18.0/src/http/ngx_http.h:12:
In file included from /home/nela/master/nginx-1.18.0/src/core/ngx_config.h:26:
In file included from /home/nela/master/nginx-1.18.0/src/os/unix/ngx_linux_config.h:18:
In file included from /usr/include/x86_64-linux-gnu/sys/types.h:25:
In file included from /usr/include/features.h:510:
/usr/include/x86_64-linux-gnu/gnu/stubs.h:7:12: fatal error: 'gnu/stubs-32.h' file not found
 # include <gnu/stubs-32.h>
           ^~~~~~~~~~~~~~~~
1 error generated.
make: *** [Makefile:106: .output/nginx.bpf.o] Error 1

System Information

❯ echo $CPATH
/home/nela/master/nginx-1.18.0/src/http/modules:/home/nela/master/nginx-1.18.0/src/http/v2:/home/nela/master/nginx-1.18.0/src/http:/home/nela/master/nginx-1.18.0/src/event:/home/nela/master/nginx-1.18.0/src/core:/home/nela/master/nginx-1.18.0/src:/home/nela/master/nginx-1.18.0/src/os/unix:/home/nela/master/nginx-1.18.0/objs:/home/nela/master/nginx-1.18.0:/usr/src/linux-headers-5.15.0-56-generic/include:/usr/src/linux-headers-5.15.0-56/include:/usr/include

❯ uname -a
Linux nelasus 5.15.0-53-generic #59-Ubuntu SMP Mon Oct 17 18:53:30 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

❯ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 22.04.1 LTS
Release:        22.04
Codename:       jammy


问:
Native crash on few android devices, Unity Game
My unity game is crashing on few android devices. Below is the crashlytics log:

```<code>Crashed: Thread: SIGSEGV  0x0000007b60251000
#00 pc 0x4d3fc libc.so
#01 pc 0x39fcffc libil2cpp.so
#02 pc 0xb30d4c libil2cpp.so
#03 pc 0x39fd6fc libil2cpp.so
#04 pc 0xb124dc libil2cpp.so
#05 pc 0xb12524 libil2cpp.so
#06 pc 0xb124dc libil2cpp.so
#07 pc 0xb2ae20 libil2cpp.so
#08 pc 0xc7ffc libc.so
#09 pc 0xb87f44 libil2cpp.so
#10 pc 0xb6c6c libc.so
#11 pc 0x5329c libc.so
#12 pc 0xb6b30 libc.so
#13 pc 0xb2a6d0 libil2cpp.so
#14 pc 0xb87f24 libil2cpp.so
</code>```

I am struggling with it from a long time. It is also affecting my game's rating on play store. If anyone know about it, please help me. Thanks.

Body:
My unity game is crashing on few android devices. Below is the crashlytics log:

Crashed: Thread: SIGSEGV  0x0000007b60251000
#00 pc 0x4d3fc libc.so
#01 pc 0x39fcffc libil2cpp.so
#02 pc 0xb30d4c libil2cpp.so
#03 pc 0x39fd6fc libil2cpp.so
#04 pc 0xb124dc libil2cpp.so
#05 pc 0xb12524 libil2cpp.so
#06 pc 0xb124dc libil2cpp.so
#07 pc 0xb2ae20 libil2cpp.so
#08 pc 0xc7ffc libc.so
#09 pc 0xb87f44 libil2cpp.so
#10 pc 0xb6c6c libc.so
#11 pc 0x5329c libc.so
#12 pc 0xb6b30 libc.so
#13 pc 0xb2a6d0 libil2cpp.so
#14 pc 0xb87f24 libil2cpp.so

I am struggling with it from a long time. It is also affecting my game's rating on play store. If anyone know about it, please help me. Thanks.


问:
How to change the text color of only selected range days in android material date picker
Required outputI'm trying to change the selected date range textview days(in between start and end date) text color to white but I'm unable to find a simple way.

The selected date range text color is to be in white


问:
I have to connect to wallet with my app but i am getting true when added permission:
without this permission

```<code>    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
</code>```

i am getting always false by calling Linking.canOpenUrl('wc:412259f2-f483-4e36-a925-ffd8a76fbc84@1?bridge=https%3A%2F%2F0.bridge.walletconnect.org&key=5e85ead542808e12c53346b1bc71af97e8bc30536daf25ad7b8a08992c08537c')even when metamask is installed on my redmi note 10s device.
is there any way to find the app that i wanna connect with is installed or not .or any other solution to solve this issue.

I am trying to know the app is installed or not so that i can connect my app to metamask app by using Linking.canOpenUrl('wc:412259f2-f483-4e36-a925-ffd8a76fbc84@1?bridge=https%3A%2F%2F0.bridge.walletconnect.org&key=5e85ead542808e12c53346b1bc71af97e8bc30536daf25ad7b8a08992c08537c').but unable to get true when app is installed .and when i added

```<code>    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
</code>```

i am getting true always even when app is uninstalled from device.

Body:
without this permission

    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />

i am getting always false by calling Linking.canOpenUrl('wc:412259f2-f483-4e36-a925-ffd8a76fbc84@1?bridge=https%3A%2F%2F0.bridge.walletconnect.org&key=5e85ead542808e12c53346b1bc71af97e8bc30536daf25ad7b8a08992c08537c')even when metamask is installed on my redmi note 10s device.
is there any way to find the app that i wanna connect with is installed or not .or any other solution to solve this issue.

I am trying to know the app is installed or not so that i can connect my app to metamask app by using Linking.canOpenUrl('wc:412259f2-f483-4e36-a925-ffd8a76fbc84@1?bridge=https%3A%2F%2F0.bridge.walletconnect.org&key=5e85ead542808e12c53346b1bc71af97e8bc30536daf25ad7b8a08992c08537c').but unable to get true when app is installed .and when i added

    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />

i am getting true always even when app is uninstalled from device.


问:
prop.sync is not working with :value (vuejs)
I have a made a custom "Select" component as well as an "Input" component. For my use case, it a certain object with "Preset" value is selected then I want the "Input" component to dynamically set the value to this Preset value. The parent component (below) has the child component "MegaSelect" (the custom select component) and "MegaCell" (custom input component)

```<code>  <MegaSelect
    :row="rowNum"
    :col="0"
    :options="frontTypes"
    :displayValue="true"
    :data.sync="data.frontType"
    placeholder="Item type"
    @change="typeChange"
  ></MegaSelect>
</code>```

Here the "Select" component called "MegaSelect" is triggering typeChange (below)

```<code>typeChange() {
  var presets = productData.getFrontType(this.data.frontType).presets
  this.wPresets = presets ? presets.w : null
  this.hPresets = presets ? presets.h : null
  this.qtyPresets = presets ? presets.qty : null
}
</code>```

typeChange will check if my selected object has a hardcoded "Preset" value. if it does, it will update the data of wPresets, hPresets and qtyPresets.

```<code>  <MegaCell
    :value="qtyPresets ? qtyPresets[0] : null"
    :data.sync="data.qty"
    dataType="Number"
    :row="rowNum"
    :col="4"
  ></MegaCell>
</code>```

it will then dynamically update the :value of another custom "input" component called "MegaCell" which has a :prop.sync updating the "data" prop.

the MegaCell component has the following template

```<code><template>
  <div
    class="mega-cell"
    :class="{
      selected: selected,
      focussed: focussed,
      outOfBounds: outOfBounds,
      warn: warn
    }"
    @mousedown="mousedown"
  >
    <input ref="field" v-model="convertedDbValue" @focus="setFocus" @dblclick="setFocus" :placeholder="placeholder" />
  </div>
</template>
</code>```

I believe my mistake has something to do with the v-model and my computed: convertedDbValue's setter (below)

```<code>convertedDbValue: {
  get: function() {
    if (!this.data) return null
    var fixedData = this.$utils.toFixedNumber(this.data / 25.4, 3)
    var adjustedData = fixedData % 1 == 0 ? parseInt(fixedData) : fixedData
    return this.dataType == 'Number' && this.unit == 'inch' ? adjustedData : this.data
  },
  set: function(value) {
    if (this.dataType !== 'String') {
      var val = this.unit == 'inch' ? this.$utils.toFixedNumber(value * 25.4, 3) : parseInt(value)
      this.$emit('update:data', val)
    } else {
      this.$emit('update:data', value)
    }
  }
}
</code>```

it's updating the data prop with a few adjustments to the inputted (number) value. how do i get the :value to dynamically change from the parent component to the child component and update the input value accordingly?

Body:
I have a made a custom "Select" component as well as an "Input" component. For my use case, it a certain object with "Preset" value is selected then I want the "Input" component to dynamically set the value to this Preset value. The parent component (below) has the child component "MegaSelect" (the custom select component) and "MegaCell" (custom input component)

  <MegaSelect
    :row="rowNum"
    :col="0"
    :options="frontTypes"
    :displayValue="true"
    :data.sync="data.frontType"
    placeholder="Item type"
    @change="typeChange"
  ></MegaSelect>

Here the "Select" component called "MegaSelect" is triggering typeChange (below)

typeChange() {
  var presets = productData.getFrontType(this.data.frontType).presets
  this.wPresets = presets ? presets.w : null
  this.hPresets = presets ? presets.h : null
  this.qtyPresets = presets ? presets.qty : null
}

typeChange will check if my selected object has a hardcoded "Preset" value. if it does, it will update the data of wPresets, hPresets and qtyPresets.

  <MegaCell
    :value="qtyPresets ? qtyPresets[0] : null"
    :data.sync="data.qty"
    dataType="Number"
    :row="rowNum"
    :col="4"
  ></MegaCell>

it will then dynamically update the :value of another custom "input" component called "MegaCell" which has a :prop.sync updating the "data" prop.

the MegaCell component has the following template

<template>

    <input ref="field" v-model="convertedDbValue" @focus="setFocus" @dblclick="setFocus" :placeholder="placeholder" />

</template>

I believe my mistake has something to do with the v-model and my computed: convertedDbValue's setter (below)

convertedDbValue: {
  get: function() {
    if (!this.data) return null
    var fixedData = this.$utils.toFixedNumber(this.data / 25.4, 3)
    var adjustedData = fixedData % 1 == 0 ? parseInt(fixedData) : fixedData
    return this.dataType == 'Number' && this.unit == 'inch' ? adjustedData : this.data
  },
  set: function(value) {
    if (this.dataType !== 'String') {
      var val = this.unit == 'inch' ? this.$utils.toFixedNumber(value * 25.4, 3) : parseInt(value)
      this.$emit('update:data', val)
    } else {
      this.$emit('update:data', value)
    }
  }
}

it's updating the data prop with a few adjustments to the inputted (number) value. how do i get the :value to dynamically change from the parent component to the child component and update the input value accordingly?


问:
R - recode from percentage to a scale from 1-10
The variable I'm working with is described as;

4.111.108 School enrollment, preprimary (% gross) (wdi_gerpp)

Total enrollment in pre-primary education, regardless of age, expressed as a percentage of the total population of ocial pre-primary education age. GER can exceed 100% due to the inclusion of over-aged and under-aged students because of early or late school entrance and grade repetition.

I want to recode the percentages to a scale from 1-11, e.g the countries that have 1-10% preprimary enrollment get the number 1, the countries with 11-20% get the number 2 etc. And the countries above 100% get the number 11. I can really figure out how to do it after researching on YouTube for an hour now. thank you! :D

I tried this, but I don't really now what to put inside the brackets.

percent_vec = paste(1:177, "%", sep = "")
as.numeric(sub("%", "", percent_vec))


问:
androidTV / googleTV cannot deploy to LEANBACK TV emulator
why dont apps deploy to the android tv emulator. im just trying to use the basic leanback sample here https://github.com/android/tv-samples. it works with pixel API 30 phone emulator but when using the android tv emulator it just says "waiting for all devices to come online" even though the emulator has started.

both the phone and tv emulators were just created through android studio using android 11 api 30

nothing on google helps. this is specific to the tv emulator. the apps deploy the phone ok.


问:
How to properly call methods and functions removing the need for static
I watched a course on OOP PDO a few months ago it was built using static and non static with autoload class maps,

but after some time reading and searching on stack overflow and this site here static methods

I decided to learn about namespaces and PSR4, I am not using a MVC as of yet but just trying to get my ducks in a row.

The included navbar used a static method to show or hide links based on a static method

```<code><div id="topbar">
    <div class="navi">
        <a href="<?= APP_URL ?>">Home</a>
        <a href="<?= APP_URL ?>/About</a>
        <a href="#">Community</a>
        <?php if (Auth::isLoggedIn()) : ?>
            <a href="<?= APP_URL ?>/account">Account</a>
            <a href="<?= APP_URL ?>/logout">Logout</a>
        <?php else: ?>
            <a href="<?= APP_URL ?>/registration">Signup</a>
            <a href="<?= APP_URL ?>/login">Login</a>
        <?php endif; ?>
    </div>
</div>
</code>```

The static method require_login

```<code>    public static function require_login(): void
    {
        if (!static::isLoggedIn()) {
            Helpers::redirect(Paths::HOME);
        }
    }
</code>```
```<code>public function isLoggedIn(): bool
{
    return (isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in']);
}
</code>```

Both i have put in a class called Auth

I change require_login to public function

Then I changed

if (!static::isLoggedIn()) {

to

```<code>if (!$this->isLoggedIn()) {
</code>```

In my navigation I added

```<code>use App\Auth\Auth
</code>```

Then changed the navigation code to

```<code><?php if ((new Auth)->isLoggedIn()) : ?>
</code>```

my question is (new Auth)->isLoggedIn() is this a acceptable way to write or call? I have not found any information on this.

Body:
I watched a course on OOP PDO a few months ago it was built using static and non static with autoload class maps,

but after some time reading and searching on stack overflow and this site here static methods

I decided to learn about namespaces and PSR4, I am not using a MVC as of yet but just trying to get my ducks in a row.

The included navbar used a static method to show or hide links based on a static method

        <a href="<?= APP_URL ?>">Home
        <a href="<?= APP_URL ?>/About
        Community
        <?php if (Auth::isLoggedIn()) : ?>
            <a href="<?= APP_URL ?>/account">Account
            <a href="<?= APP_URL ?>/logout">Logout
        <?php else: ?>
            <a href="<?= APP_URL ?>/registration">Signup
            <a href="<?= APP_URL ?>/login">Login
        <?php endif; ?>

The static method require_login

    public static function require_login(): void
    {
        if (!static::isLoggedIn()) {
            Helpers::redirect(Paths::HOME);
        }
    }

public function isLoggedIn(): bool
{
    return (isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in']);
}

Both i have put in a class called Auth

I change require_login to public function

Then I changed

if (!static::isLoggedIn()) {

to

if (!$this->isLoggedIn()) {

In my navigation I added

use App\Auth\Auth

Then changed the navigation code to

<?php if ((new Auth)->isLoggedIn()) : ?>

my question is (new Auth)->isLoggedIn() is this a acceptable way to write or call? I have not found any information on this.


问:
Spring boot export PipedInputStream is getting locked even in separated thread
I am using spring boot application with REST API export csv file using PipedOutputStream.
But when I hit the REST API end point then it is getting locked on 100th row without any exception until I force reloading of application (java.io.PipedInputStream.awaitSpace). Logs are below.

What I know is that it must be in separated thread and hence I decided to put @Async annotation to exportCsv() method. So I suppose that this should be executed in separated thread.

Questions

How may I force to handle this operation in try catch block?

Why is it getting locked when it is in separated thread? Is my understanding correct that pin is just returned to end user while it is connected to pout as PipedOutputStream during write processing?

Here is sample code

```<code>End point class

public ResponseEntity<InputStreamResource> exportCsv(Long id) {

PipedInputSTream pin = new PipedInputSTream();
PipedOutputStream pout = new PipedOutputStream(pin);

service.exportCsv(pout, id);

return ResponseEntity.ok().headers(headers).contentType(mediaType).body(new InputStreamResource(pin));
}

---
Service class

@Async
void exportCsv(OutputStream outputStream, Long id) {
BeanWriter writer = StreamFactory.newInstance().createWriter("output", new OutputStreamWriter(outputStream));
AtomicInteger index = new AtomicInteger();
try (Stream<Data> stream = repository.streamData(id)) {
  stream.filter(Objects::nonNull).forEach(e -> {
    writer.write(e);
    int i = index.incrementAndGet();

    if (i % FLUSH_SIZE == 0) writer.flush(); System.gc();
});
}

writer.flush(); writer.close();

}
</code>```

Here is log

```<code>main" prio=10 tid=0x08066000 nid=0x48d2 in Object.wait() [0xb7fd2000..0xb7fd31e8]
   java.lang.Thread.State: TIMED_WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0xa5c28be8> (a java.io.PipedInputStream)
    at java.io.PipedInputStream.awaitSpace(PipedInputStream.java:257)
    at java.io.PipedInputStream.receive(PipedInputStream.java:215)

</code>```

Body:
I am using spring boot application with REST API export csv file using PipedOutputStream.
But when I hit the REST API end point then it is getting locked on 100th row without any exception until I force reloading of application (java.io.PipedInputStream.awaitSpace). Logs are below.

What I know is that it must be in separated thread and hence I decided to put @Async annotation to exportCsv() method. So I suppose that this should be executed in separated thread.

Questions

How may I force to handle this operation in try catch block?

Why is it getting locked when it is in separated thread? Is my understanding correct that pin is just returned to end user while it is connected to pout as PipedOutputStream during write processing?

Here is sample code

End point class

public ResponseEntity<InputStreamResource> exportCsv(Long id) {

PipedInputSTream pin = new PipedInputSTream();
PipedOutputStream pout = new PipedOutputStream(pin);

service.exportCsv(pout, id);

return ResponseEntity.ok().headers(headers).contentType(mediaType).body(new InputStreamResource(pin));
}

---
Service class

@Async
void exportCsv(OutputStream outputStream, Long id) {
BeanWriter writer = StreamFactory.newInstance().createWriter("output", new OutputStreamWriter(outputStream));
AtomicInteger index = new AtomicInteger();
try (Stream<Data> stream = repository.streamData(id)) {
  stream.filter(Objects::nonNull).forEach(e -> {
    writer.write(e);
    int i = index.incrementAndGet();

    if (i % FLUSH_SIZE == 0) writer.flush(); System.gc();
});
}

writer.flush(); writer.close();

}

Here is log

main" prio=10 tid=0x08066000 nid=0x48d2 in Object.wait() [0xb7fd2000..0xb7fd31e8]
   java.lang.Thread.State: TIMED_WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0xa5c28be8> (a java.io.PipedInputStream)
    at java.io.PipedInputStream.awaitSpace(PipedInputStream.java:257)
    at java.io.PipedInputStream.receive(PipedInputStream.java:215)


问:
getting current active tab's HTML source - chrome extension with js
I'm building an extension. When I click on the extension's icon, a UI is being loaded, from which I click a button, and a screenshot is performed.

For now, what's happening is that i'm using html2canvas, and in order to screenshot the current active tab, I need to pass that tab's HTML Source ( for now i'm capturing my own extension's window -_- ).

I was attempting on following the answer [here][1], but without success. That means, I was attempting to retrieve in the content_script.js the current page's HTML, and send it via sendMessage:

```<code>function DOMtoString(document_root) {
  var html = "",
    node = document_root.firstChild;
  while (node) {
    switch (node.nodeType) {
      case Node.ELEMENT_NODE:
        html += node.outerHTML;
        break;
      case Node.TEXT_NODE:
        html += node.nodeValue;
        break;
      case Node.CDATA_SECTION_NODE:
        html += "<![CDATA[" + node.nodeValue + "]]>";
        break;
      case Node.COMMENT_NODE:
        html += "<!--" + node.nodeValue + "-->";
        break;
      case Node.DOCUMENT_TYPE_NODE:
        // (X)HTML documents are identified by public identifiers
        html +=
          "<!DOCTYPE " +
          node.name +
          (node.publicId ? ' PUBLIC "' + node.publicId + '"' : "") +
          (!node.publicId && node.systemId ? " SYSTEM" : "") +
          (node.systemId ? ' "' + node.systemId + '"' : "") +
          ">\n";
        break;
    }
    node = node.nextSibling;
  }
  return html;
}

chrome.runtime.sendMessage({
  action: "getSource",
  source: DOMtoString(document),
});
</code>```

then, in a file which popup is mounting, I have done the following, in order to attempt and grab that message (important to state - i was also trying the following code in background.js, same result):

```<code>chrome.runtime.onMessage.addListener(function (request, sender) {
  console.log("IN THE LISTENER backfgroundE - " + message);
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});
</code>```

but for some odd reason the message is not even arriving to neither my mounted-by-popup.html file, nor in my background.js file.

Any ideas?

Manifest file:

```<code>{
  "name": "Chrome plugin for Juno issues report",
  "description": "A issues report tool as a Chrome plugin",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_title": "Juno issue report"
  },
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "index.html"
  },
  "icons": {
    "16": "juno-icon.png",
    "48": "juno-icon.png",
    "128": "juno-icon.png"
  },
  "permissions": ["desktopCapture", "tabs", "downloads", "<all_urls>"],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content_script.js"]
    }
  ]
}
</code>```

I'll just add that the names of the files are aligned with the names mentioned in the manifest file.

Image of my files tree can be seen here:
[![enter image description here][2]][2]

Regards!
[1]: Getting the source HTML of the current page from chrome extension
[2]: https://i.stack.imgur.com/jh3Gf.png

Body:
I'm building an extension. When I click on the extension's icon, a UI is being loaded, from which I click a button, and a screenshot is performed.

For now, what's happening is that i'm using html2canvas, and in order to screenshot the current active tab, I need to pass that tab's HTML Source ( for now i'm capturing my own extension's window -_- ).

I was attempting on following the answer [here][1], but without success. That means, I was attempting to retrieve in the content_script.js the current page's HTML, and send it via sendMessage:

function DOMtoString(document_root) {
  var html = "",
    node = document_root.firstChild;
  while (node) {
    switch (node.nodeType) {
      case Node.ELEMENT_NODE:
        html += node.outerHTML;
        break;
      case Node.TEXT_NODE:
        html += node.nodeValue;
        break;
      case Node.CDATA_SECTION_NODE:
        html += "<![CDATA[" + node.nodeValue + "]]>";
        break;
      case Node.COMMENT_NODE:
        html += "";
        break;
      case Node.DOCUMENT_TYPE_NODE:
        // (X)HTML documents are identified by public identifiers
        html +=
          "<!DOCTYPE " +
          node.name +
          (node.publicId ? ' PUBLIC "' + node.publicId + '"' : "") +
          (!node.publicId && node.systemId ? " SYSTEM" : "") +
          (node.systemId ? ' "' + node.systemId + '"' : "") +
          ">\n";
        break;
    }
    node = node.nextSibling;
  }
  return html;
}

chrome.runtime.sendMessage({
  action: "getSource",
  source: DOMtoString(document),
});

then, in a file which popup is mounting, I have done the following, in order to attempt and grab that message (important to state - i was also trying the following code in background.js, same result):

chrome.runtime.onMessage.addListener(function (request, sender) {
  console.log("IN THE LISTENER backfgroundE - " + message);
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});

but for some odd reason the message is not even arriving to neither my mounted-by-popup.html file, nor in my background.js file.

Any ideas?

Manifest file:

{
  "name": "Chrome plugin for Juno issues report",
  "description": "A issues report tool as a Chrome plugin",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_title": "Juno issue report"
  },
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "index.html"
  },
  "icons": {
    "16": "juno-icon.png",
    "48": "juno-icon.png",
    "128": "juno-icon.png"
  },
  "permissions": ["desktopCapture", "tabs", "downloads", "<all_urls>"],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content_script.js"]
    }
  ]
}

I'll just add that the names of the files are aligned with the names mentioned in the manifest file.

Image of my files tree can be seen here:
[![enter image description here][2]][2]

Regards!
[1]: Getting the source HTML of the current page from chrome extension
[2]: https://i.stack.imgur.com/jh3Gf.png


问:
Display HTML Popup when a 3D mesh is clicked
I am currently working on an art gallery project with THREE.JS and React.js, and I would like to display html content about a painting when I click on a sign that is a 3D object. But I can't figure out how to do it, if you have any tips to help me it would be awesome!

There is my sign who is a 3D object :
3D sign

And when i click of this sign i would like to have something like that :
html popup

Thanks for reading me!

Nothing i don't know how to proceed


问:
How could I go about doing real-time system audio processing?
I've been trying to find sources online for real-time system audio processing, but cannot seem to find anything I'm looking for. I've checked out some Python libraries, like PyAudio and librosa, but I believe their use-cases are different from what I'm looking for. I made a quick test with PyAudio, and it seems that I can only process my audio input (my system's microphone).

My goal is to play Spotify, a YouTube video, or whatever from my computer and to process the audio-- I'd like to process system sounds in real-time.


问:
Jest websocket test is throwing an error "thrown: "Exceeded timeout of 5000 ms for a test"
I am using the ws library to create a websocket server

I am getting this error on running the test

src/server/server.ts

```<code>import { Server } from 'http';
import WebSocket from 'ws';
import { sessionHandler } from './sessionHandler';

export const websocketServer = new WebSocket.Server({
  noServer: true,
  clientTracking: false,
  path: '/ws',
});

const WEBSOCKET_CHECK_IDLE_CONNECTION_FREQUENCY =
  +process.env.WEBSOCKET_CHECK_IDLE_CONNECTION_FREQUENCY;

function checkIfConnectionIsAlive(ws: WebSocket) {
  if (ws.isAlive === false) {
    clearTimeout(ws.timer);
    return ws.terminate();
  }
  ws.isAlive = false;
  ws.ping();
  ws.timer = setTimeout(
    checkIfConnectionIsAlive,
    WEBSOCKET_CHECK_IDLE_CONNECTION_FREQUENCY,
    ws,
  );
}

function heartbeat() {
  this.isAlive = true;
}

export function upgradeToWebSocketConnection(server: Server) {
  server.on('upgrade', (request, socket, head) => {
    sessionHandler(request, {}, () => {
      websocketServer.handleUpgrade(request, socket, head, (ws) => {
        websocketServer.emit('connection', ws, request);
      });
    });
  });
}

websocketServer.on('connection', (ws, request) => {
  ws.isAlive = true;
  ws.on('pong', heartbeat);
  ws.send('hello');
  checkIfConnectionIsAlive(ws);
});

websocketServer.on('close', () => {
  console.debug('Shutting down websocket server');
});
</code>```

I wrote a simple test to check if I get that hello message on connecting to the server

src/tests/websocket.test.ts

```<code>import http, { Server } from 'http';
import {
  upgradeToWebSocketConnection,
  websocketServer,
} from 'server/websocket';
import WebSocket from 'ws';

function startServer(port: number): Promise<Server> {
  const server = http.createServer();

  return new Promise((resolve) => {
    server.listen(port, () => resolve(server));
  });
}

function waitForSocketState(socket: WebSocket, state: number): Promise<void> {
  return new Promise(function (resolve) {
    setTimeout(function () {
      if (socket.readyState === state) {
        resolve();
      } else {
        waitForSocketState(socket, state).then(resolve);
      }
    });
  });
}

let server: Server;
describe('Websocket server tests', () => {
  beforeEach(async () => {
    server = await startServer(8000);
    upgradeToWebSocketConnection(server);
  });

  afterEach(() => {
    websocketServer.emit('close');
    server.close();
  });

  test('Server sends hello to the client on connect', async () => {
    const client = new WebSocket(`ws://localhost:8000/ws`);

    let message: WebSocket.Data;

    client.on('message', (data) => {
      message = data.toString();

      client.close();
    });

    await waitForSocketState(client, client.OPEN);
    await waitForSocketState(client, client.CLOSED);
    expect(message).toBe('hello');
  });
});
</code>```

Can someone kindly tell me how to fix this error and make the test succeed? My guess is that it has a problem with the setTimeout section

Body:
I am using the ws library to create a websocket server

I am getting this error on running the test

src/server/server.ts

import { Server } from 'http';
import WebSocket from 'ws';
import { sessionHandler } from './sessionHandler';

export const websocketServer = new WebSocket.Server({
  noServer: true,
  clientTracking: false,
  path: '/ws',
});

const WEBSOCKET_CHECK_IDLE_CONNECTION_FREQUENCY =
  +process.env.WEBSOCKET_CHECK_IDLE_CONNECTION_FREQUENCY;

function checkIfConnectionIsAlive(ws: WebSocket) {
  if (ws.isAlive === false) {
    clearTimeout(ws.timer);
    return ws.terminate();
  }
  ws.isAlive = false;
  ws.ping();
  ws.timer = setTimeout(
    checkIfConnectionIsAlive,
    WEBSOCKET_CHECK_IDLE_CONNECTION_FREQUENCY,
    ws,
  );
}

function heartbeat() {
  this.isAlive = true;
}

export function upgradeToWebSocketConnection(server: Server) {
  server.on('upgrade', (request, socket, head) => {
    sessionHandler(request, {}, () => {
      websocketServer.handleUpgrade(request, socket, head, (ws) => {
        websocketServer.emit('connection', ws, request);
      });
    });
  });
}

websocketServer.on('connection', (ws, request) => {
  ws.isAlive = true;
  ws.on('pong', heartbeat);
  ws.send('hello');
  checkIfConnectionIsAlive(ws);
});

websocketServer.on('close', () => {
  console.debug('Shutting down websocket server');
});

I wrote a simple test to check if I get that hello message on connecting to the server

src/tests/websocket.test.ts

import http, { Server } from 'http';
import {
  upgradeToWebSocketConnection,
  websocketServer,
} from 'server/websocket';
import WebSocket from 'ws';

function startServer(port: number): Promise<Server> {
  const server = http.createServer();

  return new Promise((resolve) => {
    server.listen(port, () => resolve(server));
  });
}

function waitForSocketState(socket: WebSocket, state: number): Promise<void> {
  return new Promise(function (resolve) {
    setTimeout(function () {
      if (socket.readyState === state) {
        resolve();
      } else {
        waitForSocketState(socket, state).then(resolve);
      }
    });
  });
}

let server: Server;
describe('Websocket server tests', () => {
  beforeEach(async () => {
    server = await startServer(8000);
    upgradeToWebSocketConnection(server);
  });

  afterEach(() => {
    websocketServer.emit('close');
    server.close();
  });

  test('Server sends hello to the client on connect', async () => {
    const client = new WebSocket(`ws://localhost:8000/ws`);

    let message: WebSocket.Data;

    client.on('message', (data) => {
      message = data.toString();

      client.close();
    });

    await waitForSocketState(client, client.OPEN);
    await waitForSocketState(client, client.CLOSED);
    expect(message).toBe('hello');
  });
});

Can someone kindly tell me how to fix this error and make the test succeed? My guess is that it has a problem with the setTimeout section


问:
Error: connect ECONNREFUSED 127.0.0.1:8080 || POSTMAN
I'm working on a small project and I have to send a post request in postman, but I continue to get to connect, ECONNREFUSED 127.0.0.1:8080 error occurred.

I've already checked that I'm using the correct port and changed a few proxy setting to try and fix the problem, but nothing seems to work. When I run the project on IntelliJ, I have no errors, so I really don't know how to solve the problem.

```<code>Error: connect ECONNREFUSED 127.0.0.1:8080
Request Headers
Content-Type: application/json
User-Agent: PostmanRuntime/7.29.2
Accept: */*
Cache-Control: no-cache
Postman-Token: 6ea87f2c-511f-4124-a1ac-3c7d29fb6c81
Host: localhost:8080
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
</code>```

Body:
I'm working on a small project and I have to send a post request in postman, but I continue to get to connect, ECONNREFUSED 127.0.0.1:8080 error occurred.

I've already checked that I'm using the correct port and changed a few proxy setting to try and fix the problem, but nothing seems to work. When I run the project on IntelliJ, I have no errors, so I really don't know how to solve the problem.

Error: connect ECONNREFUSED 127.0.0.1:8080
Request Headers
Content-Type: application/json
User-Agent: PostmanRuntime/7.29.2
Accept: */*
Cache-Control: no-cache
Postman-Token: 6ea87f2c-511f-4124-a1ac-3c7d29fb6c81
Host: localhost:8080
Accept-Encoding: gzip, deflate, br
Connection: keep-alive


问:
Counting the number of time a dynamic category appeaed
I hope you are all doing well,
I am stuck at a problem and can't find a ways out. I have a sample table with shops name, target and date. Based on the target a dax measure is written which which will define the category for that particular shop.
for example if I select date between 1 december, 20222 to 2 decemeber 2022 than the category of  a1 store will be "D" however if choose date upto 3 december , 2022 the category of a1 store will be "A".   Following dax is used to assign the category.

```<code>Category =
var t1 = sum('Table'[Target])
return
if(t1 >=15 ,"A", if(t1<15 && t1>=10, "B", if(t1>10 && t1<=5, "C","D")))
</code>```

Now I want to count the total number of stores fall in a specefic category based show the total against those stores with respect to the chosen date and show blank in total for category and for count.

The output should be like this.

Kindly help

To create dax measure based on my requirements mentioned before.

Body:
I hope you are all doing well,
I am stuck at a problem and can't find a ways out. I have a sample table with shops name, target and date. Based on the target a dax measure is written which which will define the category for that particular shop.
for example if I select date between 1 december, 20222 to 2 decemeber 2022 than the category of  a1 store will be "D" however if choose date upto 3 december , 2022 the category of a1 store will be "A".   Following dax is used to assign the category.

Category =
var t1 = sum('Table'[Target])
return
if(t1 >=15 ,"A", if(t1<15 && t1>=10, "B", if(t1>10 && t1<=5, "C","D")))

Now I want to count the total number of stores fall in a specefic category based show the total against those stores with respect to the chosen date and show blank in total for category and for count.

The output should be like this.

Kindly help

To create dax measure based on my requirements mentioned before.


问:
Send Grid response not getting on the WebHook
We are trying to integrate the send grid api using the provided doc to setup the authentication and use webhoook to check the response.

We have set up the Event Webhook followed by the https://docs.sendgrid.com/for-developers/tracking-events/getting-started-event-webhook-security-features document.
We are using "Authorization Method" as OAuth-2.0 and provided the client id, client secret, token url and the http post url, handling all this by our class which we build in salesforce.
enter image description here

We are trying to hit the using the postman collect we are getting "204 no content"
and no response on webhook.


问:
Filter out everything except values of monotonic growth
Say I have micrometer timer my.timer. I have grafana metric max(my_timer_seconds_max) by (pod) that gives:

I need a metric that shows only values that grow at least for 5 minutes and filter out everything else:


问:
How to update rabbitMQ with kerl management of erlang versions
I have an pet project with using RabbitMQ 3.8.2
After some time I found that I can't connect to RabbitMQ CLI on 127.0.0.1:15672
I installed kerl for managing erlang versions, and then installed and activated erlang 25.0
I made attempt to update RabbitMQ with command

```<code>curl -s https://packagecloud.io/install/repositories/rabbitmq/rabbitmq-server/script.deb.sh | sudo bash
</code>```

from https://packagecloud.io/rabbitmq/rabbitmq-server/install
After I run command

```<code>apt-get install rabbitmq-server=3.11.4-1
</code>```

But I got next error:

```<code>Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 rabbitmq-server : Depends: erlang-base (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            erlang-base-hipe (>= 1:21.3) but it is not going to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-crypto (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-eldap (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-inets (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-mnesia (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-os-mon (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-parsetools (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-public-key (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-runtime-tools (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-ssl (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-syntax-tools (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-tools (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-xmerl (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
E: Unable to correct problems, you have held broken packages.
</code>```

I have tried advices from this cases

Unable to install rabbitmq due to incorrect versions of erlang dependencies

https://askubuntu.com/questions/1188699/rabbitmq-packages-have-unmet-dependencies
with the exception of erlang updating, because I have activated erlang 25.0 version with kerl.
Error always the same.

Body:
I have an pet project with using RabbitMQ 3.8.2
After some time I found that I can't connect to RabbitMQ CLI on 127.0.0.1:15672
I installed kerl for managing erlang versions, and then installed and activated erlang 25.0
I made attempt to update RabbitMQ with command

curl -s https://packagecloud.io/install/repositories/rabbitmq/rabbitmq-server/script.deb.sh | sudo bash

from https://packagecloud.io/rabbitmq/rabbitmq-server/install
After I run command

apt-get install rabbitmq-server=3.11.4-1

But I got next error:

Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 rabbitmq-server : Depends: erlang-base (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            erlang-base-hipe (>= 1:21.3) but it is not going to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-crypto (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-eldap (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-inets (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-mnesia (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-os-mon (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-parsetools (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-public-key (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-runtime-tools (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-ssl (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-syntax-tools (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-tools (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
                   Depends: erlang-xmerl (>= 1:21.3) but 1:20.2.2+dfsg-1ubuntu2 is to be installed or
                            esl-erlang (>= 1:21.3) but it is not installable
E: Unable to correct problems, you have held broken packages.

I have tried advices from this cases

Unable to install rabbitmq due to incorrect versions of erlang dependencies

https://askubuntu.com/questions/1188699/rabbitmq-packages-have-unmet-dependencies
with the exception of erlang updating, because I have activated erlang 25.0 version with kerl.
Error always the same.


问:
Change one menu item size in BottomNavigationView
I've bottom menu bar that has 4 items from which one has to look differently (not depending on which item is selected/not). One item has to have bigger icon size.

Currently I'm styling my elements like this:

```<code><style name="BottomNavigationView">
    <item name="itemIconTint">@color/gray</item>
    <item name="itemIconSize">26dp</item>
</style>
</code>```

However, itemIconSize is affecting all menu items and not one specific. How to change icon size for specific menu item?

Body:
I've bottom menu bar that has 4 items from which one has to look differently (not depending on which item is selected/not). One item has to have bigger icon size.

Currently I'm styling my elements like this:

However, itemIconSize is affecting all menu items and not one specific. How to change icon size for specific menu item?


问:
Why quantity in "Stock On Hand" is different (dismatch) with quantity in "Stock Move"
enter image description here

Example :
I bought 8 pcs product,then in the Stock Move its written 8 pcs product, but why in the Stock On Hand its written only 4 pcs product?

How to fix it?

The "Quantity" and the "Available Quantity" also should be written 8 pcs right?


问:
Automation data extraction from AutoCad to excel
I know that there is a way to extract the properties of the objects of a drawing from autocad to an excel table, I wanted to know if it was possible, given the path of a file, to automate the extraction of this data to an excel table

In particular I would like to create something capable of extracting data from an autocad drawing and transferring them directly to an excel table, taking as input the path of the .dwg file and the name of the table it will have to create