instruction
stringlengths
0
30k
As mentioned [here](https://github.com/jupyterlab/jupyterlab/issues/2044#issuecomment-1015377299), you can reuse existing kernel by using `--KernelProvisionerFactory.default_provisioner_name=pyxll-provisioner`. For example: ```bash STARTUP_CODE="a = 42" export PYXLL_IPYTHON_CONNECTION_FILE="$(mktemp -d)/connection-file.json" (printf "%s\n" "$STARTUP_CODE" && sleep infinity) | jupyter console --kernel=python3 -f="$PYXLL_IPYTHON_CONNECTION_FILE" & jupyter notebook --KernelProvisionerFactory.default_provisioner_name=pyxll-provisioner --log-level=ERROR ``` ``` 0.00s - Debugger warning: It seems that frozen modules are being used, which may 0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off 0.00s - to python to disable frozen modules. 0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation. 0.00s - Debugger warning: It seems that frozen modules are being used, which may 0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off 0.00s - to python to disable frozen modules. 0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation. [I 2024-03-31 03:19:56.892 LabApp] JupyterLab extension loaded from /home/nixos/demo/.venv/lib/python3.11/site-packages/jupyterlab [I 2024-03-31 03:19:56.893 LabApp] JupyterLab application directory is /home/nixos/peftai/.venv/share/jupyter/lab [I 2024-03-31 03:19:56.893 LabApp] Extension Manager is 'pypi'. Warning: Input is not a terminal (fd=0). Jupyter console 6.6.3 Python 3.11.8 (main, Feb 6 2024, 21:21:21) [GCC 13.2.0] Type 'copyright', 'credits' or 'license' for more information IPython 8.16.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: In [1]: a = 42 In [2]: ^[[23;1R[C 2024-03-31 03:19:59.664 ServerApp] To access the server, open this file in a browser: file:///home/nixos/.local/share/jupyter/runtime/jpserver-93926-open.html Or copy and paste one of these URLs: http://localhost:8888/tree?token=da6ee2fac54afc8591bb9c2de3039036fb15bd5150002e29 http://127.0.0.1:8888/tree?token=da6ee2fac54afc8591bb9c2de3039036fb15bd5150002e29 WARNING: your terminal doesn't support cursor position requests (CPR). In [2]: 0.00s - Debugger warning: It seems that frozen modules are being used, which may 0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off 0.00s - to python to disable frozen modules. 0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation. ``` You can see `jupyter console` executes `a = 42` and holds on the kernel, then all subsequential `jupyter notebook` sessions will reuse the existing kernel, where `a` is initialized to `42` out-of-the-box. [![Jupyter Notebook][1]][1] [1]: https://i.stack.imgur.com/6486D.png
{"Voters":[{"Id":6752050,"DisplayName":"273K"},{"Id":10686048,"DisplayName":"ChrisMM"},{"Id":1968182,"DisplayName":"Ulrich Eckhardt"}],"SiteSpecificCloseReasonIds":[13]}
I have a Vert.x HTTP server with static files, that are handled with router.route().handler(StaticHandler.create()) This is working fine. My question is - is it possible to modify one of my static file? For example - in `index.html` i have a meta tag <meta name="my-token" content="${MY-TOKEN}"> and i want to replace `${MY-TOKEN}` part with my generated data. Is Vert.x have some possibilities to modify it or it's not possible and i need to use one of the template engines?
Vert.x modify content of static file
|vert.x|
If you compile gtest with the Apple g++ and installed gcc with e.g. homebrew, linking to gtest will cause this error. So compile gtest and your project with the same compiler.
I am trying to create 2 rows per page in a PrimeNG Carousel. The problem is that it currently shows all the items on 1 row. I calculate the width and height of each item per row dynamically. For example, if i have 13 items and the [numvisible] = 8, it should show 4 items per row with a total of 2 rows. When the user presses next page, it should show the remaining 5. 4 on the first row and 1 on the second. I have put a StackBlitz together to show you what i have: [text](https://stackblitz.com/edit/stackblitz-starters-bvnjv8?file=src%2Fapp%2Fcomponents%2Fproject.component.ts)
how to show multiple rows per page using PrimeNG carousel?
|angular|carousel|primeng|
null
) CREATE TABLE ahli( nama VARCHAR(6), nokp VARCHAR(12), id_kelas INT(2), tahap VARCHAR(20), katalaluan VARCHAR(20), PRIMARY KEY(nokp), FOREIGN KEY(id_kelas) REFERENCES kelas(id_kelas) ON UPDATE CASCADE ON DELETE CASCADE I try to change it with another words, symbol, numbers and backspace.
I am using Python and Selenium (selenium-wire) to automatically control a browser for two sites. Browsing most sites like: https://www.google.com https://platform.cmcmarkets.com/ using a chromedriver under seleniumwire works fine. However when browsing to: https://app.plus500.com/ A Chrome error page is displayed with the message: This site can’t be reached The web page at https://app.plus500.com/ might be temporarily down or it may have moved permanently to a new web address. ERR_HTTP2_PROTOCOL_ERROR selenium-wire is a python module that extends selenium by allowing the capture of requests and responses. The site can be reached using plain selenium webdrivers, so it seems the issue lies with the selenium-wire package in use. Importing the Root Authority certificate issued by selenium-wire into Chrome allows browsing HTTPS sites without the blocking "Your connection is not private" screen. What is odd is that while certificate viewer for google.com (and other sites) shows the Selenium Wire CA: Common Name (CN) www.google.com Organisation (O) <Not part of certificate> Organisational Unit (OU) <Not part of certificate> Common Name (CN) Selenium Wire CA Organisation (O) <Not part of certificate> Organisational Unit (OU) <Not part of certificate> app.plus500.com does not: Common Name (CN) *.plus500.com Organisation (O) Edgio, Inc. Organisational Unit (OU) <Not part of certificate> Common Name (CN) DigiCert Global G2 TLS RSA SHA256 2020 CA1 Organisation (O) DigiCert Inc Organisational Unit (OU) <Not part of certificate> The plus500.com site then reports that I am offline, possible because some app assets failed to load as a result. However it does report the certificate is valid so that does not seem to be the issue. I've tried toggling the mitmproxy backend in the selenium-wire options also with no success. Packet captures to the server on port 443 show the failed connection sequence corresponds with some extra TCP RST from the server, but I cannot interpret much else from them. Please, any help diagnosing this would be great!
How to create a button with a svg inside correctly?
|html|reactjs|web|next.js|sass|
null
I would like some help with a problem that has had stumped me for two days. I have 'results' table like this: ``` result_id competition_id competitor_id competitor_ranking 1 1 1 0.1 2 1 2 0.4 3 1 3 0.2 4 1 4 0.3 5 2 1 0.4 6 2 2 0.1 7 2 3 0.2 8 2 5 0.3 9 3 3 0.1 10 3 4 0.4 11 3 5 0.2 12 3 6 0.3 ``` From the 'results' table I want to get a grouped ranking of competitors with penalties points (+1.0) included, like this: ``` competitor_id competitions rankings ranking_with_penalties 1 1; 2; M 0.1; 0.4 0.1; 0.4; +1.0 2 1; 2; M 0.4; 0.1 0.4; 0.1; +1.0 3 1; 2; 3 0.2; 0.2; 0.1 0.2; 0.2; 0.1 4 1; M; 3 0.3; 0.4 0.3; +1.0; 0.4 5 M; 2; 3 0.3; 0.2 +1.0; 0.3; 0.2 6 3 M; M; 0.3 0.3; +1.0; +1.0 ``` I know that group_concat function is an aggregate function that concatenates all non-null values in a column. I understand that the task is quite trivial. But I can not solve it. ``` CREATE TABLE results ( result_id INTEGER PRIMARY KEY, competition_id INTEGER, competitor_id INTEGER, competitor_ranking ); INSERT INTO results(competition_id, competitor_id, competitor_ranking) VALUES (1, 1, 0.1), (1, 2, 0.4), (1, 3, 0.2), (1, 4, 0.3), (2, 1, 0.4), (2, 2, 0.1), (2, 3, 0.2), (2, 5, 0.3), (3, 3, 0.1), (3, 4, 0.4), (3, 5, 0.2), (3, 6, 0.3) ; SELECT competitor_id, group_concat(coalesce(competition_id, NULL), '; ') AS competitions, group_concat(coalesce(competitor_ranking, NULL), '; ') AS rankings, group_concat(coalesce(NULLIF(competitor_ranking, NULL), '+1.0'), '; ') AS ranking_with_penalties FROM results GROUP BY competitor_id; ``` I'm looking forward to any help.
Try: ```py print(df.query("a > b")) ``` Prints: ```none a b 0 100 80 3 400 350 ```
I met same issue try ssl port https://192.168.1.227:54321 then allow exception or firefox setting -> certificate manager -> servers add exception site
EDIT. This is a tcl tk bug in Windows. This can be seen by double clicking on the window title. ``` from tkinter import * def window_clicked(event): print("window_clicked", event.x, event.y) root = Tk() root.geometry("600x300") root.bind("<Button-1>", window_clicked) root.mainloop() ------------------- window_clicked 418 99 ``` An event is logged that should not occur.
How to test a wheel against multiple versions of python?
When you call Eval, the return value of the command/function you specify, is stored in CLIPSValue parameter you supply. In your code, the last Eval call executes the (run) command and stores the value in the variable cv. The (run) command has no return value, so there's nothing meaningful that's going to be stored in the variable cv. I'm sure there are some programming languages that are exceptions, but generally printing is a side effect of functions that print; what's printed is not used as the return value of the function. So there's nothing set up in CLIPS that grabs the output of println statements in rules and uses this as the return value of the run command. I've added some sample code that shows two different mechanisms for transferring data out of CLIPS. One is adding a user defined function which you can use to call out from the actions of a rule. The other shows how you can pass information back by storing it in facts. main.c: #include "clips.h" int main( int argc, char *argv[]) { Environment *env; CLIPSValue cv, sv; env = CreateEnvironment(); Build(env,"(deftemplate message (slot value))"); Build(env,"(defrule hello => (myfun \"User Function Callout\"))"); Build(env,"(defrule goodbye => (assert (message (value \"Fact Slot Retrieval\"))))"); Eval(env,"(reset)",NULL); Eval(env,"(run)",NULL); Eval(env,"(find-all-facts ((?f message)) TRUE)",&cv); if (cv.header->type == MULTIFIELD_TYPE) { for (size_t i = 0; i < cv.multifieldValue->length; i++) { if (cv.multifieldValue->contents[i].header->type == FACT_ADDRESS_TYPE) { Fact *theFact = cv.multifieldValue->contents[i].factValue; FactSlotValue(env,theFact,"value",&sv); if (sv.header->type == STRING_TYPE) { printf("%s\n",sv.lexemeValue->contents); } } } } DestroyEnvironment(env); return -1; } userfunctions.c: #include "clips.h" void UserFunctions(Environment *); void MyFunFunction(Environment *,UDFContext *,UDFValue *); void UserFunctions( Environment *env) { AddUDF(env,"myfun","v",1,1,"s",MyFunFunction,"MyFunFunction",NULL); } void MyFunFunction( Environment *theEnv, UDFContext *context, UDFValue *returnValue) { UDFValue theArg; const char *theString; if (! UDFFirstArgument(context,STRING_BIT,&theArg)) { return; } theString = theArg.lexemeValue->contents; printf("%s\n",theString); } Output: User Function Callout Fact Slot Retrieval
it seems to me you could achieve your goal by means of formulas if you insert one column and one row you could use this formula =IF(SUM(G$5:G5)<G$2;IF(SUM(F6:$F6)<8;1;"");"") [![enter image description here][1]][1] or you can keep your original rows and columns layout and adopt this other formula: =IF(ROW()=5; IF(COLUMN()=7; 1; IF(SUM(G5:$G5)<8;1;"")); IF(SUM(G4:G$5)<G$2; IF(COLUMN()=7; 1; IF(SUM(G5:$G5)<8;1;"")); "") ) [![enter image description here][2]][2] [1]: https://i.stack.imgur.com/we5Ul.png [2]: https://i.stack.imgur.com/NYnor.png
`format()` method would work here as well: for i in range(triangle_height + 1): print('{}{}'.format(triangle_char, " ") * i) i += 1
{"Voters":[{"Id":12421110,"DisplayName":"Jean-Joseph"}]}
**The aim:** To select "Office" speakers using Applescript. **The OS**: Mac Sonoma 14.3.1 **The code:** tell application "System Settings" activate reveal pane id "com.apple.Sound-Settings.extension" end tell tell application "System Events" tell process "System Preferences" repeat until exists window "Sound" delay 0.5 end repeat tell window "Sound" repeat until exists tab group 1 delay 0.5 end repeat tell tab group 1 click radio button "Output" repeat until exists table 1 of scroll area 1 delay 0.5 end repeat tell table 1 of scroll area 1 -- Get the position of the target row set targetRowPosition to position of row 1 where value of static text 1 is "Office" -- Click on the target row click targetRowPosition end tell end tell end tell end tell end tell **The rather frustrating result:** Opens the preferences sound window then keeps running...That's it. Does not select input or output, does not select "Office" from the list of audio sources
Applescript To Select Sound Output stops at opening Sound Preferences Screen
|automation|applescript|macos-sonoma|
null
I am using a Huawei E3372 4G USB dongle on Win8.1. This dongle's settings can be accessed via browser by typing 192.168.8.1 and the user can enable a 4G connection by manually clicking the "Enable mobile data" button. This is the script I am trying to use to "Enable mobile data" connection, knowing I'm doing something wrong only on line 4: ``` #!/bin/bash curl -s -X GET "http://192.168.8.1/api/webserver/token" > token.xml TOKEN=$(grep -v '<?xml version="1.0" encoding="UTF-8"?><response><token>' -v '</token></response>' token.xml) curl "http://192.168.8.1/api/dialup/mobile-dataswitch" -H "Host: 192.168.8.1" -H "User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:68.0) Gecko/20100101 Goanna/4.8 Firefox/68.0 PaleMoon/29.0.1" -H "Accept: */*" -H "Accept-Language: en-US,en;q=0.5" --compressed -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8;" -H "_ResponseSource: Broswer" -H "__RequestVerificationToken: $TOKEN" -H "X-Requested-With: XMLHttpRequest" -H "Referer: http://192.168.8.1/html/content.html" -H "Cookie: SessionID=AgVjkIjBxOC0xPbys3nne7rA4I8GXNzUkZCcSOGPR8P3xss8XOuqRbdb0EgHidXhQXZ903xf0nk0F8J81ISqHpZ7kYvZaSW5wHWDqJ9w90pXj90cPwCm7F01fFcmp0gv" -H "Connection: keep-alive" --data-raw "<?xml version=""1.0"" encoding=""UTF-8""?><request><dataswitch>1</dataswitch></request>" date exec $SHELL ``` Upon executing the first curl command, the xml file's content would look like this: ``` <?xml version="1.0" encoding="UTF-8"?><response><token>ZsxY7Q9G90jh4FqUiAjxD9XmqLWf0rYg4RUNf6FoVzeTIlPPms0Ov1RERFFRY77o</token></response> ``` Just for test purposes, if I manually insert the token in the bash script, it works like a charm: ``` #!/bin/bash curl "http://192.168.8.1/api/dialup/mobile-dataswitch" -H "Host: 192.168.8.1" -H "User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:68.0) Gecko/20100101 Goanna/4.8 Firefox/68.0 PaleMoon/29.0.1" -H "Accept: */*" -H "Accept-Language: en-US,en;q=0.5" --compressed -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8;" -H "_ResponseSource: Broswer" -H "__RequestVerificationToken: ZsxY7Q9G90jh4FqUiAjxD9XmqLWf0rYg4RUNf6FoVzeTIlPPms0Ov1RERFFRY77o" -H "X-Requested-With: XMLHttpRequest" -H "Referer: http://192.168.8.1/html/content.html" -H "Cookie: SessionID=AgVjkIjBxOC0xPbys3nne7rA4I8GXNzUkZCcSOGPR8P3xss8XOuqRbdb0EgHidXhQXZ903xf0nk0F8J81ISqHpZ7kYvZaSW5wHWDqJ9w90pXj90cPwCm7F01fFcmp0gv" -H "Connection: keep-alive" --data-raw "<?xml version=""1.0"" encoding=""UTF-8""?><request><dataswitch>1</dataswitch></request>" date exec $SHELL ``` I've found several suggestions for the same or similar dongles, none of them worked for me, it must be due to my insufficient knowledge. My cry for help is about line 4 of the top-most script. I am making a mistake somewhere obviously. Thank you in advance for your help. ===== EDIT: SOLUTION IS FOUND ! ===== markp-fuso's suggestion was the path to my solution. Kudos. I just noticed that besides a variable "token" which was changing upon each "on/off" action, this dongle also had a less variable "SesTokInfo" which is not being changed upon each "on/off" action (I just tested that manually) and it is different than what it was yesterday. It could be "plug/unplug" of dongle that causes that, I honestly can't know. To whom it may concern: The final form of the working script which I've just tested with positive result twice would be: (note that the script contains the curl command to "Enable mobile data". The one to "Disable mobile data" should contain 0 instead of 1 in the "dataswitch>1</dataswitch" part. ``` #!/bin/bash curl -s -X GET "http://192.168.8.1/api/webserver/token" > token.xml curl -s -X GET "http://192.168.8.1/api/webserver/SesTokInfo" > sestoken.xml TOKEN=$(sed -En 's|.*<token>(.*)</token>.*|\1|p' token.xml) SESTOKEN=$(sed -En 's|.*<SesInfo>(.*)</SesInfo>.*|\1|p' sestoken.xml) typeset -p TOKEN typeset -p SESTOKEN curl "http://192.168.8.1/api/dialup/mobile-dataswitch" -H "Host: 192.168.8.1" -H "User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:68.0) Gecko/20100101 Goanna/4.8 Firefox/68.0 PaleMoon/29.0.1" -H "Accept: */*" -H "Accept-Language: en-US,en;q=0.5" --compressed -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8;" -H "_ResponseSource: Broswer" -H "__RequestVerificationToken: $TOKEN" -H "X-Requested-With: XMLHttpRequest" -H "Referer: http://192.168.8.1/html/content.html" -H "Cookie: SessionID=$SESTOKEN" -H "Connection: keep-alive" --data-raw "<?xml version=""1.0"" encoding=""UTF-8""?><request><dataswitch>1</dataswitch></request>" date exec $SHELL ```
Besides that for Spring Boot 3 you should use Spock 2.4-M4, you do not configure the test task or test suite to use JUnit Platform / Spock. By default the test task of the default test suite is configured to use JUnit 4, so the Spock tests which are JUnit 5 Platform based are not found. Besides that, I recommend you stop using the Spring Dependency Management plugin. It is an obsolete relict from times when Gradle did not have built-in BOM support, by now does more harm than good, and even the maintainer of that plugin recommends not to use it anymore, but instead to use the built-in BOM support using `platform(...)` as also documented in the Spring Boot docs.
There is an open source project called StreamingFlow4J that’s solve it in Esper CEP. It easily makes CRUD operations in Epl rules.
This is well defined in the [`vectorize`](https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html) documentation: > If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs. If you don't want this, you can define `otypes`: ``` import numpy def test(x): print(x) test = numpy.vectorize(test, otypes=[float]) test([1,2,3]) 1 2 3 ``` In any case, be aware that `vectorize` is just a convenience around a python loop. If you want to have side effects you might rather want to use an explicit python loop.
I have the following controller's action: ```C# [HttpPost("api/v1/addProduct")] [Consumes("multipart/form-data")] public Task<ProductDto?> AddProduct([FromForm] ProductRequest request, CancellationToken cancellationToken) { return _productService.AddProduct(request, cancellationToken); } ``` and the following model: ```C# public class ProductRequest { [Required] public string Title { get; set; } public string? Description { get; set; } [Required] public string PreviewDescription { get; set; } [Required] public IFormFile PreviewImage { get; set; } public IFormFile[]? Images { get; set; } [Required] public int[] CategoryIds { get; set; } public bool? IsAvailable { get; set; } } ``` I successfully sent data to the server (I use formData): [![enter image description here][1]][1] But by some reason, I see the following in the debugger: [![enter image description here][2]][2] Everything is ok with `previewImage` but where are `images`? Why `previewImage` is here, but there is no `images`? I sent them in exactly the same way as I sent `previewImage`. We can see it at the request payload screen. Help me please to figure it out. **UPDATE** I tried `IFormFileCollection`: [![enter image description here][3]][3] No result. [1]: https://i.stack.imgur.com/N6lJx.png [2]: https://i.stack.imgur.com/oruB8.png [3]: https://i.stack.imgur.com/3pxB9.png
|.net|asp.net-core-webapi|multipartform-data|form-data|
You have to use a `\U` + 8-hexadecimal code instead of `\u` + 4-hexadecimal code when the code point is more than four digits. You'll also need an appropriate font so it may or may not show up with the correct glyph on your system. ```py import unicodedata as ud mytable = mystr.maketrans('ABC', '\U00011D72\U00011D73\U00011D74') mystr_translated = 'ABC'.translate(mytable) for c in mystr_translated: print(c, ud.name(c)) ``` Output: ```none GUNJALA GONDI LETTER KHA GUNJALA GONDI LETTER TA GUNJALA GONDI LETTER THA ``` See [Unicode HOWTO: Unicode Literals in Python Source Code](https://docs.python.org/3/howto/unicode.html#unicode-literals-in-python-source-code)
If you are loading an existing search through `search.load()`, make sure the search is Public. Go the definition of your search, tick the `Public` checkbox on the main page.
I have an android application containing both java and kotlin codes. I want to scan its possible vulnerabilites using coverity sast tool version 2023.12.0. I follow the following steps: 1-) ./cov-configure --java 2-) ./cov-configure --kotlin 3-) ./cov-build --dir (path of idir file) --fs-capture-search (path of target source file) --no-command 4-) ./cov-analyze --dir (path of idir file) --aggressiveness-level high --android-security 5-) cov emit command (I did not write it here because it just commit the result to localhost) My scan results did not satisfy me, because it just scanned android manifest and some xml files. It found some vulnerabilities here, but when I look at the log file, i realized that it did not capture any java or kotlin code. So, what is my mistake ? why did it not scan java or kotlin files ? If you use this tool, can you explain me how you make android scans ? Thanks... Note: This question is important issue for me. If I did something wrong in my question, please firstly state it in comments, dont just downvote
{"OriginalQuestionIds":[78049233],"Voters":[{"Id":14098260,"DisplayName":"Alexander Nenashev"},{"Id":535480,"DisplayName":"James"},{"Id":2802040,"DisplayName":"Paulie_D","BindingReason":{"GoldTagBadge":"css"}}]}
i am trying to load all partitions data from S3 using spark, but i am not able to do so. here is how the data is stored in S3, where statusts is partition column. [![enter image description here][1]][1] i am using below java code to load the data. Dataset<Row> archivalDS = session.read().format("avro").option("basePath", folder_path) .load(folder_path); where folder_path variable value is `s3a://bucket-name/ArchiveTables/log/60a89657-47df-4df4-8aa3-4c53f43782b9/` , application is throwing error with statusts column not available in schema. after going though few threads on stack overflow, i added column statusts to dataset , so that column is present in stored Avro file, but i see that column is missing in Avro file. if i change the folder_path variable to specific partition, `s3a://bucket-name/ArchiveTables/log/60a89657-47df-4df4-8aa3-4c53f43782b9/statusts=2024-03-01/` , it works. but in that case i will be able to load the data from one partition at a time. is there a way i can load all partitions in a single load rather than giving partition value also in the path to load other question, i am using below code to load the data in database after loading the data in avro. i gave lower bound to date from where we have data stored, upper bound some random date, but i have data where statusts is null. in that case how can we provide lower or upper bound, if i don't want to miss that data also, while loading. transactionIdNullDS.repartition(6).write().mode(SaveMode.Append).format("jdbc") .option("stringtype", "unspecified").option("url", url).option("JDBCOptions.JDBC_DRIVER_CLASS", driver) .option("dbtable", tableName).option("user", "username") .option("password", "password") .option("partitionColumn", "statusts").option("lowerBound", "2022-01-01") .option("upperBound", "2999-12-31") .option("numPartitions", Integer.parseInt(System.getProperty("numPartitions.number", "8"))).save(); [1]: https://i.stack.imgur.com/roihQ.png
Spark load all partions at once
|apache-spark|pyspark|apache-spark-sql|
As per the react native docs, Flatlist wont support masonry layout. The numColumns section in Flatlist doc suggests, "Items should all be the same height - masonry layouts are not supported." Please refer, https://facebook.github.io/react-native/docs/flatlist#numcolumns
Without `docker-compose.yml` (as most VPS CPanels (open-source PaaS like Dokku, Caprover, Easypanel) don't support `docker-compose.yml`) so I had to find an alternate solution using `--env-file` option in a `Makefile`: ```make .PHONY: build-staging build-staging: ## Build the staging docker image. docker build -f docker/staging/Dockerfile . .PHONY: start-staging start-staging: ## Start the staging docker container. docker run --detach --env-file .env.staging easypanel-nextjs:0.0.1 .PHONY: stop-staging stop-staging: ## Stop the staging docker container. docker stop $$(docker ps -a -q --filter ancestor=easypanel-nextjs:0.0.1) ``` Now, I just do this in the terminal: ```bash $ make build-staging $ make start-staging $ make stop-staging ``` Obviously, the syntax becomes much cleaner with `docker compose` but most VPS CPanels don't support it so this is as good as it gets.
|ethereum|solidity|smartcontracts|remix-ide|
null
with data(s) as ( select 'US' union all select 'France' union all select 'S. Korea' ) select s::countries from data; If you pass a string not part of the enum you will have: ERROR: invalid input value for enum countries: ...
When I go on shellcheck.net it says to add `[` before and after the argument. (e.g `if [ "$VHS" == "exit" ]; then` but when I execute and type rules it says : fbd.sh: 14: [: exit: unexpected operator fbd.sh: 19: [: exit: unexpected operator fbd.sh: 22: [: exit: unexpected operator fbd.sh: 30: [: exit: unexpected operator fbd.sh: 33: [: exit: unexpected operator fbd.sh: 36: [: exit: unexpected operator fbd.sh: 39: [: exit: unexpected operator fbd.sh: 42: [: exit: unexpected operator fbd.sh: 14: [: unexpected operator fbd.sh: 19: [: unexpected operator fbd.sh: 22: [: unexpected operator fbd.sh: 30: [: unexpected operator fbd.sh: 33: [: unexpected operator fbd.sh: 36: [: unexpected operator fbd.sh: 39: [: unexpected operator fbd.sh: 42: [: unexpected operator fbd.sh: 14: [: unexpected operator fbd.sh: 19: [: unexpected operator fbd.sh: 22: [: unexpected operator fbd.sh: 30: [: unexpected operator fbd.sh: 33: [: unexpected operator fbd.sh: 36: [: unexpected operator fbd.sh: 39: [: unexpected operator fbd.sh: 42: [: unexpected operator for the following source: ``` #!/bin/sh # Customize Console # set-title FBD echo "Undertale Jokes, that's all. Mainly. You know, as ya want." while true; do #Input VHS=$(gum input --placeholder " Enter Command") # Treat Inpuit if "$VHS" == "list"; then echo "exit" echo "list" echo "rules" echo "cls" echo "puns" echo "sans" echo "issue" fi if "$VHS" == "exit"; then exit fi if "$VHS" == "rules"; then gum pager ./rules.txt fi if "$VHS" == "cls"; then clear fi if "$VHS" == "issue"; then echo "Go to github.com/fbdev64/FBD/issues and report it." fi if "$VHS" == "sans"; then gum pager ./jokes/sans.txt fi if "$VHS" == "puns"; then ggu pager ./jokes/puns.txt fi if "$VHS" == "time"; then echo $date fi done ```
unexpected operator == in square brackets when trying to use gum lib
|bash|shell|
It's like versions 1.7 (1.7.0 and 1.7.1) don't work for Windows (I know 1.7.1 works on Linux). I took play version 1.6.0 and was able to generate a new project.
I wish to work on an existing gem, which I've checked out from a git repository. I'm using a clean Ruby installation. To start, I would like to install the dependencies specified in the gemspec file so that I can build and test the gem. I'm not using bundler for this. Currently, I manually install the gems by reading the gemspec and invoking 'gem'. What I'd like to do is something like: ``` git clone my_gem cd my_gem gem magically-install-dependencies my_gem.gemspec ``` and have all of the runtime and development dependencies installed as they would be if I'd installed this from a .gem file. Is there a way to do this? I've searched the `gem` documentation and there doesn't seem to be anything that works on gemfiles other than `build`.
I'm deleting your post because this seems like a programming-specific question, rather than a conversation starter. With more detail added, this may be better as a Question rather than a Discussions post. Please see [this page](https://stackoverflow.com/help/how-to-ask) for help on asking a question on Stack Overflow. If you are interested in starting a more general conversation about how to approach an issue or concept related to the topic of this collective, feel free to make another Discussion post. You can check the discussions guidelines at https://stackoverflow.com/help/discussions-guidelines
null
TypeScript has always had [`in` operator narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-in-operator-narrowing) so that `if ("name" in val)` would serve to narrow `{name: string} | {age: number}` to `{name: string}`. TypeScript 4.9 introduced [*unlisted property* narrowing with the `in` operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#unlisted-property-narrowing-with-the-in-operator), so that `if ("age" in val)` would narrow `{name: string}` to the equivalent of `{name: string; age: unknown}`. Yes, these features are mutually inconsistent. You can read the implementing pull request at [microsoft/TypeScript#50666](https://github.com/microsoft/TypeScript/pull/50666), and the feature request at [microsoft/TypeScript#21732](https://github.com/microsoft/TypeScript/issues/21732) discussing how people want the `in` operator to work, and the tradeoffs involved. There is no "correct" mental model that works in all circumstances. TypeScript tries to support idiomatic JavaScript, even though this does not actually cohere into a single whole. TypeScript's type system is intentionally [not sound](https://www.typescriptlang.org/docs/handbook/type-compatibility.html#a-note-on-soundness), in order to enable developers to be productive. Soundness is preferred over unsoundness all else being equal, but developer productivity sometimes matters more. (See [TypeScript Design Non-Goal #3](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals#non-goals).) TypeScript *usually* treats object types as being open/extendible and not closed/sealed/exact. So the value `{a: "x", b: "y"}` is assignable to `{a: string}` despite its excess `b` property. But such things are also causes of errors, so TypeScript has [excess property checks](https://www.typescriptlang.org/docs/handbook/2/objects.html#excess-property-checks), and `in` operator narrowing. --- For the purpose of the `in` operator, I'd say the mental model is the following cognitive dissonance: if you are using `in` to check for a property that exists in some [union](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types) members, TypeScript will treat those union types as closed/sealed/exact and eliminate the other members (even though this is technically unsound). If, on the other hand, you are using `in` to check for a property that does not exist in any union member, then it treats the type as open/extendible and just adds a property of `unknown` type to that object type. Thus, when you write const test = (union: UnionBoth): void => { if ('name' in union && 'age' in union) { union.name union.age } } what happens is: first you check `'name' in union` which narrows `union` from `UnionBoth` to `{name: string}`, *eliminating* `{age: number}`. Then you check `'age' in union` which narrows `union` from `{name: string}` to `{name: string, age: unknown}`. This is completely in line with the above mental model, leading to the frankly bizarre situation here. If you switch the order of your `in` tests, you'll get the opposite bizarre thing. In my opinion, what this shows is: pretty much nobody uses union types the way you're doing now. If they're checking properties with `in`, it's because they are trying to *discriminate* a union, even though it's unsound to do so. If you really want to do this sort of check, you'll need to refactor your union type to be explicit about how things work: type UnionBoth = Name | Age | (Name & Age) const test = (union: UnionBoth): void => { if ('name' in union && 'age' in union) { union; // ^? Name & Age union.name // ^? string union.age // ^? number } } Now the possibility of `Name & Age` is explicitly mentioned, and TypeScript uses its original `in` narrowing to narrow to `Name & Age`, never using the new "unlisted property narrowing" because there's always a union member containing the key you're testing for. [Playground link to code](https://www.typescriptlang.org/play?#code/C4TwDgpgBAcghgW2gXigbygO0RAXFAZ2ACcBLTAcygF8AoUSKAQQpXSjlf0wFcEAjCMRq164aAFVMpAPaYAQjOAALKKnhIoAH2attUABQboAMl0QAlKIDGcolGAR7qAz2lz8U2QqXKL+ADcZUgATNQA+dFooGKhSADNDAHJsJCS4zCg3bygTMyTOCHTyLPdMCyjYqtLvAG5o6piAeiaoAD0AfgbG7LkAOlSIbuqWqs7hqt7MPsKJ2NHY8aq6OiA)
|javascript|reactjs|redux-toolkit|
I'm deleting your post because this seems like a programming-specific question, rather than a conversation starter. With more detail added, this may be better as a Question rather than a Discussions post. Please see [this page](https://stackoverflow.com/help/how-to-ask) for help on asking a question on Stack Overflow. If you are interested in starting a more general conversation about how to approach an issue or concept related to the topic of this collective, feel free to make another Discussion post. You can check the discussions guidelines at https://stackoverflow.com/help/discussions-guidelines
null
I'm deleting your post because this seems like a programming-specific question, rather than a conversation starter. With more detail added, this may be better as a Question rather than a Discussions post. Please see [this page](https://stackoverflow.com/help/how-to-ask) for help on asking a question on Stack Overflow. If you are interested in starting a more general conversation about how to approach an issue or concept related to the topic of this collective, feel free to make another Discussion post. You can check the discussions guidelines at https://stackoverflow.com/help/discussions-guidelines
null
I'm deleting your post because this seems like a programming-specific question, rather than a conversation starter. With more detail added, this may be better as a Question rather than a Discussions post. Please see [this page](https://stackoverflow.com/help/how-to-ask) for help on asking a question on Stack Overflow. If you are interested in starting a more general conversation about how to approach an issue or concept related to the topic of this collective, feel free to make another Discussion post. You can check the discussions guidelines at https://stackoverflow.com/help/discussions-guidelines
null
I'm deleting your post because this seems like a programming-specific question, rather than a conversation starter. With more detail added, this may be better as a Question rather than a Discussions post. Please see [this page](https://stackoverflow.com/help/how-to-ask) for help on asking a question on Stack Overflow. If you are interested in starting a more general conversation about how to approach an issue or concept related to the topic of this collective, feel free to make another Discussion post. You can check the discussions guidelines at https://stackoverflow.com/help/discussions-guidelines
Error with loading a .pb model for prediction: Op type not registered 'DecodeProtoSparseV4'
I recently received a new computer for work (a Mac). I regularly use files which have macros built in. I am not the creator of these files/macros and am not an expert in this area. For one of my files, each time I open it and click "enable macros" I get an error which says "Some controls on this presentation can't be activated. They might not be registered on this computer." I have confirmed that the macros are functioning properly on the windows machines of other colleagues. I have also tried a few other macro enabled files on my Mac which also seem to be functioning properly. Cleary there is some issue with this one file. Any suggestions on how to resolve this issue? I have entered into Visual Basic Editor and confirmed that the code is there. It has been transferred properly via cloud transfer from my old PC to my new Mac.
When I click "enable macros" on my PowerPoint presentation, I get an error saying controls can't be activated. They're not registered on this computer
|vba|powerpoint|
null
I'm writing a MAUI app, in which I'd like to add native buttons to an iOS title bar. As I understand it, I need to call `SetRightBarButtonItems` on the top-most `NavigationItem`, which for a single-page app should be MainPage. I've tried adding the following code to MainPage.xaml.cs: protected override void OnAppearing() { #if IOS var settingsButton = new UIBarButtonItem() { Title="Settings", Image = UIImage.GetSystemImage("gearshape") }; var ni = Platform.GetCurrentUIViewController().NavigationItem; ni.Title = "TEST!!"; ni.SetRightBarButtonItems([settingsButton],true); #endif base.OnAppearing(); } But it doesn't seem to be getting the correct ViewController - or it doesn't reflect the changes correctly (even the title property doesn't work). It's getting a ViewController, which isn't the case if I try running this in AppShell.xaml.cs, but anything I do to it doesn't get reflected in the UI - what is it i'm missing here?
Access UINavigationItem from within MAUI ContentPage (in order to add native buttons to navigationbar)
|c#|ios|uikit|maui|
The Imagick extension functions perfectly with PHP 8.1 and Laravel 10, but not with PHP 8.2. The new Laravel 11 is compatible with PHP 8.2, which implies that the Imagick library must also be installed to operate correctly. However, I have been unable to find instructions on how to install Imagick on PHP 8.2. I understand that Imagick is pre-installed in PHP 8.2.17, but the .dll file is not present in the ext folder. So, how can I set up my environment to work with Laravel 11, PHP 8.2, Intervention Image, and Imagick locally using Laragon, XAMPP, or WAMPP? And how can I do the same in a production environment using Ubuntu 22? I am trying to use Laravel 11 with PHP 8.2 and Intervention to process images.
Adding Imagick extension in Laragon, XAMPP, WAMPP to be used in Laravel 11 with PHP 8.2?
|internationalization|schema|json-ld|
null
I need to fine-tune an LLM on a custom dataset that includes both text and images extracted from PDFs. For the text part, I've successfully extracted the entire text data and used the OpenAI API to generate questions and answers in JSON/CSV format. This approach has been quite effective for text-based fine-tuning. However, I'm unsure about how to proceed with images. Can anyone suggest a method or library that can help me process and incorporate images into the fine-tuning process? And then later, using the fine-tuned model for QnA. Additionally, I'm confused about which model to use for this task. Any guidance, resources, or insights would be greatly appreciated.
Fine-Tuning Large Language Model on PDFs containing Text and Images
|extract|openai-api|large-language-model|fine-tuning|
I'm currently working on unit testing a Flask application using pytest. However, when I attempt to test my routes (seemingly any of my routes), I consistently receive a 404 Not Found error, despite the route being defined and working as expected outside of the testing environment. I've checked the route registration and application factory setup but haven't found the cause of the issue. Environment: Flask 2.x pytest Python 3.x config.py; class Config: SQLALCHEMY_TRACK_MODIFICATIONS = False class DevelopmentConfig(Config): SQLALCHEMY_DATABASE_URI = 'sqlite:////path/to/development.db' DEBUG = True class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:' SQLALCHEMY_TRACK_MODIFICATIONS = False app.py (simplified for brevity): def create_app(config_class=DevelopmentConfig): app = Flask(__name__) app.config.from_object(config_class) # Load the configuration from the provided class app.config['SQLALCHEMY_DATABASE_URI'] = config_class.SQLALCHEMY_DATABASE_URI app.config['SECRET_KEY'] = 'your_secret_key' # Initialize extensions with the app db.init_app(app) migrate.init_app(app, db) return app app = create_app() @app.route('/login', methods=['GET', 'POST']) def login(): # Route implementation return render_template('login.html') test_app.py: import pytest from apis.stockpulse.app import create_app from apis.stockpulse.config import TestingConfig @pytest.fixture def client(): app = create_app(TestingConfig) with app.test_client() as client: with app.app_context(): yield client def test_login_get(client): response = client.get('/login') assert response.status_code == 200 # Fails with 404 Problem: When running the test for the /login route, pytest returns a 404 status code, even though the route is correctly defined. I've attempted to debug by printing out all registered routes using app.url_map in the fixture, and it appears that only the default static route is registered. Attempts to Solve: Verified the route is correctly defined and works outside of testing. Ensured the TestingConfig is correctly applied, with TESTING = True. Checked for correct application context in tests. Attempted to explicitly print registered routes, which only showed the static route. I'm at a loss for what's causing this issue. Could it be related to how I'm initializing the app for testing or perhaps something to do with the application context not properly encapsulating the route definitions? Any insights or suggestions would be greatly appreciated.
I'm encountering difficulties while trying to post form data, including file uploads, to MongoDB using Multer and Express. Although the files are successfully uploaded to Firebase Storage, the form data is not being posted to MongoDB. I've verified that the form data is being sent correctly and that my server-side code is correctly parsing the incoming data. Additionally, my MongoDB connection seems to be established without any issues. Could anyone provide insights into potential solutions or debugging steps to resolve this issue? Any help would be greatly appreciated. User Model: ``` User +-----------------------------------------+ | User | +-----------------------------------------+ | _id: ObjectId | | firstname: String (required, min: 2, | | max: 50) | | lastname: String (required, min: 2, | | max: 50) | | email: String (required, max: 50, | | unique: true) | | password: String (required, min: 6) | | picturepath: String (default: "") | | friends: Array (default: []) | | location: String | | occupation: String | | viewedprofile: Number | | impression: Number | | createdAt: Date | | updatedAt: Date | +-----------------------------------------+ ``` index.js (Server): ``` const __filename=fileURLToPath(import.meta.url); const __dirname= path.dirname(__filename); dotenv.config(); const app=express(); app.use(express.json()) app.use(helmet()); app.use(helmet.crossOriginResourcePolicy({policy:"cross-origin"})); app.use(morgan("common")); app.use(bodyParser.json({limit:"30mb",extended:true})); app.use(bodyParser.urlencoded({limit:"30mb",extended:true})); app.use(cors()); app.use("/assets",express.static(path.join(__dirname,'public/assets'))); /* File Storage */ const Storage = multer.memoryStorage(); // Use memory storage for handling files in memory const upload = multer({ storage: Storage }); /*Routes With Files*/ app.post("/auth/register", upload.single("picture"), async (req, res) => { try { if (!req.file) { return res.status(400).json({erro:'No files were uploaded.'}); } const bucket = firebaseStorage; const file = bucket.file(req.file.originalname); const metadata = { metadata: { contentType: req.file.mimetype, }, }; await file.save(req.file.buffer, metadata); const [url] = await file.getSignedUrl({ action: 'read', expires: '01-01-2100' }); const picturepath = url; res.status(201).json({ picturepath }); } catch (error) { console.error('Error uploading file to Firebase Storage:', error); res.status(500).json({ error: 'Internal server error' }); } },register); /*Routes */ app.use("/auth",authRoutes); app.use("/users",userRoutes); app.use("/posts",postRoutes) /*MONGOOSE SETUP */ const PORT=process.env.PORT || 6001; mongoose.connect(process.env.MONGO_URL) .then(()=>{ app.listen(PORT,()=>console.log(`Server Started`)); // User.insertMany(users); // Post.insertMany(posts); }) .catch((error)=>console.log(`${error} did not connect`)); ``` Form.jsx (frontend): ``` import { useState } from "react"; import { Box, Button, TextField, useMediaQuery, Typography, useTheme, } from "@mui/material"; import EditOutlinedIcon from "@mui/icons-material/EditOutlined"; import { Formik } from "formik"; import * as yup from "yup"; import { useNavigate } from "react-router-dom"; import { useDispatch } from "react-redux"; import { setLogin } from "../../state"; import Dropzone from "react-dropzone"; import FlexBetween from "../../components/FlexBetween"; import { ref, uploadBytes, getDownloadURL } from "firebase/storage"; import { imageDB } from "../../firebaseConfig"; const registerSchema = yup.object().shape({ firstname: yup.string().required("required"), lastname: yup.string().required("required"), email: yup.string().email("invalid email").required("required"), password: yup.string().required("required"), location: yup.string().required("required"), occupation: yup.string().required("required"), picture: yup.string().required("required"), }); const loginSchema = yup.object().shape({ email: yup.string().email("invalid email").required("required"), password: yup.string().required("required"), }); const initialValuesRegister = { firstname: "", lastname: "", email: "", password: "", location: "", occupation: "", picture: "", }; const initialValuesLogin = { email: "", password: "", }; const Form = () => { const [pageType, setPageType] = useState("login"); const [alertMessage, setAlertMessage] = useState(""); const { palette } = useTheme(); const dispatch = useDispatch(); const navigate = useNavigate(); const isNonMobile = useMediaQuery("(min-width:600px)"); const isLogin = pageType === "login"; const isRegister = pageType === "register"; const handleFileUpload = async (file) => { try { if (!file) { throw new Error("File is undefined or null"); } const storageRef = ref(imageDB); // Use imageDb instead of storage const fileRef = ref(storageRef, `Users/${file.name}`); await uploadBytes(fileRef, file); const downloadURL = await getDownloadURL(fileRef); console.log(downloadURL); return downloadURL; } catch (error) { console.error("Error uploading image:", error); throw error; } }; const register = async (values, onSubmitProps) => { try { values.email = values.email.toLowerCase(); const imageURL = await handleFileUpload(values.picture); const formData = new FormData(); for (let key in values) { formData.append(key, values[key]); } formData.append("picturepath", imageURL); for (const entry of formData.entries()) { console.log(entry); } const savedUserResponse = await fetch( "http://localhost:3001/auth/register", { method: "POST", body: formData, } ); const savedUser = await savedUserResponse.json(); console.log("SAVED USER:", savedUser.picturepath); if (savedUser.error) { console.log(savedUser.msg); setAlertMessage(savedUser.msg); } else { onSubmitProps.resetForm(); setPageType("login"); } } catch (error) { console.error("Error registering:", error); setAlertMessage(error.message || "Failed to register"); } }; const login = async (values, onSubmitProps) => { const loggedInResponse = await fetch("http://localhost:3001/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(values), }); const loggedIn = await loggedInResponse.json(); onSubmitProps.resetForm(); if (loggedIn.msg) { setAlertMessage(loggedIn.msg); } else { dispatch( setLogin({ user: loggedIn.user, token: loggedIn.token, }) ); navigate("/home"); } }; const handleFormSubmit = async (values, onSubmitProps) => { if (isLogin) await login(values, onSubmitProps); if (isRegister) await register(values, onSubmitProps); }; return ( <Formik onSubmit={handleFormSubmit} initialValues={isLogin ? initialValuesLogin : initialValuesRegister} validationSchema={isLogin ? loginSchema : registerSchema} > {({ values, errors, touched, handleBlur, handleChange, handleSubmit, setFieldValue, resetForm, }) => ( <form onSubmit={handleSubmit}> <Box display="grid" gap="30px" gridTemplateColumns="repeat(4, minmax(0, 1fr))" sx={{ "& > div": { gridColumn: isNonMobile ? undefined : "span 4" }, }} > {isRegister && ( <> <TextField label="First Name" onBlur={handleBlur} onChange={handleChange} value={values.firstname} name="firstname" error={ Boolean(touched.firstname) && Boolean(errors.firstname) } helperText={touched.firstname && errors.firstname} sx={{ gridColumn: "span 2" }} /> <TextField label="Last Name" onBlur={handleBlur} onChange={handleChange} value={values.lastname} name="lastname" error={Boolean(touched.lastname) && Boolean(errors.lastname)} helperText={touched.lastname && errors.lastname} sx={{ gridColumn: "span 2" }} /> <TextField label="Location" onBlur={handleBlur} onChange={handleChange} value={values.location} name="location" error={Boolean(touched.location) && Boolean(errors.location)} helperText={touched.location && errors.location} sx={{ gridColumn: "span 4" }} /> <TextField label="Occupation" onBlur={handleBlur} onChange={handleChange} value={values.occupation} name="occupation" error={ Boolean(touched.occupation) && Boolean(errors.occupation) } helperText={touched.occupation && errors.occupation} sx={{ gridColumn: "span 4" }} /> <Box gridColumn="span 4" border={`1px solid ${palette.neutral.medium}`} borderRadius="5px" p="1rem" > <Dropzone acceptedFiles=".jpg,.jpeg,.png" multiple={false} onDrop={(acceptedFiles) => setFieldValue("picture", acceptedFiles[0]) } > {({ getRootProps, getInputProps }) => ( <Box {...getRootProps()} border={`2px dashed ${palette.primary.main}`} p="1rem" sx={{ "&:hover": { cursor: "pointer" } }} > <input {...getInputProps()} /> {!values.picture ? ( <p>Add Picture Here</p> ) : ( <FlexBetween> <Typography>{values.picture.name}</Typography> <EditOutlinedIcon /> </FlexBetween> )} </Box> )} </Dropzone> </Box> </> )} <TextField label="Email" onBlur={handleBlur} onChange={handleChange} value={values.email} name="email" error={Boolean(touched.email) && Boolean(errors.email)} helperText={touched.email && errors.email} sx={{ gridColumn: "span 4" }} /> <TextField label="Password" type="password" onBlur={handleBlur} onChange={handleChange} value={values.password} name="password" error={Boolean(touched.password) && Boolean(errors.password)} helperText={touched.password && errors.password} sx={{ gridColumn: "span 4" }} /> </Box> {/* BUTTONS */} <Box> {alertMessage && ( <Typography variant="body2" sx={{ color: "red", mb: 2 , mt:1}} >{alertMessage}</Typography> )} <Button fullWidth type="submit" sx={{ m: "2rem 0", p: "1rem", backgroundColor: palette.primary.main, color: palette.background.alt, "&:hover": { color: palette.primary.main }, }} > {isLogin ? "LOGIN" : "REGISTER"} </Button> <Typography onClick={() => { setPageType(isLogin ? "register" : "login"); resetForm(); }} sx={{ textDecoration: "underline", color: palette.primary.main, "&:hover": { cursor: "pointer", color: palette.primary.light, }, }} > {isLogin ? "Don't have an account? Sign Up here." : "Already have an account? Login here."} </Typography> </Box> </form> )} </Formik> ); }; export default Form; ``` I implemented a form using React and used the react-dropzone library for file uploads. Upon form submission, I expected the file is been uploaded to file storage and also getting picturepath as imageurl. Not getting any error in terminal as well as console but unable to see entry in db. Please check my register function .
Unable to Post Form Data to MongoDB because of picturepath
|reactjs|node.js|express|mongoose|firebase-storage|
null
I have an app that uses OpenAI and like many others my key was recently compromised. I have this simple code: const functions = require('firebase-functions'); const OpenAI = require("openai"); const openai = new OpenAI({ apiKey: functions.config().openai.key, }); exports.generateText = functions.https.onCall(async (data, context) => { try { const response = await openai.chat.completions.create({ messages: [{ role: 'user', content: data.prompt }], model: 'gpt-3.5-turbo', }); return { response: response.choices[0].message.content }; } catch (error) { throw new functions.https.HttpsError('internal', 'Failed to generate text from OpenAI.'); } }); that I then call within my iOS app as follows: let functions = Functions.functions() func generateText(prompt: String, completion: @escaping (String?, Error?) -> Void) { functions.httpsCallable("generateText").call(["prompt": prompt]) { result, error in if let error = error as NSError? { if error.domain == FunctionsErrorDomain { let code = FunctionsErrorCode(rawValue: error.code) let message = error.localizedDescription let details = error.userInfo[FunctionsErrorDetailsKey] print(code, message, details) return } } if let textResponse = (result?.data as? [String: Any])?["response"] as? String { completion(textResponse, nil) } else { completion(nil, NSError(domain: "AppErrorDomain", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to parse function response"])) } } } However as I'm not a backend engineer, I'm wondering if this is secure, or what is to stop someone using this endpoint? E.g. is this automatically restricted to being called from my app? Is there a way to do that? I note other responses ask to authenticate the user via a login, but I would rather avoid that within my app. Thank you!
Protect OpenAI key using Firebase function
|swift|firebase|google-cloud-functions|openai-api|
I am relaying my ssh connection and I want to restrict the ability of the remote user to view my files so I set `umask = 027`. However, it seems to also affect the local user in some way as I can no longer `mkdir` as the local user using either ``` mkdir test ``` or ``` sudo mkdir test ``` both yield `Permission denied` error However, I can ``` touch test ``` with no problem. I have checked that ownership of the current folder is the local user logged into wsl.
I was scrolling on stackoverflow and found this post: https://stackoverflow.com/questions/11287402/how-to-round-corner-a-logo-without-white-backgroundtransparent-on-it-using-pi It reminded me of your question I commented on 4 days ago saying it is not possible to round corners in customtkinter, so I am here to correct myself. It is indeed possible to do it using `PIL.ImageDraw.Draw.ellipse()`, here is the code: ```python from PIL import Image, ImageDraw def add_corners(im, rad): circle = Image.new('L', (rad * 2, rad * 2), 0) draw = ImageDraw.Draw(circle) draw.ellipse((0, 0, rad * 2 - 1, rad * 2 - 1), fill=255) alpha = Image.new('L', im.size, 255) w, h = im.size alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0)) alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h - rad)) alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (w - rad, 0)) alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)), (w - rad, h - rad)) im.putalpha(alpha) return im ``` In you case, the full code is: ```python import customtkinter from PIL import Image, ImageDraw image_path = #image path def add_corners(im, rad): circle = Image.new('L', (rad * 2, rad * 2), 0) draw = ImageDraw.Draw(circle) draw.ellipse((0, 0, rad * 2 - 1, rad * 2 - 1), fill=255) alpha = Image.new('L', im.size, 255) w, h = im.size alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0)) alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h - rad)) alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (w - rad, 0)) alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)), (w - rad, h - rad)) im.putalpha(alpha) return im class App(customtkinter.CTk): def __init__(self): super().__init__() frame = customtkinter.CTkFrame(self, width=200, height=111, corner_radius=5) frame.pack() image = customtkinter.CTkImage(add_corners(Image.open(image_path), 100), size=(200, 111)) image_label = customtkinter.CTkLabel(frame, image=image, text="") image_label.pack() if __name__ == "__main__": app = App() app.mainloop() ``` But this only works using .png pictures if you want a transparent background (like said in the post linked above). If you have more questions, you should refere to the post above: there is already troubleshooting here. Hope I helped you, have a nice day. Edit: because I found rounding corners useful, I created a module containing a class to automate this functionnality, the module is called MoreCustomTkinterWidgets on Pypi.
I will offer my own option for docker run. The problem of passing multi-line variables in a .env file was discussed here. https://github.com/moby/moby/issues/12997 But unfortunately, the problem has not been resolved as of 2024, and the developers suggest solving the problem using sh/bash How to solve the problem using sh 1. putting multi-line data into a file and import to variable MY_VAR.env ``` Text Text Text ``` `docker run -e MY_VAR="$(cat MY_VAR.env)"` 2. If you need to pass many variables from a file, then you will have to do a compound query Variables format in file `-e NAME_VARIABLE="Multi-line text" \` my.env ``` -e MY_VAR=" Text Text text " \ -e MY_VAR2="TEXT" \ -e MY_VAR3="TEXT TEXT TEXT" ``` `sh -c "docker run $(cat my.env)"`
I recently chose to remake the popular game called "soccer physics" but in pygame instead of its original engine, unity. However, I have a quite limited understanding of pygame and implementing game physics, so I've only managed to create [this](https://stackoverflow.com) so far with characters and sprites I found online (I know it's quite bad but it's my first time trying to code an actual 2d game). I aimed to make it a bit more fun and unique with the city background and the platform. I decided to only make one player for now as I'll be using object oriented programming, so I'm thinking I can just create the other 3 players once I've made the code for one of them in a class. Please do correct me if I'm mistaken on that. The main problem right now is the jumping and collisions, which are going to be a big obstacle for me. I managed to make the characters a very simple jump function, with moving and tilting in random directions, however it looks sort of robotic and there's no ragdoll or realistic physics to the jumping, as seen in the original soccer physics. I also have no idea on how I'll make the ball collide with the players and the ground and move accordingly. I've looked up countless tutorials but all of them use simple circles, whereas I'm trying to use an actual image of a football as a sprite along with football players, and I'm finding find this very hard to implement. Here's what I've got so far: ``` if keys[pygame.K_a] and not jumping: # checks to see if up arrow key is pressed and player isn't jumping jumping = True # sets jumping to true - activates the jump algorithm possibilities = [(x - xvelocity), (x + xvelocity)] # list of the two possible directions - right and left angles = [15,20,25,30,35] # list of random possible angles direction = random.choice(possibilities) # picks a random direction for movement angle = random.choice(angles) # picks a random angle from the given list ``` ``` if jumping: # checks if jumping is set to true (in other words if a has been pressed) y -= yvelocity # moves the player's y-position upwards yvelocity -= gravity # induces gravity to the jumping velocity, resulting in a deceleration and the player moving back down if y <= 300: # checks to see if plauer is above a certain height in the jump, and isn't colliding with the goalpost if direction == possibilities[1] and not goalright.rect.colliderect(hitbox): # checks if direction is chosen to be forward or backward x = x + xvelocity # moves player forward/left else: # checks if direction is chosen to be forward or backward x = x - xvelocity # moves player backward/right xvelocity = 1 # returns velocity back to normal if yvelocity < -15: # checks to see if max velocity/height is reached jumping = False # stops the jumping function yvelocity = 15 # returns velocity to original value / moves the player back down if direction == possibilities[1] and x < 665: # if direction is to the right (x + the velocity) display.blit((pygame.transform.rotate(player1kick, -1*angle)),(x,y)) # draws player rotated at a clockwise angle, depending on the direction they're moving elif direction == possibilities[0] and x < 665: # if direction is to the left (x - the velocity) display.blit((pygame.transform.rotate(player1kick, angle)),(x,y)) # if direction is to the left, player rotates anti-clockwise; if to the right, player rotates clockwise. else: display.blit(player1,(x,y)) # draws normal state if too close to the goal else: display.blit(player1,(x,y)) # draws normal state on the ground ``` I know it's a big ask, but if someone could give me advice on how to implement the football and jumping, similar to soccer physics, that would be great. Otherwise, please tell me if I've just made a bad choice trying to do this in pygame.
How would I code player jump physics, similar to "soccer physics", and make players collide with a ball in pygame?
|pygame|game-physics|pymunk|
null
I'm working on some code for a javascript implemenation of Conway's Game of Life Cellular Automata for a personal project, and I've reached the point of encoding the rules. I am applying the rules to each cell, then storing the new version in a copy of the grid. Then, when I'm finished calculating each cell's next state, I set the first grid's state to the second's one, empty the second grid, and start over. Here's the code I used for the rules: ``` if (Cell(i, j) == 1) { if (Nsum(i, j) == 2 || Nsum(i, j) == 3) ncells[j][i] = 1; else ncells[j][i] = 0; } else { if (Nsum(i, j) == 3) ncells[j][i] = 1; else ncells[j][i] = 0; } ``` Nsum is the function that calculates the neighborhood sum of the current cell. I say ncells[j][i] instead of ncells[i][j] because in a 2d array you adress the row first. I didn't try much, but I can't imagine a solution. Help! **EDIT:** Minimum Reproducible Example: ``` //10x10 grid let ecells = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]; let cells = empty_cells; let new_cells = cells; let paused = true; function Cell(x, y) { return cells[y][x]; } function Nsum(i, j) { if (i >= 1 && j >= 1) { return Cell(i - 1, j) + Cell(i + 1, j) + Cell(i, j - 1) + Cell(i - 1, j - 1) + Cell(i + 1, j - 1) + Cell(i, j + 1) + Cell(i - 1, j + 1) + Cell(i + 1, j + 1); } } //One can manually change the state of the cells in the "cells" grid, //which works correctly. Then, one can run the CA by changing the "paused" //value to false. function simulation() { for (i = 0; i < cells[0].length; i++) { for (j = 0; j < cells.length; j++) { if (Cell(i, j)) { ctx.fillRect(20*i - 0.5, 20*j, 20, 20); if (!pause) { if (Nsum(i, j) == 2 || Nsum(i, j) == 3) ncells[j][i] = 1; else ncells[j][i] = 0; } } else { ctx.clearRect(20*i - 0.5, 20*j, 20, 20); if (!pause) { if (Nsum(i, j) == 3) ncells[j][i] = 1; else ncells[j][i] = 0; } } } } if (!pause) cells = ncells; ncells = ecells; requestAnimationFrame(simulation); } simulation(); ```
Installing dependencies from a gemspec file
|ruby|rubygems|
null