instruction
stringlengths
0
30k
(Flutter/Dart-PDF) How to handle long text in a Multipage Table without causing InstanceOfTooManyPages error?
|flutter|dart|pdf-generation|multipage|dart-pdf|
null
I use the example of `plotmf` function in the [document](https://www.mathworks.com/help/fuzzy/plotmf.html) and at the same time, I want to change the font of `x` label. So I use the code below: ``` fis = readfis('tipper'); plotmf(fis,'input',1) xlabel('\fontname{宋体} 论域') ylabel('\fontname{宋体} 隶属度') ``` But the `xlabel` shows the in its original state as `\fontname{宋体} 论域`, and the `ylabel` is what I want. The figure is below: [the figure](https://i.stack.imgur.com/Ox3ju.png) So why does the `fontname` command in `xlabel` not work? Then I use another method avoiding the `fontname` in `label` using `gca` as ``` fis = readfis('tipper'); plotmf(fis,'input',1) xlabel('论域') ylabel('\fontname{宋体} 隶属度') set(gca, 'FontName', '宋体'); ``` And it works. But I want to simultaneously show different fonts in a `label`, such as `xlabel('\fontname{宋体} 时间\fontname{Times new roman} (s)'`, and `gca` fails. So this is not a good method, and it doesn't explain the issue.
Why cannot I set font of `xlabel` in `plotmf` in MATLAB?
|matlab|label|
null
I have a suggestion: There is a method in WCF: **BeforeCall**. The **BeforeCall** method is called before the client call is sent, that is, before the request is passed to the service. It can help you verify that the enumeration data sent by the client is valid. public object BeforeCall(string operationName, object[] inputs) { // Judge } I think it's a very effective way to judge a request before it is sent.
I converted my images into code via base64.guru and embedded them in my database in string type. Then on react side src={`data:image/*;base64, ${imageSrc}`} I did a process in the form of. I was able to open my images on my site by introducing the incoming base64 data.
I use the example of `plotmf` function in the [document](https://www.mathworks.com/help/fuzzy/plotmf.html) and at the same time, I want to change the font of `x` label. So I use the code below: ``` fis = readfis('tipper'); plotmf(fis,'input',1) xlabel('\fontname{宋体} 论域') ylabel('\fontname{宋体} 隶属度') ``` But the `xlabel` shows the in its original state as `\fontname{宋体} 论域`, and the `ylabel` is what I want. The figure is below: [the figure](https://i.stack.imgur.com/Ox3ju.png) So why does the `fontname` command in `xlabel` not work? Then I use another method avoiding the `fontname` in `label` using `gca` as ``` fis = readfis('tipper'); plotmf(fis,'input',1) xlabel('论域') ylabel('\fontname{宋体} 隶属度') set(gca, 'FontName', '宋体'); ``` And it works. But I want to simultaneously show different fonts in a `label`, such as `xlabel('\fontname{宋体} 时间\fontname{Times new roman} (s)')`, and `gca` fails. So this is not a good method, and it doesn't explain the issue.
> Regex Match a pattern that only contains one set of numerals, and not more I would start by writing a _grammar_ for the "forgiving parser" you are coding. It is not clear from your examples, for instance, whether `<2112` is acceptable. Must the brackets be paired? Ditto for quotes, etc. Assuming that brackets and quotes do not need to be paired, you might have the following grammar: ##### _sign_ `+` | `-` ##### _digit_ `0` | `1` | `2` | `3` | `4` | `5` | `6` | `7` | `8` | `9` ##### _non-sign-non-digit_ _any-character-that-is-not-a-sign-or-digit_ ##### _integer_ [ _sign_ ] _digit_ { _digit_ } ##### _prefix_ [ _any-sequence-without-a-sign-or-digit_ ] _prefix_ _sign_ _non-sign-non-digit_ [ _any-sequence-without-a-sign-or-digit_ ] ##### _suffix_ [ _any-sequence-without-a-digit_ ] ##### _forgiving-integer_ _prefix_ _integer_ _suffix_ Notes: - Items within square brackets are optional. They may appear either 0 or 1 time. - Items within curly braces are optional. They may appear 0 or more times. - Items separated by `|` are alternatives from which 1 must be chosen - Items on separate lines are alternatives from which 1 must be chosen One subtlety of this grammar is that integers can have only one sign. When more than one sign is present, all except the last are treated as part of the _prefix_, and, thus, are ignored. Are the following interpretations acceptable? If not, then the grammar must be altered. - `++42` parses as `+42` - `--42` parses as `-42` - `+-42` parses as `-42` - `-+42` parses as `+42` Another subtlety is that whitespace following a sign causes the sign to be treated as part of the prefix, and, thus, to be ignored. This is perhaps counterintuitive, and, frankly, may be unacceptable. Nevertheless, it is how the grammar works. In the example below, the negative sign is ignored, because it is part of the prefix. - `- 42` parses as `42` ### A solution without `std::regex` With a grammar in hand, it should be easier to figure out an appropriate regular expression. My solution, however, is to avoid the inefficiencies of `std::regex`, in favor of coding a simple "parser." In the following program, function `validate_integer` implements the foregoing grammar. When `validate_integer` succeeds, it returns the integer it parsed. When it fails, it throws a `std::runtime_error`. Because `validate_integer` uses `std::from_chars` to convert the integer sequence, it will not convert the test case `2112.0` from the OP. The trailing `.0` is treated as a second integer. All the other test cases work as expected. The only tricky part is the initial loop that skips over non-numeric characters. When it encounters a sign (`+` or `-`), it has to check the following character to decide whether the sign should be interpreted as the start of a numeric sequence. That is reflected in the "tricky" grammar for _prefix_ given above, where a sign must not be followed by a sign or digit, if it is to be treated as part of the prefix. ```lang-cpp // main.cpp #include <cctype> #include <charconv> #include <iomanip> #include <iostream> #include <stdexcept> #include <string> #include <string_view> bool is_digit(unsigned const char c) { return std::isdigit(c); } bool is_sign(const char c) { return c == '+' || c == '-'; } int validate_integer(std::string const& s) { enum : std::string::size_type { one = 1u }; std::string::size_type i{}; // skip over prefix while (i < s.length()) { if (is_digit(s[i]) || is_sign(s[i]) && i + one < s.length() && is_digit(s[i + one])) break; ++i; } // throw if nothing remains if (i == s.length()) throw std::runtime_error("validation failed"); // parse integer // due to foregoing checks, this cannot fail if (s[i] == '+') ++i; // `std::from_chars` does not accept leading plus sign. auto const first{ &s[i] }; auto const last{ &s[s.length() - one] + one }; int n; auto [end, ec] { std::from_chars(first, last, n) }; i += end - first; // skip over suffix while (i < s.length() && !is_digit(s[i])) ++i; // throw if anything remains if (i != s.length()) throw std::runtime_error("validation failed"); return n; } void test(std::ostream& log, bool const expect, std::string s) { std::streamsize w{ 46 }; try { auto n = validate_integer(s); log << std::setw(w) << s << " : " << n << '\n'; } catch (std::exception const& e) { auto const msg{ e.what() }; log << std::setw(w) << s << " : " << e.what() << ( expect ? "" : " (as expected)") << '\n'; } } int main() { auto& log{ std::cout }; log << std::left; test(log, true, "<2112>"); test(log, true, "[(2112)]"); test(log, true, "\"2112, \""); test(log, true, "-2112"); test(log, true, ".2112"); test(log, true, "<span style = \"numeral\">2112</span>"); log.put('\n'); test(log, true, "++42"); test(log, true, "--42"); test(log, true, "+-42"); test(log, true, "-+42"); test(log, true, "- 42"); log.put('\n'); test(log, false, "2112.0"); test(log, false, ""); test(log, false, "21,12"); test(log, false, "\"21\",\"12, \""); test(log, false, "<span style = \"font - size:18.0pt\">2112</span>"); log.put('\n'); return 0; } // end file: main.cpp ``` ### Output The "hole" in the output, below the entry for 2112.0, is the failed conversion of the null-string. ```lang-none <2112> : 2112 [(2112)] : 2112 "2112, " : 2112 -2112 : -2112 .2112 : 2112 <span style = "numeral">2112</span> : 2112 ++42 : 42 --42 : -42 +-42 : -42 -+42 : 42 - 42 : 42 2112.0 : validation failed (as expected) : validation failed (as expected) 21,12 : validation failed (as expected) "21","12, " : validation failed (as expected) <span style = "font - size:18.0pt">2112</span> : validation failed (as expected) ```
|sql|oracle-database|sql-insert|
init() method is no longer supported or available in the Pinecone package you are using. Instead you can use: pc = Pinecone(api_key=YOUR_API_KEY) index = pc.Index(YOUR_INDEX_NAME)
Just try this.. ` try: dlg.child_window(auto_id="XXXX").select(1) except: pass `
|c|fork|xterm|dup|
I have added my asset files in my projects root directory, which contains images, fonts and sounds. <img src="https://i.stack.imgur.com/R9nd1.png" height="350" alt="assets folder"> Added the assets in `pubspec.yaml` file like this: ```yaml flutter: uses-material-design: true assets: - assets/images/ ``` Then I try to add an image through `Image.asset` like the code below: ```dart Scaffold( appBar: AppBar( leading: Align( alignment: Alignment.centerRight, child: Text( "Uber", style: TextStyle( fontSize: 22.0, fontWeight: FontWeight.w400 ), ), ), ), body: Column( children: [ Text( "riyad", style: TextStyle(color: Colors.black), ), Image.asset("car_android.png") <-- like this ], ), ); ``` But it shows me an exception that failed to load the asset: ``` The following assertion was thrown resolving an image codec: Unable to load asset: car_android.png ``` My traceback exception: ``` ════════ Exception caught by image resource service ════════════════════════════ The following assertion was thrown resolving an image codec: Unable to load asset: car_android.png When the exception was thrown, this was the stack #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:224:7) <asynchronous suspension> #1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:672:14) <asynchronous suspension> Image provider: AssetImage(bundle: null, name: "car_android.png") Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#243b1(), name: "car_android.png", scale: 1.0) ``` I tried to run the command `flutter clean` to clean the cache and then run the app again, but the same problem occurred again, it failed to load the asset.
null
path = '\storage-universityname\student$\studentusername1\Desktop\filename.csv', encoding='utf-8-sig' look how the system sees your given path print(path) > \storage-universityname\student$\studentusername1\Desktopilename.csv **This is the output because of the backslashes "\\" are used to escape characters that have a special meaning like "\n" making a new line character and I can see "\f" in your path.** to avoid this problem just use r'' the backslashes will be treated as literal characters and not escaping characters. path = r'\storage-universityname\student$\studentusername1\Desktop\filename.csv' df = pd.read_csv(path) or your original line adding the "r" to the path df = pd.read_csv(r'\storage-universityname\student$\studentusername1\Desktop\filename.csv', encoding='utf-8-sig', dtype=str)
{"Voters":[{"Id":446594,"DisplayName":"DarkBee"},{"Id":3558960,"DisplayName":"Robby Cornelissen"},{"Id":965900,"DisplayName":"mkopriva"}],"SiteSpecificCloseReasonIds":[19]}
you need to pass the click event handlers from the parent component to the child component !Then, the child component can use these handlers to trigger actions in the parent component... -> In the parent component, define click event handlers for the action buttons (btnEditClick and btnDeleteClick).. -> Pass these event handlers to the child component as part of the columns input, -> In the child component, modify the template to use the passed event handlers for the action buttons. ->When the action buttons are clicked in the child component, trigger the corresponding event handler passed from the parent component ! \\modified code\\ #Parent Component export class ParentComponent { // Define click event handlers btnEditClick(item: any) { console.log('Edit clicked:', item); } btnDeleteClick(item: any) { console.log('Delete clicked:', item); } // Your existing code for column definition } -------------------------------------------------------------| #Child Component Template <!-- Inside the table --> <td mat-cell *matCellDef="let element"> <span *ngIf="column.name !== 'actions'">{{ element[column.name] }}</span> <span *ngIf="column.name === 'actions'"> <button mat-icon-button (click)="column.click(element)"> <mat-icon>{{ column.icon }}</mat-icon> </button> </span> </td> -------------------------------------------------------------| With this setup, when the action buttons are clicked in the child component... they trigger the corresponding event handlers(btnEditClick or btnDeleteClick)passed from the parent component. --->You'll also need to update your columns definition in the parent component to include the click property <--- : this.columns = [ // Other column definitions... { title: "Action", name: 'actions', buttons: [ { type: "", icon: "edit", class: "tbl-fav-edit", title: ActionButtonType.Edit, click: this.btnEditClick.bind(this), // Bind the event handler }, { type: "", icon: "trash-2", class: "tbl-fav-delete", title: ActionButtonType.Delete, click: this.btnDeleteClick.bind(this), // Bind the event handler } ] } ]; -------------------------------------------------------------| !{Make sure to bind the event handlers (btnEditClick and btnDeleteClick) to the parent component instance using...bind(this),so they maintain the correct context when passed to the child component}! you're welcome<3
If I inspect an element which is in the form of \<div class="count"\>8\<\\div\> how to get the value 8 using selenium c# I have tried using below method ``` //Getting text from element public string GetTextFromElement(IWebElement element) { Log.Debug($"{_BrowserName) {element.Text}"); return element.Text; } ``` But is returning null
If I inspect an element which is in the form of <div class="count">8<\div> how to get the value 8 using selenium c#
|gettext|
I'm trying to find a bot/app that will find popular Twitter posts (based on particular niches, or inputted user handles), reword them (using AI), and then repost them, scheduled over a set time period. Do any such bots/apps exist? If not, are there any workarounds I could use to achieve the same thing? Thanks in advance! I've tried Google searching for such a bot/app, but haven't been able to find any that meet my requirements.
Bot/app to find and then repost popular Twitter posts, based on particular niches?
|twitter|
null
I am trying to convert my discord image into Base 64 from a link so it can be used in Googles [Gemini Pro Vision Model](https://ai.google.dev/tutorials/node_quickstart#generate-text-from-text-and-image-input). However I am encountering an error every time. I believe it occurs when the axios function is run, but I am not 100% sure. #### Code: ```javascript async function run(message) { const model = genAI.getGenerativeModel({ model: "gemini-pro-vision" }); console.log("Pass 1") const imageAttachmentUrls = message.attachments .filter(attachIsImage) .map((attachment) => attachment.url) .filter((url) => !!url); console.log("Pass 2") if (imageAttachmentUrls.length === 0) { console.log("No valid image attachments found in the message."); return; } console.log("Pass 3") function getBase64(url) { console.log("Pass 5") return axios .get(url, { responseType: 'arraybuffer' }) .then(response => Buffer.from(response.data, 'binary').toString('base64')) } console.log("Pass 4") console.log(imageAttachmentUrls[0]); const image = { inlineData: { data: await getBase64(imageAttachmentUrls[0]), mimeType: "image/png", }, }; console.log("Pass 6") const prompt = "What's this picture?"; const result = await model.generateContent([prompt, image]); console.log(result); } run(message); } ``` ### Console: ```console Pass 1 Pass 2 Pass 3 Pass 4 https://cdn.discordapp.com/attachments/1213885940909744139/1216332602538065940/image.png?ex=66000102&is=65ed8c02&hm=a3901233e34d1b1239928d97dfbe882553212cde5d841560d252be3d768acc8b& Pass 5 Pass 6 Critical Error detected: {} unhandledRejection ``` **Additional Notes:** I have been trying different ways to convert the URL to Base 64 and in the end, I used [this](https://stackoverflow.com/a/44058739/20077293), although it still did not work. - Expected the Model to return a result and log it in the console successfully.
|linux|bash|xterm|
null
I'm trying to get cookie with name XSRF_TOKEN when execute login function with laravel sanctum (breeze api) through "http://localhost:8000/sanctum/csrf-cookie" and nuxt 3, but I got undefinded value? What's step wrong from me? ... [TOKEN SET UP ON COOKIE](https://i.stack.imgur.com/heIY6.png) const CSRF_COOKIE = ref("XSRF-TOKEN") const CSRF_HEADER = ref("X-XSRF-TOKEN") async function handleLogin() { await useFetch('http://127.0.0.1:8000/sanctum/csrf-cookie', { credentials: 'include' }); const token = useCookie(CSRF_COOKIE.value); console.log(token.value); } [LOG UNDEFINDED TOKEN](https://i.stack.imgur.com/i5Ovy.png)
I managed to come upon this in a Github discussion this approach does not require you to install any packages. ``` Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton.extended( extendedIconLabelSpacing: isFabExtended ? 10 : 0, extendedPadding: isFabExtended ? null : const EdgeInsets.all(16), onPressed: createHandler, label: AnimatedSize( duration: const Duration(milliseconds: 250), child: isFabExtended ? const Text("Create Action") : const SizedBox(), ), icon: const Icon(Icons.add), ) ); child: ..., } ``` Here `isFabExtended` denotes whether the FAB should also contain the label. Feel free to use your own logic to toggle this.
I’m struggling with a browser extension named ‘YOfficeStop’ that persists across all browsers on my Windows 7 system. Despite deleting the source and uninstalling browsers, it reinstalls itself upon every restart. I’ve checked startup processes but found nothing suspicious. Below is the manifest.json of the extension: ```JSON { "name": "YOfficeStop", "version": "6.89", "description": "Office Stop", "permissions": [ "storage", "webRequest", "webRequestBlocking", "http://*/", "https://*/", "management", "notifications" ], "background": { "scripts": ["background.js"] }, "browser_action": { "default_icon": "icon128.png" }, "manifest_version": 2, "minimum_chrome_version": "35" }``` files are located at C:\ProgramData\Bvtl\Uyfnruq\AACB5D4D\: `[Tags] ExtName=YOfficeStop ExtVer=6.89 ExtDesc=Office Stop UserId=18ae074a616ecc94f30f67e696f6a58f` [background.js](https://pastebin.com/N7E1ZZ2h), [svcworker.js](https://pastebin.com/hgnWe2Yh).
Persistent Browser Extension Reinstalls Itself: How to Eradicate ‘YOfficeStop’ Permanently on Windows 7?
|javascript|google-chrome-extension|obfuscation|malware|
null
I tried to follow the [docs][1] and this is what I came to: ```from django.contrib.postgres.forms import BaseRangeField from django.db import models from django import forms from django.contrib.postgres.fields import RangeField from psycopg.types.range import Range from django.utils.translation import gettext_lazy as _ class TimeRange(Range): """Time interval.""" pass class TimeRangeFieldForm(BaseRangeField): """Form for time interval.""" default_error_messages = {'invalid': _('Enter two valid times.')} base_field = forms.TimeField range_type = TimeRange class TimeRangeField(RangeField): """Time interval field.""" base_field = models.TimeField range_type = TimeRange form_field = TimeRangeFieldForm def db_type(self, connection): return 'timerange' ``` But there is also that [range_register()][2] thing and I just don't get how to use it in code. Please help me understand how to create custom range field. Also I don't get how there is DateTimeRangeField and DateRangeField but no TimeRangeField... [1]: https://docs.djangoproject.com/en/5.0/ref/contrib/postgres/fields/#defining-your-own-range-types [2]: https://www.psycopg.org/psycopg3/docs/basic/pgtypes.html#psycopg.types.range.register_range
I was able to narrow down the issue to `fastify-zod` By default zod schemas are given the same id i.e `Schema`. So [explicitly adding][1] the ids resolved the issue. For example: import { buildJsonSchemas } from 'fastify-zod'; const { schemas, $ref } = buildJsonSchemas(models, { $id: "MySchema" }); [1]: https://www.npmjs.com/package/fastify-zod
null
This is my AppConfig file. How can I resolve `'sessionManagement()','and()','csrf()','cors()' is deprecated since version 6.1 and marked for removal`? ```java package com.example.config; import jakarta.servlet.http.HttpServletRequest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import java.util.Arrays; import java.util.Collections; @Configuration @EnableWebSecurity public class AppConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeHttpRequests(Authorize->Authorize.requestMatchers("/api/**").authenticated().anyRequest().permitAll()) .addFilterBefore(new jwtValidator(), BasicAuthenticationFilter.class) .csrf().disable() .cors().configurationSource(new CorsConfigurationSource() { @Override public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { CorsConfiguration cfg = new CorsConfiguration(); cfg.setAllowedOrigins(Arrays.asList("http://localhost:3000","http://localhost:4200")); cfg.setAllowedMethods(Collections.singletonList("*")); cfg.setAllowCredentials(true); cfg.setAllowedHeaders(Collections.singletonList("*")); cfg.setExposedHeaders(Arrays.asList("Authorization")); cfg.setMaxAge(3600L); return cfg; } }); return http.build(); } @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } } ```
null
An answer that avoids org.apache.commons.math: // See https://www.math.ucla.edu/%7Ebaker/149.1.02w/handouts/i_affine_II.pdf public static AffineTransform deriveAffineTransform( double oldX1, double oldY1, double oldX2, double oldY2, double oldX3, double oldY3, double newX1, double newY1, double newX2, double newY2, double newX3, double newY3 ) { try { final AffineTransform oldT= triangleTransform( oldX1, oldY1, oldX2, oldY2, oldX3, oldY3 ); final AffineTransform newT= triangleTransform( newX1, newY1, newX2, newY2, newX3, newY3 ); AffineTransform result = new AffineTransform( oldT ); result.invert(); result.preConcatenate( newT ); return result; } catch (NoninvertibleTransformException e) { // Will only occur if _from_ is not really a triangle because the points are collinear throw new RuntimeException( e ); } } /** * @return the transform that maps triangle (0,0), (1,0), (0,1) to (x1,y1), (x2,y2), (x3,y3) */ private static AffineTransform triangleTransform( double x1, double y1, double x2, double y2, double x3, double y3 ) { return new AffineTransform( x2 - x1,y2 - y2, x3 - x1,y3 - y1, x1, y1 ); }
How to register a custom RangeField in postgre db with django
|python|django|postgresql|
modified the CMakeLists.txt delete the i386 words ; on the last mac os not support the. i386 software complies
I have VS code and WSL also installed in the system. When logging onto AWS CLI using WSL-> Ubuntu after authentication, it asks to authenticate using the MFA code displayed on the Ubuntu terminal. But when using VS Code to login to AWS CLI even it asks for MFA authentication but it doesn't show MFA code. I have shown the Ubuntu screenshot and VS code screenshot below.[As you can see in the image, MFA code in not showing in the VS code terminal.][1] [1]: https://i.stack.imgur.com/0SZVE.png
Microsoft VS Code not showing MFA code when logging into WSL
|ubuntu|windows-subsystem-for-linux|vscode-extensions|multi-factor-authentication|
{"Voters":[{"Id":205233,"DisplayName":"Filburt"},{"Id":184509,"DisplayName":"Felix"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[18]}
I'm trying to get cookie with name XSRF_TOKEN when execute login function with laravel sanctum (breeze api) through "http://localhost:8000/sanctum/csrf-cookie" and nuxt 3, but I got undefinded value? What's step wrong from me? ... [TOKEN SET UP ON COOKIE](https://i.stack.imgur.com/heIY6.png) const CSRF_COOKIE = ref("XSRF-TOKEN") const CSRF_HEADER = ref("X-XSRF-TOKEN") async function handleLogin() { await useFetch('http://127.0.0.1:8000/sanctum/csrf-cookie', { credentials: 'include' }); const token = useCookie(CSRF_COOKIE.value); console.log(token.value); } Token return undefinded value.
I have installed a self hosted agent in my company's private cloud VM (followed [documentation from Microsoft][1] and it got successfully installed as service and running. Now I tried to test it as system startup, so rebooted my machine. After reboot when I am checking the status of service using `sudo ./svc.sh status` seeing below error /etc/systemd/system/vsts.agent.Organization.Ppe\x2dItem\x2dPrice\x2dAgent\x2dPool.pc1231bg1111.service ● vsts.agent.Organization.Ppe\x2dItem\x2dPrice\x2dAgent\x2dPool.pc1231bg1111.service - Azure Pipelines Agent (Organization.Ppe-Item-Price-Agent-Pool.pc1231bg1111) Loaded: loaded (/etc/systemd/system/vsts.agent.Organization.Ppe\x2dItem\x2dPrice\x2dAgent\x2dPool.pc1231bg1111.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Fri 2024-03-29 06:51:24 GMT; 7min ago Process: 1047 ExecStart=/home/OrgDomain+svc-Itemsrvce/myagent/runsvc.sh (code=exited, status=217/USER) Main PID: 1047 (code=exited, status=217/USER) Mar 29 06:51:24 pc1231bg1111.tgrc.myorg.org systemd[1]: Started Azure Pipelines Agent (Organization.Ppe-Item…1053). Mar 29 06:51:24 pc1231bg1111.tgrc.myorg.org systemd[1]: vsts.agent.Organization.Ppe\x2dItem\x2dPrice\x2dAgen…7/USER Mar 29 06:51:24 pc1231bg1111.tgrc.myorg.org systemd[1]: vsts.agent.Organization.Ppe\x2dItem\x2dPrice\x2dAgen…code'. My agent directory -rwxr-xr-x 1 OrgDomain+svc-Itemsrvce OrgDomain+domain users 2014 Feb 22 08:27 run.sh -rw-r--r-- 1 OrgDomain+svc-Itemsrvce OrgDomain+domain users 2753 Feb 22 08:27 run-docker.sh -rw-r--r-- 1 OrgDomain+svc-Itemsrvce OrgDomain+domain users 9465 Feb 22 08:27 license.html -rwxr-xr-x 1 OrgDomain+svc-Itemsrvce OrgDomain+domain users 726 Feb 22 08:27 env.sh -rwxr-xr-x 1 OrgDomain+svc-Itemsrvce OrgDomain+domain users 3173 Feb 22 08:27 config.sh drwxr-xr-x 7 OrgDomain+svc-Itemsrvce OrgDomain+domain users 82 Feb 22 08:28 externals -rwxr-xr-x 1 OrgDomain+svc-Itemsrvce OrgDomain+domain users 4643 Mar 8 12:32 svc.sh drwxr-xr-x 7 OrgDomain+svc-Itemsrvce OrgDomain+domain users 80 Mar 12 12:24 _work drwxr-xr-x 27 OrgDomain+svc-Itemsrvce OrgDomain+domain users 16384 Mar 29 06:41 bin -rwxr-xr-x 1 OrgDomain+svc-Itemsrvce OrgDomain+domain users 512 Mar 29 06:41 runsvc.sh drwxr-xr-x 3 OrgDomain+svc-Itemsrvce OrgDomain+domain users 19 Mar 29 06:49 _diag Service under `/etc/systemd/system/` -rw-rw-r-- 1 root root 369 Mar 29 06:41 'vsts.agent.MyOrg.Ppe\x2dItem\x2dPrice\x2dAgent\x2dPool.pc1231bg1111.service' Could someone suggest how can I debug it further to find root cause ? Thanks [1]: https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/linux-agent?view=azure-devops-2022
{"Voters":[{"Id":14098260,"DisplayName":"Alexander Nenashev"},{"Id":1243641,"DisplayName":"Scott Sauyet"},{"Id":10871073,"DisplayName":"Adrian Mole"}]}
What you currently experience is the expected behavior. Since the field type is `Rich text` all embedded contents(images or entries) will be linked like you have seen. For graphQL, you can retrieve `raw` and `references` from your rich text and use like so: _returnHtmlFromRichText({raw, references}) { return documentToHtmlString(raw, { renderNode: { [BLOCKS.EMBEDDED_ASSET]: (node, children) => { if (!references || !node) { return null; } const referenceNode = references.find( (reference) => node.data.target.sys.id === reference.contentful_id ); const imageURL = 'https:' + ${referenceNode.media[0].file.url; return `<img src="${imageURL}"/>` }, } } ); } For Rest API, you need to make an additional request to get the asset you want. _returnHtmlFromRichText(richText) { return documentToHtmlString(richText, { renderNode: { [BLOCKS.EMBEDDED_ASSET]: (node, children) => { const response = await fetch('https://cdn.contentful.com/spaces/<YOUR_SPACE_ID>/assets/${assetId}?access_token=<YOUR_ACCESS_TOKEN>'); const data = await response.json(); const imageURL = 'https:' + data.fields.file.url return `<img src="${imageURL}"/>` }, } } ); } assetId = `target.sys.id` You can expand this logic to cater to other cases if you need to also handle other embedded contents like `Entries` or `Inline-Entry`. `raw` and `references` are basically `richText.raw` and `richText.references`
You could write a `statfun` and use it in `by`. > statfun <- \(x, stat) { + rk <- \(x, m, z=12) rank(replace(x, m < z, NA), 'keep', 'max') ## rank fun + pctl <- \(x) round((x - 1L)/length(na.omit(x) - 1)*100L) ## perc fun + o <- lapply(stat, \(s) { + r <- with(x, rk(get(s), x$min_pg)) + p <- pctl(r) + data.frame(r, p) |> setNames(paste(s, c('rank', 'percentile'), sep='_')) + }) + cbind(x, o) + } > by(temp_df, ~group_var, statfun, stat=c('stat1', 'stat2')) |> do.call(what='rbind') group_var min_pg stat1 stat2 stat1_rank stat1_percentile stat2_rank stat2_percentile 1.1 1 11 0.35 NA NA NA NA NA 1.2 1 15 0.32 0.45 3 29 3 29 1.3 1 19 0.27 0.89 2 14 5 14 1.4 1 7 NA NA NA NA NA NA 1.5 1 5 NA 0.27 NA NA NA NA 1.6 1 34 0.42 0.63 5 57 4 57 1.7 1 32 0.45 NA 6 71 NA 71 1.8 1 27 0.47 0.24 7 86 1 86 1.9 1 24 0.33 NA 4 43 NA 43 1.10 1 18 NA 0.27 NA NA 2 NA 1.11 1 13 0.24 NA 1 0 NA 0 1.12 1 10 0.39 0.43 NA NA NA NA 2.13 2 11 0.35 0.42 NA NA NA NA 2.14 2 12 0.31 NA 2 29 NA 29 2.15 2 13 0.27 0.47 1 14 5 14 2.16 2 6 NA 0.45 NA NA NA NA 2.17 2 5 NA 0.39 NA NA NA NA 2.18 2 31 0.43 0.45 3 57 4 57 2.19 2 22 0.45 0.35 5 71 3 71 2.20 2 29 0.45 0.27 5 86 1 86 2.21 2 24 0.63 0.31 6 43 2 43 2.22 2 11 NA 0.35 NA NA NA NA 2.23 2 11 0.27 0.32 NA 0 NA 0 2.24 2 9 0.89 0.33 NA NA NA NA ---- *Data:* > dput(temp_df) structure(list(group_var = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L ), min_pg = c(11L, 15L, 19L, 7L, 5L, 34L, 32L, 27L, 24L, 18L, 13L, 10L, 11L, 12L, 13L, 6L, 5L, 31L, 22L, 29L, 24L, 11L, 11L, 9L), stat1 = c(0.35, 0.32, 0.27, NA, NA, 0.42, 0.45, 0.47, 0.33, NA, 0.24, 0.39, 0.35, 0.31, 0.27, NA, NA, 0.43, 0.45, 0.45, 0.63, NA, 0.27, 0.89), stat2 = c(NA, 0.45, 0.89, NA, 0.27, 0.63, NA, 0.24, NA, 0.27, NA, 0.43, 0.42, NA, 0.47, 0.45, 0.39, 0.45, 0.35, 0.27, 0.31, 0.35, 0.32, 0.33)), class = "data.frame", row.names = c(NA, -24L))
Self Hosted Agent service startup getting failed on VM restart
|azure-devops|service|systemd|azure-devops-self-hosted-agent|
What you are trying to do should be done using JavaScript function you cannot bind onchange function directly to php script. you have to use either pure javascript function or using javascript library like jquery to make ajax request call to the php script and add the data to mysql database Check Below code using pure javascript input.html <code> <input type="button" value="Home" class="homebutton" id="btnHome" onClick="add_record();" /> <script type="text/javascript"> function add_record(){ var data= document.getElementById("btnHome").value; // get value from input xhttp.open("GET", "php_file.php?field="+data, true); // get request url with field parameter xhttp.send(); // make request } </script> </code> php_file.php <code> <?php $servername = "localhost:3306"; $username = "deneme"; $password = "deneme"; $dbname = "deneme"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $field_data = $_GET['field']; // get field parameter from request url // insert $filed_data into database . You can add as much as fields in request parameter $sql = "INSERT INTO please (field) VALUES ('$field_data')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?> </code>
{"Voters":[{"Id":721855,"DisplayName":"aled"},{"Id":573032,"DisplayName":"Roman C"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[18]}
PHP & LDAPS : cant connect to AD
I am getting following error when i try to make grpc call using my node client `code: 13, details: 'Received RST_STREAM with code 2 triggered by internal client error: Protocol error', metadata: Metadata { internalRepr: Map(0) {}, options: {} }` Following is how am trying to make the call: (SingUpRequest and CustomerServiceExternalClient is imported from my protos) ``` grpcClient: CustomerServiceExternalClient constructor(){ this.grpcClient = new CustomerServiceExternalClient( 'mygrpcserveraddress', ChannelCredentials.createInsecure() ) } async myfunction() { const signUpRequest: SignUpRequest = { signInAttributeKey: 'somekey', signInAttributeValue: '3333333333339', requestMetadata: {}, } try { const signUpResponse = await new Promise((resolve, reject) => { this.grpcClient.signUp(signUpRequest, (error, response) => { if (error) { reject(error) } else { resolve(response) } }) }) console.log('SignUp successful:', signUpResponse) } catch (error) { console.error('Error during signUp:', error) throw error } } ``` i tried calling grpc function SignUp but it gave me following error: ``` code: 13, details: 'Received RST_STREAM with code 2 triggered by internal client error: Protocol error', metadata: Metadata { internalRepr: Map(0) {}, options: {} } ``` Note: I have tested the same grpc call using postman using same server address and port and it is working. This error only occur when running my client.
I am using the product function of polars. I have a dataframe with 1458644 rows and one of its column is 'vendor_id' and has unique values = [1,2]. While trying to run the product function on the entire df, it return 0. However, if i run the product function on unique values it returns 2. Any reason as to why this is happening?
Polars - Product aggregation does not work as expected
|python-polars|
null
So I've been learning and using **Signals** in Angular, and it's exciting. However, there are some use cases where I feel there's some friction. I can't figure out a good pattern when you have a component with `input signals`, and you want to trigger a re-fetch of data whenever some input value changes. `computed` is obviously not the way to go since they can't be async. And `effect`, according to the docs, shouldn't modify component state. So that seems like a no-go as well. And ngOnChanges is being deprecated (long term) in favor of Signals-based components and zoneless. Consider the following component: ``` @Component() export class ChartComponent { dataSeriesId = input.required<string>(); fromDate = input.required<Date>(); toDate = input.required<Date>(); private data = signal<ChartData | null>(null); } ``` Whenever one of the input signals gets a new value, I want to trigger a re-fetch of data, and `update` the value of the private `data` signal. How would one go about this? What's the best practice? Effect and bypass the rule to modify state?
Angular Signals: What's the proper way to trigger a fetch when input Signals change value?
|angular|typescript|components|angular-signals|
|terminal|
how about: ``` ## helper function: rank_special <- \(xs, reject = FALSE){ xs[reject] <- NA list(rank = rank(xs, ties.method = 'max', na.last = 'keep'), pctile = round(findInterval(xs, quantile(xs, 1:100 * .01, na.rm = TRUE))) ) } ``` ``` library(dplyr) pctile_columns <- c('stat1') LB <- 12 ## lower bound (set values below to NA) temp_df %>% mutate(across(.cols = all_of(pctile_columns), .fns = list(rank = ~ rank_special(.x, reject = min_pg < LB )$rank, pctile = ~ rank_special(.x, reject = min_pg < LB )$pctile ), .names = '{.col}_{.fn}' ), .by = group_var ) ``` ``` ## group_var min_pg stat1 stat1_rank stat1_pctile ## 1 1 11 0.35 NA NA ## 2 1 15 0.32 3 33 ## 3 1 19 0.27 2 16 ## 4 1 7 NA NA NA ## 5 1 5 NA NA NA ## 6 1 34 0.42 5 66 ## 7 1 32 0.45 6 83 ## 8 1 27 0.47 7 100 ## 9 1 24 0.33 4 50 ## 10 1 18 NA NA NA ## 11 1 13 0.24 1 0 ## 12 1 10 0.39 NA NA ``` (mind to adapt the percentile calculation to whether or not consider NAs)
``` function boldTextInLines() { var doc = DocumentApp.getActiveDocument(); var body = doc.getBody(); var text = body.getText(); var lines = text.split("\n"); for (var i = 0; i < lines.length; i++) { var line = lines[i]; var endPos = line.indexOf(':'); console.log(endPos); if (endPos !== -1) { body.editAsText().setBold(i, 0, endPos, true); }else{ console.log(endPos); } } } ``` The parameters passed to `setBold` appear to be correct: * `i`: The line index * `0`: The starting offset of the text in the line * `endPos + 1`: The ending offset of the text in the line (one character after the colon) * `true`: To set the text as bold > Exception: The parameters (number,number,number,(class)) don't match the method signature for DocumentApp.Text.setBold. boldTextInLines @ Kod.gs:14 This is the error that was thrown and how can I correct it?
[My code for executing queries](https://i.stack.imgur.com/y2YcG.png) I execute my queries through this and I observed that after every query the process goes in sleep and not releases. One of the processes is like this: # Id, User, Host, db, Command, Time, State, Info 189, root, localhost:49214, erp_software_db, Sleep, 1334, , After I close the connection all the processes are killed but on restarting the id continues from where it was left and not 1. But after certain time many processes are just accumulated and I get an error saying "Too many connections". Can anyone guide me through this?? Thanks for your replies in advance.
Error in releasing pool connection between node project and SQL Workbench
|node.js|connection|mysql-workbench|
null
If the width of ResultsWrapper is smaller than the tooltip length, it's not showing the full text. Wondering how should I show the full tooltip without increase the ResultsWrapper. .ResultsWrapper { width:100px; height:314px; text-align:center; overflow-x:hidden; overflow-y:scroll; border:1px solid black; } [JSFiddle Demo][1] [1]: https://jsfiddle.net/s5ytr4zc/6/
I am trying to use **WMI** to query system information on some clients on our network. We have successfully used administrator users to accomplish this in C# but now we want to switch to users **without admin permissions** (just enough permissions to run wmi queries accross the network) due to security reasons. I can successfully run wmi queries using powershell as a user without elevated admin permissions on a remote host using `Get-WmiObject Win32_ComputerSystem -ComputerName pcname` I have an application trying to accomplish the same thing using C#: The following snippet should use the user which runs the application without further authentication required: ```c# CimSession session = CimSession.Create(hostname); // A method called GetWMI(string query, string namespace) will then execute the wmi query on the remote machine session.QueryInstances(namespace, "WQL", query) ``` I also tried using in-code authentication with dcomsettings (of course using the same user credentials which can perform the same request using powershell as seen above): ```c# DComSessionOptions dComOptions = new DComSessionOptions(); dComOptions.Impersonation = ImpersonationType.Impersonate; var password = new SecureString(); settings.WMIPassword.ToList().ForEach(x => password.AppendChar(x)); dComOptions.AddDestinationCredentials(new CimCredential(PasswordAuthenticationMechanism.Default, settings.WMIDomain, settings.WMIUsername, password)); CimSession session = CimSession.Create(hostname, dComOptions); // A method called GetWMI(string query, string namespace) will then execute the wmi query on the remote machine session.QueryInstances(namespace, "WQL", query) ``` Both of these ways end up throwing a `CimException: Access Denied` error. Is there maybe another way to do this in C#? My research could not come up with anything that would work - maybe there is some way I don't know about yet. We have sunk countless hours into research and debugging but nothing seems to work. For future reference I have found some older posts regarding some similar issues (most information on the internet about wmi is over a decade old): - https://stackoverflow.com/questions/10552268/wmi-using-a-non-admin-account-to-query-server - The following is actually my own post regarding the same issue - it was resolved as we tried using administrator permissions on the remote machine which would work but we now need it to work with as little permissions as possible eg. no administrator https://stackoverflow.com/questions/77911911/access-denied-trying-to-gather-wmi-information-using-c-sharp-asp-net-but-works-i - https://serverfault.com/questions/28520/which-permissions-rights-does-a-user-need-to-have-wmi-access-on-remote-machines/1105113#1105113 - https://stackoverflow.com/questions/4627394/wmi-access-denied-error-when-query-remote-computer-from-asp-net?rq=1 - https://stackoverflow.com/questions/14952833/get-wmiobject-win32-process-computername-gets-error-access-denied-code-0x8/14953535#14953535 - https://stackoverflow.com/questions/4990890/delphi-wmi-query-on-a-remote-machine I have tried all the suggestions from these posts - some of them seemed promising but turned out to not be the solution of my problem. Here is a summary of what we tried: - We granted all permissions in "wmimgmt.msc" to the root namespace and applied them to "This namespace and subnamespaces" - We added the user to the Local "Distributed COM Users" group - We added the user to the "Performance Monitor Users" and the "Remote Management Users" groups - We checked for any firewall issues and can assure that that should not be the problem - We also granted remote launch and activation permissions Here is our configuration in "wmimgmt.mcs" which should apply to the root namespace and all namespaces below (it's in German but shows that all permissions should apply to all namespaces): [![wmimgmt.msc Configuration on the root namespace][1]][1] Furthermore I found an old post in the microsoft docs stating that this is actually impossible (which is hard to believe as I already got it to work using powershell): https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc771551(v=ws.11)?redirectedfrom=MSDN > To perform this task on the local computer, you must be logged on as a member of the local Administrators group. >To perform this task on a remote computer, the account with which you are logged on must be a member of the Administrators group of that computer. If there is anything more I can provide to clear things up please let me know. Any leads would be highly appreciated - if any of my points in this post help other people in the future it was at least worth the research. [1]: https://i.stack.imgur.com/DzZS0.png
I'm using this library : [Oauth2 PHP][1] Is there a way to modify the response when token is invalid or expired from codeigniter filter? class OauthFilter implements FilterInterface { public function before(RequestInterface $request, $arguments = null) { $oauth = new Oauth(); $request = Request::createFromGlobals(); $response = new Response(); if(!$oauth->server->verifyResourceRequest($request)){ $oauth->server->getResponse()->send(); die(); } } public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { } } The default response was { "error": "invalid_token", "error_description": "The access token provided is invalid" } I know that verifyResourceRequest also calls getAccessToken. When I tried it separately it returns null. > $oauth->server->getAccessTokenData($request,$response) [1]: https://bshaffer.github.io/oauth2-server-php-docs/overview/jwt-access-tokens/
{"Voters":[{"Id":20513099,"DisplayName":"I_O "}]}
I need help with Google Drive API v3 please. I code in a procedural language (so no java or php or C#), I use WLanguage from the WinDev platform. I need to create a folder on Google Drive with API v3. - I obtained my client ID and secret key keys, - I can connect to Google Drive. BUT in my code I can't call functions like Create or Insert. I have to put the parameters for creating a folder in the URL. example : req.URL="https://www.googleapis.com/drive/v3/files?name='lili' and mimeType='application/vnd.google-apps.folder'" this creates a file named "untitled" in the drive and containing JSON I don't know how to specify in the URL that I want to create a folder? This is very urgent and I can't find help on the web Someone can help me. I thank you very much in advance. exemple code in my question
Google Drive API v3 : create folder?
|api|google-chrome|drive|windev|
null
I know this question is old, but I got the same problem with Netbeans 16 and 21. So... As far as I have seen with Laravel projects, comments in blades (`{{-- ... --}}`) trigger strange behaviors, such as preventing new lines or even inserting tabs. Strangely this doesn't always seem to happen, I think it is related to other Laravel code in the comment. Removing them restores normal behavior.
Instead of **persianJS** I used [**persian-tools**][1]. first I installed with the command below: npm install --save @persian-tools/persian-tools Then I imported this package to my target file: import * as persianTools from '@persian-tools/persian-tools'; And used it like this: persianTools.numberToWords("123200") // returns "صد و بیست و سه هزار و دویست" [1]: https://github.com/persian-tools/persian-tools
> Regex Match a pattern that only contains one set of numerals, and not more I would start by writing a _grammar_ for the "forgiving parser" you are coding. It is not clear from your examples, for instance, whether `<2112` is acceptable. Must the brackets be paired? Ditto for quotes, etc. Assuming that brackets and quotes do not need to be paired, you might have the following grammar: ##### _sign_ `+` | `-` ##### _digit_ `0` | `1` | `2` | `3` | `4` | `5` | `6` | `7` | `8` | `9` ##### _non-sign-non-digit_ _any-character-that-is-not-a-sign-or-digit_ ##### _integer_ [ _sign_ ]  _digit_  { _digit_ } ##### _prefix_ [ _any-sequence-without-a-sign-or-digit_ ] _prefix_   _sign_   _non-sign-non-digit_   [ _any-sequence-without-a-sign-or-digit_ ] ##### _suffix_ [ _any-sequence-without-a-digit_ ] ##### _forgiving-integer_ _prefix_  _integer_  _suffix_ Notes: - Items within square brackets are optional. They may appear either 0 or 1 time. - Items within curly braces are optional. They may appear 0 or more times. - Items separated by `|` are alternatives from which 1 must be chosen - Items on separate lines are alternatives from which 1 must be chosen One subtlety of this grammar is that integers can have only one sign. When more than one sign is present, all except the last are treated as part of the _prefix_, and, thus, are ignored. Are the following interpretations acceptable? If not, then the grammar must be altered. - `++42` parses as `+42` - `--42` parses as `-42` - `+-42` parses as `-42` - `-+42` parses as `+42` Another subtlety is that whitespace following a sign causes the sign to be treated as part of the prefix, and, thus, to be ignored. This is perhaps counterintuitive, and, frankly, may be unacceptable. Nevertheless, it is how the grammar works. In the example below, the negative sign is ignored, because it is part of the prefix. - `- 42` parses as `42` ### A solution without `std::regex` With a grammar in hand, it should be easier to figure out an appropriate regular expression. My solution, however, is to avoid the inefficiencies of `std::regex`, in favor of coding a simple "parser." In the following program, function `validate_integer` implements the foregoing grammar. When `validate_integer` succeeds, it returns the integer it parsed. When it fails, it throws a `std::runtime_error`. Because `validate_integer` uses `std::from_chars` to convert the integer sequence, it will not convert the test case `2112.0` from the OP. The trailing `.0` is treated as a second integer. All the other test cases work as expected. The only tricky part is the initial loop that skips over non-numeric characters. When it encounters a sign (`+` or `-`), it has to check the following character to decide whether the sign should be interpreted as the start of a numeric sequence. That is reflected in the "tricky" grammar for _prefix_ given above, where a sign must not be followed by a sign or digit, if it is to be treated as part of the prefix. ```lang-cpp // main.cpp #include <cctype> #include <charconv> #include <iomanip> #include <iostream> #include <stdexcept> #include <string> #include <string_view> bool is_digit(unsigned const char c) { return std::isdigit(c); } bool is_sign(const char c) { return c == '+' || c == '-'; } int validate_integer(std::string const& s) { enum : std::string::size_type { one = 1u }; std::string::size_type i{}; // skip over prefix while (i < s.length()) { if (is_digit(s[i]) || is_sign(s[i]) && i + one < s.length() && is_digit(s[i + one])) break; ++i; } // throw if nothing remains if (i == s.length()) throw std::runtime_error("validation failed"); // parse integer // due to foregoing checks, this cannot fail if (s[i] == '+') ++i; // `std::from_chars` does not accept leading plus sign. auto const first{ &s[i] }; auto const last{ &s[s.length() - one] + one }; int n; auto [end, ec] { std::from_chars(first, last, n) }; i += end - first; // skip over suffix while (i < s.length() && !is_digit(s[i])) ++i; // throw if anything remains if (i != s.length()) throw std::runtime_error("validation failed"); return n; } void test(std::ostream& log, bool const expect, std::string s) { std::streamsize w{ 46 }; try { auto n = validate_integer(s); log << std::setw(w) << s << " : " << n << '\n'; } catch (std::exception const& e) { auto const msg{ e.what() }; log << std::setw(w) << s << " : " << e.what() << ( expect ? "" : " (as expected)") << '\n'; } } int main() { auto& log{ std::cout }; log << std::left; test(log, true, "<2112>"); test(log, true, "[(2112)]"); test(log, true, "\"2112, \""); test(log, true, "-2112"); test(log, true, ".2112"); test(log, true, "<span style = \"numeral\">2112</span>"); log.put('\n'); test(log, true, "++42"); test(log, true, "--42"); test(log, true, "+-42"); test(log, true, "-+42"); test(log, true, "- 42"); log.put('\n'); test(log, false, "2112.0"); test(log, false, ""); test(log, false, "21,12"); test(log, false, "\"21\",\"12, \""); test(log, false, "<span style = \"font - size:18.0pt\">2112</span>"); log.put('\n'); return 0; } // end file: main.cpp ``` ### Output The "hole" in the output, below the entry for 2112.0, is the failed conversion of the null-string. ```lang-none <2112> : 2112 [(2112)] : 2112 "2112, " : 2112 -2112 : -2112 .2112 : 2112 <span style = "numeral">2112</span> : 2112 ++42 : 42 --42 : -42 +-42 : -42 -+42 : 42 - 42 : 42 2112.0 : validation failed (as expected) : validation failed (as expected) 21,12 : validation failed (as expected) "21","12, " : validation failed (as expected) <span style = "font - size:18.0pt">2112</span> : validation failed (as expected) ```
**Problem :-** You import like below. ```python from django.contrib.auth import authenticate, login ``` And then you use it as below. ```python user = authenticate(request, username=student_id, password=password) #and login(request, user) ``` Which are built in methods. This `authenticate` function doesn't use your password field in your model.(unless you already wrote code for custom authentication backend and didn't post here.) So, when you try to log in, that user doesn't exist in django built-in auth system. **Answers :-** 1) I suggest you to use django built-in auth system. Django already include built-in auth system, which you can customise for your needs. 2) Write a custom authentication backend. It's not very hard to make a custom authentication backend. It's the only way to make this work, if you want to keep using custom password fields in models. Examples :- [guide 1][1] [guide 2][2] [guide 3][3] [1]: https://reintech.io/blog/writing-custom-authentication-backend-django [2]: https://docs.djangoproject.com/en/5.0/topics/auth/customizing/ [3]: https://dev.to/amoabakelvin/creating-a-custom-authentication-backend-in-django-17bl
OAuth2 PHP change invalid_token response
|php|oauth-2.0|codeigniter-4|
{"Voters":[{"Id":16217248,"DisplayName":"CPlus"},{"Id":9473764,"DisplayName":"Nick"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[11]}
For testing my app, I need to send a mail over my companies mailhost. Unfortunately I have to use a tunnel to connect to that host and so sending mail is rejected because: ```text tls: failed to verify certificate: x509: certificate is valid for *.example.com, example.com, not host.docker.internal ``` Is there any way around this? Can I disable TLS? I'm using github.com/jhillyerd/enmime **Update after 2 comments** 1. I do **not** want to switch of TLS on the mailhost. I simply want to tell my net/smtp's Sendmail or enmime's Send to not do TLS verification. I already achieved that by copying Sendmail's code, leaving out the TLS-Part. But I don't like that approach as it feels very "hacky". 2. I'm working in a VPN and there are no credentials required when sending mails, as the mailhost can only be reached by a small set of known hosts. 3. This is also why I need a tunnel through a jumphost in order to reach the mailhost from my developer machine: Dockercontainer --> DevMac ---> Jumphost ---> Mailhost So I do a `ssh -L9925:mailhost.example.com:25 me@jumphost.example.com` That's why I have defined the mailhost to be "host.docker.internal:9925". Maybe there is another idea how I can reach the mailhost by its real name?
Here's a working solution. As I said in my comment, using regular expressions makes it far easier to retrieve the "highlighted" word. Note that it would be quite easy (by storing the word category delimiters in a dictionary, and replacing the 3 dictionaries with one dictionary of dictionaries) to make the code more flexible (adding new categories) while avoiding the repetition of `if ...` statements. ``` import re sentences = [ "Es (duftete) nach Erde und Pilze", "die [Wände] waren mit Moos überzogen.", "Ihr zerrissenes [Gewand] war wieder wie neu", "Er saß da wie verzaubert und schaute sie an und konnte seine Augen nicht {mehr} von ihr abwenden", "Da sie durchscheinend waren, sahen sie aus wie aus rosa [Glas], das von innen erleuchtet ist.", ] def getWordsSelected(sentences): # the parameter sentences is a list of the previous sentences sample showed verbDict = {} subsDict = {} adjDict = {} for wordSentenceToSearch in sentences: # SUBSTANTIVE if (substantive := re.findall(r'\[([^]]*)', wordSentenceToSearch)): subsDict.setdefault(substantive[0], []).append((wordSentenceToSearch, "substantive")) # VERB if (verb := re.findall(r'\(([^)]*)', wordSentenceToSearch)): verbDict.setdefault(verb[0], []).append((wordSentenceToSearch, "verb")) # ADJ if (adj := re.findall(r'\{([^}]*)', wordSentenceToSearch)): adjDict.setdefault(adj[0], []).append((wordSentenceToSearch, "adjective")) print(subsDict) print(verbDict) print(adjDict) ``` OUTPUT: ``` getWordsSelected(sentences) {'Wände': [('die [Wände] waren mit Moos überzogen.', 'substantive')], 'Gewand': [('Ihr zerrissenes [Gewand] war wieder wie neu', 'substantive')], 'Glas': [('Da sie durchscheinend waren, sahen sie aus wie aus rosa [Glas], das von innen erleuchtet ist.', 'substantive')]} {'duftete': [('Es (duftete) nach Erde und Pilze', 'verb')]} {'mehr': [('Er saß da wie verzaubert und schaute sie an und konnte seine Augen nicht {mehr} von ihr abwenden', 'adjective')]} ```
How compute ranks/percentiles for many columns in dataframe, while filtering each column for criteria
|emacs|terminfo|
getting "Error: Cannot read properties of undefined (reading 'username')" in my POST request
Just try this.. ` try: dlg.child_window(auto_id="XXXX").select(1) except: pass `
{"Voters":[{"Id":23569224,"DisplayName":"Lakhan"}]}
The problem was that the effect constructors were not being shared across ```Handler1``` and ```Handler2```, so, it's as if the constructors were different and that is why the handlers didn't recognise the effects. Once I put the effects in one file, then shared this amongst the compilation units, the problem is fixed.
I read similar questions and answers, but none working for me. I am trying copying sqlite database from **assets** folder to **application** data folder, but this always fail, because target database file is not created. *TRY 1:* ``` databasePath = context.getApplicationInfo().dataDir + "/databases/test.db"; Path path = Paths.get(databasePath); OutputStream applicationDatabaseStream = Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE); ``` Fails with exception: `W/System.err: java.nio.file.NoSuchFileException: /data/user/0/eu.example.test/databases/test.db` *TRY 2:* ``` databasePath = context.getApplicationInfo().dataDir + "/databases/test.db"; OutputStream applicationDatabaseStream = new FileOutputStream(databasePath); ``` Fails with exception: `W/System.err: java.io.FileNotFoundException: /data/user/0/eu.example.test/databases/test.db: open failed: ENOENT (No such file or directory)` Whats wrong with this code? I expect that code create file in application data folder.
Creating database file in application data
|java|android|android-sqlite|fileoutputstream|android-assets|