How to find memory usage with memory_profiler Python? Posted: 22 May 2021 07:48 AM PDT At the end of this question I found some code. I will put it here for convenience: import memory_profiler as mp def fun(n): tmp = [] for i in range(n): tmp.extend(list(range(i*i))) return "XXXXX" start_mem = mp.memory_usage(max_usage=True) res = mp.memory_usage(proc=(fun, [100]), max_usage=True, retval=True) print('start mem', start_mem) print('max mem', res[0][0]) print('used mem', res[0][0]-start_mem) print('fun output', res[1]) But this doesn't work because res is not a double array, it is float number. Moreover, I don't understand how to check memory usage for many functions. I mean, would something like this work? import memory_profiler as mp def fun1(n): return "XXXXX" def fun2(n): return "YYYYY" methods = [ 'fun1(n)', 'fun2(n)', ] start_mem = mp.memory_usage(max_usage=True) res = mp.memory_usage(proc=(methods[0], [100]), max_usage=True, retval=True) print('start mem', start_mem) print('max mem', res[0][0]) print('used mem', res[0][0]-start_mem) print('fun output', res[1]) |
EXTRACT YEAR from column and update another column PostgreSQL Posted: 22 May 2021 07:48 AM PDT I have created another column in my table, for year which I would like to populated it from same table column tdate by extracting the year, can someone please advise how I can do that? SELECT EXTRACT (YEAR from tdate) from test_tb, BUT how I can assigned the value now? tdate year 2006-01-02 00:00:01.132000 null 2007-01-02 00:00:01.234000 null 2008-01-02 00:00:01.336000 null 2009-01-02 00:00:01.538000 null 2010-01-02 00:00:01.639000 null 2011-01-02 00:00:03.107000 null 2012-01-02 00:00:03.210000 null 2013-01-02 00:00:03.261000 null 2014-01-02 00:00:03.363000 null 2015-01-02 00:00:03.465000 null 2016-01-02 00:00:03.591000 null 2017-01-02 00:00:04.475000 null 2018-01-02 00:00:04.526000 null 2019-01-02 00:00:04.629000 null 2020-01-02 00:00:04.731000 null Thank you! |
Printing Polynomial in Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0 format. Using python Posted: 22 May 2021 07:48 AM PDT Given polynomial, write a program that prints polynomial in Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0 format. If N = 4 For power 0, the coefficient is 5 For power 1, the coefficient is 0 For power 2, the coefficient is 10 For power 3, the coefficient is 6. Then polynomial represents "6x^3 + 10x^2 + 5" Sample Input 2: 5 0 2 1 3 2 1 4 7 3 6 Output expected: 7x^4 + 6x^3 + x^2 + 3x + 2 Please, Use dictionaries to maintain polynomial coefficients and powers and use string formatting to print the polynomial. |
How to override a module function which is used as a sub-function in another function imported by another .py file Posted: 22 May 2021 07:48 AM PDT I have a module file called A.py in A.py, there is function containing a sub-function #A.py def fun_A(): sub_function() def sub_function(): xxxx and in B.py, I import A.py and use fun_A, but want to override the sub_function(), what should i do? # B.py import A def sub_function(): xxxx xxxx fun_A() could sub_funciton() in fun_A be overrided? |
How to exclude child-elements with CSS Posted: 22 May 2021 07:48 AM PDT I have an unordered list that looks something like this, but more extensive: <ul> <li class="cat-item-15">Parent Category 2</li> <li class="cat-item-16">Parent Category 2</li> <li class="cat-item-17">Parent Category 3</li> <ul class="children"> <li>Child Category 1</li> <li>Child Category 2</li> <li>Child Category 3</li> </ul> </ul> I want to hide every li except of the Child Categories with display: none . My idea was to use the :not Selector and exclude all Child Categories. I am able to address the Child Categories with ul.children > li but how do I combine this with the :not Selector? Any ideas? |
Scraping full post Indeed with Selenium Posted: 22 May 2021 07:47 AM PDT I'm trying to make a python scraper code work, but I can't, a little help would be useful, I'm still a beginner. The code runs ok, but it crashes and exports a single job to my csv, which i think it is random and does not give any error.Please, someone with more experience who can help me with some tips.Thanks in advance. from selenium import webdriver import pandas as pd from bs4 import BeautifulSoup options = webdriver.FirefoxOptions() driver = webdriver.Firefox() driver.maximize_window() df = pd.DataFrame(columns=["Title","Location","Company","Salary","Sponsored","Description"]) for i in range(0,50,10): driver.get('https://www.indeed.co.in/jobs?q=artificial%20intelligence&l=India&start='+str(i)) jobs = [] driver.implicitly_wait(20) for job in driver.find_elements_by_class_name('result'): soup = BeautifulSoup(job.get_attribute('innerHTML'),'html.parser') try: title = soup.find("a",class_="jobtitle").text.replace("\n","").strip() except: title = 'None' try: location = soup.find(class_="location").text except: location = 'None' try: company = soup.find(class_="company").text.replace("\n","").strip() except: company = 'None' try: salary = soup.find(class_="salary").text.replace("\n","").strip() except: salary = 'None' try: sponsored = soup.find(class_="sponsoredGray").text sponsored = "Sponsored" except: sponsored = "Organic" sum_div = job.find_element_by_class_name('summary') try: sum_div.click() except: close_button = driver.find_elements_by_class_name('popover-x-button-close')[0] close_button.click() sum_div.click() driver.implicitly_wait(2) try: job_desc = driver.find_element_by_css_selector('div#vjs-desc').text print(job_desc) except: job_desc = 'None' df = df.append({'Title':title,'Location':location,"Company":company,"Salary":salary, "Sponsored":sponsored,"Description":job_desc},ignore_index=True) df.to_csv(r"C:\Users\Desktop\Python\Newtest.csv",index=False) |
How do i get string from Entry in tkinter? I use .get(), but it only returns 0 Posted: 22 May 2021 07:47 AM PDT I have trouble returning results from Entry in tkinter. I do not use it immediately after creating tne Entry: import tkinter as tk window = tk.Tk() window.title('Enchantment generator') window.geometry('315x500+400+300') window.resizable(False, False) res_lvl_mas = [] res_mas = [] def enchwind(chk_ench, ench, txt_ench, lvl_ench, ench_name, row, column): chk_ench = tk.BooleanVar() chk_ench.set(False) ench = tk.Checkbutton(window, text=ench_name, var=chk_ench) ench.grid(row=row, column=column, sticky='w') txt_ench = tk.Entry(window, width=3) txt_ench.grid(row=row, column=column+1) def resstr(lvl, resmas): res = '' list = ['/give @p ', '{', 'Enchantments:['] for i in range(len(lvl)): list.append('{id:"minecraft:') list.append(resmas[i]) list.append('",lvl:') list.append(lvl[i]) if i != len(lvl) - 1: list.append('}, ') else: list.append('}') list.append(']}') for i in range(len(list)): res += list[i] return res ench_mas = [] name_mas = ['Aqua affinity', 'Bane of arthropods', 'Binding curse', 'Blast protection', 'Channeling', 'Depth strider', 'Efficiency', 'Feather falling', 'Fire aspect', 'Fire protection', 'Flame', 'Fortune', 'Frost walker', 'Impaling', 'Infinity', 'Knockback', 'Looting', 'Loyalty', 'Luck of the sea', 'Lure', 'Mending', 'Power', 'Projective protection', 'Protection', 'Punch', 'Respiration', 'Riptide', 'Sharpness', 'Silk touch', 'Smite', 'Sweeping', 'Thorns', 'Unbreaking', 'Vanishing curse'] for i in range(34): ench_mas.append([]) for i in range(34): for j in range(7): ench_mas[i].append(0) for i in range(34): ench_mas[i][4] = name_mas[i] for i in range(17): ench_mas[i][5] = i+1 ench_mas[i][6] = 0 for i in range(17, 34): ench_mas[i][5] = i-16 ench_mas[i][6] = 2 ench_list = tk.Label(window, text='Choose the enchantments:') ench_list.grid(row=0, column=0, columnspan=4) result = tk.Label(window, text='None') result.grid(row=19, column=0, columnspan=4) for i in range(34): enchwind(ench_mas[i][0], ench_mas[i][1], ench_mas[i][2], ench_mas[i][3], ench_mas[i][4], ench_mas[i][5], ench_mas[i][6]) def clicked(): result.configure(text=txt) for i in range(34): if ench_mas[i][0]: res_lvl_mas.append(ench_mas[i][2].get()) res_mas.append(ench_mas[i][4]) txt = resstr(res_lvl_mas, res_mas) btn = tk.Button(window, text='Generate!', command=clicked) btn.grid(column=0, row=18, columnspan=4) window.mainloop() This code creates commands for enchanting minecraft items. As you can see, i have 34 entrys so I decided to store their parameters as a list of lists. In the end of the program, when i wanted to get the numbers in entrys, it always returns 0. The interface looks like that: Interface. I suppose those may be zeros left from first part of code, just to define list parameters. Shoul i move something in the code or is it incorrect at all? |
Send email to a mailing list Posted: 22 May 2021 07:47 AM PDT I have a mailing of 30000 emails. I am looking for a free solution to be able to send email to all the contain in this mailing list. I have a wordpress website. Is it possible to code in PHP the solution ? Is it easier to do with another coding langages ? Is there any blog / docs describing how to manage it ? Is there any free software which would give you this possibility ? Many thanks for your advises and help ! Etrables |
Find number of pairs in an array, whose product lie in a given range [x,y] Posted: 22 May 2021 07:47 AM PDT Given an array having n elements, find all the possible pairs of elements whose product is between x and y provided by the user, i.e. all i and j less than n, s.t. x <= a[i] * a[j] <= y. Kindly help me with the best solution for this question. Thanks in advance!!! |
Numpy is working in Python, but not in Wing101 v. 7 Posted: 22 May 2021 07:47 AM PDT The location and name of the following file is: c:\Users\Marielle\Oefeningen\untitled-2 import numpy, numpy.linalg A = numpy.array([[2, 4], [5, -6]]) numpy.linalg.eigvals(A) When I try this in Python, the result is: array([ 4., -8.]) But in Wing I get no result at all. The sys.executable in Wing is allright When I run sys.path in Wing it says: ['C:\Users\Mariëlle\Oefeningen', 'C:\Users\Mariëlle\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Mariëlle\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Mariëlle\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Mariëlle\AppData\Local\Programs\Python\Python39', 'C:\Users\Mariëlle\AppData\Local\Programs\Python\Python39\lib\site-packages', 'C:/Users/Mariëlle/Oefeningen'] When I run sys.path in Python it says: ['', 'C:\Users\Mariëlle\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Mariëlle\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Mariëlle\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Mariëlle\AppData\Local\Programs\Python\Python39', 'C:\Users\Mariëlle\AppData\Local\Programs\Python\Python39\lib\site-packages'] I installed numpy in Python with the command: pip3 install numpy I really don't know how to make numpy work in Wing. Hope someone can help me! |
Single '*' and '/' as a parameter in a function? [duplicate] Posted: 22 May 2021 07:48 AM PDT I know what the star operator does depending on its context. However i keep seeing a solo '*' as a parameter in function definitions and im confused as to what it does... Why does this work and what does it even do. I thought you would have had to follow it up with the name of the tuple you want to store the undefined amount of arguments in so you can adress it. On a similar note i also sometimes see a solo '/' as a parameter when i use the help() built-in function to quickly see what another function does. What is the purpose of it in this context? from dataclasses import dataclass help(dataclass) |
Is there a way to store an arithmetic operator in a variable and use the variable itself within a calculation in JavaScript? Posted: 22 May 2021 07:47 AM PDT Using the following 3 variables - I wanted to calculate two numbers with whatever the operator variable was set to. For example -> num1 * num2.. const num1 = 10; const num2 = 4; const operator = `*`; //Could be any arithmetic operator I know this can be done using an if or switch statement, but I'm curious to know if there is a way to do it in less lines of code using the operation variable itself in the actual calculation. I tried out the following things (I mostly expected them to turn out the way they did): console.log(num1 + operation + num2); //Outputs: "10*4" console.log(num1, operation, num2); //Outputs: 10 "*" 4 console.log(`${num1} ${operation} ${num2}`); //Outputs: "10 * 4" console.log(num1 operation num2); //Outputs: Error const calculation = num1 operation num2; console.log(calculation); //Outputs: Error console.log(1 + operation + 2); //Outputs: "1*2" console.log(Number(1 + operation + 2)); //Outputs: NaN So is there something I haven't tried yet that would make this work, or can it just not be done like this? |
Write a C++ or C program to prompt the user to enter 5 numbers using a loop. enter 5 numbers using a loop [closed] Posted: 22 May 2021 07:48 AM PDT Write a C++ or C program to prompt the user to enter 5 numbers using a loop. the program checks if the numbers divisible by 2 without remainder, then the program will print the number. Example: If the user enters 10,2,13,40,11. The program output is: 10,2,40. |
TCP client error: ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host Posted: 22 May 2021 07:47 AM PDT I have a simple TCP client code: from socket import * HOST = 'localhost' PORT = 21567 BUFSIZE = 1024 ADDR = (HOST, PORT) udpCliScok = socket(AF_INET, SOCK_DGRAM) while True: data = input('>') if not data: break udpCliScok.sendto(data.encode('UTF-8'),ADDR) data , addr = udpCliScok.recvfrom(BUFSIZE) if not data: break print(data) udpCliScok.close() but after I run it and input any text, I get the following error: Traceback (most recent call last): File "f:\Python\WSGI\Core Python Networking\tsUclnt.py", line 19, in <module> data , addr = udpCliScok.recvfrom(BUFSIZE) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host I have tried different ports but still get the same error |
Cannot resolve symbol 'StackPane' Intelij IDEA Posted: 22 May 2021 07:47 AM PDT I tried to run this code in intelij IDE, but it shows an error, java: cannot find symbol, symbol: class StackPane But when I tried the same code on Netbeans IDE, it worked well. what could be the reason for that? package javafxfirstproject; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class JavaFxFirstProject extends Application { @Override public void start(Stage primaryStage) { Button btn = new Button(); btn.setText("Say 'Hello World'"); btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println("Hello World!"); } }); StackPane root = new StackPane(); root.getChildren().add(btn); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } } |
How to ignore a .go file in a module? Posted: 22 May 2021 07:48 AM PDT I am rewriting in Go a home-grade program of mine that was previously in Python, learning on the way. As I reconsider whole sections of the code, it would be great if I could ignore some .go files I wrote (they throw compilation errors which is OK as they are not synchronized with my latest approach to the problem). I could move them out of the directory, or rename them but I was wondering whether there would be a more idiomatic way to ignore some .go files in a module directory? |
A pitfall appending class objects to a list in python Posted: 22 May 2021 07:47 AM PDT There is something not clear to me when appending an object to a python list. Since the original code is too complicated and too long to be posted here, I worked out a minimal example to show the effect. To explain it I managed to rework the code to function properly and to deliver the right result. But it required me a lot of time for debugging. The reason because it happens is still not clear to me. So I'm very happy if you can explain me, why this happens. Ok, let's go. Here the working version of the code. At the end of it you can see, that it delivers an output and works as expected: import numpy as np class foo(): def __init__(self): self.x = np.random.random() def move(self, value): self.x += value p = [] p2 = [] for _ in range(10): z = foo() z.move(4) p2.append(z) p = p2 for i in range(10): print("Print x: {}".format(p[i].x)) Running the code I get the following output (which is after time different, since I call a random generator function). But it works!: Print x: 4.18111236900313 Print x: 4.399997493230335 Print x: 4.594324823463079 Print x: 4.8205743285019045 Print x: 4.125578603746895 Print x: 4.430324972670274 Print x: 4.135255992051397 Print x: 4.9479568256336295 Print x: 4.789025666744436 Print x: 4.261426793909385 Now I show you the first version of the code, which caused me a lot of headache and a lot of anger. Please note, that I change slightly the second for loop because I found it more logical to me. I call the method move() directly and append() in one line, instead of two. Here the version: import numpy as np class foo(): def __init__(self): self.x = np.random.random() def move(self, value): self.x += value p = [] p2 = [] for _ in range(10): z = foo() p2.append(z.move(4)) # Here is the only change to the code! p = p2 for i in range(10): print("Print x: {}".format(p[i].x)) But running this code I get the following error: AttributeError: 'NoneType' object has no attribute 'x' and then I discover that the lists p and p2 have None as elements. Why that? I'm very happy to understand why... EDIT As suggested below I realized that the move() method doesn't return anything. So I changed the code as follows: import numpy as np class foo(): def __init__(self): self.x = np.random.random() def move(self, value): output = foo() output.x += value return output # <= Here the change p = [] p2 = [] for _ in range(10): z = foo() p2.append(z.move(4)) p = p2 for i in range(10): print("Print x: {}".format(p[i].x)) And it works! Another important thing learnt today... |
Python pickle module Posted: 22 May 2021 07:48 AM PDT I am noot use but i guess i heard that pickle module in preserves data structures in a file. So i wanted to try it out but i got an error in my code Here is my code: import pickle import os os.chdir("C:\\Users\\Pratik\\Desktop") f = open("test.txt", "w") pickle.dump(12.3, f) pickle.dump([1, 2, 3], f) f.close() f = open("test.txt", "r") x = pickle.load(f) print(x) print(type(x)) y = pickle.load(f) print(y) print(type(y)) f.close() I get an error whenever i run this code can someone say me why i am using python 3.9.5 |
Font color won't revert back to orginal color Posted: 22 May 2021 07:47 AM PDT The event only carries out one way and for some reason not the other way when the variable is clicked again. I have multiple other events carrying out on the same variable and they all work perfectly fine. However, when it comes to this it doesn't. Any suggestions? //Font color change for (let i = 0; i < li.length; i++) { li[i].addEventListener('click', (e) => { if (li[i].style.color == '#4D5067') { li[i].style.color = '#C8CBE7' } else { li[i].style.color = '#4D5067' } }) } |
Not able to send email to gmail address in PHP Posted: 22 May 2021 07:48 AM PDT I am trying to send an email from PHP. The below code works fine when the From address is a Non-Gmail address. However, when I use a Gmail address as a From Address, I don't receive the email. I have checked spam as well. Can you tell any reason for this behaviour? <?php // validation expected data exists if (!isset($_REQUEST['emailto']) || !isset($_REQUEST['emailsub']) || !isset($_REQUEST['emailfrom']) || !isset($_REQUEST['emailsub'])) { exit; } $emailto = $_REQUEST['emailto'] ; $emailsub = $_REQUEST['emailsub'] ; $emailfrom = $_REQUEST['emailfrom'] ; $emailmsg = $_REQUEST['emailmsg'] ; // create email headers $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=utf-8\r\n"; $headers .= "From: " . $emailfrom . "\r\n"; $headers .= "Reply-To: " . $emailfrom . "\r\n"; $headers .= "X-Mailer: PHP/" . phpversion(); mail($emailto, $emailsub, $emailmsg, $headers)); ?> Thanks |
How do I split a string into an array by whitespace in Go? Posted: 22 May 2021 07:47 AM PDT I want to get an array from this string via whitespace, but each time I try to do it, the entire function that the array is being made in is iterated instead. From my limited knowledge, I believe array := strings.Fields(string) and array := strings.Split(string, " ") should work, but both have this same issue, where an array is created for each value. I am aware that Go Arrays have fixed sizes, but I don't believe this is the issue here. It's easier to show this with the code and its output: func main() { fmt.Println(" ~~ RPN calculator ~~ ") for { fmt.Println("Enter RPN notation:") var notation string fmt.Scan(¬ation) fmt.Println() result, calcerr := RPNcalculator(notation) if calcerr != nil { fmt.Println(calcerr) } else { fmt.Println(result) } } } func RPNcalculator(notation string) (string, error) { array := strings.Fields(notation) fmt.Println(array) validsyntax, error := RPNsyntaxCheck(array) if !validsyntax && error != nil { return "", error } else { return "...", nil } } Each Array is a single value |
TypeScript Declarations Conflict Posted: 22 May 2021 07:47 AM PDT Repro: https://github.com/wenfangdu/d-ts-conflict-repro shims-vue.d.ts /* eslint-disable */ declare module '*.vue' { import type { DefineComponent } from 'vue' const component: DefineComponent<{}, {}, any> export default component } /* eslint-enable */ import 'vue' declare module 'vue' { interface HTMLAttributes extends interface { vModel?: unknown } } Run npm run serve , after the dev server starts up, these errors are printed: ERROR in src/main.ts:2:17 TS7016: Could not find a declaration file for module './App.vue'. 'D:/Repos/d-ts-conflict-repro/src/App.vue.js' implicitly has an 'any' type. 1 | import { createApp } from 'vue' > 2 | import App from './App.vue' | ^^^^^^^^^^^ 3 | import router from './router' 4 | import store from './store' 5 | ERROR in src/router/index.ts:17:46 TS7016: Could not find a declaration file for module '../views/About.vue'. 'D:/Repos/d-ts-conflict-repro/src/views/About.vue.js' implicitly has an 'any' type. 15 | // which is lazy-loaded when the route is visited. 16 | component: () => > 17 | import(/* webpackChunkName: "about" */ '../views/About.vue'), | ^^^^^^^^^^^^^^^^^^^^ 18 | }, 19 | ] 20 | What did I do wrong? |
<SOLVED> C# don't see .Include from EntityFrameworkCore.SqlServer Posted: 22 May 2021 07:47 AM PDT I'm trying to connect database to project but get n C# error (CS1061) in this code: public IEnumerable<Car> Cars => appDBContent.Car.Include(c => c.Category); Error CS1061 'object' does not contain a definition for 'Include' and no accessible extension method 'Include' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Full code: using Microsoft.EntityFrameworkCore; using AiralnePars.Data.interfaces; using AiralnePars.Data.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AiralnePars.Data.Repository { public class CarRepository : IAllCars { private readonly AppDBContent appDBContent; public CarRepository(AppDBContent appDBContent) { this.appDBContent = appDBContent; } public IEnumerable<Car> Cars => appDBContent.Car.Include(c => c.Category); public IEnumerable<Car> getFavCars { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public Car getObjectCar(int carid) { throw new NotImplementedException(); } } } Microsoft.EntityFrameworkCore.SqlServer downloaded Include is exist, we can see this here -> https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/whatsnew on second example var artists = context.Artists .Include(e => e.Albums) .ToList(); I already tried to: - reinstall Entity Framework Core and
EntityFrameworkCore.SqlServer - add
using System.Data.Entity |
Issue removing a node from a linked list Posted: 22 May 2021 07:48 AM PDT Since the code was cryptic I decided to reformulate it. This code is trying to remove the second element from a linked list (the node with number 2 on "int data"). The first parameter of remove_node is the address of the first pointer of the list, so if I have to remove the first pointer of the list I am able to start the list from the next pointer. The problem is inside the second while loop, inside the if clause, more specifically with the free(previous->next) function, it is changing the address pointed by head (aka *head) and I can't understand why this is happening. Could someone enlighten me? #include <stdlib.h> #include <stdio.h> typedef struct node { struct node *next; int data; } node; void remove_node(node **head, int int_to_remove) { node *previous; while (*head != 0 && (*head)->data == int_to_remove) { previous = *head; *head = (*head)->next; free(previous); } previous = *head; head = &((*head)->next); while (*head != 0) { if ((*head)->data == int_to_remove) { printf("*head: %p previous: %p previous->next: %p\n", *head, previous, previous->next); head = &((*head)->next); printf("*head: %p previous: %p previous->next: %p\n", *head, previous, previous->next); free(previous->next); printf("*head: %p previous: %p previous->next: %p\n", *head, previous, previous->next); previous->next = *head; printf("*head: %p previous: %p previous->next: %p\n", *head, previous, previous->next); } else { previous = *head; head = &((*head)->next); } } } int main(void) { node *list = malloc(sizeof(node)); list->next = malloc(sizeof(node)); list->next->next = malloc(sizeof(node)); list->next->next->next = 0; list->data = 1; list->next->data = 2; list->next->next->data = 1; remove_node(&list, 2); return 0; } |
Setting the Culture for the rest of the request in an Action Posted: 22 May 2021 07:47 AM PDT Our application shows invoice data, so the URL is something like https://localhost/Invoices/guid-goes-here So in the Action handling this request, I retrieve the Invoice data. Included in this data is the culture that was used in the shop. Displaying the invoice data (and consequently paying the invoice) is a separate web application, and I want to set the Culture of the Views used to display the invoice to use the Culture that matches the Invoice. However, the only sort of work-around I've found so far to set Culture per request is using middleware reading the culture from the URL. I don't want the culture in the URL. I haven't found a way to do this. Is this possible in the new asynchronous way aspnet core works? I'm using .Net 5 What I want: public class InvoiceController { [Route("{id}"] public async Task<IActionResult> Index(Guid id) { var invoice = await _apiClient.InvoiceAsync(id); // Here is what I want to do SetCultureTo(invoice.Culture); // Views and partials should now all have culture settings for resources return View(invoice); } } But because the method is async, and all the views are rendered on different thread, simply setting the CurrentCulture won't do what I want it to do. Thanks! |
How to preserve shared element transitions between mutiple activities Posted: 22 May 2021 07:49 AM PDT I have three activities A, B and C, and use shared element transitions between A and B and between B and C. A -> B works fine, and then using back button or finishAfterTransition smoothly reverses the transition from B back to A. B -> C works fine too, going back from C to B is also smooth. However A -> B -> C -> B -> A is the problem. The C -> B transition is smooth, but then the B back to A transition is 'forgotten' and is just an instant jump without a smooth transition. Why is B -> A different after having gone B -> C -> B ? When starting the activities I am using: val options = ActivityOptions.makeSceneTransitionAnimation(this, transition_name) startActivity(intent, options.toBundle()) I had a theory that the problem was occurring in B, when calling C it was changing the enterTransition, sharedElementEnterTranstion, exitTransition, sharedElementExitTranstion, returnTransition, sharedElementReturnTranstion, reenterTransition, sharedElementReenterTranstion attributes of B, and hence not transitioning back to A. However I've saved and logged all these and the object details don't seem to be different in either scenario. Any help gratefully received, thanks. I've mocked this up in a very simple three activity project to demonstrate the problem: First screen XML: <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/testtext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:clickable="true" android:onClick="secondActivity" android:text="Go to second screen" android:transitionName="transition_name" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Second screen XML: <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".SecondActivity"> <TextView android:id="@+id/testtext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Welcome to the second activity" android:transitionName="transition_name" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.147" /> <TextView android:id="@+id/testtext2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:clickable="true" android:onClick="thirdActivity" android:text="Go to third screen" android:transitionName="transition_name2" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.996" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.466" /> </androidx.constraintlayout.widget.ConstraintLayout> Third screen XML: <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ThirdActivity"> <TextView android:id="@+id/testtext2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:transitionName="transition_name2" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.845" /> </androidx.constraintlayout.widget.ConstraintLayout> Main activity: import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Pair import android.view.View class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } fun secondActivity(view: View) { val intent = Intent(this, SecondActivity::class.java) val view: View = findViewById(R.id.testtext) val pair = Pair.create(view, "transition_name") val options = ActivityOptions.makeSceneTransitionAnimation(this, pair) startActivity(intent, options.toBundle()) } } Second activity: import android.app.ActivityOptions import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.transition.Fade import android.transition.Transition import android.util.Log import android.util.Pair import android.view.View class SecondActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) } fun thirdActivity(view: View) { val intent = Intent(this, ThirdActivity::class.java) val view: View = findViewById(R.id.testtext2) val pair = Pair.create(view, "transition_name2") val options = ActivityOptions.makeSceneTransitionAnimation(this, pair) startActivity(intent, options.toBundle()) } override fun onBackPressed() { super.onBackPressed() supportFinishAfterTransition() } } Third activity: import android.os.Bundle class ThirdActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_third) } } |
Print PDF doc using Adobe pro PDF document properties Posted: 22 May 2021 07:48 AM PDT Is there a way to print using .joboptions file. Before printing, the code needs to verify if the document is already in that specification as given in .joboptions file. - Print the file changing the Default settings as highlighted
- Print the file choosing to be Print as Image
Please let me know, if these done from python/c#. Print PDF 1 Print Image PDF 2 |
404 NOT FOUND in Laravel 8 Posted: 22 May 2021 07:49 AM PDT I am creating a simple website in Laravel while running a web site ran into the problem with 404 NOT FOUND Laravel 8 . index page working when I click on about us and contact us page getting error of 404 NOT FOUND I don't know why is that. what I tried so far I attached below. Folder structure Controller class SmsController extends Controller { public function index() { return view('index'); } public function aboutus() { return view('aboutus'); } public function contactus() { return view('contactus'); } } Index.blade.php I made the links <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="{{url('aboutus')}}">Aboutus</a></li> <li><a href="{{url('contactus')}}">Contactus</a></li> </ul> routes Route::get('/', 'App\Http\Controllers\SmsController@Index'); Route::get('Aboutus', 'App\Http\Controllers\SmsController@aboutus'); Route::get('Contactus', 'App\Http\Controllers\SmsController@contactus'); |
grub does nothing after "multiboot /boot/kernel.bin" Posted: 22 May 2021 07:48 AM PDT Im trying to boot custom kernel with help of grub and qemu. If i start it with "qemu -kernel -m 64 ./kernel.bin" it works fine. Bud if i create iso with "grub-mkrescue -o os.iso ./os/" It start to load grub and screen stay black directories tree: ------ ./os/boot/ kernel.bin grub/ grub.cfg ------ content of grub.cfg set default="0" set timeout="3" ### BEGIN 10 ### menuentry "tmx.os" { multiboot /boot/kernel.bin echo " LOADING KERNEL: done" } ### END 10 ### the line "LOADING KERNEL: done" is displayed on the screen. Have somebody idea what can be wrong ? Any advise is welcome ======================================================= UPD: i have kernel_main() in "C" file, and as i can see in GDB kernel_main gets never called. Strange ? assembly code bits 32 section .text align 4 ; align at 4 byte dd 0x1BADB002 ; MAGIC dd 0x00 dd - (0x1BADB002 + 0x00) global start extern kernel_main start: cli ; Clear interrupt flag [IF = 0]; 0xFA mov esp, kernel_stack ; set stack pointer ;push eax ; multiboot structure ;push ebx ; MAGIC call kernel_main ; controll to kernel_main(); in kernelc.c hlt ; HLT Enter halt state 0xF4 end: cli hlt jmp end section .bss resb 1024*256 ; *Kb for stack kernel_stack: ; <= stack_space I cant understand, what happens to "call kernel_main" instruction ? this is "kernel.c", there is like nothing, just clear vid.mem. buffer #include "kernel.h" // <<< extern void kernel_main(); void kernel_main() { char * BUFF = (char*) 0xb8000; int i=0; int ii=0; while ( i < 80*25) { BUFF[ ii++ ] = '#'; BUFF[ ii++ ] = 0x7; i++; } } also "grub-file --is-x86-multiboot kernel.bin" is "multiboot confirmed" [SOLVED] I do not know how it cat be, bud it works now. Its MAGIC | 0x1BADB002 I wrote kernel is AT&T syntax, sub could not implement all things i need. GDT, and IDT keeps crashing, so i test one more time with kernel.s [NASM] And MAGIC, it works now. Yeeeeeeeeeeyyy :p |
React - How to get parameter value from query string? Posted: 22 May 2021 07:48 AM PDT How can I define a route in my routes.jsx file to capture the __firebase_request_key parameter value from a URL generated by Twitter's single sign on process after the redirect from their servers? http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla I tried with the following routes configuration, but the :redirectParam is not catching the mentioned param: <Router> <Route path="/" component={Main}> <Route path="signin" component={SignIn}> <Route path=":redirectParam" component={TwitterSsoButton} /> </Route> </Route> </Router> |
No comments:
Post a Comment