Wednesday, August 4, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


[express,mysql]Question using mysql data in non-app.js files

Posted: 04 Aug 2021 08:16 AM PDT

https://github.com/kimwoon11/nodejs
I have GitHub. And this is the fourth directory.
Please refer to the link.
The problem is the sing-up.js file in the routes directory.
rendered sign-up.ejs file has a membership form!

router.get('/sign-up', function(req, res, next) {res.render('sign-up');});<br>  

I'd like to make id duplicate check.
but, I know that ejs file can't use DOM function.
so, External JavaScript file imported into sign-up.ejs!!

<script src="../public/javascripts/idCheck.js"></script><br>  

but it's not working.

What did I do wrong?

And can we solve this problem in another smarter way?

Automatically retrieve password for Neo4j from AWS Secret manager using terraform

Posted: 04 Aug 2021 08:16 AM PDT

Is there a way that I can automatically retrieve secrets from AWS Secrets Manager that is the password for Neo4j which is provisioned using terraform?

authentication for GCP STT Quickstart problem

Posted: 04 Aug 2021 08:16 AM PDT

I am following the GCP Speech-to-Text Quickstart. As best as I can tell, I have followed all setup criteria.

Enabled STT for my project. Generated Service API keys and downloaded the JSON file. Installed SDK and initialized. In Windows CMD shell, I set GOOGLE_APPLICATION_CREDENTIALS to the downloaded JSON file. In Windows CMD shell, I executed gcloud auth activate-service-account --key-file= "mypath/JSON key file". I executed gcloud auth list and I see my project account identifier.

I executed the example curl command: curl -s -H "Content-Type: application/json" -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) https://speech.googleapis.com/v1/speech:recognize -d @sync-request.json

And get this error: { "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED" } }

No where in the Quickstart steps does it mention OAuth

As a test, I executed: gcloud auth application-default print-access-token

And got this: (gcloud.auth.application-default.print-access-token) File "mypath/JSON key file" was not found. Even though the file exists in the folder I specify.

Trying something else, I tried executing the Java example in the SDK. It creates a very simple SpeechClient with no credentials, which seems suspect. I made the GOOGLE_APPLICATION_CREDENTIALS env variable available to the example. I think the example uses gRCP, but not sure.

The example hangs at:

RecognizeResponse response = speech.recognize(config, audio);  

Looking online, I found the likely suspect is bad authentication, which is the same as trying the CMD line example.

Any and all guidance is appreciated.

Implementing custom in-app keyboard in android

Posted: 04 Aug 2021 08:16 AM PDT

I want to create in-app keyboard like thisenter image description here I tried just adding buttons in GridLayout but I think there is more efficient way to do it. Maybe any libraries?

Currency Exchange Rate API with bid and ask prices

Posted: 04 Aug 2021 08:16 AM PDT

I'm looking to automate a daily manual process in my company. Every morning a few people are manually inserting the bid and ask prices for each of our companies base currencies and I was thinking that we can make use of some sort of API from where we can fetch the data daily.

Now, for most APIs I stumbled upon, they seem to provide a midpoint value of the bid and ask values and I'm not sure if it's possible to extract the bid and ask from the mid point value.

The API that comes closest to my needs is this one: https://docs.openexchangerates.org/docs/bid-ask-prices, but I would like to find more alternatives.

Are there any other APIs that might help?

why the first node has less data than other nodes in TDengine cluster

Posted: 04 Aug 2021 08:16 AM PDT

I built a TDengine cluster with 4 nodes, created a database with 3 replicas and inserted some data into this database. I found that the first node always has less data than other nodes. eg:

taos> use stress_test;  Database changed.    taos> show vgroups;      vgId     |   tables    |  status  |   onlines   | v1_dnode | v1_status | v2_dnode | v2_status | v3_dnode | v3_status | compacting  |  ========================================================================================================================================             3 |        1000 | ready    |           3 |        4 | master    |        3 | slave     |        2 | slave     |           0 |             4 |        1000 | ready    |           3 |        3 | master    |        4 | slave     |        2 | slave     |           0 |             5 |        1000 | ready    |           3 |        4 | master    |        3 | slave     |        2 | slave     |           0 |             6 |        1000 | ready    |           3 |        3 | master    |        2 | slave     |        4 | slave     |           0 |             7 |        1000 | ready    |           3 |        1 | master    |        3 | slave     |        4 | slave     |           0 |  Query OK, 5 row(s) in set (0.011133s)  

From above example, we can see that node 1 has only 1 vnode, node 2, 3, 4, each has 5 vnodes. why node 1 has less data than other 3 nodes?

How do I allow partial updates via POST request in Django?

Posted: 04 Aug 2021 08:16 AM PDT

Working on a small Django app and I've been asked to set up partial updates via POST request. I'm aware that PATCH works for partial updates out of the box but I don't have access to the front end and that's not what I've been asked to do.

I was told it's a quick one line change, so I'm assuming I have to update the serializer as explained in the DRF docs (https://www.django-rest-framework.org/api-guide/serializers/#partial-updates) but I'm not sure where to do that exactly.

Serializers:

from rest_framework import serializers  from cat.models import Cat  class CatSerializer(serializers.ModelSerializer):        class Meta:          model = Cat          fields = (              'id', 'name', 'breed', 'birth_date', 'added_at', 'description')  

Viewset:

from rest_framework import viewsets  from cat.serializers import CatSerializer  from cat.models import Cat    class CatViewSet(viewsets.ModelViewSet):      queryset = Cat.objects.all().order_by('-birth_date')      serializer_class = CatSerializer  

npm command returning 406 Not Acceptable with custom registry

Posted: 04 Aug 2021 08:16 AM PDT

We are having a custom artifcatory repo for npm as I can't directly access https://registry.npmjs.org/ from our lab.

[user1@amsai0000000054 ~]$ npm config set registry=https://artifacts.xyz.com/artifactory/npm-remote/  [user1@amsai0000000054 ~]$ npm config get registry  https://artifacts.xyz.com/artifactory/npm-remote/    [user1@amsai0000000054 ~]$ npm view angular  npm ERR! code E406  npm ERR! 406 Not Acceptable - GET https://artifacts.xyz.com/artifactory/npm-remote/angular/    npm ERR! A complete log of this run can be found in:  npm ERR!     /home/user1/.npm/_logs/2021-08-04T15_12_22_598Z-debug.log  [user1@amsai0000000054 ~]$  

Any ideas what could be the wrong here?

Create cookies in browser based on object structure

Posted: 04 Aug 2021 08:17 AM PDT

I need to create several cookies on a web page based on data that's been read by Puppeteer. From my understanding, I can create cookies with document. cookie in Javascript much like the following:

document.cookie = "name=oeschger; SameSite=None; expires=Fri, 31 Dec 9999 23:59:59 GMT; Secure";  

However I can't find any way to create the above string based on an Object, or would I have to manually create some kind of function to effectively build up a cookie-based on key/value pairs from my array of objects?

My data looks like this:

[    {        "name": "cookiename",        "value": "1",        "domain": "mydomain",        "path": "/",        "expires": 1628089842,        "size": 30,        "httpOnly": false,        "secure": false,        "session": false,        "sameParty": false,        "sourceScheme": "NonSecure",        "sourcePort": 80    },    {        "name": "cookiename",        "value": "1",        "domain": "mydomain",        "path": "/",        "expires": 1628089842,        "size": 30,        "httpOnly": false,        "secure": false,        "session": false,        "sameParty": false,        "sourceScheme": "NonSecure",        "sourcePort": 80    }  ]  

Primeng carousel diferent height for carousel items

Posted: 04 Aug 2021 08:16 AM PDT

Hi im using primeng carousel but there is problem so carousel height is always based on the highest item. I want to have automatic height for every carousel item.

Is this possible?

  <p-carousel [value]="post.content" [numVisible]="1" [numScroll]="1" [circular]="true">      <ng-template let-content pTemplate="item">        <video *ngIf="content.contentType===ContentType.VIDEO" class="video" width="100%" height="auto" playsinline controls controlsList="nodownload" >          <source [src]="getContentLink(post.user.id,post.id,content.fileName)" type="video/mp4">        </video>        <img height="auto" width="100%" *ngIf="content.contentType===ContentType.PHOTO" [src]="getContentLink(post.user.id,post.id,content.fileName)"/>      </ng-template>    </p-carousel>  

Removing subdomain in a string in TypeScript

Posted: 04 Aug 2021 08:16 AM PDT

I have a string in TypeScript which is subdomain.domain.com I want to create a new string that is just the domain on its own, so for example subdomain.domain.com would become domain.com

Note: The 'subdomain' part of the URL could be different sizes so it could be 'subdomain.domain.com' or it might be 'sub.domain.com' so I can't do this on character size. The domain might also be different so it could be 'subdomain.domain.com' or it could be 'subdomain.new-domain.com'.

So basically I need to just remove up to and including the first '.' - hope that all makes sense.

Type hint issues with Union on a class method signature

Posted: 04 Aug 2021 08:16 AM PDT

I am getting a squiggly line under the Union keyword below with "syntax error in type" on VSCode's mypy and I think the error message is related to something about the method signature, but can't figure it out. I've tried both Union and Optional.

class User(object):      def __init__(self, username: str = None, password: str = None):          self.uid = ""          self.username = username          self.password = password          self.image = ""          self.images: dict = {}        @classmethod      async def get_user_by_username(          cls: "User", username: str      ) -> Union["User", None]:          user_document = await current_app.dbc.user.find_one(              {"username": username}          )          if not user_document:              return None          else:              cls.uid = str(user_document["uid"])              cls.username = user_document["username"]              cls.password = user_document["password"]              cls.image = user_document["image"]              cls.images = {}                image_dict = cls._image_url_from_image_ts(cls.uid, cls.image)              cls.images["image_url_raw"] = image_dict["image_url_raw"]              cls.images["image_url_xlg"] = image_dict["image_url_xlg"]              cls.images["image_url_lg"] = image_dict["image_url_lg"]              cls.images["image_url_sm"] = image_dict["image_url_sm"]                return cls  

As you can see the method can return None or a class instance.

The error in VSCode reads:

syntax error in type comment mypy(error) (class) Union No quick fixes available  

I can also reproduce running mypy on the terminal:

$ mypy .\user\models.py  user\models.py:18: error: syntax error in type comment  

Split and Join with Variable in Javascript

Posted: 04 Aug 2021 08:16 AM PDT

I have the ff. JSON payload of an Array

  {      "Meta": {          "LastAvailableDateTime": "",          "FirstAvailableDateTime": "",          "TotalPages": 1,          "Count": 2      },      "Links": {          "Next": null,          "Previous": null,          "Self": ""      },      "Data": {          "Transactions": [              {                  "AuthCode": "175601",                  "CardId": "************8104"              },              {                  "AuthCode": "783453",                  "CardId": "************8104"              },  

{ "AuthCode": "12132", "CardId": "************8104" } ] } }

And I want to override this payload by renaming CardId to MaskedCardId and adding a new param named CardId with an actual Card id.

My code is the ff. below

var json = //The Parsed JSON Payload;  var CardId = "123458104"    json = JSON.parse(         JSON.stringify(json).split('"CardId":')             .join('"CardId":CardId,"MaskedCardId":')  );  

I could already replace the CardId with the renamed parameter named MaskedCardId. with the ff. code

 json = JSON.parse(JSON.stringify(json).split('"CardId":').join('"MaskedCardId":'));  

But whenever I try to add a new parameter named CardId with a variable value, it is giving an error of.

failed with error: Javascript runtime error: "SyntaxError: Unexpected token: C

How do I make this line of code work with my intended purpose?. TIA

How to effeciently access subset list of dict that match certain string in Python

Posted: 04 Aug 2021 08:16 AM PDT

Given a list of dict, access only dict that have its key match to certain string.

The code below answer the intended objective. However I wonder whether there exist more efficient approach than proposed here.

nest_dict = [{'t': 'ab_t1_a', 'var': 1},   {'t': 'ab_t2_b', 'var': 22},   {'t': 'ab_t1_c', 'var': 3},   {'t': 'ab_t1_d', 'var': 4},   {'t': 'ab_t1_b', 'var': 2},   {'t': 'ab_t2_a', 'var': 11},   {'t': 'ab_t2_c', 'var': 33},   {'t': 'ab_t2_d', 'var': 44},   {'t': 'ab_t100_d', 'var': 100}]    list_val = ['t1','t2','t100']  all_data = []    for my_ls in list_val:      store_temp = [xx for xx in nest_dict if my_ls in xx['t']]      b_sort = sorted(store_temp, key=lambda d: list(d['t']))      c_opt = [x['var'] for x in b_sort]      all_data.append(c_opt)  

p.s., I just notice. using in will make the result wrong, as it will treat 1,13,14,100 as the same

Expected output of all_data

[1,2,3,4],[11,22,33,44],[130],[140],[100]  

Replace a certain part of the string which matches a pattern in python 2.7 and save in the same file

Posted: 04 Aug 2021 08:16 AM PDT

I am trying to achieve something of this sort

My input file has this kind of entries

art.range.field = 100  art.net.cap = 200  art.net.ht = 1000  art.net.dep = 8000  

I am trying to match the pattern like where art.range.field is there the value should be changed to 500. So the output of the code should be something like

art.range.field = 500  art.net.cap = 200  art.net.ht = 1000  art.net.dep = 8000  

Here is my following attempt at solving this problem

file_path = /tmp/dimension  with open(file_path,"r") as file    file_content = file.read()    new_content = re.sub(r"^.*"+parameter+".*$",parameter+" = %s" % value, file_content)    file.seek(0)    file.write(new_content)    file.truncate()  

Here I have taken parameter = art.range.field and value = 500.

But still my file is remaining unchanged as the new_content variable is not changing its value to the desired out put.

So I want to know where I am going wrong and what can be the possible solution to this.

Spring boot: check if GeoJson Point in Polygon fails

Posted: 04 Aug 2021 08:15 AM PDT

I have a GeoJson polygon and a point and i want to check if the point is in the polygon.

Classpaths:

import com.vividsolutions.jts.geom.Geometry;  import com.vividsolutions.jts.geom.Point;  

I tried with Geometry methods contains and within, but both failed. From google maps I can see, that the point should actually be insinde the polygon.

public boolean checkIfPointIsInPolygon(Geometry polygon, Point point) {       if(polygon.contains(point)) {       return true;     }  }  
{      "type": "Polygon",      "coordinates": [          [              [12.095514088869095, 49.012418152680716],              [12.095677703619003, 49.01241463418325],              [12.095661610364912, 49.012400560191],              [12.09551677107811, 49.01239352319336],              [12.095514088869095, 49.012418152680716]          ]      ]  }  
{      "coordinates": [          12.095504206503294,          49.01242468521154      ],      "type": "Point"  }    

UPDATE: One randomly created point could have been found.

{      "coordinates": [          12.095571960263833,          49.01239762127791      ],      "type": "Point"  }  

Is there a possibility in Java to parametrize classes by integers or general objects instead of types only?

Posted: 04 Aug 2021 08:15 AM PDT

Assume I want to define classes (or maybe even interfaces) that are similar in structure, but differ in a parameter that could be an integer or could be something else. Is it possible in Java to define a family of classes parametrized by an integer or even an arbitrary object? Consider the following pseudocode (which does not compile):

/** class with strings of a certain length n and a method to reduce to length n-1 */  public class StringN<int n> {      private String str;        public StringN( String str) {          if(str.length() != n) {              throw new IllegalArgumentException("string is not of required length!");          }          this.str = str;      }        public StringN<n-1> reduce() {          return new StringN<n-1>(s.substring(0, s.length() - 1));      }        @Override      public String toString() {          return str;      }  }  

Other even more natural examples that come to my mind are tensor-products in math, so where to put the parameter 'n', if one wants to define e.g. the space R^n as a Java class or in functional programming the 'arity' of a Function<>-space. So how to define a family of classes with different arity, parametrized by n?

If this is not possible in Java, does this concept exist in other more functional languages and what is the proper name for it? (like maybe 'parametrized class'?)

Edit: as a reaction to comments, the last part was just to know the general name of such a concept, not to make a deviation to other languages.

Topk values in LogQL

Posted: 04 Aug 2021 08:15 AM PDT

I need some help with Loki. I`ve got json logs like following

{"message": {"reason": "reason1"...}}  {"message": {"reason": "reason2"...}}  

And I need to print top N reasons. How can I do this?

Count unique occurrences within data frame

Posted: 04 Aug 2021 08:16 AM PDT

Let the table be as follows:

v1 v2 v3
A B A
B B A
A C
D C D

What i want R to create a table for number of occurences of unique values for each column:

v1 v2 v3
A 1 1
B 1 2
C 0 1
D 1 0

Bypass kafka authorization for port 9092 (plaintext)

Posted: 04 Aug 2021 08:16 AM PDT

I want to add authentication and authorization for my confluent kafka running with docker. This should only happen on port 9093, 9092 should work as before because the port is blocked for external clients by ip table rules. Therefore I used following config:

=> 9093 SASL_SSL
=> 9092 PLAINTEXT

Here is a part of my config:
Container environment variables

  - KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://my.host.ip:9092,SASL_SSL://my.host.ip:9093    - KAFKA_ALLOW_EVERYONE_IF_NO_ACL_FOUND=false    - KAFKA_SSL_CLIENT_AUTH=required    - KAFKA_SECURITY_INTER_BROKER_PROTOCOL=SASL_SSL    - KAFKA_SASL_MECHANISM_INTER_BROKER_PROTOCOL=PLAIN    - KAFKA_SASL_ENABLED_MECHANISMS=PLAIN    - KAFKA_AUTHORIZER_CLASS_NAME=kafka.security.authorizer.AclAuthorizer    - KAFKA_SUPER_USERS="User:admin"    - KAFKA_OPTS=-Djava.security.auth.login.config=/etc/kafka/secrets  

As I only want to configure the authentication mechanism for the SASL_SSL listener I use following jaas config as described here: https://docs.confluent.io/platform/current/kafka/authentication_sasl/index.html#recommended-broker-jaas-configuration.

kafka_jaas.config

KafkaServer {  listener.name.sasl_ssl.plain.sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required    username="admin"    password="admin"    user_admin="admin"  };    Client {  org.apache.kafka.common.security.plain.PlainLoginModule required   username="admin"   password="admin";  };  

zookeeper_jaas.config

Server {         org.apache.zookeeper.server.auth.DigestLoginModule required         user_admin="admin";  };  

When I run kafka i get the following error:

[main-SendThread(s415vm2140.detss.corpintra.net:2181)] WARN org.apache.zookeeper.ClientCnxn - SASL configuration failed: javax.security.auth.login.LoginException: Zookeeper client cannot authenticate using the 'Client' section of the supplied JAAS configuration: '/etc/kafka/secrets/kafka_jaas.conf' because of a RuntimeException: java.lang.SecurityException: java.io.IOException: Configuration Error:      Line 2: expected [controlFlag] Will continue connection to Zookeeper server without SASL authentication, if Zookeeper server allows it.  

How can I achieve that a client does not need to authentication when connecting to port 9092?

How to parse this JSON file using android library volley

Posted: 04 Aug 2021 08:15 AM PDT

I'm building an android application but I'm not able to parse this JSON file, I am using volley android library. JSON file link : https://api.covid19india.org/v4/min/data.min.json

 override fun onCreate(savedInstanceState: Bundle?) {      super.onCreate(savedInstanceState)      setContentView(R.layout.activity_main)      val recoveredT = findViewById<TextView>(R.id.recoveredT)      val url = "https://api.covid18india.org/v4/min/data.min.json"      val jsonObjectRequest = JsonObjectRequest(          Request.Method.GET, url, null,          {              val x = it.getJSONObject("UT")              val y = x.getJSONObject("total")              z = y.getString("recovered")//I'm storing it in a variable z which is of type string.           },          {              Toast.makeText(this, "error in the hood boys!", Toast.LENGTH_SHORT).show()            }      )                   MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest)    }  

I'm trying to get info for "UT"

image : enter image description here

Insert commas delimited string into a string column of Athena table

Posted: 04 Aug 2021 08:16 AM PDT

I create an athena table based on CSV in S3. I want to input a row of data which one column include commas. But it truncates the string from the commas each time.

For example:

insert into table_names (id, key_string)values (1,'{key1=1,key2=3}')

Each time, the column key_string only store '{key1=1'. I tried use double quote '"{key1=1,key2=3}"', escape char '"{key1=1,key2=3}"'. All doesn't work.

Any suggestion?

How to connect Dapp to Metamask and interact with smart contract deployed on Ropsten via Remix

Posted: 04 Aug 2021 08:16 AM PDT

I deployed a smart contract via remix to the ropsten testnet and now I want to interact with it via website(dapp). I am creating a auction dapp. The user has to input the amount of ETH he want's to bid for the article. After the value is submitted via button click I want metamask to pop up and handle the transaction.

I got the js code for connecting to metamask from https://docs.metamask.io/guide/getting-started.html#basic-considerations

if (typeof window.ethereum !== 'undefined') {      console.log('MetaMask is installed!');   }  else{        console.log('MetaMask not installed!');  }    const ethereumButton = document.querySelector('.enableEthereumButton');  const showAccount = document.querySelector('.showAccount');    ethereumButton.addEventListener('click', () => {    getAccount();  });    async function getAccount() {    const accounts = await ethereum.request({ method: 'eth_requestAccounts' });    const account = accounts[0];    showAccount.innerHTML = account;  }  

And it's working fine Metamask is popping up, but the part where I am stuck is how to connect the dapp to the deployed ropsten contract(deployed it via remix and it's visible on ropsten etherscan).

I tried to connect it with this js script

<script>        // Initialize Web3        if (typeof web3 !== 'undefined') {          web3 = new Web3(web3.currentProvider);        } else {          web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));        }          // Set Account        web3.eth.defaultAccount = web3.eth.accounts[0];          // Set Contract Abi        var contractAbi = []; // Add Your Contract ABI here!!!          // Set Contract Address        var contractAddress = ''; // ?????          // Set the Contract        var contract = web3.eth.contract(contractAbi).at(contractAddress);        ...        </script>  

But I don't know how to connect it to the contract deployed on ropsten.

After I have done some reading on the internet I created an infura node to connect to the contract, but I got stuck again. Do I have to connect to infura node when I am only using metamask to interact with the dapp.

Azure services events collection

Posted: 04 Aug 2021 08:15 AM PDT

I'm following this Azure guid : https://docs.microsoft.com/en-us/rest/api/application-insights/events/get-by-type#examples

And when I'm trying to use the sample requests : https://api.applicationinsights.io/v1/apps/DEMO_APP/events/traces

Instead of getting a valid response I get: {"error":{"message":"Valid authentication was not provided","code":"AuthorizationRequiredError","correlationId":"f5bb5980-26fc-4afb-bfec-b41729a2a81b"}}

Any ideas how can I fix it? (I logged in to my Azure account and after that I tried to use the request above)

After read holding registers with Pymodbus connection is broken in Raspberry Pi

Posted: 04 Aug 2021 08:16 AM PDT

import pymodbus       from pymodbus.client.sync import ModbusTcpClient     from time import sleep  connection = False  data = {}  while True:          if not connection:              client = ModbusTcpClient(host="176.219.185.16", port="502")              connection = client.connect()              if connection:                  print("connected")          if connection == True:              if not client.is_socket_open():                  print("connection is broken")                      connection = False          data = client.read_holding_registers(address=150,count=10,unit=1).registers          sleep(2)          print(data)  

This code is working on Windows. But i run it in raspberry pi "client.is_socket_open" is return false after read holding registers. How can i solve this? Or what is the problem in here. I dont force the client to close.

TypeScript error after upgrading version 4 useParams () from react-router-dom Property 'sumParams' does not exist on type '{}'

Posted: 04 Aug 2021 08:15 AM PDT

I get a typeScript error after upgrading to version 4 Used in useParams () from react-router-dom

"typescript": "^4.0.2"

import { useParams } from 'react-router-dom';    const { sumParams } = useParams();    
Property 'sumParams' does not exist on type '{}'.   

The project worked great and only after the upgrade does it throw an error

Rails production not work in AWS load balancer

Posted: 04 Aug 2021 08:16 AM PDT

My Rails 6 App work fine with development mode in EC2 instances. But when config to use production mode. The load balancer not able to do health check and not able to run the app.

My health check:

enter image description here

Security: Load Balancer

enter image description here

enter image description here

Security: Rails App(s)

enter image description here

enter image description here

Load balancer worked in development

enter image description here

Here the development that work with load balancer

Start rails:

rails s -p 3000 -b 0.0.0.0  

then responded

=> Booting Puma  => Rails 6.0.3.2 application starting in development   => Run `rails server --help` for more startup options  Puma starting in single mode...  * Version 4.3.5 (ruby 2.6.3-p62), codename: Mysterious Traveller  * Min threads: 5, max threads: 5  * Environment: development  * Listening on tcp://0.0.0.0:3000  

config/environments/development.rb

Rails.application.configure do    config.hosts << "xxxxxxxx.us-east-2.elb.amazonaws.com" #This is public dns of load balance    config.cache_classes = false    config.eager_load = false    config.consider_all_requests_local = true    if Rails.root.join('tmp', 'caching-dev.txt').exist?      config.action_controller.perform_caching = true      config.action_controller.enable_fragment_cache_logging = true        config.cache_store = :memory_store      config.public_file_server.headers = {        'Cache-Control' => "public, max-age=#{2.days.to_i}"      }    else      config.action_controller.perform_caching = false        config.cache_store = :null_store    end    config.action_mailer.raise_delivery_errors = false    config.action_mailer.default_url_options = { :host => 'localhost:3000' }      config.action_mailer.perform_caching = false    config.active_support.deprecation = :log    config.assets.debug = true    config.assets.quiet = true    config.file_watcher = ActiveSupport::EventedFileUpdateChecker  end  

Below is production(that not working)

config/environments/production.rb

Start rails:

RAILS_ENV=production rails s -p 3000 -b 0.0.0.0  

then responded:

=> Booting Puma  => Rails 6.0.3.2 application starting in production   => Run `rails server --help` for more startup options  Puma starting in single mode...  * Version 4.3.5 (ruby 2.6.3-p62), codename: Mysterious Traveller  * Min threads: 5, max threads: 5  * Environment: production  * Listening on tcp://0.0.0.0:3000      Rails.application.configure do    config.hosts << "xxxxxxxx.us-east-2.elb.amazonaws.com" #This is public dns of load balance    config.hosts << "3.14.65.84"    config.cache_classes = true    config.eager_load = true    config.consider_all_requests_local       = false    config.action_controller.perform_caching = true    config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?    config.assets.compile = false    config.log_level = :debug    config.log_tags = [ :request_id ]    config.action_mailer.perform_caching = false    config.i18n.fallbacks = true    config.active_support.deprecation = :notify    config.log_formatter = ::Logger::Formatter.new    if ENV["RAILS_LOG_TO_STDOUT"].present?      logger           = ActiveSupport::Logger.new(STDOUT)      logger.formatter = config.log_formatter      config.logger    = ActiveSupport::TaggedLogging.new(logger)    end  end  

Load Balancer: Health Check not work!

enter image description here

I also tried:

  1. copy config/environments/development.rb to production.rb and then run as production environment the result =====> Health Check Not Work!
  2. copy config/environment/production.rb to development.rb and then run as development environment the result =====> Health Check Work!

It seems nothing about the rails config, but the way it handle production in AWS

Help: How to make this Rails 6 work as production in AWS EC2 with load balancer ?

Laravel 7 verify email adress invalid signature

Posted: 04 Aug 2021 08:15 AM PDT

After clicking verify email address button in the email, I got 403 invalid signature. I'm using shared hosting

I have read these

  1. Laravel 5.7 email verification throws 403
  2. https://laracasts.com/discuss/channels/laravel/403-invalid-signature-every-time-i-try-to-verify-email-in-laravel-57
  3. https://laracasts.com/discuss/channels/laravel/email-verification-403-invalid-signature

but still can't solve my problem

Unable to use all cores with mpirun

Posted: 04 Aug 2021 08:15 AM PDT

I'm testing a simple MPI program on my desktop (Ubuntu LTS 16.04/ Intel® Core™ i3-6100U CPU @ 2.30GHz × 4/ gcc 4.8.5 /OpenMPI 3.0.0) and mpirun won't let me use all of the cores on my machine (4). When I run:

$ mpirun -n 4 ./test2  

I get the following error:

--------------------------------------------------------------------------  There are not enough slots available in the system to satisfy the 4 slots  that were requested by the application:    ./test2    Either request fewer slots for your application, or make more slots available  for use.  --------------------------------------------------------------------------  

But if I run with:

$ mpirun -n 2 ./test2  

everything works fine.

I've seen from other answers that I can check the number of processors with

cat /proc/cpuinfo | grep processor | wc -l  

and this tells me that I have 4 processors. I'm not interested in oversubscribing, I'd just like to be able to use all my processors. Can anyone help?

Click through transparent xlib windows

Posted: 04 Aug 2021 08:16 AM PDT

I have a transparent, watermark like application that is written with XLib in C. Currently if you click anywhere on the application nothing happens but I would like it to pass mouse input to whatever is below it. e.g. If you click the X to close a window that is below the application it should close the application, not do nothing.

No comments:

Post a Comment