Tuesday, 31 January 2023

How to implemented Nested ListView.builder in Flutter?

I have already gone through this post

for nested scrolling but it is not the correct way according to me as explained in this video from the official flutter channel

I want to achieve the below layout

enter image description here

The list header like Claim requested credentials,Claim received credentials,Pending Requests etc are dynamic and will be coming from backend. Also each item in those list header like Module 1: Designing Financial Services are also dynamic

So I need list within a list

I am using a CustomScroll but I am not able to achieve the inner list view

I am looking for a lazy list option and not just mapping the inner list over a column or a list as the inner list might contain 100 items

Here is what I have achieved

enter image description here

Here is the sample code

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          HeaderGradient(),
          Positioned(
            top: 110,
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              padding: const EdgeInsets.all(8.0),
              decoration: const BoxDecoration(
                color: grayColor,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20),
                  topRight: Radius.circular(20),
                ),
              ),
              child: CustomScrollView(
                slivers: [
                  const SliverToBoxAdapter(
                    child: ManageCredentialHeader(),
                  ),
                  SliverList(
                      delegate: SliverChildBuilderDelegate((context, index) {
                    return ManageCredentialCard();
                  }, childCount: 10))
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

and

class ManageCredentialCard extends StatelessWidget {
  const ManageCredentialCard({super.key});

  @override
  Widget build(BuildContext context) {
    return Card(
      color: Theme.of(context).colorScheme.background,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        child: Column(
          children: [
            const ManageCredentialCardHeader(),

            const ManageCredentialCardItem()
          ],
        ),
      ),
    );
  }
}

ManageCredentialCardItem is the inner list

As soon as I wrap ManageCredentialCardItem inside a ListView.builder I get error saying

RenderFlex children have non-zero flex but incoming height constraints are
unbounded.
When a column is in a parent that does not provide a finite height constraint,
for example if it is
in a vertical scrollable, it will try to shrink-wrap its children along the
vertical axis. Setting a
flex on a child (e.g. using Expanded) indicates that the child is to expand to
fill the remaining
space in the vertical direction.

Check the sample repo to check what I have tried and full source code



from How to implemented Nested ListView.builder in Flutter?

How to pass an object from a carousel view to a custom control in Xamarin.Forms?

I currently have a carousel view that makes use of an object in the binding context to obtain a list of instances of the ListItem property. The binding to MyList for the CarouselView is working fine and I am able to scroll left and right for every item in my list. The trouble that I'm having is that while the CustomControl is being loaded, it is not receiving the ListItem that will fit in the Item property. So, the this.Item property in CustomControl is just returning null.

<ContentPage.Content>
                    <CarouselView ItemsSource="{Binding MyList}">
                        <CarouselView.ItemTemplate>
                            <DataTemplate>
                                <StackLayout>
                                    <controls:CustomControl Item="{Binding}"/>
                                </StackLayout>
                            </DataTemplate>
                        </CarouselView.ItemTemplate>

                    </CarouselView>

                </Grid>
    </ContentPage.Content>
[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class HomeView : ContentPage
    {
        private ListContainer vm; 
        
        public HomeView()
        {
            InitializeComponent();
            Task.Run(async () =>
            {
                vm = DiContainer.Resolve<ListContainer>();
                await vm.Initialise();

                Device.BeginInvokeOnMainThread(() =>
                {
                    this.BindingContext = vm;
                });

            });
        }
    }
[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class CustomControl : ContentView
    {

        public static readonly BindableProperty ItemProperty = BindableProperty.Create(nameof(Item), 
            typeof(ListItem), typeof(CustomControl), default(ListItem),BindingMode.TwoWay);

        public ListItem Item
        {
            get => (ListItem)GetValue(ItemProperty);
            set => SetValue(ItemProperty, value);
        }

        public CustomControl ()
        {
            InitializeComponent ();
            BindingContext = this.Item;
        }

    }


from How to pass an object from a carousel view to a custom control in Xamarin.Forms?

Fatal Exception: java.net.SocketTimeoutException on Android 10 and above

I'm getting this crash on my app

(Platform.kt line 128 okhttp3.internal.platform.Platform.connectSocket)
Fatal Exception: java.net.SocketTimeoutException failed to connect to domain/IP (port 443) from /Another IP (port 37062) after 120000ms: isConnected failed: ETIMEDOUT (Connection timed out)

Crash details on firebase crashlytics

libcore.io.IoBridge.isConnected (IoBridge.java:343)


java.net.Socket.connect (Socket.java:646)
okhttp3.internal.platform.Platform.connectSocket (Platform.kt:128)
okhttp3.internal.connection.ConnectPlan.connectSocket (ConnectPlan.kt:246)
okhttp3.internal.connection.ConnectPlan.connectTcp (ConnectPlan.kt:128)
okhttp3.internal.connection.SequentialExchangeFinder.find (SequentialExchangeFinder.kt:41)
okhttp3.internal.connection.RealCall.initExchange$okhttp (RealCall.kt:267)
okhttp3.internal.connection.ConnectInterceptor.intercept (ConnectInterceptor.kt:32)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.kt:96)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.kt:83)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.kt:75)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
co.bosta.bosta_star_app.di.NetworkModuleKt$networkModule$1$invoke$provideOkHttpClient$$inlined$-addInterceptor$1.intercept (OkHttpClient.kt:1156)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.logging.HttpLoggingInterceptor.intercept (HttpLoggingInterceptor.kt:155)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp (RealCall.kt:205)
okhttp3.internal.connection.RealCall$AsyncCall.run (RealCall.kt:533)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1137)

java.lang.Thread.run (Thread.java:1012)
Caused by android.system.ErrnoException
isConnected failed: ETIMEDOUT (Connection timed out)
libcore.io.IoBridge.isConnected (IoBridge.java:334)

java.net.Socket.connect (Socket.java:646)
**okhttp3.internal.platform.Platform.connectSocket (Platform.kt:128)**
okhttp3.internal.connection.ConnectPlan.connectSocket (ConnectPlan.kt:246)
okhttp3.internal.connection.ConnectPlan.connectTcp (ConnectPlan.kt:128)
okhttp3.internal.connection.SequentialExchangeFinder.find (SequentialExchangeFinder.kt:41)
okhttp3.internal.connection.RealCall.initExchange$okhttp (RealCall.kt:267)
okhttp3.internal.connection.ConnectInterceptor.intercept (ConnectInterceptor.kt:32)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.kt:96)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.kt:83)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.kt:75)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
co.bosta.bosta_star_app.di.NetworkModuleKt$networkModule$1$invoke$provideOkHttpClient$$inlined$-addInterceptor$1.intercept (OkHttpClient.kt:1156)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.logging.HttpLoggingInterceptor.intercept (HttpLoggingInterceptor.kt:155)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp (RealCall.kt:205)
okhttp3.internal.connection.RealCall$AsyncCall.run (RealCall.kt:533)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1137)

java.lang.Thread.run (Thread.java:1012)

Also getting these crashes which also related to server connection

Dns.kt line 49 okhttp3.Dns$Companion$DnsSystem.lookup Fatal Exception: java.net.UnknownHostException Unable to resolve host "host.com": No address associated with hostname

Http2Stream.kt line 675 okhttp3.internal.http2.Http2Stream$StreamTimeout.newTimeoutException Fatal Exception: java.net.SocketTimeoutException timeout

ConnectPlan.kt line 315 Fatal Exception: javax.net.ssl.SSLHandshakeException SSL handshake aborted: ssl=0x75dd3e3848: I/O error during system call, Software caused connection abort

JvmOkio.kt line 94 okio.InputStreamSource.read Fatal Exception: java.net.SocketException Software caused connection abort

I found as some answers suggested I must add this to my request but I still getting the crash after that

        .connectTimeout(120, TimeUnit.SECONDS)
        .readTimeout(120, TimeUnit.SECONDS)
        .writeTimeout(120, TimeUnit.SECONDS)

Note: I check interent connection before making an API request using this method

  fun isConnected(): Boolean {
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val networkInfo=connectivityManager.activeNetworkInfo
        val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
        if (capabilities != null &&  capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
            when {
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
                    return true
                }
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
                    return true
                }
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> {
                    return true
                }
            }
        }
    } else {
        val activeNetworkInfo = connectivityManager.activeNetworkInfo
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
            return true
        }
    }
    return false
}


from Fatal Exception: java.net.SocketTimeoutException on Android 10 and above

Apollo-express-server passing only first Upload(file) and the rest are missing

I am using apollo-express server with GraphQL. I have a mutation where I pass files from front-end to back-end but I receive the file:{} object only for first one - for the other's I receive promise.

Here is my mutation declaration:

 extend type Mutation {
    createCase(input: CreateCase!, attachments: [Upload]): Case
  }

I simplified my implementation just to console.log the attachments:

Mutation: {
    createCase: async (
      parentValue: any,
      { input, attachments }: { input: CaseInterface; attachments: [File] },
      context: any
    ) => {
     
      console.log(attachments)
    }
}

I am passing the files from front-end like this:

const SEND_CASE = gql`
  mutation CreateCase($input: CreateCase!, $attachments: [Upload]) {
    createCase(input: $input, attachments: $attachments) {
      _id
    }
  }
`;

and the function usage:

 createCase({
      variables: {
        input: {
          description: props.creationData.description,
          date: new Date().toDateString(),
          priority: props.creationData.priority,
          userId: props.creationData.userId,
          categoryId: props.categories.map((el: any) => el._id),
          signature: "",
          type: props.casetype === "problem" ? 1 : 2,
        },
        attachments: props.creationData.attachments,
      },
    });

the prop.creationData.attachments is looking normal: enter image description here

The problem is that in my back-end I console.log(attachments) looks-like this:

[
  Upload {
    resolve: [Function (anonymous)],
    reject: [Function (anonymous)],
    promise: Promise { [Object] },
    file: {
      filename: 'wa.jpg',
      mimetype: 'image/jpeg',
      encoding: '7bit',
      createReadStream: [Function: createReadStream]
    }
  },
  Upload {
    resolve: [Function (anonymous)],
    reject: [Function (anonymous)],
    promise: Promise { <pending> }
  }
]

The file in second Upload object is missing and the Promise there is pending. I cannot explain myself why is that. Also I have console.log the req.body and req.header if it is needed:

{
  host: '192.168.1.152:3001',
  connection: 'keep-alive',
  'content-length': '51479',
  accept: '*/*',
  'apollo-require-preflight': 'true',
  authorization: '',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
  'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryA2VfmoLeZm9NTXsk',
  origin: 'http://localhost:3000',
  referer: 'http://localhost:3000/',
  'accept-encoding': 'gzip, deflate',
  'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8,bg;q=0.7'
}
{
  operationName: 'CreateCase',
  variables: {
    input: {
      description: 'test',
      date: 'Thu Jan 19 2023',
      priority: 1,
      userId: '630899dc48a9a14833398a7e',
      categoryId: [Array],
      signature: '',
      type: 1
    },
    attachments: [ [Upload], [Upload] ]
  },
  query: 'mutation CreateCase($input: CreateCase!, $attachments: [Upload]) {\n' +
    '  createCase(input: $input, attachments: $attachments) {\n' +
    '    _id\n' +
    '    __typename\n' +
    '  }\n' +
    '}'
}

How can I have all my files in my backend to be like the first one received?



from Apollo-express-server passing only first Upload(file) and the rest are missing

Monday, 30 January 2023

Can Android device pretend and connect as a BlueTooth controller

Can Android device pretend and connect as a BlueTooth controller? Can Android devices connect as a device to say PC and act as a Gamepad or similar device? Is it allowed and doable in code without root?

I tried this code https://developer.android.com/guide/topics/connectivity/bluetooth/connect-bluetooth-devices but can not get it to pair.



from Can Android device pretend and connect as a BlueTooth controller

exporting a javascript react class component into a typescript file

is there a way to export a javascript react class component into a typescript file? i have the following code

Login.js

class Login extends Component {

constructor(props) {
    super(props);
    this.usernameText = React.createRef();
    this.passwordText = React.createRef();
    this.urlText = React.createRef();
    this.keyPress = this.keyPress.bind(this);
  }

  .
  .   
  .
 }
 export default  Login;

index.ts

const Login = require("./uiManagement/jiraUI/Login/Login");
export {
 Login as JiraUiLogin 
}

in another project i did an npm import for the above to use the login component

 import { Component } from "react";
import { JiraUiLogin } from "infosysta-typescript-core";
class mLogin extends Component {
  render() {
    return (
      <JiraUiLogin />
    )
  }
};
export default mLogin

but i having the following error enter image description here



from exporting a javascript react class component into a typescript file

Google Play Integrity API result UNEVALUATED after mobile restart

I have released my app with google play integrity api. App works after device integrity check success

"deviceIntegrity": {
    "deviceRecognitionVerdict": ["MEETS_BASIC_INTEGRITY", "MEETS_DEVICE_INTEGRITY"]
  },

I found issue with some user facing the issue that device passes device integrity at the time of install but after restart device, deviceIntegrity check failed

here is response what i found during debugging after restart

{
   "requestDetails": {
     "requestPackageName": "com.my.package",
     "timestampMillis": "1674455009345",
     "nonce": "Y29tLm1hbnRyYS5yZHNlcnZpY2UyMDIzMDEyMzExNTIzMjajHDrnJ9vtl2AfC1fUdEDJmD_HfvFtcpc\u003d"
   },
   "appIntegrity": {
     "appRecognitionVerdict": "UNEVALUATED"
   },
   "deviceIntegrity": {
   },
   "accountDetails": {
     "appLicensingVerdict": "UNEVALUATED"
   }
 }

I have search about UNEVALUATED result

"Application integrity was not evaluated. A necessary requirement was missed, such as the device not being trustworthy enough."

But the issue accures only after restarting the android device

I Hope some one can help us on this issue.



from Google Play Integrity API result UNEVALUATED after mobile restart

Plotly Dash: Uncaught (in promise) Error after upgrading dash to 2.7.1

I have a Dash App running inside a Flask App. I am seeing a bunch of errors in the console after upgrading dash to 2.7.1

Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received


Uncaught (in promise) Error: There is already a source with this ID

at r.addSource (async-plotlyjs.js:2:1020888)
    at i.addSource (async-plotlyjs.js:2:1219363)
    at l.addSource (async-plotlyjs.js:2:2988732)
    at async-plotlyjs.js:2:2989736
    at h (async-plotlyjs.js:2:2989770)
    at l.update (async-plotlyjs.js:2:2990100)
    at b.updateData (async-plotlyjs.js:2:2338377)
    at async-plotlyjs.js:2:2336961

error-ss

I do not see any errors in the application logs. What is the error? Any suggestions on where to look / troubleshoot?



from Plotly Dash: Uncaught (in promise) Error after upgrading dash to 2.7.1

Plotly Dash: Uncaught (in promise) Error after upgrading dash to 2.7.1

I have a Dash App running inside a Flask App. I am seeing a bunch of errors in the console after upgrading dash to 2.7.1

Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received


Uncaught (in promise) Error: There is already a source with this ID

at r.addSource (async-plotlyjs.js:2:1020888)
    at i.addSource (async-plotlyjs.js:2:1219363)
    at l.addSource (async-plotlyjs.js:2:2988732)
    at async-plotlyjs.js:2:2989736
    at h (async-plotlyjs.js:2:2989770)
    at l.update (async-plotlyjs.js:2:2990100)
    at b.updateData (async-plotlyjs.js:2:2338377)
    at async-plotlyjs.js:2:2336961

error-ss

I do not see any errors in the application logs. What is the error? Any suggestions on where to look / troubleshoot?



from Plotly Dash: Uncaught (in promise) Error after upgrading dash to 2.7.1

R/Javascript: Collapsing and Expanding Networks

I am working with the R programming language.

I have the following graph network data:

library(igraph)
library(visNetwork)

from <- c("Boss", "TeamA", "TeamA", "TeamA", "SubteamA1", "SubteamA1", "SubteamA1", "SubteamA2", "SubteamA2", "SubteamA2", "SubteamA3", "SubteamA3", "SubteamA3")
to <- c("TeamA", "SubteamA1", "SubteamA2", "SubteamA3", "employee1", "employee2", "employee3", "employee4", "employee5", "employee6", "employee7", "employee8", "employee9")
a1 = data_frame <- data.frame(from, to)


from <- c("Boss", "TeamB", "TeamB", "TeamB", "SubteamB1", "SubteamB1", "SubteamB1", "SubteamB2", "SubteamB2", "SubteamB2", "SubteamB3", "SubteamB3", "SubteamB3")
to <- c("TeamB", "SubteamB1", "SubteamB2", "SubteamB3", "employee10", "employee11", "employee12", "employee13", "employee14", "employee15", "employee16", "employee17", "employee18")
a2 = data_frame <- data.frame(from, to)


final = rbind(a1, a2)

I then made it into a graph network and visualized it:

# Convert the data frame to an igraph object
g <- graph_from_data_frame(final, directed=FALSE)

# Plot the graph
plot(g)

# Optional visualization
visIgraph(g)

visIgraph(g) %>%
  visHierarchicalLayout(direction = "LR") %>%
  visInteraction(navigation = "zoom") %>%
  visInteraction(navigation = "drag") %>%
  visOptions(selectedBy = "to", 
             highlightNearest = TRUE, 
             nodesIdSelection = TRUE) 

enter image description here

My Question: I have been trying to find if there some way such that when you run the graph, it only shows one node on the screen (boss node) - and when you click on the boss node, it expands into 3 nodes (boss, team a, team b), and if you click on "team a", it expands into sub teams ... but if you double click, it collapse back to the previous layer.

The closest thing I could find to this is here: https://github.com/datastorm-open/visNetwork/issues/307

But is there some easier way to do this in R/javascript? In the end, the final output should be a (standalone) HTML file that can be viewed offline.

Thanks!

Note:



from R/Javascript: Collapsing and Expanding Networks

Drawing line of regression onto scatter graph in python

I am trying to draw the line of regression onto a scatter graph. I have two functions:

def place_y(x, slope, intercept):
    return slope * x + intercept


def draw_line_of_regression():
    """The line of regression can be used to predict further values"""
    import matplotlib.pyplot as plt  # used to draw graph
    from scipy import stats

    # Example shows relationship between age and speed
    age_x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
    speed_y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]

    slope, intercept, r, p, std_error = stats.linregress(age_x, speed_y)
    # gets variables used in drawing the line of regression

    line_of_regression = list(map(place_y(age_x, slope, intercept), age_x))

    plt.scatter(age_x, speed_y)  # draws scatter graph
    plt.plot(age_x, line_of_regression)
    plt.show()  # shows the graph


draw_line_of_regression()

When this is run there is an error with the place_y() function. Error:

    return slope * x + intercept
TypeError: can't multiply sequence by non-int of type 'numpy.float64


from Drawing line of regression onto scatter graph in python

Sunday, 29 January 2023

Using canvas pointermove event on phone, the pointerleave event gets fired

I am just trying to draw on my phone using "pointer" events.

This works on my desktop with my mouse, but not on my (android) phone. I should be able to draw curved lines, but dragging with my finger on my phone results in an "enter" and a few "moves" but then it "leave"s.

It has to be online: https://dbarc.net/SOtest.html

<!DOCTYPE html>
<html>
<!-- works on desktop, leaves on phone (dbarc.net/SOtest.html) -->
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
body { width:400px; }
#canvas { background:#eee; }    
    </style>
    <script>
  "use strict";
  let canvas, ctx, xx, yy, infodiv;
window.onload = function() {
  infodiv = document.getElementById("infodiv"); // info output
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  canvas.addEventListener('pointerenter', function() { ptrEnter(); } );
  canvas.addEventListener('pointerleave', function() { ptrLeave(); } );
  canvas.addEventListener('pointermove', function(ev) { ptrMove(ev); } );
}
function ptrEnter() { // shows an enter
  infodiv.innerHTML += "ENTER ";
}
function ptrLeave() { // shows a leave
  infodiv.innerHTML += "LEAVE ";
}
function ptrMove(ev) { // draws (no pen up/down)
  infodiv.innerHTML += "m ";
  let x0 = canvas.offsetLeft, y0 = canvas.offsetTop;
  let xold = xx, yold = yy;
  xx = Math.floor(ev.clientX) - x0; 
  yy = Math.floor(ev.clientY) - y0;
  ctx.beginPath();
  ctx.moveTo(xold,yold);
  ctx.lineTo(xx, yy);
  ctx.stroke(); 
}
    </script>
  </head>
  <body>
    <canvas id="canvas" width="400" height="300"></canvas>  
    <div id="infodiv">Events: </div>
  </body>
</html>


from Using canvas pointermove event on phone, the pointerleave event gets fired

Discriminated union in Python

Imagine I have a base class and two derived classes. I also have a factory method, that returns an object of one of the classes. The problem is, mypy or IntelliJ can't figure out which type the object is. They know it can be both, but not which one exactly. Is there any way I can help mypy/IntelliJ to figure this out WITHOUT putting a type hint next to the conn variable name?

import abc
import enum
import typing


class BaseConnection(abc.ABC):
    @abc.abstractmethod
    def sql(self, query: str) -> typing.List[typing.Any]:
        ...


class PostgresConnection(BaseConnection):

    def sql(self, query: str) -> typing.List[typing.Any]:
        return "This is a postgres result".split()

    def only_postgres_things(self):
        pass


class MySQLConnection(BaseConnection):

    def sql(self, query: str) -> typing.List[typing.Any]:
        return "This is a mysql result".split()

    def only_mysql_things(self):
        pass


class ConnectionType(enum.Enum):
    POSTGRES = 1
    MYSQL = 2


def connect(conn_type: ConnectionType) -> typing.Union[PostgresConnection, MySQLConnection]:
    if conn_type is ConnectionType.POSTGRES:
        return PostgresConnection()
    if conn_type is ConnectionType.MYSQL:
        return MySQLConnection()


conn = connect(ConnectionType.POSTGRES)
conn.only_postgres_things()

Look at how IntelliJ handles this: enter image description here

As you can see both methods: only_postgres_things and only_mysql_things are suggested when I'd like IntelliJ/mypy to figure it out out of the type I'm passing to the connect function.



from Discriminated union in Python

Automate Webview with INJECT_EVENTS permission

There is this website I need to log into with user and pass every time. I have been using the below code to inject code into the textbox in the website. (after I log in there is still more textboxes I need to fill in which I need automated)

wv.loadUrl("javascript:document.getElementById('SSUser_Logon_0-item-USERNAME').focus();");
wv.evaluateJavascript("try{document.activeElement.value='"+User+"';}catch(e){}",null);

I am now getting the error

Injecting input events requires the caller (or the source of the instrumentation, if any) to have the INJECT_EVENTS permission.

and

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

Throws an error that this permission is only granted to system apps.

I need help to either inject the code, or find another alternative to automate filling in textboxes on a website.



from Automate Webview with INJECT_EVENTS permission

Python thread calling won't finish when closing tkinter application

I am making a timer using tkinter in python. The widget simply has a single button. This button doubles as the element displaying the time remaining. The timer has a thread that simply updates what time is shown on the button.

The thread simply uses a while loop that should stop when an event is set. When the window is closed, I use protocol to call a function that sets this event then attempts to join the thread. This works most of the time. However, if I close the program just as a certain call is being made, this fails and the thread continues after the window has been closed.

I'm aware of the other similar threads about closing threads when closing a tkinter window. But these answers are old, and I would like to avoid using thread.stop() if possible.

I tried reducing this as much as possible while still showing my intentions for the program.

import tkinter as tk
from tkinter import TclError, ttk
from datetime import timedelta
import time
import threading
from threading import Event

def strfdelta(tdelta):
    # Includes microseconds
    hours, rem = divmod(tdelta.seconds, 3600)
    minutes, seconds = divmod(rem, 60)
    return str(hours).rjust(2, '0') + ":" + str(minutes).rjust(2, '0') + \
           ":" + str(seconds).rjust(2, '0') + ":" + str(tdelta.microseconds).rjust(6, '0')[0:2]

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.is_running = False
        is_closing = Event()
        self.start_time = timedelta(seconds=4, microseconds=10, minutes=0, hours=0)
        self.current_start_time = self.start_time
        self.time_of_last_pause = time.time()
        self.time_of_last_unpause = None
        # region guisetup
        self.time_display = None
        self.geometry("320x110")
        self.title('Replace')
        self.resizable(False, False)
        box1 = self.create_top_box(self)
        box1.place(x=0, y=0)
        # endregion guisetup
        self.timer_thread = threading.Thread(target=self.timer_run_loop, args=(is_closing, ))
        self.timer_thread.start()

        def on_close():  # This occasionally fails when we try to close.
            is_closing.set()  # This used to be a boolean property self.is_closing. Making it an event didn't help.
            print("on_close()")
            try:
                self.timer_thread.join(timeout=2)
            finally:
                if self.timer_thread.is_alive():
                    self.timer_thread.join(timeout=2)
                    if self.timer_thread.is_alive():
                        print("timer thread is still alive again..")
                    else:
                        print("timer thread is finally finished")
                else:
                    print("timer thread finished2")
            self.destroy()  # https://stackoverflow.com/questions/111155/how-do-i-handle-the-window-close-event-in-tkinter
        self.protocol("WM_DELETE_WINDOW", on_close)

    def create_top_box(self, container):
        box = tk.Frame(container, height=110, width=320)
        box_m = tk.Frame(box, bg="blue", width=320, height=110)
        box_m.place(x=0, y=0)
        self.time_display = tk.Button(box_m, text=strfdelta(self.start_time), command=self.toggle_timer_state)
        self.time_display.place(x=25, y=20)
        return box

    def update_shown_time(self, time_to_show: timedelta = None):
        print("timer_run_loop must finish. flag 0015")  # If the window closes at this point, everything freezes
        self.time_display.configure(text=strfdelta(time_to_show))
        print("timer_run_loop must finish. flag 016")

    def toggle_timer_state(self):
        # update time_of_last_unpause if it has never been set
        if not self.is_running and self.time_of_last_unpause is None:
            self.time_of_last_unpause = time.time()
        if self.is_running:
            self.pause_timer()
        else:
            self.start_timer_running()

    def pause_timer(self):
        pass  # Uses self.time_of_last_unpause, Alters self.is_running, self.time_of_last_pause, self.current_start_time

    def timer_run_loop(self, event):
        while not event.is_set():
            if not self.is_running:
                print("timer_run_loop must finish. flag 008")
                self.update_shown_time(self.current_start_time)
            print("timer_run_loop must finish. flag 018")
        print("timer_run_loop() ending")

    def start_timer_running(self):
        pass  # Uses self.current_start_time; Alters self.is_running, self.time_of_last_unpause

if __name__ == "__main__":
    app = App()
    app.mainloop()

You don't even have to press the button for this bug to manifest, but it does take trail and error. I just run it and hit alt f4 until it happens.

If you run this and encounter the problem, you will see that "timer_run_loop must finish. flag 0015" is the last thing printed before we check if the thread has ended. That means, self.time_display.configure(text=strfdelta(time_to_show)) hasn't finished yet. I think closing the tkinter window while a thread is using this tkinter button inside of it is somehow causing a problem.

There seems to be very little solid documentation about the configure method in tkinter. Python's official documention of tkinter mentions the function only in passing. It's just used as a read-only dictionary.
A tkinter style class gets a little bit of detail about it's configure method, but this is unhelpful.
The tkdocs lists configure aka config as one of the methods available for all widgets.
This tutorial article seems to be the only place that shows the function actually being used. But it doesn't mention any possible problems or exceptions the method could encounter.

Is there some resource sharing pattern I'm not using? Or is there a better way to end this thread?



from Python thread calling won't finish when closing tkinter application

Apply a CSS class to captions under all images (in JavaScript)

I'm using the Divi theme builder on my site. I've placed captions under each of my images in a text block. The captions are all in italics. Could anyone tell me if it's possible for me add some JavaScript that would automatically recognise the caption lines and apply a CSS class to them? It would be good if this could be automated as it would be very time consuming to manually add the CSS class to each caption.

This is the HTML I'm using:

<div class="dmpro_timeline_item_description">
  <p>
    <a style="color: inherit;" href="https://path-to-image.jpg">
      <img decoding="async" loading="lazy" src="https://path-to-image.jpg" width="300" height="237" alt="" class="wp-image-2179 alignnone size-medium" srcset="https://path-to-image.jpg 300w, https://path-to-image.jpg 1024w, https://path-to-image.jpg 768w, https://path-to-image.jpg 1536w, https://path-to-image.jpg 2048w, https://path-to-image.jpg 15w, https://path-to-image.jpg 1080w, https://path-to-image.jpg 1280w, https://path-to-image.jpg 980w, https://path-to-image.jpg 480w" sizes="(max-width: 300px) 100vw, 300px">
      <br>
      <em>This is the image caption text.</em>
    </a>
  </p>
  <p>This is where further details go (outside of the caption)</p>
</div>


from Apply a CSS class to captions under all images (in JavaScript)

Saturday, 28 January 2023

How do I get my layout component to remain static in Next13 app folder

I am trying to create a layout component that fetches its own data, I have tried adding the cache: 'force-cache' to the fetch but every time I update my CMS content and refresh my page the new content is loaded. Here is an example of my code:

const getLayoutData = async () => {
 const response = await fetch(
    `https://cdn.contentful.com/spaces/${
      process.env.CONTENTFUL_SPACE_ID
    }/environments/${
      process.env.CONTENTFUL_ENVIRONMENT || "master"
    }/entries/${fieldId}?access_token=${process.env.CONTENTFUL_ACCESS_TOKEN}`,
    {
      cache: "force-cache",
    }
  );

  const {entryTitle, ...headerData} = await response.json();

  return { headerData };
}

export default async function Layout() {
 const data = await getLayoutData();
...


from How do I get my layout component to remain static in Next13 app folder

Nextjs config for JSX file type

I have created an Next 13 application where i have installed an package @viral-loops/widgets

Once the package is installed and when i run the application i am getting the following error

error - ./node_modules/@viral-loops/widgets/dist/react/Widget.jsx
Module parse failed: Unexpected token (34:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
|   return (
>     <>
|       {props.ucid ? (
|         <form-widget ucid={props.ucid} popup={props.popup} />

Here is my next.config.js

module.exports = {
  webpack(config, { isServer }) {
    const prefix = config.assetPrefix ?? config.basePath ?? '';
    config.module.rules.push(
      {
        test: /\.svg$/,
        use: ['@svgr/webpack', 'url-loader'],
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'url-loader',
          },
        ],
      },
      {
        test: /\.(mp4|webm|mov|ogg|swf|ogv)$/,
        use: [
          {
            loader: require.resolve('file-loader'),
            options: {
              publicPath: `${prefix}/_next/static/videos/`,
              outputPath: `${isServer ? '../' : ''}static/videos/`,
              name: '[name]-[hash].[ext]',
            },
          },
        ],
      },
    );
    return config;
  },
  images: {
    disableStaticImages: true,
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'images.ctfassets.net',
        pathname: '**',
      },
    ],
  },
  sassOptions: {
    includePaths: [
      path.join(__dirname, 'styles'),
      path.join(__dirname, 'styles/variables.scss'),
    ],
    prependData: '@import "./styles/variables.scss";',
  },
  compilerOptions: {
    baseUrl: '.',
    paths: {
      '@/components/*': ['components/*'],
    },
  },
};

I have tried setting up babel-loader like below in the next.config.js webpack

module.exports = {
  webpack(config, { isServer }) {
    const prefix = config.assetPrefix ?? config.basePath ?? '';
    config.module.rules.push(
      **{test: /\.(js|jsx)$/, use: 'babel-loader'}**,

Which returns a new error like below

Syntax error: Support for the experimental syntax 'jsx' isn't currently enabled (34:5):

  32 |
  33 |   return (
> 34 |     <>
     |     ^
  35 |       {props.ucid ? (
  36 |         <form-widget ucid={props.ucid} popup={props.popup} />
  37 |       ) : null}

Add @babel/preset-react (https://github.com/babel/babel/tree/main/packages/babel-preset-react) to the 'presets' section of your Babel config to enable transformation.

I am not sure where i have to add the @babel/preset-react in Nextjs application.



from Nextjs config for JSX file type

Aligning x position of tspan in IE11 using d3.js

Really struggling with this. I've tried a lot of hacks to get the labels to render correcly on my force directed d3 graph. Here is a stackBlitz

You will notice in all other browsers except IE11 renders ok.

enter image description here

In IE:

enter image description here

As you can see in IE11 the first <tspan> isn't anchored to the middle. I've tried a combination of things with and without the x attribute, dx manipulation. I have lined them up via the dx attribute but as each set of labels have different lengths the math isn't the same for each.

The svg structure is as follows:

<text class="edgelabel" id="edgelabel0" font-size="10" style="text-anchor: middle;">
   <textPath xlink:href="#edgepath0" dominant-baseline="middle" startOffset="50%" style="cursor: pointer;">
      <tspan class="edgelabels" dx="0">label one</tspan>
      <tspan class="edgelabels" x="0" dy="22" dx="0">label two</tspan>
      <tspan class="edgelabels" x="0" dy="22" dx="0">label three</tspan>
   </textPath>
</text>

You can see above in this particular implementation I intentionally left out the x attribute for the first tspan.

This is the code that renders the above:

const edgelabels = zoomContainer
  .selectAll('.edgelabel')
  .data(links)
  .enter()
  .append('text')
  .attr('class', 'edgelabel')
  .style('text-anchor', 'middle')
  .attr('id', function (d, i) {
    return 'edgelabel' + i;
  })
  .attr('font-size', 10);

edgelabels
  .append('textPath')
  .attr('xlink:href', function (d, i) {
    return '#edgepath' + i;
  })
  .style('cursor', 'pointer')
  .attr('dominant-baseline', 'middle')
  .attr('startOffset', '50%')
  .selectAll('div.textPath')
  .data(function (d, i) {
    return d.label;
  })
  .enter()
  .append('tspan')
  .attr('class', 'edgelabels')
  .text(function (d, i) {
    return console.log(d), d;
  })
  .attr('x', function (d, i) {
    if (i > 0) {
      return 0;
    }
  })
  .attr('dy', function (d, i) {
    if (i > 0) {
      return 22;
    }
  })
  .attr('dx', 0);

Has anybody else had this issue, can you see anything wrong? Is there anything else I could try to get a consistent dx attribute for each set of labels? Could I restructure the code to get a better result?



from Aligning x position of tspan in IE11 using d3.js

Plotting nodes in a network graph with the help of co-ordinate positions

"nodes": [
{
  "data": {
    "id": 1,
    "desc": "Rohit",
    "pos": [
      121.0284957885742,
      116.3165512084961,
      59.36788940429688
    ]
   }
  },
  {
  "data": {
    "id": 2,
    "desc": "Deep",
    "pos": [
      12.10284957885742,
      116.3165512084961,
      5.936788940429688
    ]
  }
 },
 "data": {
    "id": 3,
    "desc": "Deepa",
    "pos": [
      12.10284957885742,
      11.63165512084961,
      5.936788940429688
    ]
   }
  }
  ]

The above is the co-ordinates of nodes.

"edges": [
{
  "data": {
    "id": "1_2",
    "source": 1,
    "target": 2
  }
}

The above is a sample input for the link. How can I create and assign the positions of nodes in d3 according to the given co-ordinates? I've tried with co-ordinates which has pixel as unit of the co-ordinates but the above sample set does not contain any units as such.

The full code is below...

<!DOCTYPE html>
<meta charset="utf-8">
<style>
 .node {
   fill: blue;
   stroke: black;
   stroke-width: 2px;
  }

 .node.visited {
   fill: red;
 }

 .link {
   stroke-width: 2px;
 }
</style>

<body>
 <script src="https://d3js.org/d3.v3.min.js"></script>
 <script>
   var width = 640,
       height = 480;

   var links = [{
       source: 'Rohit',
       target: 'Deep'
     },
     {
       source: 'Deep',
       target: 'Deepa'
     },
     {
       source: 'Deepa',
       target: 'Rohit'
     },
   ];
   var nodes = {};

   //adding to nodes
   links.forEach(function(link) {
     link.source = nodes[link.source] ||
       (nodes[link.source] = {
         name: link.source
       });

     link.target = nodes[link.target] ||
       (nodes[link.target] = {
         name: link.target
       });
   });

   //adding svg to body

   var svg = d3.select('body').append('svg')
     .attr('width', width)
     .attr('height', height);

   var defs = svg.append('defs');

   var gradient = defs
     .append('linearGradient')
     .attr('id', 'svgGradient')
     .attr('x1', '0%')
     .attr('x2', '10%')
     .attr('y1', '0%')
     .attr('y2', '10%');

   gradient
     .append('stop')
     .attr('class', 'start')
     .attr('offset', '0%')
     .attr('start-color', 'red')
     .attr('start-opacity', 1);

   gradient
     .append('stop')
     .attr('class', 'end')
     .attr('offset', '100%')
     .attr('stop-color', 'blue')
     .attr('stop-opacity', 1);

   var force = d3.layout.force()
     .size([width, height])
     .nodes(d3.values(nodes))
     .links(links)
     .on("tick", tick)
     .linkDistance(300)
     .start();

   var link = svg.selectAll('.link')
     .data(links)
     .enter().append('line')
     .attr('class', 'link')
     .attr('stroke', 'url(#svgGradient)');

   var node = svg.selectAll('.node')
     .data(force.nodes())
     .enter().append('circle')
     .attr('class', 'node')
     .on("click", clicked)
     .attr('r', width * 0.03);

   function clicked(event, d) {
     if (event.defaultPrevented) return; // dragged

     d3.select(this).transition()
       .style("fill", "black")
       .attr("r", width * 0.2)
       .transition()
       .attr("r", width * 0.03)
       .transition()
       .style("fill", "blue")
       //.attr("fill", d3.schemeCategory10[d.index % 10]);
   }


   //define the tick func.
   function tick(e) {
     node
       .attr('cx', function(d) {
         return d.x;
       })
       .attr('cy', function(d) {
         return d.y;
       })
       .call(force.drag);

     link
       .attr('x1', function(d) {
         return d.source.x;
       })
       .attr('y1', function(d) {
         return d.source.y;
       })
       .attr('x2', function(d) {
         return d.target.x;
       })
       .attr('y2', function(d) {
         return d.target.y;
       })

   }
    </script>
  </body>
</html>

Any changes to the above code snippet is acceptable. Please help me in finding the proper solution



from Plotting nodes in a network graph with the help of co-ordinate positions

problem on generating more data points and plotting

I am able to plot the stair-step like plot as attached using the below code

import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt

x = np.array([3.45, 3.88, 3.99, 4.33])
y = np.array([14.0, 11.0, 14.0, 31.0])
y = np.cumsum(y)
y0 = np.array([0])
x0 = np.interp([0], y, x)
x = np.concatenate([x0, x])
y = np.concatenate([y0, y])

# Plot
fig, ax = plt.subplots()
ax.step(x, y, color='r', where='post')
ax.set_xlim(2, 5)
ax.set_ylim(0, y.max())
ax.invert_yaxis()
plt.show()

enter image description here #####################################################

Now I need to generate more data points of x and y using interpolation function and want to generate same plot as above code produced(depicted above). I tried the below mentioned code but it produces different plot(depicted below), But definition says after interpolation, we should have the same plot, we just have more data points. enter image description here

import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt

x = np.array([3.45, 3.88, 3.99, 4.33])
y = np.array([14.0, 11.0, 14.0, 31.0])
y = np.cumsum(y)
y0 = np.array([0])
x0 = np.interp([0], y, x)
x = np.concatenate([x0, x])
y = np.concatenate([y0, y])

# I need to generate more data points
NUM = 100  # modify the number of points
funct = interp1d(x, y, kind='next')
x_cont = np.linspace(x[0], x[-1], NUM)
y_cont = funct(x_cont)

# Plot
fig, ax1 = plt.subplots()
ax1.step(x_cont, y_cont, color='r', where='post')
ax1.set_xlim(2, 5)
ax1.set_ylim(0, y.max())
ax1.invert_yaxis()
plt.show()


from problem on generating more data points and plotting

Running Twisted in background through layered python

What specific changes need to be made in the minimal reproducable code in this repository in order for the python app\appmain.py command to result in the Twisted server running the Flask API as a background process so that the control flow of the rest of the appmain.py program can continue?

The problem is clearly defined: A powershell command correctly runs Twisted as a background process, but then two layers of python subprocess successively invoke the correct powershell command as a foreground process, despite the fact that both layers of python subprocess invocations set shell=True to specify running as a background process.

The minimal code is very simple, and has been stripped down to the bare minimum required to reproduce the problem.

REPRODUCING THE ERROR:

Steps to reproduce the error:

  1. Make sure you have Python 3.10 installed on a windows machine
  2. git clone repo.git into windows machine
  3. Open up windows cmd and navigate to the root of the repo
  4. Run python app\appmain.py

The result will be that the twisted server is running but that the program execution is halted because Twisted is running in the foreground.

You can confirm the Twisted server is hosting the flask API by opening a web browser and navigating the browser to http://localhost:2345/hereis/the/endpoint/ where a simple {"hello":"world"} json will be output.

You can shut down the Twisted server by opening a second windows cmd window, navigating to the same directory, and typing python api\destroyIt.py so that you can resume testing from a clean slate.

THINGS THAT ARE CORRECT:

The base command run by the lowest level python in setItUp.py in the example works correctly and is:

powershell $a = start-process -NoNewWindow powershell { twistd web --wsgi myFlaskAPI.app } -PassThru
  

Next, the setItUp.py script includes shell=True in the subprocess.call(startTwistdCommand, shell=True) command that invokes what should be the correct powershell command.

Third, the api_caller.py class also includes shell=True in the subprocess.Popen( commandToRun,cwd=workingDir, stdout=subprocess.PIPE, shell=True) command that invokes setItUp.py

The shell=True argument in the python subprocess commands should cause the result to run in the background, according to our research.

PROBLEM RESTATEMENT:

So why does the Twisted server process halt the program by running Twisted in the foreground even though we seem to have made the correct changes in powershell and in python?

What specifically needs to be changed in the code given in order for the `` command to result in the Twisted server running in the background so that the appmain.py can continue running other commands?



from Running Twisted in background through layered python

Problem in generating logger file to a specific path

I am trying to generate a log file to a specific folder and path in greengrass v2. however the log file is created at the current directory.

The current directory at which the logger file is generated is

/sim/things/t1_gateway_iotgateway_1234/greengrass/packages/artifacts-unarchived/com.data.iot.RulesEngineCore/2.3.1-pp.38/package

Could you please help me where am I missing?

The following is my program.

import logging
from datetime import datetime
import os, sys
from logging.handlers import RotatingFileHandler

def getStandardStdOutHandler():

    formatter = logging.Formatter(
            fmt="[%(asctime)s][%(levelname)-7s][%(name)s] %(message)s (%(threadName)s[% (thread)d]:%(module)s:%(funcName)s:%(lineno)d)"
        )

     filename = datetime.now().strftime("rule_engine_%Y_%m_%d_%H_%M.log")
     path = "/sim/things/t1_gateway_iotgateway_1234/greengrass/logs/"

    _handler = RotatingFileHandler(path + filename, maxBytes=1000000, backupCount=5)
    _handler.setLevel(logging.DEBUG)
   _handler.setFormatter(formatter)
   return _handler


def getLogger(name: str):
    logger = logging.getLogger(name)

    logger.addHandler(getStandardStdOutHandler())

    return logger


from Problem in generating logger file to a specific path

Redirect from a Python AWS Lambda with AWS Gateway API Proxy

Posting here because I just can't get a redirect working. Using AWS API Gateway linked to a Python Lambda function as a proxy just returns the response and header json. Here is the code

import json

def lambda_handler(event, context):
    response = {}
    response["statusCode"]=301
    response["headers"]=[{"key": 'Location',"value": 
     'https://www.google.com'}]
    data = {}
    response["body"]=json.dumps(data)
return response

Any help will be appreciated?

Thanks



from Redirect from a Python AWS Lambda with AWS Gateway API Proxy

Friday, 27 January 2023

Python CLI Menu with Arrow Keys on Windows

The terminal I use on Windows is Mingw-w64 (Git Bash). I am trying to find or create a CLI menu with Python that I can navigate with arrow keys, however nothing I find works.

The Python library, simple-term-menu, doesn't work on Windows. console-menu doesn't use arrow keys but it just throws an error when I import it anyway. After importing windows-curses, I was able to get it working in CMD but not Git Bash (it says, "Redirection is not supported.")

I know for a fact that what I'm after is possible. The JavaScript framework, Adonis, is capable of it with their create command (yarn create adonis-ts-app hello-world). The NPM one doesn't work but Yarn does. Given this, it's obviously possible, but how?

Given all of this, how can I get the CLI menu I want in Git Bash, or how can I get windows-curses to work?



from Python CLI Menu with Arrow Keys on Windows

RCTModernEventEmitter fires twice for android fabric component

I am trying to create a fabric component for android, specifically I want to use the onClickHandler of the button component and pass a callback to react-native side via RCTModernEventEmitter. It works fine for iOS but for android the RCTModernEventEmitter emits twice every time I click the button

This is my spec

import type {HostComponent, ViewProps} from 'react-native';
import type {
  DirectEventHandler
} from 'react-native/Libraries/Types/CodegenTypes';
import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';

type Event = Readonly<{
  text?: string;
}>;

interface NativeProps extends ViewProps {
  text: string;
  onClickHandler?: DirectEventHandler<Event>; ////Event name should start with on
}

export default codegenNativeComponent<NativeProps>(
  'MyButtonView',
) as HostComponent<NativeProps>;

On native side I have created following files

public class MyButtonViewManager extends SimpleViewManager<MyButtonView> {

    public static final String NAME = "MyButtonView";
    ReactApplicationContext mCallerContext;

    public MyButtonViewManager(ReactApplicationContext reactContext) {
        mCallerContext = reactContext;
    }
 
    @NonNull
    @Override
    public String getName() {
        return NAME;
    }

    @NonNull
    @Override
    protected MyButtonView createViewInstance(@NonNull ThemedReactContext reactContext) {
        return new MyButtonView(reactContext);
    }

    @ReactProp(name = "text")
    public void setQrCodeText(MyButtonView view, String text) {
        view.setText(text);
    }


    @Nullable
    @Override
    public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
        return MapBuilder.of("topOnClickHandler",
                MapBuilder.of("registrationName", "onClickHandler")
        );
    }

}

public class MyButtonClickEvent extends Event<MyButtonClickEvent> {

    public MyButtonClickEvent(int viewId) {
        super(viewId);
    }
 
    @Override
    public String getEventName() {
        return "topOnClickHandler";
    }

//    @Override
//    public void dispatch(RCTEventEmitter rctEventEmitter) {
//        super.dispatch(rctEventEmitter);
//        rctEventEmitter.receiveEvent(getViewTag(), getEventName(), Arguments.createMap());
//    }

    @Override
    public void dispatchModern(RCTModernEventEmitter rctEventEmitter) {
        super.dispatchModern(rctEventEmitter);
        rctEventEmitter.receiveEvent(-1,
                getViewTag(),getEventName(),
                Arguments.createMap()
        );
    }

    @Nullable
    @Override
    protected WritableMap getEventData() {
        WritableMap event = Arguments.createMap();
        event.putString("message", "MyMessage");
        return event;
    }
}

public class MyButtonView extends androidx.appcompat.widget.AppCompatButton {

    public MyButtonView(Context context) {
        super(context);
        configureViews();
    }

    private void configureViews(){
        setBackgroundColor(Color.YELLOW);
        setOnClickListener(view -> {
            ReactContext reactContext = (ReactContext)getContext();
            EventDispatcher eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(
                    reactContext ,getId()
            );
            eventDispatcher.dispatchEvent(new MyButtonClickEvent(getId()));
        });
    }
}

On JS side

 <MyButtonView
          style=
          onClickHandler={(value: any) => {
            console.log('Hello ok bye', value.nativeEvent);
          }}
          text="Hello"
        />

I get value in onClickHandler of MyButtonView twice even though I press the button once

Fullrepo is here https://github.com/PritishSawant/ReactNativeFabricEventListenerExample

Edit:

I have updated my code to 0.71.1 and you can find it here



from RCTModernEventEmitter fires twice for android fabric component

How to change JQuery reisize handles axis as we rotate element?

I'm trying to add JQuery resize with handles to an element and it works fine, Except when I rotate it transform: rotate(90deg) or any other angle, the handles axis remains the same and causes issues.

I'm trying to rotate the resize handlers axis as per the elements' angle (if that's possible).

Here's the sample code I made for this:

<div class="main">
  <img src="https://tinypng.com/images/social/website.jpg" />
</div>

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<style>
.main {
  width: 400px;
  height: 400px;
  /* transform:rotate(90deg); */
  & img {
    width:100%;
    width:100%;
  }
}
</style>

<script>
function dragger() {
  $(".main").draggable({
      cursor: "move"
    });

    $(".main").resizable({
      handles: "n, e, s, w, se, ne",
     });
}

dragger();
</script>

Here, the resize along with draggable works perfectly fine, except as I add transform: rotate(90deg) to the `main element, the resize handles axis remains the same.

Here's a JSFiddle for the same to play around.

Any help is greatly appreciated.



from How to change JQuery reisize handles axis as we rotate element?

SARIMAX out of sample forecast with exogenous data

I am working on a timeseries analysis with SARIMAX and have been really struggling with it.

I think I have successfully fit a model and used it to make predictions, however, I don't know how to make out of sample forecast with exogenous data.

I may be doing the whole thing wrong so I have included my steps below with some sample data;

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from pandas import datetime

# Defining Sample data
df=pd.DataFrame({'date':['2019-01-01','2019-01-02','2019-01-03',
                         '2019-01-04','2019-01-05','2019-01-06',
                         '2019-01-07','2019-01-08','2019-01-09',
                         '2019-01-10','2019-01-11','2019-01-12'],
                  'price':[78,60,62,64,66,68,70,72,74,76,78,80],
                 'factor1':[178,287,152,294,155,245,168,276,165,275,178,221]
                })
# Changing index to datetime
df['date'] = pd.to_datetime(df['date'], errors='ignore', format='%Y%m%d')
select_dates = df.set_index(['date'])

df = df.set_index('date')
df.index = pd.to_datetime(df.index)
df.sort_index(inplace=True)
df.dropna(inplace=True)

# Splitting Data into test and training sets manually
train=df.loc['2019-01-01':'2019-01-09']
test=df.loc['2019-01-10':'2019-01-12']

# setting index to datetime for test and train datasets
train.index = pd.DatetimeIndex(train.index).to_period('D')
test.index = pd.DatetimeIndex(test.index).to_period('D')

# Defining and fitting the model with training data for endogenous and exogenous data
import statsmodels.api as sm

model=sm.tsa.statespace.SARIMAX(train['price'],
                                order=(0, 0, 0),
                                seasonal_order=(0, 0, 0,12), 
                                exog=train.iloc[:,1:],
                                time_varying_regression=True,
                                mle_regression=False)
model_1= model.fit(disp=False)

# Defining exogenous data for testing 
exog_test=test.iloc[:,1:]

# Forcasting out of sample data with exogenous data
forecast = model_1.forecast(3, exog=exog_test)

so my problem is really with the last line, what do I do if I want more than 3 steps?



from SARIMAX out of sample forecast with exogenous data

Thursday, 26 January 2023

Specifying complex truncated beta distribution

I'd like to specify a truncated beta distribution such that the support is [0.1, 0.4], and allow for the probability density at the lower bound to be higher than very near 0.

Here's what I have so far. I realize that the parameters I specify here may not give me the distribution exactly like I described, but I'm just trying to get a truncated beta distribution to work:

import numpy as np
import pandas as pd
import plotly.express as px
from scipy import stats

def get_ab(mean, stdev):
    kappa = (mean*(1-mean)/stdev**2 - 1)
    return mean*kappa, (1-mean)*kappa

class truncated_beta(stats.rv_continuous):
    def _pdf(self, x, alpha, beta, a, b):
        return stats.beta.pdf(x, alpha, beta) / (stats.beta.cdf(b, alpha, beta) - stats.beta.cdf(a, alpha, beta))
    def _cdf(self, x, alpha, beta, a, b):
        return (stats.beta.cdf(x, alpha, beta) - stats.beta.cdf(a, alpha, beta)) / (stats.beta.cdf(b, alpha, beta) - stats.beta.cdf(a, alpha, beta))
   
def plot_beta_distr(mu, stdev, lb, ub):
    alpha_, beta_ = get_ab((mu-lb)/ub, stdev/ub)

    dist = truncated_beta(a=lb, b=ub, alpha = alpha_, beta = beta_, name='truncated_beta')

    x = np.linspace(lb, ub, 100000)
    y = dist.pdf(x, alpha = alpha_, beta = beta_, a = lb, b = ub)

    fig = px.line(x = x, y = y)
    return fig

mu = 0.02
stdev = 0.005
lb = 0.1
ub = 0.4

plot_beta_distr(mu, stdev, lb, ub)

I get an error at the truncated_beta step:

TypeError: __init__() got an unexpected keyword argument 'alpha'

Update: The reason why the above doesn't work is very likely that I'm specifying a mu that's outside of my bounds.

Here is a simpler formulation that I generated from the advice on this post.

mean = .35
std = .1

lb = 0.1
ub = 0.5

def get_ab(mu, stdev):
    kappa = (mu*(1-mu)/stdev**2 - 1)
    return mu*kappa, (1-mu)*kappa

alpha_, beta_ = get_ab((mean - lb) / ub, std/ub)

norm = stats.beta.cdf(ub, alpha_, beta_) - stats.beta.cdf(lb, alpha_, beta_)

yr=stats.uniform.rvs(size=1000000)*norm+stats.beta.cdf(lb, alpha_, beta_)
xr=stats.beta.ppf(yr, alpha_, beta_)

xr.min()  # 0.100
xr.max()  # 0.4999
xr.std()  # 0.104
xr.mean() # 0.341

Everything lines up here except the mean is off. It's clear that I'm misspecifying something.



from Specifying complex truncated beta distribution

Request headers to scrape pypi.org

I am trying to screenscrape PyPI packages using the requests library and beautiful soup - but am met with an indefinite hang. I am able to retrieve html from a number of sites with:

session = requests.Session()
session.trust_env = False
response = session.get("http://google.com")
print(response.status_code)

i.e. without providing headers. I read from Python request.get fails to get an answer for a url I can open on my browser that the indefinite hang is likely caused by incorrect headers. So, using the developer tools, I tried to grab my request headers from the Networking tab (using Edge) with "Doc" filter to select the pypi.org response/request. I simply copy pasted these into my header variable that is passed to the get method:

headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9',
'cookie': 'session_id=<long string>',
'dnt': '1',
'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Microsoft Edge";v="108"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'none',
'sec-fetch-user': '?1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54'}

(and changing get method to response = session.get("http://pypi.org", headers=headers))

But I get the same hang. So, I think something is wrong with my headers but I'm not sure what. I'm aware that the requests Session() "handles" cookies so I tried removing the cookie key/value pair in my request header dictionary but achieved the same result.

How can I determine the problem with my headers and/or why do my current headers not work (assuming this is even the problem)?



from Request headers to scrape pypi.org

Delay between app process start and Application onCreate

I'm working on an application with large codebase. The problem is that when I launch the app from cold start state, It takes a lot of time to show the first screen of the app.
Based on here I checked the TTID for the app and it was terrifying:

Displayed com.example.myapp/.ui.MainActivity: +6s501ms

So I put some logs to check where is the problem:

class MyApp : Application() {
    override fun onCreate() {
        Log.d("Performance", "MyApp::onCreate::start")
        super.onCreate()
        // App initializations
        Log.d("Performance", "MyApp::onCreate::end")
    }
}

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        Log.d("Performance", "MainActivity::onCreate::start")
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // Ui initializations
        Log.d("Performance", "MainActivity::onCreate::end")
    }
}

After this I realized something strange:

---------------------------- PROCESS STARTED (4572) for package com.example.myapp ----------------------------
13:58:06.819 Performance    D  MyApp::onCreate::start
13:58:07.066 Performance    D  MyApp::onCreate::end
13:58:07.132 Performance    D  MainActivity::onCreate::start
13:58:07.566 Performance    D  MainActivity::onCreate::end

I noticed a strange thing. That there is a lot of delay (about 5 seconds) between PROCESS_START and App:onCreate (there isn't any timestamp for PROCESS_START but I calculated manually). Also app creation and activity creation does not take more than 1 second.
So how can I solve this problem? What can be the cause of this issue?



from Delay between app process start and Application onCreate

Flutter: File can not be deleted or can not change path of the file

I tried to change path of the internal storage file but it could not happen. Then I tried copy that file to another location and delete it from first location. unfortunately, this also did not work.

Here is my error:

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FileSystemException: Cannot delete file, path = '/storage/emulated/0/DCIM/Screenshots/Screenshot_20230116-114448.jpg' (OS Error: No such file or directory, errno = 2)

If anyone have idea then it could be helpful. Thank You.



from Flutter: File can not be deleted or can not change path of the file

HTTP Content-Security-Policy header not working correctly for script-src in Struts

I have a problem updating my version of struts struts2-core-2.5.30 project to struts2-core-6.1.1 so I began to receive an error indicating that the security policies have been violated, doing some research, I found that a header should be added

[Report Only] Refused to load the script '<URL>' because it violates the following Content Security Policy directive: "script-src 'nonce-MOz6w31eaDHGUDfV__K8LEZ1' 'strict-dynamic' http: https:". Note that 'strict-dynamic' is present, so host-based allowlisting is disabled. Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

and inside this error i have this description

[Report Only] Refused to load the script 'http://localhost:8080/Portal/html/js/jquery/jquery-1.8.3.min.js' because it violates the following Content Security Policy directive: "script-src 'nonce-MOz6w31eaDHGUDfV__K8LEZ1' 'strict-dynamic' http: https:". Note that 'strict-dynamic' is present, so host-based allowlisting is disabled. Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

[Report Only] Refused to load the script 'http://localhost:8080/Portal/html/js/jquery/jquery-ui.1.10.4.min.js' because it violates the following Content Security Policy directive: "script-src 'nonce-MOz6w31eaDHGUDfV__K8LEZ1' 'strict-dynamic' http: https:". Note that 'strict-dynamic' is present, so host-based allowlisting is disabled. Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

however I have tried these headers

<meta http-equiv="Content-Security-Policy" content="default-src 'self'">


<meta http-equiv="Content-Security-Policy" content="default-src *;
    style-src * 'unsafe-inline'; script-src * 'unsafe-inline'
    'unsafe-eval'; img-src * data: 'unsafe-inline'; connect-src *
    'unsafe-inline'; frame-src *;">

<meta http-equiv="Content-Security-Policy" content="default-src  'nonce-rAnd0m'">
<script src="${pageContext.request.contextPath}/html/js/jquery/jquery-1.8.3.min.js" type="text/javascript" nonce="rAnd0m123"></script> 

with each of them I get the same error, In my previous version of struts it did not ask me for any of this

have also tried to make an interceptor to add the corresponding directives, however it has not worked for me either.

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.StrutsStatics;


public class SessionInterceptor extends AbstractInterceptor{

   private static final long serialVersionUID = 1L;


   public String intercept(ActionInvocation invocation) throws Exception {
     
    ActionContext ac = invocation.getInvocationContext();
    HttpServletResponse response = (HttpServletResponse) ac.get(StrutsStatics.HTTP_RESPONSE);
    //HttpServletResponse response = ServletActionContext.getResponse();

    response.addHeader("X-Frame-Options", "SAMEORIGIN");
    response.addHeader("Content-Security-Policy-Report-Only", "default-src 'self'; script-src 'self' 'unsafe-inline'; object-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self'; media-src 'none'; frame-src 'none'; font-src 'self'; connect-src 'self'; report-uri REDACTED");
    response.addHeader("X-Content-Security-Policy-Report-Only", "default-src 'self'; script-src 'self' 'unsafe-inline'; object-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self'; media-src 'none'; frame-src 'none'; font-src 'self'; connect-src 'self'; report-uri REDACTED");
    return invocation.invoke();
}

}

In the same way I have updated the jquery-1.8.3 version as suggested in the comments but it has not worked for me either



from HTTP Content-Security-Policy header not working correctly for script-src in Struts

Wednesday, 25 January 2023

How to set Android Buttom sheet height match_parent?

I want to bottom dialog height expend to match_parent (as empty activity)
Here is my code.

MainActivity

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.google.android.material.bottomsheet.BottomSheetBehavior;

public class MainActivity extends AppCompatActivity {

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

        Button OpenBottomSheet = findViewById(R.id.open_bottom_sheet);

        OpenBottomSheet.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v)
                    {
                        BottomSheetDialog bottomSheet = new BottomSheetDialog();
                        bottomSheet.show(getSupportFragmentManager(),
                                "ModalBottomSheet");
                    }
        });
     }
}

BottomSheetDialog

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

public class BottomSheetDialog extends BottomSheetDialogFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable
    ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        View v = inflater.inflate(R.layout.buttom_sheet_layout,
                container, false);

        return v;
    }

}

Here is full code.



from How to set Android Buttom sheet height match_parent?

After performing t-SNE dimentionality reduction, use k-means and check what features contribute the most in each individual cluster

The following plot displays the t-SNE plot. I can show it here but unfortunately, I can't show you the labels. There are 4 different labels:

enter image description here

The plot was created using a data frame called scores, which contains approximately 1100 patient samples and 25 features represented by its columns. The labels for the plot were sourced from a separate data frame called metadata. The following code was used to generate the plot, utilizing the information from both scores and metadata data frames.

tsneres <- Rtsne(scores, dims = 2, perplexity = 6)
tsneres$Y = as.data.frame(tsneres$Y)
ggplot(tsneres$Y, aes(x = V1, y = V2, color = metadata$labels)) + 
  geom_point()

My mission:

I want to analyze the t-SNE plot and identify which features, or columns from the "scores" matrix, are most prevalent in each cluster. Specifically, I want to understand which features are most helpful in distinguishing between the different clusters present in the plot. Is it possible to use an alternative algorithm, such as PCA, that preserves the distances between data points in order to accomplish this task? perhaps it's even a better choice than t-SNE?

This is an example of scores, this is not the real data, but it's similar:

structure(list(Feature1 = c(0.1, 0.3, -0.2, -0.12, 0.17, -0.4, 
-0.21, -0.19, -0.69, 0.69), Feature2 = c(0.22, 0.42, 0.1, -0.83, 
0.75, -0.34, -0.25, -0.78, -0.68, 0.55), Feature3 = c(0.73, -0.2, 
0.8, -0.48, 0.56, -0.21, -0.26, -0.78, -0.67, 0.4), Feature4 = c(0.34, 
0.5, 0.9, -0.27, 0.64, -0.11, -0.41, -0.82, -0.4, -0.23), Feature5 = c(0.45, 
0.33, 0.9, 0.73, 0.65, -0.1, -0.28, -0.78, -0.633, 0.32)), class = "data.frame", row.names = c("Patient_A", 
"Patient_B", "Patient_C", "Patient_D", "Patient_E", "Patient_F", 
"Patient_G", "Patient_H", "Patient_I", "Patient_J"))

EDIT - PYTHON

I got to the same point python. I tried PCA at first but it produced very bad plots. So I first reduced dimensions using t-SNE, which produced much better results and clustered the data using k-means. I still got the same question as before, just now I don't mind using R or python.

This is the new plot:

enter image description here

And this is the code:

from sklearn.manifold import TSNE
tsne = TSNE(n_components=2, perplexity=30, learning_rate=200)
tsne_result = tsne.fit_transform(scores)

#create a dict to map the labels to colors
label_color_dict = {'label1':'blue', 'label2':'red', 'label3':'yellow', 'label4':'green'}

#create a list of colors based on the 'labels' column in metadata
colors = [label_color_dict[label] for label in metadata[['labels']]

plt.scatter(tsne_result[:, 0], tsne_result[:, 1], c=colors, s=50)
plt.scatter(cluster_centers[:, 0], cluster_centers[:, 1], c='red', marker='o')

# Add labels to the cluster centers
for i, center in enumerate(cluster_centers,1):
    plt.annotate(f"Cluster {i}", (center[0], center[1]), 
                 textcoords="offset points", 
                 xytext=(0,10), ha='center', fontsize=20)


from After performing t-SNE dimentionality reduction, use k-means and check what features contribute the most in each individual cluster

Import Android project into a Flutter package

I am developing a Flutter app that uses my own fork of a Flutter package called vocsy_epub_viewer (https://github.com/vongrad/vocsy_epub_viewer) as I need to make some changes in it.

I have included the plugin in pubspec.yaml and this part is working well:

dev_dependencies:
  vocsy_epub_viewer:
    path: dependencies/vocsy_epub_viewer

The vocsy_epub_viewer package contains a Flutter plugin acting as a bridge to call some platform specific code - for Android it is using vocsy_epub_viewer_android_folioreader. I have made a fork of this Android package as well (https://github.com/vongrad/vocsy_epub_viewer_android_folioreader) since I need to make changes in it.

In the Flutter package's dependencies/vocsy_epub_viewer/android/build.gradle file, the Android package was referenced as:

dependencies {
    implementation 'com.github.kaushikgodhani:vocsy_epub_viewer_android_folioreader:V3'
}

I however need to make it such that it is referenced from a local folder where it was cloned (./vocsy_epub_viewer_android_folioreader).

The project structure looks as following:

flutter project root
    dependencies
        vocsy_epub_viewer
            android
                settings.gradle
                build.gradle
                
    android
        settings.gradle
        build.gradle
    ios
    lib
    ...
    
vocsy_epub_viewer_android_folioreader  <--- this plugin needs to be included within vocsy_epub_viewer/android
    folioreader
        settings.gradle
        build.gradle
    settings.gradle
    build.gradle

I have tried to include it as following:

dependencies/vocsy_epub_viewer/android/settings.gradle

include ':folioreader'
project(':folioreader').projectDir = file('C:\\Users\\test\\Documents\\Projects\\vocsy_epub_viewer_android_folioreader')

dependencies/vocsy_epub_viewer/android/build.gradle

dependencies {
    implementation "com.folioreader:folioreader" <-- attempt to import the package from a local folder
    // implementation 'com.github.kaushikgodhani:vocsy_epub_viewer_android_folioreader:V3' <-- original import
}

But it does not seem to work. I would greatly appreciate if I could get an advice as of how to do this.



from Import Android project into a Flutter package

Calculate height of element using JS listener

I've working on an Apple style image sequence scroller from codepen: https://codepen.io/jasprit-singh/pen/LYxzQjB

I want the JS to base the scroll height on a a div that is parent to the canvas, so that I can have content before and after this section without it functioning before it is in the viewport.

I think that const html = document.documentElement; is the issue as it is reading the full contents of <html> rather than the parent div I want to select. However, I don't understand how to change it.

I've tried replacing const html = document.documentElement; with const html = document.getElementById("wrap1"); but this just stop everything working with no console errors.

What am I doing wrong/ What do I need to change?

Thanks in advance!

const html = document.documentElement;

const canvas = document.getElementById("hero-lightpass");
const context = canvas.getContext("2d");

const frameCount = 148;

const currentFrame = index =>
  (`https://www.apple.com/105/media/us/airpods-pro/2019/1299e2f5_9206_4470_b28e_08307a42f19b/anim/sequence/large/01-hero-lightpass/${index.toString().padStart(4, '0')}.jpg`);

const preloadImages = () => {
  for (let i = 1; i < frameCount; i++) {
    const img = new Image();
    img.src = currentFrame(i);
  }
};
const img = new Image();
img.src = currentFrame(1);

canvas.width = 1158;
canvas.height = 770;

img.onload = function() {
  context.drawImage(img, 0, 0);
};
const updateImage = index => {
  img.src = currentFrame(index);
  context.drawImage(img, 0, 0);
}

window.addEventListener('scroll', () => {
  const scrollTop = html.scrollTop;
  const maxScrollTop = html.scrollHeight - window.innerHeight;

  const scrollFraction = scrollTop / maxScrollTop;
  const frameIndex = Math.min(frameCount - 1, Math.ceil(scrollFraction * frameCount));

  requestAnimationFrame(() => updateImage(frameIndex + 1));
});
preloadImages();
#wrap1 {
  position: relative;
  z-index: 1;

  margin: 0;
  padding: 0;

  background: #000;
}

#wrap {
  height: 500vh;
}

canvas {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  max-width: 100vw;
  max-height: 100vh;

  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="wrap1" id="wrap1">
  <div class="wrap" id="wrap">
    <canvas id="hero-lightpass"></canvas>
  </div>
</div>


from Calculate height of element using JS listener

Error with websocket connection when trying to add dependencies

I am currently trying to add charts for the graphical part with React in an Electron software. Except that I added interactions with buttons (sections) to insert different data in the graphs depending on the click on one of the sections by the user (variable selectedSection). So I added in the dependencies of the useEffect() function the chartPMS and chartPFS functions to have access at the selectedSection variable.

The useEffect() function receives data continuously through a websocket from a python program. The problem is that when I run the code via the npm start command, I get a data display with a very high frequency and this error continuously in the console : WebSocket connection to 'ws:<URL>/' failed: WebSocket is closed before the connection is established. But the functions did receive changes to the selectedSection variable based on clicks on the different sections.

I should point out that I used the useEffect() function in this way before, it worked but I didn't have access to the updated version after clicking on one of the sections of the selectedSection variable:

  useEffect(() => {
    const socket = new WebSocket('ws://localhost:8000');

    socket.addEventListener('message', (event) => {
      setData(JSON.parse(event.data));

      chartPFS(JSON.parse(event.data));
      chartPMS(JSON.parse(event.data));
    });

  }, []);

I added selectedSection to the dependencies except that it refreshes both panels after clicking on one of the section buttons.

Here are the code:

App.js with 2 panels :

import React, { useState, useEffect, useRef, useSyncExternalStore } from 'react';
import Modal from './Modal/Modal'
import {Chart as ChartJS,LinearScale,PointElement,LineElement,Tooltip,Legend,Title,CategoryScale,elements} from 'chart.js';
import {Scatter, Line } from 'react-chartjs-2';
import { handleDataClick } from './Modal/Modal';
import { LineChart } from 'recharts';
import 'chart.js/auto';

ChartJS.register(
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Tooltip,
    Legend,
    Title);

//--------------------------- OPTIONS GRAPHIQUE ----------------------------------//

  export const options5 = {
    elements: {
      line: {
          tension: 0.3,
      },
    },
    responsive: true,
    maintainAspectRatio:false,
    plugins: {
      showLine:true,
      legend: false
    },
  };

//--------------------------- FUNCTION APP() ----------------------------------//
export default function App() {
  let da;
  const [data, setData] = useState(null);
  const [show,setShow] = useState(false);
  const [lastSelectedSection, setLastSelectedSection] = useState(null);
  const h2f5Ref = useRef(null);
  const h2f4Ref = useRef(null);
  const h2f3Ref = useRef(null);
  const h2f2Ref = useRef(null);
  const h2f1Ref = useRef(null);

  const h2m5Ref = useRef(null);
  const h2m4Ref = useRef(null);
  const h2m3Ref = useRef(null);
  const h2m2Ref = useRef(null);
  const h2m1Ref = useRef(null);

  const [selectedDataType, setSelectedDataType] = useState({id:"fs-sec-1",selected:"twist"});
  const [sectionData, setSectionData] = useState({
    "fs-sec-1": { selectedDataType: 'twist' },
    "fs-sec-2": { selectedDataType: 'twist' },
    "fs-sec-3": { selectedDataType: 'twist' },
    "fs-sec-4": { selectedDataType: 'twist' },
    "fs-sec-5": { selectedDataType: 'twist' },
    "ms-sec-1": { selectedDataType: 'twist' },
    "ms-sec-2": { selectedDataType: 'twist' },
    "ms-sec-3": { selectedDataType: 'twist' },
    "ms-sec-4": { selectedDataType: 'twist' },
    "ms-sec-5": { selectedDataType: 'twist' }
  });

  const [selectedSection, setSelectedSection] = useState("s1");
  const [selectedSailP3,setSelectedSailP3]=useState("fs");

  //----------------------- Graphiques Variables initiales  -------------------//


    const [chartDataPFS,setChartDataPFS]=useState({
      datasets: [
          {
              label: 'Draft',
              showLine:true,
              data: [{x:3,y:1},{x:3.5,y:2},{x:5.5,y:3},{x:5.25,y:4},{x:5,y:5}],
              backgroundColor: '#df9305',
              borderColor: '#df9305'
          }]
    });
    const [chartDataPMS,setChartDataPMS]=useState({
      labels:["0","1","2","3","4"],
      datasets: [
          {
              label: 'Draft',
              showLine:true,
              data: [0,2,3,2,0],
              backgroundColor: '#df9305',
              borderColor: '#df9305'
          }]
    });
 
    //----------------------- Graphiques Fonctions mise à jour  -------------------//
  const chartPFS=(d) =>{
    let dataToUse;
    console.log(selectedSection)
    dataToUse=[{x:0,y:0},
      {x:3.3/2,y:d["fs"][selectedSection]["camber"]*0.75},
      {x:3.3,y:d["fs"][selectedSection]["draft"]},
      {x:(10-3.3)/2+3.3,y:d["fs"][selectedSection]["draft"]*0.55},
      {x:10,y:0}];
    setChartDataPFS({
        datasets: [
            {
              label: 'Profile',
              showLine:true,
              maintainAspectRatio:false,
              fill:false,
              data: dataToUse,
              backgroundColor: '#000000',
              borderColor: '#000000'
            }]
    });
  };
  const chartPMS=(d) =>{
    let dataToUse;
    dataToUse=[0,
      d["ms"][selectedSection]["camber"],
      d["ms"][selectedSection]["draft"],
      d["ms"][selectedSection]["draft"],
      0];
    setChartDataPMS({
        labels:[0,1,2,3,4],
        datasets: [
            {
              label: 'Profile',
              maintainAspectRatio:false,
              fill:false,
              data: dataToUse,
              borderColor: '#000000'
            }]
    });
  };

  //----------------------- Fonctions Récupération données au clic  -------------------//

  const handleClick = (id,h2Text) => {
    const sectionId = id;
    setSelectedDataType({id:sectionId,selected:h2Text});
  };
  const handleSectionClick=(section) =>{
    setSelectedSection(section);
  };
  const handleSailP3Click=(sail) =>{
    setSelectedSailP3(sail);
  };

    //----------------------- Mise à jour données  -------------------//
    useEffect(() => {
      const socket = new WebSocket('ws://localhost:8000');

      const handler = (event) => {

        setData(JSON.parse(event.data));
        chart1(JSON.parse(event.data));
        chart2(JSON.parse(event.data));
        chart3(JSON.parse(event.data));
        chart4(JSON.parse(event.data));
        chartPFS(JSON.parse(event.data));
        chartPMS(JSON.parse(event.data));
      };

      socket.addEventListener('message', handler);

      return () => {
        socket.removeEventListener('message', handler);
        socket.close();
      };
    }, [selectedSection]);
  
  
  return (
        <div>
            <div className="home">
                <div className="template-1" id="temp1">
                <div className="panel-1">
                    <div className="panel-header">
                    <h1>FORESAIL data</h1>
                    <i className='bx bx-cog modal-trigger-panel'></i>
                    </div>
                    <div className="panel-body">
                    <div className="sec-5 modal-trigger-data" id="fs-sec-5" onClick={()=>{handleClick("fs-sec-5",h2f5Ref.current.textContent);setShow(true);}} >
                        {data && sectionData["fs-sec-5"].selectedDataType ? <span class="h1" id="h1-fs-s5">{data["fs"]["s5"][sectionData["fs-sec-5"].selectedDataType]}</span> : <span class="h1" id="h1-fs-s5">--</span>}
                        <h2 ref={h2f5Ref}>{sectionData["fs-sec-5"].selectedDataType ? sectionData["fs-sec-5"].selectedDataType.toUpperCase() : "TWIST"}</h2>
                        <h3>s5</h3>
                    </div>
                    <div className="sec-4 modal-trigger-data" id="fs-sec-4" onClick={()=>{handleClick("fs-sec-4",h2f4Ref.current.textContent);setShow(true);}}>
                        {data && sectionData["fs-sec-4"].selectedDataType ? <span class="h1" id="h1-fs-s4">{data["fs"]["s4"][sectionData["fs-sec-4"].selectedDataType]}</span> : <span class="h1" id="h1-fs-s4">--</span>}
                        <h2 ref={h2f4Ref}>{sectionData["fs-sec-4"].selectedDataType ? sectionData["fs-sec-4"].selectedDataType.toUpperCase() : "TWIST"}</h2>
                        <h3>s4</h3>
                    </div>
                    <div className="sec-3 modal-trigger-data" id="fs-sec-3" onClick={()=>{handleClick("fs-sec-3",h2f3Ref.current.textContent);setShow(true);}}>
                        {data && sectionData["fs-sec-3"].selectedDataType ? <span class="h1" id="h1-fs-s3">{data["fs"]["s3"][sectionData["fs-sec-3"].selectedDataType]}</span> : <span class="h1" id="h1-fs-s3">--</span>}
                        <h2 ref={h2f3Ref}>{sectionData["fs-sec-3"].selectedDataType ? sectionData["fs-sec-3"].selectedDataType.toUpperCase() : "TWIST"}</h2>
                        <h3>s3</h3>
                    </div>
                    <div className="sec-2 modal-trigger-data" id="fs-sec-2" onClick={()=>{handleClick("fs-sec-2",h2f2Ref.current.textContent);setShow(true);}}>
                        {data && sectionData["fs-sec-2"].selectedDataType ? <span class="h1" id="h1-fs-s2">{data["fs"]["s2"][sectionData["fs-sec-2"].selectedDataType]}</span> : <span class="h1" id="h1-fs-s2">--</span>}
                        <h2 ref={h2f2Ref}>{sectionData["fs-sec-2"].selectedDataType ? sectionData["fs-sec-2"].selectedDataType.toUpperCase() : "TWIST"}</h2>
                        <h3>s2</h3>
                    </div>
                    <div className="sec-1 modal-trigger-data" id="fs-sec-1" onClick={()=>{handleClick("fs-sec-1",h2f1Ref.current.textContent);setShow(true);}}>
                        {data && sectionData["fs-sec-1"].selectedDataType ? <span class="h1" id="h1-fs-s1">{data["fs"]["s1"][sectionData["fs-sec-1"].selectedDataType]}</span> : <span class="h1" id="h1-fs-s1">--</span>}
                        <h2 ref={h2f1Ref}>{sectionData["fs-sec-1"].selectedDataType ? sectionData["fs-sec-1"].selectedDataType.toUpperCase() : "TWIST"}</h2>
                        <h3>s1</h3>
                    </div>
                    </div>
                </div>
                <div class="panel-5">
                    <div class="panel-header">
                        <h1>SAILS sections</h1>
                        <i class='bx bx-cog modal-trigger-panel'></i>
                    </div>
                    <div class="panel-body">
                        <div class="profil-container" style=>
                            <div style=>
                                <Scatter options={options5} data={chartDataPFS}/>
                            </div>
                            <div style=>
                                <Line options={options5} data={chartDataPMS}/>
                            </div>
                        </div>
                        <div class="button-sec">
                            <input type="submit" value="Section 5" class={`section5 ${selectedSection === "s5" ? 'active' : ''}`} onClick={()=>{handleSectionClick("s5")}}/>
                            <input type="submit" value="Section 4" class={`section4 ${selectedSection === "s4" ? 'active' : ''}`} onClick={()=>{handleSectionClick("s4")}}/>
                            <input type="submit" value="Section 3" class={`section3 ${selectedSection === "s3" ? 'active' : ''}`} onClick={()=>{handleSectionClick("s3")}}/>
                            <input type="submit" value="Section 2" class={`section2 ${selectedSection === "s2" ? 'active' : ''}`} onClick={()=>{handleSectionClick("s2")}}/>
                            <input type="submit" value="Section 1" class={`section1 ${selectedSection === "s1" ? 'active' : ''}`} onClick={()=>{handleSectionClick("s1")}}/>
                        </div>
                        <div class="button-sail">
                            <input type="submit" value="Foresail" class="btn-hs modal-trigger-hs"/>
                            <input type="submit" value="Mainsail" class="btn-ms modal-trigger-ms"/>                            
                        </div>
                    </div>
                </div>
                </div>
                <Modal onClose={() => setShow(false)} show={show} Data={selectedDataType} sectionData={sectionData} setSectionData={setSectionData}/>
            </div>
        </div> 
  );
}

Python :

import asyncio
import random
import datetime
import websockets
import json

sv={"fs":{
    "s5":{"entry":2,"cfwd":3,"camber":2,"draft":3,"caft":5,"exit":5,"twist":15,"saglat":10,"saglong":10},
    "s4":{"entry":2,"cfwd":3,"camber":2,"draft":3,"caft":5,"exit":5,"twist":15,"saglat":10,"saglong":10},
    "s3":{"entry":2,"cfwd":3,"camber":2,"draft":3,"caft":5,"exit":5,"twist":15,"saglat":10,"saglong":10},
    "s2":{"entry":2,"cfwd":3,"camber":2,"draft":3,"caft":5,"exit":5,"twist":15,"saglat":10,"saglong":10},
    "s1":{"entry":2,"cfwd":3,"camber":2,"draft":3,"caft":5,"exit":5,"twist":15,"saglat":10,"saglong":10},
    },
    "ms":{
    "s5":{"entry":2,"cfwd":3,"camber":2,"draft":3,"caft":5,"exit":5,"twist":15,"saglat":10,"saglong":10},
    "s4":{"entry":2,"cfwd":3,"camber":2,"draft":3,"caft":5,"exit":5,"twist":15,"saglat":10,"saglong":10},
    "s3":{"entry":2,"cfwd":3,"camber":2,"draft":3,"caft":5,"exit":5,"twist":15,"saglat":10,"saglong":10},
    "s2":{"entry":2,"cfwd":3,"camber":2,"draft":3,"caft":5,"exit":5,"twist":15,"saglat":10,"saglong":10},
    "s1":{"entry":2,"cfwd":3,"camber":2,"draft":3,"caft":5,"exit":5,"twist":15,"saglat":10,"saglong":10},    
    }}

async def handler(websocket, path):
    while True:
        #log_decoder()
        for key1 in sv:
            for key2 in sv[key1]:
                sv[key1][key2]["entry"] = random.randint(1, 10)
                sv[key1][key2]["cfwd"] = random.randint(1, 10)
                sv[key1][key2]["camber"] = random.randint(1, 10)
                sv[key1][key2]["draft"] = random.randint(1, 4)
                sv[key1][key2]["caft"] = random.randint(1, 10)
                sv[key1][key2]["exit"] = random.randint(1, 10)
                sv[key1][key2]["twist"] = random.randint(1, 10)
                sv[key1][key2]["saglat"] = random.randint(1, 10)
                sv[key1][key2]["saglong"] = random.randint(1, 10)        
        #data = [random.randint(0, 20) for _ in range(10)]
        await websocket.send(json.dumps(sv))
        await asyncio.sleep(1)

start_server = websockets.serve(handler, "localhost", 8000)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Regards,



from Error with websocket connection when trying to add dependencies