问:
Read csv or json files that are written in Pyspark from Python?
In Pyspark, I use either df.write.json or ```ndf.write.csv to write a dataframe into csv/json files. Below is an example/</p>
```df.write.json("s3://bucket/folder/")
df.write.csv("s3://bucket/folder/")
```
<p>However, when I try to read these written files from Python, I keep getting the following error:</p>
```UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfa in position 1: invalid start byte
```
<p>I tried to use an specific encoding when I am writing these files, but didnt solve the issue. Here is an example:</p>
```df.write.csv("s3://bucket/folder/", header=True, escape='"', encoding="ISO-8859-1", sep=",")
```
<p>Here is my code for reading the files from python:</p>
```def read_multiple_csv(data_dir):
    data_files = glob(os.path.join(data_dir, "*.csv"))
    df = pd.concat((pd.read_csv(f, sep=",", encoding="ISO-8859-1", on_bad_lines='skip') for f in data_files), ignore_index=True)
    return df
```

I wonder if I am doing something wrong?

Body:
In Pyspark, I use either df.write.json or ```ndf.write.csv to write a dataframe into csv/json files. Below is an example/

df.write.json("s3://bucket/folder/")
df.write.csv("s3://bucket/folder/")

However, when I try to read these written files from Python, I keep getting the following error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfa in position 1: invalid start byte

I tried to use an specific encoding when I am writing these files, but didnt solve the issue. Here is an example:

df.write.csv("s3://bucket/folder/", header=True, escape='"', encoding="ISO-8859-1", sep=",")

Here is my code for reading the files from python:

def read_multiple_csv(data_dir):
    data_files = glob(os.path.join(data_dir, "*.csv"))
    df = pd.concat((pd.read_csv(f, sep=",", encoding="ISO-8859-1", on_bad_lines='skip') for f in data_files), ignore_index=True)
    return df

I wonder if I am doing something wrong?


来源: stackexchange

问:
Explanation for OpenCV resize functions' implementation
I trained my custom AI model in python, and I used OpenCV python binding to open and resizing images.

After training, I tried to do inference with test images, without using OpenCV.
That is, I tried to open and resize test images with PIL.image.
I appropriately considered some points, like color formatting, axis convention.
However, the onnx inference result for test images are quite nonsense,even considering model's performance.
So, I made below code snippet to check whether there exists any difference between OpenCV and Pillow's image resize policy.

```<code>import PIL
from PIL import Image
import cv2
import numpy as np

cvImg = cv2.imread("test.png")
cvImg = cv2.resize(cvImg, dsize= (200, 200), interpolation= cv2.INTER_LINEAR_EXACT)
cvImg = np.flip(cvImg, 2)

print(cvImg.shape)

pilImg = Image.open("test.png")
pilImg = pilImg.convert("RGB")
pilImg = pilImg.resize((200, 200), resample= PIL.Image.LINEAR)   #2 bilinear

pilNP = np.asarray(pilImg)

print(pilNP.shape)
diff = cvImg - pilNP

print(np.mean(diff))

cv2.namedWindow("CV", cv2.WINDOW_NORMAL)
cv2.namedWindow("PIL", cv2.WINDOW_NORMAL)
cv2.namedWindow("Diff", cv2.WINDOW_NORMAL)

cv2.imshow("CV", cvImg)
cv2.imshow("PIL", pilNP)
cv2.imshow("Diff", diff)

np.savetxt('cv0.out', cvImg[:, :, 0], delimiter=',', fmt='%.2e')
np.savetxt('cv1.out', cvImg[:, :, 1], delimiter=',', fmt='%.2e')
np.savetxt('cv2.out', cvImg[:, :, 2], delimiter=',', fmt='%.2e')

np.savetxt('PIL0.out', pilNP[:, :, 0], delimiter=',', fmt='%.2e')
np.savetxt('PIL1.out', pilNP[:, :, 1], delimiter=',', fmt='%.2e')
np.savetxt('PIL2.out', pilNP[:, :, 2], delimiter=',', fmt='%.2e')

while True:
    k = cv2.waitKey()
    if k == 32:
        flag += 1
    elif k == 27:
        exit()
</code>```

And the mean of difference between two resized image matrix was 63.06386666666667, which is quite considerable.

Also, the two resized images are looked quite similar, but the difference matrix has a lot of noise, which indicates two images has quite different pixel values.

I know what bilinear interpoliation is, but I'm quite confused which one among OpenCV and pillow is correct.
It seems that Pillow core module, which actually implements resizing function, is not publically opened.
Also, it's quite hard to dig into OpenCV's implemenation for resizing.

Looking for any help.
Thx in advance!

FYI )
There exists issue about this point, but there is no progress so far :https://github.com/python-pillow/Pillow/issues/2718

ContentLicense: CC BY-SA 4.0

Body:
I trained my custom AI model in python, and I used OpenCV python binding to open and resizing images.

After training, I tried to do inference with test images, without using OpenCV.
That is, I tried to open and resize test images with PIL.image.
I appropriately considered some points, like color formatting, axis convention.
However, the onnx inference result for test images are quite nonsense,even considering model's performance.
So, I made below code snippet to check whether there exists any difference between OpenCV and Pillow's image resize policy.

import PIL
from PIL import Image
import cv2
import numpy as np

cvImg = cv2.imread("test.png")
cvImg = cv2.resize(cvImg, dsize= (200, 200), interpolation= cv2.INTER_LINEAR_EXACT)
cvImg = np.flip(cvImg, 2)

print(cvImg.shape)

pilImg = Image.open("test.png")
pilImg = pilImg.convert("RGB")
pilImg = pilImg.resize((200, 200), resample= PIL.Image.LINEAR)   #2 bilinear

pilNP = np.asarray(pilImg)

print(pilNP.shape)
diff = cvImg - pilNP

print(np.mean(diff))

cv2.namedWindow("CV", cv2.WINDOW_NORMAL)
cv2.namedWindow("PIL", cv2.WINDOW_NORMAL)
cv2.namedWindow("Diff", cv2.WINDOW_NORMAL)

cv2.imshow("CV", cvImg)
cv2.imshow("PIL", pilNP)
cv2.imshow("Diff", diff)

np.savetxt('cv0.out', cvImg[:, :, 0], delimiter=',', fmt='%.2e')
np.savetxt('cv1.out', cvImg[:, :, 1], delimiter=',', fmt='%.2e')
np.savetxt('cv2.out', cvImg[:, :, 2], delimiter=',', fmt='%.2e')

np.savetxt('PIL0.out', pilNP[:, :, 0], delimiter=',', fmt='%.2e')
np.savetxt('PIL1.out', pilNP[:, :, 1], delimiter=',', fmt='%.2e')
np.savetxt('PIL2.out', pilNP[:, :, 2], delimiter=',', fmt='%.2e')

while True:
    k = cv2.waitKey()
    if k == 32:
        flag += 1
    elif k == 27:
        exit()

And the mean of difference between two resized image matrix was 63.06386666666667, which is quite considerable.

Also, the two resized images are looked quite similar, but the difference matrix has a lot of noise, which indicates two images has quite different pixel values.

I know what bilinear interpoliation is, but I'm quite confused which one among OpenCV and pillow is correct.
It seems that Pillow core module, which actually implements resizing function, is not publically opened.
Also, it's quite hard to dig into OpenCV's implemenation for resizing.

Looking for any help.
Thx in advance!

FYI )
There exists issue about this point, but there is no progress so far :https://github.com/python-pillow/Pillow/issues/2718


问:
Scripted requests to CloudFlare protected resource. Python
Firstly, I need to send requests to the API of the resource. The resource is protected by CloudFlare detecting system.

I cannot send any request. The response is 403 Forbidden.

No data, no cookies.

Firstly, the API request requires cookies in headers. I found the request that was sent to accept all cookies.

After that I copied the bash of request, switched off all headers and sent request through Insomnia. It returned me completed cookies.

When I send the identical request in code it returned me 403 Forbidden status and non-completed cookies.

After that I decided to check the difference between browser, Insomnia and Python requests. I used Fiddler4. Python request returned 200 OK when I send the request in Python and everything returns me completed cookies. But if I switch Fiddler off I have 403 status.

Result of sending Python request with Fiddler:
[200 OK]

```<code>__Host-ariregweb=g4q8icpEmmIdHnQmFSNsfHdNhLLsgISKE7XRzphrLiscb4pSIzrpRLm9aiLCHqXa; Domain=ariregister.rik.ee; HttpOnly; Path=/; SameSite=lax; Secure; __cf_bm=GIYOJNShc1kY79bPk7GG1U6T.jV6K4BG8DLQoc70NT8-1671428340-0-AcxNKFuuhvkmblvy/q4WPGEPezvLQUL8/k6NeylOmaX5awlf1L7eOWnc55DGMsyPzpv5YKUDL6w100KlzzjsJVE=; Domain=ariregister.rik.ee; expires=Mon, 19-Dec-22 06:09:00 GMT; HttpOnly; Path=/; SameSite=None; Secure; _cfuvid=0EIfdSb4ltpOgYzKuMthWVvN0x5L3kn_uCfhyvBEk34-1671428340155-0-604800000; Domain=ariregister.rik.ee; HttpOnly; Path=/; SameSite=None; Secure
</code>```

Result of sending Python request without Fiddler:
[403 Forbidden]

```<code>__cf_bm=0h8pprOoE6nOtjrZt6MYx6l7_4DIxIPn1_BL_e7Um2s-1671430063-0-AbvFUsYR8fOTT0NnrO1B4lJVTziYD+x2pnPLx1IyGjsgC29mqBNk+9iXhw2b1ewJiL2Cyi/iaTUilt6uPIbrSnw=; Domain=ariregister.rik.ee; expires=Mon, 19-Dec-22 06:37:43 GMT; HttpOnly; Path=/; SameSite=None; Secure
</code>```

Maybe someone had such kind of problem or has some ideas how to bypass it. Thanks a lot.

Body:
Firstly, I need to send requests to the API of the resource. The resource is protected by CloudFlare detecting system.

I cannot send any request. The response is 403 Forbidden.

No data, no cookies.

Firstly, the API request requires cookies in headers. I found the request that was sent to accept all cookies.

After that I copied the bash of request, switched off all headers and sent request through Insomnia. It returned me completed cookies.

When I send the identical request in code it returned me 403 Forbidden status and non-completed cookies.

After that I decided to check the difference between browser, Insomnia and Python requests. I used Fiddler4. Python request returned 200 OK when I send the request in Python and everything returns me completed cookies. But if I switch Fiddler off I have 403 status.

Result of sending Python request with Fiddler:
[200 OK]

__Host-ariregweb=g4q8icpEmmIdHnQmFSNsfHdNhLLsgISKE7XRzphrLiscb4pSIzrpRLm9aiLCHqXa; Domain=ariregister.rik.ee; HttpOnly; Path=/; SameSite=lax; Secure; __cf_bm=GIYOJNShc1kY79bPk7GG1U6T.jV6K4BG8DLQoc70NT8-1671428340-0-AcxNKFuuhvkmblvy/q4WPGEPezvLQUL8/k6NeylOmaX5awlf1L7eOWnc55DGMsyPzpv5YKUDL6w100KlzzjsJVE=; Domain=ariregister.rik.ee; expires=Mon, 19-Dec-22 06:09:00 GMT; HttpOnly; Path=/; SameSite=None; Secure; _cfuvid=0EIfdSb4ltpOgYzKuMthWVvN0x5L3kn_uCfhyvBEk34-1671428340155-0-604800000; Domain=ariregister.rik.ee; HttpOnly; Path=/; SameSite=None; Secure

Result of sending Python request without Fiddler:
[403 Forbidden]

__cf_bm=0h8pprOoE6nOtjrZt6MYx6l7_4DIxIPn1_BL_e7Um2s-1671430063-0-AbvFUsYR8fOTT0NnrO1B4lJVTziYD+x2pnPLx1IyGjsgC29mqBNk+9iXhw2b1ewJiL2Cyi/iaTUilt6uPIbrSnw=; Domain=ariregister.rik.ee; expires=Mon, 19-Dec-22 06:37:43 GMT; HttpOnly; Path=/; SameSite=None; Secure

Maybe someone had such kind of problem or has some ideas how to bypass it. Thanks a lot.


问:
Screen Sharing dialog box not closing after track.stop()
This Stack Over Flow got me solved problem on receiving the event after "Stop Sharing"  from dialog. But When I close the stream programmatically, "Stop Sharing" dialog box is not closing but stream got ended.</p>


问:
AttributeError: 'str' object has no attribute 'decode'`
I am trying to get the following MWE to work, however I get the following error:

words = getWords(sys.argv[1].decode(sys.stdin.encoding)) AttributeError: 'str' object has no attribute 'decode'

If I remove the decode part as suggested in other questions, it will throw a syntax error for

```<code>if words:
        ^
SyntaxError: invalid syntax
</code>```

I am uncertain as how to fix this in order to be able to receive the requested results.
Could anyone help me out here?

Thank you and sorry for the question!

```<code>#!/usr/bin/env python
# encoding: utf-8
import sys
import sqlite3
from collections import namedtuple

conn = sqlite3.connect("wnjpn.db")

Word = namedtuple('Word', 'wordid lang lemma pron pos')

def getWords(lemma):
  cur = conn.execute("select * from word where lemma=?", (lemma,))
  return [Word(*row) for row in cur]

def getWord(wordid):
  cur = conn.execute("select * from word where wordid=?", (wordid,))
  return Word(*cur.fetchone())

Sense = namedtuple('Sense', 'synset wordid lang rank lexid freq src')

def getSenses(word):
  cur = conn.execute("select * from sense where wordid=?", (word.wordid,))
  return [Sense(*row) for row in cur]

def getSense(synset, lang='jpn'):
  cur = conn.execute("select * from sense where synset=? and lang=?",
                     (synset,lang))
  row = cur.fetchone()
  return row and Sense(*row) or None

Synset = namedtuple('Synset', 'synset pos name src')

def getSynset(synset):
  cur = conn.execute("select * from synset where synset=?", (synset,))
  return Synset(*cur.fetchone())

SynLink = namedtuple('SynLink', 'synset1 synset2 link src')

def getSynLinks(sense, link):
  cur = conn.execute("select * from synlink where synset1=? and link=?",
                     (sense.synset, link))
  return [SynLink(*row) for row in cur]

def getSynLinksRecursive(senses, link, lang='jpn', _depth=0):
  for sense in senses:
    synLinks = getSynLinks(sense, link)
    if synLinks:
      print( ''.join([' '*2*_depth,
                     getWord(sense.wordid).lemma,
                     ' ',
                     getSynset(sense.synset).name]))
    _senses = []
    for synLink in synLinks:
      sense = getSense(synLink.synset2, lang)
      if sense:
        _senses.append(sense)

    getSynLinksRecursive(_senses, link, lang, _depth+1)

def getWordsFromSynset(synset, lang):
  cur = conn.execute("select word.* from sense, word where synset=? and word.lang=? and sense.wordid = word.wordid;", (synset,lang))
  return [Word(*row) for row in cur]

def getWordsFromSenses(sense, lang):
  for s in sense:
    print( getSynset(s.synset).name)
    syns = getWordsFromSynset(s.synset, lang)
    for sy in syns:
      print( '  ' + sy.lemma)

if __name__ == '__main__':
  if len(sys.argv)>=3:
    words = getWords(sys.argv[1].decode(sys.stdin.encoding))
    if words:
      for w in words:
        sense = getSenses(w)
        link = len(sys.argv)>=3 and sys.argv[2] or 'hypo'
        lang = len(sys.argv)==4 and sys.argv[3] or 'jpn'
        if link == 'syns':
          getWordsFromSenses(sense, lang)
        else:
          getSynLinksRecursive(sense, link, lang)
    else:
      print >>sys.stderr, "(nothing found)"
  else:
    print("usage: python jpWordnet.py ピラミッド syns")
</code>```

Body:
I am trying to get the following MWE to work, however I get the following error:

words = getWords(sys.argv[1].decode(sys.stdin.encoding)) AttributeError: 'str' object has no attribute 'decode'

If I remove the decode part as suggested in other questions, it will throw a syntax error for

if words:
        ^
SyntaxError: invalid syntax

I am uncertain as how to fix this in order to be able to receive the requested results.
Could anyone help me out here?

Thank you and sorry for the question!

#!/usr/bin/env python
# encoding: utf-8
import sys
import sqlite3
from collections import namedtuple

conn = sqlite3.connect("wnjpn.db")

Word = namedtuple('Word', 'wordid lang lemma pron pos')

def getWords(lemma):
  cur = conn.execute("select * from word where lemma=?", (lemma,))
  return [Word(*row) for row in cur]

def getWord(wordid):
  cur = conn.execute("select * from word where wordid=?", (wordid,))
  return Word(*cur.fetchone())

Sense = namedtuple('Sense', 'synset wordid lang rank lexid freq src')

def getSenses(word):
  cur = conn.execute("select * from sense where wordid=?", (word.wordid,))
  return [Sense(*row) for row in cur]

def getSense(synset, lang='jpn'):
  cur = conn.execute("select * from sense where synset=? and lang=?",
                     (synset,lang))
  row = cur.fetchone()
  return row and Sense(*row) or None

Synset = namedtuple('Synset', 'synset pos name src')

def getSynset(synset):
  cur = conn.execute("select * from synset where synset=?", (synset,))
  return Synset(*cur.fetchone())

SynLink = namedtuple('SynLink', 'synset1 synset2 link src')

def getSynLinks(sense, link):
  cur = conn.execute("select * from synlink where synset1=? and link=?",
                     (sense.synset, link))
  return [SynLink(*row) for row in cur]

def getSynLinksRecursive(senses, link, lang='jpn', _depth=0):
  for sense in senses:
    synLinks = getSynLinks(sense, link)
    if synLinks:
      print( ''.join([' '*2*_depth,
                     getWord(sense.wordid).lemma,
                     ' ',
                     getSynset(sense.synset).name]))
    _senses = []
    for synLink in synLinks:
      sense = getSense(synLink.synset2, lang)
      if sense:
        _senses.append(sense)

    getSynLinksRecursive(_senses, link, lang, _depth+1)

def getWordsFromSynset(synset, lang):
  cur = conn.execute("select word.* from sense, word where synset=? and word.lang=? and sense.wordid = word.wordid;", (synset,lang))
  return [Word(*row) for row in cur]

def getWordsFromSenses(sense, lang):
  for s in sense:
    print( getSynset(s.synset).name)
    syns = getWordsFromSynset(s.synset, lang)
    for sy in syns:
      print( '  ' + sy.lemma)

if __name__ == '__main__':
  if len(sys.argv)>=3:
    words = getWords(sys.argv[1].decode(sys.stdin.encoding))
    if words:
      for w in words:
        sense = getSenses(w)
        link = len(sys.argv)>=3 and sys.argv[2] or 'hypo'
        lang = len(sys.argv)==4 and sys.argv[3] or 'jpn'
        if link == 'syns':
          getWordsFromSenses(sense, lang)
        else:
          getSynLinksRecursive(sense, link, lang)
    else:
      print >>sys.stderr, "(nothing found)"
  else:
    print("usage: python jpWordnet.py ピラミッド syns")


问:
notification not received after clear the notification in ios using ionic framework
I am using Ionic Framework for my application. Local Notification is not receiving, once I clear the notification on my iPhone 8. I checked the notification settings and all are fine. I just receive vibration only, But notification is not received.

I am using the following code:

```<code>setInterval(()=>{
this.test=this.test+ 1;
let test1="test "+this.test;
    this.LocalNotificationss.schedule({
      id: 1,
      text: test1,
      //trigger:{at:new Date(new Date().getTime()+5)},
      badge:1,
      data: { secret: test1 }
    });
   },5000)
</code>```

Body:
I am using Ionic Framework for my application. Local Notification is not receiving, once I clear the notification on my iPhone 8. I checked the notification settings and all are fine. I just receive vibration only, But notification is not received.

I am using the following code:

setInterval(()=>{
this.test=this.test+ 1;
let test1="test "+this.test;
    this.LocalNotificationss.schedule({
      id: 1,
      text: test1,
      //trigger:{at:new Date(new Date().getTime()+5)},
      badge:1,
      data: { secret: test1 }
    });
   },5000)


问:
Hindi (Arial Unicode MS) fonts are not rendered in PDF on SERVER while export it from Telerik Report Designer
I used the hindi font named 'Arial Unicode MS' to show hindi font in PDF. But when I export it from telerik report to PDF programmatically. It will show hindi fonts in PDF on my LOCAL pc. but when i run it on online (SERVER) it will not show hindi fonts in PDF.

I installed Arial Unicode MS on local pc as well as on SERVER too.

I have done much R & D for this. I have not found any solution for this issue. I want that like local pc, hindi fonts should also be displayed online(SERVER).


问:
Is it possible to use freemarker as in tiles in struts2
We are trying to use freemarker in our project to remove tiles. What do I replace the followig tiles code with in freemarker -

```<code><tiles:insert page="/login/front.jsp" flush=true />
</code>```

I tried using <#include "/login.ftl"> but I am not getting the same look and feel as while using tiles.

ContentLicense: CC BY-SA 3.0

Body:
We are trying to use freemarker in our project to remove tiles. What do I replace the followig tiles code with in freemarker -

<tiles:insert page="/login/front.jsp" flush=true />

I tried using <#include "/login.ftl"> but I am not getting the same look and feel as while using tiles.


问:
How to move data from one collection to another while adding/removing some fields
I have made a change to my project by adding discriminators and I want to move the old collection rent-requests to requests while doing some name changes also to some fields. I am using a migration script to do this.

What is the best way to achieve this for large data (like 1000 record at least) ?


问:
How to disable/change the function of the share button while ar quicklook package for react-native?
While using the sample project to test AR Quicklook, the share button in AR Quicklook shares the entire 3D model as a file, is there any way in which model sharing can be stopped or altered?

The sample code for the same is in :
https://github.com/tgdevjs/rn-ar-quicklook

Tried to add canonical website for the same but I couldn't figure out how.I tried to alter the RNFileViewerManager.m    file, under react-native-file-viewer folder inside node_modules, but couldn't come up with any solution.


问:
How to make input line at the bottom of console using C#?
I want to make console like Minecraft server's one, where you see logs, and you can type in commands. I want see something like this this. I tried from another site, but still do not work. Maybe do it using events? But it will be too unefficient. Main wrong thing in my code is HandleInput(), I tried make it using lock, but it do not work. I need, to change the input line (with everything, that user enters) when there is a log in a console. I need to handle input(at the buttom of console), and "server" at one time(server sending output to console also).

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using CraftCoin;
using System.Threading;
using Snowy;
using Snowy.Data;
using Snowy.Server;

namespace LAVA2
{
    public static class ConsoleWriter
    {

        static object lockObject = new object();

        public static void WriteLine(string value) { lock (lockObject) { System.Console.WriteLine(value); } }

        public static void Write(string value) { lock (lockObject) { System.Console.Write(value); } }

        public static string ReadLine(string value) { lock (lockObject) { return System.Console.ReadLine(); } }

    }
    class Program
    {
        static SnowyServer snowy = new SnowyServer();

        static object locker = new object();
        static void Main(string[] args)
        {
            WriteLine("Starting server...");
            SnowyEvents events = new SnowyEvents();
            snowy.setEvents(events);
            List<SnowyPlugin> plugins = new List<SnowyPlugin> { new LavaPluginOnSnowy("LOLOLOLOL", events) };
            snowy.setPlugins(plugins);
            snowy.getPluginsAsSnowy().ForEach(delegate (SnowyPlugin plugin)
            {
                plugin.setServer(snowy);
            });
            snowy.getEvents().onPluginsLoad += CreateCoin;
            //Thread thread = new Thread(new ParameterizedThreadStart(HandleInput));
            Thread thread = new Thread(() => HandleInput(ref snowy, ref plugins));
            thread.Start();
            snowy.Start();
            thread.Join();
        }
        static void HandleInput(ref SnowyServer server, ref List<SnowyPlugin> plugins)
        {
            List<Command> commands = new List<Command> { new StopCommand(/*(SnowyServer)*/server), new RestartCommand(server, plugins) };
            CommandHandler handler = new CommandHandler(commands);
            while (server.getServerState() != SnowyServerState.Running)
            { Thread.Sleep(50); }
            while (true)
            {
                string result;
                lock (locker)
                {
                    Write("> ");
                    result = ReadLine();
                }
                string[] tmp = result.Split(' ');
                string[] arr = new string[tmp.Length - 1];
                for (int i = 0; i < tmp.Length; i++)
                {
                    if (i == 0) continue;
                    arr[i-1] = tmp[i];
                }
                handler.Run(tmp[0], arr);
            }
        }
        static void CreateCoin()
        {
            SnowCoin coin = new SnowCoin("SnowCoin", snowy);
            coin.BlockCoinState(Snowy.LAVA2.COIN_BLOCK_STATE.Permament_block);
            User user1 = new User(new Wallet("user1", "SnowCoin", 150), "UserName", "User1uid");
            User user2 = new User(new Wallet("user2", "SnowCoin"), "UserName", "User2uid");
            WriteLine($"{user1.getWallet().getWalletMoney()}\n---\n{user2.getWallet().getWalletMoney()}");
            UserSender userSender = new UserSender(user1, "user1");
            UserTarget userTarget = new UserTarget(user2, "user2");
            coin.SendCoins(ref userSender, ref userTarget, "", 100, new string[] { "user1", "user2" });
            user1 = new User(userSender.getWallet().toWallet("user1"), userSender.getUser());
            user2 = new User(userTarget.getWallet().toWallet("user2"), userTarget.getUser());
            WriteLine($"{user1.getWallet().getWalletMoney()}\n---\n{user2.getWallet().getWalletMoney()}");
        }
    }
}
</code>```

my output:

```<code>Starting server...
> YAY!
First tick!
tick №2!
tick №3!
tick №4!
tick №5!
stick №6!
tick №7!
tick №8!
ttick №9!
tick №10!
otick №11!
tick №12!
ptick №13!
tick №14!
tick №15!
tick №16!
tick №17!
tick №18!
tick №19!
tick №20!
tick №21!
tick №22!
tick №23!
</code>```

Expected output:

```<code>Starting server...
YAY!
First tick!
tick №2!
tick №3!
tick №4!
tick №5!
tick №6!
tick №7!
tick №8!
ttick №9!
tick №10!
tick №11!
tick №12!
tick №13!
tick №14!
tick №15!
tick №16!
tick №17!
tick №18!
tick №19!
tick №20!
tick №21!
tick №22!
tick №23!
> stop
</code>```

Body:
I want to make console like Minecraft server's one, where you see logs, and you can type in commands. I want see something like this this. I tried from another site, but still do not work. Maybe do it using events? But it will be too unefficient. Main wrong thing in my code is HandleInput(), I tried make it using lock, but it do not work. I need, to change the input line (with everything, that user enters) when there is a log in a console. I need to handle input(at the buttom of console), and "server" at one time(server sending output to console also).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using CraftCoin;
using System.Threading;
using Snowy;
using Snowy.Data;
using Snowy.Server;

namespace LAVA2
{
    public static class ConsoleWriter
    {

        static object lockObject = new object();

        public static void WriteLine(string value) { lock (lockObject) { System.Console.WriteLine(value); } }

        public static void Write(string value) { lock (lockObject) { System.Console.Write(value); } }

        public static string ReadLine(string value) { lock (lockObject) { return System.Console.ReadLine(); } }

    }
    class Program
    {
        static SnowyServer snowy = new SnowyServer();

        static object locker = new object();
        static void Main(string[] args)
        {
            WriteLine("Starting server...");
            SnowyEvents events = new SnowyEvents();
            snowy.setEvents(events);
            List<SnowyPlugin> plugins = new List<SnowyPlugin> { new LavaPluginOnSnowy("LOLOLOLOL", events) };
            snowy.setPlugins(plugins);
            snowy.getPluginsAsSnowy().ForEach(delegate (SnowyPlugin plugin)
            {
                plugin.setServer(snowy);
            });
            snowy.getEvents().onPluginsLoad += CreateCoin;
            //Thread thread = new Thread(new ParameterizedThreadStart(HandleInput));
            Thread thread = new Thread(() => HandleInput(ref snowy, ref plugins));
            thread.Start();
            snowy.Start();
            thread.Join();
        }
        static void HandleInput(ref SnowyServer server, ref List<SnowyPlugin> plugins)
        {
            List<Command> commands = new List<Command> { new StopCommand(/*(SnowyServer)*/server), new RestartCommand(server, plugins) };
            CommandHandler handler = new CommandHandler(commands);
            while (server.getServerState() != SnowyServerState.Running)
            { Thread.Sleep(50); }
            while (true)
            {
                string result;
                lock (locker)
                {
                    Write("> ");
                    result = ReadLine();
                }
                string[] tmp = result.Split(' ');
                string[] arr = new string[tmp.Length - 1];
                for (int i = 0; i < tmp.Length; i++)
                {
                    if (i == 0) continue;
                    arr[i-1] = tmp[i];
                }
                handler.Run(tmp[0], arr);
            }
        }
        static void CreateCoin()
        {
            SnowCoin coin = new SnowCoin("SnowCoin", snowy);
            coin.BlockCoinState(Snowy.LAVA2.COIN_BLOCK_STATE.Permament_block);
            User user1 = new User(new Wallet("user1", "SnowCoin", 150), "UserName", "User1uid");
            User user2 = new User(new Wallet("user2", "SnowCoin"), "UserName", "User2uid");
            WriteLine($"{user1.getWallet().getWalletMoney()}\n---\n{user2.getWallet().getWalletMoney()}");
            UserSender userSender = new UserSender(user1, "user1");
            UserTarget userTarget = new UserTarget(user2, "user2");
            coin.SendCoins(ref userSender, ref userTarget, "", 100, new string[] { "user1", "user2" });
            user1 = new User(userSender.getWallet().toWallet("user1"), userSender.getUser());
            user2 = new User(userTarget.getWallet().toWallet("user2"), userTarget.getUser());
            WriteLine($"{user1.getWallet().getWalletMoney()}\n---\n{user2.getWallet().getWalletMoney()}");
        }
    }
}

my output:

Starting server...
> YAY!
First tick!
tick №2!
tick №3!
tick №4!
tick №5!
stick №6!
tick №7!
tick №8!
ttick №9!
tick №10!
otick №11!
tick №12!
ptick №13!
tick №14!
tick №15!
tick №16!
tick №17!
tick №18!
tick №19!
tick №20!
tick №21!
tick №22!
tick №23!

Expected output:

Starting server...
YAY!
First tick!
tick №2!
tick №3!
tick №4!
tick №5!
tick №6!
tick №7!
tick №8!
ttick №9!
tick №10!
tick №11!
tick №12!
tick №13!
tick №14!
tick №15!
tick №16!
tick №17!
tick №18!
tick №19!
tick №20!
tick №21!
tick №22!
tick №23!
> stop


问:
I am unable to see Play2 option in Language and Frameworks in Intellij Community Edition
Play2 option is not available in Language and Frameworks section in Intellij Community Edition latest version.
I need to enable Play2 compiler for one project. But it is saying Play2 compiler disabled by default. And there is no way I can enable it in Intellij community edition. The option is not showing up in settings. Can somebody help here?Please click this for image screenshot
In the above image, play2 option not available in Language and Frameworks section. click this for another image taken from internet
I need this Play2 option to enable Play2 compiler for my project

I am using JDK8. But the Scala compile server recommend to use JDK17 by default for the project.

I have tried almost everything, but nothing has worked as of now.


问:
If the image file size is less than 50 kb, there is a 5 second delay in refresh the page
The goal is to apply a bounding box to the cam image and print it on the web.

python

```<code>cv.imwrite("rgb.jpg",rgb_img,[int(cv2.IMWRITE_JPEG_QUALITY),95]) //image size 53 kb
</code>```

javascript

```<code>function ref() {
    var url = "rgb.jpg";
    fetch(url, {cache: 'reload', mode: 'no-cors'})
    $('#refimg').attr('src',url);
    timerID = setTimeout("ref()", 1000);
}
</code>```

html

```<code><img style="-webkit-user-select: none;" width="300" height="200" id="refimg" alt="loading..." />
</code>```

This results in the latest image capture every second, but the size is large, causing problems such as blinking and truncated image.

So I reduced the image size.

```<code>cv.imwrite("rgb.jpg",rgb_img,[int(cv2.IMWRITE_JPEG_QUALITY),94]) //image size 48 kb
</code>```

However, when the image size is reduced to less than 50kb, the screen is updated every 5 seconds in the same JavaScript code.

```<code>cv.imwrite("rgb.webp",rgb_img,[int(cv2.IMWRITE_WEBP_QUALITY),80]) //image size 10 kb
</code>```

I've tried webp, png, and so on, but the moment it goes below 50kb, same happens.

Body:
The goal is to apply a bounding box to the cam image and print it on the web.

python

cv.imwrite("rgb.jpg",rgb_img,[int(cv2.IMWRITE_JPEG_QUALITY),95]) //image size 53 kb

javascript

function ref() {
    var url = "rgb.jpg";
    fetch(url, {cache: 'reload', mode: 'no-cors'})
    $('#refimg').attr('src',url);
    timerID = setTimeout("ref()", 1000);
}

html

This results in the latest image capture every second, but the size is large, causing problems such as blinking and truncated image.

So I reduced the image size.

cv.imwrite("rgb.jpg",rgb_img,[int(cv2.IMWRITE_JPEG_QUALITY),94]) //image size 48 kb

However, when the image size is reduced to less than 50kb, the screen is updated every 5 seconds in the same JavaScript code.

cv.imwrite("rgb.webp",rgb_img,[int(cv2.IMWRITE_WEBP_QUALITY),80]) //image size 10 kb

I've tried webp, png, and so on, but the moment it goes below 50kb, same happens.


问:
While dragging any widget ,can we drop same widget to multiple drag targets/positions
When we drag at once any widget and want to drop that same draggable widget to multiple places and on double tap it should release the draggable widget .

I want this to be done in flutter , i tried this but can achieve drop at one position only and grabbed object is released as soon we drop, but want to do at multiple position without releasing grabbed object until we double tap.


问:
Flutter Flask Push Notification issue
How can i show Push notification in Flutter app using Flask as server and my SQL as database, i wanna show notification in a flutter app when ever something new is added by admin in a specific table
Thank you

I haven't try anything yet because I'm unable to find proper solution of it

Title: Flutter Flask Push Notification issue


问:
convert Multer.File object to File object
convert multer object to file object

my response have multer object
and i need convert multer object to file object
what should i do?

multer object

Array.isArray(req.files) ? req.files.pop() : undefined;

```<code>[
  {
    fieldname: 'image',
    originalname: 'moon2.JPG',
    encoding: '7bit',
    mimetype: 'image/jpeg',
    buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 48 00 48 00 00 ff e1 29 7c 45 78 69 66 00 00 49 49 2a 00 08 00 00 00 0c 00 0f 01 02 00 06 00 00 00 9e 00 ... 282295 more bytes>,
    size: 282345
  }
]
</code>```

file object
enter image description here

i tried make binary string, base64 string, blob
but i cant make file object

try convert another types

```<code>const photoBuffer = test?.buffer as Buffer
const binaryPhoto = Buffer.from(photoBuffer).toString('binary')
const base64Photo = Buffer.from(binaryPhoto).toString('base64')
</code>```

Body:
convert multer object to file object

my response have multer object
and i need convert multer object to file object
what should i do?

multer object

Array.isArray(req.files) ? req.files.pop() : undefined;

[
  {
    fieldname: 'image',
    originalname: 'moon2.JPG',
    encoding: '7bit',
    mimetype: 'image/jpeg',
    buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 48 00 48 00 00 ff e1 29 7c 45 78 69 66 00 00 49 49 2a 00 08 00 00 00 0c 00 0f 01 02 00 06 00 00 00 9e 00 ... 282295 more bytes>,
    size: 282345
  }
]

file object
enter image description here

i tried make binary string, base64 string, blob
but i cant make file object

try convert another types

const photoBuffer = test?.buffer as Buffer
const binaryPhoto = Buffer.from(photoBuffer).toString('binary')
const base64Photo = Buffer.from(binaryPhoto).toString('base64')


问:
what is best way to implement Eventsource in android app
I was trying to connect SSE from android app but it have a problem.
It is not showing data 100%. Like in first attempt someone trigger notify command then it won't work but after that second attempt everybody get notify.
Here is my code:
//calling this code from activity on create

```<code>EventHandler eventHandler = new SimpleEventsListener();
    String url = String.format(ApiInterface.ENDPOINT + "notify/");
    EventSource.Builder builder = new EventSource.Builder(eventHandler, URI.create(url)).connectTimeoutMs(29 * 1000);

    try (EventSource eventSource = builder.build()) {
        for (; ; ) {
            eventSource.start();
            TimeUnit.SECONDS.sleep(30);
        }
    }
</code>```

here is EventSource implementation.

```<code>public class SimpleEventsListener implements EventHandler {

    @Override
    public void onOpen() throws Exception {
        System.out.println("SimpleEventsListener onOpen ");
    }

    @Override
    public void onClosed() throws Exception {
        System.out.println("SimpleEventsListener onClosed");
    }

    @Override
    public void onMessage(String event, MessageEvent messageEvent) throws Exception {
        System.out.println("SimpleEventsListener Event received " + messageEvent.getData());
        // here implemented data recieved code which coming from messageEvent.getData()
    }

    @Override
    public void onComment(String comment) throws Exception {
        System.out.println("SimpleEventsListener onComment");
    }

    @Override
    public void onError(Throwable t) {
        System.out.println("SimpleEventsListener onError: " + t);
    }

}
</code>```

What is the of best way to receive data on the first attempt too?

Body:
I was trying to connect SSE from android app but it have a problem.
It is not showing data 100%. Like in first attempt someone trigger notify command then it won't work but after that second attempt everybody get notify.
Here is my code:
//calling this code from activity on create

EventHandler eventHandler = new SimpleEventsListener();
    String url = String.format(ApiInterface.ENDPOINT + "notify/");
    EventSource.Builder builder = new EventSource.Builder(eventHandler, URI.create(url)).connectTimeoutMs(29 * 1000);

    try (EventSource eventSource = builder.build()) {
        for (; ; ) {
            eventSource.start();
            TimeUnit.SECONDS.sleep(30);
        }
    }

here is EventSource implementation.

public class SimpleEventsListener implements EventHandler {

    @Override
    public void onOpen() throws Exception {
        System.out.println("SimpleEventsListener onOpen ");
    }

    @Override
    public void onClosed() throws Exception {
        System.out.println("SimpleEventsListener onClosed");
    }

    @Override
    public void onMessage(String event, MessageEvent messageEvent) throws Exception {
        System.out.println("SimpleEventsListener Event received " + messageEvent.getData());
        // here implemented data recieved code which coming from messageEvent.getData()
    }

    @Override
    public void onComment(String comment) throws Exception {
        System.out.println("SimpleEventsListener onComment");
    }

    @Override
    public void onError(Throwable t) {
        System.out.println("SimpleEventsListener onError: " + t);
    }

}

What is the of best way to receive data on the first attempt too?


问:
noSuchElement exception for same element with same locators in mac, but it works fine in windows
I have written a simple code and also explicit and implicit wait for it (exact same code in mac & windows) and this code runs fine in windows, but makes no suchElement exception in mac. I tried multiple locator, but mac noSuchElement exception for all of them.

in windows:

```<code>@Test

public void testEyeLiner(){

WebDriverWait wait = new WebDriverWait(driver, 17);
        wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("site_search_input"))));
        WebElement searchInputBox = driver.findElement(By.id("site_search_input"));
        searchInputBox.sendKeys("eyeliner");
        searchInputBox.sendKeys(Keys.ENTER);

        wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//p[@data-at='number_of_products']"))));

        String searchResults = (driver.findElement(By.xpath("//p[@data-at='number_of_products']"))).getText();
        Assert.assertNotEquals(searchResults, "169 Results for “eyeliner”");
    }
}
</code>```

in mac:

```<code>@Test
public void testSearch() {
webDriverWait = new WebDriverWait(driver, 17);
    webDriverWait.until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector("#site_search_input"))));

    WebElement searchInputBox = driver.findElement(By.cssSelector("#site_search_input"));

    searchInputBox.sendKeys("eyeliner");
    searchInputBox.sendKeys(Keys.ENTER);

    webDriverWait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//p[@data-at='number_of_products']"))));
    String actualresult = driver.findElement(By.xpath("//p[@data-at='number_of_products']")).getText();

    Assert.assertEquals("result isn't as expected", "169 Results for “eyeliner”", actualresult);
}
</code>```

I tried multiple locators (css selector also), but all of them make noSuchElement exception in mac.

Body:
I have written a simple code and also explicit and implicit wait for it (exact same code in mac & windows) and this code runs fine in windows, but makes no suchElement exception in mac. I tried multiple locator, but mac noSuchElement exception for all of them.

in windows:

@Test

public void testEyeLiner(){

WebDriverWait wait = new WebDriverWait(driver, 17);
        wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("site_search_input"))));
        WebElement searchInputBox = driver.findElement(By.id("site_search_input"));
        searchInputBox.sendKeys("eyeliner");
        searchInputBox.sendKeys(Keys.ENTER);

        wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//p[@data-at='number_of_products']"))));

        String searchResults = (driver.findElement(By.xpath("//p[@data-at='number_of_products']"))).getText();
        Assert.assertNotEquals(searchResults, "169 Results for “eyeliner”");
    }
}

in mac:

@Test
public void testSearch() {
webDriverWait = new WebDriverWait(driver, 17);
    webDriverWait.until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector("#site_search_input"))));

    WebElement searchInputBox = driver.findElement(By.cssSelector("#site_search_input"));

    searchInputBox.sendKeys("eyeliner");
    searchInputBox.sendKeys(Keys.ENTER);

    webDriverWait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//p[@data-at='number_of_products']"))));
    String actualresult = driver.findElement(By.xpath("//p[@data-at='number_of_products']")).getText();

    Assert.assertEquals("result isn't as expected", "169 Results for “eyeliner”", actualresult);
}

I tried multiple locators (css selector also), but all of them make noSuchElement exception in mac.


问:
SQL telling me a column and expression are different data types
I am writing a program in pgadmin 4 using sql and when I try to insert data into a table, the error is telling me “column is of type Boolean but expression is of type integer” when I declared the variable in the create table as a Boolean.

I have no idea where to start


问:
Can't use passport.authenticate('local')
I posted question here cuz I my passport.authenticate('local') shows nothing, so I cannot use login function. I can activate singup api that I created, but somehow I cannot use my login api that I created as well.

Here is my code below.

```<code>var createError = require('http-errors');
var express = require('express');
var ejsMate = require('ejs-mate');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var config = require('./config')
var passport = require('passport')
// var session = require('express-session')

var homeRouter = require('./routes/home');
var usersRouter = require('./routes/users');

const mongoose = require('mongoose')

const url = config.mongoUrl
const connect = mongoose.connect(url)

connect.then((db) => {
  console.log('Connected correctly to server')
}, (err) => {console.log(err)})

var app = express();

// view engine setup
//GET, POST, DELETE, PUT
app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(passport.initialize())

//localhost:3000/
app.use('/', homeRouter);
//localhost:3000/users

app.use('/users', usersRouter);

app.use(express.static(path.join(__dirname, 'public')))

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
</code>```
```<code>var express = require('express');
const bodyParser = require('body-parser')
var User = require('../models/users')
var passport = require('passport')
var authenticate = require('../authenticate')

var router = express.Router();
router.use(bodyParser.json())

/* GET users listing. */
router.get('/', (req, res, next) => {
  console.log("HAHA")
  User.find({})
  .then((Users) => {
    res.statusCode = 200
    res.setHeader('Content-Type', 'application/json')
    res.json(Users)
  }, (err) => next(err))
  .catch((err) => next(err))
});

router.post('/signup', (req, res, next) => {
  User.register(new User({username: req.body.username}),
  req.body.password, (err, user) => {
    if(err) {
      res.statusCode = 500;
      res.setHeader('Content-Type', 'application/json');
      res.json({err: err});
    }
    else {
      if(req.body.firstname)
        user.firstname = req.body.firstname
      if(req.body.lastname)
        user.lastname = req.body.lastname
      user.save((err, user) => {
        if(err) {
          res.statusCode = 500;
          res.setHeader('Content-Type', 'application/json');
          res.json({err: err});
          return;
        }
        passport.authenticate('local')(req, res, () => {
          res.statusCode = 200;
          res.setHeader('Content-Type', 'application/json');
          res.json({success: true, status: 'Registration Successful!'});
        })
      })
    }
  })
});

router.post('/login', passport.authenticate('local'), (req, res) => {
  var token = authenticate.getToken({_id: req.user._id});
  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  res.json({success: true, token: token, status: 'You are successfully logged in!'});
})

router.get('/logout', (req, res, next) => {
  console.log(req.session)
  if (req.session) {
    req.session.destroy();
    res.clearCookie('session-id');
    res.redirect('/');
  }
  else {
    var err = new Error('You are not logged in!');
    err.status = 403;
    next(err);
  }
});

module.exports = router;
</code>```

router.post('/login', passport.authenticate('local') ---> show nothing it keep showing me an error

I need some advice and help.

Body:
I posted question here cuz I my passport.authenticate('local') shows nothing, so I cannot use login function. I can activate singup api that I created, but somehow I cannot use my login api that I created as well.

Here is my code below.

var createError = require('http-errors');
var express = require('express');
var ejsMate = require('ejs-mate');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var config = require('./config')
var passport = require('passport')
// var session = require('express-session')

var homeRouter = require('./routes/home');
var usersRouter = require('./routes/users');

const mongoose = require('mongoose')

const url = config.mongoUrl
const connect = mongoose.connect(url)

connect.then((db) => {
  console.log('Connected correctly to server')
}, (err) => {console.log(err)})

var app = express();

// view engine setup
//GET, POST, DELETE, PUT
app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(passport.initialize())

//localhost:3000/
app.use('/', homeRouter);
//localhost:3000/users

app.use('/users', usersRouter);

app.use(express.static(path.join(__dirname, 'public')))

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

var express = require('express');
const bodyParser = require('body-parser')
var User = require('../models/users')
var passport = require('passport')
var authenticate = require('../authenticate')

var router = express.Router();
router.use(bodyParser.json())

/* GET users listing. */
router.get('/', (req, res, next) => {
  console.log("HAHA")
  User.find({})
  .then((Users) => {
    res.statusCode = 200
    res.setHeader('Content-Type', 'application/json')
    res.json(Users)
  }, (err) => next(err))
  .catch((err) => next(err))
});

router.post('/signup', (req, res, next) => {
  User.register(new User({username: req.body.username}),
  req.body.password, (err, user) => {
    if(err) {
      res.statusCode = 500;
      res.setHeader('Content-Type', 'application/json');
      res.json({err: err});
    }
    else {
      if(req.body.firstname)
        user.firstname = req.body.firstname
      if(req.body.lastname)
        user.lastname = req.body.lastname
      user.save((err, user) => {
        if(err) {
          res.statusCode = 500;
          res.setHeader('Content-Type', 'application/json');
          res.json({err: err});
          return;
        }
        passport.authenticate('local')(req, res, () => {
          res.statusCode = 200;
          res.setHeader('Content-Type', 'application/json');
          res.json({success: true, status: 'Registration Successful!'});
        })
      })
    }
  })
});

router.post('/login', passport.authenticate('local'), (req, res) => {
  var token = authenticate.getToken({_id: req.user._id});
  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  res.json({success: true, token: token, status: 'You are successfully logged in!'});
})

router.get('/logout', (req, res, next) => {
  console.log(req.session)
  if (req.session) {
    req.session.destroy();
    res.clearCookie('session-id');
    res.redirect('/');
  }
  else {
    var err = new Error('You are not logged in!');
    err.status = 403;
    next(err);
  }
});

module.exports = router;

router.post('/login', passport.authenticate('local') ---> show nothing it keep showing me an error

I need some advice and help.


问:
GRPC with JavaScript Client?
Hello I m trying to find ref for GRPC with JavaScript Client.
I checked tried to search but is generally refer Node Library.

In my implementation I have .NET GRPC server and have react UI app
so just want to check is GRPC client support  JavaScript as client
or do we have any ref for GRPC for react.js.

as client I want to use grpc with JavaScript or react.js

Title: GRPC with JavaScript Client?


问:
Hot Reload not working Visual Studio 2022
I am working on an ASP.NET core MVC project. I want to enable Hot Reload on my Razor Pages. I keep getting the following error once I make a change to a .cshtml file under Views/Controller and save it.

My Hot Reload Settings

I'm starting the app without debugging. How do I get Hot Reload to work ?


问:
Minimize json for better readability
I have json which contains more than 6000 lines. I want to make it more readable. As you can see the json structure below there are some commn stuff present in all the enviroments ('commonA', 'commonB') , is there any way to manage common stuff in another file and variable stuff in separate files (so that readability improves) and finally we can link those files here in the main file to complete this structure.

Json Structure

```<code>{
    "feature": {
        "dev":{
            "commonA": {},
            "commonB": {},
            "variableDev": {}
        },
        "stage":{
            "commonA": {},
            "commonB": {},
            "variableStage": {}
        },
        "local":{
            "commonA": {},
            "commonB": {},
            "variablelocal": {}
        },
        "prod":{
            "commonA": {},
            "commonB": {},
            "variableProd": {}
        }
    }
}
</code>```

common json present in single file and variable json present in different files and somehow we can link those files to main file to complete the original sturcture.

Title: Minimize json for better readability

Body:
I have json which contains more than 6000 lines. I want to make it more readable. As you can see the json structure below there are some commn stuff present in all the enviroments ('commonA', 'commonB') , is there any way to manage common stuff in another file and variable stuff in separate files (so that readability improves) and finally we can link those files here in the main file to complete this structure.

Json Structure

{
    "feature": {
        "dev":{
            "commonA": {},
            "commonB": {},
            "variableDev": {}
        },
        "stage":{
            "commonA": {},
            "commonB": {},
            "variableStage": {}
        },
        "local":{
            "commonA": {},
            "commonB": {},
            "variablelocal": {}
        },
        "prod":{
            "commonA": {},
            "commonB": {},
            "variableProd": {}
        }
    }
}

common json present in single file and variable json present in different files and somehow we can link those files to main file to complete the original sturcture.


问:
Serving multiple mbtiles that have the same style
I'm generating a few mbtiles with TileMaker, using the exact same configuration:

test1.mbtiles

test2.mbtiles

Those tiles have a source-layer=poi.

I would like to serve them, without merging them beforehand (as I'm planning to have a mbtiles/country) with tileserver-gl, using maplibre-gl-js.

For that, I'm using a style.json that will eventually contains a bunch of layers, with some layers based on the POIs:

```<code>{
  "version": 8,
  "name": "OSM Bright",
  "layers": [
    {
        "id": "poi_z15",
        "type": "symbol",
        "source": "tests",
        "source-layer": "poi",
        "minzoom": 15,
        xxxxx,
     },
     {
        "id": "poi_z16",
        "type": "symbol",
        "source": "tests",
        "source-layer": "poi",
        "minzoom": 16,
        xxxxx,
     },

</code>```

Those layers, are based on "source-layer": "poi" and should work for both mbtiles (test1 and test2). The problem is that the layer definition requests a source, that I've tagged "source": "tests" in this example.

How, in this style, do you link both mbtiles ?
If I do

```<code>...
"sources": {
    "tests": {
      "type": "vector",
      "url": "mbtiles://test1.mbtiles"
    },
...
</code>```

It will work for the mbtiles test1. Now if I want to add the second mbtiles test2, the only way I've found so far is to create a new source, hence my style would become

```<code>...
"sources": {
    "test1": {
      "type": "vector",
      "url": "mbtiles://test1.mbtiles"
    },
    "test2": {
      "type": "vector",
      "url": "mbtiles://test2.mbtiles"
    },
...
</code>```

and in that case I need to duplicate my layers as:

```<code>{
 ...
  "layers": [
    {
        "id": "poi_z15",
        "type": "symbol",
        "source": "test1",
        "source-layer": "poi",
        "minzoom": 15,
        xxxxx,
     },
     {
        "id": "poi_z16",
        "type": "symbol",
        "source": "test1",
        "source-layer": "poi",
        "minzoom": 16,
        xxxxx,
     },
{
        "id": "poi_z15",
        "type": "symbol",
        "source": "test2",
        "source-layer": "poi",
        "minzoom": 15,
        xxxxx,
     },
     {
        "id": "poi_z16",
        "type": "symbol",
        "source": "test2",
        "source-layer": "poi",
        "minzoom": 16,
        xxxxx,
     },

</code>```

If I have 100 mbtiles, it would mean that I would need to duplicate 100 times those layers specifications.

Is there a way to do something like:

```<code>...
"sources": {
    "tests": [{
      "type": "vector",
      "url": "mbtiles://test1.mbtiles"
    },
    {
      "type": "vector",
      "url": "mbtiles://test2.mbtiles"
    }]

...
</code>```

or

```<code>...
"sources": {
    "tests": {
      "type": "vector",
      "url": ["mbtiles://test1.mbtiles", "mbtiles://test2.mbtiles"]
    }

...
</code>```

Obviously both solutions above don't work.
Thanks in advance for your feedbacks!

Body:
I'm generating a few mbtiles with TileMaker, using the exact same configuration:

test1.mbtiles

test2.mbtiles

Those tiles have a source-layer=poi.

I would like to serve them, without merging them beforehand (as I'm planning to have a mbtiles/country) with tileserver-gl, using maplibre-gl-js.

For that, I'm using a style.json that will eventually contains a bunch of layers, with some layers based on the POIs:

{
  "version": 8,
  "name": "OSM Bright",
  "layers": [
    {
        "id": "poi_z15",
        "type": "symbol",
        "source": "tests",
        "source-layer": "poi",
        "minzoom": 15,
        xxxxx,
     },
     {
        "id": "poi_z16",
        "type": "symbol",
        "source": "tests",
        "source-layer": "poi",
        "minzoom": 16,
        xxxxx,
     },

Those layers, are based on "source-layer": "poi" and should work for both mbtiles (test1 and test2). The problem is that the layer definition requests a source, that I've tagged "source": "tests" in this example.

How, in this style, do you link both mbtiles ?
If I do

...
"sources": {
    "tests": {
      "type": "vector",
      "url": "mbtiles://test1.mbtiles"
    },
...

It will work for the mbtiles test1. Now if I want to add the second mbtiles test2, the only way I've found so far is to create a new source, hence my style would become

...
"sources": {
    "test1": {
      "type": "vector",
      "url": "mbtiles://test1.mbtiles"
    },
    "test2": {
      "type": "vector",
      "url": "mbtiles://test2.mbtiles"
    },
...

and in that case I need to duplicate my layers as:

{
 ...
  "layers": [
    {
        "id": "poi_z15",
        "type": "symbol",
        "source": "test1",
        "source-layer": "poi",
        "minzoom": 15,
        xxxxx,
     },
     {
        "id": "poi_z16",
        "type": "symbol",
        "source": "test1",
        "source-layer": "poi",
        "minzoom": 16,
        xxxxx,
     },
{
        "id": "poi_z15",
        "type": "symbol",
        "source": "test2",
        "source-layer": "poi",
        "minzoom": 15,
        xxxxx,
     },
     {
        "id": "poi_z16",
        "type": "symbol",
        "source": "test2",
        "source-layer": "poi",
        "minzoom": 16,
        xxxxx,
     },

If I have 100 mbtiles, it would mean that I would need to duplicate 100 times those layers specifications.

Is there a way to do something like:

...
"sources": {
    "tests": [{
      "type": "vector",
      "url": "mbtiles://test1.mbtiles"
    },
    {
      "type": "vector",
      "url": "mbtiles://test2.mbtiles"
    }]

...

or

...
"sources": {
    "tests": {
      "type": "vector",
      "url": ["mbtiles://test1.mbtiles", "mbtiles://test2.mbtiles"]
    }

...

Obviously both solutions above don't work.
Thanks in advance for your feedbacks!


问:
Swift swipe right to dismiss present last vc
I am trying to implement a drag right to dismiss method and I already have found a way to drag right to either dismiss the vc or stay on the current vc depending on the current swipe amount. The issue I am facing is that the previous viewcontoller that presented this vc is not being presented while the current view controller is being swiped. Is there any way to add this feature while not making the app crash easily or take more time to load? Thanks!

```<code>class ViewController: UIViewController {
    var viewTranslation = CGPoint(x: 0, y: 0)
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handleDismiss)))
    }

}

extension ViewController {

    @objc func handleDismiss(sender: UIPanGestureRecognizer) {
        switch sender.state {
        case .changed:
            viewTranslation = sender.translation(in: view)
            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                self.view.transform = CGAffineTransform(translationX: self.viewTranslation.x, y: 0)
            })

        case .ended:
            if 200 > viewTranslation.x {
                UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                    self.view.transform = .identity
                })
            } else {
                dismiss(animated: true, completion: nil)
            }
        default:
            break
        }
    }
}
</code>```

I have tried this but will need to modify the code to function properly.

Body:
I am trying to implement a drag right to dismiss method and I already have found a way to drag right to either dismiss the vc or stay on the current vc depending on the current swipe amount. The issue I am facing is that the previous viewcontoller that presented this vc is not being presented while the current view controller is being swiped. Is there any way to add this feature while not making the app crash easily or take more time to load? Thanks!

class ViewController: UIViewController {
    var viewTranslation = CGPoint(x: 0, y: 0)
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handleDismiss)))
    }

}

extension ViewController {

    @objc func handleDismiss(sender: UIPanGestureRecognizer) {
        switch sender.state {
        case .changed:
            viewTranslation = sender.translation(in: view)
            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                self.view.transform = CGAffineTransform(translationX: self.viewTranslation.x, y: 0)
            })

        case .ended:
            if 200 > viewTranslation.x {
                UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                    self.view.transform = .identity
                })
            } else {
                dismiss(animated: true, completion: nil)
            }
        default:
            break
        }
    }
}

I have tried this but will need to modify the code to function properly.


问:
If we deploy the AWS EKS worker node groups in a single AWS Availability Zone (AZ). How much it will help us to save money
As we know EKS automatically manages the availability and scalability of the Kubernetes control plane nodes. And somehow i manage to deploy worker node groups in a single AWS Availability Zone (AZ. Now I want to know how it would help me to reduce cost. and how much it reduce.

As we know EKS automatically manages the availability and scalability of the Kubernetes control plane nodes. And somehow i manage to deploy worker node groups in a single AWS Availability Zone (AZ. Now I want to know how it would help me to reduce cost. and how much it reduce.


问:
How to filter a comma separated string in Django Rest Framework with iexact?
artist:

```<code>{mehedi alam, golam}, {golam, mehedi alam, zissan}, {mehedi}, {mehedi, golam, zissan}, {golam, sakib, mehedi}
</code>```

I want to filter with only "mehedi" artist.

```<code>class TrackListFilter(django_filters.FilterSet):
       artist = django_filters.CharFilter(method="artist_filter")

      def artist_filter(self, queryset, name, value):
           query = Q()
           for artist in value.split(", "):
               query |= Q(artist__iexact=artist) | Q(artist__iexact=artist + ', ') | Q(
                   artist__iexact=', ' + artist + ', ') | Q(artist__iexact=', ' + artist)
           return queryset.filter(query)
</code>```

Here I only received {mehedi} as output.
My expected output:

```<code>{mehedi}, {mehedi, golam, zissan}, {golam, sakib, mehedi}
</code>```

Body:
artist:

{mehedi alam, golam}, {golam, mehedi alam, zissan}, {mehedi}, {mehedi, golam, zissan}, {golam, sakib, mehedi}

I want to filter with only "mehedi" artist.

class TrackListFilter(django_filters.FilterSet):
       artist = django_filters.CharFilter(method="artist_filter")

      def artist_filter(self, queryset, name, value):
           query = Q()
           for artist in value.split(", "):
               query |= Q(artist__iexact=artist) | Q(artist__iexact=artist + ', ') | Q(
                   artist__iexact=', ' + artist + ', ') | Q(artist__iexact=', ' + artist)
           return queryset.filter(query)

Here I only received {mehedi} as output.
My expected output:

{mehedi}, {mehedi, golam, zissan}, {golam, sakib, mehedi}


问:
Add a new line in a
I am trying to put a newline in an editable  element when Alt+Enter is pressed. I am not quite sure what I am doing wrong in the below code.

```<code>_onkeydown: function(e) {
            let which = e.which;
            if(which === 13) {
                if(e.altKey) {
                    console.log(e);
                    console.log("Alt+Enter");
                    mytdelement.textContent += "\n" + " ddd";//String.fromCharCode(which);
                } else {
                    e.preventDefault();
                    //Do somethig else
                }
            }
        },
</code>```

I have to override the default enter behaviour, so when the user presses Alt+Enter, that should add a new line as the Enter keypress would have done.

Title: Add a new line in a <td>

Body:
I am trying to put a newline in an editable  element when Alt+Enter is pressed. I am not quite sure what I am doing wrong in the below code.

_onkeydown: function(e) {
            let which = e.which;
            if(which === 13) {
                if(e.altKey) {
                    console.log(e);
                    console.log("Alt+Enter");
                    mytdelement.textContent += "\n" + " ddd";//String.fromCharCode(which);
                } else {
                    e.preventDefault();
                    //Do somethig else
                }
            }
        },

I have to override the default enter behaviour, so when the user presses Alt+Enter, that should add a new line as the Enter keypress would have done.


问:
What is the difference between Comparison and Non-Comparison Sorting Algorithms?
If anyone know the difference between Comparison and Non-Comparison Sorting Algorithms. Then please give me the answer.</p>


问:
In a given XML File, you have to combine all the repetitive XML tag values into a single tag with a comma separator
There will be a sample xml file with in which inside the repetitive transaction tag, key and value elements are there , in this problem we need to concatenate all the key values in the transaction ID element with a and value to transaction type element with a comma separator</p>
```<code>Using java or any other language convert the given xml input into a desired output
for example:
1. we have to convert below xml into
<TransactidonType>
    <Transaction>
        <Key>278</Key>
        <Value>005010X217</Value>
    </Transaction>
    <Transaction>
        <Key>270</Key>
        <Value>005010X279A1</Value>
    </Transaction>
    <Transaction>
        <Key>271</Key>
        <Value>005010X279A1</Value>
    </Transaction>
</TransactionType>
</code>```
```<code>Output XML Should look like this
<TransactionOutput>
    <Transaction>
        <TransactionID>278,270,271</TransactionID>
        <TransactionType>005010X217,005010X279A1,005010X279A1</TransactionType>
    </Transaction>
</TransactionOutput>
</code>```
```<code></code>```

Body:
There will be a sample xml file with in which inside the repetitive transaction tag, key and value elements are there , in this problem we need to concatenate all the key values in the transaction ID element with a and value to transaction type element with a comma separator

Using java or any other language convert the given xml input into a desired output
for example:
1. we have to convert below xml into
<TransactidonType>
    <Transaction>
        <Key>278</Key>
        <Value>005010X217</Value>
    </Transaction>
    <Transaction>
        <Key>270</Key>
        <Value>005010X279A1</Value>
    </Transaction>
    <Transaction>
        <Key>271</Key>
        <Value>005010X279A1</Value>
    </Transaction>
</TransactionType>

Output XML Should look like this
<TransactionOutput>
    <Transaction>
        <TransactionID>278,270,271</TransactionID>
        <TransactionType>005010X217,005010X279A1,005010X279A1</TransactionType>
    </Transaction>
</TransactionOutput>


问:
How can I save the downloaded and converted audios to a specific folder
I'm trying to download Videos from a specific playlist and converting it to a m4a file for further downloading. The process works perfectly but the files are being saved in the same folder where my Phyton script is located. I choose a specific Output Folder but the files don't appear there.
Any ways to save the files in the desired folder?

An error message reads as follows: "input.mp4: No such file or directory"
In my Code block, I censored the playlist link and the user name on the path. Just imagine a working playlist link instead. Thanks in advance!

```<code>import os
import subprocess
</code>```

Replace <PLAYLIST_URL> with the URL of the YouTube playlist

playlist_url = "PLAYLISTLINK"

Set the output directory for the downloaded files

output_dir = "/Users/USER/Documents/VideoBot/Output"

Use youtube-dl to download the latest video in the playlist

subprocess.run(["youtube-dl", "-f", "bestaudio[ext=m4a]", "--playlist-start", "1", "--playlist-end", "1", playlist_url])

Extract the audio from the downloaded video using ffmpeg

subprocess.run(["ffmpeg", "-i", "input.mp4", "-vn", "-acodec", "copy", "output.m4a"])

Move the extracted audio file to the output directory

os.rename("output.m4a", os.path.join(output_dir, "output.m4a"))

Body:
I'm trying to download Videos from a specific playlist and converting it to a m4a file for further downloading. The process works perfectly but the files are being saved in the same folder where my Phyton script is located. I choose a specific Output Folder but the files don't appear there.
Any ways to save the files in the desired folder?

An error message reads as follows: "input.mp4: No such file or directory"
In my Code block, I censored the playlist link and the user name on the path. Just imagine a working playlist link instead. Thanks in advance!

import os
import subprocess

Replace <PLAYLIST_URL> with the URL of the YouTube playlist

playlist_url = "PLAYLISTLINK"

Set the output directory for the downloaded files

output_dir = "/Users/USER/Documents/VideoBot/Output"

Use youtube-dl to download the latest video in the playlist

subprocess.run(["youtube-dl", "-f", "bestaudio[ext=m4a]", "--playlist-start", "1", "--playlist-end", "1", playlist_url])

Extract the audio from the downloaded video using ffmpeg

subprocess.run(["ffmpeg", "-i", "input.mp4", "-vn", "-acodec", "copy", "output.m4a"])

Move the extracted audio file to the output directory

os.rename("output.m4a", os.path.join(output_dir, "output.m4a"))


问:
App is not get connected to the NodeJS server , after a build successful in React Native
Here is NodeJS , which shows No apps connected

android/build.gradle

```<code>buildscript {
    ext {
        buildToolsVersion = "30.0.2"
        minSdkVersion = 21
        compileSdkVersion = 29
        targetSdkVersion = 31
        ndkVersion = "21.4.7075529"
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.2.2")
        classpath 'com.google.gms:google-services:4.3.10'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {

    configurations.all {
          resolutionStrategy {
            force "com.facebook.react:react-native:" + "0.66.5"
          }
    }

    repositories {
        mavenCentral()
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        maven { url 'https://www.jitpack.io' }
        maven { url "https://maven.google.com" }
    }
}
</code>```

This I'm getting as a build success

I have tried the stuff's suggested by stack but app not get's connected to NodeJS server...

Body:
Here is NodeJS , which shows No apps connected

android/build.gradle

buildscript {
    ext {
        buildToolsVersion = "30.0.2"
        minSdkVersion = 21
        compileSdkVersion = 29
        targetSdkVersion = 31
        ndkVersion = "21.4.7075529"
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.2.2")
        classpath 'com.google.gms:google-services:4.3.10'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {

    configurations.all {
          resolutionStrategy {
            force "com.facebook.react:react-native:" + "0.66.5"
          }
    }

    repositories {
        mavenCentral()
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        maven { url 'https://www.jitpack.io' }
        maven { url "https://maven.google.com" }
    }
}

This I'm getting as a build success

I have tried the stuff's suggested by stack but app not get's connected to NodeJS server...


问:
How should I remove characters, split a column, and merge my new DataFrame?
I am working from a CSV file using pandas that needed some cleaning. The current state of the code needs
(1) remove "POINT" as well the parenthese
(2) split 'the_geom' into 'X coordinate' and 'Y Coordinate'
(3) merge the new DataFrame with columns 'Asset_Type', 'Tree_Latin' from the variable called location

Provided is my present code:

```<code>green = infrastructure *# data read into python *
locations = green[['the_geom', 'Asset_Type', 'Borough', 'Tree_Latin']]
BK = locations[locations["Borough"] == 'Brooklyn']
Trees_BK = BK[BK["Tree_Latin"].str.contains("NaN|No Tree") == False]
`
</code>```

Provided are some options that failed:

(1) splitting 'the_geom' into 'X coordinate' and 'Y Coordinate'

```<code>coordinates = Trees_BK['the_geom'].str.split(pat = ' ', expand = True)
coordinates.head() #* worked but didn't have rest of DataFrame from "locations"*

</code>```

(2) merging dataset from part (1)

```<code>result = pd.merge(cordinates, Trees_BK[['Asset_Type', 'Tree_Latin']], on=[1,2]) # The top the columns after the split was 1 and 2
</code>```

(3) misplaced code for removing "POINT" as well the parenthese

Trees_BK.head() Tree Data for Mapping

Body:
I am working from a CSV file using pandas that needed some cleaning. The current state of the code needs
(1) remove "POINT" as well the parenthese
(2) split 'the_geom' into 'X coordinate' and 'Y Coordinate'
(3) merge the new DataFrame with columns 'Asset_Type', 'Tree_Latin' from the variable called location

Provided is my present code:

green = infrastructure *# data read into python *
locations = green[['the_geom', 'Asset_Type', 'Borough', 'Tree_Latin']]
BK = locations[locations["Borough"] == 'Brooklyn']
Trees_BK = BK[BK["Tree_Latin"].str.contains("NaN|No Tree") == False]
`

Provided are some options that failed:

(1) splitting 'the_geom' into 'X coordinate' and 'Y Coordinate'

coordinates = Trees_BK['the_geom'].str.split(pat = ' ', expand = True)
coordinates.head() #* worked but didn't have rest of DataFrame from "locations"*

(2) merging dataset from part (1)

result = pd.merge(cordinates, Trees_BK[['Asset_Type', 'Tree_Latin']], on=[1,2]) # The top the columns after the split was 1 and 2

(3) misplaced code for removing "POINT" as well the parenthese

Trees_BK.head() Tree Data for Mapping


问:
Playing random Videos with omxplayer (PIR)
I am trying to do the following: I connected a PIR-Sensor to my raspberry pi to detect motion. If there is motion detected my pi should play random videos from the folder "videos" (about 20-30 videos in this folder). If there is no motion detected a static image should be shown.

With the following code I am able to start the specified video only (on motion detected).

```<code>import RPi.GPIO as GPIO
import time
import os

PIR=23
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR,GPIO.IN)

while True:
  if (GPIO.input(PIR)==True):
    os.system("omxplayer -o hdmi videos/biene.mp4 -b > /dev/null")
    while (GPIO.input(PIR) == True): time.sleep(.2);
</code>```

Additionaly I would like to check every 30 seconds for motion, if there is motion detected keep playing the currently playing video and continue with random videos, if there is no motion detected stop playing videos and show the above mentioned specific image.

I am totally new to raspberry pi´s and python.

Body:
I am trying to do the following: I connected a PIR-Sensor to my raspberry pi to detect motion. If there is motion detected my pi should play random videos from the folder "videos" (about 20-30 videos in this folder). If there is no motion detected a static image should be shown.

With the following code I am able to start the specified video only (on motion detected).

import RPi.GPIO as GPIO
import time
import os

PIR=23
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR,GPIO.IN)

while True:
  if (GPIO.input(PIR)==True):
    os.system("omxplayer -o hdmi videos/biene.mp4 -b > /dev/null")
    while (GPIO.input(PIR) == True): time.sleep(.2);

Additionaly I would like to check every 30 seconds for motion, if there is motion detected keep playing the currently playing video and continue with random videos, if there is no motion detected stop playing videos and show the above mentioned specific image.

I am totally new to raspberry pi´s and python.


问:
Magento2, can we allow to create attribute with user_defined as true and system also as true
In Attribute creation we have user_defined as property to create an custom attribute ,but we can create with system as 1 ,so that that attribute can't be deleted as far as i know attribute with system property can't be deleted from admin

created attribute with user_defined as 1 and system as 1 , but still it can be delectable from admin


问:
Problem with Monte Carlo program in Julia
I am running the following code in Julia.

code:

```<code>function lsmc_am_put(S, K, r, σ, t, N, P)
    Δt = t / N
    R = exp(r * Δt)
    T = typeof(S * exp(-σ^2 * Δt / 2 + σ * √Δt * 0.1) / R)
    X = Array{T}(undef, N+1, P)

    for p = 1:P
      X[1, p] = x = S
      for n = 1:N
          x *= R * exp(-σ^2 * Δt / 2 + σ * √Δt * randn())
          X[n+1, p] = x
      end
    end

    V = [max(K - x, 0) / R for x in X[N+1, :]]
    for n = N-1:-1:1
      I = V .!= 0
      A = [x^d for d = 0:3, x in X[n+1, :]]
      β = A[:, I]' \ V[I]
      cV = A' * β
      for p = 1:P
          ev = max(K - X[n+1, p], 0)
          if I[p] && cV[p] < ev
              V[p] = ev / R
          else
              V[p] /= R
          end
      end
    end
    return max(mean(V), K - S)
end
</code>```

after this, I import ForwardDiff: Dual and then run

lsmc_am_put(Dual(100,1,0),90,0.5,Dual(0.3,0.1),180/365,1000,10000)

But I get the error:

```<code>error: MethodError: no method matching _mul_partials(::ForwardDiff.Partials{2, Int64}, ::ForwardDiff.Partials{1, Float64}, ::Float64, ::Int64)

Closest candidates are:

_mul_partials(::ForwardDiff.Partials{0, A}, ::ForwardDiff.Partials{N, B}, ::Any, ::Any) where {N, A, B} at ~/.julia/packages/ForwardDiff/QdStj/src/partials.jl:141

_mul_partials(::ForwardDiff.Partials{N, A}, ::ForwardDiff.Partials{0, B}, ::Any, ::Any) where {N, A, B} at ~/.julia/packages/ForwardDiff/QdStj/src/partials.jl:142

_mul_partials(::ForwardDiff.Partials{N}, ::ForwardDiff.Partials{N}, ::Any, ::Any) where N at ~/.julia/packages/ForwardDiff/QdStj/src/partials.jl:118

…

Stacktrace:

[1] dual_definition_retval(#unused#::Val{Nothing}, val::Float64, deriv1::Float64, partial1::ForwardDiff.Partials{2, Int64}, deriv2::Int64, partial2::ForwardDiff.Partials{1, Float64})

@ ForwardDiff ~/.julia/packages/ForwardDiff/QdStj/src/dual.jl:203

[2] *****

@ ~/.julia/packages/ForwardDiff/QdStj/src/dual.jl:271 [inlined]

[3] lsmc_am_put(S::Dual{Nothing, Int64, 2}, K::Int64, r::Float64, σ::Dual{Nothing, Float64, 1}, t::Float64, N::Int64, P::Int64)

@ Main ./REPL[56]:4

[4] top-level scope

@ REPL[68]:100:
</code>```

Can someone please help me with this? I am unable to trace what I am getting wrong and how I should fix it.

I was expecting a bracket with numbers. e.g. (3.232382582308,-0.232390234823,19.232490234923)

Body:
I am running the following code in Julia.

code:

function lsmc_am_put(S, K, r, σ, t, N, P)
    Δt = t / N
    R = exp(r * Δt)
    T = typeof(S * exp(-σ^2 * Δt / 2 + σ * √Δt * 0.1) / R)
    X = Array{T}(undef, N+1, P)

    for p = 1:P
      X[1, p] = x = S
      for n = 1:N
          x *= R * exp(-σ^2 * Δt / 2 + σ * √Δt * randn())
          X[n+1, p] = x
      end
    end

    V = [max(K - x, 0) / R for x in X[N+1, :]]
    for n = N-1:-1:1
      I = V .!= 0
      A = [x^d for d = 0:3, x in X[n+1, :]]
      β = A[:, I]' \ V[I]
      cV = A' * β
      for p = 1:P
          ev = max(K - X[n+1, p], 0)
          if I[p] && cV[p] < ev
              V[p] = ev / R
          else
              V[p] /= R
          end
      end
    end
    return max(mean(V), K - S)
end

after this, I import ForwardDiff: Dual and then run

lsmc_am_put(Dual(100,1,0),90,0.5,Dual(0.3,0.1),180/365,1000,10000)

But I get the error:

error: MethodError: no method matching _mul_partials(::ForwardDiff.Partials{2, Int64}, ::ForwardDiff.Partials{1, Float64}, ::Float64, ::Int64)

Closest candidates are:

_mul_partials(::ForwardDiff.Partials{0, A}, ::ForwardDiff.Partials{N, B}, ::Any, ::Any) where {N, A, B} at ~/.julia/packages/ForwardDiff/QdStj/src/partials.jl:141

_mul_partials(::ForwardDiff.Partials{N, A}, ::ForwardDiff.Partials{0, B}, ::Any, ::Any) where {N, A, B} at ~/.julia/packages/ForwardDiff/QdStj/src/partials.jl:142

_mul_partials(::ForwardDiff.Partials{N}, ::ForwardDiff.Partials{N}, ::Any, ::Any) where N at ~/.julia/packages/ForwardDiff/QdStj/src/partials.jl:118

…

Stacktrace:

[1] dual_definition_retval(#unused#::Val{Nothing}, val::Float64, deriv1::Float64, partial1::ForwardDiff.Partials{2, Int64}, deriv2::Int64, partial2::ForwardDiff.Partials{1, Float64})

@ ForwardDiff ~/.julia/packages/ForwardDiff/QdStj/src/dual.jl:203

[2] *****

@ ~/.julia/packages/ForwardDiff/QdStj/src/dual.jl:271 [inlined]

[3] lsmc_am_put(S::Dual{Nothing, Int64, 2}, K::Int64, r::Float64, σ::Dual{Nothing, Float64, 1}, t::Float64, N::Int64, P::Int64)

@ Main ./REPL[56]:4

[4] top-level scope

@ REPL[68]:100:

Can someone please help me with this? I am unable to trace what I am getting wrong and how I should fix it.

I was expecting a bracket with numbers. e.g. (3.232382582308,-0.232390234823,19.232490234923)


问:
How can I successfully change WinForms hosted WPF RichTextBox Document Width? Document Width does not increase and wraps all text on reaching width
I am using ElementHost to host WPF RichTextBox on my Windows Forms Form. The ElementHost fills the entire Panel by DockStyle.Fill. The problem is that WPF RichTextBox doesn't change it's Document's width when I try to change it using RichTextBox.Document.PageWidth property. I simply cannot increase the Document's size and so it wraps all text and everything when they reach the limit of width of Document. It seems a bug in WPF RichTextBox, or my own code implementation is wrong and some other code is to be implemented. Please inform me the correct code implementation which successfully changes the WPF RichTextBox Document width when I use WPF RichTextBox in Windows Forms Form.

I placed the code below in Form.Load Event.

```<code>            // host1 = ElementHost
            // rtbEntry = WPF RichTextBox
            host1.Dock = DockStyle.Fill;
            host1.AutoSize = true;
            host1.Child = rtbEntry;
            rtbEntry.Height = 10000;
            rtbEntry.Width = 10000;
            rtbEntry.HorizontalScrollBarVisibility = System.Windows.Controls.ScrollBarVisibility.Visible;
            rtbEntry.Document.PageWidth = (double)20000;
            rtbEntry.Document.MinPageWidth = (double)20000;
            rtbEntry.Document.MaxPageWidth = (double)20000;
            rtbEntry.VerticalScrollBarVisibility = System.Windows.Controls.ScrollBarVisibility.Visible;
            toolStripContainer2.ContentPanel.Controls.Add(host1);

</code>```

I tried the code described above. I also tried very much to find correct code to solve this problem on Internet but there was none. Unless this problem is solved, my project is stuck with this problem.

Body:
I am using ElementHost to host WPF RichTextBox on my Windows Forms Form. The ElementHost fills the entire Panel by DockStyle.Fill. The problem is that WPF RichTextBox doesn't change it's Document's width when I try to change it using RichTextBox.Document.PageWidth property. I simply cannot increase the Document's size and so it wraps all text and everything when they reach the limit of width of Document. It seems a bug in WPF RichTextBox, or my own code implementation is wrong and some other code is to be implemented. Please inform me the correct code implementation which successfully changes the WPF RichTextBox Document width when I use WPF RichTextBox in Windows Forms Form.

I placed the code below in Form.Load Event.

            // host1 = ElementHost
            // rtbEntry = WPF RichTextBox
            host1.Dock = DockStyle.Fill;
            host1.AutoSize = true;
            host1.Child = rtbEntry;
            rtbEntry.Height = 10000;
            rtbEntry.Width = 10000;
            rtbEntry.HorizontalScrollBarVisibility = System.Windows.Controls.ScrollBarVisibility.Visible;
            rtbEntry.Document.PageWidth = (double)20000;
            rtbEntry.Document.MinPageWidth = (double)20000;
            rtbEntry.Document.MaxPageWidth = (double)20000;
            rtbEntry.VerticalScrollBarVisibility = System.Windows.Controls.ScrollBarVisibility.Visible;
            toolStripContainer2.ContentPanel.Controls.Add(host1);

I tried the code described above. I also tried very much to find correct code to solve this problem on Internet but there was none. Unless this problem is solved, my project is stuck with this problem.


问:
IBM MQ - Websphere Application Server - MQ Failover
I have a JEE application (simple EJB application which puts a message to queue) which needs to connect to a uniform cluster queue managers (QMC1, QMC2) and PUT messages. The JEE application runs in a Wepshpere application server,and uses CCDT, with the following commands to consider the queue managers as a group.

```<code>DEFINE CHANNEL(QMC1.CHL) CHLTYPE(CLNTCONN) CONNAME('192.168.1.12(9001)') QMNAME(QM) AFFINITY(NONE) TRPTYPE(TCP) REPLACE
DEFINE CHANNEL(QMC2.CHL) CHLTYPE(CLNTCONN) CONNAME('192.168.1.12(9002)') QMNAME(QM) AFFINITY(NONE) TRPTYPE(TCP) REPLACE
</code>```

I have done the connection factory setting with *QM as the queue manager name. Also in the WAS connection factory -> advanced properties -> Client reconnect options, I have selected
RECONNECT.

My issue is, when both queue managers are running I can put messages to a single the queue,
(I have increased the queue work load rank so that all the messages go to a single queue in the cluster (say QMC1).

But if QMC1 is down, the JEE application is unable to connect to the surviving queue manager (QMC2) as it is trying to re-connect to QMC1, not based on the queue manager group.

Have I misunderstood anything here? Will the RECONNECT will try to reconnect to the same queue manager, not the available queue manager based on CCDT?  Shouldn't a uniform cluster queue manager support this fail-over behavior via a CCDT queue manager group?

Appreciate any feedback.

Body:
I have a JEE application (simple EJB application which puts a message to queue) which needs to connect to a uniform cluster queue managers (QMC1, QMC2) and PUT messages. The JEE application runs in a Wepshpere application server,and uses CCDT, with the following commands to consider the queue managers as a group.

DEFINE CHANNEL(QMC1.CHL) CHLTYPE(CLNTCONN) CONNAME('192.168.1.12(9001)') QMNAME(QM) AFFINITY(NONE) TRPTYPE(TCP) REPLACE
DEFINE CHANNEL(QMC2.CHL) CHLTYPE(CLNTCONN) CONNAME('192.168.1.12(9002)') QMNAME(QM) AFFINITY(NONE) TRPTYPE(TCP) REPLACE

I have done the connection factory setting with *QM as the queue manager name. Also in the WAS connection factory -> advanced properties -> Client reconnect options, I have selected
RECONNECT.

My issue is, when both queue managers are running I can put messages to a single the queue,
(I have increased the queue work load rank so that all the messages go to a single queue in the cluster (say QMC1).

But if QMC1 is down, the JEE application is unable to connect to the surviving queue manager (QMC2) as it is trying to re-connect to QMC1, not based on the queue manager group.

Have I misunderstood anything here? Will the RECONNECT will try to reconnect to the same queue manager, not the available queue manager based on CCDT?  Shouldn't a uniform cluster queue manager support this fail-over behavior via a CCDT queue manager group?

Appreciate any feedback.


问:
Building WinUI 3 Desktop Application using LLVM/Clang
When I create a WinUI project in Visual Studio, below is how the project structure looks like:

This project by default gets built using MSBuild.

However, I would like to build this project using LLVM Clang-Cl. Stating for ample clarity, I would also be wanting to use the Generator as 'Ninja'.

Is this possible to achieve?

As a bunch of headers get generated when this project is built, I tried using running cppwinrt.exe manually on this project to generate the relevant headers. While few headers got generated but still a bunch were missing. Also, could not understand how the .g.h/.g.cpp files can get generated without MSBuild.

I have also tried this link - https://github.com/fredemmott/cmake-cpp-winrt-winui3. However, the same doesnt work with LLVM/Clang and Ninja.

Any pointers/suggestions will help.


问:
Maximum update depth exceeded. I am using react-countdown npm package, but after countdown completed a function call again anda again

I want to call a function when countdown will be completed, but after completed countdown the function call again and again, how can I solve this problem?

Here I am share my code

I am trying with a state true/false when count down will completed then state will be true then call my function but this function call again and again.

In this case I am expect to this function call once a time and solve this error: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

```<code>
 let time = "";

 const renderer = ({ days, hours, minutes, seconds, completed }) => {
     if (completed) {

   // ::::::::: ISSUES ISSUES -> maximum update depth ::::::://
   return handleUpdateStatus("");

 } else {
   // Render a countdown
   return (time = (
     <span
       style={{
         backgroundColor: "#251B37",
         color: "#38E54D",
         letterSpacing: "1px",
         fontFamily: "digital-clock-font",
         fontWeight: "700",
       }}
       className=" p-1 rounded"
     >
       {days}:{hours}:{minutes}:{seconds}
     </span>
   ));
 }
};
</code>```

Body:
I want to call a function when countdown will be completed, but after completed countdown the function call again and again, how can I solve this problem?

Here I am share my code

I am trying with a state true/false when count down will completed then state will be true then call my function but this function call again and again.

In this case I am expect to this function call once a time and solve this error: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

 let time = "";

 const renderer = ({ days, hours, minutes, seconds, completed }) => {
     if (completed) {

   // ::::::::: ISSUES ISSUES -> maximum update depth ::::::://
   return handleUpdateStatus("");

 } else {
   // Render a countdown
   return (time = (

       {days}:{hours}:{minutes}:{seconds}

   ));
 }
};