Posts

Showing posts from July, 2022

How to get user info on a static page?

I'm hosting a static page/site on GCP App Engine (written in standard js/html/css), on a company domain ; I know in localhost testing I can't get the user info in any way (which is fine, I'll hardcode dummy data). But after using gcloud app deploy and running it on the engine, is there a way to obtain user info somehow? Name, email etc. Ideally just through the app somehow - or even by calling a google cloud function or something. Nb. I have activated IAP so when hosted, the user does go through google auth on this site (all domain users are allowed in).

new line in textarea while looping with props

Given this snippet, how can I insert a new line at the specified position? <div> <textarea>: </textarea> ----------------------------------------------------------^ </div> <br> and \n are printed as text inside textarea Right now, I'm cheating like this <div> <textarea>: </textarea> </div> This also works, but I get two new lines per loop and big indentation per line <div> <textarea> : </textarea> </div> I would like to maintain code readability like the first or last example

JOIN 2 tables based on req.query in a 3rd table

I have 3 tables (deals, deals_media, access_to_deals) deals deals_media access (to deals) name pic_url type media_url deal_id customer_id deal_id deal1 http://blah video url. 1 1 1 deal2 http://blah2 img url2. 1 1 2 deal3 http://blah3 video url3. 2 2 1 I'm sending an api get request with a customer_id query parameter. I want to send back an array of objects with all the deals data the customer is eligible for and to join an array of matching deals_media to the deals.id I'm using sequalize and await functions and my query looks like: sync (req, res) => { try { const customerId = req.query.customer_id; let deals = await db.sequelize.query( 'SELECT DISTINCT deals.* FROM deals \n' + 'JOIN access ON deals.id = access.deals_i...

Access and Query tables in Datadog

We have a logs table in PostgreSQL and would like to visualize some metrics(table columns) on data dog. Is it possible to retrieve data using SQL from tables in datadog?

Debugging Perl scripts without interactive debugger

I've been tasked with understanding and debugging some legacy code written in Perl 5. The comments aren't great, and I have almost zero experience with the language (I'm a Python guy; some shell scripting experience). Basically, I need to understand it to the point where I can decide if it will be worth it to rewrite it in Python to match the rest of our code base and be more readable to those who aren't familiar with Perl's less obvious syntax (at least, to the uninitated...) or just leave it as is and do our best to make small changes as necessary despite having an incomplete understanding of what's going on. Perl is being invoked to process some data from within a script in our organization's internal scripting language (which is used to interact with our proprietary hardware). The part written in the in the proprietary scripting language is similar to a shellscript in that every line sent to the interpreter will be written in the log, so while not as ea...

(MSWord VBA) Add " symbol to search string

I'm trying to get a simple macro to work in MS word. The macro is supposed find a definition in contracts. These are typically marked within quotes (e.g. "Definition"). Hence, I want to select a word that I want to search the definition for and execute a search for the selected term in quotes. However, for some reason, I can't get it to work reliably. I've gone through the code debugging it, but the MySearchTrim variable ends up just containing ""selectiontext while I would need it to be "selectiontext" I've tried it with inserting the quotes by adding the quotes through &""" but it only worked in 30% of the cases, which I find very confusing. Can anyone help me spot the error? Thanks! Sub GehZuDefinition() Dim MySearchterm Dim MySearchTrim As String Dim myWindow As Window MySearchterm = Selection.Text MySearchTrim = Chr(34) & Trim(MySearchterm) & Chr(34) ' trimming spaces after s...

Why do g++ binaries have a significantly slower startup time than clang++?

Whenever I compile code using g++ , I've noticed that when I run the binary repeatedly, it runs significantly slower than when I compile with clang++ . test.cpp #include <iostream> int main() { std::cout << "Hello World!" << '\n'; } script.sh for ((i=0; i<2000; ++i)); do ./a.out done Compiling using g++: g++-11 -O2 test.cpp time bash script.sh -> 10.32s user 5.37s system 88% cpu 17.751 total Compiling using clang++: clang++ -O2 test.cpp time bash script.sh -> 1.42s user 1.50s system 69% cpu 4.223 total This is extremely annoying as I need to use g++ , but I also need to speed up the binary to make it easier to stress test my code, so an explanation or fix would be welcome. Note : GCC (11.3, via homebrew), clang (13.1, apple/homebrew (both seem to be the same))

What happens with Azure Service Bus when the triggering function is spun down?

We have a regular problem every couple days where some messages we sent to ServiceBus suddenly and rapidly go to the DLQ. We have it configured to try 10 times and suddenly messages across several queues in the same Function Solution (.Net 6) all DLQ with 10 delivery failures very rapidly. I understand that messages are locked and eventually released if not processed through and I understand how to configure our functions exponential retry policy on the ServiceBus trigger but in these cases what I see appears to be related to “cold start”. Looking at when the message went to the DLQ in each queue I see that the central resource available memory drops to zero for about 2-3 minutes before picking back up which I believe is an indication of the functions being spun down for inactivity. However, if I stop the functions myself the messages just stay in the active queue. They don’t go straight to the DLQ. So, if I’m right and this is related to inactivity shutdown and a typical cold start...

Is there any way to programmatically set a break point then push the button "Export to Excel" in Visual Studio 2022, IEnumerable Visualizer?

Visual Studio 2022 has a feature called IEnumerable Visualizer that allows the user to view a list of objects in a tabular format during debug. There is already a button which allows the user to "Export to Excel". This button is a very handy feature, and found myself wanting to programmatically "push the export button". I'm familiar with CsvHelpler and other libraries which make it easy to output lists of objects. But I'm wondering if there is any way to programmatically press the "Export to Excel" button? (like when writing a C# console app)

Flutter/Firestore : How do I display data from doc in a ListTile?

I am new to Flutter/Firebase/Firestore etc.. so I am struggling a bit. I want to grab the data from the documents in my 'users' collection in Firestore and display it in my account information page. I have spent hours messing around with this and I am stuck. If anybody could help me out that would be wonderful! Here are some samples of what my code, app, and firestore look like. Code: signup.dart - this is the page that creates the doc in Firebase on signup class SignUp extends StatefulWidget { const SignUp({Key? key}) : super(key: key); @override State<SignUp> createState() => _SignUpState(); } class _SignUpState extends State<SignUp> { var emailController = TextEditingController(); var passwordController = TextEditingController(); /* var docId = FirebaseFirestore.instance.collection('users').doc().id; */ final TextEditingController _usernameController = TextEditingController(); final TextEditingController _phoneNumberController =...

CodePipeline Deployment error "Invalid argument @ rb_sysopen - C:\ProgramData/Amazon/CodeDeploy/xxxxxxxx/xxxxxx/deployment-archive\*.*"

Image
I am struggling to troubleshoot my CodePipeline that fails in Install event of Deployment stage with the following error: Invalid argument @ rb_sysopen - C:\ProgramData/Amazon/CodeDeploy/0df66877-d62c-49b0-81b6-a2b98509ed51/d-DC1Q553XH/deployment-archive*.* I can see that all my app artifacts have been successfully dowloaded and unzipped from CodeBuild artifacts S3 bucket to my EC2 instance (Windows Server 2019) directory: All artifacts match to the latest CideBuild run output. I assume that the @ rb_sysopen argument is related to Ruby unzip program but am not too sure. Considering that the artifacts zip file has been already unzipped in the C:\ProgramData/Amazon/CodeDeploy/... direcory, the error seems weird. This is my appspec.yml file: version: 0.0 os: windows files: - source:\*.* destination:C:\Webapps\TestWebAPIForCodeBuild This is a fragment of CodeDeploy log file found in my target EC2 instance: 2022-07-28T03:48:35 DEBUG [codedeploy-agent(5272)]: Inst...

How is the better way for extract data this array con multiples objetcs with php

I have the following JSON response and I need to create an XML block for each sku and quantity data of each in the order. I include all the json response where I am pulling the data from. Array ( [id] => 17 [parent_id] => 0 [status] => on-hold [currency] => MXN [version] => 6.7.0 [prices_include_tax] => [date_created] => 2022-07-27T05:02:25 [date_modified] => 2022-07-27T05:02:26 [discount_total] => 0.00 [discount_tax] => 0.00 [shipping_total] => 0.00 [shipping_tax] => 0.00 [cart_tax] => 0.00 [total] => 3356.00 [total_tax] => 0.00 [customer_id] => 1 [order_key] => wc_order_xakP1gXCne19m [billing] => Array ( [first_name] => Nombre [last_name] => sjdjjje [company] => [address_1] => Pruena [address_2] => Prueba [city] => hidalgo [state] => AG ...

CPU costs of Thread.sleep() and Thread.onSpinWait()

I'm running two benchmarks in order to compare costs of Thread.sleep() and Thread.onSpinWait() : @State(Scope.Thread) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) public class ThreadSleep2Benchmark { private final ExecutorService executor = Executors.newFixedThreadPool(1); volatile boolean run; @Param({"1", "5", "10", "50", "100"}) long delay; @Setup(Level.Invocation) public void setUp() { run = true; startThread(); } @TearDown(Level.Trial) public void tearDown() { executor.shutdown(); } @Benchmark public int sleep() throws Exception { while (run) { Thread.sleep(1); } return hashCode(); } private void startThread() { executor.submit(() -> { try { Thread.sleep(delay / 2); run = false; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } ...

How to navigate from specific selected item RecyclerView Inside the Fragment, to 2 different Activity from same RecyclerView in Kotlin?

Image
How to navigate from specific selested item RecyclerView Inside the Fragment, to 2 different Activity in Kotlin? i have the basic wireframe layout, who describe my question, because i don't know how to explain with good typing. so here from the wireframe, i have 1 Activity with TabLayout, which is filled with Fragment and there is a RecyclerView in it. And then I have 2 more different Activities. for now, i've successfully implemented data parsing to "OtherActivity1" from RecyclerView inside the fragment TabLayout on MainActivity. But now, i need to open "OtherActivity2" from the same RecyclerView on Main Activity, what i mean here is specifically only from "RecyclerView Item4" and without data parsing. How To Doing That? Anyone have a tutorial?, because i can't find any tutorials like on youtube for this case. and this my sample code ( not exactly the same, but describing the same meaning) : MainActivity.kt class MainActivity : AppC...

Laravel 9 jetstream , I need to sanitize this Controllers is there away to do that? [closed]

I just started my first Laravel project and create an 'authorized waiting view' for role users, using laravel-9 jetstream and custom-made middleware. Is there a way to reduce the number of codes that have been repeated again and again? are there artisan commands to do that? what is the best way to reduce code duplication. $name = $authorizeRequestUser->name; $contact_number = $authorizeRequestUser->contact_number; $email = $authorizeRequestUser->email; $massage = 'Please Contact bellow persion to Authorize your login'; check the repeating code above. please let me know if there is a specific way to do that. <?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; class AuthorizeWaitingController extends Controller { public function index() { $name = 'John Doe'; $contact_number = '07xxxxxxx'; $email = 'jonhdoe@gmail.com '; $massage = 'Please Contact...

Getting name of current express middleware function

Long time reader first time question asker. My question is about dynamically accessing function names in express ^4.17.1. I have poured over both the internet and the express documentation with no luck. I currently have input validation set up on all of my express middleware functions that ensures I'm getting the right information in the right format. When bad or incomplete information is given to a particular middleware I throw a nicely formatted error to the global error handler and I include the route that errored, the file in which the error occured, and the exact middleware in which it occured. I've been able to dynamically retrieve both the route and the file name, but I'm having issues finding a way around hard coding in the name of the middleware. I can access the route stack and get the names of ALL middleware in the route, but there doesn't seem to be a way to determine which one you're in aside from keeping that list on res.locals and changing the array...

Swift - Return Generic Type/Data

I have URLSession shared instance that fetches data. It returns a generic type. Everything works fine when I'm fetching data from a server and displaying it. But when I fetch an image I need to return the Generic Type as the data. How can I return the generic type/data so that it can be used to create the image in the imageView? UIImageView: extension UIImageView { func loadImage(with url: URL) { if let cachedImage = imageCache.object(forKey: url.absoluteString as AnyObject) as? UIImage { self.image = cachedImage return } URLSessionManager.fetchData(with: url, isImageFetch: true) { (result: Result<Data, SessionDataTaskError>) in switch result { case .failure(let error): print(error) case .success(let data): guard let downloadedImage = UIImage(data: data) else { print("image data is nil") ...

Fragment doesnt show data from database (I recently started learning programming)

Database is working since i can see the data in app inspection i dont know what i am doing wrong and cant display the data in the FragmentShow fragment i want the data to be displayed in the above fragment in a recyclerview Any help will be appreciated ( i am a beginner ) Fragment with recyclerview class FragmentShow: Fragment(R.layout.fragment_show) { private var _binding: FragmentShowBinding? = null private val binding get() = _binding!! private lateinit var sqLiteHelper: SQLiteHelper private var adapter: EntryAdapter? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { sqLiteHelper = SQLiteHelper(requireActivity() as MainActivity) _binding = FragmentShowBinding.inflate(inflater,container,false) initRecyclerView() getEntries() return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) adapter?.notif...

"Lateinit property `app` has not been initialized" Error after Hilt Migration

I'm migrating our codebase from Dagger 2 to Hilt. I'm kind of a noob. I've gotten everything to build and compile. There is a crasher on app launch with this error: Logcat 2022-07-27 11:31:26.297 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.appname.company, PID: 17599 java.lang.RuntimeException: Unable to create application com.appname.BaseApplication: kotlin.UninitializedPropertyAccessException: lateinit property app has not been initialized at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6767) at android.app.ActivityThread.access$1500(ActivityThread.java:256) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2091) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:201) at android.os.Looper.loop(Looper.java:288) at android.app.ActivityThread.main(ActivityThread.java:7870) at java.lang.reflect.Method.invoke(...

CP only folders data that match in two different directories into one directory using linux or bash

What would be a efficient way to look into two different directories and if subdirectories match, copy these subfolders in a new output folder linux or bash scripting? I know I need cp command and do match based on SC#### values. Example folder one: [NAME]$ Project Sample_SC1234-AAA-AAA Sample_SC2345-AAA-BBB Sample_SC3456-CCC-CCC Sample_SC4567-DDD-AAA Example folder Two: [NAME]$ Lz Sample_SC1234-AAA-BBB Sample_SC4567-BBB-AAA Sample_SC5678-DDD-BBB Sample_SC6789-BBB-DDD Wanted output: [NAME]$ New Sample_SC1234-AAA-BBB Sample_SC4567-BBB-AAA Sample_SC1234-AAA-AAA Sample_SC4567-DDD-AAA

VBA macro how to click on button on website on chrome, using Selenium

I am trying to program to click on one button on website on chrome. The name of the button is "Add to Cart". Please see HTML of the website: enter image description here And this is the VBA code: CD.FindElementByCss("div.addToCartButtons clearAfter > button blue right s-addToCart > span.Add to Cart").Click How can I do this?

Duplicate entry for key 'PRIMARY' codeigniter

Image
i got error Duplicate entry '19-0' for key 'PRIMARY' after insert all multiple to database $resp = curl_exec($curl); $gorong = json_decode($resp); foreach ($gorong->data as $g){ $this->db->insert('mod_auto_harga', array( 'sv_id' => '19', 'kode' => $g->buyer_sku_code, 'keterangan' => $g->product_name, 'harga' => $g->price, 'status' => $g->seller_product_status, 'type' => $g->type, )); $id = $this->db->insert_id();

Enabling Wordpress debug mode in docker-compose environment

I'm having problems understanding how to enable wordpress debug mode through docker-compose. image of wp-config.php debug section define( 'WP_DEBUG', !!getenv_docker('WORDPRESS_DEBUG', '') ); This is the part of the wp-config.php file where I should be able to enable it. The file is read only and it seems to be designed to enable this feature through docker-compose.yaml file but I cant figure out how. I have tried adding WORDPRESS_DEBUG: 'true' to the environment section of wordpress service but it throws error with true/fals data type and 'true' as a string does not seem to work. The only solution I can come up with is to edit the file as superuser.

searching in strings from tk-inter text fails

Why does the search fail when taking a string from a tk-inter text box? The search works fine if I define the keyword as a string. Minimal example: import tkinter as tk root = tk.Tk() string="banana\napplepie\napple\n" def searchcall(): textboxcontent=textExample.get("1.0","end") keyword=filterbox.get("1.0","end") keyword="apple" # search works as expected print("keyword",keyword) print("is keyword in textbox",keyword in textboxcontent) for elem in textboxcontent.split(): print("seaching for",keyword,"in",elem,keyword in elem) textExample=tk.Text(root, height=10) textExample.insert(1.0,string) textExample.pack() filterbox=tk.Text(root, height=1) filterbox.insert(1.0,"apple") filterbox.pack() btnRead=tk.Button(root, height=1, width=11, text="search", command=searchcall) btnRead.pack() root.mainloop...

Writing to a CSV file in an S3 bucket using boto 3

I'm working on a project that needs to update a CSV file with user info periodically. The CSV is stored in an S3 bucket so I'm assuming I would use boto3 to do this. However, I'm not exactly sure how to go about this- would I need to download the CSV from S3 and then append to it, or is there a way to do it directly? Any code samples would be appreciated.

How does pybind11 methods end up calling functions from the shared library?

I can make as much out as its build system generates a shared object, and also a Python module as a proxy to that shared object. But how does the Python runtime end up doing a dlopen of the generated shared object and bind Python method calls on to corresponding functions in the shared library? I also found a reference in Python's import system about shared libraries, but nothing beyond that. Does CPython treat .so files in the module path as Python modules?

XCode can't build my project because it says my Apple ID session is expired but I can't login?

Image
So it says my session has expired, I try to login, but nothing happens... It's not like it's wrong or something if I type just one character it says "Wrong password" but if I type the correct password literally nothing happens and I can't continue building my project because of this, does anyone know what I can do? I tried to find other people with this problem but nobody seemed to have a problem where they couldn't login to their Apple ID recently.

how to edit adb connect limit

I found that the maximum number of devices connected to ADB through IP:PORT on my Linux server is 30 devices. I want to make this limit more, such as 1000 devices, by modifying the ADB source code. But I am from https://android .googlesource.com/platform/packages/modules/adb No 30 related codes were found in the downloaded source code. I tried to download more source code for ADB dependencies, but still can't find the relevant code. I don't know much about C language. Can someone give me some hints? Where should I find the code to limit the connection limit? I'm downloading all the code for AOSP now, but it always fails because of network and hard disk space issues. I'm trying to figure out a way to fix it. If I download all the code for AOSP. Will it help me to solve this problem?