2022-03-31

How to write firestore rules with session cookies for authentication

I have used this https://firebase.google.com/docs/auth/admin/manage-cookies to implement session cookies into my next.js application.

Having no client user authentication, I assume I have to handle all my firestore calls and permissions inside my server-side api; which begs the question. What use do I have of the firestore rules? Is that just obsolete?

I'm asking because I don't see a way to authenticate anything with the rules - seeing as the request.auth will always be null? I'm pretty sure I'm getting something wrong here since on that doc for session cookies I see no mention that that will basically invalidate the .rules, yet I'm struggling to implement them.



How to exclude or hide the subfolder name in the URL when you open a webpage using PHP?

I have a website that has an example URL like localhost/projects/mysite/app/index.php, my objective is to exclude the folder name "app" when I open it, and instead, it shows only localhost/projects/mysite/index.php. What is the best way to exclude or hide the sub-folders and show directly the webpage in the address bar/URL?

I tried to remove .php in the URL and it succeed. However, I can't find a way to exclude the folder name. Also, here are the steps I have done so far:

enter image description here



Bad return type in lambda expression when using Java's Optional.or() with subclasses

I am trying to use Optional.or to get an object of subclass A or, if empty, an object of subclass B:

interface Node {}
class InnerNode implements Node {}
class LeafNode implements Node {}
Optional<InnerNode> createInnerNode() {}
Optional<LeafNode> createLeafNode() {}

Optional<Node> node = createInnerNode().or(() -> createLeafNode());

When doing this, I get the following compiler error:

Bad return type in lambda expression: Optional<LeafNode> cannot be converted to Optional<? extends InnerNode>

If I instead use wildcards to explicitly tell the compiler that the Optionals contain an object extending from Node:

Optional<? extends Node> optionalInner = createInnerNode();
Optional<? extends Node> optionalLeaf = createLeafNode();
Optional<Node> node = optionalInner.or(() -> optionalLeaf);

I get the following compiler error:

Bad return type in lambda expression: Optional<capture of ? extends Node> cannot be converted to Optional<? extends capture of ? extends Node>

The only way I found to make this work, is using an Optional.empty in front:

Optional<Node> node = Optional.<Node>empty() // requires generic argument
    .or(() -> createInnerNode())
    .or(() -> createLeafNode());

But for me, this is confusing to read. Is it somehow possible to instruct the compiler to allow the statement optionalInner.or(() -> optionalLeaf)? Or are there other alternatives to make this work?



Chainlink job is not being called by the Solidity Smart Contract using Operator.sol contract

The job spec deployed and running on Chainlink node is being successfully triggered and completed when called using the Solidity smart contract that is using the Oracle.sol contract.

But, since the requirement is to return the large response (https://docs.chain.link/docs/large-responses/), so I have to use Operator.sol contract instead of Oracle.sol. Then, the job is not being called.

The deployed Operator contract is looking as:

Deployed Operator.sol


The LINK Token and Owner addresses that I have used to deploy the Operator.sol contract are:

LINK and Owner addresses


The LINK Token address is basically taken from the official Chainlink doc (https://docs.chain.link/docs/fulfilling-requests/) mentioning the Kovan Testnet LINK token address:

LINK Token address


And the owner address is taken from the Account address of the running Chainlink node:

Owner address


And the Solidity smart contract code is:

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";

contract GenericLargeResponse is ChainlinkClient {
  using Chainlink for Chainlink.Request;

  bytes public data;

  constructor(
  ) {
    setChainlinkToken(0xa36085F69e2889c224210F603D836748e7dC0088);
    setChainlinkOracle(0x8114f13FaF377FFc7A5AD32fb8a1e448667b871D);
  }

  function requestBytes(
  )
    public
  {
    bytes32 specId = "a3d1b2c945244e44bdb412c5b5287df3";
    uint256 payment = 100000000000000000;
    Chainlink.Request memory req = buildChainlinkRequest(specId, address(this), this.fulfillBytes.selector);
    req.add("data", "{\"agg_x\": \"agg_mean\", \"dataset_code\":\"MODIS/006/MOD14A1\", \"selected_band\":\"MaxFRP\", \"image_scale\":1000, \"start_date\":\"2021-09-01\", \"end_date\":\"2021-09-10\", \"geometry\":{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"properties\":{\"id\":1},\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[29.53125,19.642587534013032],[29.53125,27.059125784374068],[39.90234375,27.059125784374068],[39.90234375,19.642587534013032],[29.53125,19.642587534013032]]]}},{\"type\":\"Feature\",\"properties\":{\"id\":2},\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[46.40625,13.752724664396988],[46.40625,20.138470312451155],[56.25,20.138470312451155],[56.25,13.752724664396988],[46.40625,13.752724664396988]]]}}]}}");
       
    sendOperatorRequest(req, payment);
  }

  function fulfillBytes(
    bytes32 requestId,
    bytes memory bytesData
  )
    public
    recordChainlinkFulfillment(requestId)
  {
    data = bytesData;
  }

}

The contract is compiled and deployed successfully. But the requestBytes function is unable to trigger the job-spec running on the Chainlink node.

PS: The function of the similar smart contract that is using the Oracle.sol is successfully triggering the job-spec.


The TOML Job spec running on Chainlink node is:

type = "directrequest"
schemaVersion = 1
name = "shamba-fire-data"
contractAddress = "0x8114f13FaF377FFc7A5AD32fb8a1e448667b871D"
maxTaskDuration = "0s"
observationSource = """
    decode_log   [type="ethabidecodelog"
                  abi="OracleRequest(bytes32 indexed specId, address requester, bytes32 requestId, uint256 payment, address callbackAddr, bytes4 callbackFunctionId, uint256 cancelExpiration, uint256 dataVersion, bytes data)"
                  data="$(jobRun.logData)"
                  topics="$(jobRun.logTopics)"]

    decode_cbor  [type="cborparse" data="$(decode_log.data)"]
    fetch        [type="bridge" name="shamba-fire-bridge" requestData="{\\"id\\": $(jobSpec.externalJobID), \\"data\\":$(decode_cbor.data)}"]
    parse        [type="jsonparse" path="result,1,0" data="$(fetch)"]
    encode_data  [type="ethabiencode" abi="(uint256 value)" data="{ \\"value\\": $(parse) }"]
    encode_tx    [type="ethabiencode"
                  abi="fulfillOracleRequest2(bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes calldata data)"
                  data="{\\"requestId\\": $(decode_log.requestId), \\"payment\\": $(decode_log.payment), \\"callbackAddress\\": $(decode_log.callbackAddr), \\"callbackFunctionId\\": $(decode_log.callbackFunctionId), \\"expiration\\": $(decode_log.cancelExpiration), \\"data\\": $(encode_data)}"
                 ]
    submit_tx    [type="ethtx" to="0x8114f13FaF377FFc7A5AD32fb8a1e448667b871D" data="$(encode_tx)"]

    decode_log -> decode_cbor -> fetch -> parse -> encode_data -> encode_tx -> submit_tx
"""
externalJobID = "a3d1b2c9-4524-4e44-bdb4-12c5b5287df3"

Can anyone please point me in the right direction, like what I'm doing wrong in these steps due to which the smart contract is unable to trigger the job-spec ?



VB.NET Copying myself and then run the copy fails

I'm trying to make it possible to run my project, copy itself to update.exe and then run that update.exe for the purpose of testing the update routine.

The problem I'm having is that the exefile is copied succesfully but when update.exe is then starts, it just always crashes.

If I abort the update.exe program from the crash, but my main exe still runs, I can then just start update.exe from explorer and all works fine. I can't for life figure out why update.exe crashes if it is started after it was copied from another exefile.

Here's the code:

Public Class Updater
    Public sFullname As String
    Public sExename As String
    Public sArguments As String

    Public Sub New()
        'Constructor

        Me.Initiate()
        Me.FakeUpdate()
        Me.DoUpdate()

        'MsgBox(Me.sFullname)

    End Sub

    Private Sub Initiate()
        Dim sCmdLine As String = Environment.CommandLine()
        Dim iPos = sCmdLine.IndexOf("""", 2)
        Me.sFullname = sCmdLine.Substring(1, iPos - 1).Trim()
        Dim iPos2 = sFullname.LastIndexOf("\")
        Me.sExename = sFullname.Substring(iPos2 + 1).Trim()
        Me.sArguments = sCmdLine.Substring(iPos + 1).Trim()

    End Sub

    Private Sub FakeUpdate()
        'If we start the app with -fakeupdate parameter, copy myself to update.exe, then run update.exe to debug the update process.
        If Me.sArguments = "-fakeupdate" Then
            FileCopy(Me.sFullname, "update.exe")
            Shell("update.exe")
        End If
    End Sub

    Private Sub DoUpdate()
        If Me.sExename = "update.exe" Then
            MsgBox("DoUpdate called from update.exe")
        End If
    End Sub
End Class

Public Class Form1
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim Updater As New Updater
    End Sub
End Class

The project is configured that it runs with parameter -fakeupdate

The code is part of a larger project, but I have commented out all other code and still receive this error.

The error I'm getting from update.exe: Length cannot be less than null. Parametername: length

System.ArgumentOutOfRangeException: Length cannot be less than null.
Parameternaam: length
   bij System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy)
   bij Todo_List.Updater.Initiate() in S:\VB Projects\Todo List\Todo List\Form1.vb:regel 19
   bij Todo_List.Updater..ctor() in S:\VB Projects\Todo List\Todo List\Form1.vb:regel 8
   bij Todo_List.Form1.Form1_Load(Object sender, EventArgs e) in S:\VB Projects\Todo List\Todo List\Form1.vb:regel 594
   bij System.EventHandler.Invoke(Object sender, EventArgs e)
   bij System.Windows.Forms.Form.OnLoad(EventArgs e)
   bij System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   bij System.Windows.Forms.Control.CreateControl()
   bij System.Windows.Forms.Control.WmShowWindow(Message& m)
   bij System.Windows.Forms.Control.WndProc(Message& m)
   bij System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   bij System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

EDIT: small update, it also goes wrong if I don't even copy the file. Just shell("update.exe") goes wrong. I even created a button on the form to launch it upon click and it fails every time. But if I run it from explorer, all is fine.



How do I assign comma separated values from an Inputbox to variables in VBA?

The code is to assign values in the array created by the inputbox into variables created based on the number of comma-separated values in the array. i.e. if 5 comma-separated values (1,2,3,4,5) are entered in the Inputbox the code create 5 variables input1, input2 etc. and assign values from the input.

I have tried the following code and it is returning a "subscript out of range" error at input(v) = u

Sub test3()
    Dim strEntries As String, v As Long, item As Variant, inputArray() As String, u As Variant, input() As String
    strEntries = Application.InputBox("Enter multiple comma separated values. ", "Entries", Type:=2)
    If strEntries = "False" Then Exit Sub   'User canceled
    v = 0
    inputArray = Split(strEntries, ",")
    For Each u In inputArray
        Debug.Print u
        For v = LBound(inputArray) To UBound(inputArray)
            input(v) = u
            Next v
        v = v + 1
        Debug.Print "count =" & v
        
    Next u
End Sub


2022-03-30

Is there a way for Vim to define keywords defined by regular expressions?

I would like to have Vim treat as keywords strings that match:

( "(" <scope> ")" [:_/] ){0,1} <name>

where:

<scope> = [@+-.] ( ":" <name> )*
<name>  = [a-zA-Z][a-zA-Z0-9_]*

A regex to describe this definition of a keyword might be something like:

\(([@_-.]\(:[a-zA-Z][a-zA-Z0-9_]*\)*)\){0,1}[a-zA-Z][a-zA-Z0-9_]*

Some concrete examples:

(@:a):f
(+:b:c)_v
(-)/p
n

Using Vim's set iskeyword does not appear to be able to handle regular expressions.

I've considered expressions such as:

let @/ =~ '\<'.expand('<cword>').'\>

but <cword> doesn't seem up to this task as well.

The use case for this is keying in * to search for words matching the regex that are under the cursor.

I've also considered whether \%# might be part of the solution; however, that seems to require splitting the regex into pre- and post-parts.

Is there a way for Vim to define keywords with regular expressions for use in initiating searches under the cursor, then using n and p to find next and previous matches? Solutions do not necessarily need to involve iskeyword. I'm suspecting that using @/ is part of the solution. Your thoughts?



How can I scrape the content of a news, based on its title?

I have a Listbox where the titles and news time are scraped from 2 links and printed in the Listbox after clicking on the "View Title" button. This works correctly. All ok!

enter image description here

Now I would like to select the newspaper title from the Listbox, click on the "View Content" button, and view the news content in a multiline textbox. So I would like to view the content of the news of the selected title in the textbox below. I specify that the title is the same as the link of the news content. But I have a problem with the function to build this:

def content():
    if title.select:

        #click on title-link
        driver.find_element_by_tag_name("title").click()

        #Download Content to class for every title
        content_download =(" ".join([span.text for span in div.select("text mbottom")]))

        #Print Content in textobox
        textbox_download.insert(tk.END, content_download)

So I imagined that to get this, we would have to simulate clicking on the title of the news to open it (in html it is title), then select the text of the content (in html it is text mbottom) and then copy it in the tetbox of my file. It should be so? What are you saying? Obviously I have poorly written the code and it doesn't work. I'm not very good at scraping. Could anyone help me? Thank you

The complete code is this (is executable correctly and scrapes titles and now. I don't call the content function in the button). Aside from the above function, the code is working good and fetches the title and news time

from tkinter import *
from tkinter import ttk
import tkinter as tk
import sqlite3
import random
import tkinter.font as tkFont
from tkinter import ttk

window=Tk()
window.title("x")
window.geometry("800x800")

textbox_title = tk.Listbox(window, width=80, height=16, font=('helvetic', 12), selectbackground="#960000", selectforeground="white", bg="white") #prima era self.tutti_pronostici, per far visualizzare le chiamate dall'altra finestra
textbox_title.place(x=1, y=1)

textbox_download = tk.Listbox(window, width=80, height=15, font=('helvetic', 12), selectbackground="#960000", selectforeground="white", bg="white") #prima era self.tutti_pronostici, per far visualizzare le chiamate dall'altra finestra
textbox_download.place(x=1, y=340)

#Download All Titles and Time
def all_titles():

    allnews = []

    import requests
    from bs4 import BeautifulSoup

    # mock browser request
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
    }


    #ATALANTA
    site_atalanta = requests.get('https://www.tuttomercatoweb.com/atalanta/', headers=headers)
    soup = BeautifulSoup(site_atalanta.content, 'html.parser')

    news = soup.find_all('div', attrs={"class": "tcc-list-news"})

    for each in news:
        for div in each.find_all("div"):
            time= (div.find('span', attrs={'class': 'hh serif'}).text)
            title=(" ".join([span.text for span in div.select("a > span")]))

            news = (f" {time} {'ATALANTA'}, {title} (TMW)")
            allnews.append(news)        


    #BOLOGNA
    site_bologna = requests.get('https://www.tuttomercatoweb.com/bologna/', headers=headers)
    soup = BeautifulSoup(site_bologna.content, 'html.parser')

    news = soup.find_all('div', attrs={"class": "tcc-list-news"})

    for each in news:
        for div in each.find_all("div"):
            time= (div.find('span', attrs={'class': 'hh serif'}).text)
            title=(" ".join([span.text for span in div.select("a > span")]))

            news = (f" {time} {'BOLOGNA'}, {title} (TMW)")
            allnews.append(news)           
                            

    allnews.sort(reverse=True)

    for news in allnews:
        textbox_title.insert(tk.END, news)

#Download Content of News
def content():
    if titolo.select:

        #click on title-link
        driver.find_element_by_tag_name("title").click()

        #Download Content to class for every title
        content_download =(" ".join([span.text for span in div.select("text mbottom")]))

        #Print Content in textobox
        textbox_download.insert(tk.END, content_download)



button = tk.Button(window, text="View Titles", command= lambda: [all_titles()])
button.place(x=1, y=680)

button2 = tk.Button(window, text="View Content", command= lambda: [content()])
button2.place(x=150, y=680)

window.mainloop()


Spark Query using Inner join instead of full join

can anyone explain the below behaviour in spark sql join. It does not matter whether I am using full_join/full_outer/left/left_outer, the physical plan always shows that Inner join is being used..

q1 = spark.sql("select count(*) from table_t1 t1 full join table_t1 t2 on t1.anchor_page_id = t2.anchor_page_id and t1.item_id = t2.item_id and t1.store_id = t2.store_id where t1.date_id = '20220323' and t2.date_id = '20220324'")
q1.explain()

== Physical Plan ==
*(6) HashAggregate(keys=[], functions=[count(1)])
+- Exchange SinglePartition
   +- *(5) HashAggregate(keys=[], functions=[partial_count(1)])
      +- *(5) Project
         +- *(5) SortMergeJoin [anchor_page_id#1, item_id#2, store_id#5], [anchor_page_id#19, item_id#20, store_id#23], Inner
            :- *(2) Sort [anchor_page_id#1 ASC NULLS FIRST, item_id#2 ASC NULLS FIRST, store_id#5 ASC NULLS FIRST], false, 0
            :  +- Exchange hashpartitioning(anchor_page_id#1, item_id#2, store_id#5, 200)
            :     +- *(1) Project [anchor_page_id#1, item_id#2, store_id#5]
            :        +- *(1) Filter ((isnotnull(item_id#2) && isnotnull(anchor_page_id#1)) && isnotnull(store_id#5))
            :           +- *(1) FileScan parquet table_t1[anchor_page_id#1,item_id#2,store_id#5,date_id#18] Batched: true, Format: Parquet, Location: PrunedInMemoryFileIndex[gs://abc..., PartitionCount: 1, PartitionFilters: [isnotnull(date_id#18), (date_id#18 = 20220323)], PushedFilters: [IsNotNull(item_id), IsNotNull(anchor_page_id), IsNotNull(store_id)], ReadSchema: struct<anchor_page_id:string,item_id:string,store_id:string>
            +- *(4) Sort [anchor_page_id#19 ASC NULLS FIRST, item_id#20 ASC NULLS FIRST, store_id#23 ASC NULLS FIRST], false, 0
               +- Exchange hashpartitioning(anchor_page_id#19, item_id#20, store_id#23, 200)
                  +- *(3) Project [anchor_page_id#19, item_id#20, store_id#23]
                     +- *(3) Filter ((isnotnull(anchor_page_id#19) && isnotnull(item_id#20)) && isnotnull(store_id#23))
                        +- *(3) FileScan parquet table_t1[anchor_page_id#19,item_id#20,store_id#23,date_id#36] Batched: true, Format: Parquet, Location: PrunedInMemoryFileIndex[gs://abc..., PartitionCount: 1, PartitionFilters: [isnotnull(date_id#36), (date_id#36 = 20220324)], PushedFilters: [IsNotNull(anchor_page_id), IsNotNull(item_id), IsNotNull(store_id)], ReadSchema: struct<anchor_page_id:string,item_id:string,store_id:string>
>>>


q2 = spark.sql("select count(*) from table_t1 t1 full outer join table_t1 t2 on t1.anchor_page_id = t2.anchor_page_id and t1.item_id = t2.item_id and t1.store_id = t2.store_id where t1.date_id = '20220323' and t2.date_id = '20220324'")

q2.explain()
== Physical Plan ==
*(6) HashAggregate(keys=[], functions=[count(1)])
+- Exchange SinglePartition
   +- *(5) HashAggregate(keys=[], functions=[partial_count(1)])
      +- *(5) Project
         +- *(5) SortMergeJoin [anchor_page_id#1, item_id#2, store_id#5], [anchor_page_id#42, item_id#43, store_id#46], Inner
            :- *(2) Sort [anchor_page_id#1 ASC NULLS FIRST, item_id#2 ASC NULLS FIRST, store_id#5 ASC NULLS FIRST], false, 0
            :  +- Exchange hashpartitioning(anchor_page_id#1, item_id#2, store_id#5, 200)
            :     +- *(1) Project [anchor_page_id#1, item_id#2, store_id#5]
            :        +- *(1) Filter ((isnotnull(item_id#2) && isnotnull(anchor_page_id#1)) && isnotnull(store_id#5))
            :           +- *(1) FileScan parquet table_t1[anchor_page_id#1,item_id#2,store_id#5,date_id#18] Batched: true, Format: Parquet, Location: PrunedInMemoryFileIndex[gs://abc..., PartitionCount: 1, PartitionFilters: [isnotnull(date_id#18), (date_id#18 = 20220323)], PushedFilters: [IsNotNull(item_id), IsNotNull(anchor_page_id), IsNotNull(store_id)], ReadSchema: struct<anchor_page_id:string,item_id:string,store_id:string>
            +- *(4) Sort [anchor_page_id#42 ASC NULLS FIRST, item_id#43 ASC NULLS FIRST, store_id#46 ASC NULLS FIRST], false, 0
               +- Exchange hashpartitioning(anchor_page_id#42, item_id#43, store_id#46, 200)
                  +- *(3) Project [anchor_page_id#42, item_id#43, store_id#46]
                     +- *(3) Filter ((isnotnull(store_id#46) && isnotnull(anchor_page_id#42)) && isnotnull(item_id#43))
                        +- *(3) FileScan parquet table_t1[anchor_page_id#42,item_id#43,store_id#46,date_id#59] Batched: true, Format: Parquet, Location: PrunedInMemoryFileIndex[gs://abc..., PartitionCount: 1, PartitionFilters: [isnotnull(date_id#59), (date_id#59 = 20220324)], PushedFilters: [IsNotNull(store_id), IsNotNull(anchor_page_id), IsNotNull(item_id)], ReadSchema: struct<anchor_page_id:string,item_id:string,store_id:string>
>>>


q3 = spark.sql("select count(*) from table_t1 t1 left join table_t1 t2 on t1.anchor_page_id = t2.anchor_page_id and t1.item_id = t2.item_id and t1.store_id = t2.store_id where t1.date_id = 20220323 and t2.date_id = 20220324")

q3.explain()

== Physical Plan ==
*(6) HashAggregate(keys=[], functions=[count(1)])
+- Exchange SinglePartition
   +- *(5) HashAggregate(keys=[], functions=[partial_count(1)])
      +- *(5) Project
         +- *(5) SortMergeJoin [anchor_page_id#1, item_id#2, store_id#5], [anchor_page_id#65, item_id#66, store_id#69], Inner
            :- *(2) Sort [anchor_page_id#1 ASC NULLS FIRST, item_id#2 ASC NULLS FIRST, store_id#5 ASC NULLS FIRST], false, 0
            :  +- Exchange hashpartitioning(anchor_page_id#1, item_id#2, store_id#5, 200)
            :     +- *(1) Project [anchor_page_id#1, item_id#2, store_id#5]
            :        +- *(1) Filter ((isnotnull(item_id#2) && isnotnull(anchor_page_id#1)) && isnotnull(store_id#5))
            :           +- *(1) FileScan parquet table_t1[anchor_page_id#1,item_id#2,store_id#5,date_id#18] Batched: true, Format: Parquet, Location: PrunedInMemoryFileIndex[gs://abc..., PartitionCount: 1, PartitionFilters: [isnotnull(date_id#18), (cast(date_id#18 as int) = 20220323)], PushedFilters: [IsNotNull(item_id), IsNotNull(anchor_page_id), IsNotNull(store_id)], ReadSchema: struct<anchor_page_id:string,item_id:string,store_id:string>
            +- *(4) Sort [anchor_page_id#65 ASC NULLS FIRST, item_id#66 ASC NULLS FIRST, store_id#69 ASC NULLS FIRST], false, 0
               +- Exchange hashpartitioning(anchor_page_id#65, item_id#66, store_id#69, 200)
                  +- *(3) Project [anchor_page_id#65, item_id#66, store_id#69]
                     +- *(3) Filter ((isnotnull(item_id#66) && isnotnull(store_id#69)) && isnotnull(anchor_page_id#65))
                        +- *(3) FileScan parquet table_t1[anchor_page_id#65,item_id#66,store_id#69,date_id#82] Batched: true, Format: Parquet, Location: PrunedInMemoryFileIndex[gs://abc..., PartitionCount: 1, PartitionFilters: [isnotnull(date_id#82), (cast(date_id#82 as int) = 20220324)], PushedFilters: [IsNotNull(item_id), IsNotNull(store_id), IsNotNull(anchor_page_id)], ReadSchema: struct<anchor_page_id:string,item_id:string,store_id:string>


q4 = spark.sql("select count(*) from table_t1 t1 left outer join table_t1 t2 on t1.anchor_page_id = t2.anchor_page_id and t1.item_id = t2.item_id and t1.store_id = t2.store_id where t1.date_id = 20220323 and t2.date_id = 20220324")

q4.explain()

== Physical Plan ==
*(6) HashAggregate(keys=[], functions=[count(1)])
+- Exchange SinglePartition
   +- *(5) HashAggregate(keys=[], functions=[partial_count(1)])
      +- *(5) Project
         +- *(5) SortMergeJoin [anchor_page_id#1, item_id#2, store_id#5], [anchor_page_id#88, item_id#89, store_id#92], Inner
            :- *(2) Sort [anchor_page_id#1 ASC NULLS FIRST, item_id#2 ASC NULLS FIRST, store_id#5 ASC NULLS FIRST], false, 0
            :  +- Exchange hashpartitioning(anchor_page_id#1, item_id#2, store_id#5, 200)
            :     +- *(1) Project [anchor_page_id#1, item_id#2, store_id#5]
            :        +- *(1) Filter ((isnotnull(item_id#2) && isnotnull(anchor_page_id#1)) && isnotnull(store_id#5))
            :           +- *(1) FileScan parquet table_t1[anchor_page_id#1,item_id#2,store_id#5,date_id#18] Batched: true, Format: Parquet, Location: PrunedInMemoryFileIndex[gs://abc..., PartitionCount: 1, PartitionFilters: [isnotnull(date_id#18), (cast(date_id#18 as int) = 20220323)], PushedFilters: [IsNotNull(item_id), IsNotNull(anchor_page_id), IsNotNull(store_id)], ReadSchema: struct<anchor_page_id:string,item_id:string,store_id:string>
            +- *(4) Sort [anchor_page_id#88 ASC NULLS FIRST, item_id#89 ASC NULLS FIRST, store_id#92 ASC NULLS FIRST], false, 0
               +- Exchange hashpartitioning(anchor_page_id#88, item_id#89, store_id#92, 200)
                  +- *(3) Project [anchor_page_id#88, item_id#89, store_id#92]
                     +- *(3) Filter ((isnotnull(store_id#92) && isnotnull(item_id#89)) && isnotnull(anchor_page_id#88))
                        +- *(3) FileScan parquet table_t1[anchor_page_id#88,item_id#89,store_id#92,date_id#105] Batched: true, Format: Parquet, Location: PrunedInMemoryFileIndex[gs://abc..., PartitionCount: 1, PartitionFilters: [isnotnull(date_id#105), (cast(date_id#105 as int) = 20220324)], PushedFilters: [IsNotNull(store_id), IsNotNull(item_id), IsNotNull(anchor_page_id)], ReadSchema: struct<anchor_page_id:string,item_id:string,store_id:string>


 


The Bag of Marbles Phenomena

QUESTION:

I have a bag of marbles with a total volume of 33. There are two kinds of marbles in my bag. Blue marbles that have a volume of 3 and red marbles that have a volume of 6. If I have 8 marbles in the bag, how many blue and red marbles do I have?

I have been trying to create a code that tells me how many red and blue marbles there are but I cant seem to solve this. Any Ideas?

For this specific problem there should be 5 Blue and 3 Red.



Python automatically login to web-based router portal to check sms

I recently purchased a Huawei mobile router which has a web-based portal, but the portal automatically logs me out when I switch tabs (security feature) but I use the portal for text messages and would like to create a script that I could run when using my laptop,

There are three web pages involved in this process

Portal Login Page: http://192.168.8.1/html/index.html

Login Page

Portal Home Page: http://192.168.8.1/html/content.html#home

Home Page

Portal Sms Page: http://192.168.8.1/html/content.html#sms

Sms Page

So I have managed to get somewhere with a python script.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time 

def login_process():
  passwordStr = 'myPassword'
  browser = webdriver.Chrome()
  browser.set_window_size(900, 800)
  browser.get(('http://192.168.8.1/html/index.html'))
  username = browser.find_element_by_id('login_password')
  username.send_keys(passwordStr)
  signInButton = browser.find_element_by_id('login_btn')
  signInButton.click()
  time.sleep(3)
  browser.get(('http://192.168.8.1/html/content.html#sms'))
  time.sleep(2)
  html = browser.find_element_by_tag_name('html') 
  html.send_keys(Keys.END)
  html.send_keys(Keys.ARROW_RIGHT)
  html.send_keys(Keys.ARROW_RIGHT)
  html.send_keys(Keys.ARROW_RIGHT)
  html.send_keys(Keys.ARROW_RIGHT)
  html.send_keys(Keys.ARROW_RIGHT)
  html.send_keys(Keys.ARROW_RIGHT)
  html.send_keys(Keys.ARROW_RIGHT)
  html.send_keys(Keys.ARROW_RIGHT)
  time.sleep(10)
login_process()

But now I am struggling to find a way so that If i manually click into the browser window at the end of the function it will stay open as it automatically closes if i don't have time.sleep(10)

and I also want the function to auto run every 10 minutes until I close the script, like say I want to watch a movie.



Execute server-side shell script on button click

I am trying to execute a shell script that resides in my server. And I need to get the (string) result of this shell script after execution. However, this script should only be triggered only when a certain button in my ReactJS app is pressed.

I spent considerable amount of time looking for answer. So far, all the answers point to an idea of creating a web service then have the app call the service on button click. But none of the answers pointed how exactly this is done nor any of the answers point to any article that discusses this approach. (Sorry if this is a basic approach, but I just learned ReactJS last month from Udemy.)

Would you mind creating a simple code that demonstrates communication between the 'shell script web service' and a button (onClick)? Or at least provide an article link that discusses this approach?

Thanks for any help.

EDIT: What I tried so far is How to execute shell command in Javascript. But comments say that this will not work on browser. I guess this is the code that I need to write in my web service?



norm of differences of variables in cvxpy

How can I take the following norm in cvxpy

enter image description here

sum(norm(x[i] - x[j], p=2), i=1, j>i, i, j = n)

where x is (n, 2) variable matrix defined by x = cp.Variable((n, 2)). For the problem, I am taking n=16. The following is the code I am trying to completely

import numpy as np
import cvxpy as cp


def solver(pts, var, lmb):
    objective = cp.Minimize(cp.norm(pts - var, 2) + cp.norm(var, 2))
    prob = cp.Problem(objective)
    prob.solve()
    print(prob.value)
    return np.round(var.value, 2)

pts = np.array([(-2, 3), (-3, 5), (-1, 4), (-3, 7) , (0, 3), 
                (-2, -2), (-3, 8), (3, 1), (1, -2), (2, 6), 
                (-2, 6), (-2, 5), (-4, 3), (-4, 6), (-3, 10), 
                (2, -3)])

n = pts.shape[0]
var = cp.Variable((n, 2))

solver(pts, var, 1)


2022-03-29

Is there a way to reduce the amount of loops in this class?

Recently started with Java. I have a class where several methods loop over an Arraylist, I am wondering if there would be a way to reduce the amount of loops as they only do one check really. Some sort of way to implement a function and pass predicate? I discovered Lambdas yesterday, but not sure it would be applicable here.

public class Stock {
    private ArrayList<Products> _productList;
    public Stock(){}

    public Boolean addProduct(Products product){
        return _productList.contains(product) && _productList.add(product);
    }

    public int obtainPos(int code){
        for(int i=0; i < _productList.size(); i++)
            if(_productList.get(i).getCode() == code)
                return i;
        return -1;
    }

    public void removeProduct(int code){
        int pos = obtainPos(code);
        if(pos >=0)
            _productList.remove(pos);
        else
            System.out.println("Error - Product not found.");
    }

    public int productAmount(){ return _productList.size(); }

    public int amountType(String type){
        int i = 0;
        for(Products pr : _productList)
            if(pr.getClass().getSimpleName().equals(type))
                i++;
        return i;
    }

    @Override
    public String toString(){
        StringBuilder sb = new StringBuilder();
        for(Products pr : _productList)
            sb.append(pr.getName()).append(" \n");
        return sb.toString();
    }

    public void itemsToRemove(String reason){
        StringBuilder st = new StringBuilder();
        for(Products pr : _productList)
            st.append(pr.getName()).append(" - ").append(pr.withdraw(reason)).append("\n");

        System.out.println(st.toString());
    }
}

Thanks!



Clarifying Vault key decryption process

I'm trying to understand Vault workflow w.r.t. keys, e.g.: https://www.vaultproject.io/docs/concepts/seal

1

As I understand,

  • unseal (shared) keys are provided on init
  • they're used to acquire the combined key
  • combined key is then used to decrypt a root (master) key (which is apparently stored in the sealed vault)
  • root key is then used to decrypt the data encryption key (or a keyring which contains it?..)
  • the data encryption key is then used to en/decrypt the data in Vault

I get the unseal keys on init, how can I inspect the other keys? Is it impossible / are those keys just stored somewhere internally in Vault?

Unsealing is the process of obtaining the plaintext root key necessary to read the decryption key to decrypt the data, allowing access to the Vault.

Is the data encryption key / keyring also decrypted during the unseal, or is it... maybe decrypted on each Vault operation (so only the root key is stored somewhere in plaintext after the unseal)?

Is it ok that the root key is stored in plaintext after the unseal? Or is it still protected by passwords/tokens?.. Or if it's just transiently used to decrypt the data encryption key / keyring, then how are those protected? I guess it has smth to do with the lock icon on the image :)

I'm somewhat confused about how it all works.



React MSAL not working after page refresh

I am using @azure/msal-react and @azure/msal-browser for authentication in our application. So far i have intialized a msal instance and used it to acquire a token and fetch the alias. Everything works until i do a page refresh i want to understand if this is a cache issue i see data is present in local storage regarding msal but still getting null in active account.

here you can see the msal instance with configuration (authProvider) AuthProvider.js

import * as APIConstants from "./Common/APIConstants";

import {
  BrowserCacheLocation,
  PublicClientApplication,
  LogLevel
} from '@azure/msal-browser';

const loggerCallback = (logLevel, message) => {
  console.log(message);
};

const configuration = {
  auth: {
    authority: APIConstants.TENANT,
    clientId: APIConstants.CLIENT_ID,
    postLogoutRedirectUri: window.location.origin,
    redirectUri: window.location.origin,
    validateAuthority: true,
    navigateToLoginRequestUrl: true,
  },
  cache: {
    cacheLocation: BrowserCacheLocation.localStorage,
    storeAuthStateInCookie: true,
  },

  system: {
    loggerOptions: {
      loggerCallback,
      logLevel: LogLevel.Info,
      piiLoggingEnabled: false
    }
  }
};

export const authProvider = new PublicClientApplication(configuration);

Login.js

import React, { Component } from "react";
import { authProvider } from "../../authProvider";
import * as APIConstants from "../../Common/APIConstants";

import {
  EventType,
} from '@azure/msal-browser';

class Login extends Component {

  constructor() {
    super()
    this.successEventId = null;
  }

  loginSuccessCallback = (event) => {
    if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) {
      const payload = event.payload;
      const account = payload.account;
      authProvider.setActiveAccount(account);
      this.props.history.push("/dashboard");
    }
  }

  componentDidMount = () => {
    this.successEventId = authProvider.addEventCallback(this.loginSuccessCallback);
  }

  componentWillUnmount = () => {
    if (this.successEventId)
      authProvider.removeEventCallback(this.successEventId);
  }

  onLDAPLogin = () => {
    authProvider.loginRedirect({
      scopes: [APIConstants.RESOURCE_URI],
    })
  }



  render() {
    return (
      < div >
        <button onClick={() => this.onLDAPLogin()}>LDAP Login</button>
      </div>
    );
  }
}
export default Login;

dashboard.js

purpose dashboard.js is to collect data through api call where you use alias and token of that user to make the call

const getAllData = async () => {
                let user = await Services.getLogedInUser();
                if (user) {
                    let username = user.username;
                    let alias = username.split("@")[0];
                    let token = await Services.getAccessToken();
                    if (token) {
                        await initiateApiCall(alias,token);
                    } else {
                        props.history.push("/");
                    }
                }
                else {
                    props.history.push("/");
                }

}

Services.js

export const getAccessToken = async () => {
  const activeAccount = authProvider.getActiveAccount();
  const accounts = authProvider.getAllAccounts();

  if (!activeAccount && accounts.length === 0) {
    /*
    * User is not signed in. Throw error or wait for user to login.
    * Do not attempt to log a user in outside of the context of MsalProvider
    */
  }
  const request = {
    scopes: [APIConstants.RESOURCE_URI],
    account: activeAccount || accounts[0]
  };

  const authResult = await authProvider.acquireTokenSilent(request);

  console.log('auth result acquire token ', authResult);
  return authResult.accessToken
};

export const getLogedInUser = async () => {
  console.log('authProvider', authProvider);
  console.log('all accounts ', authProvider.getAllAccounts());
  let account = authProvider.getActiveAccount();
  console.log('account ', account);
  return account;
};

As it is shown in the console i get both active account and all accounts value but in case i refresh the page active account is null and all accounts is an empty array



Why some fields are missing from google calendar event list in NodeJS google calendar api?

I have successfully integrated NodeJS backend with google calendar. I retrieve all events from google calendar successfully.

Issue is following: not all fields are present in resulting event list. For example: some fields from organizer are missing altogether.

This is my sample response:

    {
        "kind": "calendar#event",
        "etag": "\"---\"",
        "id": "---",
        "status": "confirmed",
        "htmlLink": "---",
        "created": "2022-03-28T15:32:53.000Z",
        "updated": "2022-03-28T15:32:53.093Z",
        "creator": {
            "email": "tornike.shavishvili@ngt.ge",
            "self": true
        },
        "organizer": {
            "email": "tornike.shavishvili@ngt.ge",
            "self": true
        },
        "start": {
            "dateTime": "2022-03-28T19:30:00+04:00",
            "timeZone": "Asia/Tbilisi"
        },
        "end": {
            "dateTime": "2022-03-28T20:30:00+04:00",
            "timeZone": "Asia/Tbilisi"
        },
        "iCalUID": "---",
        "sequence": 0,
        "reminders": {
            "useDefault": true
        },
        "eventType": "default"
    }

Here are list of all parameters according to google documentation: Events Resource representations

I have researched it for several days but completely out of clue: what could be reason of missing fields? Maybe integration account needs some additional permissions?

Thank you



Overlapping bar plot in ggplot2

I'm trying to hide a variable in a stacked bar chart in a dataset.
Below is the dataset:



How to send solana via my app in vanilla js?

Trying to do a simple send and receive function in Solana with vanilla JS.

Below is my send function that works fine, and now I want a receive function. Where the provider would get Solana transferred from my treasury wallet.

I'm not sure what approach I should have, just starting out. Is there a way to just move things around in this function? Or do I have to have a totally different approach?

Thanks!

async function transferSOL() {
  // Detecing and storing the phantom wallet of the user (creator in this case)
  var provider = phantom;

  // Establishing connection
  var connection = new web3.Connection(
    web3.clusterApiUrl('devnet'),
  );

  var transaction = new web3.Transaction().add(
    web3.SystemProgram.transfer({
      fromPubkey: provider.publicKey,
      toPubkey: treasuryWallet.publicKey,
      lamports: 0.1 * web3.LAMPORTS_PER_SOL - 100  
    }),
  );
  // Setting the variables for the transaction
  transaction.feePayer = await provider.publicKey;
  let blockhashObj = await connection.getRecentBlockhash();
  transaction.recentBlockhash = await blockhashObj.blockhash;

  // Request creator to sign the transaction (allow the transaction)
  let signed = await provider.signTransaction(transaction);
  let signature = await connection.sendRawTransaction(signed.serialize());
  await connection.confirmTransaction(signature);
}


2022-03-28

How to overwrite pyspark DataFrame schema without data scan?

This question is related to https://stackoverflow.com/a/37090151/1661491. Let's assume I have a pyspark DataFrame with certain schema, and I would like to overwrite that schema with a new schema that I know is compatible, I could do:

df: DataFrame
new_schema = ...

df.rdd.toDF(schema=new_schema)

Unfortunately this triggers computation as described in the link above. Is there a way to do that at the metadata level, without triggering computation or conversions?

Edit, note:

  • the schema can be arbitrarily complicated (nested etc)
  • new schema includes updates to description, nullability and additional metadata (bonus points for updates to the type)
  • I would like to avoid writing a custom query expression generator, unless there's one already built into Spark that can generate query based on the schema/StructType


how do i parse log data and extract time, profit,position,volume from text file into a dataframes and plot profit vs time volume vs time

03/17/17 10:30:01.511363338 W (leg0)1621573201394718152:TRADE:ins=BSE/GBPINR17JUNEFUT,q=1,p=893900000,pos=0,risk_pos=0,cashflow=-89390.000000,pnl=-18.050891,net_pnl=-18.050891,tgt=893935108.275274,market_volume=16229,bbo=91/893900000 893975000/136, qty_behind=91,realized_pnl=-18.050891,unrealized_pnl=0.00000093711,market_volume=16229,bbo=91/893900000 893975000/136, qty_behind=91,realized_pnl=-18.050891,unrealized_pnl=0.000000

My code:

import datetime as dt import pandas as pd import numpy as np import re import matplotlib.pyplot as plt

filename='C:\Users\Goog\Downloads\loggg.txt' pp=[]

pnl=re.compile(r',pnl=(-?[\d]+.\d{6})\b') vol=re.compile(r'market_volume=(\d{5})')

result = [] vol1=[] with open(filename) as n: line=n.readline() while line: result +=re.findall(pnl , line) vol1+=re.findall(vol ,line) line = n.readline() print(result,vol1)

I need to parse the data only if :trade happens, note this is only one single line of data in the entire log file.


import datetime as dt
import pandas as pd
import numpy as np
import re
import matplotlib.pyplot as plt


filename='C:\\Users\\googg\Downloads\\loggg.txt'
pp=[]

pnl=re.compile(r',pnl=(-?[\d]+.\d{6})\b')
vol=re.compile(r'market_volume=(\d{5})')

result = []
vol1=[]
with open(filename) as n:
    line=n.readline()
    while line:
        result +=re.findall(pnl , line)
        vol1+=re.findall(vol ,line)
        line = n.readline()
print(result,vol1)

how do i combine both the date into a single dataframe also i need to extract time and put all of them together in a single data frame such as index is time and rest pnl,volume are set in columns?



Out of bounds exception on array that has not been initialized to a specific size

C# Coding for unity

I have several arrays set as such.

public float[] arrayName;

no set number of elements anywhere in my code

I can access the arrays up to 6 no problems but when I get to 7 I get an out of bounds exception.

No where in my code does it initialize them to a specific amount and even when I try

public float[] arrayName = new float[8] 

for instance then run a debug log to get the length

I still get 7 and cannot access past 6. I am far from an expert.

Here is the thing...

I also have a couple texture 2d arrays...

public Texture2D[] arrayName; 

which I was having the same problem with but when I set them like this

public Texture2D[] arrayName = new Texture2D[8];

all is fine.

I am so confused...

I have also tried this.

public float[] array name = new float[] {1f, 2f, 3f, 4f ,5f, 6f, 7f, 8f}

etc. same result

Somehow my arrays are being limited to 7. As I am asking this I am going to try creating new arrays which will be initialized like such

public float[] newArrayName = new float[8];

and see what happens. But I would love to learn what I am obviously doing wrong or not understanding. Thanks

These are my arrays. All work perfect up to when I try to access 7. Then Get out of bounds errors.

 public Texture2D[] terrainTexture;
public Texture2D[] terrainTextureNormal;
public float[] normalScale;
public Color[] specular;
public float[] metallic;
public float[] smoothness;
public float[] maxHeight;
public float[] minHeight;
public float[] maxSteepness;
public float[] minSteepness;
public float[] weight;
public float[] blend;

The code I use to assign the control settings to the arrays. All do as expected 0 to 6

#region Texture One Foldout terrain.showTextureOne = EditorGUILayout.Foldout(terrain.showTextureOne, " Texture One", EditorStyles.boldLabel); if (terrain.showTextureOne) {

        GUILayout.Space(20);
        terrain.terrainTexture[0] = (Texture2D)EditorGUILayout.ObjectField("Diffuse", terrain.terrainTexture[0], typeof(Texture2D), true);
        GUILayout.Space(2);
        terrain.terrainTextureNormal[0] = (Texture2D)EditorGUILayout.ObjectField("Normal Map", terrain.terrainTextureNormal[0], typeof(Texture2D), true);
        GUILayout.Space(6);
        terrain.normalScale[0] = EditorGUILayout.Slider("Normal Scale", terrain.normalScale[0], 0f, 1f);
        GUILayout.Space(10);
        terrain.metallic[0] = EditorGUILayout.Slider("Metallic",terrain.metallic[0], 0f, 1f);
        GUILayout.Space(10);
        terrain.smoothness[0] = EditorGUILayout.Slider("Smoothness", terrain.smoothness[0], 0f, 1f);
        GUILayout.Space(10);
        terrain.maxHeight[0] = EditorGUILayout.Slider("Max Height", terrain.maxHeight[0], 0f, terrain.terrainHeight);
        GUILayout.Space(10);
        terrain.minHeight[0] = EditorGUILayout.Slider("Min Height", terrain.minHeight[0], 0f, terrain.terrainHeight);
        GUILayout.Space(10);
        terrain.maxSteepness[0] = EditorGUILayout.Slider("Max Steepness",terrain.maxSteepness[0], 0, 90);
        GUILayout.Space(10);
        terrain.minSteepness[0] = EditorGUILayout.Slider("Min Steepness", terrain.minSteepness[0], 0, 90);
        GUILayout.Space(10);
        terrain.weight[0] = EditorGUILayout.Slider("Weight", terrain.weight[0], 0f, 1f);
        GUILayout.Space(10);
       
        terrain.size[0] = EditorGUILayout.Vector2Field("Size", terrain.size[0]);
        terrain.offset[0] = EditorGUILayout.Vector2Field("Offset", terrain.offset[0]);
        GUILayout.Space(10);
        GUILayout.BeginHorizontal();

        if (GUILayout.Button("Set Properties"))
        {
            terrain.ModifyTextures();
        }
        if (GUILayout.Button("Save Properties"))
        {
            terrain.SaveEditorSettings();
        }
        GUILayout.EndHorizontal();


    }

When I copy paste working code and simply modify 6 to 7 for example which is all that is and as been needed, chaos! :) Example notice the Texture2D Arrays modified and work with no errors. Arrays declared exactly the same but as you can see I change one 6 to 7 as in the normalScale line, nothing but out of bounds errors. There have been other things I have forgotten to change in other code which has caused this but I have painstakingly made sure that is not the problem.

#region Texture Eight Foldout terrain.showTextureEight = EditorGUILayout.Foldout(terrain.showTextureEight, " Texture Eight", EditorStyles.boldLabel);

    if (terrain.showTextureEight)
    {
        GUILayout.Space(20);
        terrain.terrainTexture[7] = (Texture2D)EditorGUILayout.ObjectField("Diffuse", terrain.terrainTexture[7], typeof(Texture2D), true);
        GUILayout.Space(2);
        terrain.terrainTextureNormal[7] = (Texture2D)EditorGUILayout.ObjectField("Normal Map", terrain.terrainTextureNormal[7], typeof(Texture2D), true);
        GUILayout.Space(6);
        
        terrain.normalScale[7] = EditorGUILayout.Slider("Normal Scale", terrain.normalScale[7], 0f, 1f);
        GUILayout.Space(6);
        terrain.metallic[6] = EditorGUILayout.Slider("Metallic", terrain.metallic[6], 0f, 1f);
        GUILayout.Space(10);
        terrain.smoothness[6] = EditorGUILayout.Slider("Smoothness", terrain.smoothness[6], 0f, 1f);

This is my custom editor. One through 7 work as planned. Click 8 and ... ?



ASP.NET MVC 5 : foreach loop sort and write output in specific order

I have a foreach loop in my view and I need it to write data in specific order id HTML sections. The problem is that i don't want HTML section to be seen if there is no data for that section.

int idSection1 = 1;
int idSection2 = 2;
int idSection3 = 3;

@foreach (var item in Model.ItemList)
{
    if (itme.IdSection == idSection1)
    {
        <div>
            <h4>Section 1</h4>
            foreach (var data in Model.ItemList)
            {
                if (data.IdSection == 1)
                {
                    <p>data</p>
                }
                idSection1 = idSection1 + 10;
            }
        </div>
    }

    if (itme.IdSection == idSection2)
    {
        <div>
            <h4>Section 2</h4>
            foreach (var data in Model.ItemList)
            {
                if (data.IdSection == 2)
                {
                    <p>data</p>
                }
                idSection2 = idSection1 + 10;
            }
        </div>
    }

    if (itme.IdSection == idSection3)
    {
        <div>
            <h4>Section 3</h4>
            foreach (var data in Model.ItemList)
            {
                if (data.IdSection == 2)
                {
                    <p>data</p>
                }
                idSection3 = idSection3 + 10;
            }
        </div>
    }
}

And with this my output, depending on my list and in what order data was entered is this:

<h4>Section 2</h4>
    <p>data 1</p>
    <p>data 2</p>
    <p>data 3</p>
    
<h4>Section 1</h4>
    <p>data 1</p>
    
<h4>Section 3</h4>
    <p>data 1</p>
    <p>data 2</p>

And I need it to be this, with important part that for example "Section 2" doesn't need to written if there is no data for it! :

 <h4>Section 1</h4>
    <p>data 1</p>
    
<h4>Section 2</h4>
    <p>data 1</p>
    <p>data 2</p>
    <p>data 3</p>   
    
<h4>Section 3</h4>
    <p>data 1</p>
    <p>data 2</p>


What does "replacement" mean in imbalanced learn RandomOverSampler?

I am on imbalanced learn's documentation reading about RandomOverSampler. The documentation says that RandomOverSampler is a

Class to perform random over-sampling. Object to over-sample the minority class(es) by picking samples at random with replacement. The bootstrap can be generated in a smoothed manner.

What does a replacement mean? Does it randomly duplicates samples from minority/majority class or is it something else?



Integrating report viewer in .NET core 3.1 for SSRS Reports (rdl files) [closed]

I have lot of SSRS reports (rdl) and requirement is to integrate in .NET core MVC 3.1 App using Report Viewer control. I didn't find any good solution.

I have checked https://github.com/alanjuden/MvcReportViewer but this looks very old one.

Please suggest the best way to integrate report viewer control in .NET Core MVC App.



How to build Swift framework with 3rd party SPM dependencies

I've built swift frameworks before, but I've never dealt with one that has 3rd party dependencies.

What I have right now is a Swift framework that has a dependency on several Swift packages. When I build it I see MyFramework.framework in the products folder as well as bunch of dependencies. I can make XCFramework out of it, but when integrating (embedding) it into another app I see an error that MyFramework is missing its dependencies (see image below).

enter image description here

What am I doing wrong or missing?



2022-03-27

How to remove punctuation and capitalization in my palindrome assignment?

The problem is trying to use strings to prove whether a word or phrase is a palindrome.

def is_palindrome(input_string):

    left = 0

    right = len(input_string) - 1

    while left < right:
        if input_string[left] != input_string[right]:
            return False
        left += 1
        right -= 1
    
    return True 

This what I attempted to do but when typing in my_palindrome("race car") it was proven false when it is supposed to be proven true. Need help on finding code to add to this to make punctuation and capitalization negligible.



C# / WPF - How should I save user-typed data all at once after a submit button click?

I'm learning WPF/C# via self-teaching and am currently building a small WPF app for practice instead of following tutorials, and so far it's been great; however, I have hit a roadblock that I've spent days on.

I have a WPF User Control with multiple TextBoxes where a user can type in a title, ingredients, tools, steps, notes, and add an image of what they made. After all of that is filled in, I would like for them to click a 'Submit' button and have that data saved and able to be accessed at another time.

Now for one, I don't know how I should go about doing that, I have seen mention of XML, JSON, SQLite, etc. I did try the XML method like so:

private void SubmitButton_Click(object sender, RoutedEventArgs e)
        {
            Recipe recipe = new Recipe();
            recipe.Title = TitleBox.Text;
            recipe.Step1 = StepBox1.Text;
            recipe.Step2 = StepBox2.Text;
            recipe.Step3 = StepBox3.Text;
            recipe.Step4 = StepBox4.Text;
            recipe.Step5 = StepBox5.Text;
            recipe.Step6 = StepBox6.Text;
            recipe.Ingredients = IngredientBox.Text;
            recipe.Tools = ToolBox.Text;
            recipe.Notes = NoteBox.Text;
            CreateViewModel.SaveData(recipe, TitleBox.Text);
        } 

In my ViewModel, I have this typed up:

public static void SaveData(object obj, string filename)
        {
            XmlSerializer sr = new XmlSerializer(obj.GetType());
            TextWriter writer = new StreamWriter(filename);
            sr.Serialize(writer, obj);
            writer.Close();
        }

This does end up "working" (without the image of course) in that I see the file and can access it manually via the explorer (loading the file in the program is a whole other thing I'm going to tackle another day), but I feel that this isn't the way to go about it from what I've seen on my searches. If there's a better strategy here that I'm missing, I would love to use and learn from it.

Thank you

EDIT

Alright so I downloaded and am currently using PostgreSQL thanks to @Jonathon Willcock (watched a long video on it to get the gist, and am currently diving deep into it even more as I implement it into my small app), so far I think I've been successful in saving the data into a table with the necessary values as I see it there currently, but I'm clueless when it comes to saving an image. I will continue to work at it and try to figure it out, but if anyone has any advice for me on how I could go about doing that, I would greatly appreciate it!



Can I write all "append" code in a row using "if"?

how can I in python append by condition, can i write like this?

'Segment 2': result['trips'][0]['segments'][2]['bookingClass']) if(len(result['trips'][0]['segments'] == 2,

at the moment i try to write all in one row, is this possible?

response.append({'Fare Type': result['fareType'], 'Segment 2': result['trips'][0]['segments'][2]['bookingClass']) if(len(result['trips'][0]['segments'] == 2})


importing from chessdotcom gives error as: RuntimeError: There is no current event loop in thread 'ScriptRunner.scriptThread'

import pandas as pd
import numpy as np

import streamlit as st

st.title("Chess Analysis")

from chessdotcom import get_player_profile

response = get_player_profile("fabianocaruana")

player_name = response.json['player']['name']

The error is :

 You can now view your Streamlit app in your browser.

  Local URL: http://localhost:8501
  Network URL: http://192.168.29.133:8501

2022-03-25 20:23:16.543 Traceback (most recent call last):
  File "C:\Users\sumit\anaconda3\envs\chess_engine\lib\site-packages\streamlit\scriptrunner\script_runner.py", line 443, in _run_script
    exec(code, module.__dict__)
  File "E:\Self Projects\ChessEngine\src\dashboard.py", line 8, in <module>
    from chessdotcom import get_player_profile
  File "C:\Users\sumit\anaconda3\envs\chess_engine\lib\site-packages\chessdotcom\__init__.py", line 2, in <module>
    from chessdotcom.client import *
  File "C:\Users\sumit\anaconda3\envs\chess_engine\lib\site-packages\chessdotcom\client.py", line 19, in <module>
    class Client:
  File "C:\Users\sumit\anaconda3\envs\chess_engine\lib\site-packages\chessdotcom\client.py", line 28, in Client
    loop = get_event_loop()
  File "C:\Users\sumit\anaconda3\envs\chess_engine\lib\asyncio\events.py", line 642, in get_event_loop
    raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'ScriptRunner.scriptThread'.

Any leads would be appreciated. Many thanks in advance!



How to add field in laravel backpack add user form

I need to add some fields in the user create page in admin panel. enter image description here

This page includes only name field, I need to add first name and last name field. What is the way...



Sum duplicated rows in SQL Server

Sum repeated values in datatable (VB.NET) or in SQL Server (are better one or other solutions)

I have a database in which are reported repeated rows:

Description | Price | Q.ty | Tax
AAAAAAAAAAA | 10.00 | 20.0 | 5
AAAAAAAAAAA | 10.00 | 12.0 | 5
BBBBBBBBBBB | 18.00 | 09.0 | 5
BBBBBBBBBBB | 18.00 | 12.0 | 5
CCCCCCCCCCC | 13.00 | 15.0 | 5
AAAAAAAAAAA | 17.0  | 19.0 | 5

And I want obtain something like this:

Description | Price | Q.ty | Tax
AAAAAAAAAAA | 10.00 | 51.0 | 5
BBBBBBBBBBB | 18.00 | 21.0 | 5
CCCCCCCCCCC | 13.00 | 15.0 | 5

I've created a datatable in VB.NET and I tried to sum values in it, and then show summed rows in a datagridview, but without results. Then, I've tried to do this with SQL Server (2019), without results again.

Can someone help me, please?

My code is:

Dim conn as New SqlConnection("*****")
Dim cmd2 As New SqlCommand("SELECT Description, Price, SUM(Q.ty), Tax, FROM Prodotti GROUP BY Descrizione", conn)
Dim da As New SqlDataAdapter
da.SelectCommand = cmd2
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
DataGridView1.SuspendLayout()
DataGridView1.DataSource = dt
DataGridView1.ResumeLayout()
conn.Close()

I want to obtain my goal with VB.NET or directly with SQL Server.



Read columns in Excel - write to CSV in different order

I need to understand if there is a possibility, within VB.NET, to be able to read the columns of an Excel file and write them out to a CSV file in a different order.

In practice, the Excel file we are sent has 6 columns: "amount", "branch", stock "," proposal "," quantity "," type ". The company management system accepts the text file with the columns in a different order: "branch", "stock", "amount", "quantity", "type", "proposal". This creates a problem for me because when I go to convert it my ERP fails to recognize that the column is in a different position.

I arrive at the concrete question, I would like to have the possibility to read the columns and make it possible through a script to be able to position them according to the position I decide.

I tried this code for import and convert to txt, but I need another script:

Imports System.IO
Imports ExcelDataReader
Imports System.Text

Public Class Form1

Dim tables As DataTableCollection



Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Using ofd As OpenFileDialog = New OpenFileDialog() With {.Filter = "(*.xls)|*.xls|(*.xls)|*.xlsx"}
        If ofd.ShowDialog() = DialogResult.OK Then
            txtFileName.Text = ofd.FileName
            Using Stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read)
                Using reader As IExcelDataReader = ExcelReaderFactory.CreateReader(Stream)
                    Dim result As DataSet = reader.AsDataSet(New ExcelDataSetConfiguration() With {
                                                             .ConfigureDataTable = Function(__) New ExcelDataTableConfiguration() With {
                                                             .UseHeaderRow = True}})
                    tables = result.Tables
                    cboSheet.Items.Clear()
                    For Each table As DataTable In tables
                        cboSheet.Items.Add(table.TableName)
                    Next
                End Using
            End Using
        End If
    End Using

End Sub

Private Sub cboSheet_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSheet.SelectedIndexChanged

    Dim dt As DataTable = tables(cboSheet.SelectedItem.ToString())
    dgProposte.DataSource = dt

End Sub


Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    Dim writer As TextWriter = New StreamWriter("C:\Users\antonio\Desktop\Prova.txt")

    For i As Integer = 0 To dgProposte.Rows.Count - 2 Step +1
        For j As Integer = 0 To dgProposte.Columns.Count - 1 Step +1
            writer.Write(vbTab & dgProposte.Rows(i).Cells(j).Value.ToString() & vbTab & "")
        Next

        writer.WriteLine("")

    Next
    writer.Close()
    MessageBox.Show("Dati Esportati")

End Sub


2022-03-26

Qt Designer Custom Widget Plugin Changing the Displayed Name and accessing custom Enums in Designer

I have created a Custom Widget Plugin and have a series of questions that I am hoping to get some insight on.

In the plugin onset's the class name in the name method which also must match what is in the widget class. That makes sense.

QString AnalogClockPlugin::name() const
{
    return QStringLiteral("AnalogClock");
}

QString AnalogClockPlugin::domXml() const
{
    return " <widget class=\"AnalogClock\" name=\"analogClock\">\n"
            "</ui>\n";
}

However, in Designer one sees "AnalogClock." Is there a way to have it be "Analog Clock" with a space or is one stuck just having the class name displayed? In looking through the examples and docs I am not able to find anything.

Second question, say one wants the user to be able to select the type of hands for the clock. For instance, Micky Mouse hands vs Mini Mouse hands. I have set up the enums and everything works in the widget. How does one communicate that to Designer ?? So it shows up in the Designer properties?? Again. in looking through the examples and docs I am not able to find anything.



Interacting regressors in a BQ ML Linear Regression Model

I'm trying to work out how get two regressors to interact when using BigQuery ML.

In this example below (apologies for the rough fake data!), I'm trying to predict total_hire_duration using trip_count as well as the month of the year. BQ tends to treat the month part as a constant to add on to the linear regression equation but I actually want it to grow with trip_count. For my real dataset I can't just supply the timestamp as BQML seems to over parametise.

I should add, if I supply month as a numeric value I just get a single coefficient that doesn't really work for my dataset (patterns form around parts of the academic year rather than calendar).

If the month part is a constant, then as trip_count gets very very large, the constant in the equation y = ax+b becomes inconsequential. It's almost as if I want something like y = ax + bx + c where a is the trip_count and b is a coefficient weighted on what the value of month is.

This is quite easy to do in R, I'd just run glm(bike$totalHireDuration ~ bike$tripCount:bike$month)

Here's some fake data to reproduce:

CREATE OR REPLACE MODEL
  my_model_name OPTIONS (model_type='linear_reg',
    input_label_cols =['total_hire_duration']) AS (
  SELECT
    CAST(EXTRACT(MONTH FROM DATE(start_date)) AS STRING) month,
    COUNT(*) trip_count,
    SUM(duration_sec) total_hire_duration
  FROM
    bigquery-public-data.san_francisco_bikeshare.bikeshare_trips
  GROUP BY
    date)

Any help would be greatly appreciated!



I made a tictactoe game but it is crashing once I click on an empty space

I made a tictactoe game but it is crashing once I click on an empty space.

I used an Arraylist to change the state of the index when the corresponding place is clicked in the tictactoe grid. For example, if I ticked in the top right cell in the grid the index 2 will change to 1 if the current player is 'O' or to 2 if the current player is 'X'.

There is a counter to track who is playing, if the remainder is 0 then 'O' is places or else 'X' is placed.

Also,I used a flag 'gstate' to stop the game when one player wins.

The problem is that in the beginning the game works but when it comes to any part where I make the checking which player is the winner the game crashes.

May anyone please help me.

This is the Main Jave code

package com.example.tictactoe;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
    
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
    
public class MainActivity extends AppCompatActivity {

    public int counter = 0;
    Toast msg;
    ImageView img, img2, img3, img4, img5, img6, img7, img8, img9;


    int o = 1;
    int x = 2;

    List<Integer> winner = new ArrayList<>(9);

    boolean owin, xwin = false;
    boolean gstate = true;

    //oOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO

    public void isOm() {
        if (counter % 2 != 0 && img5.getDrawable() != null) {
            winner.set(4, 1);
        } else {
        }
    }

    public void isOmr() {
        if (counter % 2 != 0 && img6.getDrawable() != null) {
            winner.set(5, 1);
        } else {
        }
    }

    public void isOml() {
        if (counter % 2 != 0 && img4.getDrawable() != null) {
            winner.set(3, 1);
        } else {
        }
    }

    public void isOru() {
        if (counter % 2 != 0 && img3.getDrawable() != null) {
            winner.set(2, 1);
        } else {
        }
    }

    public void isOmu() {
        if (counter % 2 != 0 && img2.getDrawable() != null) {
            winner.set(1, 1);
        } else {
        }
    }


    public void isOlu() {
        if (counter % 2 != 0 && img.getDrawable() != null) {
            winner.set(0, 1);
        } else {
        }
    }

    public void isOdr() {
        if (counter % 2 != 0 && img9.getDrawable() != null) {
            winner.set(8, 1);
        } else {
        }
    }

    public void isOmd() {
        if (counter % 2 != 0 && img8.getDrawable() != null) {
            winner.set(7, 1);
        } else {
        }
    }

    public void isOdl() {
        if (counter % 2 != 0 && img7.getDrawable() != null) {
            winner.set(6, 1);
        } else {
        }
    }

    //oOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO

    //xXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxX

    public void isXm() {
        if (counter % 2 == 0 && img5.getDrawable() != null) {
            winner.set(4, 2);
        } else {
        }
    }

    public void isXmr() {
        if (counter % 2 == 0 && img6.getDrawable() != null) {
            winner.set(5, 2);
        } else {
        }
    }

    public void isXml() {
        if (counter % 2 == 0 && img4.getDrawable() != null) {
            winner.set(3, 2);
        } else {
        }
    }

    public void isXru() {
        if (counter % 2 == 0 && img3.getDrawable() != null) {
            winner.set(2, 2);
        } else {
        }
    }

    public void isXmu() {
        if (counter % 2 == 0 && img2.getDrawable() != null) {
            winner.set(1, 2);
        } else {
        }
    }

    public void isXlu() {
        if (counter % 2 == 0 && img.getDrawable() != null) {
            winner.set(0, 2);
        } else {
        }
    }

    public void isXdr() {
        if (counter % 2 == 0 && img9.getDrawable() != null) {
            winner.set(8, 2);
        } else {
        }
    }

    public void isXmd() {
        if (counter % 2 == 0 && img8.getDrawable() != null) {
            winner.set(7, 2);
        } else {
        }
    }

    public void isXdl() {
        if (counter % 2 == 0 && img7.getDrawable() != null) {
            winner.set(6, 2);
        } else {
        }
    }


    //xXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxX

    public boolean oWin() {
        try {
           if(((img.getDrawable() != null) && (img2.getDrawable() != null) && (img3.getDrawable() != null) && ((int)winner.get(0) == 1) && ((int)winner.get(1) == 1) && ((int)winner.get(2) == 1)) || ((img4.getDrawable() != null) && (img5.getDrawable() != null) && (img6.getDrawable() != null) && ((int)winner.get(3) == 1) && ((int)winner.get(4) == 1) && ((int)winner.get(5) == 1)) || ((img7.getDrawable() != null) && (img8.getDrawable() != null) && (img9.getDrawable() != null) && ((int)winner.get(6) == 1) && ((int)winner.get(7) == 1) && ((int)winner.get(8) == 1)) || ((img.getDrawable() != null) && (img4.getDrawable() != null) && (img7.getDrawable() != null) && ((int)winner.get(0) == 1) && ((int)winner.get(3) == 1) && ((int)winner.get(6) == 1)) || ((img2.getDrawable() != null) && (img5.getDrawable() != null) && (img8.getDrawable() != null) && ((int)winner.get(1) == 1) && ((int)winner.get(4) == 1) && ((int)winner.get(7) == 1)) || ((img3.getDrawable() != null) && (img6.getDrawable() != null) && (img9.getDrawable() != null) && ((int)winner.get(2) == 1) && ((int)winner.get(5) == 1) && ((int)winner.get(8) == 1)) || ((img.getDrawable() != null) && (img5.getDrawable() != null) && (img9.getDrawable() != null) && ((int)winner.get(0) == 1) && ((int)winner.get(4) == 1) && ((int)winner.get(8) == 1)) || ((img3.getDrawable() != null) && (img5.getDrawable() != null) && (img7.getDrawable() != null) && ((int)winner.get(2) == 1) && ((int)winner.get(4) == 1) && ((int)winner.get(6) == 1))){
                owin = true;
            }
            return owin;
        }
        catch(Exception e) {
            //Toast.makeText(this,"An image is not here",Toast.LENGTH_SHORT).show();
            return owin;
        }
    }

    public boolean xWin() {
        try {
            if (((img.getDrawable() != null) && (img2.getDrawable() != null) && (img3.getDrawable() != null) && ((int)winner.get(0) == 2) && ((int)winner.get(1) == 2) && ((int)winner.get(2) == 2)) || ((img4.getDrawable() != null) && (img5.getDrawable() != null) && (img6.getDrawable() != null) && ((int)winner.get(3) == 2) && ((int)winner.get(4) == 2) && ((int)winner.get(5) == 2)) || ((img7.getDrawable() != null) && (img8.getDrawable() != null) && (img9.getDrawable() != null) && ((int)winner.get(6) == 2) && ((int)winner.get(7) == 2) && ((int)winner.get(8) == 2)) || ((img.getDrawable() != null) && (img4.getDrawable() != null) && (img7.getDrawable() != null) && ((int)winner.get(0) == 2) && ((int)winner.get(3) == 2) && ((int)winner.get(6) == 2)) || ((img2.getDrawable() != null) && (img5.getDrawable() != null) && (img8.getDrawable() != null) && ((int)winner.get(1) == 2) && ((int)winner.get(4) == 2) && ((int)winner.get(7) == 2)) || ((img3.getDrawable() != null) && (img6.getDrawable() != null) && (img9.getDrawable() != null) && ((int)winner.get(2) == 2) && ((int)winner.get(5) == 2) && ((int)winner.get(8) == 2)) || ((img.getDrawable() != null) && (img5.getDrawable() != null) && (img9.getDrawable() != null) && ((int)winner.get(0) == 2) && ((int)winner.get(4) == 2) && ((int)winner.get(8) == 2)) || ((img3.getDrawable() != null) && (img5.getDrawable() != null) && (img7.getDrawable() != null) && ((int)winner.get(2) == 2) && ((int)winner.get(4) == 2) && ((int)winner.get(6) == 2))){
                xwin = true;
            }
            return xwin;
        }
        catch(Exception e) {
            //Toast.makeText(this,"An image is not here",Toast.LENGTH_SHORT).show();
            return xwin;
        }
    }

    public void greset(View view) {
        counter = 0;
        //img = (ImageView) findViewById(R.id.imageView);
        img.setImageResource(0);
        //img2 = (ImageView) findViewById(R.id.imageView2);
        img2.setImageResource(0);
        //img3 = (ImageView) findViewById(R.id.imageView3);
        img3.setImageResource(0);
        //img4 = (ImageView) findViewById(R.id.imageView4);
        img4.setImageResource(0);
        //img5 = (ImageView) findViewById(R.id.imageView5);
        img5.setImageResource(0);
        //img6 = (ImageView) findViewById(R.id.imageView6);
        img6.setImageResource(0);
        //img7 = (ImageView) findViewById(R.id.imageView7);
        img7.setImageResource(0);
        //img8 = (ImageView) findViewById(R.id.imageView8);
        img8.setImageResource(0);
        //img9 = (ImageView) findViewById(R.id.imageView9);
        img9.setImageResource(0);
        gstate = true;
    }

    public void pgame(View view) {
        ImageView image = (ImageView) view;

        img = (ImageView) findViewById(R.id.imageView);
        img2 = (ImageView) findViewById(R.id.imageView2);
        img3 = (ImageView) findViewById(R.id.imageView3);
        img4 = (ImageView) findViewById(R.id.imageView4);
        img5 = (ImageView) findViewById(R.id.imageView5);
        img6 = (ImageView) findViewById(R.id.imageView6);
        img7 = (ImageView) findViewById(R.id.imageView7);
        img8 = (ImageView) findViewById(R.id.imageView8);
        img9 = (ImageView) findViewById(R.id.imageView9);

        if (image.getDrawable() != null) {
            msg = Toast.makeText(this, "Please select another space", Toast.LENGTH_SHORT);
            msg.show();
            if((ImageView)view == img){
                winner.set(0, 1);
            }
            else if((ImageView)view == img2){
                winner.set(1, 1);
            }
            else if((ImageView)view == img3){
                winner.set(2, 1);
            }
            else if((ImageView)view == img4){
                winner.set(3, 1);
            }
            else if((ImageView)view == img5){
                winner.set(4, 1);
            }
            else if((ImageView)view == img6){
                winner.set(5, 1);
            }
            else if((ImageView)view == img7){
                winner.set(6, 1);
            }
            else if((ImageView)view == img8){
                winner.set(7, 1);
            }
            else if((ImageView)view == img9){
                winner.set(8, 1);
            }
            else if((ImageView)view == img){
                winner.set(0, 2);
            }
            else if((ImageView)view == img2){
                winner.set(1, 2);
            }
            else if((ImageView)view == img3){
                winner.set(2, 2);
            }
            else if((ImageView)view == img4){
                winner.set(3, 2);
            }
            else if((ImageView)view == img5){
                winner.set(4, 2);
            }
            else if((ImageView)view == img6){
                winner.set(5, 2);
            }
            else if((ImageView)view == img7){
                winner.set(6, 2);
            }
            else if((ImageView)view == img8){
                winner.set(7, 2);
            }
            else if((ImageView)view == img9){
                winner.set(8, 2);
            }

            if (counter > 5 && counter < 9){
                this.xWin();
                this.oWin();
            }

            if (owin) {
                msg = Toast.makeText(this, "\'O\' is the winner, press the reset button", Toast.LENGTH_SHORT);
                msg.show();
                xwin = false;
                gstate = false;
            }

            if (xwin) {
                msg = Toast.makeText(this, "\'X\' is the winner, press the reset button", Toast.LENGTH_SHORT);
                msg.show();
                xwin = false;
                gstate = false;
            }

        }

        if (image.getDrawable() == null) {
            if (counter % 2 == 0) {
                image.setImageResource(R.drawable.o);
                counter += 1;

            } else {
                image.setImageResource(R.drawable.x);
                counter += 1;

            }

            image.setTranslationY(-1500);
            image.animate().translationYBy(1500).setDuration(500);




        }


    }



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

    }
}

The xml code is as following

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/cardview_light_background"
tools:context=".MainActivity">

<androidx.gridlayout.widget.GridLayout
    android:id="@+id/gridLayout"
    android:layout_width="420dp"
    android:layout_height="420dp"
    android:background="@drawable/grid"
    app:columnCount="3"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.555"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.733"
    app:rowCount="3">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="125dp"
        android:layout_height="125dp"
        android:onClick="pgame"
        app:layout_column="0"
        app:layout_row="0" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="125dp"
        android:layout_height="125dp"
        android:layout_marginLeft="22dp"
        android:onClick="pgame"
        app:layout_column="1"
        app:layout_row="0" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="125dp"
        android:layout_height="125dp"
        android:layout_marginLeft="18dp"
        android:onClick="pgame"
        app:layout_column="2"
        app:layout_row="0" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="125dp"
        android:layout_height="125dp"
        android:layout_marginTop="23dp"
        android:onClick="pgame"
        app:layout_column="0"
        app:layout_row="1" />

    <ImageView
        android:id="@+id/imageView5"
        android:layout_width="125dp"
        android:layout_height="125dp"
        android:layout_marginLeft="22dp"
        android:layout_marginTop="23dp"
        android:onClick="pgame"
        app:layout_column="1"
        app:layout_row="1" />

    <ImageView
        android:id="@+id/imageView6"
        android:layout_width="125dp"
        android:layout_height="125dp"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="23dp"
        android:onClick="pgame"
        app:layout_column="2"
        app:layout_row="1" />

    <ImageView
        android:id="@+id/imageView7"
        android:layout_width="125dp"
        android:layout_height="125dp"
        android:layout_marginTop="23dp"
        android:onClick="pgame"
        app:layout_column="0"
        app:layout_row="2" />

    <ImageView
        android:id="@+id/imageView8"
        android:layout_width="125dp"
        android:layout_height="125dp"
        android:layout_marginLeft="22dp"
        android:layout_marginTop="23dp"
        android:onClick="pgame"
        app:layout_column="1"
        app:layout_row="2" />

    <ImageView
        android:id="@+id/imageView9"
        android:layout_width="125dp"
        android:layout_height="125dp"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="23dp"
        android:onClick="pgame"
        app:layout_column="2"
        app:layout_row="2" />
</androidx.gridlayout.widget.GridLayout>

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="90dp"
    android:layout_marginBottom="45dp"
    android:onClick="greset"
    android:text="Reset"
    app:layout_constraintBottom_toTopOf="@+id/gridLayout"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0" />

</androidx.constraintlayout.widget.ConstraintLayout>


What is the matcher of any object of particular class in mockitokotlin2?

there is any() in mockitokotlin2 but it's any object. I need a matcher for any object of MyClass, like org.mockito.Matchers.any(MyClass::class.java)

is it possible?



Making HTTPS requests from ESP32

I am making a post request from my ESP32 S2 Kaluga kit. I have tested the HTTP request while running a server program in my LAN. I am using esp_http_client_handle_t and esp_http_client_config_t from esp_http_client.h to do this.

Now, I have a HTTPS api setup in AWS API gateway. I get following error with https now:

E (148961) esp-tls-mbedtls: No server verification option set in esp_tls_cfg_t structure. Check esp_tls API reference
E (148961) esp-tls-mbedtls: Failed to set client configurations, returned [0x8017] (ESP_ERR_MBEDTLS_SSL_SETUP_FAILED)
E (148971) esp-tls: create_ssl_handle failed
E (148981) esp-tls: Failed to open new connection
E (148981) TRANSPORT_BASE: Failed to open a new connection
E (148991) HTTP_CLIENT: Connection failed, sock < 0

How can I solve this? Thank you



Updating information within a list of objects with Flutter Hive

I am working with Hive for the first time to save data within flutter and am halfway there...

I have a list of weeks that I am saving within a box, and I am able to save those weeks successfully with:

  void addWeek({
    required double budget,
  }) {
    Week newWeek = Week(
      budget: budget,
    );

    listOfWeeks.add(newWeek);
    box.add(newWeek);
    notifyListeners();
  }

When I close the app and restart it I then can load all those saved weeks within the class constructor with:

@HiveType(typeId: 1)
class WeekList extends ChangeNotifier {
  WeekList() {
    int boxLength = box.length;
    for (var i = 0; i < boxLength; i++) {
      listOfWeeks.add(box.get(i));
    }
  }

What I am struggling with wrapping my head around is how to access the data and update the data within my list of weeks. The listOfWeeks holds a bunch of objects type Week which looks like this:

@HiveType(typeId: 2)
class Week extends ChangeNotifier {
  // Constructor
  Week({
    this.budget = 0.0,
  });

  //budget
  @HiveField(0)
  double budget = 0.0;
  @HiveField(1)
  String dailySpend = '\$71.43 per day';

  @HiveField(2)
  double totalSpent = 0.0;
  @HiveField(3)
  double percentLeftInBudget = 0.0;

  //Spent days of the week
  @HiveField(4)
  double sunday = 0.0;
  @HiveField(5)
  double monday = 0.0;
  @HiveField(6)
  double tuesday = 0.0;
  @HiveField(7)
  double wednesday = 0.0;
  @HiveField(8)
  double thursday = 0.0;
  @HiveField(9)
  double friday = 0.0;
  @HiveField(10)
  double saturday = 0.0;

I figure in all the update functions for all the values I need to use a box.put() but I can't seem to wrap my head around the syntax for this. WOuld it be something like:

  //updateBudget
  void updateBudget({required double newBudget, required int index}) {
    listOfWeeks[index].budget = newBudget;
    box.put(index,listOfWeeks[index].budget);
    notifyListeners();
  }

but then if I moved to the next update function for updating let's say the value of saturday I just cant use box.put(index,listOfWeeks[index].saturday);

I tried box.put(listOfWeeks[index]).budget to access the specific value but that doesn't seem to work. Any help would be greatly appreciated, thanks!



2022-03-25

Reach js-conflux-sdk git repo cannot be read when building from CI Docker container

The step in my Docker file which reads RUN yarn install --frozen-lockfile is failing with the following error text when executed in a .github action.

It reads as though there's a problem running git ls remote --tags --heads ssh://git@github.com/reach-sh/js-conflux-sdk.git which further seems to indicate that 'ssh: not found'

'ssh' is definitely present within the build environment, and the reach-sh/js-conflux-sdk repo is not private. I cannot reproduce this on my local machine. What am I missing?

#10 [builder 6/7] RUN yarn install
#10 sha256:0241e5ad2b01044255a03052e8f2a2540c5fb45a447a1b93c55b90ed86436440
#10 10.84 yarn install v1.22.17
#10 11.81 [1/4] Resolving packages...
#10 12.75 [2/4] Fetching packages...
#10 13.13 error Command failed.
#10 13.13 Exit code: 128
#10 13.13 Command: git
#10 13.13 Arguments: ls-remote --tags --heads ssh://git@github.com/reach-sh/js-conflux-sdk.git
#10 13.13 Directory: /apps/launchpad-api
#10 13.13 Output:
#10 13.13 "ssh" -oBatchMode=yes: line 1: ssh: not found
#10 13.13 fatal: Could not read from remote repository.
#10 13.13 
#10 13.13 Please make sure you have the correct access rights
#10 13.13 and the repository exists.
#10 13.13 info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
#10 ERROR: executor failed running [/bin/sh -c yarn install]: exit code: 128
------
 > [builder 6/7] RUN yarn install:
------
executor failed running [/bin/sh -c yarn install]: exit code: 128

I've attempted explicitly installing ssh into the build container which reported that ssh was already installed.

I've checked that git ls-remote --tags --heads ssh://git@github.com/reach-sh/js-conflux-sdk.git can be run from my local machine without any special permissions.

I've tried to delete and rebuild my yarn.lock file which didn't do anything at all differently.



When a method has no return statement, how do I print out it's return value?

EDITED.

I am learning about Linked Lists. For each process applied by a Method, it is printed out to the console. So, adding, removing, searching (i.e, displaying the result of a search), are all streamed to stdout, but I cannot seem to do this for the insertion Method even though the insert Method is executed.

Some Methods have a return statement, while others rely on the __repr__() for conversion to string, to then be streamed to the console. The insertion Method (not mine, but a course worked example) takes two arguments and does not have a return statement. The most consistent error message I get when attempting to print is TypeError: %d format: a real number is required, not NoneType, or TypeError: not enough arguments for format string, where I have replaced %d with %s.

What I do not understand is, why I am unable to display test data for the insert Method, while I can do so for all others. The code,

#!/usr/bin/env python3

class Node:
  data = None
  next_node = None

  def __init__(self, data):
    self.data = data

  def __repr__(self):
    return "<Node data: {}>".format(self.data)

# Linked List
class LinkedList:

  def __init__(self):
    self.head = None

  def is_empty(self):
    return self.head == None  # corrected

  def size(self):
    current = self.head
    count = 0

    while current:
      count += 1
      current = current.next_node

    return count

  # Adding a node
  def add(self, data):

    new_node = Node(data)
    new_node.next_node = self.head
    self.head = new_node
    

  # Searching the List
  def search(self, key):

    current = self.head

    while current:
      if current.data == key:
        return current
      else:
        current = current.next_node
    return None
  
  # Inserting into the List
  def insert(self, data, index):
    
    if index == 0:
      self.add(data)

    if index > 0:
      new_data = Node(data)

    position = index
    current = self.head

    while position > 1:
      current = current.next_node
      position -= 1

    past_node = current
    future_node = current.next_node

    past_node.next_node = new_data
    new_data = current.next_node

  # Removing a node from the List
  def remove(self, key):
    
    current = self.head
    previous = None
    found = False

    while current and not found:
      if current.data == key and current == self.head:
        found = True
        self.head = current.next_node
      elif current.data == key:
        found = True
        previous.next_node = current.next_node

    return current

  def __repr__(self):
    
    nodes = []
    current = self.head

    while current:
      if current is self.head:
        nodes.append("[Head: {}]".format(current.data))
      elif current.next_node is None:
        nodes.append("[Tail {}]".format(current.data))
      else:
        nodes.append("[{}]".format(current.data))

      current = current.next_node
    return '-> '.join(nodes)

Test output;

l = LinkedList()
l.add(1)
l.add(2)
l.add(3)
l.add(5)
l.add(6)
l.add(7)

length = l.size()
print("Size of list: {}".format(length))  # Size of list: 6

print(l)  # [Head: 7]-> [6]-> [5]-> [3]-> [2]-> [Tail: 1]

seek = l.search(7)
print("Found: {}".format(seek))  # Found: <Node data: 7>

between = l.insert(4, 3)
if between is not None:
  print(f"Inserted {between} at index {between}")
else:
  print("A problem with code") # A problem with code

gone = l.remove(1)
print("Removed: {}".format(gone))  # Removed: <Node data: 1>

# Note the insertion of '4' at index 3
print(l)  # [Head: 7]-> [6]-> [5]-> [4]-> [3]-> [Tail: 2]

THIS CODE WORKS!

Other variants of the print format have been tried f"{}", .format() and even an attempt at conversion to string str() was made, with no luck. Could someone explain exactly what the problem is (though, I believe it to be a NoneType issue) and how to resolve it?

I hope my question is clearer. Thank you.



Values of a vector to remain equal to another vector based on conditions

I'm using this dataset.

I want to create a variable named neg_gw_shock such that

neg_gw_shock = (-gw_level_dev) if gw_level_dev < 0 
neg_gw_shock =  NA if gw_level_dev >= 0

How can I do that?



How to update a progress Bar in QML by calculating the countdown on the C++ side in the QTWidget?

I basically want to send the progress from the c++ side to update the value of the ProgressBar on the QML size.

I am trying to integrate QML into a widget application. The thing is I have my mainwindwo.cpp file like this:

    MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QQmlContext *context = ui->quickWidget->rootContext();
    QString title = "Progress Bar App";
    int progress = 0;
    context->setContextProperty("_myString",title); //Set Text in QML that says Hello World

    timer = new QTimer(this);


    connect(timer, SIGNAL(timeout()), this, SLOT(myFunction()));
    timer->start(1000);

    progress = myFunction();
    context->setContextProperty("_myProgress", progress);
    if(progress == 100.0){
        timer->stop();
    }

    ui->quickWidget->setSource(QUrl("qrc:/main.qml"));
    ui->quickWidget->show();
}

MainWindow::~MainWindow()
{
    delete ui;
}

int MainWindow::myFunction(){
    //Calculate progress
    static uint16_t total_time = 50000;
    static uint16_t progress = 0;
    static uint16_t i = 0;
//    for(double i=0; i<=total_time; i=i+1000){

//        progress = ((i)*100)/total_time;
//        qDebug()<<"Progress: "<<progress<<endl;

//    }

    if(i < total_time){
        i = i + 1000;
                progress = ((i)*100)/total_time;
                qDebug()<<"Progress: "<<progress<<endl;
    }else{
        qDebug()<<"Finished: "<<progress<<endl;
    }

    return progress;

}

I want to send the progress to calculated here to the ProgressBar in QML side but I can't seem to get it to work.

My question is if you typically create a C++ class with a header and cpp files, how do you do the samething but instead use things in a QTWidget or the Mainwindow.cpp file and send data continuously from it to the QML file to update a ProgressBar?