instruction
stringlengths
0
30k
null
The problem is that my code works but when downloading it says that the file type is not supported by my code ---> ``` var urlContract = "https://dashboard-8tl3.onrender.com/%D0%90%D0%BD%D0%BD%D0%BE%D1%82%D0%B0%D1%86%D0%B8%D1%8F_2024-03-11_144401.png" function downloadContract(urlContract) { if (urlContract.includes("png")) { const blob = new Blob([urlContract], { type: "image/png" }); const link = document.createElement("a"); link.setAttribute("href", URL.createObjectURL(blob)); link.setAttribute("download", "Contract.png"); link.click(); } if (urlContract.includes("jpeg")) { const blob = new Blob([urlContract], { type: "image/jpeg" }); const link = document.createElement("a"); link.setAttribute("href", URL.createObjectURL(blob)); link.setAttribute("download", "Contract.jpeg"); link.click(); } if (urlContract.includes("pdf")) { const blob = new Blob([urlContract], { type: "application/pdf" }); const link = document.createElement("a"); link.setAttribute("href", URL.createObjectURL(blob)); link.setAttribute("download", "Contract.pdf"); link.click(); } ```
{"Voters":[{"Id":4621513,"DisplayName":"mkrieger1"},{"Id":197758,"DisplayName":"toolic"},{"Id":9214357,"DisplayName":"Zephyr"}],"SiteSpecificCloseReasonIds":[13]}
HTML CODE: ![](https://i.stack.imgur.com/m7BIY.png) My code for this dropdown selection is: ```java WebElement LocationInput = driver.findElement(By.xpath("//*[@id=\"app\"]/div[1]/div[2]/div[2]/div/div[1]/div[2]/form/div[1]/div/div[3]/div/div[2]/div/div/div[1]")); LocationInput.click(); pauseFor(3); WebElement CountryName = driver.findElement(By.xpath("//*[@id=\"app\"]/div[1]/div[2]/div[2]/div/div[1]/div[2]/form/div[1]/div/div[3]/div/div[2]/div/div/div[1]")); Actions actions1 = new Actions(driver); actions.moveToElement(CountryName).sendKeys("Canadian").sendKeys(Keys.ENTER).build().perform(); pauseFor(4); ``` This code is selecting another dropdown, but I want to select the dropdown with link text containing Canadian in it How can I select this dropdown?
{"Voters":[{"Id":476,"DisplayName":"deceze"}],"SiteSpecificCloseReasonIds":[13]}
the given code is not conerging to correct eigenvalues. Kindly highlight potential issues and make corrections. ``` import numpy as np import matplotlib.pyplot as plt from scipy.integrate import simps xlower = 10**-15 xupper = 60 dr = 0.001 x = np.arange(xlower,xupper+ dr,dr) G = x.shape[0] delta_x = dr G def potential(x, l=0): V = l*(l+1)/2*x**2 - 1/x return V def intervals(): delta_E = 1 E = 0 energy_intervals = [] while E>-1: energy_intervals.append((E-delta_E, E)) E = E - delta_E return energy_intervals 1-2/6 def Numerov(E, x,v, G): psis = [0] * G psis[1] = 10**-6 for j in range(1,len(x)-1): m = 2*(1-5/12* delta_x**2 * 2*(E - v[j]))*psis[j] n = (1+1/12*delta_x**2*(E - v[j-1])*2)*psis[j-1] o = 1 + 1/12*delta_x**2 *(E - v[j+1])*2 psis[j+1] = (m - n)/o return psis def binary_search(function, left, right,x, v, G): print('left', left) print('right', right) precision = 10**-14 iter = 0 while abs(right - left) > precision and iter <= 10: mid = (left + right) / 2 print('mid', mid) psis = function(mid, x, v, G) left_psis = function(left, x,v, G) print('psis', psis[-1]) if np.isclose(psis[-1], 10**-6): return mid, psis elif left_psis[-1]*psis[-1] < 0: print('psis < 0') right = mid print('new right', left) else: print('psis > 0') left = mid print('new left', right) iter += 1 if np.isclose(psis[-1], 10**-6): mid = (left + right) / 2 return mid, psis return None, None def main(): n_samples = 1 potentials = [] eigenvectors = {} eigenvalues = {} for i in range(n_samples): eigenvectors[i] = [] eigenvalues[i] = [] V = potential(x) energy_intervals = intervals() for interval in energy_intervals: print(interval) eigenvalue, psis = binary_search(Numerov, interval[0], interval[1], x, V, G) if eigenvalue is not None: print("eigenvalue found") eigenvalues[i].append(eigenvalue) eigenvectors[i].append(psis) print(f"{i}th sample is done") return eigenvalues, eigenvectors eigenvalues, eigenvectors= main() eigenvalues ``` I tried counting the nodes in the solution first before implementing bisection method. but that didn't work also. The code is not converging to correct eigenvalues.
This can help [SqlDumpReader][1] ``` from sql_dump_parser import SqlSimpleDumpParser sample_lines = [ 'create table TBL1 (id1 int, id2 int, id3 int);', 'insert into TBL1 (id2, id1) values (1, 2)', 'insert into TBL1 values (3, 4, 5)' ] sql_parser = SqlSimpleDumpParser() data = sql_parser.parse_tables(sample_lines) print(data) print(sql_parser.table_descriptions) ``` OUTPUT: ``` {'TBL1': [[2, 1, None], [3, 4, 5]]} {'TBL1': {'id1': int, 'id2': int, 'id3': int}} ``` Read files: ``` from sql_dump_parser import SqlSimpleDumpParser sql_parser = SqlSimpleParser() with open("sample_data\\dump01.sql", "r", encoding='UTF-8') as file_in: data = sql_parser.parse_tables(file_in) ``` [1]: https://github.com/pashaalex/SqlDumpReader
I'm using Angular xeditable for my project. I'm using Angular xeditable row component for my grid. As I know, if I use return $http.post('api/students',model).sucess(function(data) { }) .error(function(data) { }) ; As I know, what happens - above code will call students CONTROLLER post method web api. If it returns OK, success will be executed and returned else error will be executed and returned. But my question is - can I call `.error` call from JavaScript itself? Let's say: if( textbox == "") return $http.post().error()....... else return $http.post().sucess().... Why I want something like this? Because for single textbox I have to make server trip to check whether it is empty or not. If it is not empty, I return OK() else I return (let's say) NotFound(). OK will execute success call, NotFound will execute error call. So at JS side if I check whether string is empty or not. If empty forcefully (without server trip) I want to 'return' .error callback. Is it possible? $http.post will make server trip, I know that. But what at client side if I want to return error promise forcefully?
Return Angular promise at client side, without server round-trip
{"Voters":[{"Id":1145388,"DisplayName":"Stephen Ostermiller"}],"SiteSpecificCloseReasonIds":[13]}
Say I have an interface like `interface IThing { virtual string A => "A"; }`. What effect does the `virtual` keyword have on implementing types here? Surprisingly, I couldn't find anything regarding this on either SO, `dotnet` GitHub pages and discussions, nor on `learn.microsoft.com`, possibly buried under all the unrelated content where the words `interface` and `virtual` appear in any combination. From my quick testing it doesn't appear to have any sensible effect. My intuition tells me to expect from the implementing classes' hierarchy to have been introduced the given virtual members, as if the base implementing class has declared them itself, but it's not the case. For example: ```c# class Thing: IThing { } class Thing2: Thing { override public string A => "!"; // ERROR: No suitable method found to override. } ``` If I declare the `A` property on `Thing`, but do not declare it explicitly as virtual, it still won't compile. I also have the freedom apparently to just define them w/o the modifier despite it being present in the interface and it compiles. And code using `IThing` only sees the default implementation of `A` regardless of what I do unless the class implements the interface directly and not through inheritance in this setup. Can somebody clarify the use of the `virtual` modifier on interface members? I use the latest stable language version of C#.
After using Thymeleaf for server-side rendering in Spring, I saw a post about JTE on Reddit that was mentioning the Spring View Component library https://github.com/tschuehly/spring-view-component, prompting curiosity about different UI design approaches. What are the potential downsides of JTE and patterns that group the views and the logic needed to render it into components instead of having the views in the resources folder? Why does it look like Thymeleafe is the "standard" template engine even though the speed, syntax and the tooling of JTE looks better suited. What technical challenges or limitations might arise with JTE or such integrated design patterns in terms of scalability, performance, and maintainability in server-side rendering contexts? What is considered to be a modern way of structuring the UI layer of a JVM and server side rendered enterprise application?
Thymeleaf, JTE, and Alternative Patterns for Spring Server-Side Rendering
|server-side-rendering|
This could be accomplished using Power Query, available in Windows Excel 2010+ and Excel 365 (Windows or Mac) To use Power Query - Select some cell in your Data Table - `Data => Get&Transform => from Table/Range` or `from within sheet` - When the PQ Editor opens: `Home => Advanced Editor` - Make note of the Table **Name** in Line 2 - Paste the M Code below in place of what you see - Change the Table name in line 2 back to what was generated originally. - Read the comments and explore the `Applied Steps` to understand the algorithm ``` let Source = Excel.CurrentWorkbook(){[Name="Orders"]}[Content], //Repeat rows per quantity #"Repeat Rows" = Table.AddColumn(Source,"Repeats", each Table.Repeat(Table.FromRecords({_}),[Quantity]), type table[Order ID=text, #"Phone S/N"=text, Description=text, Quantity=Int64.Type]), #"Removed Columns" = Table.RemoveColumns(#"Repeat Rows",Table.ColumnNames(Source)), #"Expanded Repeats" = Table.ExpandTableColumn(#"Removed Columns", "Repeats", Table.ColumnNames(Source)), //Group by Order ID, then process group separately #"Grouped Rows" = Table.Group(#"Expanded Repeats", {"Order ID"}, { {"Updated", (t)=> let //create updated description text strings phones = Table.SelectRows(t, each [#"Phone S/N"] <> null), accessories = Table.SelectRows(t, each [#"Phone S/N"]=null), updated = List.Transform(List.Zip({phones[Description],accessories[Description]}),each Text.Combine(_," + ")), //Add a column of the Table with the updated description column added #"Add Column" = Table.FromColumns( Table.ToColumns(t) & {updated},{"Order ID", "Phone S/N", "Description","Quantity", "Updated Description"} ) in #"Add Column", type table [Order ID=nullable text, #"Phone S/N"=nullable text, Description=nullable text, Quantity=nullable number, Updated Description = nullable text]}}), //Re-expand the table and remove the duplicated rows #"Expanded Updated" = Table.ExpandTableColumn(#"Grouped Rows", "Updated", {"Phone S/N", "Description", "Quantity", "Updated Description"}), #"Removed Duplicates" = Table.Distinct(#"Expanded Updated") in #"Removed Duplicates" ``` [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/lhbS8.png
A FPGA Project Proposal where I can use both PS and PL
|embedded|fpga|vivado|hdmi|soc|
null
{"Voters":[{"Id":11182,"DisplayName":"Lex Li"},{"Id":1974224,"DisplayName":"Cristik"},{"Id":5468463,"DisplayName":"Vega"}]}
I am a beginner and I want to build LLVM, clang and Libfuzzer from source. So I run the cmake command ``` cmake -S llvm -B build -G Ninja \ -DLLVM_ENABLE_PROJECTS="clang;lldb" \ -DLLVM_ENABLE_RUNTIMES="libcxx" \ -DCMAKE_BUILD_TYPE=Debug \ -DLLVM_TARGETS_TO_BUILD="AArch64" \ -DLLVM_ENABLE_ASSERTIONS=ON \ -DLLVM_USE_SANITIZER=Address \ -DLLVM_USE_SANITIZE_COVERAGE=On \ -DLLDB_USE_SYSTEM_DEBUGSERVER=ON \ -DCMAKE_C_COMPILER=/opt/homebrew/opt/llvm/bin/clang \ -DCMAKE_CXX_COMPILER=/opt/homebrew/opt/llvm/bin/clang++ \ -DCMAKE_OSX_ARCHITECTURES='arm64' \ -DCMAKE_CXX_FLAGS="-isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk" ``` But then when I build it, it got the error: > llvm-project/llvm/tools/vfabi-demangle-fuzzer/vfabi-demangler-fuzzer.cpp:20:16: error: variable has incomplete type ‘SMDiagnostic’ > 20 | SMDiagnostic Err; > llvm-project/llvm/include/llvm/AsmParser/Parser.h:29:7: note: forward declaration of ‘llvm::SMDiagnostic’ > 29 | class SMDiagnostic; > llvm-project/llvm/tools/vfabi-demangle-fuzzer/vfabi-demangler-fuzzer.cpp:33:44: error: member access into incomplete type ‘llvm::Module’ > 33 | FunctionType::get(Type::getVoidTy(M-\>getContext()), false); > llvm-project/llvm/include/llvm/AsmParser/Parser.h:26:7: note: forward declaration of ‘llvm::Module’ > 26 | class Module; > 2 errors generated. > \[3998/4053\] Building CXX object tools/llvm-r…/CMakeFiles/llvm-readobj.dir/ELFDumper.cpp.o > ninja: build stopped: subcommand failed. When I asked chatgpt, the answer was to include some headers in the file. I did this and still the build failed. Is this file necessary for libfuzzer? Can I change my cmake command to properly build all the necessary projects that I need to work on my project in LibFuzzer, which I believe is llvm, clang, lldb and Libfuzzer. Please give me any idea on how to resolve this and properly build. Thanks a lot for your help.
Build LLVM, Clang and Libfuzzer
|build|clang|llvm|lldb|libfuzzer|
null
I came up with a query myself. Not sure if a simpler solution exists. ``` SELECT DISTINCT * FROM ( SELECT group_concat(v2_id ORDER BY v2_sort_me ASC) FROM ( SELECT v1.id AS v1_id, v2.id AS v2_id, v1.sort_me AS v1_sort_me, v2.sort_me AS v2_sort_me FROM t v1 JOIN t v2 ON abs(v1.value - v2.value) < 20 ) GROUP BY v1_id HAVING COUNT(*) > 1 ORDER BY v1_sort_me ASC ) ```
The provided code dynamically wraps consecutive paragraphs with the class *foo* inside separate `<div>` elements with the class *wrap*: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> <style> /* Styles for better visualization */ body { font-family: Arial, sans-serif; margin: 0; padding: 0; } .wrap { background-color: #f0f0f0; padding: 10px; margin-bottom: 10px; } .foo { background-color: #ffff99; padding: 5px; margin: 5px 0; } </style> <body> <div> <p>Text 1</p> <p class="foo">Text 2</p> <p>Text 3</p> <p>Text 4</p> <p>Text 5</p> <p>Text 6</p> <p class="foo">Text 7</p> <p class="foo">Text 8</p> <p>Text 9</p> <p class="foo">Text 10</p> <p>Text 11</p> <p class="foo">Text 12</p> <p class="foo">Text 13</p> <p class="foo">Text 14</p> <p class="foo">Text 15</p> <p>Text 16</p> </div> <script> function wrapFooElements() { //select all paragraphs with class "foo" var paragraphs = document.querySelectorAll('p.foo'); //variable to keep track of the current wrap var currentWrap = null; //loop through each paragraph with class "foo" for (var i = 0; i < paragraphs.length; i++) { var paragraph = paragraphs[i]; //check if a new wrap is needed or if the current wrap can be reused if (!currentWrap || paragraph.previousElementSibling !== currentWrap) { //create a new wrap element currentWrap = document.createElement('div'); currentWrap.classList.add('wrap'); //insert the wrap before the current paragraph paragraph.parentNode.insertBefore(currentWrap, paragraph); } //move the paragraph inside the current wrap currentWrap.appendChild(paragraph); } } // Call the function to wrap paragraphs with class "foo" wrapFooElements(); </script> <!-- end snippet -->
I am trying to setup a set of computers to connect over an ad-hoc network, or mesh (on top of adhoc) using batman-adv. The adhoc network is able to establish a station, but I can't ping one computer from another. When using batman-adv to create a mesh on top of the adhoc network, the bat0 device never seems to have any traffic. Here is the setup for two computers: # Computer 1: ``` # /etc/config/wireless config wifi-device 'radio0' option type 'mac80211' option path 'platform/ahb/18100000.wmac' option channel '5' option band '2g' option htmode 'HT20' option cell_density '0' option hwmode '11n' config wifi-iface 'wifinet0' option device 'radio0' option network 'bat0' option mode 'adhoc' option ssid 'spiri-mesh' option bssid '02:CA:FF:EE:BA:BE' option mcast_rate '12000' # /etc/config/network config interface 'loopback' option device 'lo' option proto 'static' option ipaddr '127.0.0.1' option netmask '255.0.0.0' config globals 'globals' option ula_prefix 'fd6b:8d01:7c47::/48' config interface 'lan' option proto 'static' option ipaddr '192.168.1.2' option netmask '255.255.255.0' option gateway '192.168.1.1' option device 'br-lan' config device option name 'br-lan' option type 'bridge' list ports 'eth0' config interface 'bat0' option proto 'batadv' option routing_algo 'BATMAN_IV' option aggregated_ogms '1' option ap_isolation '0' option bonding '0' option fragmentation '1' option gw_mode 'off' option log_level '0' option orig_interval '1000' option bridge_loop_avoidance '1' option distributed_arp_table '1' option multicast_mode '1' config interface 'mesh' option proto 'static' option ipaddr '192.168.2.1' option netmask '255.255.255.0' option device 'bat0' config device option name 'bat0' option ipv6 '0' ``` # Computer 2: ``` # /etc/config/wireless config wifi-device 'radio0' option type 'mac80211' option path 'platform/ahb/18100000.wmac' option channel '5' option band '2g' option htmode 'HT20' option cell_density '0' option hwmode '11n' config wifi-iface 'wifinet0' option device 'radio0' option network 'bat0' option mode 'adhoc' option ssid 'spiri-mesh' option bssid '02:CA:FF:EE:BA:BE' option mcast_rate '12000' # /etc/config/network config interface 'loopback' option device 'lo' option proto 'static' option ipaddr '127.0.0.1' option netmask '255.0.0.0' config globals 'globals' option ula_prefix 'fd6b:8d01:7c47::/48' config interface 'lan' option proto 'static' option ipaddr '192.168.1.3' option netmask '255.255.255.0' option gateway '192.168.1.1' option device 'br-lan' config device option name 'br-lan' option type 'bridge' list ports 'eth0' config interface 'bat0' option proto 'batadv' option routing_algo 'BATMAN_IV' option aggregated_ogms '1' option ap_isolation '0' option bonding '0' option fragmentation '1' option gw_mode 'off' option log_level '0' option orig_interval '1000' option bridge_loop_avoidance '1' option distributed_arp_table '1' option multicast_mode '1' config interface 'mesh' option proto 'static' option ipaddr '192.168.2.2' option netmask '255.255.255.0' option device 'bat0' config device option name 'bat0' option ipv6 '0' ``` After setting up the config, I am using the following to start services: (Note: my wireless interface name shows up as phy0-ibss0) ``` # Load batman-adv module modprobe batman-adv # Replace phy0-ibss0 with your wireless interface name (use 'iw dev' to find it) batctl if add phy0-ibss0 # Activate the interfaces ifconfig phy0-ibss0 up ifconfig bat0 up # Assign IP address to bat0 interface (use different IPs for each device) ifconfig bat0 192.168.2.1 netmask 255.255.255.0 # Use 192.168.2.2 for the other device ``` What is going wrong here?
Adhoc / mesh network not working (with and without batman-adv)
|networking|mesh|openwrt|adhoc|
|python|mongodb|web-scraping|pymongo|langchain|
See title start forward... I need to log onto youtube as I am a new domain admin many thanks in advance! research google domain admin allowed sites no workie How can I access, log in, create a youtube account for my new business? Im having trouble getting myself access while being a new online business owner. YELP! :)))
I am the domain admin, newbie, how do I connect youtube.com on my domain?
|asp.net|dns|youtube|google-admin-sdk|google-domain-api|
null
I'm not sure the cookies are the best place to store user preferences. Cookies are sent to server so if you don't plan on storing those preferences on the server, it is useless extra network used. I think using localStorage suits more your needs. Anyway, [w3schools][1] gives two good functions to handle cookies in Javascript : ```js function setCookie(cname, cvalue, exdays) { const d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); let expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } function getCookie(cname) { let name = cname + "="; let decodedCookie = decodeURIComponent(document.cookie); let ca = decodedCookie.split(';'); for(let i = 0; i <ca.length; i++) { let c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } ``` Now, if you want to use localStorage, the [documentation of Mozilla][2] is a good start. ```js localStorage.setItem("darkmode", "true"); var darkmode = localStorage.getItem("darkmode") === "true"; ``` [1]: https://www.w3schools.com/js/js_cookies.asp [2]: https://developer.mozilla.org/fr/docs/Web/API/Window/localStorage
What you want is a "stable" sort. "Stable" means it maintains the current order when the keys are identical. The default algorithm, quicksort, is not stable. ``` df2.sort_values('size',kind='stable') ```
Here: ``` g++.exe -o bin\Release\GraphicsC++.exe obj\Release\main.o -s ..\..\..\..\Windows\SysWOW64\glu32.dll ``` You are trying to statically link a DLL (glu32.dll). You cannot do that, and your "simple code snippet" does not need OpenGL in any event. Moreover you cannot normally statically link code built using a different incompatible toolchain. If you do need to link the OpenGL Utility library in your code, you should link the *MinGW provided* export library with the command line switch `-lglu32`. That will cause the _appropriate_ Windows provided DLL to be loaded at runtime. The linker will look in various places to find the export library - all those places specified by `-L <path>` switches in the "verbose" log. That will work for OS provided DLLs. If you add third-party libraries you will need to add your own `-L <path>` switches (there will be a place for that in the IDE rather then specifying them directly nod doubt). You should not try to link a specific DLL path - and using a relative path is bound to fail at some time, it rather assumes that your project will always be in the same place relative to the DLL. Linking the OpenGL Utility library on its own with no other OpenGL support probably won't be useful either - but that is a different issue.
This is because the generic type `S` can have more keys than just `"a"` and `"b"` — that's what the `extends` keyword means in that position: that the generic type `S` must be [constrained](https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints) by `Pick<Test, "a" | "b">` (not that it **only** has keys `"a"` and `"b"`). TypeScript is [structurally-typed](https://www.typescriptlang.org/docs/handbook/type-compatibility.html) (more [here](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html#structural-type-system) and [here](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#structural-typing)), so supplying a generic type that satisfies `Pick<Test, "a" | "b">` that **also** has an [index signature](https://www.typescriptlang.org/docs/handbook/2/objects.html#index-signatures) of `symbol` keys with `unknown` values will be accepted by the compiler… [TS Playground](https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&removeComments=true&target=99&jsx=4&exactOptionalPropertyTypes=true&inlineSourceMap=true&inlineSources=true&isolatedModules=true&noImplicitOverride=true&noErrorTruncation=true&ssl=13&ssc=1&pln=21&pc=75#code/JYOwLgpgTgZghgYwgAgCoQM5mQbwFACQcAXMllKAOYDchARqSAK4C2d0tBCpdA9rwBsIcELQC+ePEOxwoUUuSoBtALrIAvMlW08MJiARhgvEMkhYAPAGVkEAB6QQAEwzIACsAQBrC+iwAaZAAiOCDkAB9guiCAPkDUWwcIZ1cvCABPXhhkKxiACgA3OAFSVFUASlxCWSgNZCKBcUkwdIAHFAAxfjr8IgUwChAaekZWdihOJTT0hXS2QRVSfS8QXgB3UTwxHQQTLGRQVqYwUjzprOQu3nLVOqUrOb4BPKCYfiDywJCgr+iVHXMYAsV0C52yV3yh2O5WoyAA9HDkAB5LyBOjHMiPQQHVyrGQYDDASggOB0IRmXhkAZUPBAA) ```lang-ts type Foo = { a: string; b: number; [key: symbol]: unknown; }; const input: (keyof Foo)[] = [Symbol("foo"), "a", "b"]; test<Foo, keyof Foo>(input); // Ok, but symbol is not assignable to string ``` …but `symbol` is not assignable to `string`, so it would be a type error to accept an array of such values (or any other non-string value). In the second code block example of your question you provided this code and question: ```lang-ts type S = Pick<Test, "a" | "b">; type T = keyof S; const val: T[] = []; arr = val; // why it is ok? ``` There, `S` is a type that looks like `{ a: string; b: number }` and T is the union of its keys, which is `"a" | "b"`. An array of `"a"` and `"b"` values are assignable to `string`, so there's no problem there. A modified version of your `test` function that uses these types would look like this… [TS Playground](https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&removeComments=true&target=99&jsx=4&exactOptionalPropertyTypes=true&inlineSourceMap=true&inlineSources=true&isolatedModules=true&noImplicitOverride=true&noErrorTruncation=true#code/JYOwLgpgTgZghgYwgAgCoQM5mQbwFACQcAXMllKAOYDchARqSAK4C2d0tBCpdA9rwBsIcELQC+ePEOxwoUUuSoBtALrIAvMlW08MJiARhgvEMkhYAFADc4A0hYDWEAJ68YyAArAEDgDzosABpkACI4EOQAH1C6EIA+AEpVBNxCWSgNZBsBcUkwZwAHFAAxfkz8IgUwChAaekZWdihOJSdnBWc2QRVSfQcQXgB3UTwxHQQTLGRQAqYweza3ZFLeJLVNJQBlTr4BCxCYfhCE4LCQ09iVHXMwCxm5hNogA) ```lang-ts function test(val: (keyof Pick<Test, "a" | "b">)[]) { arr = val; } ``` > Note that `keyof Pick<Test, "a" | "b">` is just `"a" | "b"`. …and attempting to provide an array of values that includes a non-string will produce a compiler diagnostic error: ```lang-ts type Foo = { a: string; b: number; [key: symbol]: unknown; }; const input: (keyof Foo)[] = [Symbol("foo"), "a", "b"]; test(input); /* Error ~~~~~ Argument of type '(keyof Foo)[]' is not assignable to parameter of type '("a" | "b")[]'. Type 'keyof Foo' is not assignable to type '"a" | "b"'. Type 'symbol' is not assignable to type '"a" | "b"'.(2345) */ ```
What effect does the `virtual` modifier have on an interface member?
|c#|oop|inheritance|
I'm using **Auto** mode in Blazor Web App. I tried to use Authentication and authorization in the server project. But I cannot use authorization in the client project. I want to add `<AuthorizeView>` tag in some components exist in the client project. This tag is unknown in the client project. How can I use `<AuthorizeView>`tag in the client project?
Please help me :(( According to the network diagram above, the connection from company A's pc0 to the server system including gmail and facebook is successful, but company B's pc6 and pc7 cannot ping the server system. I tried to give ip from dns but it didn't work. I just joined this system course. I hope everyone can answer my questions. Thank you. The system works normally, all devices are connected successfully, can send emails from the pc to the server
Network System - Cisco Packet Tracer
|networking|system|packet|cisco|
null
**Method 1 (recommended)** make sure to import: import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.dsl.SearchRequest; import org.elasticsearch.client.dsl.SearchResponse; import org.elasticsearch.index.query.QueryBuilders; then inside your code write this: // Construct the search request SearchRequest searchRequest = new SearchRequest("your_index"); searchRequest.source(sourceBuilder -> sourceBuilder.query(QueryBuilders.matchAllQuery()) // Add a query to match all documents .aggregations(aggregationBuilder -> aggregationBuilder .terms("my-agg-name", term -> term.field("my-field")) // Add an aggregation named "my-agg-name" of type terms to group documents by the value of "my-field" // Now we have a number of groups and we will add the sub-aggregation to them .aggregations(subAggregationBuilder -> subAggregationBuilder .avg("my-sub-agg-name", avg -> avg.field("my-other-field"))))); // Add a sub-aggregation named "my-sub-agg-name" of type avg to calculate the average of "my-other-field" // Execute the search request and retrieve the search response SearchResponse<Void> searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);//assuming that you already defined a client // You can handle the search response by using it directly System.out.println(searchResponse); **Method 2 (not recommended)** I will share another method it is not recommended but useful if you can't do your code using the java-client, you still can use your basic query by: // Define your query, for example in your case the aggregation will be String query = "{\n" + " \"aggs\": {\n" + " \"my-agg-name\": {\n" + " \"terms\": {\n" + " \"field\": \"my-field\"\n" + " },\n" + " \"aggs\": {\n" + " \"my-sub-agg-name\": {\n" + " \"avg\": {\n" + " \"field\": \"my-other-field\"\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}"; // Create the request Request request = new Request("POST", "/your_index/_search"); // Add your query to the request request.setJsonEntity(query); // Execute the request Response response = client.getLowLevelClient().performRequest(request); // This will print JSON file that has all the data, it will look like the Elasticsearch response exactly System.out.println(response.getEntity().getContent()); // You can extract the average by parsing the JSON response
You'd have to edit file `gradle/libs.versions.toml` and add in TOML format: [versions] androidx_compose_bom = '2024.03.00' androidx_compose_uitest = '1.6.4' androidx_media3 = '1.3.0' # ... [libraries] androidx_compose_bom = { module = "androidx.compose:compose-bom", version.ref = "androidx_compose_bom" } androidx_compose_uitest = { module = "androidx.compose.ui:ui-test-junit4", version.ref = "androidx_compose_uitest" } androidx_media3_exoplayer = { module = "androidx.media3:media3-exoplayer", version.ref = "androidx_media3" } androidx_media3_exoplayer_dash = { module = "androidx.media3:media3-exoplayer-dash", version.ref = "androidx_media3" } androidx_media3_ui = { module = "androidx.media3:media3-ui", version.ref = "androidx_media3" } # ... And one can even bundle these (optional): [bundles] androidx_media3 = ["androidx_media3_exoplayer", "androidx_media3_exoplayer_dash", "androidx_media3_ui"] Which means, you can't just copy & paste, but have to convert to TOML.<br/> Be aware that for BOM dependencies, this only works for the BOM itself.<br/> When there's no version number, one can use: `//noinspection UseTomlInstead`. The names of the definitions of the default empty activity app are kind of ambiguous, since they're not explicit enough. There `androidx` should better be called `androidx_compose`, where applicable... because eg. `libs.androidx.ui` does not provide any understandable meaning (low readability), compared to `libs.androidx.compose.ui`. Proper and consistent labeling is important there. --- Once added there, one can use them in `build.gradle` or `build.gradle.kts`: implementation(libs.androidx.media3.exoplayer) implementation(libs.androidx.media3.exoplayer.dash) implementation(libs.androidx.media3.ui) Or by the bundle: implementation(libs.androidx.media3) Further reading: - [Sharing dependency versions between projects](https://docs.gradle.org/current/userguide/platforms.html) - [Migrate your build to version catalogs](https://developer.android.com/build/migrate-to-catalogs)
i am here to ask about the problem about this function that calculates the sum at a given depth in a tree, it is working in all cases but the last level, the compiler is giving me this : `[Done] exited with code=3221225477 in 0.309 seconds` and this is my code and everything you need(there is more other functions and stuff but i think this is enough): ``` #include <stdio.h> #include <stdlib.h> #include <math.h> typedef int element; typedef struct node{ element e; struct node * left; struct node * right; }node; typedef node * tree; int isEmpty(tree a){ return a==NULL; } element root(tree a){ return a->e; } tree left(tree a){ return a->left; } tree right(tree a){ return a->right; } int max(int x,int y){ return x>y?x:y; } int sumAtBis(tree a, int n, int i){ if(i==n){ if(isEmpty(a)) return 0; else return root(a); } return sumAtBis(left(a),n,i+1)+sumAtBis(right(a),n,i+1); } int sumAt(tree a, int n){ return sumAtBis(a,n,0); } int testSumAtBis(tree a, int n, int i){ return sumAt(a,n)==0?1:0; } int testSumAt(tree a, int n){ return testSumAtBis(a,n,0)==0?1:0; } int main(){ node g={-1,NULL,NULL}; node f={1,NULL,NULL}; node e={0,&f,&g}; node d={0,NULL,NULL}; node c={1,&d,&e}; node b={-1,NULL,NULL}; node a={1,&c,&b}; tree v; v=&a; printf("%d\n",sumAt(v,3)); return 0; } ``` i tried printing the value of i at each level when but it also gives an error so i can't know, also i tried to ask Copilot and Gemini but they didn't help
I have observed an issue while using the **Hyperband** algorithm in **Optuna**. According to the Hyperband algorithm, when **min_resources** = 5, **max_resources** = 20, and **reduction_factor** = 2, the search should start with an **initial space of 4** models for bracket **1**, with each model receiving **5** epochs in the first round. Subsequently, the number of models is reduced by a factor of **2** in each round and search space should also reduced by factor of **2** for next brackets i.e bracket 2 will have initial search space of **2** models, and the number of epochs for the remaining models is doubled in each subsequent round. so total models should be **11** is expected but it is training lot's of models. ``` import optuna import numpy as np # Toy dataset generation def generate_toy_dataset(): np.random.seed(0) X_train = np.random.rand(100, 10) y_train = np.random.randint(0, 2, size=(100,)) X_val = np.random.rand(20, 10) y_val = np.random.randint(0, 2, size=(20,)) return X_train, y_train, X_val, y_val X_train, y_train, X_val, y_val = generate_toy_dataset() # Model building function def build_model(trial): model = Sequential() model.add(Dense(units=trial.suggest_int('unit_input', 20, 30), activation='selu', input_shape=(X_train.shape[1],))) num_layers = trial.suggest_int('num_layers', 2, 3) for i in range(num_layers): units = trial.suggest_int(f'num_layer_{i}', 20, 30) activation = trial.suggest_categorical(f'activation_layer_{i}', ['relu', 'selu', 'tanh']) model.add(Dense(units=units, activation=activation)) if trial.suggest_categorical(f'dropout_layer_{i}', [True, False]): model.add(Dropout(rate=0.5)) model.add(Dense(1, activation='sigmoid')) optimizer_name = trial.suggest_categorical('optimizer', ['adam', 'rmsprop']) if optimizer_name == 'adam': optimizer = tf.keras.optimizers.Adam() else: optimizer = tf.keras.optimizers.RMSprop() model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy', tf.keras.metrics.AUC(name='val_auc')]) return model def objective(trial): model = build_model(trial) # Assuming you have your data prepared # Modify the fit method to include AUC metric history = model.fit(X_train, y_train, validation_data=(X_val, y_val), verbose=1) # Check if 'val_auc' is recorded auc_key = None for key in history.history.keys(): if key.startswith('val_auc'): auc_key = key break if auc_key is None: raise ValueError("AUC metric not found in history. Make sure it's being recorded during training.") # Report validation AUC for each model for i, auc_value in enumerate(history.history[auc_key]): trial.report(auc_value, step=i) # Check for pruning based on the intermediate AUC value if trial.should_prune(): raise optuna.TrialPruned() return max(history.history[auc_key]) # Optuna study creation study = optuna.create_study( direction='maximize', pruner=optuna.pruners.HyperbandPruner( min_resource=5, max_resource=20, reduction_factor=2 ) ) # Start optimization study.optimize(objective) ```
Optuna Hyperband Algorithm Not Following Expected Model Training Scheme
|python|algorithm|machine-learning|optuna|
This is my ``Magento_Checkout/web/template/summary/cart-items.html`` ``` <!-- /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ --> <div class="block items-in-cart" data-bind="mageInit: {'collapsible':{'collapsible': true, 'openedState': 'active', 'active': isItemsBlockExpanded() }}"> <div class="title" data-role="title"> <strong role="heading" aria-level="1"> <translate args="maxCartItemsToDisplay" if="maxCartItemsToDisplay < getCartLineItemsCount()"></translate> <translate args="'of'" if="maxCartItemsToDisplay < getCartLineItemsCount()"></translate> <translate args="'Cart'" if="getCartSummaryItemsCount() === 1"></translate> <translate args="'Cart'" if="getCartSummaryItemsCount() > 1"></translate> (<span data-bind="text: getCartSummaryItemsCount().toLocaleString(window.LOCALE)"></span> <span data-bind="i18n: 'items'"></span>) </strong> </div> <div class="content minicart-items" data-role="content"> <div class="minicart-items-wrapper"> <ol class="minicart-items"> <each args="items()"> <li class="product-item"> <div class="product"> <each args="$parent.elems()" render=""></each> </div> </li> </each> </ol> </div> </div> <div class="actions-toolbar" if="maxCartItemsToDisplay < getCartLineItemsCount()"> <div class="secondary"> <a class="action viewcart" data-bind="attr: {href: cartUrl}"> <span data-bind="i18n: 'View and Edit Cart'"></span> </a> </div> </div> </div> ``` Here, the checkout accordion is handled. I want this accordion to be initially open at the first step (shipping step), and closed at the second step (payment step) obviously, in both steps, I want there to be the possibility to open/close the accordion. I created my own mixin, ``Magento_Checkout/web/js/view/summary/cart-items-mixin.js`` ``` define(['Magento_Checkout/js/model/step-navigator'], function (stepNavigator) { 'use strict'; var mixin = { isShippingState: function () { return !stepNavigator.isProcessed('shipping'); }, isItemsBlockExpanded: function () { return !stepNavigator.isProcessed('shipping'); } }; return function (target) { return target.extend(mixin); }; }); ``` in this way, it does not seem to achieve the desired effect. I tried using the ``subscribe()``function of ``stepNavigator`` but I couldn't solve it. it is as if the accordion maintains the same state in both steps. Because if I open it in the first step, it will also be open in the second, and vice versa. So, to recap, the result I want to get is: - in the first step the accordion must initially be open (and interactable) - in the second step tha accordion must be initially closed (and interactable) PS: obviously, I've registered the mixin in a ``requirejs-config.js`` file as shown below: ``` /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ var config = { 'config': { 'mixins': { 'Magento_Checkout/js/view/summary/cart-items': { 'Magento_Checkout/js/view/summary/cart-items-mixin': true } } } }; ``` So, the mixin is correctly registered! Do you guys have got any ideas how to solve this?
You can't do this directly. `addParticle` is a function within your `ParticleContainer` component, inaccessible from the outside scope - and you can't move it outside because it references the `setParticleDetails` function which is necessary internal to the component (as that is returned from `useState` which, like all React hooks, can *only* be called from inside a function component). What you can do though, and which is perfectly normal and expected for a React component library, is to export a custom hook to do this. There are a few ways to design the API, depending on what you want consumers to be able to do with your library, but as a starting point based on what you've already shared, I would guess you want to return an object (an array would also work, but I've gone with an object below) containing both the UI of all the rendered `Particle` component, and the `addParticle` function: function useParticles() { const [particleDetails, setParticleDetails] = useState<AddParticleProps[]>( [] ); const addParticle = ({ src, height, width, animationDuration, }: AddParticleProps) => { setParticleDetails([ ...particleDetails, { src, height, width, animationDuration }, ]); }; const particles = particleDetails.map((props, index) => { return <Particle key={index} id={index} {...props} />; }); return { particles, addParticles }; }; Once you have this, consumers can easily recreate your proposed `ParticleContainer` component like this: function ParticleContainer({ height = "40px", width = "40px", position, }: ParticleContainerProps) { const { particles, addParticle } = useParticles(); return ( <div className="particlesContainer" style={{ height, width, position }}> {particles} </div> ); } where the `addParticles` function is not currently used, but can easily be used however the consumer wants to within the component (eg pass it as an `onclick` handler to some button in a child component). This also decouples the logic of rendering and adding "particles" from the styling of the container component (the width, height and position) - the `ParticleContainer`, or whatever alternative a consumer wants to use for a container, contains that information, and the `useParticles` hook is looking after the logic of adding the particles themselves.
{"Voters":[{"Id":1127428,"DisplayName":"Dale K"},{"Id":6152400,"DisplayName":"P.Salmon"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[11]}
from bs4 import BeautifulSoup as bs import requests as rq #Replace <your url> with the url you want to scrap url ='<your url>' r=requests.get(url) soup=bs(r.content,"html.parser") links = soup.find_all("a") # Create an empty dict dct = {} for x in links: # Get keys of the dict being clickable text and value being links key = x.string val = x.get("href") print(dct) The output will be a dictionary in which the keys are clickable texts and the values are the links these texts lead to if clicked.
My tests folder consists outside of src folder looks like this: myproject/ src/ config/ controllers/ types/ schemas/ app.ts tests/ data/ routes/ barber/ auth/ login.test.ts When I write a test I need to import app so I do that as this: import app from '../../../../src/app'; is there a way to have "@"? instead of all that "../../.."? tsconfig looks like this: "baseUrl": "./", "paths": { "@/*": ["./src/*"] },
When building pygame (2.5.2) with buildozer (1.5.0) on python (3.10.12) the error attached occurs. It happens when building pygame for armeabi-v7a. The command ran was `buildozer -v android debug` I am following this tutorial: [https://www.youtube.com/watch?v=L6XOqakZOeA](https://stackoverflow.com) ``` fatal error: 'longintrepr.h' file not found #include "longintrepr.h" ^~~~~~~~~~~~~~~ 1 error generated. --- For help with compilation see: https://www.pygame.org/wiki/Compilation To contribute to pygame development see: https://www.pygame.org/contribute.html --- error: command '/home/captaindeathead/.buildozer/android/platform/android-ndk-r25b/toolchains/llvm/prebuilt/linux-x86_64/bin/clang' failed with exit code 1 STDERR: # Command failed: ['/usr/bin/python3', '-m', 'pythonforandroid.toolchain', 'create', '--dist_name=myapp', '--bootstrap=sdl2', '--requirements=python3,pygame,jnius,sdl2,sdl2_image,sdl2_mixer,sdl2_ttf,png,jpeg', '--arch=arm64-v8a', '--arch=armeabi-v7a', '--copy-libs', '--color=always', '--storage-dir=/media/captaindeathead/HardDrive/PythonProjects/Farm_CEO/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a', '--ndk-api=21', '--ignore-setup-py', '--debug'] # ENVIRONMENT: # SHELL = '/bin/bash' # SESSION_MANAGER = 'local/plazmaPC:@/tmp/.ICE-unix/1429,unix/plazmaPC:/tmp/.ICE-unix/1429' # QT_ACCESSIBILITY = '1' # COLORTERM = 'truecolor' # XDG_CONFIG_DIRS = '/etc/xdg/xdg-ubuntu:/etc/xdg' # SSH_AGENT_LAUNCHER = 'gnome-keyring' # XDG_MENU_PREFIX = 'gnome-' # TERM_PROGRAM_VERSION = '1.87.2' # XDG_CONFIG_DIRS_VSCODE_SNAP_ORIG = '/etc/xdg/xdg-ubuntu:/etc/xdg' # GNOME_DESKTOP_SESSION_ID = 'this-is-deprecated' # GTK_IM_MODULE = 'ibus' # GDK_BACKEND_VSCODE_SNAP_ORIG = '' # LANGUAGE = 'en_AU:en' # GIO_MODULE_DIR_VSCODE_SNAP_ORIG = '' # GNOME_SHELL_SESSION_MODE = 'ubuntu' # SSH_AUTH_SOCK = '/run/user/1000/keyring/ssh' # XMODIFIERS = '@im=ibus' # DESKTOP_SESSION = 'ubuntu' # BAMF_DESKTOP_FILE_HINT = '/var/lib/snapd/desktop/applications/code_code.desktop' # GTK_MODULES = 'gail:atk-bridge' # PWD = '/media/captaindeathead/HardDrive/PythonProjects/Farm_CEO' # GSETTINGS_SCHEMA_DIR = '/home/captaindeathead/snap/code/155/.local/share/glib-2.0/schemas' # XDG_SESSION_DESKTOP = 'ubuntu' # LOGNAME = 'captaindeathead' # GTK_EXE_PREFIX = '/snap/code/155/usr' # XDG_SESSION_TYPE = 'x11' # GPG_AGENT_INFO = '/run/user/1000/gnupg/S.gpg-agent:0:1' # SYSTEMD_EXEC_PID = '1474' # XAUTHORITY = '/run/user/1000/gdm/Xauthority' # GJS_DEBUG_TOPICS = 'JS ERROR;JS LOG' # WINDOWPATH = '2' # HOME = '/home/captaindeathead' # USERNAME = 'captaindeathead' # LANG = 'en_AU.UTF-8' # LS_COLORS = 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.webp=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:' # XDG_CURRENT_DESKTOP = 'Unity' # INVOCATION_ID = '3952f7f4c7a44edca819404e373c3b7b' # MANAGERPID = '1133' # CHROME_DESKTOP = 'code-url-handler.desktop' # GJS_DEBUG_OUTPUT = 'stderr' # GSETTINGS_SCHEMA_DIR_VSCODE_SNAP_ORIG = '' # GTK_IM_MODULE_FILE_VSCODE_SNAP_ORIG = '' # LESSCLOSE = '/usr/bin/lesspipe %s %s' # XDG_SESSION_CLASS = 'user' # TERM = 'xterm-256color' # GTK_PATH = '/snap/code/155/usr/lib/x86_64-linux-gnu/gtk-3.0' # LESSOPEN = '| /usr/bin/lesspipe %s' # USER = 'captaindeathead' # GTK_PATH_VSCODE_SNAP_ORIG = '' # DISPLAY = ':0' # SHLVL = '1' # LOCPATH = '/snap/code/155/usr/lib/locale' # QT_IM_MODULE = 'ibus' # GTK_EXE_PREFIX_VSCODE_SNAP_ORIG = '' # XDG_RUNTIME_DIR = '/run/user/1000' # XDG_DATA_DIRS_VSCODE_SNAP_ORIG = '/usr/share/ubuntu:/usr/share/gnome:/home/captaindeathead/.local/share/flatpak/exports/share:/var/lib/flatpak/exports/share:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop' # JOURNAL_STREAM = '8:34211' # XDG_DATA_DIRS = '/home/captaindeathead/snap/code/155/.local/share:/home/captaindeathead/snap/code/155:/snap/code/155/usr/share:/usr/share/ubuntu:/usr/share/gnome:/home/captaindeathead/.local/share/flatpak/exports/share:/var/lib/flatpak/exports/share:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop' # GDK_BACKEND = 'x11' # PATH = '/home/captaindeathead/.buildozer/android/platform/apache-ant-1.9.4/bin:/home/captaindeathead/.local/bin:/home/captaindeathead/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/snap/bin' # GDMSESSION = 'ubuntu' # ORIGINAL_XDG_CURRENT_DESKTOP = 'ubuntu:GNOME' # DBUS_SESSION_BUS_ADDRESS = 'unix:path=/run/user/1000/bus' # GTK_IM_MODULE_FILE = '/home/captaindeathead/snap/code/common/.cache/immodules/immodules.cache' # LOCPATH_VSCODE_SNAP_ORIG = '' # GIO_MODULE_DIR = '/home/captaindeathead/snap/code/common/.cache/gio-modules' # GIO_LAUNCHED_DESKTOP_FILE_PID = '25766' # GIO_LAUNCHED_DESKTOP_FILE = '/var/lib/snapd/desktop/applications/code_code.desktop' # TERM_PROGRAM = 'vscode' # _ = '/home/captaindeathead/.local/bin/buildozer' # OLDPWD = '/media/captaindeathead/HardDrive/PythonProjects' # PACKAGES_PATH = '/home/captaindeathead/.buildozer/android/packages' # ANDROIDSDK = '/home/captaindeathead/.buildozer/android/platform/android-sdk' # ANDROIDNDK = '/home/captaindeathead/.buildozer/android/platform/android-ndk-r25b' # ANDROIDAPI = '31' # ANDROIDMINAPI = '21' # # Buildozer failed to execute the last command # The error might be hidden in the log above this error # Please read the full log, and search for it before # raising an issue with buildozer itself. # In case of a bug report, please add a full log with log_level = 2 ``` I have tried python3.11, 3.10, 3.9, 3.8, 3.7 and wsl, lbuntu vm, ubuntu on my pc, google colab. All of them have had the same error #longintrepr.h not found!
|python|android|pygame|buildozer|
I have a DataGrid - there is 1. A hidden column (SubjectFull) and a visible column with up to 60 characters of SubjectFull called Subject. 2. A Column called Unread - this is an image in the case it has not been unread. I can get a ToolTip to show the value of SubjectFull for just the visible part of the grid, but it messes up as soon as I scroll down. For Each row As DataRowView In DGV.Items.OfType(Of DataRowView) Dim DGRow As DevComponents.WPF.Controls.AdvGridRow = DGV.ItemContainerManager.ContainerFromItem(row, True) Dim vTooltip As String = row("SubjectFull") DGRow.ToolTip = vTooltip Next I'm trying to get a handle on this using Dim DGV As New DGVx With DGV .Name = "Inbox_DGV" .ContextMenu = ReturnContexMenu() End With RegisterControl(Inbox_Grid, DGV) Grid.SetRow(DGV, 1) Inbox_Grid.Children.Add(DGV) Dim vStyle As New Style(GetType(DevComponents.WPF.Controls.AdvGridRow)) Dim vSetter As New Setter With vSetter .Property = DevComponents.WPF.Controls.AdvGridRow.IsSelectedProperty .Value = New Binding("Select") With {.Mode = BindingMode.TwoWay} End With Dim vSetter2 As New Setter With vSetter2 .Property = DevComponents.WPF.Controls.AdvGridRow.ForegroundProperty .Value = New Binding("Unread") With {.Mode = BindingMode.TwoWay} End With vStyle.Setters.Add(vSetter) vStyle.Setters.Add(vSetter2) DGV.Resources.Add(GetType(DevComponents.WPF.Controls.AdvGridRow), vStyle) The binding for the checkbox (select) works well, but I'm struggling to find a way to binding the string from the hidden column to the row and assigning a colour to a row where there is an image for unread. Any pointers would be appreciated
Binding forecolour and ToolTip to a DataGrid
|wpf|
|mysql|query-optimization|
I'm not at a proper machine to test this on, but I think it's simpler if you use a two-stage approach. First, generate each of the images with its label, then pipe all those into a second `montage` command to lay them all out together. In simple terms, that will look like this: for f in *.jpg; do # Generate a single, labelled image on stdout in MIFF format magick "$f" ... MIFF:- done | magick montage MIFF:- ... result.jpg I use `MIFF` as the intermediate format because it can preserve and propagate any bit-depth, any transparency and all meta-data. So, your actual command will look more like this: for f in $(ls -rt *.jpg) ; do # Take first 8 characters, no need to invoke external process like "cut" label="${f:0:8}" magick "$f" -label "$label" -font Arial -pointsize 16 \ -auto-orient -resize 200x200 -background black \ -fill grey MIFF:- done | magick montage -background black MIFF:- -geometry +2+2 -tile 8x result.jpg
I am trying to understand the internal workings of RowSet. How does it set the properties data and create a connection? ``` RowSetFactory factory = RowSetProvider.newFactory(); JdbcRowSet jdbcRowSet = factory.createJdbcRowSet(); jdbcRowSet.setUrl( … ); jdbcRowSet.setUsername( … ); jdbcRowSet.setPassword( … ); jdbcRowSet.setCommand( … ); jdbcRowSet.execute(); ```
null
I'm going through [this][1] azure exercises and have a question regarding this statement: From the All resources view in the Azure portal, go to the Overview page of ***the production slot*** of the web app. I have 2 deployment slots in my newly created test app services. Creating a `training-Staging` slot is the only configuration change i did for this app settings.: Name | Status | App service plan | Traffic % _________________________________________________________________________ training (Production) | Running | ASP-Training-a8b0 | 100 training-Staging | Running | ASP-Training-a8b0 | 0 However in the `All Resources` windows, I don't see a production slot (created by default) slot, only `training-Staging`: Name | Type | Resource group | Location | Subscription -------------------------------------------------------------------------------------------------------------------- Application Insights Smart Detection Action group Training Global ... ASP-Training-a8b0 App Service plan Training East US ... Training App Service Training East US ... Training Application Insights Training East US ... Staging (training/Staging) App Service (Slot) training East US ... There is no link or button to go into configuration for production slot in `Deployment slots` configuration too (but such link exists for staging slot). Where can I find the production slot resource? [1]: https://learn.microsoft.com/en-us/training/modules/stage-deploy-app-service-deployment-slots/5-exercise-deploy-a-web-app-by-using-deployment-slots
Application settings for production deployment slot in azure app services
|c#|azure|azure-appservice|azure-deployment|azure-deployment-slots|
I have stuck with a pretty simple problem - I can't communicate with process' stdout The process is a simple stopwatch, so I'd be able to start it, stop and get current time. The code of stopwatch is: ```python import argparse import time def main() -\> None: parser = argparse.ArgumentParser() parser.add_argument('start', type=int, default=0) start = parser.parse_args().start while True: print(start) start += 1 time.sleep(1) if __name__ == "__main__": main() ``` And its manager is: ```python import time import asyncio class RobotManager: def __init__(self): self.cmd = ["python", "stopwatch.py", "10"\] self.robot = None async def start(self): self.robot = await asyncio.create_subprocess_exec( *self.cmd, stdout=asyncio.subprocess.PIPE, ) async def stop(self): if self.robot: self.robot.terminate() await self.robot.wait() async def state(self): print("communicating...") stdout, stderr = await self.robot.communicate() print(stdout, stderr) async def main(): robot = RobotManager() await robot.start() time.sleep(5) await robot.state() time.sleep(5) await robot.stop() asyncio.run(main()) ``` After running python manager.py it hangs when getting state of robot. Appreciate any help! I tried to replace proc.communicate() with proc.stdout.readline() but nothing changed
There's a list of supported formats in [`terminalLinkParsing`](https://github.com/microsoft/vscode/blob/main/src/vs/workbench/contrib/terminalContrib/links/browser/terminalLinkParsing.ts#L9) at the definition of `lineAndColumnRegexClauses`. At the time of this writing, among the supported formats, I see - `foo:339:12-789` - `foo:339:12-341.789` - `"foo",339.12-789` - `"foo",339.12-341.789` - `"foo", lines 339-341` - `"foo", lines 339-341, characters 12-789` See also https://stackoverflow.com/q/77184537/11107541.
How to write a clickable link in VS Code terminal that points to a multiline range?
Please suggest the right way to implement it. The below-mentioned is the error I got when I try implement a line chart Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID '' can be reused. The code below is used visually to represent the Historical/periodic chart of cryptocurrency over period of time ``` const CoinInfo = ({ coin }) => { const [historicData, setHistoricData] = useState(); const [days, setDays] = useState(1); const { currency } = useCryptoState(); let chartRef = null; Chart.register(CategoryScale); const fetchHistoricData = async () => { const { data } = await axios.get(HistoricalChart(coin.id, days, currency)); setHistoricData(data?.prices); }; console.log(coin); useEffect(() => { fetchHistoricData(); }, [days]); useEffect(() => { if (chartRef) { chartRef.destroy(); } }, []); const darkTheme = createTheme({ palette: { primary: { main: "#fff", }, type: "dark", }, }); const StyledContainer = styled("div")({ width: "75%", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", marginTop: 25, padding: 40, [theme.breakpoints.down("md")]: { width: "100%", marginTop: 0, padding: 20, paddingTop: 0, }, }); const chartData = { labels: historicData?.map((coin) => { const date = new Date(coin[0]); const time = days === 1 ? `${date.getHours()}:${date.getMinutes()}` : date.toLocaleDateString(); return time; }), datasets: [ { data: historicData?.map((coin) => coin[1]), label: `Price (Past ${days} Days) in ${currency}`, borderColor: "#EEBC1D", }, ], }; return ( <ThemeProvider theme={darkTheme}> <StyledContainer> {!historicData ? ( <CircularProgress style={{ color: "gold" }} size={250} thickness={1} /> ) : ( <> <Line ref={(reference) => (chartRef = reference)} data={chartData} /> </> )} </StyledContainer> </ThemeProvider> ); }; export default CoinInfo; ```
I am using the Chart.js library to draw a Line graph using coingeko api. But it not working properly. Please suggest the right way to implement
|reactjs|charts|material-ui|linechart|react-chartjs-2|
null
The build process of my app is not completing and it stops at react-native-reanimated setup. This is my terminal screen (https://i.stack.imgur.com/5NVvC.png) I have tried a few of the commands from a similar stack overflow thread (https://stackoverflow.com/questions/58131602/unable-to-resolve-module-react-native-reanimated) but I think it is a different problem because its not working and the same error persists. I am an absolute beginner in this field and please let me know if you need any additional info regarding this error like dependencies etc. My dependencies are My dependencies are added here "dependencies": { "@react-native-masked-view/masked-view": "^0.2.8", "@react-navigation/native": "^6.1.17", "@react-navigation/native-stack": "^6.9.26", "@react-navigation/stack": "^6.3.3", "react": "18.1.0", "react-native": "^0.70.3", "react-native-gesture-handler": "^2.16.0", "react-native-image-base64": "^0.1.4", "react-native-maps": "^1.3.2", "react-native-reanimated": "^3.8.1", "react-native-safe-area-context": "^4.9.0", "react-native-screens": "^3.30.1", "react-native-share": "^8.0.0" }, Here it shows react-native-reanimated correctly but it it still shows the same error
tsconfig for path route outside of src
|node.js|typescript|
I found this error: ``` Error: Timeout of 60000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. ``` I am encountering this error, in my selenium test automation with mocha js, below are my two codes and the `package.json`. I really am not able to resolve. Can someone help me please? ```js it('Steps para criação de GR', async function () { this.timeout(26000); await grpage.clickFinancial(); await grpage.ButtonGr(); await grpage.NewGr(); }); ```
{"Voters":[{"Id":286934,"DisplayName":"Progman"},{"Id":1362568,"DisplayName":"Mike Kinghan"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[18]}
I am trying to automate the captcha using the below code I am getting an error Please make sure the TESSDATA_PREFIX environment variable is set to your "tessdata" directory. Failed loading language 'eng' Tesseract couldn't load any languages! ```java WebElement captchaElement = driver.findElement(By.xpath("//img[@alt='captcha']")); File scr = captchaElement.getScreenshotAs(OutputType.FILE); String path = (".\\ScreenShots\\" + "captcha-" + jLib.getSystemDateInFormat() + ".png"); FileHandler.copy(scr, new File(path)); Thread.sleep(2000); ITesseract image = new Tesseract(); image.setDatapath("C:\\Program Files (x86)\\Tesseract-OCR\\tessdata\\eng.traineddata"); String str = image.doOCR(new File(path)); System.out.println("image OCR : " + str); ``` I am trying to read the text present in the captcha image but I am unable to do that
I try to go from Spring-Boot 2.7 to 3.1 - its regarding Security. What I have under old version 2. public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure (HttpSecurity http) throws Exception { http.cors ().and () .csrf ().disable () .authorizeRequests () .antMatchers ("/web/test").permitAll () .antMatchers ("/web/**").hasAnyRole ("USER") .anyRequest ().authenticated () .and () .addFilter (new SecurityAuthenticationFilter (authenticationManager ())) .addFilter (new SecurityAuthorizationFilter (authenticationManager ())) .sessionManagement () .sessionCreationPolicy (SessionCreationPolicy.STATELESS); } What I already have for version 3. @Bean public SecurityFilterChain securityFilterChain (HttpSecurity http) throws Exception { http .cors (Customizer.withDefaults ()) .csrf (AbstractHttpConfigurer::disable) .authorizeHttpRequests ((requests) -> requests .requestMatchers ("/web/test").permitAll () .requestMatchers ("/web/**").hasRole ("USER") .anyRequest ().authenticated () ) //.addFilter (new SecurityAuthenticationFilter (authenticationManager ())) .sessionManagement (httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionCreationPolicy (SessionCreationPolicy.STATELESS)) ; return http.build(); But here I struggle with authenticationManager () of former WebSecurtyConfigurationAdapter - for my 2 custom filters. Where can get this and can I use my filters as they are in Spring3?? They are public class SecurityAuthorizationFilter extends BasicAuthenticationFilter { public SecurityAuthorizationFilter (AuthenticationManager authenticationManager) { super (authenticationManager); } @Override protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { UsernamePasswordAuthenticationToken upa = getAuthentication (request); if (upa == null) { filterChain.doFilter (request, response); } else { SecurityContextHolder.getContext ().setAuthentication (upa); filterChain.doFilter (request, response); } } @SuppressWarnings ("unchecked") private UsernamePasswordAuthenticationToken getAuthentication (HttpServletRequest request) { String token = request.getHeader (SecurityConstants.TOKEN_HEADER); if (token != null && token.startsWith (SecurityConstants.TOKEN_PREFIX) == true) { byte [] signingKey = SecurityConstants.JWT_SECRET.getBytes (); token = token.replace (SecurityConstants.TOKEN_PREFIX, ""); Jws <Claims> claim = Jwts.parserBuilder ().setSigningKey (signingKey).build ().parseClaimsJws (token); String usr = claim.getBody ().getSubject (); List <LinkedHashMap <?, ?>> cs = claim.getBody ().get ("roles", List.class); List <SimpleGrantedAuthority> claims = new ArrayList <SimpleGrantedAuthority> (); for (int i = 0; i < cs.size (); i ++) { claims.add (new SimpleGrantedAuthority (cs.get (i).get ("authority"). toString ())); } if (usr.length () > 0) { return new UsernamePasswordAuthenticationToken (usr, null, claims); } } return null; } } and public class SecurityAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private final AuthenticationManager authenticationManager; public SecurityAuthenticationFilter (AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; setFilterProcessesUrl (SecurityConstants.AUTH_LOGIN_URL); } @Override public Authentication attemptAuthentication (HttpServletRequest request, HttpServletResponse response) { String usr = request.getParameter ("username"); String pwd = request.getParameter ("password"); UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken (usr, pwd); return authenticationManager.authenticate (upat); } @Override protected void successfulAuthentication (HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, Authentication authentication) throws java.io.IOException, ServletException { UserDetails user = ((UserDetails) authentication.getPrincipal ()); @SuppressWarnings ("unchecked") Collection <GrantedAuthority> roles = (Collection <GrantedAuthority>) user.getAuthorities (); String token = Jwts.builder () .signWith (Keys.hmacShaKeyFor (SecurityConstants.JWT_SECRET.getBytes ()), SignatureAlgorithm.HS512) .setHeaderParam ("typ", SecurityConstants.TOKEN_TYPE) .setIssuer (SecurityConstants.TOKEN_ISSUER) .setAudience (SecurityConstants.TOKEN_AUDIENCE) .setSubject (user.getUsername ()) .setExpiration (new java.util.Date (System.currentTimeMillis () + 60 * 60 * 24 * 1000)) // 24h lifetime of token .claim ("roles", roles) .compact (); response.addHeader (SecurityConstants.TOKEN_HEADER, SecurityConstants.TOKEN_PREFIX + token); } } Thanks!
You can work with a custom parser, like: <pre><code>import Data.Char(toLower) import Options.Applicative(ReadM, eitherReader) data OutputType = File | Env | Db parseOutputType :: <b>ReadM OutputType</b> parseOutputType = <b>eitherReader</b> $ (go . map ToLower) where go &quot;file&quot; = Right File go &quot;env&quot; = Right Env go &quot;db&quot; = Right Db go _ = Left &quot;Enter a valid option: file, env, or db&quot;</code></pre> and then parse the options with: <pre><code>import Options.Applicative data <em>MyOptions</em> = <em>MyOptions</em> { display :: OutputType } parseOptions :: Parser <em>MyOptions</em> parseOptions = <em>MyOptions</em> &lt;$&gt; option <b>parseOutputType</b> (long &quot;display&quot;)</code></pre>
I'm currently working a UI selenium project in which I want to get the String data from the UI and parse it into a variable in my .feature scenario file. I will use this scenario to explain, in this case, I only have the customerID: **Given** I search for customer A <customerID> **When** I get the customer info: customer name <customer name> and last orderID <lastOrderID> in customer general info page **Then** I compare it with the actual last orderID in the order list to see if the customer name <customername> and the last orderID <lastOrderID> are matching. Example: |customerID|customername|lastOrderID| |3434423432| ??? | ?? | I would like to get String data of the customername and lastOrderID from the UI and parse these values into the cucumber variables. What should I do here? Btw, this is the first time I send a question on stackoverflow, so appologize if my info is being explained vaguely. Much appreciate for any helps! I have looked around on the Internet for help, but I'm kinda stuck here.
Asyncio: how to communicate with Process?
|python|python-asyncio|
null
I am writing a small app to upload files to a shared Google Drive using a service account (JSON file credential, no user impersonation or consent, service account has been granted permission directly). There are many example scripts online but none seemed to work as-is. I have ended up with the script below. I was able to connect a few times and read files from Drive but then I took a break. When I returned, I started getting these errors: "[{'message': 'Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.', 'domain': 'global', 'reason': 'unauthorized'}] Current code (with some extra lines to force the traffic into Fiddler for inspection) is: from google.oauth2 import service_account from googleapiclient.discovery import build import google.auth.transport.requests import httplib2 import google_auth_httplib2 import os, sys, argparse import json from pprint import pprint parser=argparse.ArgumentParser() parser.add_argument("--keyfile", help="JSON key file",required=True) parser.add_argument("--datafile", help="File to upload",required=True) parser.add_argument("--folderid", help="Google Drive folder for the file",required=True) args=parser.parse_args() def upload_file_to_gdrive(key_file,folder_id,data_file): print(os.path.abspath(key_file)) #scopes = ['https://www.googleapis.com/auth/drive.metadata', 'https://www.googleapis.com/auth/drive'] scopes = ['https://www.googleapis.com/auth/drive'] creds = service_account.Credentials.from_service_account_file(filename=key_file,scopes=scopes) # if not creds or not creds.token_state: # if creds and creds.expired and creds.refresh_token: creds.refresh(google.auth.transport.requests.Request()) print(creds.service_account_email) print(creds.valid) print(creds.token_state) http = httplib2.Http(disable_ssl_certificate_validation=True , proxy_info=httplib2.ProxyInfo(httplib2.socks.PROXY_TYPE_HTTP, "localhost", 8888 ) ) authorized_http = google_auth_httplib2.AuthorizedHttp(credentials=creds, http=http) service = build(serviceName='drive',version='v3', http=authorized_http) #service = build(serviceName='drive',version='v3',credentials=creds) results = service.about().get(fields="*").execute() upload_file_to_gdrive(args.keyfile,args.folderid,args.datafile) Via Fiddler, I can see that the client is hitting the token API, https://oauth2.googleapis.com/token, and receiving an access token. I can also see that the access token is included in the request to GET https://www.googleapis.com/drive/v3/about. GET https://www.googleapis.com/drive/v3/about?fields=%2A&alt=json HTTP/1.1 Host: www.googleapis.com accept: application/json accept-encoding: gzip, deflate user-agent: (gzip) x-goog-api-client: gdcl/2.124.0 gl-python/3.12.2 cred-type/sa content-length: 0 authorization: Bearer ya29.c.c0AY_VpZgZ-JOjiMEHpXd5JDFydx33qiEjyGA8k52SGhRmZqPVaXIo8lEhY2gkHt8VmtGrD8H0qWkIkkKk..... What could be causing this access token to be rejected by the service?
Got TypeError when new SourceTextModule() with a `cachedData` option. It says `TypeError: A dynamic import callback was not specified.` But the `importModuleDynamically` option is clearly there. ```js import vm from "vm"; let context = vm.createContext({console}) async function importModuleDynamically(name) { let stt = new vm.SyntheticModule(['name'], function () { this.setExport('name', name) }) await stt.link(() => null) await stt.evaluate() return stt } function initializeImportMeta(meta, module) { meta.url = module.identifier } let code = 'export default () => import("fs")' let mod1 = new vm.SourceTextModule(code, { context, identifier: 'mod1', importModuleDynamically, initializeImportMeta }) let cachedData = mod1.createCachedData() await mod1.link(() => null) await mod1.evaluate() console.log(await mod1.namespace.default()) let mod2 = new vm.SourceTextModule(code, { context, identifier: 'mod1', cachedData, importModuleDynamically, initializeImportMeta }) await mod2.link(() => null) await mod2.evaluate() console.log(await mod2.namespace.default()) console.log(mod1, mod2) ``` Once `cachedData` is set, it means `import()` can not longer be used any more?
|c#|blazor|blazor-server-side|blazor-webassembly|
I am new to script writing, self taught over the last 6 months. The below script has been working fine for multiple things but the letter returns as a PDF letter named "Site Utilities" this is the whole spreadsheet name. I would like it to return tab/sheet name "Park Letter" instead. Even better would be a chosen name or a cell within the sheet...? Would anyone be kind enough to assist please? The below script has been working fine its just them name situation. `function Email3() {` `var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();` `var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();` `//var email = Session.getUser().getEmail();` `var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Park Letter").getRange("F20");` `var emailAddress = emailRange.getValue();` `var subject = "Coffee Morning";` `var body = ("Attached is a letter about the up coming Coffee Morning. \n \nMany thanks, \n \nCoast and Country Parks");` `var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};` `var shID = getSheetID("Park Letter") //Get Sheet ID of sheet name "Master"` `var url = "``https://docs.google.com/spreadsheets/d/``"+ ssID + "/export?format=pdf&id="+ssID+"&gid="+shID;` `var result = UrlFetchApp.fetch(url , requestData);` `var contents = result.getContent();` `MailApp.sendEmail (emailAddress, subject ,body, {attachments:[{fileName:sheetName+".pdf", content:contents, mimeType:"application//pdf"}]});` `};` `function getSheetID(name){` `var ss = SpreadsheetApp.getActive().getSheetByName(name)` `var sheetID = ss.getSheetId().toString()` `return sheetID` `}` I have looked at other examples where it states get sheet name rather than spreadsheet but this didn't seem to work. I also saw an option for just changing the name "Get New Name". This made sense but I don't think I am putting the code within the right section. Sorry if I am not making sense.
Would like the script to return the PDF letter via email with the sheet name not the spreadsheet name
I see so many people asking questions about their website, JavaScript, HTML, etc. But my question is, have all these people figured out how to make a server and host a website themselves? I have never figured out how to do any of that. They would not be asking their questions if they had no website to be working on, right?
How are there so many web development questions? Is it really that easy to get a web server, register a domain name, etc?
|css|html|javascript|
{"Voters":[{"Id":238704,"DisplayName":"President James K. Polk"},{"Id":9014097,"DisplayName":"Topaco"},{"Id":9214357,"DisplayName":"Zephyr"}]}
I am plotting histograms showing distributions of an angle tau. I used a random normal distribution as shown: N= 100000 tau = np.arccos(np.random.normal(-1, 1, N)) I got the error "RuntimeWarning: invalid value encountered in arccos tau = np.arccos(np.random.normal(-1, 1, N))", which did not pop up with a uniform distribution. Does anyone know why this happened with the normal distribution? Thanks in advance.
I think a good and simple solution is to use an adorner to render the masking symbols as an overlay of the original input. Show the adorner to render the masking characters while hiding the password by setting the foreground brush to the background brush. The following example shows how to use an `Adorner` to decorate the `TextBox`. I have removed some code to reduce the complexity (the original library code also contained validation of input characters and password length, event logic, routed commands, `SecureString` support, low-level caret positioning to support any font family for those cases where the font is not a monospace font and password characters and masking characters won't align correctly etc. and a much more complex default `ControlTemplate`). The current version therefore only supports monospace fonts. The supported fonts have to be registered in the constructor. You could implement monospace font detection instead. However, it's a fully working example (happy easter!). **UnsecurePasswodBox.cs** ```c# public class UnsecurePasswodBox : TextBox { public bool IsShowPasswordEnabled { get => (bool)GetValue(IsShowPasswordEnabledProperty); set => SetValue(IsShowPasswordEnabledProperty, value); } public static readonly DependencyProperty IsShowPasswordEnabledProperty = DependencyProperty.Register( "IsShowPasswordEnabled", typeof(bool), typeof(UnsecurePasswodBox), new FrameworkPropertyMetadata(default(bool), OnIsShowPasswordEnabledChaged)); public char CharacterMaskSymbol { get => (char)GetValue(CharacterMaskSymbolProperty); set => SetValue(CharacterMaskSymbolProperty, value); } public static readonly DependencyProperty CharacterMaskSymbolProperty = DependencyProperty.Register( "CharacterMaskSymbol", typeof(char), typeof(UnsecurePasswodBox), new PropertyMetadata('●', OnCharacterMaskSymbolChanged)); private FrameworkElement? part_ContentHost; private AdornerLayer? adornerLayer; private UnsecurePasswordBoxAdorner? maskingAdorner; private Brush foregroundInternal; private bool isChangeInternal; private readonly HashSet<string> supportedMonospaceFontFamilies; private FontFamily fallbackFont; static UnsecurePasswodBox() { DefaultStyleKeyProperty.OverrideMetadata( typeof(UnsecurePasswodBox), new FrameworkPropertyMetadata(typeof(UnsecurePasswodBox))); TextProperty.OverrideMetadata( typeof(UnsecurePasswodBox), new FrameworkPropertyMetadata(OnTextChanged)); ForegroundProperty.OverrideMetadata( typeof(UnsecurePasswodBox), new FrameworkPropertyMetadata(propertyChangedCallback: null, coerceValueCallback: OnCoerceForeground)); FontFamilyProperty.OverrideMetadata( typeof(UnsecurePasswodBox), new FrameworkPropertyMetadata(propertyChangedCallback: null, coerceValueCallback: OnCoerceFontFamily)); } public UnsecurePasswodBox() { this.Loaded += OnLoaded; // Only use a monospaced font this.supportedMonospaceFontFamilies = new HashSet<string>() { "Consolas", "Courier New", "Lucida Console", "Cascadia Mono", "Global Monospace", "Cascadia Code", }; this.fallbackFont = new FontFamily("Consolas"); this.FontFamily = fallbackFont; } private void OnLoaded(object sender, RoutedEventArgs e) { this.Loaded -= OnLoaded; FrameworkElement adornerDecoratorChild = this.part_ContentHost ?? this; this.adornerLayer = AdornerLayer.GetAdornerLayer(adornerDecoratorChild); if (this.adornerLayer is null) { throw new InvalidOperationException("No AdornerDecorator found in parent visual tree."); } this.maskingAdorner = new UnsecurePasswordBoxAdorner(adornerDecoratorChild, this) { Foreground = Brushes.Black }; HandleInputMask(); } private static void OnIsShowPasswordEnabledChaged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var unsecurePasswordBox = (UnsecurePasswodBox)d; unsecurePasswordBox.HandleInputMask(); Keyboard.Focus(unsecurePasswordBox); } private static void OnCharacterMaskSymbolChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((UnsecurePasswodBox)d).RefreshMask(); private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((UnsecurePasswodBox)d).RefreshMask(); private static object OnCoerceForeground(DependencyObject d, object baseValue) { var unsecurePasswordBox = (UnsecurePasswodBox)d; // Reject external font color change while in masking mode // as this would reveal the password. // But store new value and make it available when exiting masking mode. if (!unsecurePasswordBox.isChangeInternal && !unsecurePasswordBox.IsShowPasswordEnabled) { unsecurePasswordBox.foregroundInternal = baseValue as Brush; } return unsecurePasswordBox.isChangeInternal ? baseValue : unsecurePasswordBox.IsShowPasswordEnabled ? baseValue : unsecurePasswordBox.Foreground; } private static object OnCoerceFontFamily(DependencyObject d, object baseValue) { var unsecurePasswordBox = (UnsecurePasswodBox)d; var desiredFontFamily = baseValue as FontFamily; return desiredFontFamily is not null && unsecurePasswordBox.supportedMonospaceFontFamilies.Contains(desiredFontFamily.Source) ? baseValue : unsecurePasswordBox.FontFamily; } public override void OnApplyTemplate() { base.OnApplyTemplate(); this.part_ContentHost = GetTemplateChild("PART_ContentHost") as FrameworkElement; } private void HandleInputMask() { this.isChangeInternal = true; if (this.IsShowPasswordEnabled) { this.adornerLayer?.Remove(this.maskingAdorner); ShowText(); } else { HideText(); this.adornerLayer?.Add(this.maskingAdorner); } this.isChangeInternal = false; } private void ShowText() => SetCurrentValue(ForegroundProperty, this.foregroundInternal); private void HideText() { this.foregroundInternal = this.Foreground; SetCurrentValue(ForegroundProperty, this. Background); } private void RefreshMask() { if (!this.IsShowPasswordEnabled) { this.maskingAdorner?.Update(); } } private class UnsecurePasswordBoxAdorner : Adorner { public Brush Foreground { get; set; } private readonly UnsecurePasswodBox unsecurePasswodBox; private const int DefaultTextPadding = 2; public UnsecurePasswordBoxAdorner(UIElement adornedElement, UnsecurePasswodBox unsecurePasswodBox) : base(adornedElement) { this.IsHitTestVisible = false; this.unsecurePasswodBox = unsecurePasswodBox; } public void Update() => InvalidateVisual(); protected override void OnRender(DrawingContext drawingContext) { base.OnRender(drawingContext); var typeface = new Typeface( this.unsecurePasswodBox.FontFamily, this.unsecurePasswodBox.FontStyle, this.unsecurePasswodBox.FontWeight, this.unsecurePasswodBox.FontStretch, this.unsecurePasswodBox.fallbackFont); double pixelsPerDip = VisualTreeHelper.GetDpi(this).PixelsPerDip; ReadOnlySpan<char> maskedInput = MaskInput(this.unsecurePasswodBox.Text); var maskedText = new FormattedText( maskedInput.ToString(), CultureInfo.CurrentCulture, this.unsecurePasswodBox.FlowDirection, typeface, this.unsecurePasswodBox.FontSize, this. Foreground, pixelsPerDip) { MaxTextWidth = ((FrameworkElement)this.AdornedElement).ActualWidth + UnsecurePasswordBoxAdorner.DefaultSystemTextPadding; Trimming = TextTrimming.None; }; var textOrigin = new Point(0, 0); textOrigin.Offset(this.unsecurePasswodBox.Padding.Left + UnsecurePasswordBoxAdorner.DefaultSystemTextPadding, 0); drawingContext.DrawText(maskedText, textOrigin); } private ReadOnlySpan<char> MaskInput(ReadOnlySpan<char> input) { if (input.Length == 0) { return input; } char[] textMask = new char[input.Length]; Array.Fill(textMask, this.unsecurePasswodBox.CharacterMaskSymbol); return new ReadOnlySpan<char>(textMask); } } } ``` **Generic.xaml** ```xaml <Style TargetType="local:UnsecurePasswodBox"> <Setter Property="BorderBrush" Value="{x:Static SystemColors.ActiveBorderBrush}" /> <Setter Property="BorderThickness" Value="1" /> <Setter Property="Background" Value="White" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="local:UnsecurePasswodBox"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <AdornerDecorator Grid.Column="0"> <ScrollViewer x:Name="PART_ContentHost" /> </AdornerDecorator> <ToggleButton Grid.Column="1" IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsShowPasswordEnabled}" Background="Transparent" VerticalContentAlignment="Center" Padding="4,0"> <ToggleButton.Content> <TextBlock Text="&#xE890;" FontFamily="Segoe MDL2 Assets" /> </ToggleButton.Content> <ToggleButton.Template> <ControlTemplate TargetType="ToggleButton"> <ContentPresenter Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" /> </ControlTemplate> </ToggleButton.Template> </ToggleButton> </Grid> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> ```
I am creating a data pipeline in Fabric Data Factory using date as a parameter. However, the system presents the following error: [enter image description here](https://i.stack.imgur.com/gbUuX.png) And I wanted to pass a date in variable format that always collects the current day and sets it in the variable {vi}, and the day following {vi} in {vf}. However, I can't get the system to work even by passing the dates in a fixed way as shown in the example below: [enter image description here](https://i.stack.imgur.com/3WVwt.png) However, I get this error: [enter image description here](https://i.stack.imgur.com/LoV3b.png) Does anyone have any ideas on how I should proceed in this case?
Difficulty creating a data pipeline with Fabric Datafactory using REST
|azure|rest|azure-pipelines|azure-data-factory|fabric|