Download file from the shared folder of Google Drive by using rclone Posted: 06 Apr 2021 08:46 AM PDT I'm wondering if rclone is able to donwload file from the shared folder of Google Drive. If yes, what is the command to do it? rclone sync cloud_name:(what is the shared folder name?)file_name destination_path |
Why IF statement become false , If I write a name present in the nested list Posted: 06 Apr 2021 08:46 AM PDT #When I input "Ali" it jumps to new user statment . Anyone please explain me why? i am a newbie Data_base = [["Ali","1234","5000"],["Sara","1234","2000"]] User_name = input("Enter your name") if User_name in Data_base: print("User persent") elif User_name not in Data_base: print("New User") New_User_name = input("Your name: ") Data_base.append(New_User_name) print(Data_base) |
Elixir: Looping through a map, comparing it to itself, and updating it Posted: 06 Apr 2021 08:46 AM PDT I have a map of a billiard ball table, as follows: ball_map = %{ "cue" => {"x":-15.0, "z": 0.0, "velocity_x": 0.0, "velocity_z": 0.0, "is_idle": true}, "ball_1" => {"x":15.0, "z": 0.0, "velocity_x": 0.0, "velocity_z": 0.0, "is_idle": true}, "ball_2" => {"x":17.0, "z": 1.1, "velocity_x": 0.0, "velocity_z": 0.0, "is_idle": true}, "ball_3" => {"x":17.0, "z": -1.1, "velocity_x": 0.0, "velocity_z": 0.0, "is_idle": true} } I need to apply collisions to it. For that to work properly, each ball must be checked against the others, and the ball locations must be updated as it checks. In my previous attempts, I made a "collision map" and then applied the new locations after, but this had problems with subsequent collisions. So what I'm trying to do is - Loop through each item in the map.
- Compare that item with every other item, and run a check for collision on it (I have a function for that).
- Update both items upon collision, while keeping the format of
ball_map . The code I've come up with for that is this: collision_result = Enum.reduce(result, fn {ball_a, body_a}, acc -> new_result = Enum.map(result, fn {ball_b, body_b} acc -> if (ball_a != ball_b) do has_collided = checkStaticCollisions(body_a, body_b, const_physics["billiard_ball_radius"]) # Takes in parameters (Body A, Body B, radius) # Returns true or false if has_collided == true do calc = PGS.Collision.calculatePosAfterCollision(ball_a, body_a, ball_b, body_b, const_physics["billiard_ball_radius"]) # Takes in parameters (Key of Ball A, Value of Ball A, Key of Ball B, Value of Ball B, radius) # Returns {"id_of_ball_a" => {new X and Z pos}, "id_of_ball_b" => {new X and Z pos}} new_a_pos = calc[ball_a] new_b_pos = calc[ball_b] new_a = %{"x" => new_a_pos["x"], "z" => new_a_pos["z"], "velocity_x" => body_a["velocity_x"], "velocity_z" => body_a["velocity_z"], "is_idle" => body_a["is_idle"]} new_b = %{"x" => new_b_pos["x"], "z" => new_b_pos["z"], "velocity_x" => body_b["velocity_x"], "velocity_z" => body_b["velocity_z"], "is_idle" => body_b["is_idle"]} Map.put(acc, ball_a, new_a) Map.put(acc, ball_a, new_a) else acc end else acc end end) end) Now this doesn't work, as I'm getting a BadMapError (I assume something to do with the acc s on else's), but I'm also positive this will result in a list within a list. I'm still rather new to Elixir, and I'm not sure what else I can do. Is there anything else I can try to make this work? Are there non enum-approaches (does recursion count?)? |
Object cannot be added to the event session. (null) (Microsoft SQL Server, Error: 25602) Posted: 06 Apr 2021 08:46 AM PDT |
Does Content-Length include also headers length? Posted: 06 Apr 2021 08:45 AM PDT When a web server returns a content-length of its response, does it include also the response headers length or just the actual response body content? Thanks |
what is the R code for splitting columns and adding a date Posted: 06 Apr 2021 08:45 AM PDT I have a input file like this | Product | Days |SALES | | -------- | -----------|-------------- | | Google | MTWTFSASU |28000 | | Google | THFSASU |10000 | I need the data to split like this. The date here is a start_date value which I input from a txt file . LEts consider start_date="01/01/2021". Then the first occurrence should have the date as "01/01/2021" for Monday and then the consecutive days based on the day(Monday-Sunday). Product | Days | SALES | NO_OF_DAYS | DATE | Google | M | 4000 | 7 | 01/01/2021 | Google | T | 4000 | 7 | 01/02/2021 | Google | W | 4000 | 7 | 01/03/2021 | Google | T | 4000 | 7 | 01/04/2021 | Google | F | 4000 | 7 | 01/05/2021 | Google | SA | 4000 | 7 | 01/06/2021 | Google | SU | 4000 | 7 | 01/07/2021 | Apple | T | 2500 | 4 | 01/02/2021 | Apple | F | 2500 | 4 | 01/05/2021 | Apple | SA | 2500 | 4 | 01/06/2021 | Apple | SU | 2500 | 4 | 01/07/2021 | |
Javascript ID that I need to associate with a list of SVG files Posted: 06 Apr 2021 08:45 AM PDT Teaching my self some Javascript this spring break while my students are on break and I have been using some resources to intergrade weather in our live event broadcasts for the high school I work for. I am using openweathermap.org to fetch data that I want to associate with Erik Flowers Weather Icons I have been slowly but surely piecing things together but I am stuck on taking a ID which outputs the exact file name I need, the file name changes with the weather, then putting it into a div. With the below I output wi wi-owm-803 but it needs to be <i class="wi wi-owm-803"></i> and it will associate with folder of SVG files. const key = '4e2d45d68584fcbfbbc77bba2a0d6cd7'; if(key=='') document.getElementById('temp').innerHTML = ('Remember to add your api key!'); function weatherBallon( cityID ) { fetch('https://api.openweathermap.org/data/2.5/weather?id=' + cityID+ '&appid=' + key + '&units=imperial') .then(function(resp) { return resp.json() }) // Convert data to json .then(function(data) { drawWeather(data); }) .catch(function() { // catch any errors }); } function drawWeather( d ) { var icon = "wi wi-owm-" + d.weather[0].id; document.getElementById('windMPH').innerHTML = Math.round(d.wind.speed) + ' mph'; document.getElementById('direction').innerHTML = Math.round(d.wind.deg); document.getElementById('description').innerHTML = icon; document.getElementById('temp').innerHTML = Math.round(d.main.temp) + '°'; document.getElementById('location').innerHTML = d.name; document.getElementById('id').innerHTML = d.id; <h1 div id="windDirection"></div> </h1> <div id="weather"> <h1 id="icon"></h1> <h1 id="temp"></h1> <h1 <div id="description"</div></h1> <h1 <div id="location"></div></h1> <h1 <div id="windMPH"</div> </h1> <h1 <div id="direction"</div></h1> With this code I output wi wi-owm-803 but it needs to be and it will associate with folder of SVG files. |
Symfony internalization routes with params Posted: 06 Apr 2021 08:45 AM PDT I am developing a project in Symfony 4.3. I am trying to create URLs in different languages. I have tried to use this notation: /** * @Route({ * "it": "/{_locale}/rassegna/stampa", * "bg": "/{_locale}/Статии/в/печата" * }, name="rassegna_stampa", utf8=true) */ The problem is that when I try to create a link in a twig, for example: path('rassegna_stampa', {'_locale':'it'}) I receive an error telling me me that: An exception has been thrown during the rendering of a template ("Unable to generate a URL for the named route "rassegna_stampa" as such route does not exist."). So it seems that _locale is not matched... |
VHDL- back and forth seven segment counter Posted: 06 Apr 2021 08:45 AM PDT I'm doing a university assignment where a code was given from an old board and i had to run it on a new one. (Nexys --> Basys3). In one of the tasks, it was necessary to make the seven segment count to 9 (0-1-2-3-4-5-6-7-8-9) and then back to 0 (9-8-7-6-5-4-3-2-1-0). I did this task, but the teacher did not like exacly how it counts. It was something like (0-1-2-3-4-5-6-7-8-9 -> 9-8-7-6-5-4-3-2-1-0-0-1...) but should be (...1-0-1...). And one more task is that with each new digit, the little dot should change it value (0 <--> 1) I honestly do not fully understand the VHDL syntax,. which makes it much more difficult. So my questions are: - At the moment i cannot understand why i have this additional "0" when counting...and how can i fix this ?
- How to make little dot change it's value so it "blinks" ?
Yes, i know that you should simply change the value of correct bit something like...seg(7) <= '1'; but for some reason even this doesn't work...or again i do not fully understand something. Code: .vhd library IEEE; use IEEE.STD_LOGIC_1164.ALL; use IEEE.STD_LOGIC_ARITH.ALL; use IEEE.STD_LOGIC_UNSIGNED.ALL; entity Nexysdemo is Port ( clk : in std_logic; btn : in std_logic_vector(3 downto 0); sw : in std_logic_vector(7 downto 0); led : out std_logic_vector(7 downto 0); -- Cathode patterns of 7-segment an : out std_logic_vector(3 downto 0); --4 Anode signals seg : out std_logic_vector(7 downto 0)); end Nexysdemo; architecture Behavioral of Nexysdemo is ------------------------------------------------------------------------ -- Signal Declarations ------------------------------------------------------------------------ signal clkdiv : std_logic_vector(24 downto 0); -- 24 downto 0 signal cntr : std_logic_vector(4 downto 0); -- 3 downto 0 signal cclk : std_logic; signal dig : std_logic_vector(6 downto 0); ------------------------------------------------------------------------ -- Module Implementation ------------------------------------------------------------------------ begin led <= sw; dig <= "0111111" when cntr = "00000" else --0 "0000110" when cntr = "00001" else --1 "1011011" when cntr = "00010" else --2 "1001111" when cntr = "00011" else --3 "1100110" when cntr = "00100" else --4 "1101101" when cntr = "00101" else --5 "1111101" when cntr = "00110" else --6 "0000111" when cntr = "00111" else --7 "1111111" when cntr = "01000" else --8 "1101111" when cntr = "01001" else --9 "1111111" when cntr = "01010" else --8 "0000111" when cntr = "01011" else --7 "1111101" when cntr = "01100" else --6 "1101101" when cntr = "01101" else --5 "1100110" when cntr = "01110" else --4 "1001111" when cntr = "01111" else --3 "1011011" when cntr = "10000" else --2 A "0000110" when cntr = "10001" else --1 B "0111111" when cntr = "10010" else --0 C "0000000"; seg(6 downto 0) <= not dig; an <= btn; seg(7) <= '1'; -- Divide the master clock (100Mhz) down to a lower frequency. process (clk) begin if clk = '1' and clk'Event then clkdiv <= clkdiv + 1; end if; end process; cclk <= clkdiv(24); --24 process (cclk) begin if cclk = '1' and cclk'Event then if cntr = "10010" then --1001 cntr <= "00000"; else cntr <= cntr + 1; end if; end if; end process; end Behavioral; Basys-3-Master.xdc # Clock signal set_property PACKAGE_PIN W5 [get_ports clk] set_property IOSTANDARD LVCMOS33 [get_ports clk] create_clock -add -name sys_clk_pin -period 10.00 -waveform {0 5} [get_ports clk] ## Switches set_property PACKAGE_PIN V17 [get_ports {sw[0]}] set_property IOSTANDARD LVCMOS33 [get_ports {sw[0]}] set_property PACKAGE_PIN V16 [get_ports {sw[1]}] set_property IOSTANDARD LVCMOS33 [get_ports {sw[1]}] set_property PACKAGE_PIN W16 [get_ports {sw[2]}] set_property IOSTANDARD LVCMOS33 [get_ports {sw[2]}] set_property PACKAGE_PIN W17 [get_ports {sw[3]}] set_property IOSTANDARD LVCMOS33 [get_ports {sw[3]}] set_property PACKAGE_PIN W15 [get_ports {sw[4]}] set_property IOSTANDARD LVCMOS33 [get_ports {sw[4]}] set_property PACKAGE_PIN V15 [get_ports {sw[5]}] set_property IOSTANDARD LVCMOS33 [get_ports {sw[5]}] set_property PACKAGE_PIN W14 [get_ports {sw[6]}] set_property IOSTANDARD LVCMOS33 [get_ports {sw[6]}] set_property PACKAGE_PIN W13 [get_ports {sw[7]}] set_property IOSTANDARD LVCMOS33 [get_ports {sw[7]}] ## LEDs set_property PACKAGE_PIN U16 [get_ports {led[0]}] set_property IOSTANDARD LVCMOS33 [get_ports {led[0]}] set_property PACKAGE_PIN E19 [get_ports {led[1]}] set_property IOSTANDARD LVCMOS33 [get_ports {led[1]}] set_property PACKAGE_PIN U19 [get_ports {led[2]}] set_property IOSTANDARD LVCMOS33 [get_ports {led[2]}] set_property PACKAGE_PIN V19 [get_ports {led[3]}] set_property IOSTANDARD LVCMOS33 [get_ports {led[3]}] set_property PACKAGE_PIN W18 [get_ports {led[4]}] set_property IOSTANDARD LVCMOS33 [get_ports {led[4]}] set_property PACKAGE_PIN U15 [get_ports {led[5]}] set_property IOSTANDARD LVCMOS33 [get_ports {led[5]}] set_property PACKAGE_PIN U14 [get_ports {led[6]}] set_property IOSTANDARD LVCMOS33 [get_ports {led[6]}] set_property PACKAGE_PIN V14 [get_ports {led[7]}] set_property IOSTANDARD LVCMOS33 [get_ports {led[7]}] ##7 segment display set_property PACKAGE_PIN W7 [get_ports {seg[0]}] set_property IOSTANDARD LVCMOS33 [get_ports {seg[0]}] set_property PACKAGE_PIN W6 [get_ports {seg[1]}] set_property IOSTANDARD LVCMOS33 [get_ports {seg[1]}] set_property PACKAGE_PIN U8 [get_ports {seg[2]}] set_property IOSTANDARD LVCMOS33 [get_ports {seg[2]}] set_property PACKAGE_PIN V8 [get_ports {seg[3]}] set_property IOSTANDARD LVCMOS33 [get_ports {seg[3]}] set_property PACKAGE_PIN U5 [get_ports {seg[4]}] set_property IOSTANDARD LVCMOS33 [get_ports {seg[4]}] set_property PACKAGE_PIN V5 [get_ports {seg[5]}] set_property IOSTANDARD LVCMOS33 [get_ports {seg[5]}] set_property PACKAGE_PIN U7 [get_ports {seg[6]}] set_property IOSTANDARD LVCMOS33 [get_ports {seg[6]}] set_property PACKAGE_PIN V7 [get_ports {seg[7]}] set_property IOSTANDARD LVCMOS33 [get_ports {seg[7]}] set_property PACKAGE_PIN U2 [get_ports {an[0]}] set_property IOSTANDARD LVCMOS33 [get_ports {an[0]}] set_property PACKAGE_PIN U4 [get_ports {an[1]}] set_property IOSTANDARD LVCMOS33 [get_ports {an[1]}] set_property PACKAGE_PIN V4 [get_ports {an[2]}] set_property IOSTANDARD LVCMOS33 [get_ports {an[2]}] set_property PACKAGE_PIN W4 [get_ports {an[3]}] set_property IOSTANDARD LVCMOS33 [get_ports {an[3]}] ##Buttons set_property PACKAGE_PIN U18 [get_ports {btn[0]}] set_property IOSTANDARD LVCMOS33 [get_ports {btn[0]}] set_property PACKAGE_PIN T18 [get_ports {btn[1]}] set_property IOSTANDARD LVCMOS33 [get_ports {btn[1]}] set_property PACKAGE_PIN W19 [get_ports {btn[2]}] set_property IOSTANDARD LVCMOS33 [get_ports {btn[2]}] set_property PACKAGE_PIN T17 [get_ports {btn[3]}] set_property IOSTANDARD LVCMOS33 [get_ports {btn[3]}] ## Configuration options, can be used for all designs set_property CONFIG_VOLTAGE 3.3 [current_design] set_property CFGBVS VCCO [current_design] |
Accessing AJAX response outside of the ajax scope Posted: 06 Apr 2021 08:45 AM PDT I have a nested ajax script, I am trying to access the response from inner ajax outside of ajax block but I can't var hresponse=''; $.ajax({ url: "getFpo.php", type: "post", data:{id:id}, success: function (response) { if(response==1) { window.location.href ="fpo_detail.php?fpo_id="+id; } else { $.ajax({ url: "getFpolist.php", type: "post", data:{id:id}, success: function (response) { callback(response); }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); } }); function callback(data) { hresponse=data; } } }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); } }); console.log(hresponse); But it doesn't work. I have tried callback and assigning simply to a global variable |
What algorithm to efficiently traverse all edges in a graph? Posted: 06 Apr 2021 08:46 AM PDT Big Picture I'm writing some code to simulate a computer at the transistor level. The emulator boils down to a graph where each node is a transistor, and each edge is a wire connecting any two transistor nodes on the graph. This graph is cyclic, and transistor nodes may be connected to themselves. To run a single "step" of the emulator, two separate functions are run: - Each wire edge is processed, setting the input of its target node from the output of its source node. Each wire is visited exactly once each step, but a transitor may be visited multiple times.
- Each transistor node output state is updated from its input's states (how is outside the scope of this question, I'm pretty sure I'm doing it efficiently).
I believe I have the second step optimised, but I need help making the first step more efficient. Implementation The code looks roughly like this: type InputBit = usize; type OutputBit = usize; struct Emulator { inputs: Vec<u64>, outputs: Vec<u64>, wires: Vec<(InputBit, OutputBit)>, } impl Emulator { fn step(&mut self) { step_wires(&mut self); step_transistors(&mut self); } fn step_wires(&mut self) { for (input, output) in self.wires.iter() { // NB omitted bit-twiddling to get bit indices self.outputs[output] = self.inputs[input]; } } fn step_transistors(&mut self) { // ... omitted for brevity ... } } Each transistor node N is composed of two input bits at bit 2N and 2N+1 in self.inputs , and two output bits at 2N and 2N+1 in self.outputs . The problem as I see it, is that my list of wires (and the transistors) is in arbitrary order. This means it's really cache inefficient. For example, imagine this set of wires (input node bit, output node bit): [ (0, 1000), (1000, 2000), (1, 1001), (1001, 2001) ] If my memory cache size is < 1000 bits, that means I get a cache miss for most of the reads and writes. If they were reorganised into: [ (0, 1000), (1, 1001), (1000, 2000), (1001, 2001) ] Then it's less cache misses. Equally, I could also "move" the Transitor Nodes to give the following equivalent graph: [ (0, 2), (1, 3), (2, 4), (3, 5) ] Which now only uses one cache line! Much faster. (Note this example is slightly misleading, as the Node indices will be densely packed, i.e. there wont be any "empty" node indices that are unused. But it is fine to "swap" nodes). Finally, The Question What algorithm can I use to chose which order I visit the Wire Edges, and/or reorder the Transitor Node indices, so that I have the minimum number of cache misses while traversing the graph? I think something that reduces the total "distances" of all the edges would be a good start? And then something that sorts the edges so that ones which are entirely within a single cache line are visited first, in cache line order? And then do between-different-cache-line edges in some order? Any help pointing towards the right things to google much appreciated! |
How can I search values of consecutive XML nodes with C#? Posted: 06 Apr 2021 08:45 AM PDT I want to select nodes from an XML that have consecutive child nodes with values matching with the respective words from my search term. Here is a sample XML: <book name="Nature"> <page number="4"> <line ln="10"> <word wn="1">a</word> <word wn="2">white</word> <word wn="3">bobcat</word> <word wn="3">said</word> <line> <line ln="11"> <word wn="1">Hi</word> <word wn="2">there,</word> <word wn="3">Bob.</word> <line> </page> My search term is Hi Bob. I want find all the nodes from the above XML that contain two consecutive words with values %Hi% and %Bob%. Please note that I want to perform a partial and case-insensitive match for each word in my search term. It should return the following output for the above XML: ln="10" wn="2" wn="3" Please note that line (ln=10) is selected because it contains two consecutive words (in the correct order) that match with the search term. white=%Hi% bobcat=%Bob% However, the next line (ln=11) is not selected because the matching nodes are not consecutive. Please note that all the words from the search term should be matched in order for it to be considered a match. Thank you! |
TypeError with scatterplot and label Posted: 06 Apr 2021 08:45 AM PDT This seems pretty simple, but for some reason, I can't get it to work. This is in pandas 1.2.3 and matplotlib 3.4.0 running on an anaconda's python 3.8.8 on Windows 10 64-bit, inside a Jupyter notebook locally. I've created a replication below. First, a working version; note the commented out label line: import numpy as np import pandas as pd import matplotlib.pyplot as plt df_test = pd.DataFrame(np.random.randn(1000, 4), columns=list("ABCD")) df_test.plot(kind="scatter", x="A", y="B", alpha=0.4, figsize=(10,7), #label="la la", s=df_test["C"]*100, c="D", cmap=plt.get_cmap("jet"), colorbar=True, ) plt.legend() Running the above gives a complaint No handles with labels found to put in legend (as expected) and some deprecation warnings, but shows a chart. The dots are nicely colored, and you might even see the empty legend box. Now, uncomment the label line: df_test.plot(kind="scatter", x="A", y="B", alpha=0.4, figsize=(10,7), label="la la", s=df_test["C"]*100, c="D", cmap=plt.get_cmap("jet"), colorbar=True, ) plt.legend() and when I run this, I get a TypeError: object of type 'NoneType' has no len() error like the below: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) D:\anaconda\envs\tf-gpu\lib\site-packages\IPython\core\formatters.py in __call__(self, obj) 339 pass 340 else: --> 341 return printer(obj) 342 # Finally look for special method names 343 method = get_real_method(obj, self.print_method) D:\anaconda\envs\tf-gpu\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig) 246 247 if 'png' in formats: --> 248 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs)) 249 if 'retina' in formats or 'png2x' in formats: 250 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs)) D:\anaconda\envs\tf-gpu\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs) 130 FigureCanvasBase(fig) 131 --> 132 fig.canvas.print_figure(bytes_io, **kw) 133 data = bytes_io.getvalue() 134 if fmt == 'svg': D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs) 2228 else suppress()) 2229 with ctx: -> 2230 self.figure.draw(renderer) 2231 2232 if bbox_inches: D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 72 @wraps(draw) 73 def draw_wrapper(artist, renderer, *args, **kwargs): ---> 74 result = draw(artist, renderer, *args, **kwargs) 75 if renderer._rasterizing: 76 renderer.stop_rasterizing() D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 49 renderer.start_filter() 50 ---> 51 return draw(artist, renderer, *args, **kwargs) 52 finally: 53 if artist.get_agg_filter() is not None: D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\figure.py in draw(self, renderer) 2732 2733 self.patch.draw(renderer) -> 2734 mimage._draw_list_compositing_images( 2735 renderer, self, artists, self.suppressComposite) 2736 D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite) 130 if not_composite or not has_images: 131 for a in artists: --> 132 a.draw(renderer) 133 else: 134 # Composite any adjacent images together D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 49 renderer.start_filter() 50 ---> 51 return draw(artist, renderer, *args, **kwargs) 52 finally: 53 if artist.get_agg_filter() is not None: D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\_api\deprecation.py in wrapper(*inner_args, **inner_kwargs) 429 else deprecation_addendum, 430 **kwargs) --> 431 return func(*inner_args, **inner_kwargs) 432 433 return wrapper D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe) 2923 renderer.stop_rasterizing() 2924 -> 2925 mimage._draw_list_compositing_images(renderer, self, artists) 2926 2927 renderer.close_group('axes') D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite) 130 if not_composite or not has_images: 131 for a in artists: --> 132 a.draw(renderer) 133 else: 134 # Composite any adjacent images together D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 49 renderer.start_filter() 50 ---> 51 return draw(artist, renderer, *args, **kwargs) 52 finally: 53 if artist.get_agg_filter() is not None: D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\legend.py in draw(self, renderer) 612 613 self.legendPatch.draw(renderer) --> 614 self._legend_box.draw(renderer) 615 616 renderer.close_group('legend') D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\offsetbox.py in draw(self, renderer) 366 for c, (ox, oy) in zip(self.get_visible_children(), offsets): 367 c.set_offset((px + ox, py + oy)) --> 368 c.draw(renderer) 369 370 bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\offsetbox.py in draw(self, renderer) 366 for c, (ox, oy) in zip(self.get_visible_children(), offsets): 367 c.set_offset((px + ox, py + oy)) --> 368 c.draw(renderer) 369 370 bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\offsetbox.py in draw(self, renderer) 366 for c, (ox, oy) in zip(self.get_visible_children(), offsets): 367 c.set_offset((px + ox, py + oy)) --> 368 c.draw(renderer) 369 370 bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\offsetbox.py in draw(self, renderer) 366 for c, (ox, oy) in zip(self.get_visible_children(), offsets): 367 c.set_offset((px + ox, py + oy)) --> 368 c.draw(renderer) 369 370 bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\offsetbox.py in draw(self, renderer) 692 if self._clip_children and not (c.clipbox or c._clippath): 693 c.set_clip_path(tpath) --> 694 c.draw(renderer) 695 696 bbox_artist(self, renderer, fill=False, props=dict(pad=0.)) D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 49 renderer.start_filter() 50 ---> 51 return draw(artist, renderer, *args, **kwargs) 52 finally: 53 if artist.get_agg_filter() is not None: D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\collections.py in draw(self, renderer) 1007 def draw(self, renderer): 1008 self.set_sizes(self._sizes, self.figure.dpi) -> 1009 super().draw(renderer) 1010 1011 D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 49 renderer.start_filter() 50 ---> 51 return draw(artist, renderer, *args, **kwargs) 52 finally: 53 if artist.get_agg_filter() is not None: D:\anaconda\envs\tf-gpu\lib\site-packages\matplotlib\collections.py in draw(self, renderer) 378 do_single_path_optimization = False 379 if (len(paths) == 1 and len(trans) <= 1 and --> 380 len(facecolors) == 1 and len(edgecolors) == 1 and 381 len(self._linewidths) == 1 and 382 all(ls[1] is None for ls in self._linestyles) and TypeError: object of type 'NoneType' has no len() It seems to be an interaction with the c= for the coloring and the label= . If I comment out the color stuff (c=, cmap, colorbar), the plot renders with a legend box, and we saw that it also works with colors included and label commented out. I also tried restarting the kernel, and had same results. I have not tried making new environments with other versions yet, as I wanted to see if this was just me, or something others could replicate. (BTW, On Colab, python 3.7.10, pandas 1.1.5, matplotlib 3.2.2, the code does appear to work (with a minor figsize complaint), so could be something about the more recent versions of these packages, or my setup...) So, please be kind, but could anyone point out what silly thing I'm missing here? Any suggestions? Anyone able to replicate? |
How to dynamically select elements with document.querySelectorAll() for function call? Posted: 06 Apr 2021 08:45 AM PDT I have been working on this fiddle: https://jsfiddle.net/j1vrb7to/165/ The code in that fiddle is this: HTML: <div id="CalculationContainer"> <input type="numbers" class="form-control new-tuition" /> <br /> <input type="numbers" class="form-control new-tuition" /> <br /> <input type="numbers" class="form-control new-tuition" /><br /><br /> <input type="numbers" id="new-tuition-total" disabled="disabled" /><br /> <br /> <input type="numbers" class="form-control new-state" /> <br /> <input type="numbers" class="form-control new-state" /> <br /> <input type="numbers" class="form-control new-state" /><br /><br /> <input type="numbers" id="new-state-total" disabled="disabled" /> </div> JavaScript: const NewTuitionInputs = document.querySelectorAll("div#CalculationContainer > input.new-tuition"); const NewStateInputs = document.querySelectorAll("div#CalculationContainer > input.new-state"); NewTuitionInputs.forEach(function(input) { input.onchange = function() { var total = 0; NewTuitionInputs.forEach(function(input) { total += parseInt(input.value); }); document.getElementById("new-tuition-total").value = total; } }); NewStateInputs.forEach(function(input) { input.onchange = function() { var total = 0; NewStateInputs.forEach(function(input) { total += parseInt(input.value); }); document.getElementById("new-state-total").value = total; } }); As the users enter values into the textboxes, I want to update the value of another field to display running totals. Ultimately I will need to keep track of 20+ running totals on my form. Instead of maintaining 20+ functions, is it possible to use a single function to calculate running totals on the fly? Here is some pseudocode to demonstrate what I'm thinking: var ThisInput = document.querySelectorAll("div#CalculationContainer > input.[INPUT_CLASS_PARAMETER_HERE]"); ThisInput.forEach(function(input) { input.onchange = function() { var total = 0; ThisInput.forEach(function(input) { total += parseInt(input.value); }); document.getElementById("[DYNAMICALLY_CHOOSE_WHERE_TO_DISPLAY").value = total; } }); |
Copy file from a folder to another Posted: 06 Apr 2021 08:46 AM PDT I want to copy a file from a folder, one directory above the python script being interpreted, to a folder in the same directory the python script lives. This is the folder structure. -----/A ---------copyme.txt -----/test ----------myCode.py ---------/B I want to copy file copyme.txt , from folder A , to folder B , under the test folder. This is the code i tried: import os import shutil shutil.copyfile('../A/copyme.txt', '/B') However, i received this error: Traceback (most recent call last): File "test.py", line 4, in <module> shutil.copyfile('../A/copyme.txt', 'B') File "/home/user1/anaconda3/lib/python3.8/shutil.py", line 261, in copyfile with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst: IsADirectoryError: [Errno 21] Is a directory: 'B' |
Getting the error: bash: (program): cannot execute binary file: Exec format error, on both 32-bit and 64-bit Windows Posted: 06 Apr 2021 08:45 AM PDT There is a program developed for linguistic research (http://people.csail.mit.edu/mcollins/code.html). When I try to run the parser using Git bash terminal on Windows, I get the error: bash: cannot execute binary file: Exec format error. First, I assumed it's because of my 64-bit OS, since the file is 32-bit. So, I tried the program on a 32-bit system, but got the same message. Any ideas on how to fix the issue?: file (program) shows: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.2.5, with debug_info, not stripped uname -srv for my 64-bit OS, shows: MINGW64_NT-10.0-19042 3.1.7-340.x86_64 2021-03-26 22:17 UTC uname -srv for my 32-bit OS, shows: MINGW32_NT-6.1-7601 3.1.7-340.i686 2021-03-26 22:01 UTC P.S.: If you'd like to give it a try, this code should work in the program directory, but it doesn't work for me: gunzip -c models/model2/events.gz | code/parser examples/sec23.tagged models/model2/grammar 10000 1 1 1 1 > examples/sec23.model2 |
Why is there an Error when using the format.join function Posted: 06 Apr 2021 08:46 AM PDT c = conn.cursor() c.execute("CREATE TABLE IF NOT EXISTS Filterdata({})".format(' ,'.join(df.columns))) What could be the error in this Code please. i keep getting this OperationalError: near "(": syntax error UPDATE The reason why i am getting this error message is that My columns have values like 1.5, 3.6, 9.0 i strongly believe this is the reason for the error. please assist on how to use the full float numbers. |
trying to send correlation id in response Posted: 06 Apr 2021 08:46 AM PDT I am trying to add my logger correlation id to the header and return in the response in header. I am using the framework Spring Boot. This is the code: public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception { response.addHeader("requestId", CORRELATION_ID_LOG_VAR_NAME); MDC.remove(CORRELATION_ID_LOG_VAR_NAME); ThreadLocalUtils.remove(); } |
How to pass argument(input) in an npx command to run the npm package Posted: 06 Apr 2021 08:45 AM PDT I have an npm package that takes JSON file as input(argument). I want to know How to pass input via CLI while running an npm package using npx? I set up the command to run the package but I don't know how to give input via CLI. In my package.json file, I have these two commands. "bin": { "biz-card": "index.js", "test": "app.js" }, I want to pass an argument to the test command so that it can run the app.js file app.js file code #!/usr/bin/env node module.export = { sayHello: (name) => { console.log(`Hello ${name}`); } } Anyone can help me with this |
How to run a script from a package from the command line Posted: 06 Apr 2021 08:45 AM PDT I have trouble running a Python module from a package as a script from the command line. I have a Python package located at /path/to/pkg with a structure that goes something like this: pkg subpkg1 __init__.py module1.py subpkg2 __init__.py module2.py __init__.py The content of module2.py is something like: from subpkg1 import module1 if __name__ == '__main__': module1.foo() I want to be able to run module2.py from the command line regardless of the current working directory, but I can't get it to work. These are the various alternatives I've tried: python /path/to/pkg/subpkg2/module2.py . This results in the error ImportError: No module named subpkg1 python -m /path/to/pkg/subpkg2/module2 . This results in the same error as above, ImportError: No module named subpkg1 python -m /path/to/pkg.subpkg2.module2 . This results in the output /usr/bin/python: Import by filename is not supported. . I don't even understand what this message is supposed to tell me. python -m pkg.subpkg2.module2 . This results in the output /usr/bin/python: No module named subpkg2 . I'm like: Of course there is no module named subpkg2 , because it's a package, not a module. But weirdly, Python was apparently able to locate pkg without me providing a path to it? I'm confused. What am I doing wrong? Note that I have not appended /path/to to the PYTHONPATH and if possible, I'd like to avoid doing so. I just want Python to be aware of the fact that module2.py is located inside a package rather than just being an isolated script, so that the absolute import from subpkg1 import module1 can be resolved. Note also that I'm on Python 2.7 in case it makes any difference. |
How to upload files from location system to GCP Storage using Python in cloud sherr Posted: 06 Apr 2021 08:45 AM PDT I have files on my local system ,I'm able to upload to GCP Storage using python by connecting to GCP account using json file. I'm running this python program manually in a command prompt but want use the same program which can read data from my local system or share drive ..any suggestion how we can connect to local system path or share drive path from VM / Cloud shell to upload files to GCP Storage. Thanks |
Loop through multiple rows as labels and data in chart.js and PHP Posted: 06 Apr 2021 08:46 AM PDT Using chart.js I want to create a graph of a given stock price. The labels and data are fetched using the data from $select_query. Here I create a dynamic function that gets the ticker name from the URL: https://signal-invest.com/tick/?ticker=LOW $select_query = $con->prepare("SELECT Date_buy, Name_buy, Price_buy FROM daily_buy_orders WHERE Name_buy = ?"); $select_query->bind_param('s', $ticker); // 's' specifies the variable type => 'string' $select_query->execute(); I tried to loop through the rows using the while loop but failed. <canvas id="myChart" style="border: 1px solid black; margin: 25px 25px" height="300"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { //labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], labels: [<?php $get_dates = $select_query->get_result(); while ($rows = mysqli_fetch_assoc($get_dates)) { $dates = $rows["Date_buy"]; echo ''.$dates.''; } ?>], datasets: [{ label: '# of Votes', //data: [12, 19, 3, 5, 2, 3], data: [<?php $get_prices = $select_query->get_result(); while ($rowss = mysqli_fetch_assoc($get_prices)) { $prices = $rowss["Price_buy"]; echo ''.$prices.''; } ?>], backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgb(75, 192, 192)', borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> Above code messes with my table below. When creating the tables the while loop actually works. I tried to use the same thinking when doing the while loops for the labels and data in chartjs, didn't work though. <table style="width:50%" border="solid"> <tr> <th>Name</th> <th>Price</th> <th>Date of signal</th> </tr> <?php $result = $select_query->get_result(); while ($row = mysqli_fetch_assoc($result)) { $name_buy = $row["Name_buy"]; $price_buy = $row["Price_buy"]; $date = $row["Date_buy"]; echo buy_table($name_buy, $price_buy, $date); } ?> </table> |
Glomming to make a sh script Posted: 06 Apr 2021 08:46 AM PDT Is this a stupid thing to do? - pipe output of ls -1 to a file
- edit the file to surround each line with quote characters
- and add a command at front of each line
- make the file executable
- run it as a script
I ask because the files swept up in ls -1 have special characters like parentheses, back quotes, etc. My editor macro surrounds each filename with double-quotes, but that's not enough. Is there a more righteous way to do this? Should I be glomming within the script itself? I like using the editing step to catch errors, but I may just be being stubborn, (Context: I have thousands of MP3 files and want to run a program on each to get its tempo.) What's the smart thing to do here? |
Cannot read property username of undefinded discord.js Posted: 06 Apr 2021 08:45 AM PDT I am making a ship command, the error messages work but the shipping does not. I always get this error: Type Error: Cannot read property "username" of undefined . Can someone help me to fix it? Here is my code: const { DiscordAPIError } = require("discord.js"); const Discord = require('discord.js'); const client = new Discord.Client(); module.exports = { name: 'ship', description: "Ship two users!", execute(message, args) { const user = message.mentions.members.first(); const user2 = message.mentions.members.first(+1) ; const images = [(1-100) code is different, put every number there] const result = Math.floor(Math.random() * images.length); const error = new Discord.MessageEmbed() .setColor("#000000") .setTitle("Ship") .setDescription("There was an error: Check if you mentioned a user other than you!") .setFooter(message.author.username) .setTimestamp() ; if(!user) return message.reply(error); if(!user2) user2 = message.author.username; if(user.id === message.author.id) return message.reply(error); const embed = new Discord.MessageEmbed() .setColor("#2A333E") .setTitle("Ship") .setDescription(user2.user.username + " + " + user.user.username + " =") .addField(images[result] + "%" , "Is this good or not so good?") .setFooter(message.author.username) .setTimestamp() ; message.channel.send(embed) }} |
Warning: Failed prop type: Invalid prop `tag` supplied to `NavLink` Posted: 06 Apr 2021 08:46 AM PDT I'm currently trying to integrate a shard-dashboard into my react app. Everything works pretty well, except that the search-navbar is scaled way too big. The console gives me the following error: "Warning: Failed prop type: Invalid prop tag supplied to NavLink . in NavLink (at SidebarNavItem.js:8)". The mentioned file looks as follows: import React from "react"; import PropTypes from "prop-types"; import { NavLink as RouteNavLink } from "react-router-dom"; import { NavItem, NavLink } from "shards-react"; const SidebarNavItem = ({ item }) => ( <NavItem> <NavLink tag={RouteNavLink} to={item.to}> {item.htmlBefore && ( <div className="d-inline-block item-icon-wrapper" dangerouslySetInnerHTML={{ __html: item.htmlBefore }} /> )} {item.title && <span>{item.title}</span>} {item.htmlAfter && ( <div className="d-inline-block item-icon-wrapper" dangerouslySetInnerHTML={{ __html: item.htmlAfter }} /> )} </NavLink> </NavItem> ); SidebarNavItem.propTypes = { /** * The item object. */ item: PropTypes.object }; export default SidebarNavItem; I've already googled this up a lot, but all related errors I've found were caused by some components which are not part of my code. |
newPlot() function is not working with DOM element in Plotly.js as running from typescript file Posted: 06 Apr 2021 08:45 AM PDT I have a typescript project. I want to draw a histogram for an array of numbers. But it is throwing me an error when I am trying to draw it on a new window and a DOM element. public showHistogram(arrOfValues: number[]){ arrOfValues = [1,2,3,4,5,4,1,2,3,6,5,11]; let trace = [{ x: arrOfValues, type: 'histogram' as Plotly.PlotType, }]; var myWindow = window.open("", "MsgWindow", "width=1000,height=1000"); myWindow.document.write("<div id='histo'><p>Histogram!!!</p></div>"); var element = document.getElementById('histo'); //if (element != null){Plotly.newPlot('histo', trace)}; Plotly.newPlot(element,trace); return 1; } |
Running ray serve in a docker container in foreground, not daemon mode Posted: 06 Apr 2021 08:46 AM PDT I'm running Ray Serve to host a HTTP API of a ray remote function. Is there a better way than below to run Ray Serve in foreground (i.e not daemon mode). Code is taken pretty straight from ray serve example: import os import time import ray.serve ray.serve.init(blocking=True, http_host="0.0.0.0", ray_init_kwargs={ 'webui_host': '0.0.0.0', 'redis_password': os.getenv('RAY_REDIS_PASSWORD'), }) ray.serve.create_endpoint("my_endpoint", "/echo") def echo_v1(flask_request, response="hello from python!"): return "1" ray.serve.create_backend(echo_v1, "echo:v1") ray.serve.link("my_endpoint", "echo:v1") # Make sure the Docker container doesn't exit while True: time.sleep(2) Without the last part: # Make sure the Docker container doesn't exit while True: time.sleep(2) The Docker container will immediately exit. |
Angular Template: How to bind RXJS Observable and read its properties? Posted: 06 Apr 2021 08:45 AM PDT I have created this interface: interface IGame { name: string; description: string; } I'm using it as an Observable and passing it as Input to the Component : @Input() public game: Observable<IGame>; I can see its value printed using the JSON pipe: <h3>{{game | json}}</h3> When binding to a specific property, nothing is displayed (just an empty string): <h3>{{game.name}}</h3> <h3>{{game.description}}</h3> |
Initialize array of primitives Posted: 06 Apr 2021 08:46 AM PDT I am wondering, What's exactly the difference between these two ways of initializing an array of primitives: int[] arr1 = new int[]{3,2,5,4,1}; int[] arr2 = {3,2,5,4,1}; and which one is preferred ? |
How to change revision format in Google Code? Posted: 06 Apr 2021 08:46 AM PDT I'm REALLY new to DVCS and am trying out Mercurial with Google Code as I'd like to share some extensions that I recently wrote for Google Chrome. I notice that in Google Code, most projects seem to refer to changesets via sequential numbers (eg. 1, 2, 3, etc. -- (see screenshot #1 below)). My test project (screenshot #2), however, uses the hex values and I don't see anything in project settings to change this. How do I get it to display using the aforementioned linear format? Also, being new to social coding, it seems that everywhere else on the internet, your email address is a private thing but these DVC systems seem to want your email to associate with commits (and Google, github, etc. seem intent on displaying them). Is there some sort of etiquette here? It seems that most people on Google Code edit their config file to only show the username with no real name or email information for associated commits. |
No comments:
Post a Comment