Sunday, June 19, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


.net 6 console app : Pre-Compile not work well, neither Crossgen or Publish with ready to run or Publish to Signal App

Posted: 19 Jun 2022 08:25 PM PDT

i want to pre-compile my .net 6 code to speed up first call of the method, something like ngen.exe do during NetFamework age.

I have a .net 6 testing console app, as simple as below:

internal class Program  {      private static readonly Stopwatch Stopwatch = new Stopwatch();      private static int Delay = 3000;      static void Main(string[] args)      {          var end = DateTime.Now.AddMilliseconds(Delay);          while (DateTime.Now < end)          {              continue;          }          Stopwatch.Start();          Console.WriteLine("Test 1");          Stopwatch.Stop();          Console.WriteLine($"Cost[{Stopwatch.ElapsedMilliseconds}]ms");          Stopwatch.Restart();          Console.WriteLine("Test 2");          Stopwatch.Stop();          Console.WriteLine($"Cost[{Stopwatch.ElapsedMilliseconds}]ms");          Console.ReadLine();      }  }  

i try these methods, there are not work well when i run it.

corssgen

# Publish  $ cd /home/root/src/Tester  $ dotnet publish Tester.csproj -o bin/publish -f net6.0 -c Release -r linux-x64 -p:UseAppHost=true --self-contained=false    # Crossgen2  $ cd /home/root/bin/crossgen2.linux-x64.6.0.5  $ ./crossgen2 -r . --targetarch x64 --targetos linux /home/root/src/Tester/bin/publish/Tester.dll --out /home/root/src/Tester/bin/crossgen/Tester.dll    $ cp /home/root/src/Tester/bin/publish/Tester.deps.json /home/root/src/Tester/bin/crossgen  $ dotnet /home/root/src/Tester/bin/crossgen/Tester.dll  

deploying/ready-to-run

$ cd /home/root/src/Tester  $ dotnet publish  -o bin/readyToRun -f net6.0 -c Release -r linux-x64 --self-contained=false -p:PublishReadyToRun=true  $ dotnet /home/root/src/Tester/readyToRun/Tester.dll  

deploying/single-file

$ cd /home/root/src/Tester  $ dotnet publish -o bin/native -f net6.0 -c Release -r linux-x64 -p:UseAppHost=true --self-contained=true -p:PublishSingleFile=true -p:PublishTrimmed=true  $ dotnet /home/root/src/Tester/native/Tester.dll  

native-aot

$ cp -rf /home/root/src/Tester /home/root/src/Tester_AOT  $ vi /home/root/src/Tester_AOT/Tester.csproj  <Project Sdk="Microsoft.NET.Sdk">    <PropertyGroup>      <OutputType>Exe</OutputType>      <TargetFramework>net6.0</TargetFramework>      <ImplicitUsings>enable</ImplicitUsings>      <Nullable>enable</Nullable>      <PublishAot>true</PublishAot>    </PropertyGroup>  </Project>    $ cd /home/root/src/Tester_AOT  $ dotnet publish -r linux-x64 -c Release -p:UseAppHost=true --self-contained=false  $ dotnet bin/Release/net6.0/linux-x64/publish/Tester.dll  

there output similar like

Test 1  Cost[9]ms  Test 2  Cost[0]ms  

if any one can tell me the right way to do this , many thanks.

can't get the data from database

Posted: 19 Jun 2022 08:24 PM PDT

i made a php code for get and encode the data from my database. i tested it on postman but no data showed.please help me. code:

<?php  include '../database.php';    $sql = "SELECT * FROM tb_obat";    $res= mysqli_query($kon,$sql);      if(true){      $data = array();      while($row = mysqli_fetch_assoc($kon, $res)){          $data[] = $row;      }       var_dump ($data);      echo json_encode(array(          "success"=>true,          "data"=> $data,          ));  } else {      echo json_encode(array("success"=>false,      ));  }  ?>  

output:

array(0) { } {"success":true,"data":[]}  

How to parse and access columns based on headers in file? - Python

Posted: 19 Jun 2022 08:24 PM PDT

I believe this is a 3 step process but please bear with me. I'm currently reading Shell output which is being saved to a file and the output looks like this:

Current Output:

  Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name      tcp        0      0 123.345.789:1234        0.0.0.0:*               LISTEN      23044/test            tcp        0      0 0.0.0.0:5915            0.0.0.0:*               LISTEN      99800/./serv      tcp        0      0 0.0.0.0:1501            0.0.0.0:*               LISTEN      -        

I'm trying to access each columns information based on the header value. This is something I was able to do in Powershell but not sure how to achieve it in Python.

Expected Output:

Proto,Recv-Q,Send-Q,Local Address,Foreign Address,State,PID/Program name  tcp,0,0,123.345.789:1234,0.0.0.0:*,LISTEN,23044/test            tcp,0,0,0.0.0.0:5915,0.0.0.0:*,LISTEN,99800/./serv      tcp,0,0,0.0.0.0:1501,0.0.0.0:*,LISTEN,-      
proto = data["Proto"]  for p in proto:      print(p)  

Output: tcp tcp tcp

What I've tried?:

Where do I begin.. I've tried Splitting, Replacing and Translate.

Proto,Recv-Q,Send-Q,Local,Address,,,,,,,,,,,Foreign Address,,,,,,,,,State,,,,,, PID/Program,name      tcp,,,,,,,,0,,,,,,0 123.345.789:1234,,,,,,,,0.0.0.0:*,,,,,,,,,,,,,,,LISTEN,,,,,,23021/java,,,,,,,,    tcp,,,,,,,,0,,,,,,0 0.0.0.0:5915,,,,,,,,,,,,0.0.0.0:*,,,,,,,,,,,,,,,LISTEN,,,,,,99859/./statserv      tcp,,,,,,,,0,,,,,,0 0.0.0.0:1501,,,,,,,,,,,,0.0.0.0:*,,,,,,,,,,,,,,,LISTEN,,,,,,-         

Since some of the headers contain a space in between them it's sort of difficult to map the columns accordingly.

Looking for the best way to approach this.

Thank you.

How can I restrict file types and make my code more secure?

Posted: 19 Jun 2022 08:24 PM PDT

I'm brand new to Flask and attempting to make a secure file upload web app. I want to limit the file types that can be uploaded and specifically block scripting languages.

My app.py code:

from flask import Flask, render_template, request, current_app, abort  import os    app = Flask(__name__)    app.config["UPLOAD_PATH"] = "Desktop"  app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']  app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024    @app.route("/",methods=["GET","POST"])  def upload_file():      if request.method == "POST":          f = request.files['file_name']          f.save(os.path.join(app.config['UPLOAD_PATH'], f.filename))          return render_template("upload-file.html", msg="File has been successfully uploaded")      return render_template("upload-file.html", msg="Please Choose a File")      if __name__ == "__main__":      app.run(debug=True)  

And my upload-file.html code:

{{msg}}  <br>  <form action="/" method="POST" enctype="multipart/form-data">      <input  type="file" name="file_name" multiple>      <input type="submit" value="Submit">  </form>  

Discord JS bot dont reply again

Posted: 19 Jun 2022 08:23 PM PDT

if i have bot to reply to message like

if (message.content == '1') {    message.channel.send('2');  }  

when member send 1 once again the bot is send 2 again How do I make him reply only once and not reply again?

SpringToolSuite4 - Spring Tools 3 Add Install Error

Posted: 19 Jun 2022 08:22 PM PDT

I was using Spring 4.10.0 version and then re-downloaded it with Spring 4.9.0 due to namespaces error.

However, spring tools 3 add-on for spring tools 4 are not installed in the marketplace. I deleted the version 4.10.0 that I used last time and deleted the existing workspace and re-created it with the same name, but I don't know what the problem is.

In the error log, there is a saying, "The process is not accessible because another process is using the file." Is this a problem? I erased all the previous files, but if this is a problem, how can I solve it? Please help me..

I installed something else (Tern Eclipse~, Eclipse Enterprise Java~) just in case, but there was no problem with the installation.

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

C++ array with multiple object

Posted: 19 Jun 2022 08:25 PM PDT

This is my code for input list vehicle (can Car or Truck). But it's not work and error: no match for 'operator=' (operand types are 'Vehicle' and 'Car*'). How I can input vehicle (can Car or Truck) for true?

class Vehicle {};  class Car : public Vehicle {};  class Truck : public Vehicle {};    class ListVehicle {    Vehicle *pVehicle;    int n;     public:    void input() {      for (int i = 0; i < n; i++) {        int type;        cout << "Enter vehicle type (1: car, 2: truck): ";        cin >> type;        cin.ignore();        switch (type) {          case 1: {            pVehicle[i] = new Car();            break;          }          case 2: {            pVehicle[i] = new Truck();            break;          }          default:            cout << "Invalid type" << endl;            break;        }      }    }  };  

Airflow run a DAG to manipulate DB2 data that rasise a jaydebeapi.Error

Posted: 19 Jun 2022 08:24 PM PDT

I follow the offcial website of Airflow to produce my Airflow DAG to connect to DB2. When i run a DAG to insert data or update data that will raise a jaydebeapi.Error. Even though Airflow raise a jaydebeapi.Error, the data still has inserted/updated in DB2 successfully. The DAG on the Airflow UI will be marked FAILED. I don't know what steps i miss to do.

My DAG code snippet:

with DAG("my_dag1", default_args=default_args,      schedule_interval="@daily", catchup=False) as dag:        cerating_table = JdbcOperator(          task_id='creating_table',          jdbc_conn_id='db2',          sql=r"""              insert into DB2ECIF.T2(C1,C1_DATE) VALUES('TEST',CURRENT DATE);          """,          autocommit=True,          dag=dag     )  

DAG log:

[2022-06-20 02:16:03,743] {base.py:68} INFO - Using connection ID 'db2' for task execution.  [2022-06-20 02:16:04,785] {dbapi.py:213} INFO - Running statement:               insert into DB2ECIF.T2(C1,C1_DATE) VALUES('TEST',CURRENT DATE);          , parameters: None  [2022-06-20 02:16:04,842] {dbapi.py:221} INFO - Rows affected: 1  [2022-06-20 02:16:04,844] {taskinstance.py:1889} ERROR - Task failed with exception  Traceback (most recent call last):    File "/home/airflow/.local/lib/python3.7/site-packages/airflow/providers/jdbc/operators/jdbc.py", line 76, in execute      return hook.run(self.sql, self.autocommit, parameters=self.parameters, handler=fetch_all_handler)    File "/home/airflow/.local/lib/python3.7/site-packages/airflow/hooks/dbapi.py", line 195, in run      result = handler(cur)    File "/home/airflow/.local/lib/python3.7/site-packages/airflow/providers/jdbc/operators/jdbc.py", line 30, in fetch_all_handler      return cursor.fetchall()    File "/home/airflow/.local/lib/python3.7/site-packages/jaydebeapi/__init__.py", line 596, in fetchall      row = self.fetchone()    File "/home/airflow/.local/lib/python3.7/site-packages/jaydebeapi/__init__.py", line 561, in fetchone      raise Error()  jaydebeapi.Error  [2022-06-20 02:16:04,847] {taskinstance.py:1400} INFO - Marking task as FAILED. dag_id=my_dag1, task_id=creating_table, execution_date=20210101T000000, start_date=, end_date=20220620T021604  

I have installed required python packages of Airflow. List below:

Package(System) name/Version

  1. Airflow/2.3.2
  2. IBM DB2/11.5.7
  3. OpenJDK/15.0.2
  4. JayDeBeApi/1.2.0
  5. JPype1/0.7.2
  6. apache-airflow-providers-jdbc/3.0.0

I have tried to use the latest version of item 4(1.2.3) and item 5(1.4.0) still doesn't work. I also have downgraded Airflow version to 2.2.3 or 2.2.5 got same result.

How to solve this problem?

How do I send a chat message packet in Minecraft

Posted: 19 Jun 2022 08:24 PM PDT

I've been searching for how to send a chat message via a packet for hours now. No matter what I searched up, I never had luck. Currently, I know what chat packets look like but have no clue how to send the data as a packet to Minecraft (specifically, a 'Paper (Velocity)' server). I've tried looking at the source code of mods like Auto GG to no avail.

Get new instance on every new reference to an object

Posted: 19 Jun 2022 08:22 PM PDT

I'm making a class that whenever an attribute is accessed or an instance is called, it appends the attribute name to a list in the class.

class Foo:      def __init__(self) -> None:          self.elements = []            def __getattr__(self, __name: str) -> "Foo":          self.elemenets.append(__name)          return self                def __call__(self, *elements):          self.elements.extend(elements)          return self            def display(self) -> str:          disp = ' '.join(elements)                    if self.elements:              for element in elements:                  disp += ', ' + element.display()                    return x  

And I would like to be able use it in this way:

bar = Foo()    print(bar.baz(bar().spam))  

Currently, this is giving me a maximum recursion depth reached error.

What I would like is to get a string back like the following:

'baz, spam'  

I'm having a hard time wrapping my head around this. Basically, every time bar is accessed (or in other words, when the reference count increases) maybe it in itself is a new instance of itself like so:

>>> bar  # new id() for 'bar'  >>> bar   # new id() for 'bar'  

I know there has to be some good solution for this, maybe a factory or metaclass solution but I can't seem to figure it out.

DatePicker With Placeholder using Xamarin

Posted: 19 Jun 2022 08:25 PM PDT

I created a custom DatePicker to look like it has placeholder, but the problem is, when clicking the DatePicker then when the DatePicker Dialog opens and I click on okay with the preselected/default date value of today, The date is not written in the field. Below is my code.

I think the reason is that since "Date" property has a default value of today and there is no change in the selection when the "OK" button was clicked

    using System;      using System.Collections.Generic;      using System.Linq;      using System.Text;      using System.Threading.Tasks;            using Xamarin.Forms;      using Xamarin.Forms.Xaml;            namespace XXX.XXX.Mobile.Controls      {          [XamlCompilation(XamlCompilationOptions.Compile)]          public partial class DatePickerWithPlaceHolder : DatePicker          {              public static readonly BindableProperty NullableDateProperty = BindableProperty.Create(nameof(NullableDate),typeof(DateTime?),typeof(DatePickerWithPlaceHolder), null, BindingMode.TwoWay);            private string _format;            public DateTime? NullableDate          {              get => (DateTime?)GetValue(NullableDateProperty);              set              {                  SetValue(NullableDateProperty, value);                  UpdateDate();              }          }            private void UpdateDate()          {              DatePickerWithPlaceHolder datePicker = this;                if (NullableDate.HasValue)              {                  if (null != _format) Format = _format;                  Date = NullableDate.Value;                  datePicker.FontAttributes = FontAttributes.None;                  datePicker.TextColor = Color.Black;              }              else              {                  _format = Format;                  Format = "Select Date";                  datePicker.FontAttributes = FontAttributes.Italic;                  datePicker.TextColor = Color.Gray;              }          }            protected override void OnBindingContextChanged()          {              base.OnBindingContextChanged();              UpdateDate();          }            protected override void OnPropertyChanged(string propertyName = null)          {              base.OnPropertyChanged(propertyName);              if (propertyName == "Date") NullableDate = Date;              if (propertyName == "NullableDate") UpdateDate();          }      }  }  

When using ik to look at target if the target is rotating around the player when the target is coming from behind the player is not looking at it why?

Posted: 19 Jun 2022 08:25 PM PDT

using UnityEngine;  using System;  using System.Collections;  using System.Collections.Generic;    [RequireComponent(typeof(Animator))]  public class TestingIK : MonoBehaviour  {      public List<Transform> lookObjects = new List<Transform>();      public float weightDamping = 1.5f;        private Animator animator;      private Transform lastPrimaryTarget;      private float lerpEndDistance = 0.1f;      private float finalLookWeight = 0;      private bool transitionToNextTarget = false;        void Start()      {          animator = GetComponent<Animator>();      }        // Callback for calculating IK      void OnAnimatorIK()      {          if (lookObjects != null)          {              Transform primaryTarget = null;              float closestLookWeight = 0;                // Here we find the target which is closest (by angle) to the players view line              foreach (Transform target in lookObjects)              {                  Vector3 lookAt = target.position - transform.position;                  lookAt.y = 0f;                  float dotProduct = Vector3.Dot(new Vector3(transform.forward.x, 0f, transform.forward.z).normalized, lookAt.normalized);                  float lookWeight = Mathf.Clamp(dotProduct, 0f, 1f);                  if (lookWeight > closestLookWeight)                  {                      closestLookWeight = lookWeight;                      primaryTarget = target;                  }              }                if (primaryTarget != null)              {                  if ((lastPrimaryTarget != null) && (lastPrimaryTarget != primaryTarget) && (finalLookWeight > 0f))                  {                      // Here we start a new transition because the player looks already to a target but                      // we have found another target the player should look at                      transitionToNextTarget = true;                  }              }                // The player is in a neutral look position but has found a new target              if ((primaryTarget != null) && !transitionToNextTarget)              {                  lastPrimaryTarget = primaryTarget;                  finalLookWeight = Mathf.Lerp(finalLookWeight, closestLookWeight, Time.deltaTime * weightDamping);                  float bodyWeight = finalLookWeight * .75f;                  animator.SetLookAtWeight(finalLookWeight, bodyWeight, 1f);                  animator.SetLookAtPosition(primaryTarget.position);              }                // Let the player smoothly look away from the last target to the neutral look position              if ((primaryTarget == null && lastPrimaryTarget != null) || transitionToNextTarget)              {                  finalLookWeight = Mathf.Lerp(finalLookWeight, 0f, Time.deltaTime * weightDamping);                  float bodyWeight = finalLookWeight * .75f;                  animator.SetLookAtWeight(finalLookWeight, bodyWeight, 1f);                  animator.SetLookAtPosition(lastPrimaryTarget.position);                  if (finalLookWeight < lerpEndDistance)                  {                      transitionToNextTarget = false;                      finalLookWeight = 0f;                      lastPrimaryTarget = null;                  }              }          }      }  }  

I have a cube that move in circles around the player.

When the cube is getting behind the player from the left side the player is looking at it a bit behind and then return the head back but then when the cube is coming back from the right side the player is not looking at it at all he start looking at the cube only when the cube is almost directly in front of him.

The right side is not active when the cube is coming back from behind to front from the right side.

Update :

I found that if i change this line

float dotProduct = Vector3.Dot(new Vector3(transform.forward.x, 0f, transform.forward.z).normalized, lookAt.normalized);  

Adding minus before the forward in both on x and z to this :

float dotProduct = Vector3.Dot(new Vector3(-transform.forward.x, 0f, -transform.forward.z).normalized, lookAt.normalized);  

Now it will work fine when the object is coming from the back from the right side but now the left side is not working.

So it's either the left side from the front to behind without the minus or the right side from the back to front with the minus.

How can i solve it so it will work for both sides front/behind equal ?

can't view Wordpress Content in ionic App

Posted: 19 Jun 2022 08:25 PM PDT

I'm new in ionic and I have connected ionic app with wordpress website built with "wpbakery" page builder using rest api but i have a problem : While i am trying to view this code in my app

<div>    {{ info.content.rendered }}  </div>  

This content just show HTML tags like this is screenshot

enter image description here

How i can fix that?

if condition inside list comprehension without an iterable to put a default value

Posted: 19 Jun 2022 08:23 PM PDT

>>> x = 7  >>> res = [ 'True' if x > 1 and x < 5 ]    File "<stdin>", line 1      res = [ 'True' if x > 1 and x < 5 ]                                         ^  SyntaxError: invalid syntax  >>> res = [ 'True' if x > 1 and x < 5 else 'False']  ['False']  

I want to put a default value inside the res list based on some condition and keep the list empty otherwise. So with what syntax/value should I replace False with to keep the list empty in case the condition fails.

I can do it in other ways but this seems like a single line syntax to create a list and initialize a value to it. I found other posts but everywhere a for loop/iterable is used inside the list comprehension which is not relevant in this case.

Is this vue js html line split by Prettier or ESLint in VSCode

Posted: 19 Jun 2022 08:22 PM PDT

When I save my Vue JS component in VSCode the template code shown below is split from a single line into two or more, depending on the length of the "Load Depot.." string.

Sometimes, depending on the length of the string it splits in the middle of the quotes and breaks my code.

I have both ESLint or Prettier enabled in the project, but I don't know which one is responsible for this and how to fix it.

      <h4>Depot Edit - {{ route.params.code }}, {{ depotStore.currentDepot ? depotStore.currentDepot.name : "Loading..." }} </h4>    

This receives a line break in an inconvenient location

      <h4>Depot Edit - {{ route.params.code }}, {{ depotStore.currentDepot ? depotStore.currentDepot.name : "Loading   Depot..."   }} </h4>    

Changing fonts family in pubspec.yaml

Posted: 19 Jun 2022 08:23 PM PDT

I want to change the font family in pubspec.yaml but what happens when I run pub get isn't what I'm expecting. Here's what I did...

fonts:    - family: Parisienne        fonts:         - asset: assets/fonts/Parisienne-Regular.ttf       style: italic       weight: 70     

and what I got after running pub get

[creepy_ipad] flutter pub get  Error detected in pubspec.yaml:  Error on line 70, column 12: Mapping values are not allowed here. Did you miss a colon earlier?     ╷  70 │       fonts:     │            ^     ╵  Please correct the pubspec.yaml file at C:\Users\Khomotjo\creepy_ipad\pubspec.yaml  exit code 1  

I honestly don't know what to do please help. THANK YOU

When slide 5 is displayed change slide transition properties on slide 1

Posted: 19 Jun 2022 08:25 PM PDT

I have a presentation that slide 1 .AdvanceOnClick = msoTrue. This is so after the slide show starts, it waits for mouse click before advancing (want slide 1 to display and wait for mouse click).

After the initial mouse click to start advancing, for example on slide 5, I want to change the .AdvanceOnClick to msoFalse on Slide 1 so the second and subsequent loops auto progress without user intervention. Basically, I want to change the Slide 1 transition properties when the presentation advances to, for example, slide 5.

I have tried the following code, which works fine, but I can't run this code from a different slide;

With ActivePresentation.Slides(1).SlideShowTransition      .AdvanceOnClick = msoTrue      .AdvanceOnTime = msoTrue      .AdvanceTime = 5  End With  

How to load md link which is stored inside a md link--Flutter

Posted: 19 Jun 2022 08:23 PM PDT

I am currently trying to show md file using MarkDown as a package from flutter_markdown and I find this source https://stackoverflow.com/a/63567194/13240914 It is stated that to load md file from asset using

future: DefaultAssetBundle.of(context).loadString              ("assets/manual/" + file),  

but, is there a way to load md file from a link ( something like: "http://mdlink.co.id/data.md" ) ?

Python np select to create a new column by applying condition on other columns

Posted: 19 Jun 2022 08:26 PM PDT

I am trying to create a new column for a data frame, but it seems giving incorrect result in the new column, The data is below:

df = pd.DataFrame(np.random.randint(0,30,size=10),                   columns=["Random"],                   index=pd.date_range("20180101", periods=10))  df=df.reset_index()  df.loc[:,'Random'] = '20'  df['Recommandation']=['No', 'Yes', 'No', 'Yes', 'Yes', 'Yes', 'No', 'No', 'Yes', 'No']  df['diff']=[3,2,4,1,6,1,2,2,3,1]  df    

I am trying to create another column in 'new' by using the following condition:

If the 'index' is in the first three date, then, 'new'='random',   elif the 'Recommendation' is yes, than 'new'= 'Value of the previous row of the new column'+'diff'  else: 'new'= 'Value of the previous row of the new column'  

My code is below:

import numpy as np  df['new'] = 0  df['new'] = np.select([df['index'].isin(df['index'].iloc[:3]), df['Recommandation'].eq('Yes')],                       [df['new'], df['diff']+df['new'].shift(1)],                       df['new'].shift(1)                       )  #The expected output  df[new]=[20,20,20,21,27,28,28,28,31,31]  df    

AttributeError: 'DataFrame' object has no attribute 'qcut

Posted: 19 Jun 2022 08:24 PM PDT

I am trying to bin values in dataframe column:

data['New_column'] = data.qcut(data['Old_column'], q=4, labels=["25%","50%","75%","100%"])  

and getting an error:

AttributeError: 'DataFrame' object has no attribute 'qcut'  

MacOS M1, Pandas 1.4.2, Python 3.9.12, Anaconda 2022.05

Are there any solutions to this?

Environment variable / tag in docker-compose > entrypoint.sh

Posted: 19 Jun 2022 08:25 PM PDT

In my development environment, I have a docker-compose.yml which builds an image from a Dockerfile.

I then push this to dockerhub, and my PROD servers use that image (using docker-compose-prod.yml). In PROD I'm using docker-swarm (currently three nodes).

When building the image, in the Dockerfile, it uses entrypoint.sh so I can run both apache and cron within the same container.

This is a requirement of the web app I'm working with (whilst I'd ideally split the cron out into a separate container, it's not practical).

The result is that the crontab runs no matter the environment; i.e. whenever I docker-compose up in my DEV environment, the crontab runs. For a variety of reasons, this isn't desired.

I already have different docker-compose.yml files on DEV vs PROD (*-prod.yml), but the task to start crontab is within entrypoint.sh which is embedded within the image.

So, is there anyway I can pass some type of server tag / environment variable within entrypoint.sh so on anything other than PROD, it doesn't start/add the crontab?

For example: new-entrypoint.sh

#!/bin/bash    if NODE IS LIVE  {    # Setup a cron schedule    echo "* * * * * /usr/local/bin/php /var/www/html/cron.php >> /var/log/cron.log 2>&1    # This extra line makes it a valid cron" > /var/www/scheduler.txt      crontab /var/www/scheduler.txt    #cron    service cron start  }    /usr/sbin/apache2ctl -D FOREGROUND  

If I was the use an .ENV file and variable, I'm firstly not sure how I'd reference that in the entrypoint.sh but also how do I manage different .ENV files between DEV and PROD (bear in mind I'm running PROD as a docker-swarm).

Or, can I use a node tag (like I can for docker-compose > deploy > placement > constraints)?

Ideally it'll, by default NOT run the crontab, and only run from if a specific ENV or tag is met.

Thanks!

FILES

docker-compose.yml

version: "3.5"  services:    example:      build:        context: .        dockerfile: ./example.Dockerfile      image: username/example  ...  

docker-compose-prod.yml

version: '3.5'  services:    example:      image: username/example  ...  

Dockerfile

FROM php:7.4-apache    RUN ....    # MULTIPLE ENTRYPOINTS to enable cron and apache  ADD entrypoint.sh /entrypoint.sh     RUN chmod +x /entrypoint.sh    ENTRYPOINT /entrypoint.sh  

entrypoint.sh

#!/bin/bash    # Setup a cron schedule  echo "* * * * * /usr/local/bin/php /var/www/html/cron.php >> /var/log/cron.log 2>&1  # This extra line makes it a valid cron" > /var/www/scheduler.txt    crontab /var/www/scheduler.txt  #cron  service cron start    /usr/sbin/apache2ctl -D FOREGROUND  

Vlookup and Countif by its color and lookup value

Posted: 19 Jun 2022 08:23 PM PDT

I am trying to make a risk map. I am trying to find the number of cells with the corresponding colour and lookup value. For example, E3 will be 2 because, on the table next to it, there are 2 red highlighted risks for credit risk. the picture is only example, I am trying to count it automatically because there are more than a hundred risk data which is updated every month so I don't want to count every time. I tried to find a VBA function and tried to combine excel's own function but couldn't do it.

Google Analytics 4 does not work with Nextjs Script tag

Posted: 19 Jun 2022 08:22 PM PDT

I have built a site with Nextjs. I tried integrating GA to the site. I tried to implement with next/script tag but GA does not show reports, users, pageviews, etc. on the dash board. But if I use normal script tag then it works.

Why Google Analytics is not working with next/script tag.

GA Code Snippet with next/script [not working]

<Script    src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GA_MEASUREMENT_ID}`}    strategy="afterInteractive"    />      <Script id="google-analytics-script" strategy="afterInteractive">          {`                window.dataLayer = window.dataLayer || [];                function gtag(){dataLayer.push(arguments);}                gtag('js', new Date());                gtag('config', '${process.env.GA_MEASUREMENT_ID}');          `}   </Script>   

Note: I have also tried setting ga code inside dangerouslySetInnerHTML with next/script but it still does not work.

GA code snippet with regular script tag [working]

<script    async    src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GA_MEASUREMENT_ID}`}   />     <script     dangerouslySetInnerHTML={{     __html: `     window.dataLayer = window.dataLayer || [];     function gtag(){dataLayer.push(arguments);}     gtag('js', new Date());     gtag('config', '${process.env.GA_MEASUREMENT_ID}', { 'send_page_view': true });              `,     }}   />  

Now my simple question is that why google analytics is not working with next/script?

how to fast set the bitset by using multiple position once

Posted: 19 Jun 2022 08:26 PM PDT

how to fast set the bitset by using multiple position, eg: the position : 1,4,5,6,9,3. the bitset is 0101111001....,whether can use SIMD instruction? I know the simple method, eg: assume the word_t is unsigned char:

void set_mask(word_t* bitset, int position) {    int index= position / std::numeric_limits<word_t>::digits;    int offset = position % std::numeric_limits<word_t>::digits;    bitset[index] |= (1U << (std::numeric_limits<word_t>::digits -1 - offset));  }  

How to automatic intent to other activity like from SplashActivity to other Activity with timer? [duplicate]

Posted: 19 Jun 2022 08:25 PM PDT

How to automatic intent to other activity like from SplashActivity to other Activity with timer using Kotlin?

Error with badge_icon in MDIcon Kivy Python

Posted: 19 Jun 2022 08:25 PM PDT

I cant use badge_icon MDIcon from this documentation. And this is the source that I used to use. What happened?

MDNavigationLayout:      ScreenManager:          id: screen_manager            Screen:              name: "scr 0"              BoxLayout:                  orientation: "vertical"                  BoxLayout:                      MDLabel:                          text: "Screen 0"                          halign: "center"                      MDIcon:                          icon: "git"                          badge_icon: "numeric-10"  

And the result of this source code is like this.

The git icon don't have badge_icon

How to make Apple Sign In Revoke Token POST Request?

Posted: 19 Jun 2022 08:23 PM PDT

How do I structure a swift POST request to satisfy the Sign In With Apple token revocation requirements?

I am not sure what form-data, client_id, client_secret, token, or token_type_hint are supposed to be. I was able to implement Sign in With Apple to create a user, but very lost on the revocation part of this.

I am looking to perform this client-side with Swift, as that would be the most convenient. Firebase may be developing a solution built into their SDK, but not sure if that is a one-size fits all solution for developers using Firebase.

https://developer.apple.com/documentation/sign_in_with_apple/revoke_tokens#url

Edit: source of requirements https://developer.apple.com/support/offering-account-deletion-in-your-app

The following functions live in the same class (ViewModel). The first does my login/registration flow. Some of the code is related to Firebase flows and can be largely ignored, but you can see I grab the token string and nonce for client_secret. The second function resembles the POST request for token revocation (which gets called from a delete account function not shown). Has anyone had success with this approach/boilerplate?

Testing the token revocation method below with a button tap in my app returns status code 400. I cannot revoke tokens with this method, and I am not sure what else to do.

public func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {      // Sign in using Firebase Auth      if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {          guard let nonce = currentNonce else {              print("Invalid state: A login callback was received, but no login request was sent.")              return          }                    // JWT          guard let appleIDToken = appleIDCredential.identityToken else {              print("Unable to fetch identity token")              return          }                    guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {              print("Unable to serialize token string from data")              return          }                    let credential = OAuthProvider.credential(withProviderID: "apple.com", idToken: idTokenString, rawNonce: nonce)          Auth.auth().signIn(with: credential) { result, error in              if error != nil {                  print(error!.localizedDescription)                  return              }              else { // successful auth, we can now check if its a login or a registration                  guard let user = Auth.auth().currentUser else {                      print("No user was found.")                      return                  }                  let db = Firestore.firestore()                  let docRef = db.collection("Users").document(("\(user.uid)"))                  docRef.getDocument{ (document, error) in                      if let document = document, document.exists {                          // User is just logging in, their db store exists                          print("Successful Apple login.")                                                    // Token revocation requirements                          self.clientSecret = nonce                          self.appleToken = idTokenString                                                    if (self.isDeletingAccount == true) {                              print("Is deleting account.")                              self.isReauthenticated = true                          }                          self.isLogged = true                      }                      else { // document does not exist! we are registering a new user                          db.collection("Users").document("\(user.uid)").setData([                              "name": "\(appleIDCredential.fullName?.givenName ?? "")"                          ])                          print("Successful Apple registration.")                                                    self.clientSecret = nonce                          self.appleToken = idTokenString                                                    self.isLogged = true                      }                  }              }          }      }  }      // POST request to revoke user's Apple token from Barfix app  func appleAuthTokenRevoke(completion: (([String: Any]?, Error?) -> Void)? = nil) {            let paramString: [String : Any] = [          "client_id": Bundle.main.bundleIdentifier!, //"com.MyCompany.Name",          "client_secret": self.clientSecret,          "token": self.appleToken,          "token_type_hint": "access_token"      ]            let url = URL(string: "https://appleid.apple.com/auth/revoke")!            var request = URLRequest(url: url)      request.httpMethod = "POST"            do {          request.httpBody = try JSONSerialization.data(withJSONObject: paramString, options: .prettyPrinted)      }      catch let error {          print(error.localizedDescription)          completion?(nil, error)      }            request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")            let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in          guard let response = response as? HTTPURLResponse, error == nil else {              print("error", error ?? URLError(.badServerResponse))              return          }                    guard (200 ... 299) ~= response.statusCode else {              print("statusCode should be 2xx, but is \(response.statusCode)")              print("response = \(response)")              return          }                              if let error = error {              print(error)          }          else {              print("deleted accont")          }      }      task.resume()  }  

Listing packages in MWAA with a broken scheduler

Posted: 19 Jun 2022 08:23 PM PDT

So, I'm currently working with an Airflow installation via MWAA. I'm having this issue with a broken dependency, specifically:

ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.

apache-airflow-providers-amazon 1.4.0 requires watchtower~=0.7.3, but you have watchtower 2.0.1 which is incompatible.

I want to get a list of the currently installed packages to do some debugging, but the broken install also seems to break the scheduler. Also, the worker logs suggest that it just keeps trying and failing to install what is listed in requirements.txt.

Besides just removing the package with a broken dependency, is there any way of listing the currently installed packages outside of just creating a DAG to do it? I know the DAG shouldn't be difficult to write, It's just that it will never be executed anyways since the scheduler is preoccupied

here is the current requirements.txt:

--trusted-host <A private repository>  --index-url <A private repository>  gnupg  snowflake-connector-python  snowflake-sqlalchemy  apache-airflow-providers-snowflake  

EDIT: I tried adding "apache-airflow-providers-amazon" from our internal repo and got some strange results. No errors reported in the log, except for a failure to connect to the standard pypi repo (this error also occurs with working versions of requirements.txt however). However, the scheduler still appears to be broken.

SwiftUI - delete row in list with context menu - UI glitch

Posted: 19 Jun 2022 08:23 PM PDT

I've a array of items displayed using List in my SwiftUI View. I tired to add a contextMenu to delete individual items in the List. The following is the result.

delteing items from list

The animation is not what is expected. The row blinks before moving the next one. How to set animation.right or something like that so that there is no UI glitch and looks like the default behavior which happens at onDelete.

PS: I can't use onDelete because, in my app, swiping right and left has other functions.

Here is the code.

  struct ListDelete: View {            @State var cars = ["Tesla", "Mercedes", "Audi", "Tata", "Jaguar"]            var body: some View {          List(cars, id: \.self) { car in              Text(car).contextMenu {                  Button(action: {                      if let index = self.cars.firstIndex(of: car) {  //                        self.cars.remove(at: index)                          self.cars.remove(atOffsets: [index])                      }                  }, label: {                      HStack {                          Text("Delete")                          Spacer()                          Image(systemName: "trash")                      }                  })              }          }      }  }    

The two approaches used to remove the items from the array, resulted in this same behavior.

Numpy array dimensions

Posted: 19 Jun 2022 08:26 PM PDT

How do I get the dimensions of an array? For instance, this is 2x2:

a = np.array([[1,2],[3,4]])  

No comments:

Post a Comment