instruction
stringlengths
0
30k
Supabase auth sessions are stored client-side, so in theory clearing local storage without calling your logout API endpoint should suffice. However the downside is that if the user is logged in on multiple devices, this will only log them out on the current one.
I coded this to output a title to the a window in tkinter and when I run my code a window pops up but there is no text inside. import tkinter as tk from tkinter import ttk #window window = tk.Tk() window.title ('Test') window.geometry('300x150') #title title_label = ttk.Label(master=window, text= 'Test Test Test', font='Calibri 24') title_label.pack() #run window.mainloop() [enter image description here](https://i.stack.imgur.com/Fdfrv.png)` your text`
I generate a temporary csv from a sheet of an xlsm file. Below saves it locally. I only need it to be emailed. ```vba Sub ExportSheetAsCSVAndEmail3() Dim ws As Worksheet Dim wbExport As Workbook Dim csvFile As String Dim OutApp As Object, OutMail As Object Set ws = ThisWorkbook.Worksheets("Testinfo") Set wbExport = Application.Workbooks.Add ws.Copy Before:=wbExport.Worksheets(wbExport.Worksheets.Count) csvFile = ThisWorkbook.Path & "\" & ws.Name & ".csv" wbExport.SaveAs FileName:=csvFile, FileFormat:=xlCSV Set OutApp = CreateObject("Outlook.Application") Set OutMail = OutApp.CreateItem(0) With OutMail .To = "Test@Test.com" .subject = "CSV Exported" .body = "As attached." .Attachments.Add csvFile .Send End With wbExport.Close SaveChanges:=False Set OutMail = Nothing Set OutApp = Nothing End Sub ``` It seems you must save a copy of the generated csv locally then reference it as the attached. This would cause a pile of unnecessary csv files on the machine over time. There is the `Kill` function to remove the csv after its emailed but that requires elevated rights so it's not practical. Is there is a workaround like referencing it from memory?
Generate temporary csv from sheet then attach to email without saving
|excel|vba|outlook|
null
Here is a slightly edited version that will work in the expected way: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> $("#test-form").on("input",function(ev){ const checked=$(".form-check-input:checked").get().map(el=>el.value) $("#selected-cases").val(checked.join(",")); }).submit(function(ev){ // at submit time: copy input text to #summary div $("#summary").html("selected-cases : <br/>"+$("#selected-cases").val()) ev.preventDefault(); }) <!-- language: lang-css --> #selected-cases {width:500px} <!-- language: lang-html --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <form id="test-form"> <div class="col-12"> <label for="selected-cases" class="form-label">selected cases<span class="text-muted"> *</span></label> <input type="text" id="selected-cases" name="selected-cases" class="form-control" value="3966382,4168801,4168802,4169839"> </div> <hr class="my-4"><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3966382" checked>Save CaseID : 3966382</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4029501">Save CaseID : 4029501</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168818">Save CaseID : 4168818</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168801" checked>Save CaseID : 4168801</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168802" checked>Save CaseID : 4168802</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168822">Save CaseID : 4168822</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3966388">Save CaseID : 3966388</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4114087">Save CaseID : 4114087</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3966385">Save CaseID : 3966385</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169838">Save CaseID : 4169838</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169843">Save CaseID : 4169843</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168829">Save CaseID : 4168829</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168828">Save CaseID : 4168828</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168835">Save CaseID : 4168835</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169835">Save CaseID : 4169835</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169836">Save CaseID : 4169836</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169837">Save CaseID : 4169837</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169839" checked>Save CaseID : 4169839</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3946200">Save CaseID : 3946200</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3946201">Save CaseID : 3946201</label> </div> <button class="w-10 btn btn-primary btn-sm" type="submit">Save</button> <div class="col-md-5"> <div id="summary"> selected-cases : <br/> </div> </div> </form> <!-- end snippet -->
I am new to gcc and I'm trying to modify the source code of either *gcc* or *arm-none-eabi-gcc* in order to rename the compiler in the codebase to something like *myCompiler*. This adjustment would enable commands such as `myCompiler --version` to be recognized. I understand that using symbolic links offers a workaround, but it doesn't involve modifying the source code directly. I am specifically interested in altering the source code and renaming `gcc` to `myCompiler`. I've downloaded the source code for both *gcc* and *arm-none-eabi-gcc*, but I'm uncertain how to proceed. I'm unable to locate main files such as gcc.c or main.c that I could play around with. Any guidance on how to begin would be greatly appreciated.
UPDATE The parameter has been updated to **with_vectors**. Simply set with_vectors = True in your search method.
|javascript|html|reactjs|button|
When running my code I realized that after around 30 requests it gets very slow to fetch the rest, taking a long time to complete the code. My goal with this code is to fetch users from a Telegram's group and dump their information in a JSON file, with ther name, username and bio. This is the code I am running: ``` import configparser import json import asyncio from telethon.tl.functions.users import GetFullUserRequest from telethon import TelegramClient from telethon.errors import SessionPasswordNeededError from telethon.tl.functions.channels import GetParticipantsRequest from telethon.tl.types import ChannelParticipantsSearch from telethon.tl.types import ( PeerChannel ) # Reading Configs config = configparser.ConfigParser() config.read("config.ini") # Setting configuration values api_id = config['Telegram']['api_id'] api_hash = config['Telegram']['api_hash'] api_hash = str(api_hash) phone = config['Telegram']['phone'] username = config['Telegram']['username'] # Create the client and connect client = TelegramClient(username, api_id, api_hash) async def main(phone): await client.start() print("Client Created") # Ensure you're authorized if await client.is_user_authorized() == False: await client.send_code_request(phone) try: await client.sign_in(phone, input('Enter the code: ')) except SessionPasswordNeededError: await client.sign_in(password=input('Password: ')) me = await client.get_me() user_input_channel = input("enter entity(telegram URL or entity id):") if user_input_channel.isdigit(): entity = PeerChannel(int(user_input_channel)) else: entity = user_input_channel my_channel = await client.get_entity(entity) offset = 0 limit = 100 all_participants = [] count = 0 while True: participants = await client(GetParticipantsRequest(my_channel, ChannelParticipantsSearch(''), offset, limit,hash=0)) if not participants.users or offset >= 100: break all_participants.extend(participants.users) count +=1 print(len(participants.users)) offset += len(participants.users) print("finished") all_user_details = [] for participant in all_participants: user_full = await client(GetFullUserRequest(participant.id)) all_user_details.append({ "id": user_full.full_user.id, "bio": user_full.full_user.about }) with open('user_data.json', 'w') as outfile: json.dump(all_user_details, outfile) with client: client.loop.run_until_complete(main(phone)) ``` With some debug I could realize that the problem is the in the for loop, this is the loop it is taking a long time to complete ``` for participant in all_participants: user_full = await client(GetFullUserRequest(participant.id)) all_user_details.append({ "id": user_full.full_user.id, "bio": user_full.full_user.about }) ``` Why is this happening and how do I optmize this code to run more effiently? My compiler is python3 version 3.11.6 Do you guys need more information? **Update----------------** What I have tried: As [jsbueno](https://stackoverflow.com/users/108205/jsbueno) suggested, I've adjusted my code to send multiple requests instead of one request by user, using the asyncio. It worked well for a group base with 80 users, but above from that, I got the following errors: 1. `Server response had invalid buffer: Invalid response buffer (HTTP code 429)` 2. `Server indicated flood error at transport level: Invalid response buffer (HTTP code 429)` which indicates too many concurrent requests to the API, so I have tried with the semaphore method, and ended up with the code like this: ``` # ... (other imports and code) api_semaphore = asyncio.Semaphore(10) #Updated line async def main(phone): await client.start() print("Client Created") # Ensure you're authorized if await client.is_user_authorized() == False: await client.send_code_request(phone) try: await client.sign_in(phone, input('Enter the code: ')) except SessionPasswordNeededError: await client.sign_in(password=input('Password: ')) me = await client.get_me() user_input_channel = input("enter entity(telegram URL or entity id):") if user_input_channel.isdigit(): entity = PeerChannel(int(user_input_channel)) else: entity = user_input_channel my_channel = await client.get_entity(entity) # Fetch all participants offset = 0 limit = 100 all_participants = [] count = 0 while True: participants = await client(GetParticipantsRequest(my_channel, ChannelParticipantsSearch(''), offset, limit,hash=0)) if not participants.users or offset >= 1000: break all_participants.extend(participants.users) count +=1 print(len(participants.users)) offset += len(participants.users) print("finished") # Process the participants as needed all_user_details = [] tasks = [] for participant in all_participants: async with api_semaphore: # This will prepare all requests and let them be ready to go tasks.append(asyncio.create_task(client(GetFullUserRequest(participant.id)))) #Updated line # ... (rest of the code) ``` With that code, I still have the same problems mentioned earlier, even though they are limited in concurrent requests now. Why is this happening, and what is taking so much time of processing after the loops are finished?
I've been having lots of problems with ```NavigationSplitView``` in **SwiftUI** under **macOS** (14.3 if it matters). The latest one is this: ```NavigationSplitViewVisibility.detailOnly``` doesn't seem to do anything, it just reverts to showing the 3 original columns. If anyone knows how to actually trigger ```NavigationSplitView``` to only display the detail area I will be eternally grateful. This is the code that is not working: ``` import SwiftUI struct ContentView: View { @State private var columnVisibility: NavigationSplitViewVisibility = .all private var cvString: String { "\(columnVisibility)"} var body: some View { NavigationSplitView(columnVisibility: $columnVisibility) { VStack { Text("Sidebar") .frame(maxWidth: .infinity, maxHeight: .infinity) } .background(.red) } content: { VStack { Text("Content") .frame(maxWidth: .infinity, maxHeight: .infinity) } .background(.orange) } detail: { VStack { Spacer() Text("Detail") .frame(maxWidth: .infinity, maxHeight: .infinity) HStack { Text("Current Visibility:") .bold() Text("\(cvString)") .fontDesign(.monospaced) } Button("Next Visibility") { self.columnVisibility = columnVisibility.next() } Spacer() } .background(.green) } } } // Extension just to toggle between Visibilities extension NavigationSplitViewVisibility { func next() -> NavigationSplitViewVisibility { switch self { case .all: print("All -> DetailOnly"); return .detailOnly case .detailOnly: print("DetailOnly -> DoubleColumn"); return .doubleColumn case .doubleColumn: print("DoubleColumn -> All"); return .all default: print("Not handled.") return self } } } ```
NavigationSplitViewVisibility.detailOnly not working in macOS
|swift|macos|swiftui|navigationsplitview|navigationsplitviewvisibility|
I'm following the Next.js 14 Learning Tutorial ([https://nextjs.org/learn/dashboard-app/fetching-data][1]) and I'm able to do everything they show. To show data in the frontend they first create a file with the definitions of our data: **definitions.tsx** // This file contains type definitions for your data. // It describes the shape of the data, and what data type each property should accept. // For simplicity of teaching, we're manually defining these types. // However, these types are generated automatically if you're using an ORM such as Prisma. export type User = { id: string; name: string; email: string; password: string; }; then in another file, we have the query: **data.tsx** import { sql } from '@vercel/postgres'; import { unstable_noStore as noStore } from 'next/cache'; import { Users } from './definitions'; export async function fetchUsers() { noStore(); try { const data = await sql<User>`SELECT * FROM users LIMIT 5`; const result = data.rows; return result; } catch (error) { console.error('Database Error:', error); throw new Error('Failed to fetch data.'); } } the ui with the fetched data is created in another file. I will write the example they give first: **latest-invoices.tsx** import { ArrowPathIcon } from '@heroicons/react/24/outline'; import clsx from 'clsx'; import Image from 'next/image'; import { lusitana } from '@/app/ui/fonts'; import { LatestInvoice } from '@/app/lib/definitions'; export default async function LatestInvoices({ latestInvoices, }: { latestInvoices: LatestInvoice[]; }) { return ( <div className="flex w-full flex-col md:col-span-4 lg:col-span-4"> <h2 className={`${lusitana.className} mb-4 text-xl md:text-2xl`}> Latest Invoices </h2> <div className="flex grow flex-col justify-between rounded-xl bg-gray-50 p-4"> {<div className="bg-white px-6"> {latestInvoices.map((invoice, i) => { return ( <div key={invoice.id} className={clsx( 'flex flex-row items-center justify-between py-4', { 'border-t': i !== 0, }, )} > ... it's way more complex than what I want to do. I want to display the user data in rows in the page. For that I created a simple file like that: **user-list.tsx** import { User } from '@/app/lib/definitions'; export default async function UserList({ userList, }: { userList: User[]; }) { userList.map((variable, i) => { return ( <p> {variable.id} <br /> {variable.name} <br /> {variable.email} <br /> {variable.password} </p> )}); } Using that I receive the following error message: Error: Cannot read properties of undefined (reading 'map') 6 | userList: User[]; 7 | }) { > 8 | userList.map((variable, i) => { | ^ 9 | return ( 10 | <p> 11 | {variable.id} <br /> As a matter of fact, I'm not very aware what this chunck of the code (latest-invoices.tsx) makes and it will be great if someone could explain it to me. Is it specific of TypeScript? export default async function LatestInvoices({ latestInvoices, }: { latestInvoices: LatestInvoice[]; }) { and in my file (user-list.tsx), I tried to copy this logic above without knowing well what I was doing and for sure the problem is here. It's mapping somehow the array from the users query, but I'm not sure if the data is fit to an array... export default async function UserList({ userList, }: { userList: User[]; }) { userList.map((variable, i) => { So I'd appreciate if you could show me the simpliest way to display the user data like this: id01 - UserName01 - email01 - password01 id02 - UserNmae02 - email02 - password02 etc. [1]: https://nextjs.org/learn/dashboard-app/fetching-data
Display user data in Next.js 14 standards without extra libs
|react-typescript|next.js14|
|python|linear-regression|
|sql|presto|trino|
[ 'a' => [ 'a' => ['a' => null, 'b' => null], 'b' => ['a' => null, 'b' => null] ], 'b' => [ 'a' => ['a' => null, 'b' => null], 'b' => ['a' => null, 'b' => null] ] ] How can I get the below string from the above array? aaa,aab,aba,abb,baa,bab,bba,bbb
Just find another way to do it. `window.getSelection()` is just frustratingly poorly designed. It should have been a text based function, not a node based function from day 1. Let's take something really basic - you want to highlight a text an make that section bold. Great, window.getSelection() is fantastic for that...once. However since you also want to make part of that text italic...well...now you're screwed. The text you want to highlight is now divided between 2 or potentially more nodes...which is an issue when the starting point given by window.getSelection() only applies to the specified node and does not take formating into account - the amount of characters to the right of the node that the beginging of the text is in when it's ivided up into several nodes...it just beecomes a fantastic mess. You can no longer look up the selected phrase in it's entirety as tags like <b> or <br> will result in you not finding the text, or, if you look up without formatting then you now need to loop through each and every character - and even then you may have several pieces of text that are the same, so looping through the nodes won't help you get where you should do your edits to the text anyways, since you now need to crossrefference formatted and unformatted text... just don't use it, it's garbage from an era where bad programmers saw it as their duty to dictate what browser you use or how you should highlight text - and if something was buggy or wrong it's the users fault for not doing things the way the programmer wanted them to. Code something better yourself from scratch instad. Hell, even something like putting all the letters in an array where each item in the array is a seperate letter and then decide starting point and ending point with onmousedown/onmouseup is simpler an faster instead if you having to deal with `window.getSelection()` utter garbage is what it is. It is woefully unfit for 99% of eeverything you want it to do. It would have been so much better with `getSelected(text); returning the position of the first and last character as well as the selected text. Or divide it up in 3 seperate functions for all I care. That woul have been a thousand times better.
What is happening here: - You see a gradient cause of vertex attributes interpolation. - [![enter image description here][1]][1] - There is an optimization inside [`THREE.BufferGeometry`](https://threejs.org/docs/#api/en/core/BufferGeometry), to minimise the number of attributes passes called `indexing` by reusing attributes. So two adjacents triangle share the same color attribute on their adjacent side vertices. ```glsl const indices = [ 0, 1, 2, 2, 3, 0, ]; ``` - You need to used non-indexed geometries so each triangle have unique vertices attributes, like here: [How to disable color interpolation when using vertexColors?][2] [1]: https://i.stack.imgur.com/bZevi.jpg [2]: https://discourse.threejs.org/t/how-to-disable-color-interpolation-when-using-vertexcolors/29006
I am trying to use a form with two images, and then download both images to local when submitted the form. But both images are downloaded as the same image. In HTML I have this fields: <img src="data:image/jpeg;base64,UklGRoog..." id="foto_muestra__url_val"> <img src="data:image/jpeg;base64,/9j/4AAQ..." id="foto_monton__url_val"> Then I have this JS Called when Form Submitted: var selectFotoMonton = document.getElementById("foto_monton__url_val"); var selectedFotoMonton_url = selectFotoMonton.src; var selectFotoMuestra = document.getElementById("foto_muestra__url_val"); var selectedFotoMuestra_url = selectFotoMuestra.src; $.ajax({ type: "POST", url: "procesos/procesar_imagenes.php", data: { encodedFotoMuestra: encodeURIComponent(selectedFotoMuestra_url), encodedFotoMonton: encodeURIComponent(selectedFotoMonton_url) }, contentType: "application/x-www-form-urlencoded;charset=UTF-8", done: function(data){ //uniqid_code_ = data.responseText; }, success: function(data){ }, error: function(xhr, status, error) { var err = eval("(" + xhr.responseText + ")"); alert(err.Message); } }); And then, in the file **procesos/procesar_imagenes.php** : if (ISSET($_POST['encodedFotoMonton'])){ $isFotoMontonSaved = saveImage($_POST['encodedFotoMonton'], true); $isFotoMuestraSaved = saveImage($_POST['encodedFotoMuestra'], false); } And then, I have the function saveImage() before this code in the same file: function saveImage($base64img_encoded, $isMonton){ $previousDir = ''; //define('UPLOAD_IMAGES_DIR', $previousDir.'/Imagenes/'); //define('UPLOAD_IMAGES_DIR', '../Imagenes/'); $fileExtension = "jpeg"; $isFileImage = true; $base64img = rawurldecode($base64img_encoded); //base64_decode // DEPRECATED FOR BASE64 - FORMAT IN HTML-URL DECODER if (str_contains($base64img, 'data:image/jpeg')) { $fileExtension = "jpeg"; $base64img = str_replace('data:image/jpeg;base64,', "", $base64img); } else if (str_contains($base64img, 'data:image/jpg')) { $fileExtension = "jpg"; $base64img = str_replace('data:image/jpg;base64,', "", $base64img); } else if (str_contains($base64img, 'data:image/png')) { $fileExtension = "png"; $base64img = str_replace('data:image/png;base64,', "", $base64img); } else if (str_contains($base64img, 'data:image/gif')) { $fileExtension = "gif"; $base64img = str_replace('data:image/gif;base64,', "", $base64img); } else if (str_contains($base64img, 'data:image/tiff')) { $fileExtension = "tiff"; $base64img = str_replace('data:image/tiff;base64,', "", $base64img); } else if (str_contains($base64img, 'data:image/webm')) { $fileExtension = "webm"; $base64img = str_replace('data:image/webm;base64,', "", $base64img); } else { $isFileImage = false; } if ($isFileImage){ $selected_img = 'muestra'; if ($isMonton) { $selected_img = 'monton'; } $file_img = '../Imagenes/temp_' . $selected_img . '.' . $fileExtension; if (file_exists($file_img)) { unlink($file_img); } $file_action = file_put_contents($file_img, $base64img); if ($file_action){ return $base64img; // Mandar mensaje de Imagen Procesada } else { return $base64img; // Mandar mensaje de Imagen no procesada } } else { return 'No se han detectado las imágenes. '.$base64img; } } And the results as images: [![enter image description here][1]][1] There's something I am not doing well but I don't know where or why it happens. I always test with different images, for Monton image and Muestra image. Monton = Mount image Muestra = Preview image Thanks in advance! If something it's bad explained, please tell me. [1]: https://i.stack.imgur.com/rrCoT.png
How do we set the `fontSet` attribute on `MatIcon` in order to get the Material Symbols to render. I'm trying to render the [`expand_content` symbol](https://fonts.google.com/icons?selected=Material%20Symbols%20Outlined%3Aexpand_content%3AFILL%400%3Bwght%40400%3BGRAD%400%3Bopsz%4024) however it is not rendering as shown in the material icons font. This is the markup for rendering it as a `span` element: ``` <span class="material-symbols-outlined"> expand_content </span> ``` This is how Angular Renders it: https://stackblitz.com/edit/stackblitz-starters-lgahav?file=src%2Fmain.ts,src%2Findex.html This is the markup: ``` <mat-icon fontSet="material-icons-outlined">expand_content</mat-icon> ``` And this is the icon I'm trying to render. [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/MQE2l.png
I'm working on a PHP project where I need to frequently merge multiple nested arrays. The key point is that I want to preserve unique key-value pairs across the arrays, giving priority to values from later arrays in the merge sequence. **Here's a simplified example:** ```php $array1 = [ 'fruits' => [ 'apple' => 'red', 'banana' => 'yellow' ], 'numbers' => [1, 2] ]; $array2 = [ 'fruits' => [ 'orange' => 'orange', 'apple' => 'green' // Should overwrite 'red' ], ]; $array3 = [ 'numbers' => [2, 3, 4], // Should extend, not replace 'colors' => ['blue', 'purple'] // New key should be added ]; // Desired Output: $mergedArray = [ 'fruits' => [ 'apple' => 'green', 'banana' => 'yellow', 'orange' => 'orange' ], 'numbers' => [1, 2, 3, 4], 'colors' => ['blue', 'purple'] ]; ``` **My Current Approach (inefficient for large arrays):** PHP function mergeNestedArraysInefficient($arrays) { $mergedArray = []; foreach ($arrays as $array) { foreach ($array as $key => $value) { if (is_array($value)) { // Nested array - handle recursively if (!isset($mergedArray[$key])) { $mergedArray[$key] = $value; } else { $mergedArray[$key] = mergeNestedArraysInefficient([$mergedArray[$key], $value]); } } else { // Simple value - overwrite if key exists $mergedArray[$key] = $value; } } } return $mergedArray; } **Question:** Can anyone suggest a more efficient and elegant solution for this type of array merging in PHP? Are there built-in functions or well-established patterns that handle this scenario effectively, especially when dealing with larger, more complex arrays?
Efficiently Merging Nested Arrays in PHP While Preserving Unique Key-Value Pairs
|php|arrays|algorithm|performance|merge|
You are calling `round` on a complete `data.frame`, which is generally fine assuming that all columns are numeric. For instance, ```r sapply(mtcars, is.numeric) # mpg cyl disp hp drat wt qsec vs am gear carb # TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE round(head(mtcars, 3)) # mpg cyl disp hp drat wt qsec vs am gear carb # Mazda RX4 21 6 160 110 4 3 16 0 1 4 4 # Mazda RX4 Wag 21 6 160 110 4 3 17 0 1 4 4 # Datsun 710 23 4 108 93 4 2 19 1 1 4 1 ``` However, your frame is _not_ all numeric: ```r sapply(gdp, is.numeric) # [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE # [27] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE # [53] TRUE TRUE TRUE TRUE TRUE TRUE FALSE ``` So you cannot do a math-operation on the frame-as-a-whole. The columns that are strings look like they should be numbers, so I suspect that something in your data import or earlier in your data-processing _corrupted_ those columns. While we can mend it here and likely not lose much precision, this is certainly not ideal, and it is not always a lossless process ... so go back and fix whatever broke the data. There are a few ways to work around this: 1. Mend those columns, assuming that columns 38, 39, and 59 are _supposed_ to be numeric: ```r gdp[,c(38, 39, 59)] <- lapply(gdp[,c(38, 39, 59)], as.numeric) round(gdp) # # 4 4 5 5 1 4 2 -1 2 4 5 -1 -1 4 4 4 2 -1 2 -3 4 6 3 3 3 3 3 1 -1 2 1 3 1 3 3 3 4 3 0 1 2 3 3 2 1 -1 -3 2 1 2 1 2 2 1 2 2 2 -4 6 2 ``` This rounded each of your 59 columns. 2. Don't mend those columns (back to the original `gdp` here), just round the other 56 columns: ```r round(gdp[,-c(38, 39, 59)]) # # 4 4 5 5 1 4 2 -1 2 4 5 -1 -1 4 4 4 2 -1 2 -3 4 6 3 3 3 3 3 1 -1 2 1 3 1 3 3 3 4 3 2 3 3 2 1 -1 -3 2 1 2 1 2 2 1 2 2 2 -4 6 ``` If you intend to round and save back into `gdp` (overwriting the raw numbers), then you can do ```r gdp[,-c(38, 39, 59)] <- round(gdp[,-c(38, 39, 59)]) ``` recognizing that the three columns are still strings (and not rounded). 3. Go back earlier in your pipe, either at the import or some other intermediate operation, and fix the source of the problem instead of mending it here. I really prefer this to the first two, over to you. --- Data ```r gdp <- structure(list(4.34054896320299, 5.07809761043293, 5.27711385836413, 1.38995128628369, 3.75881936763187, 2.09736970647879, -1.43845053330176, 1.99560023463674, 4.13809677493917, 4.64215574445912, -1.44513434368933, -1.18458141215473, 4.39146286737468, 3.57714670648173, 4.42298460692567, 2.03388706463849, -1.20929826319077, 1.53632028085542, -2.73456973098722, 3.631979295881, 6.31216765588185, 3.25065642338708, 2.51088596744542, 2.53862353656405, 3.23541610899424, 2.69816667236526, 0.74148609960973, -1.43420012525736, 2.09661276602233, 1.40570856500528, 2.76088229716902, 1.46871823407399, 2.57225920399024, 3.1972120547039, 3.27051107297336, 3.59798501816873, 2.92544098347776, "-0.0399197287893003", "0.756774050858581", 1.91648045091225, 2.89584777850045, 2.53378411366741, 1.79648632582968, 1.04493013677586, -0.820367898524154, -3.45001592321435, 1.86029167805893, 0.814519357932042, 1.53310203539129, 1.13869234666606, 1.54038064866397, 1.95300411790625, 0.933375361665711, 1.59713559028371, 2.40486787201, 1.82966838809384, -3.70095252825833, 5.77954841835778, "1.55148744876492"), row.names = 4L, class = "data.frame") ```
null
First upgrade the pip version pip install --upgrade pip Then install system dependencies (Ubuntu) sudo apt-get install -y libssl-dev libffi-dev libxml2-dev libxslt1-dev libopenblas-dev Then try to install again pip install rpy2
i would like to implement a formula to have rows hidden or unhidden dependent on the product type, From the research i have done so far i have gathered the solution to this will be VBA. I have next to no experience with this topic how ever. ' code edited into the question from the comments Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Target.Address = "$B$1" Then If Range("B1").Value = "Please Select" Then Rows([11:52]).EntireRow.Hidden = True ElseIf Range("B1").Value = "Red" Then Rows([11:31]).EntireRow.Hidden = False Rows([32:52]).EntireRow.Hidden = True ElseIf Range("B1").Value = "Blue" Then Rows([11:31]).EntireRow.Hidden = True Rows([32:52]).EntireRow.Hidden = False End If End If End Sub For an oversimplification of document scope the input reference will be product colour (Cell A1) and selection will use data validation (Cell B1) to of 2 choices (Red, Blue). Essentially i would the first 10 rows to always remain visible, rows 11-31 should be visible if B1 input is 'Red' and rows 32-52 visible if B1 input is Blue. i have tried a couple examples i have found however they seem to be out of date or involve password protection which i do not intend to use unless required. The attached image is a quick sort of over view on the desired operation, ![Simplified Sheet Example](https://i.stack.imgur.com/9GOsi.png)
When you publish packages, it's important to know where you're putting them. If you publish your packages to the default npm registry, registry.npmjs.org, they won't automatically appear in the GitHub Packages section of your GitHub repository. For them to show up there, you need to publish them directly to GitHub Packages. This means using GitHub's package registry instead of the default one. Once you publish your packages to GitHub Packages, they'll be visible in the GitHub Packages section of your repository
{"Voters":[{"Id":6574038,"DisplayName":"jay.sf"},{"Id":22180364,"DisplayName":"Jan"},{"Id":466862,"DisplayName":"Mark Rotteveel"}],"SiteSpecificCloseReasonIds":[13]}
I'm developing PowerShell Cmdlets in C#. I would like to define mandatory parameters, but that are mutually exclusive. Example: Parameter A Parameter B When invoking the command, I must set only parameter A or only parameter B, but I cannot set both and I cannot set none.
How to my own cmdlet (using C#) with two input parameters mandatory but mutually exclusive?
UPDATE- i ran the project in a different Ide and somehow it works fine now
I have been learning how to use the Pi4J library and tried to implement the minimal example application that can be found in the [Pi4J website](https://pi4j.com/getting-started/minimal-example-application/) The code that I used is here: ```java package org.PruebaRaspberry11; import com.pi4j.Pi4J; import com.pi4j.io.gpio.digital.DigitalInput; import com.pi4j.io.gpio.digital.DigitalOutput; import com.pi4j.io.gpio.digital.DigitalState; import com.pi4j.io.gpio.digital.PullResistance; import com.pi4j.util.Console; public class PruebaRaspberry11 { private static final int PIN_BUTTON = 24; private static final int PIN_LED = 22; private static int pressCount = 0; public static void main (String[] args) throws InterruptedException, IllegalArgumentException { final var console = new Console(); var pi4j = Pi4J.newAutoContext(); var ledConfig = DigitalOutput.newConfigBuilder(pi4j) .id("led") .name("LED Flasher") .address(PIN_LED) .shutdown(DigitalState.LOW) .initial(DigitalState.LOW); var led = pi4j.create(ledConfig); var buttonConfig = DigitalInput.newConfigBuilder(pi4j) .id("button") .name("Press button") .address(PIN_BUTTON) .pull(PullResistance.PULL_DOWN) .debounce(3000L); var button = pi4j.create(buttonConfig); button.addListener(e -> { if (e.state().equals(DigitalState.LOW)) { pressCount++; console.println("Button was pressed for the " + pressCount + "th time"); } }); while (pressCount<5) { if(led.state().equals(DigitalState.HIGH)){ led.low(); console.println("LED low"); } else { led.high(); console.println("LED high"); } Thread.sleep(500/(pressCount+1)); } pi4j.shutdown(); } } ``` I've tested all the hardware (the LED, the button) to make sure that the work fine. In the console, the "LED high" "LED low" lones are printed, but the LED doesn't blink and nothing happens when I press the button. What is more strange is that the first time I run the code it worked, but I tried to do some modifications and never worked again, even after deleting the changes I did.
|flutter|firebase|google-cloud-firestore|stream-builder|
null
I'm modifying a part of a fairly large tool that uses PyTorch to optimize some parameters. I noticed that if I add this line to the code, the results are getting worse: self.gammas = self.gammas.unsqueeze(2).squeeze(2) `self.gammas` is a tensor that at this point only contains zeros, and will later be optimized. Unfortunately, I'm not able to condense the project into a small example, but are there general reasons why this no-op might have an impact on the optimization process? I've made sure that the process is deterministic: If I run the code multiple times both with an without the modification, the results are consistent.
Why could a no-op change the optimization result?
|pytorch|tensor|
|c#|visual-studio|weak-references|
Dear **@Vinayak Bhat** Kindly first check you have same ios version in **xcode** and **podfile** then run application after these commands: Deintegrate the pods: cd ios pod deintegrate Remove the Podfile and Podfile.lock: rm Podfile rm Podfile.lock Remove the build folder: rm -rf build Remove the userdata: rm -rf ~/Library/Developer/Xcode/DerivedData/ Update the pods: pod update run application: cd .. yarn android or npx react-native run-android Hope this will help you to fix the problem.
I'm extremely new to RPGLE and I'm getting some errors like: `The length parameter must be a numeric constant between 1 and the maximum for the type. (20).` on all of my zoned variables. And I'm getting `The Factor 2 operand is not valid for the specified operation. (30).` On my `Write ClassAverage;` What is factor 2 operand? ``` **FREE dcl-f wuexampl1 Disk Usage(*Input) ; dcl-f ch6print printer Usage(*output); dcl-s Totalscore zoned(3,0); dcl-s FIN char(1); dcl-s RecordCount zoned(2,0); dcl-s AverageScore zoned(3,0); dcl-s ClassAverage zoned(3,0); Write HEADER; Read EXAMREC; DOW Not %eof(wuexampl1); AverageScore = (Exam1 + Exam2 + Exam3 + Exam4 + Exam5) / 5; Totalscore += AverageScore; FIN = SFNAME; RecordCount += 1; Write DETAIL; Read EXAMREC; enddo; ClassAverage = Totalscore / RecordCount; Write ClassAverage; *inlr = *on; return;
Why do I need numeric constant?
|rpgle|
Okay I figured out what was going on. In fact, my click event was firing first when the menu is open and I click the `toggle_button`. And my call in my toggle function `blur()` was firing the `focusout` event. I just needed to pass a check from the click event so that my toggle function knows not to blur. Now my code looks like this... var dropdown = document.createElement("div") ; dropdown.setAttribute("tabindex" , "0") ; // enables the DIV to allow focus var toggle_button = document.createElement("div") ; toggle_button.addEventListener("click" , function() { toggleDropdown(dropdown , true) ; // add a boolean for checking }) ; dropdown.addEventListener("focusout" , function() { toggleDropdown(dropdown) ; }) ; dropdown.appendChild(toggle_button) ; document.body.appendChild(dropdown) ; And my function like so... function toggleDropdown( dropdown , check ) { if ( dropdown.classList.contains("open") ) { // The blur function fires the focusout event. // Don't fire if checked. if (!check) { dropdown.blur() ; } var options_wrap = dropdown.getElementsByClassName("options_wrap")[0] ; dropdown.removeChild(options_wrap) ; dropdown.classList.remove("open") ; } else { dropdown.focus() ; var options_wrap = document.createElement("div") ; options_wrap.setAttribute("class" , "options_wrap") ; var opt1 = document.createElement("div") ; var opt2 = document.createElement("div") ; opt1.addEventListener("click" , function() { /* do unique stuff. */ }) ; opt2.addEventListener("click" , function() { /* do unique stuff. */ }) ; options_wrap.appendChild(opt1) ; options_wrap.appendChild(opt2) ; dropdown.appendChild(options_wrap) ; dropdown.classList.add("open") ; } }
Adafruit BNO08x Lib Not working with PicoRP2040 - PlatformIO
|arduino|i2c|adafruit|platformio|rp2040|
``` List { //I Want This Button To Appear When User Over Scroll To Top Button(action:{}, label: { Text("Archive") }) ForEach(0..<5) { item in ChatButton() } .listRowInsets(EdgeInsets.init(top: 0, leading: 0, bottom: 0, trailing: 0)) .listRowPlatterColor(.clear) Rectangle() .frame(width: Sizes.width - 8, height: Sizes.h2) .foregroundColor(Color("Background")) .listRowInsets(EdgeInsets.init(top: 0, leading: 0, bottom: 0, trailing: 0)) .listRowPlatterColor(.clear) CenteredTextButton(text: "Durumlar", textColor: Color("White"), isLink: true, destinationKey: "statuses", buttonAction: {}) .listRowInsets(EdgeInsets.init(top: 0, leading: 0, bottom: 0, trailing: 0)) .listRowPlatterColor(.clear) } ``` In the above code i want the Button that says Archive to appear whe user scrolls to top when user already at the top (ex: on negative offset y)[![enter image description here][1]][1] [1]: https://i.stack.imgur.com/NGAWL.png
How can i create an animation like whatsapp archive button spawn animation with SwiftUI on WatchOS?
|swift|swiftui|mobile|watchkit|watchos|
Generate the following two result sets: 1.Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S). 2.Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format: There are a total of [occupation_count] [occupation]s. where [occupation_count] is the number of occurrences of an occupation in OCCUPATIONS and [occupation] is the lowercase occupation name. If more than one Occupation has the same [occupation_count], they should be ordered alphabetically. Note: There will be at least two entries in the table for each type of occupation. Input Format The OCCUPATIONS table is described as follows:Occupation will only contain one of the following values: Doctor, Professor, Singer or Actor. Sample Input An OCCUPATIONS table that contains the following records: Sample Output Ashely(P) Christeen(P) Jane(A) Jenny(D) Julia(A) Ketty(P) Maria(A) Meera(S) Priya(S) Samantha(D) There are a total of 2 doctors. There are a total of 2 singers. There are a total of 3 actors. There are a total of 3 professors. Generate the following two result sets: 1.Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S). 2.Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format: There are a total of [occupation_count] [occupation]s. where [occupation_count] is the number of occurrences of an occupation in OCCUPATIONS and [occupation] is the lowercase occupation name. If more than one Occupation has the same [occupation_count], they should be ordered alphabetically. Note: There will be at least two entries in the table for each type of occupation. Input Format The OCCUPATIONS table is described as follows:Occupation will only contain one of the following values: Doctor, Professor, Singer or Actor. Sample Input An OCCUPATIONS table that contains the following records: Sample Output Ashely(P) Christeen(P) Jane(A) Jenny(D) Julia(A) Ketty(P) Maria(A) Meera(S) Priya(S) Samantha(D) There are a total of 2 doctors. There are a total of 2 singers. There are a total of 3 actors. There are a total of 3 professors.
I am trying to download a file from my ftp server. As soon as the file is larger than 300KB, the download fails. Below that limit, it works. The ftp server is running in a Docker container (image: delfer/alpine-ftp-server). Here is my method: ```java public InputStream getInputStreamFromURI(String uri) throws IOException { try { ftp.addProtocolCommandListener(new PrintCommandListener( new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")), true)); assureConnection(false); ftp.setBufferSize(2048000); ftp.setAutodetectUTF8(true); ftp.setDataTimeout(Duration.ofSeconds(6000)); ftp.enterLocalPassiveMode(); InputStream is; logger.trace("Retrieve file " + uri + " from FTP server..."); is = ftp.retrieveFileStream(uri); ftp.completePendingCommand(); logger.trace("FTP response was: " + ftp.getReplyString()); return is; } catch (FTPConnectionClosedException e1) { logger.error("Server has closed connection, we will try again..."); return getInputStreamFromURI(uri); } catch (ConnectException e2) { logger.error("The server could not be connected, let's try again..."); return getInputStreamFromURI(uri); } catch (NoRouteToHostException e3) { logger.error("Server was not routable, let's try again..."); return getInputStreamFromURI(uri); } } ``` Here are the logs from the ftp container: ``` [pid 1336] OK LOGIN: Client "172.12.123.12" [pid 1338] [ppdw] FAIL DOWNLOAD: Client "172.12.123.12", "file.csv", 366760 byte ``` What could be the problem? So far I have tried to save the file temporarily. <s>However, this temp file is not created.</s> Another idea would be to split the file, but that didn't work either. *Update:* Here is the log for the small file: ``` OK DOWNLOAD: Client "172.12.123.12", "file.csv", 228893 bytes, 0.74Kbyte/sec ``` *Update:* Adding the "ftp.addProtocolCommandListener" did not change anything in the logs.
Yeap, you can do that, however requires kind of a workaround: So you have your package structure (shortened of course): - Package -- Sources --- Executables ---- Executable_One ----- main.swift ---- Executable_Two ----- main.swift If you arrange it this way and try to launch the app, Xcode will fire 'Overlapping sources...' error, cause you have two files named "main.swift". To fix that, you go to Package.swift and declare both of your executables as `executableTarget` and exclude other executable from each of them: let package = Package( ... targets: [ ... .executableTarget( name: "Executable_One", path: "Sources/Executables", exclude: ["Executable_Two"] ), .executableTarget( name: "Executable_Two", path: "Sources/Executables", exclude: ["Executable_One"] ), ... ] Might be tricky but works.
I have a python code which uses Hugging Face Transformers to run an NLP task on a PDF document. When I run this code in Jupyter Notebook, it takes more than 1.5 hours to complete. I then setup the same code to run via a locally hosted Streamlit web app. To my surprise, it ran in under 5 mins! I believe I am comparing apples to apples because: - I am analyzing the same PDF document in each case - Since the Streamlit app is locally hosted, all computation is running on my laptop CPU. I am not using any Hugging Face virtual resources. The HF models are being downloaded to my computer. - The `.py` file is generated from the Jupyter Notebook using 'streamlit-juypter' which just takes the Python code in the notebook and adds a few Streamlit statements So, essentially same code running on same data using same hardware. The only differences I can think of which may explain this are: - Streamlit is running a `.py` python file from the command line instead of a `.ipynb` notebook - Streamlit is running inside a virtual environment instead of my main Python installation Has anyone ever experienced something like this? Can running the same python code from the command line result in 20x greater speed?
null
`useCallback` and `useMemo` are drastically overused and then you run into problems like this where you're not sure if you should leave things out of the dependency list and then you get stuck and confused about the whole thing. The simplest solution is to just not use `useCallback/useMemo` (unless and until you are absolutely sure you need them, and you'll know when that is, trust me) ``` const handleSubmit = () => { if(!disabled) { return onSubmit() } } ```
I had change bucket name too then It did works alright. So very name and try again
I want to implement inside my web-app a file-upload with Uppy package together with Supabase. I followed this tutorial: https://www.youtube.com/watch?v=JLaq0x9GbbY When I'm using this exact same code I'm getting this error on upload: ` "error": "Invalid Input", "message": "The object name contains invalid characters"` After searching for a solution, I found this code: https://github.com/supabase/supabase/blob/master/examples/storage/resumable-upload-uppy/index.html (source: https://supabase.com/docs/guides/storage/uploads/resumable-uploads#uppyjs-example) But again, exact same error as previous one. ` "error": "Invalid Input", "message": "The object name contains invalid characters"` To be clear, I have tried several types of files: test.png, image.jpeg, etc. Nothing works. My code: ``` "use client"; import React, { useEffect, useState } from "react"; import Uppy from "@uppy/core"; import { Dashboard } from "@uppy/react"; import Tus from "@uppy/tus"; import "@uppy/core/dist/style.min.css"; import "@uppy/dashboard/dist/style.min.css"; import { createBrowserClient } from "@supabase/ssr"; function ImagesDragzone() { const [images, setImages] = useState<any[]>([]); const [loading, setIsLoading] = useState(false); const [error, setError] = useState<any>(null); const SUPABASE_ANON_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; const SUPABASE_PROJECT_ID = "vopvzwbjhdsvhnwvluwb"; const STORAGE_BUCKET = "library"; const BEARER_TOKEN = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; const supabaseStorageURL = `https://${SUPABASE_PROJECT_ID}.supabase.co/storage/v1/object/public/`; const supabase = createBrowserClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY! ); var uppy = new Uppy().use(Tus, { endpoint: supabaseStorageURL, headers: { authorization: `Bearer ${BEARER_TOKEN}`, apikey: SUPABASE_ANON_KEY as string, }, uploadDataDuringCreation: true, chunkSize: 6 * 1024 * 1024, allowedMetaFields: [ "bucketName", "objectName", "contentType", "cacheControl", ], }); useEffect(() => { getBucket(); uppy.on("file-added", (file) => { const supabaseMetadata = { bucketName: STORAGE_BUCKET, objectName: file.name, contentType: file.type, }; file.meta = { ...file.meta, ...supabaseMetadata, }; console.log("file added", file); }); uppy.on("complete", (result) => { console.log( "Upload complete! We’ve uploaded these files:", result.successful ); }); }, []); async function getBucket() { setIsLoading(true); const { data, error } = await supabase.storage.from("library").list(); // console.log(data); // console.log(error); if (error) { setError(error); } else { setImages(data); } setIsLoading(false); } return ( <div> <h1>Image Showcase</h1> {error && <div>errror</div>} <div> <Dashboard uppy={uppy} showProgressDetails={true} /> </div> {loading && <div>Loading...</div>} {!loading && images.length > 0 && ( <> <h1>My images</h1> <ul> {images.map((image) => ( <li key={image.name}>{/* uploaded image here */}</li> ))} </ul> </> )} </div> ); } export default ImagesDragzone; ```
Query an alphabetically ordered list of all names in OCCUPATIONS Table
|mysql|
null
It seems surprising you wouldn't use or consider **Parse.com** for something like this. (If not Parse, some other bAAs with a similar feature set.) Note: Parse is now at back4app.com. 1) Parse is the easiest possible way to do push with an iOS app 2) the whole idea of Parse is that you have cloud code, and it's incredibly simple: https://parse.com/docs/cloud_code_guide you can have cloud code routines, and, you can have "cron" routines that go off regularly. It's why everyone's using Parse! Note that it is super-easy to call cloud functions from iOS, with Parse. Here's an example: -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { int thisRow = indexPath.row; PFUser *delFriend = [self.theFriends objectAtIndex:thisRow]; NSLog(@"you wish to delete .. %@", [delFriend fullName] ); // note, this cloud call is happily is set and forget // there's no return either way. life's like that sometimes [PFCloud callFunctionInBackground:@"clientRequestFriendRemove" withParameters:@{ @"removeThisFriendId":delFriend.objectId } block:^(NSString *serverResult, NSError *error) { if (!error) { NSLog(@"ok, Return (string) %@", serverResult); } }]; [self back]; // that simple } Notice I'm calling a cloud function "clientRequestFriendRemove". So that's just a piece of cloud code I wrote and which is on our Parse account, in fact here it is: Parse.Cloud.define("clientRequestHandleInvite", function(request, response) { // called from the client, to accept an invite from invitorPerson var thisUserObj = request.user; var invitorPersonId = request.params.invitorPersonId; var theMode = request.params.theMode; // theMode is likely "accept" or "ignore" console.log( "clientRequestAcceptInvite called.... invitorPersonId " + invitorPersonId + " By user: " + thisUserObj.id ); console.log( "clientRequestAcceptInvite called.... theMode is " + theMode ); if ( invitorPersonId == undefined || invitorPersonId == "" ) { response.error("Problem in clientRequestAcceptInvite, 'invitorPersonId' missing or blank?"); return; } var query = new Parse.Query(Parse.User); query.get( invitorPersonId, { success: function(theInvitorPersonObject) { console.log("clientRequestFriendRemove ... internal I got the userObj ...('no response' mode)"); if ( theMode == "accept" ) { createOneNewHaf( thisUserObj, theInvitorPersonObject ); createOneNewHaf( theInvitorPersonObject, thisUserObj ); } // in both cases "accept" or "ignore", delete the invite in question: // and on top of that you have to do it both ways deleteFromInvites( theInvitorPersonObject, thisUserObj ); deleteFromInvites( thisUserObj, theInvitorPersonObject ); // (those further functions exist in the cloud code) // for now we'll just go with the trick of LETTING THOSE RUN // so DO NOT this ........... response.success( "removal attempt underway" ); // it's a huge problem with Parse that (so far, 2014) is poorly handled: // READ THIS: // parse.com/questions/can-i-use-a-cloud-code-function-within-another-cloud-code-function }, error: function(object,error) { console.log("clientRequestAcceptInvite ... internal unusual failure: " + error.code + " " + error.message); response.error("Problem, internal problem?"); return; } } ); } ); (Fuller examples ... https://stackoverflow.com/a/24010828/294884 ) 3) it's trivial to **make Push happen from the cloud code** in Parse, again this is why everyone uses it. For example, here's a Parse cloud code fragment that relates to Push: function runAPush( ownerQueryForPush, description ) // literally run a push, given an ownerQuery // (could be 1 to millions of devices pushed to) { var pushQuery = new Parse.Query(Parse.Installation); pushQuery.matchesQuery('owner', ownerQueryForPush); Parse.Push.send ( { where: pushQuery, data: { swmsg: "reload", alert: description, badge: "Increment", title: "YourClient" } }, { success: function() { console.log("did send push w txt message, to all..."); }, error: function(error) { console.log("problem! sending the push"); } } ); } 4) it's unbelievably easy to do everything relating to your food database, on a NoSQL environment. Nothing could be easier than the Parse approach 5) you get the **whole back end** for free (for adding foods, whatever) - normally months of work 6) finally I guess Parse is quite free (until you have so many users you'd be making a fortune anyway) So, I can't imagine doing what you say any other way - it would be a nightmare otherwise.
My requirement is to have a core app to manage authentication, which should include google authentication (all-auth in django) and django_cas_ng (CAS authentication). Now I want to be able to use this authentication app for multiple projects (CAS system). I should register only for one app , and should be able to login to another app using the same username and password. (CAS auth system). path('', django_cas_ng.views.LoginView.as_view(), name='cas_ng_login'), path('accounts/logout', django_cas_ng.views.LogoutView.as_view(), name='cas_ng_logout'), I the url cas_ng_login redirects me to CAS_SERVER_URL = 'http://localhost:8000/accounts/', where I have the google authentication implemented. [enter image description here](https://i.stack.imgur.com/JOTBJ.png)
I am trying to implement authentication in django using django_cas_ng, and also provide a option for all-auth for google login
|python|django|google-oauth|django-allauth|
null
This didn't work for me since /snap/bin was already in the path (Ubuntu 22). Despite the path ok I got "/system.slice/cron.service is not a snap cgroup" running anythin snap from cron. I had to start a dummy process with just loading the selenium model and loop it infinitly, then it worked... A better solution is to add: loginctl enable-linger <user> There seems to be some systemd magic that happens when you logoff
AG Grid is a client-side grid that is designed to be framework **ag**nostic. It is not dependent on any framework, allowing it to be easily integrated with any of them. When posting, describe the problem, add some screenshots/code samples. Don't forget to specify if you integrate it with frameworks like Angular v1, Angular v2, or other frameworks or if you're using it with native JavaScript or TypeScript. [Documentation and forum][1] [GitHub repository][2] ### Related tags: - [tag:ag-grid-react] for AG Grid questions using React implementation. - [tag:ag-grid-angular] for AG Grid questions using Angular implementation. - [tag:ag-grid-vue] for AG Grid questions using Vue implementation. - [tag:ag-grid-solid] for AG Grid questions using Solid implementation. [1]: http://www.ag-grid.com [2]: https://github.com/ag-grid/ag-grid
This didn't work for me since /snap/bin was already in the path (Ubuntu 22). Despite the path ok I got "/system.slice/cron.service is not a snap cgroup" running anything snap from cron. I had to start a dummy process with just loading the selenium model and loop it infinitly, then it worked... A better solution is to add: loginctl enable-linger user There seems to be some systemd magic that happens when you logoff
I've got a page which needs to kick a user back to the previous one if they don't have permissions to view. I made this very simple component as a test but I'm finding that it navigates back two pages not one. Any ideas why? import React, { useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; const GoBack = () => { const navigate = useNavigate(); const [state, setState] = useState('init'); if (state === 'init') setState('goBack'); useEffect(() => { if (state === 'goBack') navigate(-1); }, [state]); return <p>You are not permitted to view this page</p>; }; export default GoBack;
Try using `datetime.datetime.utcnow()`. Also you can use `datetime.datetime.now(datetime.timezone.utc)` which is more correct in Python 3.x
|azure-devops|
We have installed .NET 8.0 Hosting Bundle but when we go to change an application pool to enable it, it is missing from the list. How do we get this to appear? It is also not under ISAPI and CGI Restrictions so may this be why? The path to .NET 8 seems to be different to 2 and 4 and where it is located there is no `aspnet_isapi.dll` to map to. Cheers Installing .NET8 and the option being available under application pools
ASP.NET Coer 8 is missing from application pool selection after install
|asp.net-core|.net-8.0|
Not sure this is what you want, but it works if you just enclose the outer loop into a future. I also changed two things: - the assignment `command_set[[j]] <-` is done into the future - the future returns the time difference ```r library(shiny) library(ipc) library(future) plan(multisession) library(promises) # to use %...>% ftc_parallel <- function(queue){ start <- Sys.time() future({ for(i in 1:5){ command_set <- vector(mode = "list") for(j in 1:3){ Sys.sleep(sample(1:3, size = 1)) command_set[[j]] <- data.frame( Colonne1 = runif(2), Colonne2 = runif(2), Colonne3 = runif(2) ) } queue$producer$fireAssignReactive("react_val", i) # write in file # results <- bind_rows(Filter(Negate(is.null), lapply(command_set, value))) # write.table(results, append = T, sep=";") } end <- Sys.time() end - start }, seed = TRUE) %...>% print() } ui <- fluidPage(titlePanel(""), sidebarLayout( sidebarPanel(), mainPanel( actionButton("bouton", "Button") ))) server <- function(input, output) { react_val <- reactiveVal(0) queue <- shinyQueue() queue$consumer$start(100) observe({ print(react_val())}) observeEvent(input$bouton, { ftc_parallel(queue) NULL }) } shinyApp(ui = ui, server = server) ```
I'm encountering an issue with React Router where I'm trying to implement authentication for my application using React Router's Route components. I have an Auth component that checks the user's authentication status by making an asynchronous request to my server's /users/check-auth endpoint. If the user is authenticated, it should render the protected routes using <Outlet />, otherwise, it should redirect to the login page. This is my Auth.jsx ``` function Auth() { const [isLoggedIn, setIsLoggedIn] = useState(false); const navigate = useNavigate(); useEffect(() => { const checkAuth = async () => { try { const response = await axios.get(`${base}/users/check-auth`, { withCredentials: true, }); if (response.status === 200) { setIsLoggedIn(true); } } catch (error) { setIsLoggedIn(false); } }; checkAuth(); }, [navigate]); return isLoggedIn ? <Outlet /> : <Login />; } ``` These are my Routes ``` function App() { return ( <Provider store={store}> <Toaster richColors position="top-center" /> <Router> <Routes> <Route path="/signup" element={<Register />} /> <Route path="/login" element={<Login />} /> <Route element={<Auth />}> <Route path="/" element={<Home />} /> <Route path="/user-details" element={<UserDetails />} /> </Route> </Routes> </Router> </Provider> ); } export default App; ``` and this code is in Login.jsx ``` const handleSubmit = async (e) => { e.preventDefault(); const userDetails = { email: data.email, password: data.password, }; try { const response = await axios.post(`${base}/users/login`, userDetails); toast.success(response.data.message); Cookies.set("aToken", response.data.data.accessToken, { expires: 1, path: "", }); navigate("/"); } catch (error) { toast.error(error.response.data.message); } }; ``` after this didn't work, i tried different appraoch using reducer where i set isloggedin status to true after a successfull login and then use it in auth.jsx to check whether the user is authenticated or not, this was the code for it: ``` const { isLoggedIn } = useSelector((state) => state.user); let token = Cookies.get("aToken") || isLoggedIn; if (!token) { return <Login />; } return <Outlet />; ``` also there is this problem in the above code aswell. It didn't work if i used only cookies or only isLoggedIn. I had to use both in order to make it work. https://daisyui.onrender.com/ this was achieved using both cookies and islogged in. i want to understand what is the problem. i think it has something to do with batch updates of react or maybe something else that i dont know of. Please help me with it.
For using refs in an array, [this earlier answer](https://stackoverflow.com/a/72835670/6243352) logs an empty refs array in Vue versions between 3.2.25 and 3.2.31 inclusive: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const {ref, onMounted} = Vue; Vue.createApp({ setup() { const items = [ {id: 1, name: "item name 1"}, {id: 2, name: "item name 2"}, {id: 3, name: "item name 3"}, ]; const elements = ref([]); onMounted(() => { console.log( elements.value.map(el => el.textContent) ); }); return {elements, items}; } }).mount("#app"); <!-- language: lang-html --> <div id="app"> <div v-for="(item, i) in items" ref="elements" :key="item.id"> <div>ID: {{item.id}}</div> <div>Name: {{item.name}}</div> </div> </div> <script src="https://unpkg.com/vue@3.2.31/dist/vue.global.prod.js"></script> <!-- end snippet --> A workaround is replacing `refs="elements"` with `:ref="el => elements[i] = el"`: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const {ref, onMounted} = Vue; Vue.createApp({ setup() { const items = [ {id: 1, name: "item name 1"}, {id: 2, name: "item name 2"}, {id: 3, name: "item name 3"}, ]; const elements = ref([]); onMounted(() => { console.log( elements.value.map(el => el.textContent) ); }); return {elements, items}; } }).mount("#app"); <!-- language: lang-html --> <div id="app"> <div v-for="(item, i) in items" :ref="el => elements[i] = el" :key="item.id"> <div>ID: {{item.id}}</div> <div>Name: {{item.name}}</div> </div> </div> <script src="https://unpkg.com/vue@3.2.31/dist/vue.global.prod.js"></script> <!-- end snippet -->
|reactjs|node.js|firebase|google-cloud-storage|
null
In the case we use Mongo-rs instead of the standard MongoDB. This is mainly when we need the to transactions working with Mongo. However this requires a change it the connection string which becomes something like this: `mongodb://localhost:30001/?directConnection=true` In my case this was all I need to get things up and running an I hope that this will save some time to other people getting the same issue as me.
If you look at the `VideoFrame` `timestamp` property [docs on mdn][1]. It says it is an > integer indicating the timestamp of the video in microseconds. What does that actually mean -- as in when does this timestamp get generated? - Is it the timestamp from when the frame got generated on the server? - Is it the timestamp from when the video frame was received in the HTMLVideoElement? - Is it the timestamp from when the video stream first started rendering? - Or is it not standard and dependent on a different system to manually set this timestamp? I've looked around and haven't found any clarifying docs or blog posts explaining. I am trying to measure latency for a video stream over webRTC and am wondering if this property can be of any use to me. [1]: https://developer.mozilla.org/en-US/docs/Web/API/VideoFrame/timestamp
Collect all unique key paths of a multidimensional array
|php|arrays|loops|multidimensional-array|key|
null
You shoudl try this it will helpful ``` const fetchCategories = async (father: number) => { showLoading(); try { const { data: categoriesData, error } = await supabase.from('categoria').select('*').eq('pai', father); if (error) throw error; setCategories(categoriesData); hideLoading(); console.log(categoriesData); } catch (error: any) { hideLoading(); await showToast({ message: error.message || error.error_description, duration: 5000 }); } } ``` try and catch method doesn't block the JS thread, that's why executing of function is not working as your expectation.
You need to trust the workspace; otherwise, it will not show icons of extensions in the activity bar.
Try using the following formula: [![enter image description here][1]][1] ---------- =LET( _LastRow, COUNTA(L:L), _FRng, B3:INDEX(B:M,_LastRow,), _CriteriaRange1, L3:INDEX(L:L,_LastRow), _CriteriaRange2, M3:INDEX(M:M,_LastRow), _Output, FILTER(_FRng,(_CriteriaRange1="Dan")*(_CriteriaRange2="Negotiating")), INDEX(_Output,SEQUENCE(ROWS(_Output)),{1,11,12})) ---------- Also the simplest one I can see is this, since you are already extracting the individual columns using the `_LastRow` variable for `_FRng`, `_CriteriaRange1` & `CriteriaRange2` then. [![enter image description here][2]][2] ---------- =LET( _LastRow, COUNTA(L:L), _FRng, B3:INDEX(B:B,_LastRow,), _CriteriaRange1, L3:INDEX(L:L,_LastRow), _CriteriaRange2, M3:INDEX(M:M,_LastRow), FILTER(CHOOSE({1,2,3},_FRng,_CriteriaRange1,_CriteriaRange2),(_CriteriaRange1="Dan")*(_CriteriaRange2="Negotiating"))) ---------- [1]: https://i.stack.imgur.com/huBIx.png [2]: https://i.stack.imgur.com/d3EJG.png
|optimization|scipy|scipy-optimize|
Type compatibility checking in typescript is based on [structural equivalence](https://www.typescriptlang.org/docs/handbook/type-compatibility.html). That means, for a type `A` to be compatible to `B`, on the instance (ie non-static) level there must not exist a required property or method in one of them, that does not exist in the other. But your `TimeSeriesDB` type does not have any required non-static properties or method. So when checking the structural equivalence between `Promise<boolean>` and `TimeSeriesDB` typescript is not able to find any property or method that is required in `TimeSeriesDB` that does not exist in `Promise<boolean>`. Thus, it considers the types as being structural equivalent and therefore it's allowed to return a `Promise<boolean>` You will quickly find a compilation error if you do for instance the following ``` export class TimeSeriesDB { private static inst: TimeSeriesDB; public static db: InfluxDB; public static connected: Promise<boolean>; constructor() { const url = Settings.get('INFLUX2_URL'); const token = Settings.get('INFLUX2_TOKEN'); TimeSeriesDB.db = new InfluxDB({ url, token, }); } // Add this instance level method public someMethod(): void { } static async connect() { return true; } static disconnect() { // delete this.instance.db } static get instance(): TimeSeriesDB { if (this.inst === undefined) { this.inst = new TimeSeriesDB(); this.connected = this.connect(); } return this.connected; } } export default TimeSeriesDB.instance ``` Then you will get an error telling you > Property 'someMethod' is missing in type 'Promise<boolean>' but required in type 'TimeSeriesDB'.
A python script is being executed by a QProcess. Inside this script, a specific file should be open and written to it. The file path should always be `\\127.0.0.1\folder\myfile.json`. def write_to_json(IP, slice_id, json_lines): #IP = "127.0.0.1" (or any other network id as str) #slice_id = 1 #json_lines: string output_file = r"\\{}\hatches\slice{}.json".format(IP, slice_id) subprocess.run(f"echo. >> {output_file}", shell=True) with open(output_file, "a") as f: #also tried w for line in json_lines: f.write(line + '\n') When this code is being executed by an IDE, it works fine and the Path could be found. When run using QProcess, the file system seems to add random backslashes so the path cannot be found: [Errno 2] No such file or directory: '\\\\127.0.0.1\\hatches\\slice1.json' Also, other approaches were tried (except of parsing to the file using subprocess, since the length of each line might be bigger than 48k elements, which exceeds the max. length of the enabled path length in Windows. Otherwise, parsing the input to the file would have worked using subprocess): 1. passing the path as output_file = r"{}\hatches\slice{}.json".format(IP, slice_id) output: [Errno 2] No such file or directory: '127.0.0.1\\hatches\\slice1.json' 2. removing the backslashes leads to: output_file.remove(r"\\","") output: [Errno 2] Could not connect to network '127.0.0.1hatchesslice1.json' Does anyone have any idea how to be able to solve this backslash issue? (The synax cannot be changed since otherwise, no connection can be made.)
Opening specific path to file stored inside a network connection whencalled by QProcess(Pyside6)
|python|pyside6|qt6|qprocess|
{"Voters":[{"Id":1509264,"DisplayName":"MT0"},{"Id":22180364,"DisplayName":"Jan"},{"Id":466862,"DisplayName":"Mark Rotteveel"}],"SiteSpecificCloseReasonIds":[11]}
Yes, you can run both Angular and NestJS on the same server. One approach, although not required is to run each in a docker container. I have integrated Angular and NestJS in a boilerplate project. You can refer to the "prod" folder there and check the docker compose file. Feel free to fork the project and use it as a base for your own. https://github.com/godardth/typescript-fullstack-boilerplate
Im making a calorie counting just for learing, as a beginner. I wont to create def where i can choose the name(self) that will be enscrpted to the class, insert to this one name values in order to use them later but the value enscripted to class is not what i write as variable but just the name of the variable i gived in def. I gived to def variable 'new' later making ``` global x, x = new ``` and givining this x to class as a self. Here variable new is user1 so i wont x to be user1. I expected that when i try to use def from class it will be enscripcted as user1 not x, but its the opposite. here i have ``` user1.Body_information() ``` but it says: ``` NameError: name 'user1' is not defined. Did you mean: 'User'? ``` It would work though if there was ``` x.Body_information() ``` But i wont the (self) to be thing i written out in new_user(thing i wont as the self) so i could create new classes with this function. [here is the class](https://i.stack.imgur.com/tCEH4.png) [And here the ](https://i.stack.imgur.com/efhOG.png)function [Error](https://i.stack.imgur.com/hFxqt.png) At the beginning i just tried only with the variable 'new', without all the global x thing but it didint work at all then. I was thinking about counting the number of the def being called and based of the number of calls add this number to a value that would be enscrpited to class. (so it would be user1 on the frist call, user2 on the second call and so on) But i dont feel like im capable of doing that at least not alone and maybe there are easier way to do it so thanks in advance for any help. Here is the whole code: > Blockquote class User: def __init__(self, name, weight, height, BMI, gender, age): self.weight_of_user = weight self.height_of_user = height self.BMI_of_user = BMI self.gender = gender self.age = age def Body_information(self): print ('your weight is ' + str(self.weight_of_user)) print ('your height is ' + str(self.height_of_user)) print ('your BMI is ' + str(self.BMI_of_user)) def new_user(new): print('Welcome to the calorie counting program') name = input('choose a name') gendergiv = input('are you female or male?') if gendergiv != 'male' and gendergiv != 'female': print('Please chosse one of the two genders available') new_user(new) weightgiv = float(input('Please insert your weight')) heightgiv = float(input('Please insert your height (in meters)')) agegiv = int(input('Please insert your age')) BMIgiv = int(weightgiv / (heightgiv * heightgiv)) global x x = new x = User(name = name, weight = weightgiv, height = heightgiv, BMI = BMIgiv, gender = gendergiv, age = agegiv) new_user('user1') user1.Body_information()
What does the VideoFrame timestamp actually correlate to?