2021年5月8日星期六

How can i get refreshtoken from headers when i use node.js?

I have two accesstoken and refreshtoken in authorization.

The one in front is the accesstoken and the one in the back is the refreshtoken. Getting the accesstoken in front was successful, how can I filter out the refreshtoken?

this is headers

headers: {                  authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjE3MjA2OTc4MzciLCJpYXQiOjE2MjA0NTkzMTYsImV4cCI6MTYyMDQ1OTMyMX0.eYTj0L2g6Z1BM7C-EmtJUXWw9l_t5ua59-w5ZQrvTfU             //this is refreshtoken  //          eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjE3MjA2OTc4MzciLCJpYXQiOjE2MjA0NTkzMTYsImV4cCI6MTYyMDQ1OTQzNn0.8rl3avx3eL7DhxCgu1kUTqYr_f2fjNs7o-ZxEUTsKs8',  }  

Getting the accesstoken in front was successful, like this

        const authHeader = req.headers["authorization"];          const token = authHeader && authHeader.split(" ")[1];          console.log("token::::::::", token);            //success get accesstoken  

then how can i get refreshtoken?

i want to get refreshtoken like this

console.log(refreshtoken)  eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjE3MjA2OTc4MzciLCJpYXQiOjE2MjA0NTkzMTYsImV4cCI6MTYyMDQ1OTQzNn0.8rl3avx3eL7DhxCgu1kUTqYr_f2fjNs7o-ZxEUTsKs8  
https://stackoverflow.com/questions/67445223/how-can-i-get-refreshtoken-from-headers-when-i-use-node-js May 08, 2021 at 03:44PM

Why my neural does not converge using Jax

I am learning Jax, but I encountered an weird question. If I using the code as follows,

import numpy as np  import jax.numpy as jnp  from jax import grad, value_and_grad  from jax import vmap # for auto-vectorizing functions  from functools import partial # for use with vmap  from jax import jit # for compiling functions for speedup  from jax import random # stax initialization uses jax.random  from jax.experimental import stax # neural network library  from jax.experimental.stax import Conv, Dense, MaxPool, Relu, Flatten, LogSoftmax # neural network layers  import matplotlib.pyplot as plt # visualization    net_init, net_apply = stax.serial(      Dense(40), Relu,      Dense(40), Relu,      Dense(40), Relu,      Dense(1)  )  rng = random.PRNGKey(0)  in_shape = (-1, 1,)  out_shape, params = net_init(rng, in_shape)    def loss(params, X, Y):      predictions = net_apply(params, X)      return jnp.mean((Y - predictions)**2)    @jit  def step(i, opt_state, x1, y1):      p = get_params(opt_state)      val, g = value_and_grad(loss)(p, x1, y1)      return val, opt_update(i, g, opt_state)    opt_init, opt_update, get_params = optimizers.adam(step_size=1e-3)  opt_state = opt_init(params)    val_his = []  for i in range(100):      val, opt_state = step(i, opt_state, xrange_inputs, targets)      val_his.append(val)  params = get_params(opt_state)  val_his = jnp.array(val_his)    xrange_inputs = jnp.linspace(-5,5,100).reshape((100, 1)) # (k, 1)  targets = jnp.cos(xrange_inputs)  predictions = vmap(partial(net_apply, params))(xrange_inputs)  losses = vmap(partial(loss, params))(xrange_inputs, targets) # per-input loss    plt.plot(xrange_inputs, predictions, label='prediction')  plt.plot(xrange_inputs, losses, label='loss')  plt.plot(xrange_inputs, targets, label='target')  plt.legend()  

the neural network can approximate the function cos(x) well.

But if I rewrite the neural network part by myself as follows

import numpy as np  import jax.numpy as jnp  from jax import grad, value_and_grad  from jax import vmap # for auto-vectorizing functions  from functools import partial # for use with vmap  from jax import jit # for compiling functions for speedup  from jax import random # stax initialization uses jax.random  from jax.experimental import stax # neural network library  from jax.experimental.stax import Conv, Dense, MaxPool, Relu, Flatten, LogSoftmax # neural network layers  import matplotlib.pyplot as plt # visualization  import numpy as np  from jax.experimental import optimizers  from jax.tree_util import tree_multimap    def initialize_NN(layers, key):              params = []      num_layers = len(layers)      keys = random.split(key, len(layers))      a = jnp.sqrt(0.1)      #params.append(a)      for l in range(0, num_layers-1):          W = xavier_init((layers[l], layers[l+1]), keys[l])          b = jnp.zeros((layers[l+1],), dtype=np.float32)          params.append((W,b))      return params    def xavier_init(size, key):      in_dim = size[0]      out_dim = size[1]            xavier_stddev = jnp.sqrt(2/(in_dim + out_dim))      return random.truncated_normal(key, -2, 2, shape=(out_dim, in_dim), dtype=np.float32)*xavier_stddev        def net_apply(params, X):      num_layers = len(params)      #a = params[0]      for l in range(0, num_layers-1):          W, b = params[l]          X = jnp.maximum(0, jnp.add(jnp.dot(X, W.T), b))      W, b = params[-1]      Y = jnp.dot(X, W.T)+ b      Y = jnp.squeeze(Y)      return Y        def loss(params, X, Y):      predictions = net_apply(params, X)      return jnp.mean((Y - predictions)**2)    key = random.PRNGKey(1)  layers = [1,40,40,40,1]  params = initialize_NN(layers, key)    @jit  def step(i, opt_state, x1, y1):      p = get_params(opt_state)      val, g = value_and_grad(loss)(p, x1, y1)      return val, opt_update(i, g, opt_state)    opt_init, opt_update, get_params = optimizers.adam(step_size=1e-3)  opt_state = opt_init(params)    val_his = []  for i in range(10000):      val, opt_state = step(i, opt_state, xrange_inputs, targets)      val_his.append(val)  params = get_params(opt_state)  val_his = jnp.array(val_his)      xrange_inputs = jnp.linspace(-5,5,100).reshape((100, 1)) # (k, 1)  targets = jnp.cos(xrange_inputs)  predictions = vmap(partial(net_apply, params))(xrange_inputs)  losses = vmap(partial(loss, params))(xrange_inputs, targets) # per-input loss    plt.plot(xrange_inputs, predictions, label='prediction')  plt.plot(xrange_inputs, losses, label='loss')  plt.plot(xrange_inputs, targets, label='target')  plt.legend()  

my neural network will always converge to a constant, which seems to be trapped by a local minima. I am really confused about that.

The only differences should be initialization, the neural network part and the setting for the parameter params. I have tried different initialization, which make no difference. I wonder if it it because of the setting for optimizing params is wrong, then I can not get convergence.

https://stackoverflow.com/questions/67444953/why-my-neural-does-not-converge-using-jax May 08, 2021 at 03:05PM

Vue ref/reactive with default value

I am using Vue3 composition API. I have an input field which needs to be in sync with store, incase the data changes in store it should be updated

Code

const store = useStore()  const savedAge = computed(() => store.state.profile.age)  // The saved is async and can be updated at anytime in store     const age = ref(savedAge.value)    <!-- template -->  <input v-model="age" /> // here the age is null event if savedAge value has updated in store    

Please note I don't want two way binding with store, I want my reactive property to update if store value has been updated

How do I achieve this?

https://stackoverflow.com/questions/67437365/vue-ref-reactive-with-default-value May 07, 2021 at 11:03PM

Angular redirect to dist

Is there a solution to automatically redirect to Angular dist folder if we first try to acess to the root project ? (Instead of display the following) : enter image description here

I tried with .htaccess but without success, I have a 404 error :

RewriteEngine On  RewriteCond %{REQUEST_URI} !^/dist/  RewriteRule ^(.*)$ /dist/$1 [L]  

Thanks

https://stackoverflow.com/questions/67436603/angular-redirect-to-dist May 07, 2021 at 10:15PM

2021年5月7日星期五

Collapsible nabbed being covered by other elements Bootstrap

I have used Bootstrap to make a collapsible navbar, which has a toggle button to open it up. But when I added more elements after the navbar, they don't seem to move down when clicking the toggle button, thus the navbar functionality is working fine, it's just not showing up there. What can I do? Here's my code:

<nav class="navbar navbar-expand-lg navbar-light" style="width: 100vw; height: 15vh; background-color: white;">     <div class="container-fluid">      <a class="navbar-brand" href="#"><div id="logoimg"></div></a>               <button id="the-toggle-btn" onclick="onToggleClick()" class="navbar-toggler" style="right: 0%;" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight">            <span class="navbar-toggler-icon"></span>     </button>                <div class="collapse navbar-collapse" id="collapsibleNavbar">      <ul class="navbar-nav">        <li class="nav-item">          <div class="dropdown show">    <a class="btn dropdown-toggle" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">    Top Talent    </a>      <div class="dropdown-menu" aria-labelledby="dropdownMenuLink">      <a class="dropdown-item">MetaExperts Skills Directory</a>      <a class="dropdown-item">MetaExperts Expertise</a>      <a class="dropdown-item">Support</a>    </div>  </div>        </li>        <li class="nav-item">          <a class="nav-link" href="#">Why Expert</a>        </li>        <li class="nav-item">          <a class="nav-link" href="#">Customer Service</a>        </li>         <li class="nav-item">          <a class="nav-link" href="#">Resources</a>        </li>        <li class="nav-item">          <a class="nav-link" href="#">About</a>        </li>        <li class="nav-item">          <a class="nav-link" href="#">Contact Us</a>        </li>             <li class="nav-item">          <a class="nav-link" href="#">Executive Blog</a>        </li>      </ul>       </div>        <form class="d-flex flex-row">         <i class="fa fa-search" id="search-icon" style="font-size: 4vh; margin-left: 75%; margin-right: 5vh;"></i>         <input id="searchbox" class="form-control me-2 type="search" placeholder="Search" aria-label="Search">       <i class="fa fa-times" id="close-icon"></i>        </form>           </div>    </nav>  <!-- Here is where the navber ends and the problem begins. I want the images below to move down when the navber is collapsed-->  <div id="image-cover">    <div class="demo-img" id="demo-image-one"></div>     <div class="demo-img" id="demo-image-two"></div>     <div class="demo-img" id="demo-image-three"></div>   </div>  
https://stackoverflow.com/questions/67444580/collapsible-nabbed-being-covered-by-other-elements-bootstrap May 08, 2021 at 02:06PM

add the day information to timestep in a dataframe

I am trying to read the csv file into a dataframe,the csv fileThe csv file looks like this.

enter image description here

The cell value only contains the hour information and miss the day information. I would like to read this csv file into a dataframe and transform the timing information into the format like 2021-05-07 04:04.00 i.e., I would like to add the day information . How to achieve that.

I used the following code, but it seems that pyspark just add the day information as 1970=01=01, kind of system setting.

spark = SparkSession.builder.getOrCreate()  spark.conf.set("spark.sql.legacy.timeParserPolicy","LEGACY")  df_1 = spark.read.csv('test1.csv', header = True)  df_1 = df_1.withColumn('Timestamp', to_timestamp(col('Timing'), 'HH:mm'))  df_1.show(truncate=False)  

And I got the following result.

+-------+-------------------+  | Timing|          Timestamp|  +-------+-------------------+  |04:04.0|1970-01-01 04:04:00|  |19:04.0|1970-01-01 19:04:00|  
https://stackoverflow.com/questions/67444579/add-the-day-information-to-timestep-in-a-dataframe May 08, 2021 at 02:06PM

(Next JS 10.2) Audio Worklet Support

Our application is built on top of Next, and we are currently in the process of migrating our audio recording engine to Audio Worklet API from Script Processor. (with backwards compatibility of course) Part of the transition is also upgrading to Webpack 5. We are utilizing both Web Workers and Audio Worklets. Prior to switch to Webpack 5, which comes with native support for Workers, (or so it appears) we used worker-plugin. It worked wonderfully for both, however with the transition we can no longer rely on it, because it uses outdated webpack's APIs, and Next comes with its own bundled Webpack 4 and 5, which don't seem to have backwards compatibility included.

Now the challenge is to get these working with Webpack 5 bundled with Next. The first issue comes from web worker's global scope being undefined. This can be resolved with by setting config.output.globalObject to "(typeof self !== 'undefined' ? self : this)". Once workers are functional, the next issue comes when trying to bundle worklet's code. Currently, Webpack 5 doesn't support worklet import, but they expose parser config, which can be used to tell webpack to load it as a worker, as per this Github issue. This will fail with Next unless you also set config.output.publicPath = "/_next/"; Upon loading the chunk via audioContext.audioWorklet.addModule(...), the code crashes with Uncaught TypeError: Cannot read property 'webpackChunk_N_E' of undefined. If we inspect the chunk containing bundled worklet code, we'll see that this prop is being used in the following way:

var chunkLoadingGlobal = (typeof self !== 'undefined' ? self : this)["webpackChunk_N_E"] = (typeof self !== 'undefined' ? self : this)["webpackChunk_N_E"] || [];  var parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);  .  .  .  (typeof self !== 'undefined' ? self : this)["webpackHotUpdate_N_E"] = function...  

It's clear, that AudioWorkletGlobalScope doesn't have either self or this, so that's why it's not going too well.

So the question is, how can this be worked around? Audio Worklets seem to be getting very little attention still from both Next and Webpack, despite it being available by default now even in Safari. (since 14.5)

Below are the code snippets representing our current state. (we are using Typescript)

next.config.js

module.exports = withPlugins([...], {    future: {webpack5: true},    webpack: (config, options) => {      config.output.globalObject = `(typeof self !== 'undefined' ? self : this)`;      config.output.publicPath = "/_next/";        config.resolve = {        ...config.resolve,        alias: {          ...config.resolve.alias,          "audio-worklet": path.resolve(__dirname, "src/util/audio-worklet")        }      }        config.module.parser = {        ...config.module.parser,        javascript: {          worker: ["AudioWorklet from audio-worklet", "..."]        }      }        config.output.chunkFilename = options.isServer        ? `${options.dev ? "[name].[hash]" : "[name].[chunkhash]"}.js`        : `static/chunks/${options.dev ? "[name].[hash]" : "[name].[chunkhash]"}.js`;        return config;    }  });  

src/util/audio-worklet.ts

export const AudioWorklet = (url: URL) => {    return url as unknown as string;  };  

.../audio-context.ts

import { AudioWorklet } from "audio-worklet";    const audioContext = new AudioContext();  audioContext.audioWorklet.addModule(new AudioWorklet(new URL("path/to/processor.worklet.ts", import.meta.url)));  

.../audio-worklet-processor.worklet.ts

// import statements for utility code    class Processor extends AudioWorkletProcessor {    // Your run of the mill processor code  }    registerProcessor("processor", Processor);  

Sources:

https://stackoverflow.com/questions/67444578/next-js-10-2-audio-worklet-support May 08, 2021 at 02:06PM

Xcode 12.2 debug iPhone 11 Pro iOS14.5 device, all variable is nil in breakpoint

Due to company restrictions,I cannot upgrade macos 11,so cannot use xcode12.5

add iOS 14.5 devicesupport into xcode12.2, everything is normal when debug on simulators, but debug on real iOS14.5 device, the all variable is nil in breakpoint,anyone know how to solve it, thanks for your help!

Text

https://stackoverflow.com/questions/67444577/xcode-12-2-debug-iphone-11-pro-ios14-5-device-all-variable-is-nil-in-breakpoint May 08, 2021 at 02:05PM

Php procedure sqlsrv script with MSSQL error

I would also need help with the procedure. I have written this code in php

      $sql = "EXEC EXPORT_DAT @id_w = '".$id_w."'";    $stmt = sqlsrv_prepare($link, $sql);    if (!sqlsrv_execute($stmt)) {  echo die( print_r( sqlsrv_errors(), true));    }    else     {    while($row  = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC)) {    $value[] = $row;    }    echo json_encode($value);    }  

but the procedure returns this error.

Array ( [0] => Array ( [0] => 01000 [SQLSTATE] => 01000 [1] => 0 [code] => 0 [2] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]CREATE TABLE tbl_point_50000263 (id varchar (max)) [message] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]CREATE TABLE tbl_point_50000263 (id varchar (max)) ) )

I don't know what can be wrong because C # it works.

Thank you

https://stackoverflow.com/questions/67444575/php-procedure-sqlsrv-script-with-mssql-error May 08, 2021 at 02:05PM

In shopify is it possible to develop the front-end by using React JS

I am curious about using React JS in the Shopify theme only for the front-end. I want to use the liquid for the backend as Shopify provides, but for the front-end, I want to develop it in React JS.

Is it possible? If yes How? I didn't use the react in Shopify.

https://stackoverflow.com/questions/67444573/in-shopify-is-it-possible-to-develop-the-front-end-by-using-react-js May 08, 2021 at 02:05PM

Why does socket.io give a ERR_CONNECTION_TIMED_OUT error?

The browser console shows:

socket.io.min.js:6 GET http://www.europasprak.com:9001/socket.io/?EIO=4&transport=polling&t=NbAYx93 net::ERR_CONNECTION_TIMED_OUT  

The error can be seen live at http://www.europasprak.com/elearning/subscription/2938/course by first logging at http://www.europasprak.com/engine/modules/user/login.php with using the user demo@demo.com with the demo password.

The client connection:

var elearningSocket;  $(function() {    if ('undefined' != typeof io && 'undefined' == typeof elearningSocket) {      console.log("Creating a socket on $gSocketHostname:$NODEJS_SOCKET_PORT/elearning");      elearningSocket = io.connect('$gSocketHostname:$NODEJS_SOCKET_PORT/elearning');    }  });  

My socket.io.min.js version is:

/*!   * Socket.IO v4.0.1   * (c) 2014-2021 Guillermo Rauch   * Released under the MIT License.   */  

The server implementation:

var http = require('http');  var https = require('https');  var cors = require('cors');  var connect = require('connect');  var cookie = require('cookie');  var path = require('path');  var fs = require('fs');  var redis = require('redis');  var ioredis = require('socket.io-redis');  var socketio = require('socket.io');    var utils = require('./utils.js');  var config = require('./config');    var sslKey = '';  var sslCertificate = '';  var sslChain = '';  if (fs.existsSync(config.ssl.path + config.ssl.key)) {    sslKey = fs.readFileSync(path.resolve(config.ssl.path + config.ssl.key));    sslCertificate = fs.readFileSync(path.resolve(config.ssl.path + config.ssl.certificate));    sslChain = fs.readFileSync(path.resolve(config.ssl.path + config.ssl.chain));    console.log("The virtual host HAS an SSL private key");  } else {    console.log("The virtual host DOESN'T have an SSL private key");  }    console.log("Configuring the server for HTTP");  console.log("The HTTP server is used by the healthcheck even if the socket is served on the HTTPS server");  var httpServer = http.createServer(utils.httpHandler);  httpServer.listen(config.socketio.port, function() {    console.log('The NodeJS HTTP server [port: ' + config.socketio.port + '] is listening...');  });    if (sslKey) {    console.log("Configuring the server for HTTPS");    var options = {      key: sslKey,      cert: sslCertificate,      ca: sslChain,      requestCert: false,      rejectUnauthorized: false    };    var httpsServer = https.createServer(options, utils.httpHandler);    httpsServer.listen(config.socketio.sslport, function() {      console.log('The NodeJS HTTPS server [port: ' + config.socketio.sslport + '] is listening...');    });  }    module.exports.io = socketio(httpsServer, {    cors: {      origin: '*',      methods: [        'GET',        'POST'      ],      allowedHeaders: [],      credentials: true    }  });  console.log(module.exports.io);    module.exports.io.adapter(ioredis({ host: config.redis.hostname, port: config.redis.port }));  var redisClient = redis.createClient(config.redis.port, config.redis.hostname);    module.exports.io.use(function (socket, handler) {    if (socket.request.headers.cookie) {      socket.request.cookies = cookie.parse(decodeURIComponent(socket.request.headers.cookie));      socket.request.sessionID = socket.request.cookies['PHPSESSID'];      socket.request.socketSessionId = socket.request.cookies['socketSessionId'];      console.log("Authorization attempt with sessionID: " + socket.request.sessionID + " and socketSessionId: " + socket.request.socketSessionId);      redisClient.get("PHPREDIS_SESSION:" + socket.request.sessionID, function (error, reply) {        if (error) {          console.log("The redis client had an error: " + error);          return handler(new Error('The connection was refused because the redis client had an error.'));        } else if (!reply) {          console.log('The connection was refused because the redis client did not find the sessionID.');          return handler(new Error('The connection was refused because the redis client did not find the sessionID.'));        } else {          var redisSocketSessionId = utils.getRedisValue(reply, "socketSessionId");          if ('undefined' == typeof socket.request.socketSessionId || redisSocketSessionId != socket.request.socketSessionId) {            console.log('The connection was refused because the socketSessionId was invalid.');            return handler(new Error('The connection was refused because the socketSessionId was invalid.'));          } else {            console.log('The connection was granted.');            handler();          }        }      });    } else {      console.log('The connection was refused because no cookie was transmitted.');      return handler(new Error('The connection was refused because no cookie was transmitted.'));    }  });  
https://stackoverflow.com/questions/67444571/why-does-socket-io-give-a-err-connection-timed-out-error May 08, 2021 at 02:04PM

react hooks setInterval,Why can it be modified for the first time

Why is it that the correct count value can be obtained in setinterval after the first click, and then the transformation does not occur again?

import React, { useEffect, useState } from 'react';  const Demo1 = () => {    let [count, setCount] = useState(1);    const onCountClick = () => {      count += 1;      setCount(count);    };    useEffect(() => {      setInterval(() => {        console.log(count);      }, 1000);    }, []);    console.log(count);    return <button onClick={() => onCountClick()}>test</button>;  };  
https://stackoverflow.com/questions/67444566/react-hooks-setinterval-why-can-it-be-modified-for-the-first-time May 08, 2021 at 02:04PM

How can I work with .ctf files programmatically if I'm not the one who made them?

I have a .ctf file containing deep forex history for the last 20 years.
In order to backtest the data and visualize it with charts, I want to be able to use the data inside the file. It is not clear to me how to use the file (my understanding is that CTF files are binary files) or how it is structured.

Any help would be greatly appreciated.

https://stackoverflow.com/questions/67444565/how-can-i-work-with-ctf-files-programmatically-if-im-not-the-one-who-made-them May 08, 2021 at 02:04PM