instruction
stringlengths
0
30k
I have the following chart with 1 point: [![enter image description here][1]][1] Is there a way to draw a line from this point or convert the point to a line like the following screenshots? [![enter image description here][2]][2] or [![enter image description here][3]][3] [1]: https://i.stack.imgur.com/kmOAx.png [2]: https://i.stack.imgur.com/aM3Dl.jpg [3]: https://i.stack.imgur.com/2bv4s.jpg A fiddle to test: https://jsfiddle.net/ak8xcd7s/ HTML: <script src="https://code.highcharts.com/highcharts.js"></script> <div id="container"></div> JS: const chart = Highcharts.chart('container', { yAxis: { min: 0, max: 100 }, xAxis: { categories: ['02-2024'] }, series: [{ data: [20], pointPlacement: 'on' }], });
Highchart draw line if there is one point
|javascript|highcharts|
In my case, I have this entry in `tsconfig.json` which only has `"./src/types/global.d.ts"`: { ... "files": [ "./src/types/global.d.ts" ] ... } **Solution # 1** You can delete the whole `files` entry. **Solution # 2** Add `include` in your `tsconfig.json` which has the folder which you want `tsc` to build: { "files": [ ... ], "include": [ "./src/**.*.ts" ], } I have my `server.ts` in the `src` directory. I run the following command `npm run build` (which is just `tsc` in `package.json`), and the build file is now successfully created.
When I try to fit CatBoostClassifier on GPU with pandas dataframe with embeddings, I get this error: CatBoostError: Attempt to call single feature writer on packed feature writer The data type for embedding in the column is object. `Catboost version==1.2.2.` When I remove the embedding column from the training, everything works fine, so it's definitely about the embeddings. I tried to store it as a list, as an ndarray, as a tensor. It doesn't affect anything. I prescribe the embedding_features parameter. \ Class imbalance or the existance of eval_set also doesn't affect anything. Found out that `task_type='GPU'` is causing this error. Even if you try some simple code from documentation usage examples, but with `task_type='GPU'`: ```from catboost import CatBoostClassifier cat_features = [3] embedding_features=[0, 1] train_data = [ [[0.1, 0.12, 0.33], [1.0, 0.7], 2, "male"], [[0.0, 0.8, 0.2], [1.1, 0.2], 1, "female"], [[0.2, 0.31, 0.1], [0.3, 0.11], 2, "female"], [[0.01, 0.2, 0.9], [0.62, 0.12], 1, "male"] ] train_labels = [1, 0, 0, 1] eval_data = [ [[0.2, 0.1, 0.3], [1.2, 0.3], 1, "female"], [[0.33, 0.22, 0.4], [0.98, 0.5], 2, "female"], [[0.78, 0.29, 0.67], [0.76, 0.34], 2, "male"], ] model = CatBoostClassifier(iterations=2, learning_rate=1, depth=2, task_type='GPU') model.fit(train_data, train_labels, cat_features=cat_features, embedding_features=embedding_features) preds_class = model.predict(eval_data) ``` The usage of GPU is essential in this case.
Method to add new or update existing item in C# Dictionary
|c#|dictionary|containskey|
null
After this: create directory importDir as C:/dump you should have also ran grant read, write on directory importdir to import Otherwise, `import` user won't be able to access any file in that directory. If it (`import` user) won't *write* anything there, then `read` privilege is enough. (BTW, I wouldn't name user `import`; although allowed, it causes confusion as it looks as the `import` database utility.) As of (the last) error you got: should've probably been impdp import/123@PDB1 directory=importDir ... ---- just PDB1, not XEPDB1
I use NUCLEO-F042K6 board to generate a PWM signal. I use Timer2 for that purpose. Timer2 has 4 channels, but according to *STM32F042x4 Datasheet* CH1 cannot be redirected to physical pin. [![Picture 1: Timer 2 schematic - Reference manual][1]][1] [![Picture 2: Alternate functions - Datasheet[2]][2] I still want to utilize Timer 2 and for that purpose I want to use CH2. Unfortunately, I am not able to get a PWM signal on the output. Here is my code: void TIM2_setup(void){ // Enable Timer 2 clock RCC->APB1ENR |= RCC_APB1ENR_TIM2EN; // I/O port A clock enable RCC->AHBENR |= RCC_AHBENR_GPIOAEN; //These bits are written by software to configure the I/O mode. 10: Alternate function mode GPIOA->MODER |= (0x2UL << GPIO_MODER_MODER1_Pos); //Alternate function AF1 selection for port A pin 1 GPIOA->AFR[0] |= (0x2UL << GPIO_AFRL_AFSEL1_Pos); TIM2->CR1 |= TIM_CR1_CMS; TIM2->CR1 |= TIM_CR1_ARPE; // : PWM mode 1 TIM2->CCMR1 |= (0x6UL << TIM_CCMR1_OC2M_Pos); TIM2->CCMR1 |= TIM_CCMR1_OC2PE; TIM2->CCER |= TIM_CCER_CC2E; TIM2->ARR = 8; TIM2->CCR2 = 6; TIM2->PSC = 0; TIM2->CNT = 0; TIM2->CR1 |= TIM_CR1_CEN; } I should mention that I configured Timer 3 with the (almost) same values, but using Channel 1 and it worked. I assume that the error lies in the registers configuration. [1]: https://i.stack.imgur.com/o4zpA.png [2]: https://i.stack.imgur.com/YKTxE.png
Configuring timer channel as output
|stm32|cpu-registers|pwm|
Both your implementations use a stack. The first uses the callstack, while the other uses an explicit stack. There are several differences that impact performance: 1. The call stack is managed implicitly, using compiled code (CPython), which gives an advantage over a stack that must be managed with Python code (`extend`, `pop`) 2. The second implementation does not translate the recursive pattern 1-to-1. It populates the stack in *advance* for what needs to be visited after the first child's subtree has been visited, meaning the stack footprint could be larger than in the recursive version. Besides the overhead of the `reversed` iterator, we need to take into account that memory allocation also costs time. We cannot do much about the first point, so it is not expected to do better with a stack-based iterative implementation. Still, to tackle the second point, we could try to write an iterative version that more closely mimics the recursive version: ``` def itr_dfs2(graph, start): visited = set() stack = deque() current = iter([start]) try: while True: for node in current: if node not in visited: visited.add(node) stack.append(current) current = iter(graph[node]) break else: current = stack.pop() except IndexError: pass ``` Here the stack consists of iterators, not nodes. This more closely resembles the recursive implementation, where the state of the `for` loop iterations are part of the stack frame, and these loops get resumed one a recursive call comes back to it. To time your code it is better to make use of `timeit` and take the minimum of several measurements (using `timeit.repeat`) so to exclude a bit the effect of other load on the machine it runs on. So I changed the time measuring code to this: ``` import timeit n = 10000 r = 5 t1 = min(timeit.repeat(lambda: rec_dfs(graph, 'A'), repeat=r, number=n)) t2 = min(timeit.repeat(lambda: itr_dfs(graph, 'A'), repeat=r, number=n)) t3 = min(timeit.repeat(lambda: itr_dfs2(graph, 'A'), repeat=r, number=n)) print(t1) print(t2) print(t3) ``` The results I got showed that `t3` was often (but not always) somewhere between `t1` and `t2`.
If you use `persistCredentials: true` for `checkout` task, the token lifespan in whole pipeline is `1hour`. If you `don't` want to use github token to push the code, as you mentioned you can separate out the git push into another job. Checked on my side, you cannot put the new job in same pipeline, you can publish the repo content as an artifact, and use `pipeline resource` trigger in a new pipeline, download the artifact and push to github repo.
Title could be worded better, but essentially I am trying to use open cv in Rust and I found the `opencv` crate Per the example from the github page I tried this to display camera feed ``` use opencv::{highgui, prelude::*, videoio, Result}; fn main() -> Result<()> { let window = "video capture"; highgui::named_window(window, highgui::WINDOW_AUTOSIZE)?; let mut cam = videoio::VideoCapture::new(0, videoio::CAP_ANY)?; // 0 is the default camera let opened = videoio::VideoCapture::is_opened(&cam)?; if !opened { panic!("Unable to open default camera!"); } loop { let mut frame = Mat::default(); cam.read(&mut frame)?; if frame.size()?.width > 0 { highgui::imshow(window, &frame)?; } let key = highgui::wait_key(10)?; if key > 0 && key != 255 { break; } } Ok(()) } ``` It works, but it is extremely slow, feels very laggy This is the comparison Python code ``` import cv2 vid = cv2.VideoCapture(0) while True: ret, frame = vid.read() cv2.imshow('window', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break vid.release() cv2.destroyAllWindows() ``` Python version has no lag what so ever Is the camera feed being slow just something I overlooked or is it just simply the way things currently are? My scenario is that I need to take pictures, convert them into HSV and do some processing By doing this in Rust I was hoping to speed up both the picture taking and processing part
Rust opencv crate has very severe camera lag
|python|opencv|rust|rust-cargo|
I'm currently working on a project where I'm able to generate a sitemap successfully. I've created several sitemaps, and one of them is named "videos". After some research, I discovered that Google recommends using a dedicated sitemap for videos. Here's an example of the structure recommended by Google for a video sitemap: ```` <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"> <url> <loc>https://www.example.com/videos/some_video_landing_page.html</loc> <video:video> <video:thumbnail_loc>https://www.example.com/thumbs/123.jpg</video:thumbnail_loc> <video:title>Lizzi is painting the wall</video:title> <video:description> Gary is watching the paint dry on the wall Lizzi painted. </video:description> <video:player_loc> https://player.vimeo.com/video/987654321 </video:player_loc> </video:video> </url> </urlset> ````` After many hours of research, I couldn't find any documentation regarding generating a video sitemap with Next.js that allows customizing the tags. Currently, my code looks like this: ```` if (id === "videos") { if (Array.isArray(video)) { return video.map((video) => ({ url: `${baseUrl}/tv/${video.id}/${helpers.formatTextUrl(video.title)}`, hello: new Date().toISOString(), changeFrequency: "daily", priority: 0.5, })); } } ````` The resulting output looks like this: ````` <url> <loc>http://51.89.219.222:3001/tv/68/070324-le-journal-de-maritima-tv</loc> <changefreq>daily</changefreq> <priority>0.5</priority> </url> ````
I'm a beginner in creating browser plug-ins. Could some kind soul help me with the best way to transfer data between browser tabs? I would like to transfer data from a script running on an inactive tab in real time and use it to control the operation of the page on the active tab. I will be grateful for any advice that will bring me closer to understanding the topic. I'm trying to use the Web Audio API to analyze the sound played in a video element on an inactive tab and send it in real time to the active tab using a plugin.
Transferring data between cards
|web-audio-api|browser-tab|chrome-plugins|
null
Cut out some parts but this is how i'm trying to save it I would really want to be able to use the same file name and resave over the map_file_path which I have defined already. It works the first time but any subsequent times when making requests, it takes me back to the original map that I created.. ``` @app.route("/", methods=['GET', 'POST']) def landing_page(): if request.method == 'POST': address = request.form.get('address', '') print(address) county_name, lat, lng = geocode_address(address) if not county_name: return "County geocoding failed, please try again. if counties_data: folium_map = folium.Map(location=[lat, lng], zoom_start=13) # Add GeoJSON layers for counties for county_data in counties_data: GEOID, county_name, geometry_wkt, crime_percentile = county_data if geometry_wkt: geojson = wkt_to_geojson(geometry_wkt) folium.GeoJson( geojson, name=county_name, style_function=lambda feature, crime_percentile=crime_percentile: { 'fillColor': color_scale(crime_percentile), 'color': 'rgba(0, 0, 0, 0)', 'weight': 1, 'fillOpacity': 0.3 }, ).add_to(folium_map) # add a marker for the provided address folium.Marker([lat, lng], popup=f'<b>{address}</b>').add_to(folium_map) else: return f"No matching county found in the database for '{county_name}'." folium_map.save(map_file_path) return redirect(url_for('show_map')) return render_template('landing_page.html') @app.route("/map") def show_map(): return render_template('map_view.html') if __name__ == "__main__": app.run() ```
Generating maps with folium/flask only works the first time, subsequent requests return the same map
|javascript|python|folium|
null
![enter image description here](https://i.stack.imgur.com/NgfLZ.jpg) In the above graph as it has mentioned to break the ties alphabetically so in depth first search it goes from p to q ,q to r ,r to w,and from w whether it goes to z or it goes to v Iam confused here ,also can any one help me what will be the answer with bfs.
|depth-first-search|breadth-first-search|
You can use the sorted function along with a lambda function as the key to achieve this. Here's an example of how you can sort the dictionary by values in ascending order: average = {'ali': 7.83, 'mahdi': 13.4, 'hadi': 16.2, 'hasan': 3.57} sorted_average = dict(sorted(average.items(), key=lambda item: item[1])) print(sorted_average) This will output: {'hasan': 3.57, 'ali': 7.83, 'mahdi': 13.4, 'hadi': 16.2} Here, sorted(average.items(), key=lambda item: item[1]) sorts the dictionary items based on their values (item[1]), and dict() is used to convert the sorted items back into a dictionary.
"root element" is not really a thing here. The browser will see the component deeply embedded in the layout and page. You can make your own root: ```html <div class="root"> <div class="foo"> <div>Hello</div> <div>World</div> </div> <span class="foo2"> Second root element </span> </div> ``` and then apply a style to the 'root level' elements with ```css .root > * { margin: 1em; ... } ``` The [child combinator (>)][1] makes that it only applies to the direct children of a .root element. With the descendant combinator (just a space) the style aplies to all descendants. [1]: https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator
On Angular 16 with Material 16, if you have background/foreground setup as the following: ```sass @use '@angular/material' as mat; @use "sass:map"; // ... // Background for dark theme. $custom-dark-theme-background: ( status-bar: black, app-bar: map.get(mat.$grey-palette, 900), background: #28364a, hover: rgba(white, 0.04), card: #415267, dialog: map.get(mat.$grey-palette, 800), disabled-button: rgba(white, 0.12), raised-button: map.get(mat.$grey-palette, 800), focused-button: $light-focused, selected-button: map.get(mat.$grey-palette, 900), selected-disabled-button: map.get(mat.$grey-palette, 800), disabled-button-toggle: black, unselected-chip: map.get(mat.$grey-palette, 700), disabled-list-option: #28364a, tooltip: #616161, ); // Foreground for dark theme. $custom-dark-theme-foreground: ( base: white, divider: $light-dividers, dividers: $light-dividers, disabled: $light-disabled-text, disabled-button: rgba(white, 0.3), disabled-text: $light-disabled-text, elevation: black, hint-text: $light-disabled-text, secondary-text: $light-secondary-text, icon: white, icons: white, text: white, slider-min: white, slider-off: rgba(white, 0.3), slider-off-active: rgba(white, 0.3), ); ``` Define the dark theme: ```sass $custom-dark-theme: mat.define-dark-theme(( color: ( primary: $custom-dark-primary, accent: $custom-dark-accent, warn: $custom-dark-warn ) )); ``` > Adding `@debug $custom-dark-theme;` to the scss file after the above is a good way to see what color options can be passed in the first block of code above. Then manually set the background and foreground. The non-`color` versions appear to be the ones that are actively used but I'm setting both to match the 'new' `color` theme definition style. ```sass $custom-dark-theme: map.set($custom-dark-theme, 'color', 'background', $custom-dark-theme-background); $custom-dark-theme: map.set($custom-dark-theme, 'background', $custom-dark-theme-background); $custom-dark-theme: map.set($custom-dark-theme, 'color', 'foreground', $custom-dark-theme-foreground); $custom-dark-theme: map.set($custom-dark-theme, 'foreground', $custom-dark-theme-foreground); ```
In Usual arithmetic conversions, the results of unsigned integer and signed integer operations differ on different compilers
|c++|gcc|visual-c++|clang|mingw|
null
I'm trying to animate photos with the '.project-img' class under 'first dog' and 'second dog' in the same way as the first photo. However, my code, which uses forEach to assign addEventListener to these elements, doesn't seem to be working. Can someone please help me understand what might be causing the issue or provide insights on how to achieve the After identifying why this code isn't working, I noticed that the perspective is too much pushed towards the top of the picture. How can this be fixed <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> //ANIMATING THE MAIN IMAGE ON THE START PAGE let myPanel = document.getElementById("panel"); let subpanel = document.getElementById("panel-container"); const projectPanel = document.querySelectorAll("#panel-project"); // const projectSubpanel = document.querySelector("#project-img"); let mouseX, mouseY; let transformAmount = 3; function transformPanel(panel, subpanel, mouseEvent) { mouseX = mouseEvent.pageX; mouseY = mouseEvent.pageY; const centerX = panel.offsetLeft + panel.clientWidth / 2; const centerY = panel.offsetTop + panel.clientHeight / 2; const percentX = (mouseX - centerX) / (panel.clientWidth / 2); const percentY = -((mouseY - centerY) / (panel.clientHeight / 2)); subpanel.style.transform = "perspective(400px) rotateY(" + percentX * transformAmount + "deg) rotateX(" + percentY * transformAmount + "deg)"; } function handleMouseEnter(panel, subpanel) { setTimeout(() => { subpanel.style.transition = ""; }, 100); subpanel.style.transition = "transform 0.1s"; } function handleMouseLeave(panel, subpanel) { subpanel.style.transition = "transform 0.1s"; setTimeout(() => { subpanel.style.transition = ""; }, 100); subpanel.style.transform = "perspective(400px) rotateY(0deg) rotateX(0deg)"; } myPanel.addEventListener("mousemove", (event) => transformPanel(myPanel, subpanel, event) ); myPanel.addEventListener("mouseenter", () => handleMouseEnter(myPanel, subpanel) ); myPanel.addEventListener("mouseleave", () => handleMouseLeave(myPanel, subpanel) ); projectPanel.forEach((el) => { const projectSubpanel = el.querySelector(".project-img"); el.addEventListener("mousemove", (event) => transformPanel(el, projectSubpanel, event) ); el.addEventListener("mouseenter", () => handleMouseEnter(el, projectSubpanel) ); el.addEventListener("mouseleave", () => handleMouseLeave(el, projectSubpanel) ); }); <!-- language: lang-css --> * { margin: 0; padding: 0; box-sizing: border-box; } :root { /* rgba(116, 116, 116) */ --gray-color: #ededed; } body { font-family: 'Raleway', sans-serif; } /* //////////////////LOADER///////////////////// */ .loader { position: absolute; width: 100%; height: 100vh; overflow: hidden; z-index: 99; } .loader-box { display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%; height: 100vh; font-size: 20rem; color: transparent; -webkit-text-stroke: 3px #cbcbcb; } .loader-box.first { position: absolute; top: 0; left: 0; background-color: var(--gray-color); z-index: 2; } .loader-box.second { position: absolute; top: 0; left: 0; background-color: #b8b8b8; z-index: 1; } /* //////////////////NAV///////////////////// */ nav { position: absolute; left: 50%; transform: translateX(-50%); height: 100px; width: 90%; display: flex; align-items: center; padding-block: 10px; z-index: 2; background-color: #fff; overflow: hidden; } nav a { padding: 5px 20px; text-decoration: none; color: rgb(62, 62, 62); } .name-logo { margin-right: auto; text-transform: uppercase; font-size: 1.8rem; color: rgb(116, 116, 116); font-weight: 500; } .menu { display: flex; list-style: none; font-size: 1.1rem; } /* //////////////////Start Page///////////////////// */ .start-page { /* background-color: red; */ overflow: hidden; height: 100vh; display: flex; justify-content: space-around; align-items: center; } .start-image { width: 50%; height: 100%; } .start-page #panel { display: flex; justify-content: center; align-items: center; filter: grayscale(60%) } .start-text { display: flex; flex-direction: column; justify-content: center; align-items: center; width: 50%; height: 100%; } .start-text p, .start-title, .image { background-color: #fff; z-index: 3; } .start-text p { font-size: 1.3rem; margin-right: 100px; } .start-title { text-transform: uppercase; font-size: 5rem; color: transparent; -webkit-text-stroke: 2px black; } .start-title span { color: transparent; -webkit-text-stroke: 3px black; } /* PARALAX */ #panel, #panel-container { width: 500px; height: 650px; } #panel-container { display: flex; justify-content: center; align-items: center; position: relative; background: url("https://picsum.photos/id/237/200/300") center top; background-size: cover; background-position: 50% 50%; transform: perspective(400px) rotateX(0deg) rotateY(0deg); transform-style: preserve-3d; /* box-shadow: 1.5rem 2.5rem 5rem 0.7rem rgba(0, 0, 0, 0.13); */ } .panel-content { color: black; text-align: center; padding: 20px; transform: translateZ(80px) scale(0.8); transform-style: preserve-3d; overflow-wrap: break-word; } /* LINE */ .decoration-line { position: absolute; top: 0; left: 50%; height: 300vh; width: 1px; background-color: black; z-index: -1; } .decoration-line.one { left: 10%; } .decoration-line.three { left: 90%; } /* MY WORK */ .my-work { width: 100%; } .my-work h1 { font-size: 6rem; width: 60%; margin: 0 auto 100px auto; text-transform: uppercase; color: transparent; -webkit-text-stroke: 3px black; background-color: #fff; text-align: center; z-index: 3; } .projects { position: relative; width: 78%; left: 11%; } .project { display: flex; justify-content: space-evenly; align-items: center; width: 100%; margin-bottom: 100px; } .panel-project { min-width: 550px; height: 300px; } .project-img { display: flex; justify-content: center; align-items: center; position: relative; transform: perspective(400px) rotateX(0deg) rotateY(0deg); transform-style: preserve-3d; min-width: 550px; height: 300px; background-size: cover; background-position: center; border: 1px solid black; border-radius: 10px; filter: grayscale(60%) } .project-desription { width: 50%; text-align: center; background-color: #fff; padding: 0 50px; } .project-desription h2 { font-size: 2.5rem; -webkit-text-stroke: 1px black; color: transparent; margin-bottom: 30px; } .project-desription p { line-height: 1.5rem; } .reverse { flex-direction: row-reverse; } #komornik { background-image: url("https://picsum.photos/id/237/200/300"); } #hulk-factory { background-image: url("https://picsum.photos/id/237/200/300"); } @media only screen and (max-width:1200px) { /* LOADER */ .loader-box { font-size: 15rem; } /* START PAGE */ .start-text p { font-size: 1rem; } .start-title { font-size: 4rem; } #panel-container { width: 380px; } /* MY WORK */ .project-img { min-width: 400px; height: 200px; } .project-desription p { line-height: 1.2rem; } } @media only screen and (max-width:992px) { /* MY WORK */ .my-work h1 { font-size: 4rem; } .project { flex-direction: column; } .project-desription { width: 100%; text-align: center; background-color: #fff; margin-top: 25px; padding: 0 50px; } .project-desription h2 { font-size: 2.5rem; -webkit-text-stroke: 1px black; color: transparent; margin-bottom: 30px; } .project-desription p { line-height: 1.5rem; } } @media only screen and (max-width:768px) { /* LOADER */ .loader-box { font-size: 10rem; } /* MENU */ .menu { display: none; } nav { align-items: flex-start; width: 100%; transition: .3s; } .name-logo { padding: 15px 0 0 30px; } .menu-active { height: 300px; } .menu-active .menu { position: absolute; top: 30%; display: block; text-align: center; width: 100%; font-size: 1.7rem; } .menu-active li { padding: 15px 0; } .hamburger-menu { position: relative; width: 50px; height: 50px; cursor: pointer; margin-right: 40px; } .hamburger-line, .hamburger-line::before, .hamburger-line::after { content: ""; position: absolute; width: 100%; height: 2px; background-color: black; display: block; } .hamburger-line { top: 50%; left: 0; transform: translateY(-50%); } .hamburger-line::before { top: -12px; } .hamburger-line::after { top: 12px; } /* START PAGE */ .start-page { padding-top: 120px; flex-direction: column; justify-content: center; } .start-image { width: 100%; } .start-text { width: 80%; } .start-title { font-size: 3rem; } #panel { height: 400px; } #panel-container { height: 50vh; width: 100%; top: 50px; } .start-text p, .start-title, .image { background-color: transparent; z-index: 0; } .decoration-line { display: none; } } @media only screen and (max-width:576px) { /* LOADER */ .loader-box { font-size: 7rem; } .name-logo { font-size: 1.3rem; } .start-title { font-size: 2.2rem; } .start-title { -webkit-text-stroke: 1px black; } .start-title span { -webkit-text-stroke: 2px black; } /* MY WORK */ .my-work { width: 100%; } .my-work h1 { margin-top: 50px; font-size: 3.5rem; width: 100%; } .project-desription { padding: 0 0; } } @media only screen and (max-height:800px) { #panel, #panel-container { width: 350px; height: 450px; } .start-text p { font-size: 1rem; } .start-title { font-size: 3.5rem; } /* LOADER */ } <!-- language: lang-html --> <nav> <a class="name-logo" href="#">LOREM IPSUM</a> <div class="hamburger-menu"> <div class="hamburger-line"></div> </div> <ul class="menu "> <li class="menu-li"><a href="">Start</a></li> <li class="menu-li"><a href="">Work</a></li> <li class="menu-li"><a href="">Contact</a></li> </ul> </nav> <main> <div class="decoration-line one"></div> <div class="decoration-line two"></div> <div class="decoration-line three"></div> <div class="start-page"> <div class="image"> <div id="panel"> <div id="panel-container"> <div id="panel-content"></div> </div> </div> </div> <div class="start-text"> <h1 class="start-title">Lorem ipsum dolor sit amet consectetur adipisicing elit. </h1> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe quo distinctio adipisci accusamus libero vel quos, cum, autem dolore laborum quibusdam recusandae odio ex odit aperiam aliquam ipsum enim iure </p> </div> </div> <div class="my-work"> <h1>Lorem ipsum</h1> <div class="projects"> <div class="project"> <a id="panel-project" href="" target="_blank"> <div id="komornik" class="project-img"></div> </a> <div class="project-desription"> <h2>First Dog</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe quo distinctio adipisci accusamus libero vel quos, cum, autem dolore laborum quibusdam recusandae odio ex odit aperiam aliquam ipsum enim iure. Cupiditate fugiat quia, quo possimus a fugit. Deserunt nesciunt placeat quam? Dignissimos ipsa aut atque veritatis aspernatur, quaerat iste et?</p> </div> </div> <div class="project reverse"> <a id="panel-project" href="" target="_blank"> <div id="hulk-factory" class="project-img"></div> </a> <div class="project-desription"> <h2>Second dog</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe quo distinctio adipisci accusamus libero vel quos, cum, autem dolore laborum quibusdam recusandae odio ex odit aperiam aliquam ipsum enim iure. Cupiditate fugiat quia, quo possimus a fugit. Deserunt nesciunt placeat quam? Dignissimos ipsa aut atque veritatis aspernatur, quaerat iste et?</p> </div> </div> </div> </main> <!-- end snippet --> ```
You can use formulas like these: In `A14` :`=INDEX(T(+$A$4:$A$10),MATCH(0,INDEX(COUNTIF(A$13:A13,$A$4:$A$10),),0))` In `B14` :`=SUMIF($A$4:$A$10,A14,$B$4:$B$10)-SUMIF($A$4:$A$10,A14,$C$4:$C$10)` As a supplement, alternative formulas to B14 can also be given. =SUMPRODUCT({1;-1},SUMIF($A$4:$A$10,$A14,INDIRECT({"$B$4:$B$10";"$C$4:$C$10"}))) =SUMPRODUCT({1;-1},SUMIF($A$4:$A$10,$A14,OFFSET($B$4:$B$10,,{0;1}))) [![Customers][1]][1] [1]: https://i.stack.imgur.com/22ADx.png
I believe this will work in `2010`: B1: =IF(A1="Name","Group",IF(A2="Name","", INDEX($A$1:A1,LOOKUP(2,1/($A$1:A1="Name"),ROW($A$1:A1))-1))) and fill down. [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/vNNmx.png
It should be possible to handle full line reading with keys suppression by taking advantage of [ReadKey(bool intercept)][1] with some custom solution like: public static string? ReadLine(bool intercept) { if (!intercept) { return Console.ReadLine(); } StringBuilder sb = new(); int position = 0; ConsoleKeyInfo c; do { c = Console.ReadKey(true); if (!char.IsControl(c.KeyChar)) { sb.Insert(position++, c.KeyChar); } else { switch (c.Key) { case ConsoleKey.Delete: if (position < sb.Length) sb.Remove(position, 1); break; case ConsoleKey.Backspace: if (position > 0) sb.Remove(--position, 1); break; case ConsoleKey.LeftArrow: position = Math.Max(position - 1, 0); break; case ConsoleKey.RightArrow: position = Math.Min(position + 1, sb.Length); break; case ConsoleKey.End: position = sb.Length; break; case ConsoleKey.Home: position = 0; break; default: if (c.KeyChar == 26) // Ctrl+Z { Console.WriteLine(); return null; } break; } } } while (c.Key != ConsoleKey.Enter); Console.WriteLine(); return sb.ToString(); } static void Main(string[] args) { Console.Write("Insert something: "); var input = ReadLine(true); Console.WriteLine($"You typed: {input}"); } [1]: https://learn.microsoft.com/en-us/dotnet/api/system.console.readkey?view=net-8.0#system-console-readkey(system-boolean)
For starters the typedef name `new` is not good. It will be much better for example to use typedef name `Node` typedef struct Node Node; struct Node { Node *prev; Node *next; int data; }; you should decide what to do if the specified index is greater than the current number of nodes in the list: whether to append a new node or to report an error. As for your code then it can not run fine. For example if the specified index is equal to 0 then this code snippet if(index==0) { return insert(head,0,9); } invokes an infinite recursive call of the function itself. Also it is unclear why the third argument is the integer constant 9. Also the function returns nothing if the specified index is not equal to 0. And this statement in main new * head=(new *)malloc(sizeof(new)); does not make sense. For example if the user will not call the function `create` then calls of the function `insert` will invoke undefined behavior. Initially a list should be empty. That is in main you should write new *head = NULL; I would declare and define the function `insert` the following way. int insert( Node **head, size_t index, int data ) { if (index != 0) { while ( head != NULL && --index != 0 ) { head = &( *head )->next; } } int success = index == 0; if (success) { Node *node = malloc( sizeof( *node ) ); success = node != NULL; if (success) { node->data = data; if (*head == NULL) { node->prev = NULL; node->next = NULL; *head = node; } else { node->prev = *head; node->next = ( *head )->next; ( *head )->next = node; } } } return success; } The function returns `1` if a node in the given position was inserted in the list or `0` if the specified index is out of the acceptable range `[0, number of existent nodes]` or a memory for a new node was not allocated. Instead of the return type `int` you could introduce an enumeration that will classify possible errors or success. Here is a demonstration program. #include <stdio.h> #include <stdlib.h> typedef struct Node { struct Node *prev; struct Node *next; int data; } Node; int insert( Node **head, size_t index, int data ) { if (index != 0) { while ( head != NULL && --index != 0 ) { head = &( *head )->next; } } int success = index == 0; if (success) { Node *node = malloc( sizeof( *node ) ); success = node != NULL; if (success) { node->data = data; if (*head == NULL) { node->prev = NULL; node->next = NULL; *head = node; } else { node->prev = *head; node->next = ( *head )->next; ( *head )->next = node; } } } return success; } FILE *display( const Node *head, FILE *fp ) { for (; head != NULL; head = head->next) { fprintf( fp, "%d -> ", head->data ); } fputs( "null", fp ); return fp; } void clear( Node **head ) { while (*head) { Node *tmp = *head; *head = ( *head )->next; free( tmp ); } } int main( void ) { Node *head = NULL; int a[] = { 1, 2, 3, 6, 7 }; const size_t N = sizeof( a ) / sizeof( *a ); int success = 1; for (size_t i = 0; success && i < N; i++) { success = insert( &head, i, a[i] ); } fputc( '\n', display( head, stdout ) ); clear( &head ); fputc( '\n', display( head, stdout ) ); } The program output is 1 -> 2 -> 3 -> 6 -> 7 -> null null Try to write the function `create` yourself. It should be declared like size_t create( Node **head, const int a[], size_t n ); The function returns the actual number of added elements of an array to the list. Pay attention to that it would be reasonsable to introduce one more structure like for example struct DoubleLinkedList { struct Node *head; struct Node *tail; size_t size; }; And define functions that will deal with an object of this structure type.
I get `Stack Level Too Deep Error ` when i call vendor.account_owner in the `index.html.erb` the vendor migration file looks like this ``` class CreateVendors < ActiveRecord::Migration[7.0] def change create_table :vendors, id: :uuid do |t| t.string :name t.text :description t.string :website t.references :account_owner, foreign_key: { to_table: :users }, type: :uuid t.jsonb :data_classification, default: '{}', null: false t.integer :auth_type, default: 0 t.integer :risk, default: 1 t.datetime :engagement_date t.datetime :last_review_date t.boolean :is_active, default: true t.timestamps end end end ``` the Vendor model looks like this ``` class Vendor < ApplicationRecord store_accessor :data_classification, :employee_data, :corporate_data, :customer_data, :personal_data, :healthcare_data, :payments_data enum :auth_type, { Unknown: 0, SSO: 1, Password: 2 } enum :risk, { Low: 0, Medium: 1, High: 2 } belongs_to :account_owner, class_name: 'User', foreign_key: :author_id has_many :documents, as: :documentable def account_owner account_owner.first_name end end ``` while the User model looks like this ``` class User < ApplicationRecord ... has_many :authored_policies, class_name: 'Policy', foreign_key: 'author_id' has_many :created_groups, class_name: 'Group', foreign_key: 'creator_id' has_many :vendors, foreign_key: 'account_owner_id' def full_name first_name + " " + last_name end end ``` I have checked a similar error message on the platform but it doesn't address this particular situation I'll need help as I believe I am probably missing something
Generate a video sitemap for Next.js
|next.js|next.js13|sitemap|google-search|robots.txt|
I'm trying to create a simple RAG using the ```infoslack/mistral-7b-arxiv-paper-chunked``` dataset on Hugging Face. As in https://stackoverflow.com/questions/77671277/valueerror-invalid-pattern-can-only-be-an-entire-path-component, I'm getting ```ValueError: Invalid pattern: '**' can only be an entire path component```. However, none of the solutions in that question work here. The code: from datasets import load_dataset dataset = load_dataset("infoslack/mistral-7b-arxiv-paper-chunked", split="train") The error message in full: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[21], line 3 1 from datasets import load_dataset ----> 3 dataset = load_dataset("infoslack/mistral-7b-arxiv-paper-chunked", split="train") File ~\AppData\Local\anaconda3\Lib\site-packages\datasets\load.py:1773, in load_dataset(path, name, data_dir, data_files, split, cache_dir, features, download_config, download_mode, verification_mode, ignore_verifications, keep_in_memory, save_infos, revision, use_auth_token, task, streaming, num_proc, storage_options, **config_kwargs) 1768 verification_mode = VerificationMode( 1769 (verification_mode or VerificationMode.BASIC_CHECKS) if not save_infos else VerificationMode.ALL_CHECKS 1770 ) 1772 # Create a dataset builder -> 1773 builder_instance = load_dataset_builder( 1774 path=path, 1775 name=name, 1776 data_dir=data_dir, 1777 data_files=data_files, 1778 cache_dir=cache_dir, 1779 features=features, 1780 download_config=download_config, 1781 download_mode=download_mode, 1782 revision=revision, 1783 use_auth_token=use_auth_token, 1784 storage_options=storage_options, 1785 **config_kwargs, 1786 ) 1788 # Return iterable dataset in case of streaming 1789 if streaming: File ~\AppData\Local\anaconda3\Lib\site-packages\datasets\load.py:1502, in load_dataset_builder(path, name, data_dir, data_files, cache_dir, features, download_config, download_mode, revision, use_auth_token, storage_options, **config_kwargs) 1500 download_config = download_config.copy() if download_config else DownloadConfig() 1501 download_config.use_auth_token = use_auth_token -> 1502 dataset_module = dataset_module_factory( 1503 path, 1504 revision=revision, 1505 download_config=download_config, 1506 download_mode=download_mode, 1507 data_dir=data_dir, 1508 data_files=data_files, 1509 ) 1511 # Get dataset builder class from the processing script 1512 builder_cls = import_main_class(dataset_module.module_path) File ~\AppData\Local\anaconda3\Lib\site-packages\datasets\load.py:1219, in dataset_module_factory(path, revision, download_config, download_mode, dynamic_modules_path, data_dir, data_files, **download_kwargs) 1214 if isinstance(e1, FileNotFoundError): 1215 raise FileNotFoundError( 1216 f"Couldn't find a dataset script at {relative_to_absolute_path(combined_path)} or any data file in the same directory. " 1217 f"Couldn't find '{path}' on the Hugging Face Hub either: {type(e1).__name__}: {e1}" 1218 ) from None -> 1219 raise e1 from None 1220 else: 1221 raise FileNotFoundError( 1222 f"Couldn't find a dataset script at {relative_to_absolute_path(combined_path)} or any data file in the same directory." 1223 ) File ~\AppData\Local\anaconda3\Lib\site-packages\datasets\load.py:1203, in dataset_module_factory(path, revision, download_config, download_mode, dynamic_modules_path, data_dir, data_files, **download_kwargs) 1188 return HubDatasetModuleFactoryWithScript( 1189 path, 1190 revision=revision, (...) 1193 dynamic_modules_path=dynamic_modules_path, 1194 ).get_module() 1195 else: 1196 return HubDatasetModuleFactoryWithoutScript( 1197 path, 1198 revision=revision, 1199 data_dir=data_dir, 1200 data_files=data_files, 1201 download_config=download_config, 1202 download_mode=download_mode, -> 1203 ).get_module() 1204 except ( 1205 Exception 1206 ) as e1: # noqa: all the attempts failed, before raising the error we should check if the module is already cached. 1207 try: File ~\AppData\Local\anaconda3\Lib\site-packages\datasets\load.py:769, in HubDatasetModuleFactoryWithoutScript.get_module(self) 759 def get_module(self) -> DatasetModule: 760 hfh_dataset_info = HfApi(config.HF_ENDPOINT).dataset_info( 761 self.name, 762 revision=self.revision, 763 token=self.download_config.use_auth_token, 764 timeout=100.0, 765 ) 766 patterns = ( 767 sanitize_patterns(self.data_files) 768 if self.data_files is not None --> 769 else get_data_patterns_in_dataset_repository(hfh_dataset_info, self.data_dir) 770 ) 771 data_files = DataFilesDict.from_hf_repo( 772 patterns, 773 dataset_info=hfh_dataset_info, 774 base_path=self.data_dir, 775 allowed_extensions=ALL_ALLOWED_EXTENSIONS, 776 ) 777 split_modules = { 778 split: infer_module_for_data_files(data_files_list, use_auth_token=self.download_config.use_auth_token) 779 for split, data_files_list in data_files.items() 780 } File ~\AppData\Local\anaconda3\Lib\site-packages\datasets\data_files.py:662, in get_data_patterns_in_dataset_repository(dataset_info, base_path) 660 resolver = partial(_resolve_single_pattern_in_dataset_repository, dataset_info, base_path=base_path) 661 try: --> 662 return _get_data_files_patterns(resolver) 663 except FileNotFoundError: 664 raise EmptyDatasetError( 665 f"The dataset repository at '{dataset_info.id}' doesn't contain any data files" 666 ) from None File ~\AppData\Local\anaconda3\Lib\site-packages\datasets\data_files.py:223, in _get_data_files_patterns(pattern_resolver) 221 try: 222 for pattern in patterns: --> 223 data_files = pattern_resolver(pattern) 224 if len(data_files) > 0: 225 non_empty_splits.append(split) File ~\AppData\Local\anaconda3\Lib\site-packages\datasets\data_files.py:473, in _resolve_single_pattern_in_dataset_repository(dataset_info, pattern, base_path, allowed_extensions) 471 else: 472 base_path = "/" --> 473 glob_iter = [PurePath(filepath) for filepath in fs.glob(PurePath(pattern).as_posix()) if fs.isfile(filepath)] 474 matched_paths = [ 475 filepath 476 for filepath in glob_iter (...) 483 ) 484 ] # ignore .ipynb and __pycache__, but keep /../ 485 if allowed_extensions is not None: File ~\AppData\Roaming\Python\Python311\site-packages\fsspec\spec.py:606, in AbstractFileSystem.glob(self, path, maxdepth, **kwargs) 602 depth = None 604 allpaths = self.find(root, maxdepth=depth, withdirs=True, detail=True, **kwargs) --> 606 pattern = glob_translate(path + ("/" if ends_with_sep else "")) 607 pattern = re.compile(pattern) 609 out = { 610 p: info 611 for p, info in sorted(allpaths.items()) (...) 618 ) 619 } File ~\AppData\Roaming\Python\Python311\site-packages\fsspec\utils.py:734, in glob_translate(pat) 732 continue 733 elif "**" in part: --> 734 raise ValueError( 735 "Invalid pattern: '**' can only be an entire path component" 736 ) 737 if part: 738 results.extend(_translate(part, f"{not_sep}*", not_sep)) ValueError: Invalid pattern: '**' can only be an entire path component
Another ValueError: Invalid pattern: '**' can only be an entire path component
|python|
WordPress question I have a category C. And this has subcategories A,B,X,Z I want to display how many posts are in the subcategories of C in total. I know that there are 204. But I only ever get 184 displayed. Why is that? Because subcategories A and B are not counted. Why is that? Nobody knows. Because they start with a letter that comes before C in the alphabet? I've been looking for the error in the code for so long now, but can't find anything that helps. Now I have also made A times TestA and from B a TestB. And then it counts correctly. How can I solve this without renaming the subcategories?? This is my current code (which is counting exactly what it should if I rename the sub cats....) $category_args = [ 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => 0, 'post_status' => 'publish', 'taxonomy' => 'category', 'pad_counts' => true, // Count Sub Cats posts to Cats 'exclude' => [1, 69, 71], // Exclude categories: "Uncategorized", "Authors", and "Editorial Office" ]; $categories = get_categories($category_args); $categories = array_filter($categories, fn($category) => $category->parent === 0); // Don't show subcategories foreach ($categories as $category) { $child_categories = get_categories(['child_of' => $category->term_id, 'hide_empty' => 0]); $post_count = 0; if (!empty($child_categories)) { foreach ($child_categories as $child_category) { $post_count += $child_category->count; } } else { $post_count = $category->count; } if ($post_count > 0) { echo '<li class="styleCheckbox">'; echo '<input type="checkbox" data-select="sectionFilter" id="section_' . $category->term_id . '" value="' . $category->term_id . '">'; echo '<label for="section_' . $category->term_id . '">'; echo '<span class="connector">'; echo '<span class="filter-name">' . $category->name . '</span>'; echo '<span class="filter-counter">' . $post_count . '</span>'; echo '</span>'; echo '</label>'; echo '</li>'; } } Is it a bug or am I stupid?
I have three 1D NumPy Arrays XX, YY, and ZZ. They are organized such that ZZ[i] is the height of a hill at coordinates XX[i], YY[i]. How can I plot this using Python? Edit: The arrays are quite large (each contain about 3e5 data points) Thanks
Safari on iOS has unique behavior when it comes to managing history and caching pages. The best method is to use the `pageshow` event, which is triggered when a page is navigated back to, and `persisted` event which tells if a webpage is loading from a cache or not. ```javascript document.addEventListener("DOMContentLoaded", function() { window.addEventListener("pageshow", function(event) { let page = event.target; if (page.id === "yourPageId") { if (event.persisted) { window.location.reload(); } } }); }); ```
null
I have an ASP.NET 6.0 C# application which is registered in Entra ID, let us say it is called MyApp. In the Azure portal for MyApp, under App registrations, I have used Manage - App roles to define custom roles, Editor and Viewer. Then in Manage - Users and groups I have assigned users and groups to these roles. In the application code I have a GraphServiceClient. With the following code I can get a collection of AppRoleAssignments, where gs is a GraphServiceClient object: var approles = await gs.Me.AppRoleAssignments.Request().GetAsync(); However these AppRoleAssignments are not the custom roles. If the user has a role assigned, there is one AppRoleAssignment that has a ResourceDisplayName of MyApp in the approles collection above, but how can I get the custom roles, Editor or Viewer, assigned to the currently logged in user? I have looked at this sample https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/5-WebApp-AuthZ/5-1-Roles which shows how to set an Authorize attribute using a custom role but I don't want to do that, I want code to list the custom roles in MyApp that are assigned to the current user.
How to get application roles assigned for current logged on user via C# and GraphServiceClient
|c#|asp.net|asp.net-core|msal|entra|
null
I am new to html and css. I tried writing some code for a webpage and it looked good on desktop view but I noticed that in mobile view, the right half of the page is whitespace. To fix this, I have tried to make the parent elements width '100%' and the child element width to 'auto', as you can see from the code below. Would really appreciate if you could link videos that will help me understand the concept needed to fix this!! <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-css --> * { box-sizing: border-box; margin: 0; padding: 0; } li, a, button, input { font-family: "Helvetica", sans-serif; text-decoration: none; font-size: 18px; color: azure; font-weight: 500; } header { display: flex; justify-content: space-between; align-items: center; padding: 20px 7%; background-color: cadetblue; width: 100%; } .logo { cursor: pointer; width: 70px; height: 70px; margin-right: 100px; } .nav { list-style: none; } .nav li { display: inline-block; padding: 0 20px; } .nav li a { transition: all 0.35s ease 0s; } .nav li a:hover { color: greenyellow; } button { background-color: greenyellow; color: azure; transition: all 0.3s ease 0s; padding: 10px 25px; border: none; border-radius: 50px; cursor: pointer; } button:hover { background-color: darkseagreen; opacity: 0.8; } .box { margin-left: 100px; margin-right: 20px; height: 40px; width: auto; padding: 10px 20px; background-color: azure; border-radius: 30px; box-shadow: 0 10px 25px rgba(112, 128, 144, 0.3); color: black; } .box input { width: 0; outline: none; border: none; font-weight: 500; transition: all 0.3s ease 0s; background: transparent; } h1 { color: greenyellow; font-family: Helvetica, Arial, sans-serif; font-size: 150px; text-align: center; margin: 150px auto; width: auto; } p { font-family: Helvetica, Arial, sans-serif; font-size: 40px; text-align: center; margin-bottom: 100px; } main { background-color: blanchedalmond; padding: 100px; width: 100%; } <!-- language: lang-html --> <header> <img class="logo" src="logo.svg" alt="logo"> <nav> <ul class="nav"> <li><a href="#">Home</a></li> <li><a href="#">Services</a></li> <li><a href="#">Project</a></li> </ul> </nav> <input class="box" type="text" placeholder="search"> <a href="#"><button>Search</button></a> </header> <main> <h1>Hello World</h1> <p>Our app will help Road desing engineers to manage traffic. This app will use AI technology to plan roads and traffic lights, so you won't have to wait in traffic. </p> </main> <!-- end snippet -->
I have just exported a teachable machine model in the h5 file format, and i set it up locally in my development environment but i keep getting this error ``` TypeError: Error when deserializing class 'DepthwiseConv2D' using config={'name': 'expanded_conv_depthwise', 'trainable': True, 'dtype': 'float32', 'kernel_size': [3, 3], 'strides': [1, 1], 'padding': 'same', 'data_format': 'channels_last', 'dilation_rate': [1, 1], 'groups': 1, 'activation': 'linear', 'use_bias': False, 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'bias_regularizer': None, 'activity_regularizer': None, 'bias_constraint': None, 'depth_multiplier': 1, 'depthwise_initializer': {'class_name': 'VarianceScaling', 'config': {'scale': 1, 'mode': 'fan_avg', 'distribution': 'uniform', 'seed': None}}, 'depthwise_regularizer': None, 'depthwise_constraint': None}. Exception encountered: Unrecognized keyword arguments passed to DepthwiseConv2D: {'groups': 1} ``` Here is my code: ``` from keras.models import load_model # TensorFlow is required for Keras to work from PIL import Image, ImageOps # Install pillow instead of PIL import numpy as np # Disable scientific notation for clarity np.set_printoptions(suppress=True) # Load the model model = load_model("keras_model.h5", compile=False) # Load the labels class_names = open("labels.txt", "r").readlines() # Create the array of the right shape to feed into the keras model # The 'length' or number of images you can put into the array is # determined by the first position in the shape tuple, in this case 1 data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) # Replace this with the path to your image image = Image.open("jap span.jfif").convert("RGB") # resizing the image to be at least 224x224 and then cropping from the center size = (224, 224) image = ImageOps.fit(image, size, Image.Resampling.LANCZOS) # turn the image into a numpy array image_array = np.asarray(image) # Normalize the image normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1 # Load the image into the array data[0] = normalized_image_array # Predicts the model prediction = model.predict(data) index = np.argmax(prediction) class_name = class_names[index] confidence_score = prediction[0][index] # Print prediction and confidence score print("Class:", class_name[2:], end="") print("Confidence Score:", confidence_score) ``` Expected an output of which class and confidence level but error returned
Trying to export Teachable Machine Model But returning error
|python|tensorflow|
null
I'm deploying a Node.js/MongoDB app to Heroku, and it crashes with the following error: MongooseServerSelectionError: connection <monitor> to 104.155.184.217:27017 closed **Here's the relevant part of my logs:** 2022-07-10T23:36:17.323791+00:00 heroku[web.1]: Process exited with status 1 2022-07-10T23:36:17.574484+00:00 heroku[web.1]: State changed from up to crashed ... 2022-07-10T23:36:51.593762+00:00 app[web.1]: MongooseServerSelectionError: connection <monitor> to 104.155.184.217:27017 closed ... **Code:** **server.js** const express = require('express') const morgan = require('morgan') const cors = require('cors') const connectDB = require('./config/db') const passport = require('passport') const bodyParser = require('body-parser') const routes = require('./routes/index') connectDB() const app = express() if(process.env.NODE_ENV === 'development') { app.use(morgan('dev')) } app.use(cors()) app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.json()) app.use(routes) app.use(passport.initialize()) require('./config/passport')(passport) const PORT = process.env.PORT || 3000 app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)) **package.json:** "dependencies": { "bcrypt": "^5.0.1", "body-parser": "^1.20.0", "connect-mongo": "^4.6.0", "cors": "^2.8.5", "cross-env": "^7.0.3", "express": "^4.18.1", "jwt-simple": "^0.5.6", "mongoose": "^6.4.4", "morgan": "^1.10.0", "nodemon": "^2.0.19", "passport": "^0.6.0", "passport-jwt": "^4.0.0" } **Procfile:** web:node server **Things I've tried:** [![enter image description here][1]][1] If I type `heroku restart` into the command prompt, it works. [![enter image description here][2]][2] And if I type `heroku logs --tail` into the command prompt, it shows me the initial image again; it doesn't work. [1]: https://i.stack.imgur.com/lju2F.png [2]: https://i.stack.imgur.com/3u4Qx.png **Question:** How can I resolve this error and keep my Heroku app running without crashing?
> If a Windows username is created in a xxx@domain.com email syntax... Allow me to correct you there: it isn't "e-mail syntax" - it's (an RFC 822-compliant) _User Principal Name_, or UPN for short. Crucially, _it is not an e-mail address_. <sub>**Nostalgia time!**: Back in the days of Windows 2000 I remember the mood and expectation was that UPNs would _eventually_ be mapped to a valid e-mail address _and_ they'd replace NT's `DOMAIN\USERNAME`-style logins long before Windows Server 2003 came out - well, that never happened, and despite Microsoft _really_ pushing people to use UPNs in the early 2000s I think they realised it wasn't going to go anywhere by the time Windows 7 came out.</sub> > How does `Netplwiz` retrieve and display usernames properly in their email syntax? (_Ghidra speedrun time..._) I noticed that `netplwiz` uses COM to access and call-out into services that would be resolved at runtime and so _it's possible_ that `netplwiz` may be using some hither-unknown COM interface/service to perform some aspects of name translation, so the function list here is not exhaustive. But moving on to what a straightforward static-analysis can tell us: * Looking at the Imports table, ``netplwiz.dll` directly references dozens of Win32 libraries, and from those I saw these imported funcs that can perform name translation (either searching by UPN or login-name and resolving it to a SID, or vice-versa; or translating between them). * [`API-MS-WIN-SECURITY-ACTIVEDIRECTORYCLIENT-L1-1-0.DLL::DsCrackNamesW`][1] * `API-MS-WIN-SECURITY-BASE-L1-1-0.DLL::AllocateAndInitializeSid` * `API-MS-WIN-SECURITY-BASE-L1-1-0.DLL::GetTokenInformation` * [`API-MS-WIN-SECURITY-LSALOOKUP-L2-1-0.DLL::LookupAccountNameW`][2] * `API-MS-WIN-SECURITY-LSALOOKUP-L2-1-0.DLL::LookupAccountSidW` * `API-MS-WIN-SECURITY-SDDL-L1-1-0.DLL::ConvertSidToStringSidW` * `DSROLE.DLL::DsRoleGetPrimaryDomainInformation` * `SAMCLI.DLL::NetLocalGroupEnum` * `SAMCLI.DLL::NetLocalGroupGetMembers` * `SAMCLI.DLL::NetUserGetInfo` * [`SECUR32.DLL::TranslateNameW`][3] ---- There are other parts of Win32 that can do this too, which `netplziwz` doesn't use, like: * [`NetQueryDisplayInformation`][4]. * [`NetUserEnum`][5] * [`GetUserNameExW`][6] > Can that be done for the currently logged in user? Yes. From the command-line, just run `whoami /upn` [1]: https://learn.microsoft.com/en-us/windows/win32/api/ntdsapi/nf-ntdsapi-dscracknamesw [2]: https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-lookupaccountnamew [3]: https://learn.microsoft.com/en-us/windows/win32/api/secext/nf-secext-translatenamew [4]: https://learn.microsoft.com/en-us/windows/win32/api/lmaccess/nf-lmaccess-netquerydisplayinformation [5]: https://learn.microsoft.com/en-us/windows/win32/api/lmaccess/nf-lmaccess-netuserenum [6]: https://learn.microsoft.com/en-us/windows/win32/api/secext/nf-secext-getusernameexw
So I did not find any solutions to my problem that makes use of the `Illuminate\Foundation\Testing\RefreshDatabase::class` I instead opted to use a different trait which caused a slight performance issue but still works. The trait that I used is `Illuminate\Foundation\Testing\DatabaseMigrations::class`
Try to downgrade from 4.4.0 to `4.3.15` or `4.3.8` `id 'com.google.gms.google-services' version '4.3.15' apply false`
My site collects address information through our gravity form. We use the google places API to suggest the address as the user types. However, when Chrome users click the field it overlays their auto-fill options for saved addresses. Most times these addresses come in as "Street number..Street Name" as opposed to the google places API showing city, state, zip after that. This is for a moving company so kind of important to know what city the lead is coming in from. My question is, is there any way to disallow the user's auto-fill box from showing, regardless of their chrome browser settings (autofill on/off)? So if they click the field for the "Address" nothing happens, thus they are forced to start typing and clicking the suggested address once the correct one populates?
Counting posts from a category that has sub categories
|wordpress|
The `-e` option to `bash`'s built-in `echo` is a non-POSIX extension that enables processing of backslashed characters according to the XSI extension to the POSIX standard. POSIX `echo` is supposed to treat `-e` as an ordinary argument, not an option. You can see this behavior using `/bin/echo`, which is POSIX compliant and does not implement the XSI extension. $ /bin/echo -e foo\\nbar -e foo\nbar In `bash` 3.2, the nonstandard extension `-e` can be used to enable the XSI extension: $ /bin/bash -c 'echo -e foo\\nbar' foo bar This can also be enabled using the `xpg_echo` option: % /bin/bash -O xpg_echo -c 'echo foo\\nbar' foo bar Turning POSIX mode on make `echo` POSIX-compliant *and* enables the XSI extension. $ /bin/bash --posix -c 'echo foo\\nbar' foo bar $ /bin/bash --posix -c 'echo -e foo\\nbar' -e foo bar Now let's jump to `bash` 5.2. (I'm assuming there are no significant differences between any of the 4.x versions and 5.2; corrections welcome.) Plain `echo` behaves as in 3.2: no XSI extension and non-compliant with POSIX. `xpg_echo` also works as before: $ bash -c 'echo foo\\nbar' foo\nbar $ bash -c 'echo -e foo\\nbar' foo bar $ bash -O xpg_echo -c 'echo foo\\nbar' foo bar `--posix` behaves a little differently, and in my opinion is buggy. In POSIX mode, `-e` is *still* recognized as enabling backslash procession, rather than as an ordinary word: $ bash --posix -c 'echo -e foo\\nbar' foo bar When `xpg_echo` is enabled, making `-e` unnecessary, *now* it is properly treated as an ordinary argument in POSIX mode: $ bash --posix -O xpg_echo -c 'echo -e foo\\nbar' -e foo bar To avoid these portability issues, use `printf` instead, which historically did not have as many diverging implementations, and is much more portable in practice than `echo`.
I cannot perform actions on my markers. I would like to be able to open a popup when clicked. I cannot use version 3. I am unable to implement GestureDetector and I cannot find a compatible module with version 6. Here is my collection of markers: ``` allMarkers.add( Marker( point: LatLng(poi.lat, poi.longi), height: 12, width: 12, child: ColoredBox(color: Colors.blue[900]!), ) ); ``` And here is my map: ``` FlutterMap( mapController: _mapController, options: const MapOptions( initialCenter: LatLng(46.322749002340636, -0.46578249554813433), initialZoom: 10, ), children: [ TileLayer( urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', userAgentPackageName: 'com.example.app', ), PolylineLayer( polylines: lstPolygone , ), MarkerLayer( markers: allMarkers.take(allMarkers.length).toList() ), ], ); ``` And here are the versions of my libraries: ``` cupertino_icons: ^1.0.2 http: ^1.2.0 flutter_map: ^6.1.0 latlong2: ^0.9.0 geoxml: ^2.6.1 cached_network_image: ^3.3.1 provider: ^6.1.2 path: ^1.8.3 sqflite: ^2.3.2 connectivity_checker: ^1.1.0 flutter_html: ^3.0.0-beta.2 ``` I tried to downgrade the version of flutter_map to access the builder in the marker, but it is incompatible. I tried to create widgets in the child to have a GestureDetector, I tried to add an onTap but nothing works
Manage actions on a marker with flutter_map 6.1.0
|flutter|dart|google-maps-markers|gesturedetector|fluttermap|
null
I am using Flask to try to develop a website for the first time. I finished the log in system for the website and now I making an online course of sort for those who have logged in. I have set up the log in successfully and now I am trying to make a system where one can watch video lectures. while to the lectures works the actual lectures do not play. When clicking a lecture the url changes from http://127.0.0.1:5000/course_page/Analytics to http://127.0.0.1:5000/course_page/Analytics#Lecture_2. But the rest of the page does not change does not even open the lecture. I've set up a Flask route to serve course pages which includes video URLs in the course data. On the frontend, I have a list of lectures that should allow users to click and view the corresponding video. However, the video does not load upon clicking the lecture link. Here are the essential parts of my code related to this issue: ``` @app.route('/course_page/<course_name>') def course_page(course_name): # Logic to check user session and fetch course data # ... course_data = get_course_data(course_name) return render_template('course_page.html', course=course_data) ``` HTML for Lecture List: ``` <!-- Snippet from course_page.html --> <div id="sidebar"> <!-- ... --> <ul id="lecture-list"> {% for lecture in course['lectures'] %} <li> <a href="javascript:void(0);" onclick="loadVideo('{{ lecture['url']|tojson|safe }}')"> {{ lecture['title'] }} </a> </li> {% endfor %} </ul> <!-- ... --> </div> ``` JavaScript Function to Load Video: ``` <script> // Function intended to load video into the main content area function loadVideo(videoUrl) { var mainContent = document.getElementById('main-content'); var fullPath = "{{ url_for('static', filename='') }}" + videoUrl; mainContent.innerHTML = '<video controls><source src="' + fullPath + '" type="video/mp4"></video>'; mainContent.querySelector('video').load(); } </script> ``` Despite this setup, when I click a lecture link, the URL changes as expected, but no video appears in the #main-content area. I'm looking for guidance on how to correctly load and display the video content when a lecture link is clicked. Please let me if you need more information.
Flask Application Not Dynamically Loading Video Content on Lecture Selection
|flask|
null
I want to get the time complexity of this pseudocode: ``` count = 0; for (i = 1; i < n; i *= 2) for (j = 0; j < i; j++) count++; ``` I thought it was log(n)\*log(n), but the answer is log(n). I was told that because i\*2 has nonlinear growth, I can't multiply directly. I am confused why I can't do that: I don't know the rules about when I can multiply when I can't. When I calculate time complexity, I just multiply them when I meet nested loops. How should I calculate it correctly?
Why I can't calculate time complexity by multiplying?
Can I disallow the ability for a user to select/see a Chrome autofill option when using google places API? It's causing incomplete address submissions
|autofill|google-places-autocomplete|
null
I am able to retrieve the value of `app.config` settings in Azure Function app using the below code. ```csharp var test = Properties.Settings.Default.Setting1; ``` ![enter image description here](https://i.imgur.com/9cuyz6S.png) ***My `app.config`:*** ```csharp <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" > <section name="ClassLibrary1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> </sectionGroup> </configSections> <connectionStrings> <add name="ClassLibrary1.Properties.Settings.Setting1" connectionString="Test Value from app.config" /> </connectionStrings> <userSettings> <ClassLibrary1.Properties.Settings> <setting name="Setting2" serializeAs="String"> <value>Sample App setting</value> </setting> </ClassLibrary1.Properties.Settings> </userSettings> </configuration> ``` Thanks @[Peter Morlion](https://blog.submain.com/app-config-basics-best-practices/) for the clear steps. - In `Class library` => `Class1.cs` file, add the below code ```csharp public class Class1 { public string GetAppSettings() { var setval = Properties.Settings.Default.Setting1; return setval; } } ``` - Reference the class library dll in the `Azure Function` App. ![enter image description here](https://i.imgur.com/72GgzaT.png) ***My `Function1.cs`:*** ```csharp [Function("Function1")] public IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req) { Class1 appset = new Class1(); var values = appset.GetAppSettings(); _logger.LogInformation(values); ------- ``` ***Output:*** ![enter image description here](https://i.imgur.com/CTsIXOB.png)
null
null
i would not suggest to store data in json due to usage you need at compile time. so something like this string value = businessMessagesModel.MSG_1.en - will be available at compile time. as a different approach i would suggest: this is example to have class as enum which you can add messages at compilation and dynanicaly pick base on key name... ```C# public sealed class RejectReasons { public static RejectReasons SI { get; } = new RejectReasons("SI", "INVALID SELLER ID"); public static RejectReasons SD { get; } = new RejectReasons("SD", "INVALID SELLER DBA NAME"); public static RejectReasons SM { get; } = new RejectReasons("SM", "INVALID SELLER MCC"); public static RejectReasons SS { get; } = new RejectReasons("SS", "INVALID SELLER STREET ADDRESS 1"); public static RejectReasons SN { get; } = new RejectReasons("SN", "INVALID SELLER CITY NAME"); public static RejectReasons SR { get; } = new RejectReasons("SR", "INVALID SELLER REGION CODE"); public static RejectReasons SP { get; } = new RejectReasons("SP", "INVALID SELLER POSTAL CODE"); public static RejectReasons SC { get; } = new RejectReasons("SC", "INVALID SELLER COUNTRY CODE"); public static RejectReasons SU { get; } = new RejectReasons("SU", "INVALID SELLER CURRENCY CODE"); public static RejectReasons SL { get; } = new RejectReasons("SL", "INVALID SELLER LANGUAGE(Canada)"); public static RejectReasons AX { get; } = new RejectReasons("AX", "AMEX ISSUE.Please contact Premium Partner Servicing for details."); private RejectReasons(string name, string description) { Name = name; Description = description; } public string Name { get; } public string Description { get; } public override string ToString() => Name; public static IEnumerable<string> GetNames() => GetValues().Select(RejectReasons => RejectReasons.Name); public static string GetValue(string name) => GetValues().FirstOrDefault(RejectReasons => RejectReasons.Name == name)?.Description; public static IReadOnlyList<RejectReasons> GetValues() { return typeof(RejectReasons).GetProperties(BindingFlags.Public | BindingFlags.Static) .Select(property => (RejectReasons)property.GetValue(null)) .ToList(); } } ``` usage: ``` RejectReasons.GetValues(); //will return all as List<rejectedReasons> RejectReasons.GetValue("AX").Dump(); // will return text ```
How to fix Heroku "State changed from up to crashed" (Mongoose connection error)
|javascript|node.js|mongodb|mongoose|heroku|
I installed Visual Studio 2022 and created new ASP.NET Core web app project with .NET 8.0 framework, but after creating project, while viewing solution explorer there is no templates of ASP.NET application, I am confused I installed .NET 8.0 and Visual Studio 2022, in Visual Studio I installed 3 workloads - ASP.NET & web development, Azure development, .NET desktop development. 1. I created new project in Visual Studio 2022 by choosing "ASP.NET Core web app (Razor pages)" ![creating project](https://i.stack.imgur.com/bp3ro.png) 2. I gave it a project name, location, [configuration](https://i.stack.imgur.com/UhL5g.png) 3. I chose .NET 8.0 framework and created the project ![enter image description here](https://i.stack.imgur.com/WNIXu.png) 4. This is the result, it says solution 0 projects ![enter image description here](https://i.stack.imgur.com/Dq0cT.png) But the templates, `.sln` and `.csproj` are created in the specified folder, then I right click on solution [enter image description here](https://i.stack.imgur.com/w2MIq.png) and try to add existing `.csproj` file But the final result is this: ![enter image description here](https://i.stack.imgur.com/OPYRh.png)
ASP.NET Core web app not get created in Visual Studio 2022
In the following program: ``` #include <stdio.h> int main() { int c; c = getchar(); putchar(c); } ``` Even if If write many characters in the input and press `enter`, it only prints the first character. However in the following program: ``` #include <stdio.h> int main() { int c; do { c = getchar(); putchar(c); } (while c != EOF); } ``` When I write multiple characters, it prints all of them. My question is the following: Why, when I press enter, doesn't it print only the first character in my input as in the first program and how come the condition in while is evaluated before `putchar(c)` is called?
Why does getchar in C accept many characters in a loop but not outside one
|c|stdio|getchar|
This looks like a genuine bug. I have escalated the issue to Google. To send a report of your own, and get notified of changes, open a spreadsheet and choose **Help > Report a Problem** or **Help > Help Sheets Improve**. If you are on a paid Google Workspace Domain, see [Contact Google Workspace support](https://support.google.com/a/answer/1047213).
To log events on Flutter Web, you firstly need to configure your Facebook Pixel inserting the snippet above `</head>` in `web/index.html`. You can find the snippet following this [guide][1] After that, you can send events to your pixel utilizing dart interoperability. More informations [here][2] import 'dart:developer'; import 'dart:js_interop_unsafe'; import 'dart:js_interop'; @JS() external void fbq(String command, String eventName, JSAny parameters); class Tracking { static void sendEvent( {required String eventName, Map<String, dynamic>? parameters}) { //Meta Pixel try { final args = JSObject(); parameters?.entries.forEach((element) { args[element.key] = element.value; }); fbq('trackCustom', eventName, args); } catch (e) { log(e.toString()); } } } [1]: https://www.facebook.com/business/help/952192354843755 [2]: https://dart.dev/interop/js-interop/usage
I need to replace the function returns by a module. I'm using **CommonJS** with **nodejs 18**. **index.js** ```js const sinon = require("sinon"); const axios = require("axios"); const fs = require("fs"); const fileConverter = require("./file-converter"); async function main() { // Anyway, here is the way I did it for now: sinon.stub(fs.promises, "readFile").withArgs("test").returns("File content"); sinon .stub(axios, "get") .withArgs("/codec-parameters?type=json") .resolves("File decoder"); const result = await fileConverter.fromFilePath("test"); console.log(result); } main(); ``` **file-converter.js** ```js const getCodec = require("./file-converter-codec"); const fs = require("fs"); class FileConverter { #codecs; #filePath; constructor(filePath) { this.#filePath = filePath; } async convert() { const fileContent = await fs.promises.readFile(this.#filePath); const codec = await getCodec("json"); return codec.decode(fileContent); } } async function fromFilePath(filePath) { const fileParsed = new FileConverter(filePath); return await fileParsed.convert(); } module.exports = { fromFilePath, }; ``` **file-converter-codec.js** ```js const axios = require("axios"); class FileConverterCodec { #parameters; constructor(parameters) { this.#parameters = parameters; } decode(data) { return "File has been decoded"; } } module.exports = async (type) => { const parameters = await axios.get(`/codec-parameters?type=${type}`); return new FileConverterCodec(parameters); }; ``` How can I stub the getCodec method that is called from inside of the class FileConverter? As the class FileConverter is not exported, I don't know how to do it. I want to prevent it from calling a REST API dependency Is my reasoning correct if I include Axios directly here and stub it before it gets required from the file-converter-codec.js? I didn't want to stub Axios directly, which is called 2 modules deeper. I prefer to stub a level under the file to be tested, no more! Otherwise, unit testing would require examining very deeply the sparse code in the case of a huge project. Is it correct? If it's correct then how can I stub a module that exports a function directly, like the one in the file-converter-codec.js? [Codesandbox of this example](https://codesandbox.io/p/sandbox/agitated-night-4dt8ll) _Note that I cannot modify the source code of the required module to add a name to it. Otherwise, I would have already done it._
I'm currently working on a project where I'm able to generate a sitemap successfully. I've created several sitemaps, and one of them is named "videos". After some research, I discovered that Google recommends using a dedicated sitemap for videos. Here's an example of the structure recommended by Google for a video sitemap: ```` <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"> <url> <loc>https://www.example.com/videos/some_video_landing_page.html</loc> <video:video> <video:thumbnail_loc>https://www.example.com/thumbs/123.jpg</video:thumbnail_loc> <video:title>Lizzi is painting the wall</video:title> <video:description> Gary is watching the paint dry on the wall Lizzi painted. </video:description> <video:player_loc> https://player.vimeo.com/video/987654321 </video:player_loc> </video:video> </url> </urlset> ````` After many hours of research, I couldn't find any documentation regarding generating a video sitemap with Next.js that allows customizing the tags. Currently, my code looks like this: ```` if (id === "videos") { if (Array.isArray(video)) { return video.map((video) => ({ url: `${baseUrl}/tv/${video.id}/${helpers.formatTextUrl(video.title)}`, hello: new Date().toISOString(), changeFrequency: "daily", priority: 0.5, })); } } ````` The resulting output looks like this: ````` <url> <loc>http://exemple.com/tv/68/070324-le-journal-de-maritima-tv</loc> <changefreq>daily</changefreq> <priority>0.5</priority> </url> ````
Your structure when viewed as a table means for every new message, your adding a new column to the table. (and that's why you have the mess of having to re-generate the class each time). Why not make the Message ID a column like all the other fields? Hence this: [ { "ID": 0, "en": "Something went wrong, please try again later", "ar": "..." }, { "ID": 1, "en": "User created successfully", "ar": "..." }, { "ID": 2, "en": "Phone number already exists", "ar": "..." }, { "ID": 3, "en": "Validation Error, Fix it then try again", "ar": "..." } ] So, now in code you can read/load the above into a list, Say this class: public class Msg { public int id { get; set; } public string en { get; set; } public string ar { get; set; } } And now to load the above, we have this: string sFile = @"c:\test\msg.txt"; string sjson = File.ReadAllText(sFile); msgs = JsonConvert.DeserializeObject<List<Msg>>(sjson); Debug.Print(msgs[0].en); Debug.Print(msgs[1].en); So, you address each message by a number, but you have to lookup, and know that number, so LITTLE advantages by using a column name for the message number. The above is thus not only far more friendly, but allows you to pull such data into a List "of some class" item. This will allow you to make a nice editor for all the messages, and editing, or adding new messages becomes rather simple.
I'm extremely new to Python (a couple of weeks into my self learning journey) and I've hit a wall. The Goal: To have a script that will read the files in the folder the script was run from, dynamically create buttons for any .lnk files it finds, extract the icon from the target .exe file and add it to the button for that link. When clicked, the button will launch the shortcut.lnk file it was pointed to when created. Effectively creating a popup menu of shortcuts in the taskbar for windows. The Problem: I can get it to work without the images, but as soon as I try to add an image to the tk.Button(image) it then only works for the last button it creates. I'm sure its something I'm doing wrong with the way I get the image but I just can't figure out what. Result: ![result](https://i.stack.imgur.com/v0yeZ.png) The above image shows the result, the first two buttons do absolutely nothing when clicked and the third works as expected. If i comment out the part that adds the image to the button, all three buttons work to open their respective links. The Code: ``` import tkinter as tk import os import pyautogui from win32api import GetSystemMetrics from PIL import Image, ImageTk import win32com.client import win32gui import win32ui def execlink(linkpath): # print(linkpath) os.startfile(linkpath) class IconExtractor: def __init__(self): self.photo = None self.root = None # Keep a reference to the Tkinter root window self.label = None # Keep a reference to the Label widget def extract_icon(self, exe_path, ico_path): # Load the executable file icon_handles, num_icons = win32gui.ExtractIconEx(exe_path, 0) # Check if any icons were found if icon_handles: # Select the first icon from the list h_icon = icon_handles[0] # Create a device context hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) # Create a bitmap and draw the icon into it hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, 32, 32) # You may adjust the size (32x32 in this case) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), h_icon) # Save the bitmap as an icon file hbmp.SaveBitmapFile(hdc, ico_path) # Release the icon resources win32gui.DestroyIcon(h_icon) else: print("No icons found in the executable.") def on_closing(self): # This function is called when the user closes the Tkinter window self.root.destroy() def main(self, lnk_path, ico_path): # Explicitly initialize the Tkinter event loop # root = tk.Tk() # root.withdraw() # Hide the root window # lnk_path = r'' # ico_path = r'' # Get the target path from the .lnk file shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut(lnk_path) target_path = shortcut.TargetPath if os.path.exists(target_path): # Extract the icon from the executable self.extract_icon(target_path, ico_path) # Check if the .ico file was generated successfully if os.path.exists(ico_path): # Open the ICO file using Pillow with Image.open(ico_path) as img: # Convert the image to a format compatible with PhotoImage img = img.convert("RGBA") self.photo = ImageTk.PhotoImage(img) # # Create the main window # self.root = tk.Toplevel(root) # # # Create a button to activate the .lnk file with the icon # button = tk.Button(self.root, text="Activate", compound=tk.LEFT, image=self.photo, # command=self.activate_lnk) # button.pack(side=tk.LEFT) # # # Bind the closing event # self.root.protocol("WM_DELETE_WINDOW", self.on_closing) # # # Run the Tkinter event loop # self.root.mainloop() # else: # print("Failed to generate .ico file.") else: print("Failed to retrieve the target path.") class LinksMenu: def __init__(self): self.MainWindow = tk.Tk() self.MainWindow.geometry("100x40+" + str(pyautogui.position()[0]) + "+100") self.MainWindow.overrideredirect(True) self.MainWindow.bind("<KeyPress>", self.closing) self.btnframe = tk.Frame(self.MainWindow) self.btnframe.configure(bg='') self.btnframe.columnconfigure(0, weight=1) count = 1 files = [File for File in os.listdir('.') if os.path.isfile(File)] for File in files: if File[-4:] == ".lnk": GetImage.main(os.path.realpath(File), os.path.dirname(os.path.realpath(File)) + '\\' + File[0:-4] + '.ico') newbutton = (tk.Button (self.btnframe, name=File[0:-4].lower() + 'btn', text=File[0:-4], compound=tk.LEFT, image=GetImage.photo, font=('Arial', 14), bg='DodgerBlue4', command=lambda m=os.path.realpath(File): [execlink(m), self.close_after_choice()])) newbutton.grid(padx=2, pady=2, row=count, column=0, sticky=tk.W+tk.E) count += 1 self.btnframe.pack(fill='x') self.MainWindow.geometry("300x" + str(count*45) + "+" + str(pyautogui.position()[0]) + "+" + str(GetSystemMetrics(1)-(count*45))) self.MainWindow.configure(bg='') self.MainWindow.mainloop() def closing(self, event): if event.state == 8 and event.keysym == "Escape": self.MainWindow.destroy() def close_after_choice(self): self.MainWindow.destroy() if __name__ == "__main__": GetImage = IconExtractor() LinksMenu() ``` I've tried: - saving the icon as a png and then recalling it by the filepath - adding it to a new object and then adding the new object to the tk.Button (in case the link was persisting) - converting it to a png in memory before adding to the tk.Button - not dynamically creating the buttons (in case it was something to do with re-using the same object name 'newbutton' - destroying the object that is called (via a class) to get the image in the first place Full disclosure, I used ChatGPT to help with the code for the icon extraction.
I manage a longitudinal dataset of schools that is shaped wide, so there is one row per school and variables about each school that span multiple years. Stakeholders often need a table displaying a subset of schools and variables from our 1,000+ variable file. For example, our marketing team wants to be updated regularly when a school closes. I would prepare an Excel spreadsheet with all the recently closed schools and the variables that are relevant for the marketing team. I was able to pull this information fine with Stata 14 using a simple browse command. My code with Stata 14 would look like this: ``` browse school AccountID county enrollment ClosedDate GradesServed website if statustype=="closed" & year(ClosedDate)==2024 ``` The variables would list in the order of my code. With Stata 17, the variables are listed in their order within the dataset. I need the variables to list in the order they are called within the browse command. I know the `order` command and could reorder the variables. But I often have to pull multiple lists and save other changes into our records in the same working session. The variable lists are so long that ordering and reordering them would take a long time. Is there an easy way to `browse` or `export` a list of variables in a specific order using Stata 17?
In Stata17, is there a way to browse variables in a specific order rather than the dataset's variable order?
I suspect you've tried to install the "Vibrancy" extension. This extension changes the default CSS of Visual Studio Code and I think the latest version of Visual Studio Code is not letting us change its default CSS. I also have restarted my laptop because I am facing the same problem I think reinstalling Visual Studio Code is the best option, or we will have to wait for the developers of Visual Studio Code to fix this bug.
This is answer is more along the lines of a trick, or even a hack. As the comment above by @ThomA states, all branches of a `CASE` expression need to have the same type. You can achieve this by casting the `UserId` to text and then left padding with some number (say 10) of zeroes. This means that, when used for sorting, the `UserId` column would sort as text. However, since it is now fixed width, left padded with zeroes, a lexicographical sort should agree with a numeric sort. <!-- language: sql --> ORDER BY CASE WHEN @sortOrder = '1' THEN CASE @sortField WHEN 'FirstName' THEN FIRSTNAME WHEN 'SkillNames' THEN SkillNames WHEN 'UserId' THEN CAST(RIGHT('0000000000' + CAST(UserId AS varchar(10)), 10) AS varchar(10)) END END ASC, CASE WHEN @sortOrder = '-1' THEN CASE @sortField WHEN 'UserId' THEN CAST(RIGHT('0000000000' + CAST(UserId AS varchar(10)), 10) AS varchar(10)) WHEN 'FirstName' THEN FirstName WHEN 'SkillNames' THEN SkillNames END END DESC Sort order for the `UserId`: 0000000001 0000000004 0000000010 0000000011 0000000053 0000000101