Understanding logs from SGDClassfier with log loss for Logistic Regression model in python Posted: 21 Feb 2022 01:35 PM PST I fit a Logistic regression model with SGDClassifier using the loss as 'log loss' and setting the log level verbose = 1. clf = SGDClassifier(loss='log',random_state=123,verbose=1) clf.fit(X,Y) The logs I got where as below -- Epoch 1 Norm: 30075.68, NNZs: 3, Bias: 15.380843, T: 200, Avg. loss: 245306398.448941 Total training time: 0.00 seconds. -- Epoch 2 Norm: 27972.51, NNZs: 3, Bias: -69.971163, T: 400, Avg. loss: 213504329.868022 Total training time: 0.00 seconds. -- Epoch 3 Norm: 77152.19, NNZs: 3, Bias: -129.169105, T: 600, Avg. loss: 141240838.989763 Total training time: 0.00 seconds. -- Epoch 4 Norm: 45522.49, NNZs: 3, Bias: -117.146703, T: 800, Avg. loss: 171279669.044693 Total training time: 0.01 seconds. Can I please know what parameters like Norm, NNZ and T mean in the above logs. Thank you. |
The histograms in ggplot2 Posted: 21 Feb 2022 01:35 PM PST I am new to histograms in ggplot2. I am trying to use ggplot2 to build a histogram for the dataset "Admission"(the picture below). I am using the "Gender" column to be the x-axis, and cut by the "Admit" column. However, the graph(the picture below) only shows the number of male and female which is 2 but not the data in the "Freq" column. This is the code(X is the dataset): ggplot(X, aes( x=Gender, fill=Admit) )+ geom_bar(color="black") + labs(x="Gender", title="Adimission", fill="Admit") I am not sure that my thinking is right, is there any one can give me some hints? Thanks. enter image description here enter image description here |
Django and Pandas - Create an object from a Foreying Key field Posted: 21 Feb 2022 01:34 PM PST I am trying to create objects importing data from an excel with pandas, than creating objects with django. But i am geting this error message: Asset matching query does not exist. My Models class Asset(models.Model): ticker = models.CharField(max_length=255, unique=True) class Transaction(models.Model): id = models.AutoField(primary_key=True) OrderChoices = ( ('Buy', 'Buy'), ('Sell', 'Sell'), ) date = models.DateField(("Date"), default=date.today) order = models.CharField(max_length = 8, choices = OrderChoices) asset = models.ForeignKey(Asset, on_delete=models.CASCADE, default=1) shares_amount = models.FloatField() share_cost = models.FloatField() And here is my updater file code: class Command(BaseCommand): def handle(self, *args, **options): excel_file = "orders.xlsx" df_2 = pd.read_excel(excel_file) df_2 = df_2[['Date(UTC)','Pair', 'Type', 'Order Amount', 'AvgTrading Price']] df_2.columns = ['date', 'asset', 'order', 'shares_amount','share_cost'] df_2['date'] = df_2['date'].str[:9] df_2['asset'] = df_2['asset'].str.replace('USDT', '') df_2['order'] = df_2['order'].str.replace('BUY', 'Buy') print(df_2['asset']) for index, row in df_2.iterrows(): try: Transaction.objects.create( date = datetime.date.today(), order = df_2['order'] , asset = Asset.objects.get(ticker = df_2['asset']), shares_amount = df_2['shares_amount'], share_cost_brl = df_2['share_cost'], ) except Exception as e: print(f' Key Exception - {e}') pass When i try to print(df_2['asset']) , i get as result a list with id(from pandas index) and ticker |
Webpack 5 reuseExistingChunk Posted: 21 Feb 2022 01:34 PM PST Im trying to understand how reuseExistingChunk from SplitChunksPlugin works and i came across with this example https://github.com/webpack/webpack.js.org/issues/2122. This example is very arbitrary and i cant figure out how the original modules created in the first place. Can you provide me with a real example containing simple modules? Thank you. |
Bing Visual Search API endpoint returns different results than bing.com/visualsearch Posted: 21 Feb 2022 01:34 PM PST I'm trying to collect similar images of an image using Bing Visual Search API. I have the following code snippet and I'm providing an insightsToken of this image to the API endpoint. import requests import json BASE_URI = "https://api.bing.microsoft.com/v7.0/images/visualsearch" SUBSCRIPTION_KEY = '' HEADERS = {'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY} # To get an insights, call the /images/search endpoint. Get the token from insightsToken = 'ccid_twIfDfmx*cp_BF680FB5127A96880FCA7D76CC402B60*mid_D6663701CA72F63CF255CBF7EB4998ED50CAABC8*simid_608045920540183139*thid_OIP.twIfDfmxxN4umi!_-sacdNAHaFo' formData = '{"imageInfo":{"imageInsightsToken":"' + insightsToken + '", }, "knowledgeRequest":{"invokedSkills": ["SimilarImages"]}}' file = {'knowledgeRequest': (None, formData)} def main(): try: response = requests.post(BASE_URI, headers=HEADERS, files=file) response.raise_for_status() print_json(response.json()) except Exception as ex: raise ex def print_json(obj): """Print the object as json""" print(json.dumps(obj, sort_keys=True, indent=2, separators=(',', ': '))) # Main execution if __name__ == '__main__': main() Take a look at the first few images that bing.com/visualsearch shows for that image. I tried both uploading an image and providing a link of an image. The results were the identical. Now take a look at the first few images that were collected with the code snippet via API endpoint. For some reason, bing.com/visualsearch results are much better and precise than Bing Visual Search API. I know that Bing Image Search API has the market parameter (based on IP, and your cookies and browsing history). However, even when I tried to change my IP and use incognito mode in a browser, I still got identical results when using bing.com/visualsearch . So I think this parameter doesn't affect the outcome to such a large extent. Why are the results so different? |
Premake makes wrong configurations that wont build Posted: 21 Feb 2022 01:34 PM PST I've started to add premake to my c++ project, but when I built my project files, premake generated configurations that do not build(wrong toolset). As you can see I normally should have Debug/Release as configurations and Win32 and x86 as a platform, but it also adds Debug win64 and Release win64 that do not build Batch build platforms Screenshot of the batch build window: main premake script: workspace "MiniGin" startproject "MiniGin" toolset ("v143") workspace "MiniGin" startproject "MiniGin" toolset ("v143") configurations { "Debug", "Release" } platforms { "Win32", "Win64" } filter { "platforms:Win32" } system "Windows" architecture "x86" filter { "platforms:Win64" } system "Windows" architecture "x86_64" outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}" -- Include directories IncludeDir = {} IncludeDir["Glad"] = "3rdParty/Glad/include" IncludeDir["SDL2"] = "3rdParty/SDL2/include" IncludeDir["SDL2_image"] = "3rdParty/SDL2_image/include" IncludeDir["SDL2_ttf"] = "3rdParty/SDL2_ttf/include" IncludeDir["glm"] = "3rdParty/glm" IncludeDir["vld"] = "3rdParty/VLD" include "3rdParty/Glad" project "MiniGin" location "Minigin" kind "ConsoleApp" cppdialect "C++20" language"C++" staticruntime "On" targetdir("bin/" .. outputdir .. "/%{prj.name}") objdir("bin-int/" .. outputdir .. "/%{prj.name}") warnings "High" flags { "FatalWarnings" --Treat warnings as errors } files { "%{prj.name}/**.h", "%{prj.name}/**.cpp", "$(SolutionDir)3rdParty/VLD/**.h", "$(SolutionDir)3rdParty/glm/**.hpp", "$(SolutionDir)3rdParty/glm/**.inl" } defines { "_CRT_SECURE_NO_WARNINGS" } includedirs { "$(SolutionDir)3rdParty/glm", "$(SolutionDir)3rdParty/SDL2/include", "$(SolutionDir)3rdParty/SDL2_image/include", "$(SolutionDir)3rdParty/SDL2_ttf/include", "$(SolutionDir)3rdParty/Glad", "$(SolutionDir)3rdParty/VLD/include" } libdirs { "$(SolutionDir)3rdParty/SDL2/lib/$(Platform)", "$(SolutionDir)3rdParty/SDL2/lib/$(Platform)", "$(SolutionDir)3rdParty/SDL2_image/lib/$(Platform)", "$(SolutionDir)3rdParty/SDL2_ttf/lib/$(Platform)", "$(SolutionDir)3rdParty/VLD/lib/$(Platform)" } links { "Glad", "opengl32.lib", "xinput.lib", "SDL2.lib", "SDL2main.lib", "SDL2_image.lib", "SDL2_ttf.lib", "vld.lib", } postbuildcommands { "{COPY} $(SolutionDir)3rdParty/SDL2/lib/$(Platform)/SDL2.dll %{cfg.targetdir}", "{COPY} $(SolutionDir)3rdParty/SDL2_image/lib/$(Platform)/*.dll %{cfg.targetdir}", "{COPY} $(SolutionDir)3rdParty/SDL2_ttf/lib/$(Platform)/*.dll %{cfg.targetdir}", } filter "system:windows" staticruntime "On" systemversion "latest" filter "configurations:Debug*" defines "MG_DEBUG" runtime "Debug" symbols "On" filter "configurations:Release*" defines "MG_RELEASE" runtime "Release" optimize "On" second premake script(GLAD): project "Glad" kind "StaticLib" language "C" targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("bin-int/" .. outputdir .. "/%{prj.name}") files { "include/glad/glad.h", "include/KHR/khrplatform.h", "src/glad.c" } includedirs { "include" } filter "system:windows" systemversion "latest" staticruntime "On" filter { "system:windows", "configurations:Release" } buildoptions "/MT" |
référencement web Posted: 21 Feb 2022 01:34 PM PST référencement web Notre spécialisation nous distingue de nombreuses agences de marketing en ligne. Nous n'offrons pas tout, seulement ce que nous pouvons vraiment faire. |
UDP over TCP in C Posted: 21 Feb 2022 01:33 PM PST I'd like to send a whole udp packet (data + each header) as payload of a TCP packet using C. More precisely, I capture the udp packet (using libpcap) and I want to immediately send it to some client - without processing nor looking to its headers -through a tcp connection, but I sending the packet (like a char* buffer) as payload doesn't work. Thanks |
how can I write this in terraform in backend pool Posted: 21 Feb 2022 01:33 PM PST I have application gateway that is not working using Terraform until I added the target VM with the virtual network manually on azure portal but I want to put put correctly in terraform below. How would I do that... and the code below backend_address_pool { name = "sample_appgateway_backpool" value=azurerm_network_interface.dev_westeurope_sample.name } |
Wrong AccentColor showing, color ignored Posted: 21 Feb 2022 01:33 PM PST I added a non-blue color named AccentColor to my assets catalogue. When running my app the tint color is default blue. The "Global accent Color Name" in build settings is correctly set to "AccentColor". Do I need to set anything else? What setting could override this? |
Use TypeScript props keys for function component props Posted: 21 Feb 2022 01:33 PM PST I have this code for example: interface Props { children: any, className?: string, marginTop?: number, marginBottom?: number, } const Div = styled.div` ${(props: Props) => { return css` flex:1; ${props.marginTop && "margin-top: " + props.marginTop + "px;"}; ${props.marginBottom && "margin-bottom: " + props.marginBottom + "px;"}; `; }} `; export const Column: React.FC<Props> = ({ children, className marginTop, marginBottom }) => { return ( <Div className={className} marginBottom={marginBottom} marginTop={marginTop}> {children} </Div> ); }; Now I have to declare the props twice, once in Props and once in the exported component. Is there a way to make all defined Props available as props for the component? Just to make it clear, this is the part I'm trying to save my self to write again: ({ children, className marginTop, marginBottom }) |
Enumerate a list based in a condition in other list Posted: 21 Feb 2022 01:34 PM PST list1 is the original list list2 is the criterion list list3 is the resulting list Operation: if index (first element of each nested list) in list1 occurs in list2, delete this nested list and continue enumeration with the next element not in list2. Example 1: list1 = [[1,'a'],[2,'b'],[3,'c'],[4,'d'],[5,'e'],[6,'f'],[7,'g'], [8,'h']] list2 = [3,4,5,7] list3 = [[1,'a'],[2,'b'],[3,'f'],[4,'h']] Example 2: list1 = [[0,'do'],[1,'re'],[2,'mi'],[3,'fa'],[4,'sol'],[5,'la'],[6,'si']] list2 = [1,3,5] list3 = [[0,'do'],[1,'mi'],[2,'sol'],[3,'si']] |
How can i test my if statement so it will be code covered? Posted: 21 Feb 2022 01:33 PM PST I have this function testing(x) { if(x == 10) { return 10; } } so my test looks like this it('testing function', () => { expect(component.testing(10)).toBe(10); }) and it passes but the problem is that when i run code-coverage than i see that code coverage is descresed because of this if statement - so i can't find a way how can i test this if statement so the branch coverage will be fine |
No CloseRead() / CloseWrite() implementation for tls.Conn Posted: 21 Feb 2022 01:33 PM PST I am currently trying to switch a Go server from using a net.TCPConn to using a tls.Conn for its API calls. The problem I am running into is that my server relies on net.TCPConn 's ability to close the read and write connection independently (via net.TCPConn.CloseRead() and net.TCPConn.CloseWrite() ), a feature which is not implemented at the net.Conn level or in tls.Conn implementation.* * I know that tls.Conn does have an implementation of CloseWrite() , but under the hood this method only calls SetWriteDeadline() and doesn't close the file descriptor, which is the functionality that I need. My questions are as follows: - Is there a specific design reason for not having an implementation for
CloseRead() and CloseWrite() in net.Conn ? It looks like the implementations of net.Conn that have these methods define them almost identically. - Why isn't there an implementation of these methods in
tls.Conn which closes the file descriptors? Thank you in advance for your response! |
How to sort sets of lines like paragraph in bash by the content of it's first line? Posted: 21 Feb 2022 01:34 PM PST I would like to sort various paragraphs in a file by alphabetical order according to the first line: Hampton this is good (mind the mail) Burlington I'm fine Greater Yukonshire Fields (empty) Those blocks of text might consist of one or more lines, but are seperated by one or more blank lines. Desired result: Burlington I'm fine Greater Yukonshire Fields (empty) Hampton this is good (mind the mail) |
How to deal with the sign bit of integer representations with odd bit counts? Posted: 21 Feb 2022 01:34 PM PST Let's assume we have a representation of -63 as signed seven-bit integer within a uint16_t . How can we convert that number to float and back again, when we don't know the representation type (like two's complement). An application for such an encoding could be that several numbers are stored in one int16_t. The bit-count could be known for each number and the data is read/written from a third-party library. An algorithm should be developed that makes the compiler create the right encoding/decoding independent from the actual representation type. One way that seems to work well, is to shift the bits such that their sign bit coincides with the sign bit of an int16_t and let the compiler do the rest. Of course this makes an appropriate multiplication or division necessary. Please see this example: #include <iostream> #include <cmath> int main() { // -63 as signed seven-bits representation uint16_t data = 0b1000001; // Shift 9 bits to the left int16_t correct_sign_data = static_cast<int16_t>(data << 9); float f = static_cast<float>(correct_sign_data); // Undo effect of shifting f /= pow(2, 9); std::cout << f << std::endl; // Now back to signed bits f *= pow(2, 9); uint16_t bits = static_cast<uint16_t>(static_cast<int16_t>(f)) >> 9; std::cout << "Equals: " << (data == bits) << std::endl; return 0; } I have two questions: - This example uses actually a number with known representation type (two's complement) converted by https://www.exploringbinary.com/twos-complement-converter/. Is the bit-shifting still independent from that and would it work also for other representation types?
- Is this the canonical and/or most elegant way to do it?
|
Neo4j - Update relationship properties dynamically from JSON Posted: 21 Feb 2022 01:35 PM PST I would like to create/update properties of an existing Neo4j relationship object dynamically from JSON key values, but this creates a new relationship with a new on each update pass. What I would like to keep only one relationship. JSON object "properties.json" {"prop1":"val1","prop2":"val2"} Query not satisfying : CALL apoc.load.json("properties.json") YIELD value as props WITH props MERGE (client:Client {name: 'Alice'})-[r:KNOWS]->(client:Client {name: 'John'}) ON CREATE SET r = props Results not satisfying (if r was already existing): id> 123 prop1 val1 prop2 val2 id> 124 prop1 val1 prop2 val2 But when the properties are set statically, then it works. Query satisfying : ... ON CREATE SET r.prop1 = "val1", r.prop2 = "val2" Results satisfying (if r was already existing): id> 125 prop1 val1 prop2 val2 Any idea how to solve this ? |
Django - post request body additional data from drf serializer Posted: 21 Feb 2022 01:35 PM PST I need user to send me data in this format. Each items in the "data", mast contain "mandatory_key" and they can additionally send any other keys they want. { "data": [ { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... } ] } since "mandatory_key" is the only key that I know, I can make my serializer like this. class MySerializer(Serializer): mandatory_key = CharField() When I initiate this serializer with data attribute, in the validated_data, it only gives me mandatory_key , not other keys. serializer = MySerializer(data=request.data) if serializer.is_valid(): print(serializer.validated_data) Is there any ways I can do this using serializer? I don't want to manually validate it. Because the use case is much different. Thanks! |
insert if exist on another table mysql on a specific value Posted: 21 Feb 2022 01:34 PM PST I have 2 tables. Table1 has 2 columns, id and city with 4 rows (names of city). Table2 has 4 columns, id , city , produk and price . I have 1 record on table2 that has value "Nasional" on column city How can I update this 1 row and insert the names of the city on table1 How can I achieve this INSERT INTO table2 WHERE EXISTS ( SELECT name FROM table1 WHERE name='nasional' ); |
Angular ngFor not working in specific dialog? Posted: 21 Feb 2022 01:34 PM PST (respPIN and internalNotes are both of type InternalNotes[]) When I set the following in encounter.component.ts: this.ps.GetInternalNotes(resp.PersonID.toString()).subscribe(respPIN => { this.internalNotes = respPIN; }); I get the ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. So I changed it to this.ps.GetInternalNotes(resp.PersonID.toString()).subscribe(respPIN => { for (let index = 0; index < respPIN.length; index++) { this.internalNotes.push(respPIN[index]); } }); I've looked in the debugger in DevTools and it appears fine to me (array of json objects with key value pairs). But the data does not show in the table of the dialog. This is where I send the data from that component to the dialog this.dialog.open(DialogInternalNotesThreeComponent, { data: { data: this.internalNotes } }); dialog-internal-notes-three.component.ts: this.internalNotes = this.data; dialog-internal-notes-three.component.html: <table> <tbody> <tr *ngFor="let note of internalNotes"> <td>{{note.CreateDate}}</td> <td>{{note.CreatedByText}}</td> <td>{{note.Note}}</td> </tr> </tbody> </table> What am I missing? |
How to create a scrollable radiobutton list in TKinter Posted: 21 Feb 2022 01:34 PM PST I am trying to create a scrollable list of radiobuttons in tkinter, but I'm not getting it to work. I have tried embedding my list of radiobuttons in various tkinter containers, but I get the same result, i.e., scrollbar doesn't work and the radiobutton list doesn't get cleared from the container (e.g., so I can replace it with a different list of radiobuttons). I have searched for how to do this and can't find anything. Is this possible? Here's my sample application: import tkinter as tk from tkinter import ttk class CodeSampleForStackoverflow: def __init__(self, window): self.main_window = window self.mainframe = ttk.Frame(self.main_window, padding = '15 3 12 12') self.mainframe.grid(column = 0, row = 0, sticky = "W, E, N, S") self.file_choice = tk.StringVar() self.contents_list = list() self.display_folder_btn = ttk.Button(self.mainframe, text = "Display list of choices", width = 20) self.display_folder_btn.grid(row = 1, column = 0, columnspan = 2) self.display_folder_btn.bind("<Button-1>", self.list_folder_contents) self.folder_contents_canvas = tk.Canvas(self.mainframe) self.scroll_y = tk.Scrollbar(self.folder_contents_canvas, orient="vertical") self.scroll_y.pack(fill = 'y', side = 'right') self.folder_contents_canvas.grid(row=2, column = 0, columnspan = 2) self.folder_contents_frame = tk.Text(self.folder_contents_canvas, height = 7, width = 50, yscrollcommand = self.scroll_y.set) self.folder_contents_frame.pack(side = "top", fill = "x", expand = False, padx = 20, pady = 20) def list_folder_contents(self, event): try: self.contents_list = ['A dictum nulla auctor id.', 'A porttitor diam iaculis quis.', 'Consectetur adipiscing elit.', \ 'Curabitur in ante iaculis', 'Finibus tincidunt nunc.', 'Fusce elit ligula', \ 'Id sollicitudin arcu semper sit amet.', 'Integer at sapien leo.', 'Lorem ipsum dolor sit amet', \ 'Luctus ligula suscipit', 'Nam vitae erat a dolor convallis', \ 'Praesent feugiat quam ac', 'Pretium diam.', 'Quisque accumsan vehicula dolor', \ 'Quisque eget arcu odio.', 'Sed ac elit id dui blandit dictum', 'Sed et eleifend leo.', \ 'Sed vestibulum fermentum augue', 'Suspendisse pharetra cursus lectus', 'Ultricies eget erat et', \ 'Vivamus id lorem mi.'] contents_dict = dict() self.folder_contents_frame.delete(1.0, 'end') counter = 0 for i in self.contents_list: contents_dict[str(counter+1)] = i counter+=1 for (text, value) in contents_dict.items(): #self.folder_contents_frame.insert(1.0, text+"\t"+value+"\n") ttk.Radiobutton(self.folder_contents_frame, text = value, variable = self.file_choice, value = text, style = "TRadiobutton").grid(column = 0, columnspan = 2, sticky = tk.W) self.scroll_y.config(command = self.folder_contents_frame.yview) except Exception as exc: print(exc) #----------------------------------------- def main(): root = tk.Tk() root.title('Scrollable radiobutton list') root.geometry("500x600") tabs = ttk.Notebook(root) tabs.pack(fill = "both") scrollable_radiobutton_list_frame = ttk.Frame(tabs) tabs.add(scrollable_radiobutton_list_frame, text = "Scrollable radiobutton list") my_checker = CodeSampleForStackoverflow(window = scrollable_radiobutton_list_frame) root.mainloop() if __name__ == '__main__': main() If you comment out the line in the list_folder_contents method that creates the radiobuttons and uncomment the line above it, you can see how I'd like it to behave, but with radiobuttons rather than plain text. Edit: side question: If anyone knows why (in the text version) the items are being added in reverse order, I'd appreciate guidance there as well. Thank you for any help you can offer! |
How to downgrade user to read only? Posted: 21 Feb 2022 01:33 PM PST There are some users in the Redshift data warehouse who have read and edit permissions. What query should I run to remove their edit permissions so that they can only do select queries? |
Astra Theme Product catalogue alignment is needed Posted: 21 Feb 2022 01:34 PM PST I'm using the WooCommerce with WordPress, It works very good except for the products, it doesn't align as it should. The images are in different sizes, the product names and prices aren't aligned and the most Obviously the buttons are not bottom aligned! How can I fix this? It needs to be a pure CSS solution and it should work with my code. zimbabox.com Thanks, O.M |
form rendering 'None' in production Posted: 21 Feb 2022 01:34 PM PST When I use the password reset in development it works fine. However in production after the user opens the reset email the password reset form is not displayed however other forms on the site via crispy forms are working fine. Nothing has been changed from dev to production besides the url in the view. The server and dev are running the same version of crispy forms. I did it based off this tutorial and it seems I have made all the required changes for production When checking the urls of the email between production and dev i do not see an issue http://127.0.0.1:8000/reset/MQ/***hm*-e00d**b30b635b358be1573e********/ https://domain.co/reset/MQ/***ht*-71ff80c**580c6cecc3ffd44********/ view that sends the email: def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = User.objects.filter(Q(email=data)|Q(username=data)) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" plaintext = template.loader.get_template('users/password_reset_email.txt') htmltemp = template.loader.get_template('users/password_reset_email.html') c = { "email":user.email, 'domain':'domain.com', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'https', } text_content = plaintext.render(c) html_content = htmltemp.render(c) try: msg = EmailMultiAlternatives(subject, text_content, 'myemail@email.com', [user.email], headers = {'Reply-To': 'myemail@email.com'}) msg.attach_alternative(html_content, "text/html") msg.send() except BadHeaderError: return HttpResponse('Invalid header found.') return redirect ("password_reset_done") password_reset_form = PasswordResetForm() return render(request=request, template_name="users/password_reset.html", context={"password_reset_form":password_reset_form}) template that the user resets password (auth_view): {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="loginout-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Reset Password</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="login-register-btn" type="submit">Reset</button> </div> </form> </div> {% endblock content %} urls: from users import views as user_views path("reset_password/", user_views.password_reset_request, name="password_reset"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="users/password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name="users/password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="users/password_reset_done.html"), name="password_reset_complete"), Update: If I try and render the form like {{ form }} it only renders None leading me to believe the context is not being passed and not a crispy issue Update: Although I am pretty sure it has nothing to do with it I double checked all my email settings and they look good. I also tried the template from the tutorial and it did the same thing |
Read call is slowing down execution by 1 minute? Posted: 21 Feb 2022 01:35 PM PST So, I have this simple program in C that tries to make a HTTP request: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> void err(const char *msg) { fprintf(stderr, "[ERROR] %s\n", msg); exit(1); } int main(int argc,char *argv[]) { char *host; int port; char *request; host = "api.ipify.org"; port = 80; request = "GET / HTTP/1.1\r\nHost: api.ipify.org\r\n\r\n"; struct hostent *server; struct sockaddr_in serv_addr; int sockfd, bytes, sent, received, total; char response[4096]; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) err("Couldn't open socket"); server = gethostbyname(host); if (server == NULL) err("No such host"); memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length); /* connect the socket */ if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) err("Couldn't connect"); /* send the request */ total = strlen(request); sent = 0; while (sent < total) { bytes = write(sockfd, request + sent, total - sent); if (bytes < 0) err("Couldn't send request"); if (bytes == 0) break; sent += bytes; } /* receive the response */ memset(response, 0, sizeof(response)); total = sizeof(response) - 1; received = 0; while (received < total) { bytes = read(sockfd, response + received, total - received); if (bytes < 0) err("Couldn't receive response"); if (bytes == 0) break; received += bytes; } /* * if the number of received bytes is the total size of the * array then we have run out of space to store the response * and it hasn't all arrived yet - so that's a bad thing */ if (received == total) err("Couldn't store response"); /* close the socket */ close(sockfd); /* process response */ printf("Response:\n%s\n",response); return 0; } But, when I compile it and run it, it does what it is supposed to do, but it takes very long. Running it with the time command reveals that it takes ~1m 0.3s to execute. If I comment out the read function call, the execution time goes back to 0.3s. This means that for some reason, it is delaying my program by exactly 1 minute. I've tried putting a printf at the very start of the main function, but that also doesn't get called until 1 minute has passed. Why is the entire main function delayed by one function and how can I fix this? |
NavbarBrand and the NavLink are not on the same level in reactstrap Posted: 21 Feb 2022 01:34 PM PST This is my react app and the code given below is the AppNavbar.js which is in my components folder: import React, { Component } from 'react'; import 'bootstrap/dist/css/bootstrap.css'; import './AppNavbar.css' // import './AppNabar.css' import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink, Container } from 'reactstrap'; class AppNavbar extends Component{ state = { isOpen: false } toggle = () => { this.setState({ isOpen: !this.state.isOpen }); } render() { return( <div id='menu'> <Navbar color='dark' dark expand="sm" className='mb-5'> <Container className='allelements'> <NavbarBrand href='/'>cloudBook</NavbarBrand> <NavbarToggler onClick={this.toggle} /> <Collapse isOpen={this.state.isOpen} navbar> <Nav className='me-auto' navbar> </Nav> <NavLink href='https://github.com/Sarthak8822' className='gitlink'>Github</NavLink> </Collapse> </Container> </Navbar> </div> ) } } export default AppNavbar; And this my App.js file: import './App.css'; import AppNavbar from './components/AppNavbar' function App() { return ( <AppNavbar /> ) } export default App; Now the problem is that my Navbar elements are not aligned properly I'm not able to get what the problem is in my AppNavbar.js file? Please provide the Css styling or something which can resolve my problem. |
Why does textfieldDidEndEditing getting called immediately after textfieldBeginEditing in iOS 13? Works Fine in iOS lower versions Posted: 21 Feb 2022 01:34 PM PST I want to edit the textfield's text and save it whenever user slides on to left on the collection view cell and clicks on rename.So I wrote cell.textfield.becomefirstresponder() whenever rename is clicked..Then In case of handling textfield delegate methods, First textDidBeginEditing is called , then without even doing anything, textfieldDidEndEditing is getting called resigning the responder status.It is happening only in iOS 13 public func textFieldDidBeginEditing(_ textField: UITextField) { self.emptyView.isHidden = true } public func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) { setChangedValues(selectedTextField: textField) } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { //setChangedValues(selectedTextField: textField) textField.resignFirstResponder() return true } public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if range.location == 0 && string == " " { return false } //Fix:- when u remove the text completely and still textfield contains the last character if range.location == 0 && string == "" { textField.text = "" } //Setting the limit var maxLimit = 50 if textField.tag == 2 { maxLimit = 15 } let newLength = (textField.text?.count)! + string.count - range.length if newLength <= maxLimit { //If new character is typed } else { //If the entered character is more than the limit, return false return newLength<=maxLimit } return true } func setChangedValues(selectedTextField: UITextField) { if (selectedTextField.text?.isEmpty)! { assetsTableView.reloadData() } else { var assetModels = Array<FHTeamAssetsModel>() if isEdit { //Both are different, please update if selectedTextField.text != assetsList[selectedAsset!][WPEConstants.ASSET__NAME]! { //Getting the asset based on asset list selection let asset = FHBase.getAssetModel(id: assetsList[selectedAsset!][WPEConstants.ASSET__ID]!) asset.name = selectedTextField.text FHBase.updateTeamAssets(model: asset) } if selectedPath > 0 { //Getting the updated sub asset list assetModels = FHBase.getTeamAssetsModels(assetId: assetsPathArray[selectedPath][WPEConstants.ASSET_ID]) } else { //Getting the updated asset list(without assetId) assetModels = FHBase.getTeamAssetsModels(assetId: nil) } } else { if selectedPath > 0 { //Creating a new sub-asset, with assetId FHBase.shared.createAssetsModel(name: selectedTextField.text, assetId: assetsPathArray[selectedPath][WPEConstants.ASSET_ID], assetName: assetsPathArray[selectedPath][WPEConstants.ASSET_NAME]) //Getting the updated sub asset list assetModels = FHBase.getTeamAssetsModels(assetId: assetsPathArray[selectedPath][WPEConstants.ASSET_ID]) } else { //Creating a new asset(without assetId) FHBase.shared.createAssetsModel(name: selectedTextField.text, assetId: nil, assetName: nil) //Getting the updated asset list(without assetId) assetModels = FHBase.getTeamAssetsModels(assetId: nil) } } //Creating asset list self.createAssetsList(assetModels: assetModels) assetsTableView.reloadData() self.isEdit = false } self.updateEmptyStateUI() } |
Extended Event in Anaysis Service 2008 Posted: 21 Feb 2022 01:35 PM PST Is Extended Event supported in Anaysis Service 2008? If yes, can someone provide me XMLA script for creating extended events? |
How can I write a file in UTF-8 format? Posted: 21 Feb 2022 01:35 PM PST I have bunch of files that are not in UTF-8 encoding and I'm converting a site to UTF-8 encoding. I'm using simple script for files that I want to save in UTF-8, but the files are saved in old encoding: header('Content-type: text/html; charset=utf-8'); mb_internal_encoding('UTF-8'); $fpath = "folder"; $d = dir($fpath); while (False !== ($a = $d->read())) { if ($a != '.' and $a != '..') { $npath = $fpath . '/' . $a; $data = file_get_contents($npath); file_put_contents('tempfolder/' . $a, $data); } } How can I save files in UTF-8 encoding? |
Vim start with cursor where last went off Posted: 21 Feb 2022 01:35 PM PST How do i make Vim always start at the line I was at when i exited that given file last time? |
No comments:
Post a Comment