qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,446,016 | <p>While building flutter app, I am getting this error.</p>
<pre><code>One or more plugins require a higher Android SDK version.
Fix this issue by adding the following to C:\flutter\projects\my_app\android\app\build.gradle:
android {
compileSdkVersion 33
...
}
</code></pre>
<p>However, in my build.gradle I have :</p>
<pre><code>android {
compileSdkVersion flutter.compileSdkVersion
...
}
</code></pre>
<p>But I am unable to find the location where flutter.compileSdkVersion is defined. Any idea where is this defined? I have already run flutter upgrade and flutter --version returns Flutter 3.0.5.</p>
| [
{
"answer_id": 74446579,
"author": "Robert Sandberg",
"author_id": 13263384,
"author_profile": "https://Stackoverflow.com/users/13263384",
"pm_score": 2,
"selected": true,
"text": "<flutter-installation>\\packages\\flutter_tools\\gradle\\flutter.gradle\n"
},
{
"answer_id": 74447079,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "android {\ncompileSdkVersion flutter.compileSdkVersion\n...\n}\n"
},
{
"answer_id": 74447464,
"author": "Rahul",
"author_id": 16569443,
"author_profile": "https://Stackoverflow.com/users/16569443",
"pm_score": 0,
"selected": false,
"text": "compileSdkVersion Math.max(flutter.compileSdkVersion, 33)"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9906708/"
] |
74,446,025 | <pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def GaussFit():
xdata_raw = [0,24,22,20,18,16,14,12,10,8,6,4,2,-24,-22,-20,-18,-16,-14,-12,-10,-8,-6,-4,-2]
ydata_raw =[0.398,0.061,0.066,0.076,0.095,0.115,0.148,0.183,0.211,0.270,0.330,0.361,0.391,0.061,0.066,0.076,0.095,0.115,0.148,0.183,0.211,0.270,0.330,0.361,0.391]
y_norm = []
for i in range(len(ydata_raw)):
temp = ydata_raw[i]/0.398
y_norm.append(temp)
plt.plot(xdata_raw, y_norm, 'o')
xdata = np.asarray(xdata_raw)
ydata = np.asarray(y_norm)
def Gauss(x, A, B):
y = A*np.exp(-1*B*x**2)
return y
parameters, covariance = curve_fit(Gauss, xdata, ydata)
fit_A = parameters[0]
fit_B = parameters[1]
fit_y = Gauss(xdata, fit_A, fit_B)
plt.plot(xdata, ydata, 'o', label='data')
plt.plot(xdata, fit_y, '-', label='fit')
plt.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)
plt.legend()
plt.xlabel('Winkel der Auslenkung in °')
plt.ylabel('Intensität [I]')
plt.title('vertikale Ausrichtung')
GaussFit()
</code></pre>
<p>so this is the funktion and i got this plot:<a href="https://i.stack.imgur.com/M5Fct.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>as you can see, its not high quality. Im trying to fit my data to a gauss-kurve and norm it to 1. but it seems numpy got a problem with the range of the numbers. Any ideas how to fix it and get a reasonable plot?</p>
| [
{
"answer_id": 74446579,
"author": "Robert Sandberg",
"author_id": 13263384,
"author_profile": "https://Stackoverflow.com/users/13263384",
"pm_score": 2,
"selected": true,
"text": "<flutter-installation>\\packages\\flutter_tools\\gradle\\flutter.gradle\n"
},
{
"answer_id": 74447079,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "android {\ncompileSdkVersion flutter.compileSdkVersion\n...\n}\n"
},
{
"answer_id": 74447464,
"author": "Rahul",
"author_id": 16569443,
"author_profile": "https://Stackoverflow.com/users/16569443",
"pm_score": 0,
"selected": false,
"text": "compileSdkVersion Math.max(flutter.compileSdkVersion, 33)"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510345/"
] |
74,446,048 | <p>I'm doing automation using WDIO and want to upload a file but the input element is disabled. The style element of the input selector has :</p>
<p><a href="https://i.stack.imgur.com/A4pmB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A4pmB.png" alt="enter image description here" /></a></p>
<p>When I change it to this, element is visible</p>
<p><a href="https://i.stack.imgur.com/9eb2c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9eb2c.png" alt="enter image description here" /></a></p>
<p>I wish to change this through my javascript code, this is what I've tried so far:</p>
<pre><code>const inputFilePath = "#kyc-image-file-input";
await this.driver.execute(
(elem) => elem.style.display = 'block',
await this.driver.$(inputFilePath),
);
await WaitUtil.pause(this.driver, 5000);
await (await this.digioPage.getPanAndAadhaarUploadFileInputEle()).setValue(remoteFilePath);
await WaitUtil.pause(this.driver, 5000);
</code></pre>
<p>Javascript throws the below error when I do this:
<a href="https://i.stack.imgur.com/tMjLo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tMjLo.png" alt="enter image description here" /></a></p>
<p>Please let me know the correct way of changing the display property.</p>
<p>Thanks in advance :)</p>
| [
{
"answer_id": 74446579,
"author": "Robert Sandberg",
"author_id": 13263384,
"author_profile": "https://Stackoverflow.com/users/13263384",
"pm_score": 2,
"selected": true,
"text": "<flutter-installation>\\packages\\flutter_tools\\gradle\\flutter.gradle\n"
},
{
"answer_id": 74447079,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "android {\ncompileSdkVersion flutter.compileSdkVersion\n...\n}\n"
},
{
"answer_id": 74447464,
"author": "Rahul",
"author_id": 16569443,
"author_profile": "https://Stackoverflow.com/users/16569443",
"pm_score": 0,
"selected": false,
"text": "compileSdkVersion Math.max(flutter.compileSdkVersion, 33)"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17330468/"
] |
74,446,067 | <p>I want to rotate a sprite in C and SDL2, with a set center of rotation, and without scaling or anti-aliasing.</p>
<p>My game resolution is 320x240, and the display is scaled up when I set the game to full screen, because I'm using <a href="https://wiki.libsdl.org/SDL_RenderSetLogicalSize" rel="nofollow noreferrer"><code>SDL_RenderSetLogicalSize(renderer, 320, 240)</code></a>.</p>
<ol>
<li><p>Using SDL2's <a href="https://wiki.libsdl.org/SDL_RenderCopyEx" rel="nofollow noreferrer"><code>SDL_RenderCopyEx()</code></a> (or <a href="https://wiki.libsdl.org/SDL_RenderCopyExF" rel="nofollow noreferrer"><code>SDL_RenderCopyExF()</code></a>) to rotate a SDL_Texture.</p>
<p>As shown in this example ( <a href="https://imgur.com/UGNDfEY" rel="nofollow noreferrer">https://imgur.com/UGNDfEY</a> ) when the window is set to full screen, the texture is scaled up and at much higher resolution. Is would like the final 320x240 rendering to be scaled up, not the individual textures.</p>
</li>
<li><p>Using SDL_gfx's <a href="https://www.ferzkopp.net/Software/SDL2_gfx/Docs/html/_s_d_l2__rotozoom_8h.html#a6f5f31a362f63370dc60049df14d6856" rel="nofollow noreferrer"><code>rotozoomSurface()</code></a> was a possible alternative.</p>
<p>However, as shown in this example ( <a href="https://imgur.com/czPEUhv" rel="nofollow noreferrer">https://imgur.com/czPEUhv</a> ), while this method give the intended low-resolution and aliased look, it has no center of rotation, and renders the transparency color as half-transparent black.</p>
</li>
</ol>
<p>Is there a function that does what I'm looking for? Are there some tricks to get around that?</p>
| [
{
"answer_id": 74451910,
"author": "Durza42",
"author_id": 19111973,
"author_profile": "https://Stackoverflow.com/users/19111973",
"pm_score": 1,
"selected": false,
"text": "SDL_Texture"
},
{
"answer_id": 74460653,
"author": "InsaneClock",
"author_id": 20510259,
"author_profile": "https://Stackoverflow.com/users/20510259",
"pm_score": 0,
"selected": false,
"text": "#define kScreenWidth 320\n#define kScreenHeight 240\n\nSDL_Window* g_window = NULL;\nSDL_Texture* g_texture = NULL;\nSDL_Renderer* g_renderer = NULL;\n\nSDL_Texture* g_sprite = NULL;\ndouble g_sprite_angle = 0.0;\nSDL_FRect g_sprite_frect = {\n .x = 50.0f,\n .y = 50.0f,\n .w = 32.0f,\n .h = 32.0f,\n};\n\nvoid\nsdl_load(void)\n{\n SDL_Init(SDL_INIT_VIDEO);\n g_window = SDL_CreateWindow(NULL, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, kScreenWidth, kScreenHeight, 0);\n g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_PRESENTVSYNC);\n g_texture = SDL_CreateTexture(g_renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, kScreenWidth, kScreenHeight);\n SDL_RenderSetLogicalSize(g_renderer, kScreenWidth, kScreenHeight);\n}\n\nvoid\nsprite_load(void)\n{\n g_sprite = IMG_LoadTexture(g_renderer, \"./sprite.png\");\n}\n\nvoid\ndraw(void)\n{\n SDL_SetRenderTarget(g_renderer, g_texture);\n SDL_RenderClear(g_renderer);\n SDL_RenderCopyExF(g_renderer, g_sprite, NULL, &g_sprite_frect, g_sprite_angle, NULL, SDL_FLIP_NONE);\n\n SDL_SetRenderTarget(g_renderer, NULL);\n SDL_RenderClear(g_renderer);\n SDL_RenderCopy(g_renderer, g_texture, NULL, NULL);\n \n SDL_RenderPresent(g_renderer);\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510259/"
] |
74,446,081 | <p>my code:</p>
<pre><code>userlog = input("What is your username?")
passlog = input("What is your password?")
for fileread in open("accounts.txt", "r").readlines():
file = fileread.split()
if userlog == file[0] and passlog == file[1]:
print("Succesfully logged in")
elif userlog != file[0] and passlog != file[1]:
print("Username or password is incorrect")
</code></pre>
<p>instead of printing just "Succesfully logged in" or "Username or password is incorrect" it prints "Username or password is incorrect" for all lines in the text file and when the login info is typed correct it does the same but one is replaced with "Succesfully logged in"</p>
<p>I don't have a single clue what to do I'm obviously pretty new to python.</p>
| [
{
"answer_id": 74451910,
"author": "Durza42",
"author_id": 19111973,
"author_profile": "https://Stackoverflow.com/users/19111973",
"pm_score": 1,
"selected": false,
"text": "SDL_Texture"
},
{
"answer_id": 74460653,
"author": "InsaneClock",
"author_id": 20510259,
"author_profile": "https://Stackoverflow.com/users/20510259",
"pm_score": 0,
"selected": false,
"text": "#define kScreenWidth 320\n#define kScreenHeight 240\n\nSDL_Window* g_window = NULL;\nSDL_Texture* g_texture = NULL;\nSDL_Renderer* g_renderer = NULL;\n\nSDL_Texture* g_sprite = NULL;\ndouble g_sprite_angle = 0.0;\nSDL_FRect g_sprite_frect = {\n .x = 50.0f,\n .y = 50.0f,\n .w = 32.0f,\n .h = 32.0f,\n};\n\nvoid\nsdl_load(void)\n{\n SDL_Init(SDL_INIT_VIDEO);\n g_window = SDL_CreateWindow(NULL, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, kScreenWidth, kScreenHeight, 0);\n g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_PRESENTVSYNC);\n g_texture = SDL_CreateTexture(g_renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, kScreenWidth, kScreenHeight);\n SDL_RenderSetLogicalSize(g_renderer, kScreenWidth, kScreenHeight);\n}\n\nvoid\nsprite_load(void)\n{\n g_sprite = IMG_LoadTexture(g_renderer, \"./sprite.png\");\n}\n\nvoid\ndraw(void)\n{\n SDL_SetRenderTarget(g_renderer, g_texture);\n SDL_RenderClear(g_renderer);\n SDL_RenderCopyExF(g_renderer, g_sprite, NULL, &g_sprite_frect, g_sprite_angle, NULL, SDL_FLIP_NONE);\n\n SDL_SetRenderTarget(g_renderer, NULL);\n SDL_RenderClear(g_renderer);\n SDL_RenderCopy(g_renderer, g_texture, NULL, NULL);\n \n SDL_RenderPresent(g_renderer);\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510263/"
] |
74,446,085 | <p>Created an index tr_logintracker in elasticsearch using the below. We are using Elasticsearch version 7.17
We even tried with data type of Integer in place of index</p>
<pre class="lang-json prettyprint-override"><code>{
"mappings": {
"properties": {
"logintime": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
},
"logouttime": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
},
"logout": {
"type": "long"
},
"vehicleid": {
"type": "long"
},
"driverid": {
"type": "long"
},
"vehicleownerid": {
"type": "long"
}
}
}
}
</code></pre>
<p>Index is created</p>
<pre class="lang-json prettyprint-override"><code>{
"acknowledged": true,
"shards_acknowledged": true,
"index": "tr_logintracker"
}
</code></pre>
<p>Document is inserted into the index. Same can be seen using</p>
<pre class="lang-json prettyprint-override"><code>{
"query": {
"match_all" : {}
}
}
</code></pre>
<p>Response</p>
<pre class="lang-json prettyprint-override"><code>{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.0,
"hits": [
{
"_index": "tr_logintracker",
"_type": "_doc",
"_id": "6pJHe4QBPiDyvh1VwkiC",
"_score": 1.0,
"_source": {
"data": {
"vehicleownerid": 17,
"driverid": 21,
"vehicleid": 20,
"logintime": "2022-11-15 18:03:29",
"logout": 0
}
}
}
]
}
}
</code></pre>
<p>But when the same is queried null result is getting fetched
Query</p>
<pre class="lang-json prettyprint-override"><code>{
"query": {
"bool": {
"must": [
{ "match": { "driverid" : 21 }}
]
}
}
}
</code></pre>
<p>Response</p>
<pre class="lang-json prettyprint-override"><code>{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 0,
"relation": "eq"
},
"max_score": null,
"hits": []
}
}
</code></pre>
<p>When checked /tr_logintracker/_mapping can see the below. Which does not look correct. The second set of entries is happening when we insert the document into the index.</p>
<pre class="lang-json prettyprint-override"><code>{
"tr_logintracker": {
"mappings": {
"properties": {
"data": {
"properties": {
"driverid": {
"type": "long"
},
"logintime": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"logout": {
"type": "long"
},
"vehicleid": {
"type": "long"
},
"vehicleownerid": {
"type": "long"
}
}
},
"driverid": {
"type": "long"
},
"logintime": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
},
"logout": {
"type": "long"
},
"logouttime": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
},
"vehicleid": {
"type": "long"
},
"vehicleownerid": {
"type": "long"
}
}
}
}
}
</code></pre>
<p>We also tried the option of dynamic mapping - getting the index created by the program which is inserting. Even in that case query is not fetching the result.</p>
| [
{
"answer_id": 74446297,
"author": "Paulo",
"author_id": 4534923,
"author_profile": "https://Stackoverflow.com/users/4534923",
"pm_score": 1,
"selected": false,
"text": "driverid"
},
{
"answer_id": 74446305,
"author": "Triet Doan",
"author_id": 1814420,
"author_profile": "https://Stackoverflow.com/users/1814420",
"pm_score": 0,
"selected": false,
"text": "match_all"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510354/"
] |
74,446,092 | <p>NOTE: Using <code>PyAutoGui</code> library</p>
<p>I am trying to make python click on each icon on screen in order, I have gotten it to successfully print each item on screen with it's <code>box</code> values of <em>left</em> and <em>top</em> in place of X and Y coordinates. But I can't figure out how to get left/top converted into X/Y values for use with the <code>pyautogui.click()</code></p>
<p>Code:</p>
<pre><code>import pyautogui
coordinates = pyautogui.locateAllOnScreen('eachIcon.png')
for element in coordinates:
print(element)
</code></pre>
<p>Prints:</p>
<pre><code>Box(left=124, top=699, width=14, height=14)
</code></pre>
<p><strong>What command would I use to extract Left and Top as X and Y number coordinates?</strong></p>
<p>I am entirely new to python and practically new to coding (took a beginners class of C++ in college). I've spent a good hour googling and trying every term I can think of, I'm stumped: hence the post.</p>
| [
{
"answer_id": 74484365,
"author": "Gianpi",
"author_id": 20525800,
"author_profile": "https://Stackoverflow.com/users/20525800",
"pm_score": 1,
"selected": false,
"text": "Box(left=124, top=699, width=14, height=14)"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13032383/"
] |
74,446,115 | <p>Building a simple ToDo app in React/NodeJS/Express with MySQL. Users join a group ("family" in the code), then tasks are viewable filtered by familyId. To create a task, I first have a query that finds the user's familyId from the Users table, then I want to include that familyId value in the subsequent INSERT query for creating the task row in the Tasks table. My task.model.js is below:</p>
<pre><code>const sql = require("./db.js");
// constructor
const Task = function(task) {
this.title = task.title;
this.familyId = task.familyId;
this.description = task.description;
this.completed = task.completed;
this.startDate = task.startDate;
this.userId = task.userId;
};
Task.create = (task, result) => {
sql.query("SELECT familyId FROM users WHERE userId = ?", task.userId, (err, res) => {
if (err) {
console.log("Error selecting from USERS: ", err);
return result(err, null);
}
sql.query("INSERT INTO tasks (familyId, title, description, completed, startDate) VALUES (?,?,?,?,?)", [result, task.title, task.description, task.completed, task.startDate], (err, res) => {
if (err) {
console.log("Error inserting in TASKS: ", err);
return result(err, null);
}
})
console.log("created task: ", { id: res.insertId, ...task });
return result(null, { id: res.insertId, ...task });
});
};
</code></pre>
<p>However, I cannot figure out how to properly use the familyId result of the SELECT query as a parameter in the suqsequent INSERT query. I know the overall syntax works because I can manually plug in an ID value as a parameter and the entire operation completes successfully - I just need to know how to use the resule of the first query in the next.</p>
| [
{
"answer_id": 74484365,
"author": "Gianpi",
"author_id": 20525800,
"author_profile": "https://Stackoverflow.com/users/20525800",
"pm_score": 1,
"selected": false,
"text": "Box(left=124, top=699, width=14, height=14)"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14496639/"
] |
74,446,117 | <p>I have this type:</p>
<pre><code>type RouteList = 'admin/dashboard' | 'admin/users' | 'admin/roles';
</code></pre>
<p>How can I create this type above from this array dynamically?</p>
<pre><code>const routeList = ['admin/dashboard','admin/users','admin/roles'];
</code></pre>
| [
{
"answer_id": 74446300,
"author": "Moein Moeinnia",
"author_id": 18318552,
"author_profile": "https://Stackoverflow.com/users/18318552",
"pm_score": 3,
"selected": true,
"text": "const routeList = ['admin/dashboard','admin/users','admin/roles'] as const;\n\ntype RouteList = typeof routeList[number]"
},
{
"answer_id": 74446314,
"author": "Build For Dev",
"author_id": 20477335,
"author_profile": "https://Stackoverflow.com/users/20477335",
"pm_score": -1,
"selected": false,
"text": "const yourRoute = 'admin/users';\nconst routeList = ['admin/dashboard','admin/users','admin/roles'];\nlet isApproved = false;\n\nif (routeList.includes(yourRoute)) {\n isApproved = true;\n}\n\nconsole.log(isApproved);\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2766013/"
] |
74,446,150 | <p>I got the following graph for each job title with salary in box plot:
<a href="https://i.stack.imgur.com/Tr7kG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Tr7kG.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/Afd2E.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Afd2E.png" alt="enter image description here" /></a></p>
<p>so there are some outliers here, presented as dot, I want to make some jitters like this for each job title have outliers:</p>
<p><a href="https://i.stack.imgur.com/H1kPx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/H1kPx.png" alt="enter image description here" /></a></p>
<p>Is there any way I can do it with Vegalite package?<br />
can someone gives me some advices please?<br />
Thanks in advance!</p>
| [
{
"answer_id": 74468350,
"author": "giantmoa",
"author_id": 20258205,
"author_profile": "https://Stackoverflow.com/users/20258205",
"pm_score": 2,
"selected": false,
"text": "StatisticalGraphics.jl"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20136433/"
] |
74,446,158 | <p>I don't know NgRx yet and I need to manage state in an Angular app,
the app is pretty simple, we have list of items, when user goes to items list I download that data and show it, but when user navigates to admin page and then comes back to items list component I don't want to download items list again. Can I manage state in Angular using services and BehaviorSubject? And what is the easiest way to manage state in simple Angular application (if it's possible without using NgRx)?</p>
| [
{
"answer_id": 74468350,
"author": "giantmoa",
"author_id": 20258205,
"author_profile": "https://Stackoverflow.com/users/20258205",
"pm_score": 2,
"selected": false,
"text": "StatisticalGraphics.jl"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12224228/"
] |
74,446,164 | <p>How can I specify a textSize for all text elements within a Column / Row?</p>
<p>I have difficulty finding a method, which helps me doing something like the <code>UnspecifiedFontSize</code> (pseudo code):</p>
<pre><code>Row {
UnspecifiedFontSize(size= 128.dp) {
Text("ping")
Text("pong")
}
}
</code></pre>
| [
{
"answer_id": 74446416,
"author": "lisonge",
"author_id": 10717907,
"author_profile": "https://Stackoverflow.com/users/10717907",
"pm_score": 4,
"selected": true,
"text": "LocalTextStyle"
},
{
"answer_id": 74448867,
"author": "Gabriele Mariotti",
"author_id": 2016562,
"author_profile": "https://Stackoverflow.com/users/2016562",
"pm_score": 2,
"selected": false,
"text": "TextStyle"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870799/"
] |
74,446,169 | <p>How can I make groovy on Jenkins mask
<strong>My groovy code:</strong></p>
<pre><code>sh "sonar-scanner -Dsonar.host.url=http://sonarurl:9000 -Dsonar.login=squ_a1111"
</code></pre>
<p><strong>Jenkins Console:</strong></p>
<pre><code>sonar-scanner -Dsonar.host.url=http://sonarurl:9000 -Dsonar.login=squ_a1111
</code></pre>
<p>When I run it, the <strong>token</strong> appears in the console, but I don't want it to appear. How can I do masking?</p>
<p>I want it this way, For example:</p>
<pre><code>sonar-scanner -Dsonar.host.url=http://sonarurl:9000 -Dsonar.login=******
</code></pre>
| [
{
"answer_id": 74446981,
"author": "Pexers",
"author_id": 9213148,
"author_profile": "https://Stackoverflow.com/users/9213148",
"pm_score": 0,
"selected": false,
"text": "steps {\n withCredentials([\n string(credentialsId: \"sonar-creds\", variable: 'PWD_SONAR')\n ]) {\n script {\n sh \"sonar-scanner -Dsonar.host.url=http://sonarurl:9000 -Dsonar.login=$PWD_SONAR\"\n }\n }\n}\n"
},
{
"answer_id": 74447375,
"author": "Resul Zoroğlu",
"author_id": 14686302,
"author_profile": "https://Stackoverflow.com/users/14686302",
"pm_score": 3,
"selected": true,
"text": "def token = \"squ_a1111\"\nwrap([$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: [[password: token]]]) {\n sh \"sonar-scanner -Dsonar.host.url=http://sonarurl:9000 -Dsonar.login=${token}\"\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14686302/"
] |
74,446,175 | <p>I have a list with 2 minimum numbers and I am trying to get the index of the minimum number 33 at index [5], but my loop stops at [0] once it's found the min. Unsure how to get the get last index value.</p>
<pre><code> rain_data = [33, 57, 60, 55, 53, 33]
min_value = rain_data[0]
min_index = 0
def minimum(rain_data)
for val in range(len(rain_data)):
if rain_data[val] < min_value:
min_value = rain_data[val]
min_index = val
# display the min value and index
print(min_value)
print(min_index)
results = (float(min_value) , min_index)
</code></pre>
<p>I have ran the loop and it stops at [0] and not the desired [5] index</p>
| [
{
"answer_id": 74446981,
"author": "Pexers",
"author_id": 9213148,
"author_profile": "https://Stackoverflow.com/users/9213148",
"pm_score": 0,
"selected": false,
"text": "steps {\n withCredentials([\n string(credentialsId: \"sonar-creds\", variable: 'PWD_SONAR')\n ]) {\n script {\n sh \"sonar-scanner -Dsonar.host.url=http://sonarurl:9000 -Dsonar.login=$PWD_SONAR\"\n }\n }\n}\n"
},
{
"answer_id": 74447375,
"author": "Resul Zoroğlu",
"author_id": 14686302,
"author_profile": "https://Stackoverflow.com/users/14686302",
"pm_score": 3,
"selected": true,
"text": "def token = \"squ_a1111\"\nwrap([$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: [[password: token]]]) {\n sh \"sonar-scanner -Dsonar.host.url=http://sonarurl:9000 -Dsonar.login=${token}\"\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20495309/"
] |
74,446,200 | <p>I have a struct like this:</p>
<pre><code>import Foundation
struct Product: Identifiable {
var name: String
let expirationDate: Date
let id = UUID()
}
</code></pre>
<p>and a list like this:</p>
<pre><code>import SwiftUI
struct ContentView: View {
@Binding var products: [Product]
var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}
var body: some View {
VStack {
List {
ForEach(products) { product in
HStack {
Text(product.name)
Spacer()
Text(self.dateFormatter.string(from: product.expirationDate))
}
}
}
}
</code></pre>
<p>how can I sort this list so that the closest expiration date from now is on top of the list?</p>
<p>I don't even know how to get just the expirationDates from products array.
I would appreciate any help. Thank you in advance!</p>
| [
{
"answer_id": 74446407,
"author": "Timmy",
"author_id": 13278922,
"author_profile": "https://Stackoverflow.com/users/13278922",
"pm_score": 3,
"selected": true,
"text": "timeIntervalSinceNow"
},
{
"answer_id": 74450148,
"author": "malhal",
"author_id": 259521,
"author_profile": "https://Stackoverflow.com/users/259521",
"pm_score": 1,
"selected": false,
"text": "Table"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20484841/"
] |
74,446,227 | <p>I have a dictionary with missing values (the key is there, but the associated value is empty). For example I want the dictionary below:</p>
<pre><code>dct = {'ID': '', 'gender': 'male', 'age': '20', 'weight': '', 'height': '5.7'}
</code></pre>
<p>to be changed to this form:</p>
<pre><code>dct = {'ID': {'link': '','value': ''}, 'gender': 'male', 'age': '20', 'weight': {'link': '','value': ''}, 'height': '5.7'}
</code></pre>
<p>I want the ID and Weight key should be replaced with nested dictionary if its empty.</p>
<p>How can I write that in the most time-efficient way?</p>
<p>I have tried solutions from below links but didnt work,</p>
<pre><code>def update(orignal, addition):
for k, v in addition.items():
if k not in orignal:
orignal[k] = v
else:
if isinstance(v, dict):
update(orignal[k], v)
elif isinstance(v, list):
for i in range(len(v)):
update(orignal[k][i], v[i])
else:
if not orignal[k]:
orignal[k] = v
</code></pre>
<p>Error: TypeError: 'str' object does not support item assignment</p>
<p><a href="https://stackoverflow.com/questions/72712804/fill-missing-keys-by-comparing-example-json-in-python?force_isolation=true">Fill missing keys by comparing example json in python</a></p>
<p><a href="https://stackoverflow.com/questions/33910764/adding-missing-keys-in-dictionary-in-python?force_isolation=true">Adding missing keys in dictionary in Python</a></p>
| [
{
"answer_id": 74446407,
"author": "Timmy",
"author_id": 13278922,
"author_profile": "https://Stackoverflow.com/users/13278922",
"pm_score": 3,
"selected": true,
"text": "timeIntervalSinceNow"
},
{
"answer_id": 74450148,
"author": "malhal",
"author_id": 259521,
"author_profile": "https://Stackoverflow.com/users/259521",
"pm_score": 1,
"selected": false,
"text": "Table"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17451339/"
] |
74,446,240 | <p>I have created an automated data client that pulls data from a txt file and inputs it into a csv file. Each data entry contains a timestamp, but it is not in the format I need it in, I need it to match the datetime.now() format:</p>
<p><strong>ORIGINAL FORMAT</strong> [03/11/22 01:06:09:190]</p>
<p><strong>DESIRED FORMAT</strong> 2022-11-03 01:06:09.190000</p>
<p>I am currently using the following code to pull the timestamp from each line of data I need:
82: reTimestamp = r'\d{2}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}:\d{3}'</p>
<pre><code>105: for line in f:
106: line.strip()
108: timestamp = re.findall(reTimestamp, line.strip())
110: print(timestamp)
</code></pre>
<hr />
<p>Output: ['03/11/22 01:05:06:172']</p>
<p>Every function is working well up until now because im having trouble converting this timestamp to the desired format. I would also like to get rid of the square brackets '[]'</p>
| [
{
"answer_id": 74446407,
"author": "Timmy",
"author_id": 13278922,
"author_profile": "https://Stackoverflow.com/users/13278922",
"pm_score": 3,
"selected": true,
"text": "timeIntervalSinceNow"
},
{
"answer_id": 74450148,
"author": "malhal",
"author_id": 259521,
"author_profile": "https://Stackoverflow.com/users/259521",
"pm_score": 1,
"selected": false,
"text": "Table"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20348095/"
] |
74,446,245 | <pre><code>#include <iostream>
#include <cstring>
int main()
{
char c1[5];
char c2[5];
if ( strlen(c1) == 0)
{
std::cout<<" c1 empty";
}
if (strcmp(c2, "") == 0)
{
std::cout<<" c2 empty";
}
return 0;
}
</code></pre>
<p>if ( strlen(c1) == 0) ==> equivalent assembly code ==></p>
<pre><code>lea rax, [rbp-5]
movzx eax, BYTE PTR [rax]
test al, al
jne .L2
</code></pre>
<p>if (strcmp(c2, "") == 0) ==> equivalent assembly code ==></p>
<pre><code>movzx eax, BYTE PTR [rbp-10]
movzx eax, al
test eax, eax
jne .L3
</code></pre>
<p>Not able to differentiate assembly code, they almost generate same code in assembly. Which is efficient way of checking array as empty?
Any help or more information will be appreciated.</p>
| [
{
"answer_id": 74446803,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 0,
"selected": false,
"text": "strlen"
},
{
"answer_id": 74447054,
"author": "RavaT",
"author_id": 16468530,
"author_profile": "https://Stackoverflow.com/users/16468530",
"pm_score": -1,
"selected": false,
"text": "#include<iostream>\n#include<cstring>\nint main()\n{\nchar c1[5],c2[5];\nstd::cin>>c1>>c2;\nstd::cout<<\"Length of first string =\"<<strlen(c1)<<\"\\n\";\nstd::cout<<\"Value returned by strcmp() =\"<<strcmp(c1,c2);\nreturn 0;\n} \n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2129218/"
] |
74,446,282 | <p>Is it possible to create a table layout using <code>display:table</code>, <code>display:table-row</code> and <code>display:table-cell</code> if <strong>table-cell is not a direct child of table-row</strong> ?</p>
<p>The example below would work if I remove the div with class <code>nestedDiv</code>, in such a way that the col divs are direct children of the row div.</p>
<p>Is this possible without altering the html structure?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
display: table;
width: 100%;
}
section .row {
display: table-row;
}
section .col {
display: table-cell;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
<section>
<div class="row">
<div class="nestedDiv"> <!-- nested div, this will not work -->
<div class="col">Column A</div>
<div class="col">Column B</div>
<div class="col">Column C</div>
</div>
</div>
<div class="row">
<div class="col">1</div>
<div class="col">2</div>
<div class="col">3</div>
</div>
</section>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74446471,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 0,
"selected": false,
"text": ".col {\n display: table-cell;\n padding: 0.2rem;\n}\n\n.row {\n display: table-row;\n}"
},
{
"answer_id": 74446863,
"author": "Alohci",
"author_id": 42585,
"author_profile": "https://Stackoverflow.com/users/42585",
"pm_score": 2,
"selected": true,
"text": ".nestedDiv"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571682/"
] |
74,446,331 | <p>Sometimes I want to use <em>all columns</em> and sometimes I want to <em>exclude the last column</em>.</p>
<pre><code>df.iloc[:, :].apply(foobar) # all columns
df.iloc[:, :-1].apply(foobar) # exclude last column
</code></pre>
<p>Can I parameterize that somehow?</p>
<pre><code>if exclude_last:
idx = ':-1'
else:
idx = ':'
df.iloc[:, idx].apply(foobar)
</code></pre>
| [
{
"answer_id": 74446371,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "df.iloc[:, :-1 if exclude_last else df.shape[1]].apply(foobar)\n"
},
{
"answer_id": 74446394,
"author": "saeedghadiri",
"author_id": 1988231,
"author_profile": "https://Stackoverflow.com/users/1988231",
"pm_score": 2,
"selected": true,
"text": "df.columns"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4865723/"
] |
74,446,349 | <p>I am trying to trigger an Azure Function from Logic Apps. Running the Azure function takes more than 2 minutes as it is reading a file from a location, converts it to another format and then writes it to a different location. The problem is that the Logic Apps is creating a request, waits for 2 minutes to get a response, but this response doesn't come because the function is not finishing that fast. So the logic app assumes there is an error and recreates the request.</p>
<p>I read in the documentation that there is no way to increase the timeout period. I tried creating two threads in the azure function. One returns 202 http status code to the logic app, and the other one would remain as a daemon and keeps running. But the file doesn't seem to be copied.</p>
<p>Does anyone have any idea how could this be achieved?</p>
| [
{
"answer_id": 74446371,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "df.iloc[:, :-1 if exclude_last else df.shape[1]].apply(foobar)\n"
},
{
"answer_id": 74446394,
"author": "saeedghadiri",
"author_id": 1988231,
"author_profile": "https://Stackoverflow.com/users/1988231",
"pm_score": 2,
"selected": true,
"text": "df.columns"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5836462/"
] |
74,446,353 | <p>Sample XML file (insert path):</p>
<pre><code><FilePath>
<TemplatePath> "C:\Users\test.txt" </TemplatePath>
</FilePath>
</code></pre>
<p>I am trying to take the value of but i always get a run-time error '91', this is the code:</p>
<pre><code>Sub testxml()
Set oXMLFile = CreateObject("Microsoft.XMLDOM")
oXMLFile.Load ("C:\Users\Config.xml")
Set prova = oXMLFile.SelectNodes("//FilePath/TemplatePath").item(0).Text
Debug.Print prova
</code></pre>
<p>I also cannot find proper documentation (I've tried to see on Microsoft learn but it doesn't explain very well those things).</p>
<p>Thank you!</p>
| [
{
"answer_id": 74446371,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "df.iloc[:, :-1 if exclude_last else df.shape[1]].apply(foobar)\n"
},
{
"answer_id": 74446394,
"author": "saeedghadiri",
"author_id": 1988231,
"author_profile": "https://Stackoverflow.com/users/1988231",
"pm_score": 2,
"selected": true,
"text": "df.columns"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19893881/"
] |
74,446,357 | <p>I'm using flutter for my first mobile application. I want to trigger an action without clicking a button.
this is the code :</p>
<pre><code> IconButton(
icon: Icon(
characteristic.isNotifying
? Icons.sync_disabled
: Icons.sync,
color: Theme.of(context).iconTheme.color?.withOpacity(0.5)),
onPressed: onNotificationPressed,
)
</code></pre>
<p>Thanks in advance for your help</p>
| [
{
"answer_id": 74446371,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "df.iloc[:, :-1 if exclude_last else df.shape[1]].apply(foobar)\n"
},
{
"answer_id": 74446394,
"author": "saeedghadiri",
"author_id": 1988231,
"author_profile": "https://Stackoverflow.com/users/1988231",
"pm_score": 2,
"selected": true,
"text": "df.columns"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20285309/"
] |
74,446,375 | <p>Building off of <a href="https://stackoverflow.com/questions/74445734/how-can-i-get-the-length-of-a-string-using-typescript-types">this question</a> (no I do not have a grand scheme, I simply thought of this after getting my question answered.):</p>
<p>I have the following:</p>
<pre><code>type LengthOfString<T extends string, L extends any[] = []> =
T extends `${string}${infer R}`
? LengthOfString<R, [...L, string]>
: L["length"]
type StringOfLength<T extends string, N extends number> = LengthOfString<T> extends N ? T : never
function isStringOfLength<T extends string, N extends number>(str: T, len: N): str is StringOfLength<T, N> {
return str.length === len
}
function takeString<T extends string>(str: StringOfLength<T, 5>) {
if (!isStringOfLength<T, 5>(str, 5)) throw Error("String length !== 5")
console.log(str)
}
// Works! (fresh)
takeString("22222")
// As expected, errors (fresh)
takeString("2222")
let str = "22222"
// Errors -- how can I avoid this? (str isn't fresh)
takeString(str)
</code></pre>
<p>As shown in the code, I have a run-time type guard <code>isStringOfLength</code> that is meant to throw runtime errors for non-fresh variables. However, I am unsure about how to change my code to <em>accept</em> these non-fresh values, while type-checking against the fresh strings as shown with the first two calls.</p>
<p><a href="https://www.typescriptlang.org/play?ts=4.8.4#code/C4TwDgpgBAMhB2BzYALA8gMwMrAE4EskAeAFSggA9gEATAZyjr0MQBpZyraGBDeEANoBdKAF4owgHxioAKChQylavHpQABgBIA3kwJIAvjsIYIuKACUD6uQoUB%20WAmTpszYhfYCAdL5js9FiFJeTsALlgBACIAG2dUKKFZWVBIKBx9REw4JFRSThU1QKR2ADkC7ih4AFcAWwAjM2lxHJdMDJZSaWVK8scyCPgIADczZIxq%20ABjYHwAe3gofDoOpGz4lHye1QZitihy7bUahqaACj0IknY4%20AjSgEoIvSWGVayMVrzrg%20ltUNwEGA1Vwiz03luLjEonEt1kBnGkxm80WwB4AGsIO8tlwdox3IhJBc8BF3utcpsfgBWSQPKD-BT4DBQM4AQmWZM%20G1I7BpxNwvIedNQuDmAHcoABRXCi3BnKLvKCQ1BQVkwqBUqIPUJTBZ0OZxCFzRD87UI2QAegtUAA6nNcOi6KyWRhAXQUNq0Zj3vKAEz%20-1a5JWqAAQQYlEgMwgNHYZllDDOrog7s9GKxBL9AaDsjiwHx5nEUQDgeD1ulCagAFoq1AUOKoFM%20FAAJJQHjDOb4GhQVDLRz817wADk%20eTqZS6Z9egeQA" rel="nofollow noreferrer">TS Playground</a></p>
| [
{
"answer_id": 74446525,
"author": "nullptr",
"author_id": 9549012,
"author_profile": "https://Stackoverflow.com/users/9549012",
"pm_score": 0,
"selected": false,
"text": "let str = \"22222\" as const"
},
{
"answer_id": 74446720,
"author": "Tobias S.",
"author_id": 8613630,
"author_profile": "https://Stackoverflow.com/users/8613630",
"pm_score": 2,
"selected": true,
"text": "string"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7589775/"
] |
74,446,378 | <p>I've been busting my head on what should be a simple problem. I've got a div that needs to be clickable, which means I have to put an <code><a></code> tag into the <code><div></code>. I can't put the entire content into an <code><a></code> tag, because there's text inside of this component which contains more inline <code><a></code> tags. (You can't have nested <code><a></code> tags, I've discovered).
So I thought it would be a simple solution to warp an <code><a></code> tag with a <code><div></code>, and just style the <code><a></code> tag so that it functions as a background to the <code><div></code>, with the other text containing the inline <code><a></code> tags showing <em>ontop</em> of the "clickable background". However I can't style it so that it functions as a background. My css knowledge is quite limited, I thought using <code>display: block</code> in combination with <code>padding: 100%</code> would solve this. That just messes up the entire layout, even when moving around the <code><a></code> tag in my html. Here's the relevant code:</p>
<p>CSS:</p>
<pre><code>.clickable {
background-color: $color-accent-white;
display: block;
padding: 100%;
}
</code></pre>
<p>HTML:</p>
<pre><code><events>
{{#each events}}
<div>
<section>
<div class="row">
<a class="clickable" href="{{ link }}" <!-- The culprit! -->
{{#if link_target}}target="{{ link_target }}"{{/if}} data-show-until="{{ show_until }}"></a>
<div class="col-12 col-md-4">
{{> [content/content_picture]
large=image.large
alt=image.alt
link=null
}}
</div>
<div class="col-12 col-md-8">
<p class="mb-0">
<small>
{{ subline }}
</small>
</p>
<p class="h3">
{{ headline }}
</p>
{{{ text }}}
</div>
</div>
</section>
</div>
{{/each}}
</events>
</code></pre>
<p>I've tried all sorts of combinations with varying positions vs display modes and paddings. How can I make my <code><a></code> tag fit the size of it's parent <code><div></code>?</p>
| [
{
"answer_id": 74446525,
"author": "nullptr",
"author_id": 9549012,
"author_profile": "https://Stackoverflow.com/users/9549012",
"pm_score": 0,
"selected": false,
"text": "let str = \"22222\" as const"
},
{
"answer_id": 74446720,
"author": "Tobias S.",
"author_id": 8613630,
"author_profile": "https://Stackoverflow.com/users/8613630",
"pm_score": 2,
"selected": true,
"text": "string"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15694013/"
] |
74,446,381 | <p>I have a variable called $path which has a value of</p>
<pre><code>My Pictures/Tony/Automatic Upload/Tony’s iPhone/2022-11-13 10-57-52.mov
</code></pre>
<p>trying to use split-path to get just <strong>2022-11-13 10-57-52.mov</strong></p>
<pre><code>Split-Path -Path $path -Leaf -Resolve
Split-Path : Cannot find path 'C:\Users\Tony\My Pictures\Tony\Automatic Upload\Tony’s iPhone\2022-11-13 10-57-52.mov' because it does not exist.
At line:1 char:1
+ Split-Path -Path $path -Leaf -Resolve
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Users\Tony\M...13 10-57-52.mov:String) [Split-Path], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SplitPathCommand
</code></pre>
<p>don't have it working yet... any guidance ?</p>
| [
{
"answer_id": 74446525,
"author": "nullptr",
"author_id": 9549012,
"author_profile": "https://Stackoverflow.com/users/9549012",
"pm_score": 0,
"selected": false,
"text": "let str = \"22222\" as const"
},
{
"answer_id": 74446720,
"author": "Tobias S.",
"author_id": 8613630,
"author_profile": "https://Stackoverflow.com/users/8613630",
"pm_score": 2,
"selected": true,
"text": "string"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/800592/"
] |
74,446,398 | <p>The topic was raised due to dealing with some graph problems. So I'm receiving information about graph structure via <code>stdin</code> and input looks like this:</p>
<pre><code>Number of Edges
ID of NodeN1 Id of NodeN2
ID of NodeN3 Id of NodeN4
ID of NodeN5 Id of NodeNn
...
</code></pre>
<p>The first line represents amount of edges in graph, the other lines represent edges themselves(displayed as two IDs of corresponding nodes of that particular edge), for example the graph with 3 edges and 3 nodes will look like this:</p>
<pre><code>3
0 1
0 2
1 2
</code></pre>
<p>After receiving this data, I'm parsing it in a following way, iterating over the range of input and then saving nodes in two different lists using <code>map()</code> approach:</p>
<pre><code>E = int(input())
lst = []
lst_ = []
for x in range(E):
l, q = map(int, input().split())
lst.append(l)
lst_.append(q)
</code></pre>
<p>After this I can just simply use something like <code>Networkx</code> add these edges to <code>Graph()</code> class, for example in the following manner:</p>
<pre><code>import networkx as nx
G = nx.Graph()
for x in range (len(lst)):
G.add_edge(lst[x],lst_[x])
</code></pre>
<p>Right now my problem is following - I would like to change structure of graph representation in this way: to have list of lists, where lists inside represents the nodes connected to particular node. It might sounds a bit fuzzy so let's use example. For the graph above(with 3 nodes and 3 edges) the new list of lists structure should look like this:</p>
<pre><code>mega_lst = [[1,2],[0,2],[0,1]]
</code></pre>
<p>First list looks like <code>[1,2]</code> because these are the IDs that were connected to 0 in the graph, etc. I can think of some solution using pandas indexing but I think there should be much easier way to solve it using nested lists. Can you please give a hint in what direction should I go?</p>
<p>Many thanks :)</p>
| [
{
"answer_id": 74446546,
"author": "Temba",
"author_id": 3593621,
"author_profile": "https://Stackoverflow.com/users/3593621",
"pm_score": 3,
"selected": true,
"text": "networkx"
},
{
"answer_id": 74446936,
"author": "Riccardo Bucco",
"author_id": 5296106,
"author_profile": "https://Stackoverflow.com/users/5296106",
"pm_score": 1,
"selected": false,
"text": "networkx"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3079439/"
] |
74,446,399 | <p>I have created an parmeter @myxml and populated it with my xml. I am able to get most of the data returned but I am running in to a problem with a node called userarea.
if i am select s.PO.value('<em>:UserArea[1]/</em>:Property[4]', 'nvarchar(50)') as MFG
I can get the mfg name however if one of the propertys are not in the xml then then i get the wrong value.
is there a way to call the property by its name and not the index.Property[Manufacture]??</p>
<pre><code>Declare @POXML as XML
Set @POXML = '<SyncPurchaseOrder releaseID="9.2">
<DataArea>
<PurchaseOrder>
<PurchaseOrderLine>
<LineNumber>1</LineNumber>
<UserArea>
<Property>
<NameValue name="ActiveFlag">true</NameValue>
</Property>
<Property>
<NameValue name="ExchangeRate">1.00</NameValue>
</Property>
<Property>
<NameValue name="UDFCHAR02"/>
</Property>
<Property>
<NameValue name="Manufacturer">SHA</NameValue>
</Property>
<Property>
<NameValue name="ManufacturerPart">16710761-001</NameValue>
</Property>
<Property>
<NameValue name="TransactionNumber"/>
</Property>
<Property>
<NameValue name="TransactionLine"/>
</Property>
<Property>
<NameValue name="UDFNUM02">2</NameValue>
</Property>
</UserArea>
</PurchaseOrderLine>
<PurchaseOrderLine>
<LineNumber>2</LineNumber>
<UserArea>
<Property>
<NameValue name="ActiveFlag">true</NameValue>
</Property>
<Property>
<NameValue name="ExchangeRate">1.00</NameValue>
</Property>
<Property>
<NameValue name="UDFCHAR02"/>
</Property>
<Property>
<NameValue name="Manufacturer">MIS</NameValue>
</Property>
<Property>
<NameValue name="ManufacturerPart">20021676+80</NameValue>
</Property>
<Property>
<NameValue name="TransactionNumber"/>
</Property>
<Property>
<NameValue name="TransactionLine"/>
</Property>
<Property>
<NameValue name="UDFCHAR11">18275884-001</NameValue>
</Property>
<Property>
<NameValue name="UDFNUM02"/>
</Property>
</UserArea>
</PurchaseOrderLine>
</PurchaseOrder>
</DataArea>
</SyncPurchaseOrder>'
drop table if exists #reqOnPo
select s.PO.value('*:UserArea[1]/*:Property[4]', 'nvarchar(50)') as MFG
--,s.PO.value('(/SyncPurchaseOrder/DataArea/PurchaseOrder/PurchaseOrderLine/UserArea/Property/NameValue[@name="Manufacturer"])[5]', 'nvarchar(max)') as MFG1
into #reqOnPo
from @POXML.nodes('./*:SyncPurchaseOrder/*:DataArea/*:PurchaseOrder/*:PurchaseOrderLine') as s(PO)
select * from #reqonpo
I have tried putting the name in place of the index value but i get errors.
</code></pre>
| [
{
"answer_id": 74446546,
"author": "Temba",
"author_id": 3593621,
"author_profile": "https://Stackoverflow.com/users/3593621",
"pm_score": 3,
"selected": true,
"text": "networkx"
},
{
"answer_id": 74446936,
"author": "Riccardo Bucco",
"author_id": 5296106,
"author_profile": "https://Stackoverflow.com/users/5296106",
"pm_score": 1,
"selected": false,
"text": "networkx"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510586/"
] |
74,446,444 | <p><strong>INPUT TABLE</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">pcd</th>
<th style="text-align: center;">INCOME</th>
<th style="text-align: right;">Education</th>
<th style="text-align: right;">age1to_20</th>
<th style="text-align: right;">TG</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">a1001</td>
<td style="text-align: center;">INCOME_1</td>
<td style="text-align: right;">Education_1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: left;">a1003</td>
<td style="text-align: center;">INCOME_2</td>
<td style="text-align: right;">Education_2</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">2</td>
</tr>
<tr>
<td style="text-align: left;">a1001</td>
<td style="text-align: center;">INCOME_3</td>
<td style="text-align: right;">Education_2</td>
<td style="text-align: right;">5</td>
<td style="text-align: right;">2</td>
</tr>
<tr>
<td style="text-align: left;">a1002</td>
<td style="text-align: center;">INCOME_2</td>
<td style="text-align: right;">Education_2</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">5</td>
</tr>
<tr>
<td style="text-align: left;">a1003</td>
<td style="text-align: center;">INCOME_1</td>
<td style="text-align: right;">Education_2</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">4</td>
</tr>
</tbody>
</table>
</div>
<p><strong>REQUIRED OUTPUT</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">pcd</th>
<th style="text-align: center;">INCOME_1</th>
<th style="text-align: right;">INCOME_2</th>
<th style="text-align: right;">INCOME_3</th>
<th style="text-align: right;">Education_1</th>
<th style="text-align: right;">Education_2</th>
<th style="text-align: right;">age1to_20</th>
<th style="text-align: right;">TG</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">a1001</td>
<td style="text-align: center;">1</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">6</td>
<td style="text-align: right;">1.5</td>
</tr>
<tr>
<td style="text-align: left;">a1002</td>
<td style="text-align: center;">0</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">5</td>
</tr>
<tr>
<td style="text-align: left;">a1003</td>
<td style="text-align: center;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">3</td>
</tr>
</tbody>
</table>
</div>
<p><em><strong>pcd is index and income1,income2,income3,education1,education2,age are aggregated to sum while TG is aggregated to average.</strong></em></p>
<pre><code>pd.pivot_table(df, index=['pcd', 'age1to_20'],
aggfunc={'INCOME':sum,'Education'=sum,'age1to_20'=sum,'TG':avg},fill_value=0)
</code></pre>
<p>Tried above code but finding no success</p>
| [
{
"answer_id": 74446570,
"author": "exokamen",
"author_id": 14662128,
"author_profile": "https://Stackoverflow.com/users/14662128",
"pm_score": 0,
"selected": false,
"text": "pd.pivot_table(df, index=['pcd', 'age1to_20'], \n values=['age1to_20']\n columns=['income', 'education']\n aggfunc={'INCOME':sum,'TG':avg},fill_value=0)\n"
},
{
"answer_id": 74446591,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "melt"
},
{
"answer_id": 74446727,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 1,
"selected": false,
"text": "x=pd.crosstab(df['pcd'],columns=df['INCOME'])\nprint(x)\n'''\nINCOME INCOME_1 INCOME_2 INCOME_3\npcd \na1001 1 0 1\na1002 0 1 0\na1003 1 1 0\n'''\n\ny=pd.crosstab([df['pcd']],columns=[df['Education']])\nz=df.groupby('pcd').agg({'age1to_20':'sum','TG':'mean'})\nfinal=x.join([y,z])\nprint(final)\n'''\n INCOME_1 INCOME_2 INCOME_3 Education_1 Education_2 age1to_20 TG\npcd \na1001 1 0 1 1 1 6 1.5\na1002 0 1 0 0 1 1 5.0\na1003 1 1 0 0 2 3 3.0\n'''\n\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13106084/"
] |
74,446,450 | <p>I'm still quite the beginner when it comes to more complex formula in Google Sheets. I'm trying to do an analysis for my company, the data is in a db-like table (CSV import), one of the columns contains a date, another one a status. I want to count how many times a certain status falls into a given week.</p>
<p>Here's an example (sheet "data"):</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Status</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>resolved</td>
<td>11/13/2022</td>
</tr>
<tr>
<td>resolved</td>
<td>11/13/2022</td>
</tr>
<tr>
<td>resolved</td>
<td>11/12/2022</td>
</tr>
<tr>
<td>created</td>
<td>11/10/2022</td>
</tr>
<tr>
<td>resolved</td>
<td>11/05/2022</td>
</tr>
<tr>
<td>created</td>
<td>11/04/2022</td>
</tr>
<tr>
<td>created</td>
<td>11/02/2022</td>
</tr>
</tbody>
</table>
</div>
<p>First three rows are week 44, the others week 43. I want a table that looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>week</th>
<th>created</th>
<th>resolved</th>
</tr>
</thead>
<tbody>
<tr>
<td>43</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>44</td>
<td>1</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p>So example for cell B2 of the result table have <code>=DCOUNTA(data!A1:B8,"Status",{"Status","Date";"created",[WEEK == A2]})</code><br />
(what I need in square brackets)</p>
<p>The problem I have is that the WEEK function expects an input, so how can I circumvent that? Does the DCOUNTA function work for this or do I need another function?</p>
<p>Thanks for your help!</p>
| [
{
"answer_id": 74446570,
"author": "exokamen",
"author_id": 14662128,
"author_profile": "https://Stackoverflow.com/users/14662128",
"pm_score": 0,
"selected": false,
"text": "pd.pivot_table(df, index=['pcd', 'age1to_20'], \n values=['age1to_20']\n columns=['income', 'education']\n aggfunc={'INCOME':sum,'TG':avg},fill_value=0)\n"
},
{
"answer_id": 74446591,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "melt"
},
{
"answer_id": 74446727,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 1,
"selected": false,
"text": "x=pd.crosstab(df['pcd'],columns=df['INCOME'])\nprint(x)\n'''\nINCOME INCOME_1 INCOME_2 INCOME_3\npcd \na1001 1 0 1\na1002 0 1 0\na1003 1 1 0\n'''\n\ny=pd.crosstab([df['pcd']],columns=[df['Education']])\nz=df.groupby('pcd').agg({'age1to_20':'sum','TG':'mean'})\nfinal=x.join([y,z])\nprint(final)\n'''\n INCOME_1 INCOME_2 INCOME_3 Education_1 Education_2 age1to_20 TG\npcd \na1001 1 0 1 1 1 6 1.5\na1002 0 1 0 0 1 1 5.0\na1003 1 1 0 0 2 3 3.0\n'''\n\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510109/"
] |
74,446,461 | <p>I have a nested list as follows:</p>
<pre><code>bpas = {{1, 1/19, 3}, {2, 3/19, 3}, {3, 7/19, 1}}
</code></pre>
<p>I want to replace the element whose first part equals to <code>2</code> with more than one element.
In this case it would be <code>{2, 3/19, 3}</code>, replaced by <code>{2, 6/19, 3}, {1, 1/19, 6}</code>.</p>
<p>Say, I want to get the following form:</p>
<pre><code>bpas = {{1, 1/19, 3}, {2, 6/19, 3}, {1, 1/19, 6}, {3, 7, 7/19, 1}}
</code></pre>
<p>I used the syntax <code>bpas /. {x_ /; x == 2, y_, z_} -> {{2, 2 y, z}, {1, y/3, 2 z}}</code>, but only getting:</p>
<pre><code>{{1, 1/19, 3}, {{2, 6/19, 3}, {1, 1/19, 6}}, {3, 7/19, 1}}
</code></pre>
<p>So, how can I get the proper output?</p>
| [
{
"answer_id": 74448051,
"author": "Bill",
"author_id": 2797269,
"author_profile": "https://Stackoverflow.com/users/2797269",
"pm_score": 0,
"selected": false,
"text": "bpas = {{1,1/19,3},{2,6/19,3},{1,1/19,6},{3,7,7/19,1}};\nbpas/.{head__,{2,y_,z_},tail__}->{head,{2,2y,z},{1,y/3,2z},tail}\n"
},
{
"answer_id": 74448430,
"author": "Chris Degnen",
"author_id": 879601,
"author_profile": "https://Stackoverflow.com/users/879601",
"pm_score": 2,
"selected": true,
"text": "bpas /. {x_ /; x == 2, y_, z_} -> Sequence[{2, 2 y, z}, {1, y/3, 2 z}]\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510509/"
] |
74,446,476 | <p>How it is posible to make a filter which is a comparison (a function)? So we can implement a filter like this</p>
<p>Because I got this console output:</p>
<blockquote>
<p>ERROR: aggregate functions are not allowed in WHERE</p>
<p>WHERE MAX(vr.utz) > p_utz_begin AND fu.id_fl</p>
</blockquote>
<p>this is the code.</p>
<pre><code>SELECT m_id_unit,
lf.CAN_freq,
lf.CAN_blackout,
lf.GPS_freq,
lf.GPS_blackout,
lf.chargeloss
FROM tlm.main_dash_tele_freq_blackout(m_id_unit, p_utz_begin, p_utz_end) lf
JOIN var.vreadings vr ON vr.id_unit = lf.m_id_unit
JOIN dat.fleet_units fu ON fu.id_unit = lf.m_id_unit
WHERE MAX(vr.utz) > p_utz_begin AND fu.id_fleet <> 10
</code></pre>
| [
{
"answer_id": 74448051,
"author": "Bill",
"author_id": 2797269,
"author_profile": "https://Stackoverflow.com/users/2797269",
"pm_score": 0,
"selected": false,
"text": "bpas = {{1,1/19,3},{2,6/19,3},{1,1/19,6},{3,7,7/19,1}};\nbpas/.{head__,{2,y_,z_},tail__}->{head,{2,2y,z},{1,y/3,2z},tail}\n"
},
{
"answer_id": 74448430,
"author": "Chris Degnen",
"author_id": 879601,
"author_profile": "https://Stackoverflow.com/users/879601",
"pm_score": 2,
"selected": true,
"text": "bpas /. {x_ /; x == 2, y_, z_} -> Sequence[{2, 2 y, z}, {1, y/3, 2 z}]\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14903696/"
] |
74,446,505 | <p>The module "Watch Updates" (webhook) since yesterday started returning only the ID of the updates, with every other field empty (message text, message ID, everything else).
Tried with different bots created with 2 different accounts (1 premium and 1 standard), and same result: empty update except for the update ID.
The "List Updates" module works fine and gives me everything for some reason. This is not an issue of having a webhook active while calling the List Updates method.
Every time I activate a "Watch Updates" module I dont use the "List Updates" module anymore.
This isssue started yesterday, how can I fix it?
(I tried with bot privacy enabled and disabled, in different group chats)</p>
| [
{
"answer_id": 74459850,
"author": "Redox15",
"author_id": 20519405,
"author_profile": "https://Stackoverflow.com/users/20519405",
"pm_score": 1,
"selected": false,
"text": "null"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16720310/"
] |
74,446,560 | <p>In my app users can register an account using Email authentication with Firebase, one of the required fields while registering is the phone number, which is stored as a string value in Firestore:</p>
<pre><code> final phoneField = TextFormField(
controller: phoneController,
keyboardType: TextInputType.phone,
autofocus: false,
autocorrect: false,
textInputAction: TextInputAction.next,
validator: (value) {
RegExp regex = RegExp(r'(^(?:[00]+)?[0-9]{10,15}$)');
if (value!.isEmpty) {
return AppLocalizations.of(context)!.phoneValidationEmpty;
}
if (!regex.hasMatch(value)) {
return ("Please Enter a Valid phone Number");
}
},
onSaved: (value) {
phoneController.text = value!;
},
textAlign: TextAlign.center,
decoration: InputDecoration(
prefixIcon: Icon(Icons.phone),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: AppLocalizations.of(context)!.phoneNumber,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
</code></pre>
<p>Am trying to add a functionality in the "validator" that can access the "Users" collection and check all documents (users information), especially the "phone" field for any duplication.</p>
<p>I tried using query snapshot but it seems am not using it properly, I appreciate any help.</p>
| [
{
"answer_id": 74448165,
"author": "Mark Munene",
"author_id": 20159503,
"author_profile": "https://Stackoverflow.com/users/20159503",
"pm_score": 0,
"selected": false,
"text": "import { beforeUserCreated } from \"firebase-functions/v2/identity\"; \n \n//runs before a user is created using firebase authentication\nexport const beforecreated = beforeUserCreated((event) => {\n // Check if phone number exists in firestore\n }); \n \n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17369207/"
] |
74,446,599 | <p>I have a java stand alone application. I build a jar, and I create a .exe file from this jar file.</p>
<p>Then I can start the application by double click on it. Now I need to create a .bat file to close the exe program. Now I build a .bat file like this:</p>
<pre><code>TASKKILL /F /PID easyManagement.exe
pause
</code></pre>
<p>the script is executed without error but the program easyManagement is every time on.</p>
<p><strong>EDIT</strong>
In task manager I can display my program like this:
<a href="https://i.stack.imgur.com/wuatD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wuatD.png" alt="enter image description here" /></a></p>
<p>This code:</p>
<pre><code>TASKKILL /IM easyManagement.exe
</code></pre>
<p>run without error but the application is on every time.</p>
| [
{
"answer_id": 74448165,
"author": "Mark Munene",
"author_id": 20159503,
"author_profile": "https://Stackoverflow.com/users/20159503",
"pm_score": 0,
"selected": false,
"text": "import { beforeUserCreated } from \"firebase-functions/v2/identity\"; \n \n//runs before a user is created using firebase authentication\nexport const beforecreated = beforeUserCreated((event) => {\n // Check if phone number exists in firestore\n }); \n \n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2405663/"
] |
74,446,607 | <p>Model:</p>
<pre><code>from django.db import models
class VilleStation(models.Model):
nomVille = models.CharField(max_length=255)
adresse = models.CharField(max_length=255)
cp = models.CharField(max_length=5)
def __str__(self):
return self.nomVille
</code></pre>
<p>admin.py :</p>
<pre><code>from django.contrib import admin
from prixcarbu.models import VilleStation
class VilleStationAdmin(admin.ModelAdmin):
list_display = ('nomVille', 'adresse','cp',)
fields = ('nomVille', 'adresse','cp',)
admin.site.register(VilleStation, VilleStationAdmin)
</code></pre>
<p>I imported a CSV file using database browser for SQLite. Table contains the data but admin page doesn't show it.</p>
| [
{
"answer_id": 74448165,
"author": "Mark Munene",
"author_id": 20159503,
"author_profile": "https://Stackoverflow.com/users/20159503",
"pm_score": 0,
"selected": false,
"text": "import { beforeUserCreated } from \"firebase-functions/v2/identity\"; \n \n//runs before a user is created using firebase authentication\nexport const beforecreated = beforeUserCreated((event) => {\n // Check if phone number exists in firestore\n }); \n \n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11230924/"
] |
74,446,611 | <p>How to add hours to a Date object?</p>
<p>This was a clock ONLY that is 1 hour ahead. Can be customized to whatever amount of hours you need.</p>
<p>This works in all time zones.</p>
<p>If you want to add more hours just change the output for each hour 0-23</p>
<pre><code>```
<script type="text/javascript">
window.onload = function () {
DisplayCurrentTime();
};
function DisplayCurrentTime() {
var date = new Date();
var a = date.getHours() == 0 ? "1" : "" ;
var b = date.getHours() == 1 ? "2" : "" ;
var c = date.getHours() == 2 ? "3" : "" ;
var d = date.getHours() == 3 ? "4" : "" ;
var e = date.getHours() == 4 ? "5" : "" ;
var f = date.getHours() == 5 ? "6" : "" ;
var g = date.getHours() == 6 ? "7" : "" ;
var h = date.getHours() == 7 ? "8" : "" ;
var i = date.getHours() == 8 ? "9" : "" ;
var j = date.getHours() == 9 ? "10" : "" ;
var k = date.getHours() == 10 ? "11" : "" ;
var l = date.getHours() == 11 ? "12" : "" ;
var m = date.getHours() == 12 ? "1" : "" ;
var n = date.getHours() == 13 ? "2" : "" ;
var o = date.getHours() == 14 ? "3" : "" ;
var p = date.getHours() == 15 ? "4" : "" ;
var q = date.getHours() == 16 ? "5" : "" ;
var r = date.getHours() == 17 ? "6" : "" ;
var s = date.getHours() == 18 ? "7" : "" ;
var t = date.getHours() == 19 ? "8" : "" ;
var u = date.getHours() == 20 ? "9" : "" ;
var v = date.getHours() == 21 ? "10" : "" ;
var w = date.getHours() == 22 ? "11" : "" ;
var x = date.getHours() == 23 ? "12" : "" ;
var am = date.getHours() <= 10 ? "AM" : "";
var pm = date.getHours() == 11 ? "PM" : "";
var pma = date.getHours() == 12 ? "PM" : "";
var pmb = date.getHours() == 13 ? "PM" : "";
var pmc = date.getHours() == 14 ? "PM" : "";
var pmd = date.getHours() == 15 ? "PM" : "";
var pme = date.getHours() == 16 ? "PM" : "";
var pmf = date.getHours() == 17 ? "PM" : "";
var pmg = date.getHours() == 18 ? "PM" : "";
var pmh = date.getHours() == 19 ? "PM" : "";
var pmi = date.getHours() == 20 ? "PM" : "";
var pmj = date.getHours() == 21 ? "PM" : "";
var pmk = date.getHours() == 22 ? "PM" : "";
var ama = date.getHours() == 23 ? "AM" : "";
var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
time = a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t + u + v + w + x + ":" + minutes + " " + am + pm + pma + pmb + pmc + pmd + pme + pmf + pmg + pmh + pmi + pmj + pmk + ama;
var lblTime = document.getElementById("lblTime");
lblTime.innerHTML = time;
};
</code></pre>
<p>One hour from now is: < span id='lblTime'></p>
<pre><code>
</code></pre>
| [
{
"answer_id": 74446732,
"author": "peinearydevelopment",
"author_id": 1874522,
"author_profile": "https://Stackoverflow.com/users/1874522",
"pm_score": 0,
"selected": false,
"text": "Date"
},
{
"answer_id": 74446959,
"author": "Build For Dev",
"author_id": 20477335,
"author_profile": "https://Stackoverflow.com/users/20477335",
"pm_score": 2,
"selected": true,
"text": "var datetime = new Date();\nconst timeFormat = { hour: '2-digit', minute: '2-digit'}\nconsole.log(\"Before: \", datetime.toLocaleTimeString('en-US', timeFormat));\n\n//ADD n Hour\ndatetime.setHours(datetime.getHours()+1); \nconsole.log(\"After: \", datetime.toLocaleTimeString('en-US', timeFormat));"
},
{
"answer_id": 74446968,
"author": "R4ncid",
"author_id": 14326899,
"author_profile": "https://Stackoverflow.com/users/14326899",
"pm_score": 0,
"selected": false,
"text": "const addHours = (date, hours) => \n new Date(date.getTime() + 3600 *1000 * hours)\n\nconst formatDate = date => {\n const hour = date.getHours()\n const minutes = date.getMinutes()\n const isAm = hour < 13\n return `${(isAm? hour: hour - 12).toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')} ${isAm? 'AM': 'PM'}`\n}\n\nconst addHourAndFormat = (date, hours) => formatDate(addHours(date, hours))\n\nconst date1 = new Date('2022-11-15 14:54:00')\nconst date2 = addHours(date1, 5)\n\nconsole.log(formatDate(date1))\nconsole.log(formatDate(date2))\n\nconsole.log(addHourAndFormat(date1, 13))"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510653/"
] |
74,446,635 | <p>I have a table as shown below</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Id</th>
<th>FName</th>
<th>Gender</th>
<th>StatusValue</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Sam</td>
<td>Male</td>
<td>SV001</td>
</tr>
<tr>
<td>2</td>
<td>Emma</td>
<td>Female</td>
<td>SV002</td>
</tr>
<tr>
<td>3</td>
<td>Ava</td>
<td>Unknown</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td>John</td>
<td>Male</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td>Olivia</td>
<td>Female</td>
<td></td>
</tr>
<tr>
<td>6</td>
<td>Joe</td>
<td>Male</td>
<td></td>
</tr>
<tr>
<td>7</td>
<td>Mia</td>
<td>Female</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>I want to display the below output</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Id</th>
<th>Gender</th>
<th>StatusValue</th>
<th>Count</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Female</td>
<td>SV001</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>Female</td>
<td>SV002</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>Female</td>
<td>Empty</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>Male</td>
<td>SV001</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>Male</td>
<td>SV002</td>
<td>0</td>
</tr>
<tr>
<td>6</td>
<td>Male</td>
<td>Empty</td>
<td>2</td>
</tr>
<tr>
<td>7</td>
<td>Unknown</td>
<td>SV001</td>
<td>0</td>
</tr>
<tr>
<td>8</td>
<td>Unknown</td>
<td>SV002</td>
<td>0</td>
</tr>
<tr>
<td>9</td>
<td>Unknown</td>
<td>Empty</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>Here I want to display all possible combinations with matching counts.
<strong>Note</strong>: cannot use common table expressions and PIVOT, since the tool is not supporting few of the SQL keywords.
I have tried the below but it is giving wrong count</p>
<pre><code>SELECT Gender,StatusValue,Count(*) as Count FROM Persons
WHERE Gender <> '' AND StatusValue <> ''
GROUP BY Gender,StatusValue
UNION
SELECT
CASE WHEN G.Gender <> '' THEN G.Gender ELSE 'Empty' END,
CASE WHEN T.StatusValue <> '' THEN T.StatusValue ELSE 'Empty' END, 0 as COUNT from
(SELECT DISTINCT Gender FROM Persons) as G, (SELECT DISTINCT StatusValue FROM Persons) as T
</code></pre>
| [
{
"answer_id": 74446732,
"author": "peinearydevelopment",
"author_id": 1874522,
"author_profile": "https://Stackoverflow.com/users/1874522",
"pm_score": 0,
"selected": false,
"text": "Date"
},
{
"answer_id": 74446959,
"author": "Build For Dev",
"author_id": 20477335,
"author_profile": "https://Stackoverflow.com/users/20477335",
"pm_score": 2,
"selected": true,
"text": "var datetime = new Date();\nconst timeFormat = { hour: '2-digit', minute: '2-digit'}\nconsole.log(\"Before: \", datetime.toLocaleTimeString('en-US', timeFormat));\n\n//ADD n Hour\ndatetime.setHours(datetime.getHours()+1); \nconsole.log(\"After: \", datetime.toLocaleTimeString('en-US', timeFormat));"
},
{
"answer_id": 74446968,
"author": "R4ncid",
"author_id": 14326899,
"author_profile": "https://Stackoverflow.com/users/14326899",
"pm_score": 0,
"selected": false,
"text": "const addHours = (date, hours) => \n new Date(date.getTime() + 3600 *1000 * hours)\n\nconst formatDate = date => {\n const hour = date.getHours()\n const minutes = date.getMinutes()\n const isAm = hour < 13\n return `${(isAm? hour: hour - 12).toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')} ${isAm? 'AM': 'PM'}`\n}\n\nconst addHourAndFormat = (date, hours) => formatDate(addHours(date, hours))\n\nconst date1 = new Date('2022-11-15 14:54:00')\nconst date2 = addHours(date1, 5)\n\nconsole.log(formatDate(date1))\nconsole.log(formatDate(date2))\n\nconsole.log(addHourAndFormat(date1, 13))"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20458386/"
] |
74,446,639 | <p>I want to make an app that opens many URL schemes.<br/>
To make it, I tried some ways:</p>
<ol>
<li><p>I used <code>UIApplication.shared.open(url, options: [:], completionHandler: nil)</code>. <br/>
But this way I must add the URL scheme in <code>info.plist</code>. <br/>
And in <code>info.plist</code> I can add a maximum of 50 URL schemes. <br/>
(I want to add over 50 URL schemes)</p>
</li>
<li><p>I tried using <code>WKWebView</code>. <br/>
But The <code>WKWebView</code> doesn't handle non-http URL schemas. <br/>
The webview only opens http, https. <br/></p>
</li>
</ol>
<p>I want to open over 50 URL schemes, what should I do?</p>
| [
{
"answer_id": 74451866,
"author": "Bulat Yakupov",
"author_id": 17834877,
"author_profile": "https://Stackoverflow.com/users/17834877",
"pm_score": 0,
"selected": false,
"text": "SafariServices"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8880303/"
] |
74,446,640 | <p><a href="https://i.stack.imgur.com/iDKS3.png" rel="nofollow noreferrer">why Flutter is showing Expected to find ','. in main.dart file</a></p>
<p>Flutter is showing Expected to find ','. in main.dart file</p>
<p><a href="https://i.stack.imgur.com/iDKS3.png" rel="nofollow noreferrer">https://i.stack.imgur.com/iDKS3.png</a></p>
| [
{
"answer_id": 74446689,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": "home: Scaffold(\n appBar: AppBar(...), //here a comma\n body: YoueBodyWidget(),\n \n),\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20215140/"
] |
74,446,643 | <p>I want to push my commit from repository to different repository in deploy stage but I did not do it.</p>
<pre><code>
deploy-job:
stage: deploy
before_script:
- 'which ssh-agent || ( apt-get update -qy && apt-get install openssh-client -qqy )'
- eval `ssh-agent -s`
- echo ${SSH_PRIVATE_KEY}
- echo ${SSH_PRIVATE_KEY}
## Create the SSH directory and give it the right permissions
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- echo "$SSH_PUBLIC_KEY" >> ~/.ssh/id_rsa.pub
- echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
script:
- git branch -a
- git config --global user.email "${CI_EMAIL}"
- git config --global user.name "${CI_USERNAME}"
- git add .
- git commit -m "Compiled PDF from $CI_COMMIT_SHORT_SHA [skip ci]" || echo "No changes, nothing to commit!"
- git remote rm origin && git remote add origin http://USERNAME:${USERNAME_password}@ip:3000/USERNAME/first_exe.git
- git branch -a
- git push -f -u origin main
</code></pre>
<p>But I take this error:</p>
<pre><code>To http://ip:3000/username/first_exe.git
! [remote rejected] main -> main (shallow update not allowed)
error: failed to push some refs to 'http://USERNAME:${USERNAME_password}@ip:3000/USERNAME/first_exe.git'
</code></pre>
<p>What is the problem?</p>
<p>Thanks.</p>
| [
{
"answer_id": 74446689,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": "home: Scaffold(\n appBar: AppBar(...), //here a comma\n body: YoueBodyWidget(),\n \n),\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12158653/"
] |
74,446,659 | <p><strong>Brief Context:</strong> I am trying to create a chat application where I want to load only N number of messages at first (say 20) and as the user scrolls up and reaches the top then more 20 messages are fetched via AJAX and prepended to the existing messages. These messages are older messages, of course. I searched everywhere for the logic to create an infinite scroll for reverse fetching rows from table and prepending but everywhere I got the infinite scroll to fetch and append the next rows which I do not want in this case. Therefore, I decided to try and create a logic or figure a way that I can do this reverse infinite scrolling myself. Hence, I tried doing the below thing.</p>
<p><strong>What I tried:</strong> When the first 20 messages are fetched and say their <code>id</code> are in range 81-100 then I capture the lower id 81 and place it as in the <code>data-id</code> attribute of the parent container of the chat box. Now, when <code>scroll</code> event is called I send this <code>id</code> which is 81 to the backend and run the query with <code>WHERE (id < 81 AND id >= 81-20) ORDER BY id ASC</code> and return the earlier 20 rows as required. In the <code>success</code> function of the AJAX call I update the new lower <code>id</code> to the parent element of the chatbox. Where earlier it was 81 now it would be 61.</p>
<p><strong>Problem:</strong> For the first scroll I can get the 81 detected properly but once the value changes the scroll element doesn't detect the updated value which is 61. It still returns 81.</p>
<p><strong>Expectations:</strong> How can I make the scroll event detect the updated <code>data-id</code> value whenever it user scrolls to the top?</p>
<p><strong>Code</strong></p>
<pre><code>var chatBox = $(".retrive-chat");
$('.chat-box').scroll(function (event) {
var st = $(this).scrollTop();
var lastid = $(this).find(".retrive-chat").data('id');
console.log(lastid); // RETURNS OLD VALUE EVERYTIME
// PREPEND OLD MESSAGES IN CHAT ON SCROLL TOP
if(st <= 10){
$.ajax({
url: 'processes/chat.php',
type: 'POST',
data: 'type=loadmore&to='+to+'&lastid='+lastid,
dataType: 'JSON',
success: function(data){
chatBox.attr('data-id', data.mid); // UPDATE VALUE WHEN THE NEWS ROWS ARE FETCHED
chatBox.prepend(data.html);
}
});
}
});
</code></pre>
<p>HTML</p>
<pre><code><div class="retrive-chat" data-id="81"></div>
</code></pre>
<p>This <code>data-id</code> value is initially assigned from another AJAX call and then later updated when the scroll event gets fired but the updated value is not detected when the scroll event is fired again. It keeps on using 81.</p>
| [
{
"answer_id": 74446704,
"author": "Kathara",
"author_id": 5621032,
"author_profile": "https://Stackoverflow.com/users/5621032",
"pm_score": 3,
"selected": true,
"text": ".data()"
},
{
"answer_id": 74446708,
"author": "Pointy",
"author_id": 182668,
"author_profile": "https://Stackoverflow.com/users/182668",
"pm_score": 1,
"selected": false,
"text": ".attr()"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337540/"
] |
74,446,686 | <p>I am trying to force a rejection for a <code>promise.allSettled()</code> function in a controlled way.
The idea is run a series of urls in batches through an API, this API from time to time returns a 500 error for a given request and it can be safetly retried. So I want to trigger a rejection on <code>promise.allSettled()</code> where I can collect the failing urls and later on rerun then on a recursion.</p>
<p><strong>Batchrequest function</strong></p>
<pre><code>export async function batchRequest(poolLimit, array, iteratorFn, exception) {
const promises = []
const racers = new Set()
for (const item of array) {
const pro = Promise.resolve().then(() => iteratorFn(item, array))
promises.push(pro)
racers.add(pro)
const clean = () => racers.delete(pro)
pro.then(clean).catch(clean)
if (racers.size >= poolLimit) await Promise.race(racers)
}
const results = await Promise.allSettled(promises)
// Collect errors rejected by iteratorFn,
const rejected = results
.filter(({ status, reason }) => status === 'rejected' && reason.name === exception)
.map(({ reason }) => reason.error)
// Recurse the array of rejected urls
if (rejected.length) {
await batchRequest(poolLimit, rejected, iteratorFn, exception)
}
}
</code></pre>
<p>Here we run the promises as normal but collect all rejected urls, I am trying to use the <code>exception</code> 'timeout' as the rule to determine if it needs to be rerun as it was just a timeout error.</p>
<p><strong>Iterator function</strong></p>
<pre><code>async function runRequest(url) {
try {
const { data } = await axios('https://exampleAPI.com')
// Take the data and write it somewhere...
} catch (error) {
if (error.response.status === 500) {
throw { name: 'timeout', url }
}
}
})
const urls = [...many urls]
await batchRequest(100, urls, runRequest, 'timeout')
</code></pre>
<p>I am getting an error saying</p>
<p><code>This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "#<Object>".] { code: 'ERR_UNHANDLED_REJECTION' }</code></p>
<p>How can I force a controlled rejection on <code>promise.allSettled()</code>?</p>
<p><strong>UPDATE</strong>-----</p>
<p>I found that the unhandled rejection was at the point in which I started the batchrequest</p>
<pre><code>await batchRequest(100, urls, runRequest, 'timeout')
</code></pre>
<p>It needs a try catch here:</p>
<pre><code>const urls = [...many urls]
try {
await batchRequest(100, urls, runRequest, 'timeout')
} catch (error) {
console.log(error)
}
</code></pre>
<p>but the whole point was to use the <code>promise.allSettled()</code> to absorb the error and not get out of the batchrequest</p>
| [
{
"answer_id": 74446704,
"author": "Kathara",
"author_id": 5621032,
"author_profile": "https://Stackoverflow.com/users/5621032",
"pm_score": 3,
"selected": true,
"text": ".data()"
},
{
"answer_id": 74446708,
"author": "Pointy",
"author_id": 182668,
"author_profile": "https://Stackoverflow.com/users/182668",
"pm_score": 1,
"selected": false,
"text": ".attr()"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10564162/"
] |
74,446,687 | <p>If I have this code,</p>
<pre><code>subroutine min_distance(r,n,k,centroid,distance,indices,distancereg)
integer, intent(out):: n,k
real,dimension(:,:),intent(in),allocatable::centroid
real,dimension(:,:),intent(in),allocatable::r
integer,dimension(:),intent(out),allocatable::indices,distancereg
real ::d_min
integer::y,i_min,j,i
integer,parameter :: data_dim=2
allocate (indices(n))
allocate (distancereg(k))
!cost=0.d0
do j=1,n
i_min = -1
d_min=1.d6
do i=1,k
distance=0.d0
distancereg(i)=0.d0
do y=1,data_dim
distance = distance+abs(r(y,j)-centroid(y,i))
distancereg(i)=distancereg(i)+abs(r(y,j)-centroid(y,i))
end do
if (distance<d_min) then
d_min=distance
i_min=i
end if
end do
if( i_min < 0 ) print*," found error by assigning k-index to particle ",j
indices(j)=i_min
end do
</code></pre>
<p>What I want to do is, when I calculate distance for each k, I want to paralelize it. ie. Assign each thread to do it. For example if k=3, then for k=1 the distance calculated by thread 1, and so on. I have tried with omp_nested, omp_ordered, but still showing some error. will appreciate if there is any advice / guidance .</p>
<p>Thanks</p>
| [
{
"answer_id": 74448025,
"author": "Victor Eijkhout",
"author_id": 2044454,
"author_profile": "https://Stackoverflow.com/users/2044454",
"pm_score": 1,
"selected": false,
"text": "j"
},
{
"answer_id": 74448694,
"author": "PierU",
"author_id": 14778592,
"author_profile": "https://Stackoverflow.com/users/14778592",
"pm_score": 1,
"selected": true,
"text": " do j=1,n\n distancereg(:)=0.d0\n !$OMP PARALLEL DO PRIVATE(y)\n do i=1,k\n do y=1,data_dim\n distancereg(i)=distancereg(i)+abs(r(y,j)-centroid(y,i))\n end do\n end do\n !$OMP PARALLEL END DO\n indices(j)=minloc(distancereg,dim=1)\n end do\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17615644/"
] |
74,446,695 | <p>I have a <code>login</code> route where I want to set a cookie after I verify the login credentials. <strong>The client and the server are on different ports</strong>.</p>
<pre><code>const app = express();
app.use(
cors({
credentials: true,
origin: true,
})
);
app.use(cookieParser());
app.use('/login', (req, res) => {
res.cookie('secureCookie', JSON.stringify({ id: 1 }), {
secure: false,
httpOnly: true,
});
return res.json({ success: true });
});
app.use('/check', (req, res) => {
console.log(req.cookies);
return res.json({ id: 1 });
});
</code></pre>
<p>The issue is that I don't see the cookie in the devtools (applications tab) after the login request returns. Also, when trying to fetch the <code>check</code> endpoint using <code>credentials: 'include'</code> it doesn't send the cookie.</p>
<p>What I'm doing wrong?</p>
<p>Here are the requests:</p>
<pre><code> fetch('http://localhost:4000/login');
fetch('http://localhost:4000/check', {
credentials: 'include',
});
</code></pre>
| [
{
"answer_id": 74446771,
"author": "Edoardo Sichelli",
"author_id": 14498331,
"author_profile": "https://Stackoverflow.com/users/14498331",
"pm_score": -1,
"selected": false,
"text": "res.json({ success: true });\n"
},
{
"answer_id": 74446856,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 2,
"selected": true,
"text": "credentials: include"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4159572/"
] |
74,446,715 | <p>I am trying to get the regex right to return one or the other but not both:
When I run for example the following:</p>
<pre><code>aws secretsmanager list-secrets | jq -r ".SecretList[] | select(.Name|match(\"example-*\")) | .Name "
</code></pre>
<p>it returns</p>
<pre><code>example-secret_key
</code></pre>
<p>as well as</p>
<pre><code>examplecompany-secret_key
</code></pre>
<p>how can I modify the command to return one and not the other? Thanks</p>
| [
{
"answer_id": 74446771,
"author": "Edoardo Sichelli",
"author_id": 14498331,
"author_profile": "https://Stackoverflow.com/users/14498331",
"pm_score": -1,
"selected": false,
"text": "res.json({ success: true });\n"
},
{
"answer_id": 74446856,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 2,
"selected": true,
"text": "credentials: include"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/323179/"
] |
74,446,719 | <p>I am learning C++ and was wondering if there is an equivalent to assigning a user input to a variable in one line, like you can do in C# for example:</p>
<p><code>string foo = Console.ReadLine();</code></p>
<p>I was hoping that one of these would work, but they don't.</p>
<p><code>const string foo = cin >> foo;</code></p>
<p><code>cin >> const string foo;</code></p>
<p>Ideally the variable should be a constant, but that's not necessarily a requirement.</p>
<p>Are there ways of one lining it in C++ or will I just have to learn to live with this?</p>
<pre><code>double foo = 0;
cin >> foo;
</code></pre>
| [
{
"answer_id": 74446834,
"author": "Robert Shepherd",
"author_id": 19970913,
"author_profile": "https://Stackoverflow.com/users/19970913",
"pm_score": 0,
"selected": false,
"text": "if(double b = 0; std::cin >> b)\n{\n // Code\n}\n"
},
{
"answer_id": 74446846,
"author": "john",
"author_id": 882003,
"author_profile": "https://Stackoverflow.com/users/882003",
"pm_score": 2,
"selected": false,
"text": "double console_read_double()\n{\n double x = 0.0;\n cin >> x;\n return x;\n}\n\nint main()\n{\n double y = console_read_double();\n double z = console_read_double();\n ...\n}\n"
},
{
"answer_id": 74447220,
"author": "DrosvarG",
"author_id": 11502610,
"author_profile": "https://Stackoverflow.com/users/11502610",
"pm_score": 0,
"selected": false,
"text": "const"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12215968/"
] |
74,446,725 | <p>I'm trying to recursively find c and header files in a script, while avoiding globbing out any that exist in the current directory.</p>
<pre><code>FILE_MATCH_LIST='"*.c","*.cc","*.cpp","*.h","*.hh","*.hpp"'
FILE_MATCH_REGEX=$(echo "$FILE_MATCH_LIST" | sed 's/,/ -o -name /g')
FILE_MATCH_REGEX="-name $FILE_MATCH_REGEX"
</code></pre>
<p>This does exactly what I want it to:</p>
<pre><code> + FILE_MATCH_REGEX='-name "*.c" -o -name "*.cc" -o -name "*.cpp" -o -name "*.h" -o -name "*.hh" -o -name "*.hpp"'
</code></pre>
<p>Now, if I call find with that string (in quotes), it maintains the leading and trailing quotes and breaks find:</p>
<pre><code>files=$(find $root_dir "$FILE_MATCH_REGEX" | grep -v $GREP_IGNORE_LIST)
+ find [directory] '-name "*.c" -o -name "*.cc" -o -name "*.cpp" -o -name "*.h" -o -name "*.hh" -o -name "*.hpp"'
</code></pre>
<p>This results in a "unknown predicate" error from find, because the entire predicate is single quoted.</p>
<p>If I drop the quotes from the variable in the find command, I get a strange behavior:</p>
<pre><code>files=$(find $root_dir $FILE_MATCH_REGEX | grep -v $GREP_IGNORE_LIST)
+ find [directory] -name '"*.c"' -o -name '"*.cc"' -o -name '"*.cpp"' -o -name '"*.h"' -o -name '"*.hh"' -o -name '"*.hpp"'
</code></pre>
<p>Where are these single quotes coming from? They exist if I echo that variable as well, but they aren't there in the command when I'm actually setting the <code>$FILE_MATCH_REGEX</code> (As seen at the beginning of the question).</p>
<p>This of course also breaks find, because it's looking for the actual double quoted string, instead of expanding the <code>*.h</code> etc.</p>
<p>How do I get these strings into find without all of these quoting woes?</p>
| [
{
"answer_id": 74447186,
"author": "vgersh99",
"author_id": 13680534,
"author_profile": "https://Stackoverflow.com/users/13680534",
"pm_score": 1,
"selected": false,
"text": "find"
},
{
"answer_id": 74448388,
"author": "tjm3772",
"author_id": 19271565,
"author_profile": "https://Stackoverflow.com/users/19271565",
"pm_score": 3,
"selected": true,
"text": "#!/bin/bash\npatterns=( '*.c' '*.cc' '*.h' '*.hh' )\nfind_args=( \"-name\" \"${patterns[0]}\" )\nfor (( i=1 ; i < \"${#patterns[@]}\" ; i++ )) ; do\n find_args+=( \"-o\" \"-name\" \"${patterns[i]}\" )\ndone\nfind [directory] \"${find_args[@]}\"\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4526336/"
] |
74,446,777 | <p>I am currently encountering this problem in my react native app using Firebase:</p>
<blockquote>
<p>Collection references must have an odd number of segments</p>
</blockquote>
<p>I've seen similar cases in stackoverflow but wasn't able to solve my problem. Here is my code :</p>
<pre><code> const getData = async () => {
console.log(user.uid + " ")
const col = collection(db, "users", user.uid)
const taskSnapshot = await getDoc(col)
console.log(taskSnapshot)
}
getData()
</code></pre>
<p>I am trying to open my document with the document reference (user.uid) but I am getting this error : <code>Collection references must have an odd number of segments</code></p>
<p>Hope you can help me solve this problem.</p>
| [
{
"answer_id": 74446822,
"author": "Dharmaraj",
"author_id": 13130697,
"author_profile": "https://Stackoverflow.com/users/13130697",
"pm_score": 2,
"selected": true,
"text": "getDoc()"
},
{
"answer_id": 74446824,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": "collection(db, \"users\", user.uid)\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15814593/"
] |
74,446,783 | <p>I need some help with grouping data by continuous values.</p>
<p>If I have this data.table</p>
<pre><code>dt <- data.table::data.table( a = c(1,1,1,2,2,2,2,1,1,2), b = seq(1:10), c = seq(1:10)+1 )
a b c
1: 1 1 2
2: 1 2 3
3: 1 3 4
4: 2 4 5
5: 2 5 6
6: 2 6 7
7: 2 7 8
8: 1 8 9
9: 1 9 10
10: 2 10 11
</code></pre>
<p>I need a group for every following equal values in column a. Of this group i need the first (also min possible) value of column b and the last (also max possible) value of column c.</p>
<p>Like this:</p>
<pre><code> a b c
1: 1 1 4
2: 2 4 8
3: 1 8 10
4: 2 10 11
</code></pre>
<p>Thank you very much for your help. I do not get it solved alone.</p>
| [
{
"answer_id": 74446872,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 3,
"selected": true,
"text": "> dt[, .(a = a[1], b = b[1], c = c[.N]), rleid(a)][, -1]\n a b c\n1: 1 1 4\n2: 2 4 8\n3: 1 8 10\n4: 2 10 11\n"
},
{
"answer_id": 74449341,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "dplyr"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15505651/"
] |
74,446,788 | <p>I am trying to print out a list holding objects and their attributes where every element in the list is printed in a new line. However, I don't know how or where to add '\n' when appending the object.</p>
<p><em>client_manager.py</em></p>
<pre><code>class ClientManager:
# Constructor for the client list
def __init__(self):
self.__client_list = []
def add_client(self, first_name, last_name, title, preferred_pronouns,
date_of_birth, occupation, account_balance, overdraft_limit):
self.__client_list.append(Client(first_name, last_name, title, preferred_pronouns,
date_of_birth, occupation, account_balance, overdraft_limit))
</code></pre>
<p><em>test.py</em></p>
<pre><code>def test_manager():
manager = ClientManager()
manager.add_client("John", "Smith", "Mr", "He/him", "06/08/2003", "student", 455.0, 100.0)
manager.add_client("Sam", "Mason", "Mr", "He/him", "01/09/2002", "student", 455.0, 100.0)
manager.print_client_list()
test_manager()
</code></pre>
<p>I would like to get an output like this:</p>
<pre><code>[Client(John, Smith, Mr, He/him, 06/08/2003, student, 455.0, 100.0),
Client(Sam, Mason, Mr, He/him, 06/08/2003, student, 455.0, 100.0)]
</code></pre>
<p>Instead of</p>
<pre><code>[Client(John, Smith, Mr, He/him, 06/08/2003, student, 455.0, 100.0), Client(Sam, Mason, Mr, He/him, 06/08/2003, student, 455.0, 100.0)]
</code></pre>
<p>I tried using join but that doesn't work and raises an error:</p>
<p>self.__client_list = '\n'.join(self.__client_list)</p>
<p>So how can you implement \n or should you use another method?</p>
| [
{
"answer_id": 74446872,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 3,
"selected": true,
"text": "> dt[, .(a = a[1], b = b[1], c = c[.N]), rleid(a)][, -1]\n a b c\n1: 1 1 4\n2: 2 4 8\n3: 1 8 10\n4: 2 10 11\n"
},
{
"answer_id": 74449341,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "dplyr"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14731803/"
] |
74,446,830 | <p>I am sending a request to some url. I Copied the curl url to get the code from curl to python tool. So all the headers are included, but my request is not working and I recieve status code 403 on printing and error code 1020 in the html output. The code is</p>
<pre><code>import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
# 'Accept-Encoding': 'gzip, deflate, br',
'DNT': '1',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
}
response = requests.get('https://v2.gcchmc.org/book-appointment/', headers=headers)
print(response.status_code)
print(response.cookies.get_dict())
with open("test.html",'w') as f:
f.write(response.text)
</code></pre>
<p>I also get cookies but not getting the desired response. I know I can do it with selenium but I want to know the reason behind this. Thanks in advance.
<strong>Note:</strong>
I have installed all the libraries installed with request with same version as computer and still not working and throwing 403 error</p>
| [
{
"answer_id": 74446872,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 3,
"selected": true,
"text": "> dt[, .(a = a[1], b = b[1], c = c[.N]), rleid(a)][, -1]\n a b c\n1: 1 1 4\n2: 2 4 8\n3: 1 8 10\n4: 2 10 11\n"
},
{
"answer_id": 74449341,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "dplyr"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13849446/"
] |
74,446,854 | <p>I have an array of objects Called Lines. The <strong>Lines</strong> array is inside <strong>rows</strong> array & the rows array is inside <strong>tabs</strong> array. I want to take some data from lines array & put them in another array called <strong>colors</strong></p>
<p>the array look like this----</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"tabs": [{
"selectedHouseType": "1",
"rows": [{
"selectedDecor": "2",
"lines": [{
"selectedColor": "white",
"selectedQty": 0,
"selectedUnit": "1",
}, {
"selectedColor": "black",
"selectedQty": "2",
"selectedUnit": "3",
}]
}, {
"selectedDecor": "1",
"lines": [{
"selectedColor": "black",
"selectedQty": 0,
"selectedUnit": "2",
"
}]
}]
}, {
"selectedHouseType": "select",
"rows": [{
"selectedDecor": "2",
"lines": [{
"selectedColor": "red",
"selectedQty": 0,
"selectedUnit": "",
}]
}]
}]</code></pre>
</div>
</div>
</p>
<p>I want to collect the datas from <strong>lines</strong> array & put them in another array called "<strong>colors</strong>"</p>
<p>which will look like this---</p>
<pre><code>colors: [{
"selectedColor": "white",
"selectedQty": 0,
"selectedUnit": "1",
}, {
"selectedColor": "black",
"selectedQty": "2",
"selectedUnit": "3",
},
{
"selectedColor": "black",
"selectedQty": 0,
"selectedUnit": "2",
},
{
"selectedColor": "red",
"selectedQty": 0,
"selectedUnit": "",
}
]
</code></pre>
<p>I am using <strong>vue js</strong>. How do I do this?</p>
| [
{
"answer_id": 74446872,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 3,
"selected": true,
"text": "> dt[, .(a = a[1], b = b[1], c = c[.N]), rleid(a)][, -1]\n a b c\n1: 1 1 4\n2: 2 4 8\n3: 1 8 10\n4: 2 10 11\n"
},
{
"answer_id": 74449341,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "dplyr"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19813093/"
] |
74,446,875 | <p>Creating a demo for setting submit button disabled until all are required <code>TextField</code> is not empty...</p>
<p>username and password <code>TextField</code> are empty.. then submit button should be disabled...</p>
<p>I have done with my basic way, but looking for advanced code so that it can be not repeated typing like I have more text fields</p>
<p>here is my basic code...</p>
<pre><code>class _Stack4State extends State<Stack4> {
TextEditingController txtusername = TextEditingController();
TextEditingController txtpassword = TextEditingController();
bool isenable = false;
void checkfieldvalue(String username, String password) {
if (username.length > 3 && password.length > 6) {
setState(() {
isenable = true;
});
} else {
setState(() {
isenable = false;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[300],
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
const SizedBox(
height: 20,
),
TextField(
controller: txtusername,
onChanged: (value) {
checkfieldvalue(txtusername.text, txtpassword.text);
},
),
SizedBox(
height: 20,
),
TextField(
controller: txtpassword,
onChanged: (value) {
checkfieldvalue(txtusername.text, txtpassword.text);
}),
const SizedBox(
height: 20,
),
ElevatedButton(
child: isenable ? Text('Register') : Text('Fill Data First'),
onPressed: () {
if (isenable == true) {
//code for submit
}
},
),
]),
),
),
);
}
}
</code></pre>
| [
{
"answer_id": 74446872,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 3,
"selected": true,
"text": "> dt[, .(a = a[1], b = b[1], c = c[.N]), rleid(a)][, -1]\n a b c\n1: 1 1 4\n2: 2 4 8\n3: 1 8 10\n4: 2 10 11\n"
},
{
"answer_id": 74449341,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "dplyr"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18817235/"
] |
74,446,884 | <pre><code>def my_function(x,y,z):
out = True
if(x < y) | (x > z):
out = False
return out
</code></pre>
<p>Can you help me understand what this is doing? Is it, "out is True, but if x is less than y or greater than z: out is False"? I am unsure about the <code>|</code> operator.</p>
| [
{
"answer_id": 74446927,
"author": "Temba",
"author_id": 3593621,
"author_profile": "https://Stackoverflow.com/users/3593621",
"pm_score": 0,
"selected": false,
"text": "testValues = [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]\nfor x, y, z in testValues:\n print(\"The values are: x = %d, y = %d, z = %d\" % (x, y, z))\n print(\"out is:\", my_function(x, y, z))\n"
},
{
"answer_id": 74447107,
"author": "morri_bdoc",
"author_id": 20509535,
"author_profile": "https://Stackoverflow.com/users/20509535",
"pm_score": -1,
"selected": false,
"text": "def my_function(x,y,z):\n global out\n out = True\n if(x < y) | (x > z):\n out = False\n return out\n\n\nx = 6\ny = 2\nz = 5\nmy_function(x,y,z)\n"
},
{
"answer_id": 74447119,
"author": "Jared Smith",
"author_id": 3757232,
"author_profile": "https://Stackoverflow.com/users/3757232",
"pm_score": 2,
"selected": false,
"text": ">"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510744/"
] |
74,446,978 | <p>I've spent quite a lot of time figuring it out but I'm stuck, I have a nested JSON and I want to enrich the values of "attr" with those matching the keys of "codes", thanks in advance.</p>
<p>My Input JSON:</p>
<pre class="lang-json prettyprint-override"><code>{
"items": {
"a1b2xxxx": {
"name": "item 1",
"attr": [
"A",
"B",
"C"
]
},
"c2b2cxxxx": {
"name": "item 2",
"attr": [
"D",
"E",
"F"
]
}
},
"codes": {
"A": {
"color": "green"
},
"B": {
"size": "M"
},
"C": {
"sku": "NS"
},
"D": {
"stock": 2
},
"E": {
"some_key": "some_value"
},
"F": {
"foo": "bar"
}
}
}
</code></pre>
<p>My Desired Output JSON:</p>
<pre class="lang-json prettyprint-override"><code>{
"items": {
"a1b2xxxx": {
"name": "item 1",
"attr": {
"A": {
"color": "green"
},
"B": {
"size": "M"
},
"C": {
"sku": "NS"
}
}
},
"c2b2xxxx": {
"name": "item 2",
"attr": {
"D": {
"stock": 2
},
"E": {
"some_key": "some_value"
},
"F": {
"foo": "bar"
}
}
}
},
"codes": {
"A": {
"color": "green"
},
"B": {
"size": "M"
},
"C": {
"sku": "NS"
},
"D": {
"stock": 2
},
"E": {
"some_key": "some_value"
},
"F": {
"foo": "bar"
}
}
}
</code></pre>
<p>My approach is following:</p>
<ol>
<li>Using <strong>cardinality</strong> operation convert <code>attr</code> to an array of objects</li>
<li>Then maybe I can map values from codes using <strong>modify-default-beta</strong></li>
</ol>
<p>But I am stuck at step 1. Here is my transformer:</p>
<pre class="lang-json prettyprint-override"><code>[
{
"operation": "cardinality",
"spec": {
"items": {
"*": {
"attr": "ONE"
}
}
}
}
]
</code></pre>
| [
{
"answer_id": 74446927,
"author": "Temba",
"author_id": 3593621,
"author_profile": "https://Stackoverflow.com/users/3593621",
"pm_score": 0,
"selected": false,
"text": "testValues = [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]\nfor x, y, z in testValues:\n print(\"The values are: x = %d, y = %d, z = %d\" % (x, y, z))\n print(\"out is:\", my_function(x, y, z))\n"
},
{
"answer_id": 74447107,
"author": "morri_bdoc",
"author_id": 20509535,
"author_profile": "https://Stackoverflow.com/users/20509535",
"pm_score": -1,
"selected": false,
"text": "def my_function(x,y,z):\n global out\n out = True\n if(x < y) | (x > z):\n out = False\n return out\n\n\nx = 6\ny = 2\nz = 5\nmy_function(x,y,z)\n"
},
{
"answer_id": 74447119,
"author": "Jared Smith",
"author_id": 3757232,
"author_profile": "https://Stackoverflow.com/users/3757232",
"pm_score": 2,
"selected": false,
"text": ">"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74446978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14041796/"
] |
74,447,004 | <p>This is a signup form from MAILCHIMP I'm trying to customize.
I'm almost there, I just need to put the checkbox to the left of the sentence before it.</p>
<p><img src="https://i.stack.imgur.com/3YXZx.png" alt="Screenshot" /></p>
<p>I tried using all sorts of "align" commands in CSS with the checkbox object as the class name, also the parent objects it sits inside. No luck. I'm sure I'm missing something simple...</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>@font-face {
font-family: museo-sans;
src: url(/fonts/museosans_300.otf) format("opentype");
font-display: auto;
font-style: normal;
font-weight: 300;
font-stretch: normal
}
@font-face {
font-family: museo-sans-bold;
src: url(/fonts/museosans_700.otf) format("opentype");
font-display: auto;
font-style: normal;
font-weight: 700;
font-stretch: normal
}
@font-face {
font-family: bwstretch;
src: url(/fonts/BWSTRETCH-BLACK.OTF) format("opentype");
font-display: auto;
font-style: normal;
font-weight: 800;
font-stretch: normal
}
h2 {
font-family: bwstretch;
text-align: center;
text-transform: uppercase;
font-size: 2em !important;
}
* {
margin: 0;
padding: 0;
border: none;
font-family: museo-sans;
color: #ffc860;
}
body {
font-size: 1em;
background-color: #191f43;
font-family: museo-sans;
}
#wrapper {
width: 80% overflow: auto;
/* will contain if #first is longer than #second */
background-color: #191f43;
}
#first {
width: 40%;
float: left;
/* add this */
padding-left: 5%;
background-color: #191f43;
}
#mc_embed_signup {
width: 60% float:left;
/* add this */
overflow: hidden;
/* if you don't want #second to wrap below #first */
background-color: #191f43;
color: #ffc860;
font-family: museo-sans;
}
#mc-embedded-subscribe-form input[type=checkbox] {
display: flex;
width: auto;
}
#mergeRow-gdpr {
margin-top: 20px;
}
#mergeRow-gdpr fieldset label {
font-weight: normal;
}
#mc-embedded-subscribe-form .mc_fieldset {
border: none;
min-height: 0px;
padding-bottom: 0px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<!-- Start MailChimp stuff -->
<!-- Begin Mailchimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-071822.css" rel="stylesheet" type="text/css">
<div id="wrapper">
<div id="first"><img src="https://via.placeholder.com/100"></div>
<div id="mc_embed_signup">
<form action="https://opipets.us17.list-manage.com/subscribe/post?u=3fa8d83aedc08e2a8814c787c&amp;id=27f9c81072&amp;v_id=4140&amp;f_id=00bb56e0f0" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank"
novalidate>
<div id="mc_embed_signup_scroll">
<h2>Join our Whitelist</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address <span class="asterisk">*</span>
</label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" required>
</div>
<div id="mergeRow-gdpr" class="mergeRow gdpr-mergeRow content__gdprBlock mc-field-group">
<div class="content__gdpr">
<p>I agree to receive email communications from Opis Group Ltd</p>
<br>
<fieldset class="mc_fieldset gdprRequired mc-field-group" name="interestgroup_field">
<label class="checkbox subfield" for="gdpr_90860"><input type="checkbox" id="gdpr_90860" name="gdpr[90860]" value="Y" class="av-checkbox gdpr"></label>
</fieldset>
<p>Your privacy is our policy. Occasionally, we'll contact you about our products and services, and other content that may be of interest. You can unsubscribe at any time.</p>
</div>
<div class="content__gdprLegal">
<p>We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. <a href="https://mailchimp.com/legal/terms" target="_blank">Learn more about Mailchimp's privacy practices here.</a></p>
</div>
</div>
<div hidden="true"><input type="hidden" name="tags" value="6456416,6456520"></div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_3fa8d83aedc08e2a8814c787c_27f9c81072" tabindex="-1" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</div>
</form>
</div>
</div>
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script>
<script type='text/javascript'>
(function($) {
window.fnames = new Array();
window.ftypes = new Array();
fnames[0] = 'EMAIL';
ftypes[0] = 'email';
}(jQuery));
var $mcj = jQuery.noConflict(true);
</script>
<!--End mc_embed_signup-->
<!-- End MailChimp stuff -->
</body></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74447190,
"author": "Cazlo",
"author_id": 19743717,
"author_profile": "https://Stackoverflow.com/users/19743717",
"pm_score": 0,
"selected": false,
"text": "display: flex;"
},
{
"answer_id": 74447310,
"author": "isherwood",
"author_id": 1264804,
"author_profile": "https://Stackoverflow.com/users/1264804",
"pm_score": 1,
"selected": false,
"text": "@font-face {\n font-family: museo-sans;\n src: url(/fonts/museosans_300.otf) format(\"opentype\");\n font-display: auto;\n font-style: normal;\n font-weight: 300;\n font-stretch: normal\n}\n\n@font-face {\n font-family: museo-sans-bold;\n src: url(/fonts/museosans_700.otf) format(\"opentype\");\n font-display: auto;\n font-style: normal;\n font-weight: 700;\n font-stretch: normal\n}\n\n@font-face {\n font-family: bwstretch;\n src: url(/fonts/BWSTRETCH-BLACK.OTF) format(\"opentype\");\n font-display: auto;\n font-style: normal;\n font-weight: 800;\n font-stretch: normal\n}\n\nh2 {\n font-family: bwstretch;\n text-align: center;\n text-transform: uppercase;\n font-size: 2em !important;\n}\n\n* {\n margin: 0;\n padding: 0;\n border: none;\n font-family: museo-sans;\n color: #ffc860;\n}\n\nbody {\n font-size: 1em;\n background-color: #191f43;\n font-family: museo-sans;\n}\n\n#wrapper {\n width: 80% overflow: auto;\n /* will contain if #first is longer than #second */\n background-color: #191f43;\n}\n\n#first {\n width: 40%;\n float: left;\n /* add this */\n padding-left: 5%;\n background-color: #191f43;\n}\n\n#mc_embed_signup {\n width: 60% float:left;\n /* add this */\n overflow: hidden;\n /* if you don't want #second to wrap below #first */\n background-color: #191f43;\n color: #ffc860;\n font-family: museo-sans;\n}\n\n#mc_embed_signup .mc-field-group input[type=checkbox] {\n width: auto;\n display: inline-block;\n}\n\n#mergeRow-gdpr {\n margin-top: 20px;\n}\n\n#mergeRow-gdpr fieldset label {\n font-weight: normal;\n}\n\n#mc-embedded-subscribe-form .mc_fieldset {\n border: none;\n min-height: 0px;\n padding-bottom: 0px;\n}"
},
{
"answer_id": 74447398,
"author": "Bugginthesystem ",
"author_id": 19295912,
"author_profile": "https://Stackoverflow.com/users/19295912",
"pm_score": 2,
"selected": true,
"text": "@font-face {\n font-family: museo-sans;\n src: url(/fonts/museosans_300.otf) format(\"opentype\");\n font-display: auto;\n font-style: normal;\n font-weight: 300;\n font-stretch: normal\n}\n\n@font-face {\n font-family: museo-sans-bold;\n src: url(/fonts/museosans_700.otf) format(\"opentype\");\n font-display: auto;\n font-style: normal;\n font-weight: 700;\n font-stretch: normal\n}\n\n@font-face {\n font-family: bwstretch;\n src: url(/fonts/BWSTRETCH-BLACK.OTF) format(\"opentype\");\n font-display: auto;\n font-style: normal;\n font-weight: 800;\n font-stretch: normal\n}\n\nh2 {\n font-family: bwstretch;\n text-align: center;\n text-transform: uppercase;\n font-size: 2em !important;\n}\n\n* {\n margin: 0;\n padding: 0;\n border: none;\n font-family: museo-sans;\n color: #ffc860;\n}\n\nbody {\n font-size: 1em;\n background-color: #191f43;\n font-family: museo-sans;\n}\n\n#wrapper {\n width: 80%;\n overflow: auto; /* will contain if #first is longer than #second */\n background-color: #191f43;\n}\n\n#first {\n width: 40%;\n float:left; /* add this */\n padding-left: 5%;\n background-color: #191f43;\n}\n\n#mc_embed_signup {\n width: 60%;\n float:left; /* add this */\n overflow: hidden; /* if you don't want #second to wrap below #first */\n background-color: #191f43;\n color: #ffc860;\n font-family: museo-sans;\n}\n\n#mc-embedded-subscribe-form input[type=checkbox]{\n display: flex;\n width: auto;\n}\n\n#mergeRow-gdpr {\n margin-top: 20px;\n}\n\n#mergeRow-gdpr fieldset label {\n font-weight: normal;\n}\n\n#mc-embedded-subscribe-form .mc_fieldset{\n border:none;\n min-height: 0px;\n padding-bottom:0px;}\n\n\nspan{\n display: flex;\n align-items: center;\n}"
},
{
"answer_id": 74447928,
"author": "Ali Iqbal",
"author_id": 20321054,
"author_profile": "https://Stackoverflow.com/users/20321054",
"pm_score": 0,
"selected": false,
"text": " <div style=\"display:flex\">\n <input type=\"checkbox\">\n <p>I agree to receive email communications from Opis Group Ltd</p>\n </div>\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19818844/"
] |
74,447,041 | <p>I found this partial solution to my problem:</p>
<p><a href="https://stackoverflow.com/a/73193498/10789707">Google Sheets auto increment column A if column B is not empty</a></p>
<p>With this formula:</p>
<p><code>=ARRAYFORMULA(IFERROR(MATCH($B$2:$B&ROW($B$2:$B),FILTER($B$2:$B&ROW($B$2:$B),$B$2:$B<>""),0)))</code></p>
<p>What I need is the same but instead of continuous numbers I'd need it to restart incrementing from 1 at each new category string on an adjacent column (column A in example below, categories strings are A, B, C, D etc.).</p>
<p>For example:</p>
<p><a href="https://i.stack.imgur.com/OcJcO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OcJcO.png" alt="COLUMNS C AND D" /></a></p>
<p>Problem with formula in C12 and C15 (added numbers 1 and 2)</p>
<p>Needed result in column D, as with D11 and D19 restarts incrementing from 1 at new category string)</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>1</th>
<th></th>
<th></th>
<th></th>
<th>needed result</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>A</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>A</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>4</td>
<td>A</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>5</td>
<td>A</td>
<td>1</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>6</td>
<td>A</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>7</td>
<td>A</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>8</td>
<td>A</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>9</td>
<td>A</td>
<td>1</td>
<td>3</td>
<td>3</td>
</tr>
<tr>
<td>10</td>
<td>A</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>11</td>
<td>B</td>
<td>1</td>
<td>4</td>
<td>1</td>
</tr>
<tr>
<td>12</td>
<td>B</td>
<td></td>
<td>1</td>
<td></td>
</tr>
<tr>
<td>13</td>
<td>B</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>14</td>
<td>C</td>
<td>1</td>
<td>5</td>
<td>2</td>
</tr>
<tr>
<td>15</td>
<td>C</td>
<td></td>
<td>2</td>
<td></td>
</tr>
<tr>
<td>16</td>
<td>C</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>17</td>
<td>C</td>
<td>1</td>
<td>6</td>
<td>3</td>
</tr>
<tr>
<td>18</td>
<td>C</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>19</td>
<td>D</td>
<td>1</td>
<td>7</td>
<td>1</td>
</tr>
<tr>
<td>20</td>
<td>D</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>21</td>
<td>D</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>22</td>
<td>D</td>
<td>1</td>
<td>8</td>
<td>2</td>
</tr>
<tr>
<td>23</td>
<td>D</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>24</td>
<td>D</td>
<td>1</td>
<td>9</td>
<td>3</td>
</tr>
<tr>
<td>25</td>
<td>D</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>26</td>
<td>D</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>27</td>
<td>D</td>
<td>1</td>
<td>10</td>
<td>4</td>
</tr>
<tr>
<td>28</td>
<td>D</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>29</td>
<td>D</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74447231,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 3,
"selected": true,
"text": "=INDEX(IF(B2:B=\"\",,COUNTIFS(A2:A&B2:B, A2:A&B2:B, ROW(A2:A), \"<=\"&ROW(A2:A))))\n"
},
{
"answer_id": 74447333,
"author": "ztiaa",
"author_id": 17887301,
"author_profile": "https://Stackoverflow.com/users/17887301",
"pm_score": 2,
"selected": false,
"text": "=ArrayFormula(if(B2:B=\"\",,countifs(A2:A,A2:A,B2:B,\"<>\",row(A2:A),\"<=\"&row(A2:A))))\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10789707/"
] |
74,447,074 | <pre><code>var alphabet = "FIN SLHOJVHEN GYKOHU";
</code></pre>
<p>I want to split it every 2 character so it would print
"I LOVE YOU "</p>
<p>I already try this but it didn't work</p>
<pre><code>for (var i = 0 ; i \< alphabet.length ; i+=2 ){
alphabet.split(i)
</code></pre>
<p>correct me please</p>
| [
{
"answer_id": 74447171,
"author": "Diego D",
"author_id": 1221208,
"author_profile": "https://Stackoverflow.com/users/1221208",
"pm_score": 1,
"selected": false,
"text": "split"
},
{
"answer_id": 74447180,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "var alphabet = \"FIN SLHOJVHEN GYKOHU\";\nvar output = alphabet.replace(/[A-Z]([A-Z]|(?=\\s))/g, \"$1\");\nconsole.log(output);"
},
{
"answer_id": 74447205,
"author": "Warm Red",
"author_id": 14209943,
"author_profile": "https://Stackoverflow.com/users/14209943",
"pm_score": 2,
"selected": false,
"text": "let alphabet = \"FIN SLHOJVHEN GYKOHU\";\nalphabet = [...alphabet].filter((_, i) => i%2).join(\"\");\nconsole.log(alphabet); //I LOVE YOU;\n"
},
{
"answer_id": 74447403,
"author": "pier farrugia",
"author_id": 19996700,
"author_profile": "https://Stackoverflow.com/users/19996700",
"pm_score": 1,
"selected": false,
"text": "let alphabet = \"FIN SLHOJVHEN GYKOHU\";\nlet toPrint = '';\ndo {\n let temp = alphabet.slice(0, 2);\n toPrint += temp[1];\n alphabet = alphabet.slice(2, alphabet.length);\n} while (alphabet !== '');\nconsole.log(toPrint);"
},
{
"answer_id": 74448180,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 1,
"selected": false,
"text": "\\<"
},
{
"answer_id": 74451876,
"author": "bobble bubble",
"author_id": 5527985,
"author_profile": "https://Stackoverflow.com/users/5527985",
"pm_score": 2,
"selected": false,
"text": "I LOVE YOU"
},
{
"answer_id": 74487210,
"author": "Ankit Kumar",
"author_id": 15285399,
"author_profile": "https://Stackoverflow.com/users/15285399",
"pm_score": -1,
"selected": false,
"text": "var alphabet = \"FIN SLHOJVHEN GYKOHU\";\nconst arrayAlpha = alphabet.split('');\nlet stringToPrint = '';\nfor(let i=1; i<arrayAlpha.length; i+=2){\nstringToPrint = stringToPrint + arrayAlpha[i]\n}\n\nconsole.log(stringToPrint)\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20446649/"
] |
74,447,077 | <p>I am currently trying to sort a list of objects in this case students, based on their grades, student number, name, etc.</p>
<pre><code> listOfStudents.sort([](const Students& student1, const Students& student2)
{
if (student1.getStudentNumber() == student2.getStudentNumber())
return student1 < student2;
return student1.getStudentNumber() < student2.getStudentNumber();
});
</code></pre>
<p><strong>This is the code I am currently using</strong> to sort the list based on their student number but it points an error to the student1 and student2 saying "The object has type qualifiers that are not compatible".</p>
<p><strong>Here is the code for the Student Class:</strong></p>
<pre><code>class Students {
int studentNumber;
string studentName;
int grade1;
int grade2;
int grade3;
int grade4;
int grade5;
int total;
public:
void setStudent(int number, string name, int g1, int g2, int g3, int g4, int g5, int total) {
this->studentNumber = number;
this->studentName = name;
this->grade1 = g1;
this->grade2 = g2;
this->grade3 = g3;
this->grade4 = g4;
this->grade5 = g5;
this->total = total;
}
int getStudentNumber() {
return this->studentNumber;
}
string getStudentName() {
return this->studentName;
}
int getGrade1() {
return this->grade1;
}
int getGrade2() {
return this->grade2;
}
int getGrade3() {
return this->grade3;
}
int getGrade4() {
return this->grade4;
}
int getGrade5() {
return this->grade5;
}
int getTotal() {
return this->total;
}
};
</code></pre>
<p>and this is the implementation part</p>
<pre><code> list <Students> listOfStudents;
Students students;
</code></pre>
<p>The above codes are currently producing errors about the list type qualifiers etc.</p>
<p>Did I miss something? Im sure I did. Thank you in advance for relieving my idiocy.</p>
| [
{
"answer_id": 74447171,
"author": "Diego D",
"author_id": 1221208,
"author_profile": "https://Stackoverflow.com/users/1221208",
"pm_score": 1,
"selected": false,
"text": "split"
},
{
"answer_id": 74447180,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "var alphabet = \"FIN SLHOJVHEN GYKOHU\";\nvar output = alphabet.replace(/[A-Z]([A-Z]|(?=\\s))/g, \"$1\");\nconsole.log(output);"
},
{
"answer_id": 74447205,
"author": "Warm Red",
"author_id": 14209943,
"author_profile": "https://Stackoverflow.com/users/14209943",
"pm_score": 2,
"selected": false,
"text": "let alphabet = \"FIN SLHOJVHEN GYKOHU\";\nalphabet = [...alphabet].filter((_, i) => i%2).join(\"\");\nconsole.log(alphabet); //I LOVE YOU;\n"
},
{
"answer_id": 74447403,
"author": "pier farrugia",
"author_id": 19996700,
"author_profile": "https://Stackoverflow.com/users/19996700",
"pm_score": 1,
"selected": false,
"text": "let alphabet = \"FIN SLHOJVHEN GYKOHU\";\nlet toPrint = '';\ndo {\n let temp = alphabet.slice(0, 2);\n toPrint += temp[1];\n alphabet = alphabet.slice(2, alphabet.length);\n} while (alphabet !== '');\nconsole.log(toPrint);"
},
{
"answer_id": 74448180,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 1,
"selected": false,
"text": "\\<"
},
{
"answer_id": 74451876,
"author": "bobble bubble",
"author_id": 5527985,
"author_profile": "https://Stackoverflow.com/users/5527985",
"pm_score": 2,
"selected": false,
"text": "I LOVE YOU"
},
{
"answer_id": 74487210,
"author": "Ankit Kumar",
"author_id": 15285399,
"author_profile": "https://Stackoverflow.com/users/15285399",
"pm_score": -1,
"selected": false,
"text": "var alphabet = \"FIN SLHOJVHEN GYKOHU\";\nconst arrayAlpha = alphabet.split('');\nlet stringToPrint = '';\nfor(let i=1; i<arrayAlpha.length; i+=2){\nstringToPrint = stringToPrint + arrayAlpha[i]\n}\n\nconsole.log(stringToPrint)\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20510986/"
] |
74,447,110 | <p>It's possible to create this file structure with one line of code in bash?</p>
<pre><code>├── assets
│ ├── css
│ │ └── index.css
│ ├── js
│ │ └── index.js
│ └── images
</code></pre>
| [
{
"answer_id": 74447174,
"author": "Arnaud Valmary",
"author_id": 6255757,
"author_profile": "https://Stackoverflow.com/users/6255757",
"pm_score": 3,
"selected": true,
"text": "mkdir -p assets/{css,js,images}; touch assets/{css/index.css,js/index.js}\n"
},
{
"answer_id": 74447538,
"author": "Dr Claw",
"author_id": 12962618,
"author_profile": "https://Stackoverflow.com/users/12962618",
"pm_score": 0,
"selected": false,
"text": "$ tree\n.\n0 directories, 0 files\n\n$ for i in assets/{{css/index.css,js/index.js},images}; do\n [[ $i == \"assets/images\" ]] && (install -d \"$i\"||:) || install -D /dev/null \"$i\"\ndone\n\n$ tree\n.\n└── assets\n ├── css\n │ └── index.css\n ├── images\n └── js\n └── index.js\n\n4 directories, 2 files\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779365/"
] |
74,447,118 | <p>I upgraded my project to Spring Boot 3 and Spring Security 6, but since the upgrade the CSRF protection is no longer working.</p>
<p>I'm using the following configuration:</p>
<pre class="lang-java prettyprint-override"><code>@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated())
.httpBasic(withDefaults())
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS))
.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.builder().username("user").password("{noop}test").authorities("user").build();
return new InMemoryUserDetailsManager(user);
}
</code></pre>
<p>On my webpage I only have a single button:</p>
<pre class="lang-html prettyprint-override"><code><button id="test">Test CSRF</button>
</code></pre>
<p>And the following JavaScript code:</p>
<pre class="lang-js prettyprint-override"><code>document.querySelector("#test").addEventListener('click', async function() {
console.log('Clicked');
// This code reads the cookie from the browser
// Source: https://stackoverflow.com/a/25490531
const csrfToken = document.cookie.match('(^|;)\\s*XSRF-TOKEN\\s*=\\s*([^;]+)')?.pop();
const result = await fetch('./api/foo', {
method: 'POST',
headers: {
'X-XSRF-Token': csrfToken
}
});
console.log(result);
});
</code></pre>
<p>In Spring Boot 2.7.x this setup works fine, but if I upgrade my project to Spring Boot 3 and Spring Security 6, I get a 403 error with the following debug logs:</p>
<pre><code>15:10:51.858 D o.s.security.web.csrf.CsrfFilter: Invalid CSRF token found for http://localhost:8080/api/foo
15:10:51.859 D o.s.s.w.access.AccessDeniedHandlerImpl: Responding with 403 status code
</code></pre>
<p>My guess is that this is related to the changes for <a href="https://github.com/spring-projects/spring-security/issues/4001" rel="nofollow noreferrer">#4001</a>. However I don't understand what I have to change to my code or if I have to XOR something.</p>
<p>I did check if it was due to the new deferred loading of the CSRF token, but even if I click the button a second time (and verifying that the XSRF-TOKEN cookie is set), it still doesn't work.</p>
| [
{
"answer_id": 74456381,
"author": "g00glen00b",
"author_id": 1915448,
"author_profile": "https://Stackoverflow.com/users/1915448",
"pm_score": 1,
"selected": false,
"text": "XorCsrfTokenRequestAttributeHandler"
},
{
"answer_id": 74494999,
"author": "Matt Raible",
"author_id": 65681,
"author_profile": "https://Stackoverflow.com/users/65681",
"pm_score": 2,
"selected": false,
"text": ".csrf(csrf -> csrf\n .csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse())\n .csrfTokenRequestHandler(new ServerCsrfTokenRequestAttributeHandler()))\n"
},
{
"answer_id": 74521360,
"author": "Steve Riesenberg",
"author_id": 15835039,
"author_profile": "https://Stackoverflow.com/users/15835039",
"pm_score": 3,
"selected": true,
"text": "XSRF-TOKEN"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1915448/"
] |
74,447,128 | <p>I try to sum per fruit sort the total.</p>
<p>So I have it:</p>
<pre><code>listfruit= [('Watermeloenen', '123,20'), ('Watermeloenen', '2.772,00'), ('Watermeloenen', '46,20'), ('Watermeloenen', '577,50'), ('Watermeloenen', '69,30'), ('Appels', '3.488,16'), ('Sinaasappels', '137,50'), ('Sinaasappels', '500,00'), ('Sinaasappels', '1.000,00'), ('Sinaasappels', '2.000,00'), ('Sinaasappels', '1.000,00'), ('Sinaasappels', '381,25')]
def total_cost_fruit_per_sort():
number_found = listfruit
fruit_dict = {}
for n, f in number_found:
fruit_dict[f] = fruit_dict.get(f, 0) + int(n)
result = '\n'.join(f'{key}: {val}' for key, val in fruit_dict.items())
return result
print(total_cost_fruit_per_sort())
</code></pre>
<p>So that it looks like:</p>
<pre><code>Watermeloenen: 800
Sinaasappels: 1000
</code></pre>
<p>But if I run the code I get this error:</p>
<pre><code> File "c:\Users\engel\Documents\python\code\extract_text.py", line 292, in <genexpr>
result = sum(int(n) for _, n in listfruit)
ValueError: invalid literal for int() with base 10: '123,20'
</code></pre>
<p>But I parse the second value to an int, even when I try to do it to parse to float. Doesn't work.</p>
<p>Question: how can I can calculate total of each fruit sort?</p>
| [
{
"answer_id": 74447242,
"author": "pL3b",
"author_id": 17200418,
"author_profile": "https://Stackoverflow.com/users/17200418",
"pm_score": 1,
"selected": false,
"text": "result = sum(float(n.replace(\".\", \"\").replace(\",\", \".\")) for _, n in listfruit)\n"
},
{
"answer_id": 74447379,
"author": "Luca Clissa",
"author_id": 7678074,
"author_profile": "https://Stackoverflow.com/users/7678074",
"pm_score": 2,
"selected": true,
"text": ".replace"
},
{
"answer_id": 74447469,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 2,
"selected": false,
"text": "locale.delocalize"
},
{
"answer_id": 74447515,
"author": "Riccardo Bucco",
"author_id": 5296106,
"author_profile": "https://Stackoverflow.com/users/5296106",
"pm_score": 2,
"selected": false,
"text": "import locale\n\nlocale._override_localeconv = {'thousands_sep': '.', 'decimal_point': ','}\nnew_listfruit = [(n, locale.atof(v)) for n, v in listfruit]\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7713770/"
] |
74,447,142 | <p>I have a main project <strong>A</strong> which depends on a project <strong>B</strong>. The project <strong>B</strong> contains special button and there is <code>B/theme</code> folder in which I describe specific styles. If I use <code>B.Button</code> in <strong>B</strong> and compile and run <strong>B</strong> - styles work fine. Hovewer if I use the button <code>B.Button</code> in <strong>A</strong> I get button without styles at all.</p>
<p>Is there right way to save styles of <code>B.Button</code> in <strong>A</strong> project?</p>
<p>The theme styles for the button:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>qx.Theme.define("B.theme.Appearance",
{
extend : qx.theme.indigo.Appearance,
appearances :
{
"mybutton": {
include: "button",
style: function(states){
return {
padding: 100
};
}
}
}
});</code></pre>
</div>
</div>
</p>
<p>I understand I could separate styles into a special theme project and describe all required stuff there but I think about about <strong>B</strong> as a fully independent project which I could load from another location (e.g. remote repository) and this project is provided with own styles too among widgets/classes.</p>
| [
{
"answer_id": 74447242,
"author": "pL3b",
"author_id": 17200418,
"author_profile": "https://Stackoverflow.com/users/17200418",
"pm_score": 1,
"selected": false,
"text": "result = sum(float(n.replace(\".\", \"\").replace(\",\", \".\")) for _, n in listfruit)\n"
},
{
"answer_id": 74447379,
"author": "Luca Clissa",
"author_id": 7678074,
"author_profile": "https://Stackoverflow.com/users/7678074",
"pm_score": 2,
"selected": true,
"text": ".replace"
},
{
"answer_id": 74447469,
"author": "jsbueno",
"author_id": 108205,
"author_profile": "https://Stackoverflow.com/users/108205",
"pm_score": 2,
"selected": false,
"text": "locale.delocalize"
},
{
"answer_id": 74447515,
"author": "Riccardo Bucco",
"author_id": 5296106,
"author_profile": "https://Stackoverflow.com/users/5296106",
"pm_score": 2,
"selected": false,
"text": "import locale\n\nlocale._override_localeconv = {'thousands_sep': '.', 'decimal_point': ','}\nnew_listfruit = [(n, locale.atof(v)) for n, v in listfruit]\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3297142/"
] |
74,447,149 | <p>I would like to serialize (and deserialize) an C# object to a json string.
Normally when objects are serialized, objects are enclosed in a pair of <code>{}</code> in the generated json.
But here I am interested in object to be serialized to only a string.</p>
<p>I am interested in doing this to encapsulate logic about how <code>ItemNumber</code>s should be formatted.
But I am not interested expose the fact that I am using a class for the <code>ItemNumber</code> instead of an ordinary string.</p>
<p>Here is an example of what I am looking for.
The class <code>ItemNumber</code> is contained in the class <code>Item</code>.</p>
<pre><code>public class ItemNumber
{
private string _value;
public ItemNumber(string num)
{
_value = num;
}
}
public class Item
{
public ItemNumber ItemNumber { get; set; }
}
public void Main()
{
var itemNumber = new ItemNumber("ABC-1234");
var item = new Item
{
ItemNumber = itemNumber,
};
var json = System.Text.Json.JsonSerializer.Serialize(item);
}
</code></pre>
<p>I would like for an <code>Item</code> to be serialized to json looking like this:</p>
<pre class="lang-json prettyprint-override"><code>{
"itemNumber": "ABC-1234" // <- Notice, not an object. Just a string
}
</code></pre>
<p>I understand that I probably have to implement custom serializer, but the guide have found seems to assume that a C# object should always be serialized to a json object.</p>
<p>How do implement the serialization logic I am looking for?</p>
| [
{
"answer_id": 74447338,
"author": "ThisQRequiresASpecialist",
"author_id": 19381612,
"author_profile": "https://Stackoverflow.com/users/19381612",
"pm_score": 0,
"selected": false,
"text": "?"
},
{
"answer_id": 74447891,
"author": "BurnsBA",
"author_id": 1462295,
"author_profile": "https://Stackoverflow.com/users/1462295",
"pm_score": 3,
"selected": true,
"text": "ItemNumber"
},
{
"answer_id": 74449038,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 1,
"selected": false,
"text": "public class Item\n{\n [System.Text.Json.Serialization.JsonIgnore]\n public ItemNumber ItemNumber { get; set; }\n\n [System.Text.Json.Serialization.JsonPropertyName(\"itemNumber\")]\n public string _itemNumberValue\n {\n get { return ItemNumber==null? null: ItemNumber.ToString(); }\n set {ItemNumber = new ItemNumber(value);}\n }\n\n public Item(string itemNumber)\n {\n ItemNumber = new ItemNumber(itemNumber);\n }\n public Item() { }\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4755799/"
] |
74,447,202 | <p>I want to pipe and filter from an API response, but response format is as follows.</p>
<p>JSON:</p>
<blockquote>
<p>{
activeAwards: [
{
name: 'x',
status: 'valid'
},
{
name: 'y',
status: 'valid'
},
{
name: 'z',
status: 'invalid'
}
]
}</p>
</blockquote>
<p>I have tried tap to get in 'activeAwards' and filter it.</p>
<p>Code:</p>
<pre><code> .pipe(
tap(data => {
data.activeAwards.filter(award =>
award.status === 'valid';
);
})
)
.subscribe(response => {
console.log(response);
}),
catchError(error => {
return error;
});
</code></pre>
<p>But according to the code above I`m getting all 3 objects, which is all of them, it should be 2 objects</p>
| [
{
"answer_id": 74447338,
"author": "ThisQRequiresASpecialist",
"author_id": 19381612,
"author_profile": "https://Stackoverflow.com/users/19381612",
"pm_score": 0,
"selected": false,
"text": "?"
},
{
"answer_id": 74447891,
"author": "BurnsBA",
"author_id": 1462295,
"author_profile": "https://Stackoverflow.com/users/1462295",
"pm_score": 3,
"selected": true,
"text": "ItemNumber"
},
{
"answer_id": 74449038,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 1,
"selected": false,
"text": "public class Item\n{\n [System.Text.Json.Serialization.JsonIgnore]\n public ItemNumber ItemNumber { get; set; }\n\n [System.Text.Json.Serialization.JsonPropertyName(\"itemNumber\")]\n public string _itemNumberValue\n {\n get { return ItemNumber==null? null: ItemNumber.ToString(); }\n set {ItemNumber = new ItemNumber(value);}\n }\n\n public Item(string itemNumber)\n {\n ItemNumber = new ItemNumber(itemNumber);\n }\n public Item() { }\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17134599/"
] |
74,447,208 | <p>I have this query :</p>
<pre><code>select pivot_table.*
from (
Select STATUS,USER_TYPE
FROM TRANSACTIONS tr
join TRANSACTION_STATUS_CODES sc on sc.id = tr.user_type
join TRANSACTION_USER_TYPES ut on ut.id=tr.user_type
WHERE Tr.User_Type between 1 and 5
And tr.status!=1
AND Tr.Update_Date BETWEEN TO_DATE('2022-01-01 00:00:00', 'yyyy-mm-dd HH24:MI:SS')
AND TO_DATE('2022-11-13 23:59:59', 'yyyy-mm-dd HH24:MI:SS')
) t
pivot(
count(user_type)
FOR user_type IN (1,2,3,5)
) pivot_table;
</code></pre>
<p>Which gives:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>status</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>5</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>3</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>4</td>
<td>13</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>5</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>3</td>
<td>5</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>0</td>
<td>4</td>
<td>0</td>
<td>0</td>
<td>8</td>
</tr>
</tbody>
</table>
</div>
<p>Wanted result:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>status</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>5</th>
<th>total</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>3</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>13</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>13</td>
</tr>
<tr>
<td>5</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>5</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>6</td>
</tr>
<tr>
<td>0</td>
<td>4</td>
<td>0</td>
<td>0</td>
<td>8</td>
<td>12</td>
</tr>
<tr>
<td>sum of statuses 2,4,5</td>
<td>17</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>17</td>
</tr>
<tr>
<td>sum of all statuses</td>
<td>26</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>35</td>
</tr>
</tbody>
</table>
</div>
<p>I have tried adding:</p>
<pre class="lang-sql prettyprint-override"><code>Select STATUS,USER_TYPE,
count(user_type) as records,
sum(user_type) over (partition by status) as total
</code></pre>
<p>and in the end:</p>
<pre class="lang-sql prettyprint-override"><code>pivot ( sum (records) for user_type in (1,2,3,5)) pivot_table
</code></pre>
<p>but logically I am still not there.</p>
| [
{
"answer_id": 74447338,
"author": "ThisQRequiresASpecialist",
"author_id": 19381612,
"author_profile": "https://Stackoverflow.com/users/19381612",
"pm_score": 0,
"selected": false,
"text": "?"
},
{
"answer_id": 74447891,
"author": "BurnsBA",
"author_id": 1462295,
"author_profile": "https://Stackoverflow.com/users/1462295",
"pm_score": 3,
"selected": true,
"text": "ItemNumber"
},
{
"answer_id": 74449038,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 1,
"selected": false,
"text": "public class Item\n{\n [System.Text.Json.Serialization.JsonIgnore]\n public ItemNumber ItemNumber { get; set; }\n\n [System.Text.Json.Serialization.JsonPropertyName(\"itemNumber\")]\n public string _itemNumberValue\n {\n get { return ItemNumber==null? null: ItemNumber.ToString(); }\n set {ItemNumber = new ItemNumber(value);}\n }\n\n public Item(string itemNumber)\n {\n ItemNumber = new ItemNumber(itemNumber);\n }\n public Item() { }\n}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19198699/"
] |
74,447,218 | <p>wondering how I can order the clusters on y-axis by decreasing count of kiwi?</p>
<pre><code>df = data.frame()
df = data.frame(matrix(df, nrow=200, ncol=2))
colnames(df) <- c("cluster", "name")
df$cluster <- sample(20, size = nrow(df), replace = TRUE)
df$fruit <- sample(c("banana", "apple", "orange", "kiwi", "plum"), size = nrow(df), replace = TRUE)
p = ggplot(df, aes(x = as.factor(cluster), fill = as.factor(fruit)))+
geom_bar(stat = 'count') +
theme_classic()+
coord_flip() +
theme(axis.text.y = element_text(size = 20),
axis.title.x = element_text(size = 20),
axis.title.y = element_text(size = 20),
axis.text=element_text(size=20)) +
theme(legend.text = element_text(size = 20)) +
xlab("Cluster")+
ylab("Fruit count") +
labs( fill = "")
p
</code></pre>
<p><a href="https://i.stack.imgur.com/TbSiB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TbSiB.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74447434,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": false,
"text": "library(tidyverse)\n\ndf %>%\n mutate(cluster = factor(cluster, \n names(sort(table(fruit == 'kiwi', cluster)[2,]))),\n fruit = factor(fruit, c('kiwi', 'apple', 'banana', \n 'orange', 'plum'))) %>%\n ggplot(aes(x = cluster, fill = fruit))+\n geom_bar(position = position_stack(reverse = TRUE)) + \n theme_classic()+\n coord_flip() +\n theme(axis.text.y = element_text(size = 20),\n axis.title.x = element_text(size = 20),\n axis.title.y = element_text(size = 20),\n axis.text=element_text(size=20)) +\n theme(legend.text = element_text(size = 20)) +\n scale_fill_manual(values = c('olivedrab', 'yellowgreen', 'yellow2', \n 'orange2', 'plum4')) +\n xlab(\"Cluster\")+\n ylab(\"Fruit count\") +\n labs( fill = \"\")\n"
},
{
"answer_id": 74447449,
"author": "Antti",
"author_id": 6783732,
"author_profile": "https://Stackoverflow.com/users/6783732",
"pm_score": 0,
"selected": false,
"text": "order <- df %>%\n # count how many times kiwi occurs per cluster\n count(fruit, cluster) %>% filter(fruit == 'kiwi')\n\ndf <- df %>%\n # join the counts to the original df by cluster\n left_join(order %>% select(cluster, n)) %>% \n \n # if na make zero (otherwise NAs appear at the top of the plot)\n mutate(n = ifelse(is.na(n), 0, n),\n # arrange the clusters by n\n cluster = fct_reorder(as.factor(cluster), n)) \n\n"
},
{
"answer_id": 74447456,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 0,
"selected": false,
"text": "forcats::fct_reorder()"
},
{
"answer_id": 74447470,
"author": "Robert Hacken",
"author_id": 2094893,
"author_profile": "https://Stackoverflow.com/users/2094893",
"pm_score": 3,
"selected": true,
"text": "x = reorder(cluster, fruit=='kiwi', sum)"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12372071/"
] |
74,447,222 | <p>So, I did this in order to find the second biggest value in an array (I know there are a lot of answers out there, I just want to know why this approach fails)</p>
<p>With a first <code>reduce()</code> method on the number array I find the largest number, then using a second <code>reduce()</code> method I tried to use an <code>if</code> statement to check return the biggest number only if the compared numbers are not the previous biggest one found. This is the code:</p>
<pre><code>const arr = [1,6,2,7,3,9,5,8];
const biggest = arr.reduce((a,b)=> {
return Math.max(a,b)
})
console.log(biggest)
const secondBiggest = arr.reduce((a,b)=>{
if(a!= biggest && b!= biggest){
return Math.max(a,b)
}
})
console.log(secondBiggest) // --> NAN
</code></pre>
| [
{
"answer_id": 74447492,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 2,
"selected": true,
"text": "reduce"
},
{
"answer_id": 74447540,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 0,
"selected": false,
"text": "const arr = [1, 6, 2, 7, 3, 9, 5, 2];\n\nconst biggest = Math.max([...arr])\n\nconsole.log(biggest)\n\nconst secondBiggest = arr.reduce((accumulator, current) => {\n if (current != biggest) {\n return Math.max(accumulator, b)\n }\n return a\n})\n\nconsole.log(secondBiggest)"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6900034/"
] |
74,447,228 | <p>I would like to get the actual date of accounts that have expired but still enabled in the active directory. I always get the date + 1 day. For example, if a user is expired today (15/11/2022), it will shows (16/11/2022)... Can you help me with this?</p>
<pre><code>Get-ADUser -Filter * -properties AccountExpirationDate |
Where-Object{$_.AccountExpirationDate -lt (Get-Date) -and $_.AccountExpirationDate -ne $null -and $_.Enabled -eq $True} |
select-object Name, SamAccountName, AccountExpirationDate | Sort-Object -Property {$_.AccountExpirationDate} -Descending
</code></pre>
| [
{
"answer_id": 74447752,
"author": "Theo",
"author_id": 9898643,
"author_profile": "https://Stackoverflow.com/users/9898643",
"pm_score": 2,
"selected": true,
"text": "accountExpires"
},
{
"answer_id": 74449530,
"author": "ak2595",
"author_id": 17163818,
"author_profile": "https://Stackoverflow.com/users/17163818",
"pm_score": 0,
"selected": false,
"text": "Get-ADUser -Filter 'Enabled -eq $true' -Properties AccountExpirationDate, accountExpires |\nWhere-Object {($_.accountExpires -gt 0 -and $_.accountExpires -ne 9223372036854775807) -and \n ($_.AccountExpirationDate -le $refDate)} |\nSelect-Object Name, SamAccountName, @{Name=\"AccountExpirationDate\";Expression={(get-date $_.AccountExpirationDate).AddDays(-1)}} | \nSort-Object AccountExpirationDate -Descending\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17163818/"
] |
74,447,247 | <p>Please, help me with my problem?</p>
<p>I am fetching some data from Strapi and display it in the component.
Everything works well on first rerender, but then odd behaviour starts.</p>
<p>First of all - when i navigate to another page and then navigate back to original page - I ALWAYS get error message =</p>
<blockquote>
<p>Uncaught TypeError: Cannot read properties of undefined (reading '0')</p>
</blockquote>
<p>When i stay on the same page and then try to refresh it - sometimes it works OK, sometimes I get the same error message as above.</p>
<p>I think it has something to do with fetching and I i guess don't understand some important concept
How can i fix my problem and whats the best way to fetch data from strapi and use it in components?</p>
<p>Here is the code for fetch function</p>
<pre><code>const [data2, setdata2] = useState({});
useEffect(() => {
axios
.get(`${process.env.REACT_APP_HOST}/api/flipcards`)
.then(({ data }) => setdata2(data))
.catch((error) => setError2(error))},
[])
</code></pre>
<p>and here is the component:</p>
<pre><code><Box sx={data2text}>
<Typography sx={data2title}>{data2.data[0].attributes.title2}</Typography>
<Typography>{data2.data[0].attributes.details}</Typography>
</Box>
</code></pre>
<p>Thanks!!</p>
| [
{
"answer_id": 74447752,
"author": "Theo",
"author_id": 9898643,
"author_profile": "https://Stackoverflow.com/users/9898643",
"pm_score": 2,
"selected": true,
"text": "accountExpires"
},
{
"answer_id": 74449530,
"author": "ak2595",
"author_id": 17163818,
"author_profile": "https://Stackoverflow.com/users/17163818",
"pm_score": 0,
"selected": false,
"text": "Get-ADUser -Filter 'Enabled -eq $true' -Properties AccountExpirationDate, accountExpires |\nWhere-Object {($_.accountExpires -gt 0 -and $_.accountExpires -ne 9223372036854775807) -and \n ($_.AccountExpirationDate -le $refDate)} |\nSelect-Object Name, SamAccountName, @{Name=\"AccountExpirationDate\";Expression={(get-date $_.AccountExpirationDate).AddDays(-1)}} | \nSort-Object AccountExpirationDate -Descending\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12396859/"
] |
74,447,271 | <p>I have a list the contains names and numbers. And for all items with the same name in the list I want to calculate the sum of those numbers.</p>
<p>Please note, I cannot use the numpy function.</p>
<p>This is my 2d list:</p>
<pre class="lang-py prettyprint-override"><code>list = [('apple', 3), ('apple', 4), ('apple', 6), ('orange', 2), ('orange', 4), ('banana', 5)]
</code></pre>
<p>And then adding up the numbers with the same name the expected output is below.</p>
<p>Expected output:</p>
<pre><code>apple: 13
orange: 6
banana: 5
</code></pre>
| [
{
"answer_id": 74447752,
"author": "Theo",
"author_id": 9898643,
"author_profile": "https://Stackoverflow.com/users/9898643",
"pm_score": 2,
"selected": true,
"text": "accountExpires"
},
{
"answer_id": 74449530,
"author": "ak2595",
"author_id": 17163818,
"author_profile": "https://Stackoverflow.com/users/17163818",
"pm_score": 0,
"selected": false,
"text": "Get-ADUser -Filter 'Enabled -eq $true' -Properties AccountExpirationDate, accountExpires |\nWhere-Object {($_.accountExpires -gt 0 -and $_.accountExpires -ne 9223372036854775807) -and \n ($_.AccountExpirationDate -le $refDate)} |\nSelect-Object Name, SamAccountName, @{Name=\"AccountExpirationDate\";Expression={(get-date $_.AccountExpirationDate).AddDays(-1)}} | \nSort-Object AccountExpirationDate -Descending\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20511050/"
] |
74,447,285 | <p><code>jq .</code> has the side-effect of pretty printing the input.</p>
<pre class="lang-bash prettyprint-override"><code>$ echo '{"foo":"bar", "baz":[1,2,3]}' | jq .
{
"foo": "bar",
"baz": [
1,
2,
3
]
}
</code></pre>
<p>But if I want to use <a href="/questions/tagged/jq" class="post-tag" title="show questions tagged 'jq'" aria-label="show questions tagged 'jq'" rel="tag" aria-labelledby="jq-container">jq</a> to incorporate the input with some surrounding text, the input renders compactly</p>
<pre class="lang-bash prettyprint-override"><code>$ echo '{"foo":"bar", "baz":[1,2,3]}' | jq -r '"My value is:\n\(.)\nSome other stuff"'
My value is:
{"foo":"bar","baz":[1,2,3]}
Some other stuff
</code></pre>
<p>Is there any way to force pretty printing here? I'd like the output to be</p>
<pre><code>My value is:
{
"foo": "bar",
"baz": [
1,
2,
3
]
}
Some other stuff
</code></pre>
| [
{
"answer_id": 74447286,
"author": "glenn jackman",
"author_id": 7552,
"author_profile": "https://Stackoverflow.com/users/7552",
"pm_score": 2,
"selected": false,
"text": "echo '{\"foo\":\"bar\", \"baz\":[1,2,3]}' | jq -r '\"My value is:\", . , \"Some other stuff\"'\n# .........................................................^^^^^\n"
},
{
"answer_id": 74447374,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 0,
"selected": false,
"text": "jq"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7552/"
] |
74,447,292 | <p>I'm trying to get the subcategories on a listing page in Shopware 6. However i can't seem to find the functionality to get an array with the subcategories with the template variables.</p>
<p>My goal is to loop over the children and make some kind of fastlinks in a CMS-element.</p>
<p>Is there a standard functionality build in shopware to get the children by id or name in TWIG?</p>
<p>I've tried to find anything relevant in</p>
<pre><code>page.header.navigation.active
</code></pre>
<p>But the child data isn't available.</p>
<p>Thanks!</p>
| [
{
"answer_id": 74447720,
"author": "newgennerd",
"author_id": 12553209,
"author_profile": "https://Stackoverflow.com/users/12553209",
"pm_score": 3,
"selected": true,
"text": "// myPlugin/src/DataResolver/SubcategoryListCmsElementResolver.php\n<?php\n\nnamespace MyPlugin\\DataResolver;\n\nuse Shopware\\Core\\Content\\Category\\CategoryDefinition;\nuse Shopware\\Core\\Content\\Category\\CategoryEntity;\nuse Shopware\\Core\\Content\\Cms\\Aggregate\\CmsSlot\\CmsSlotEntity;\nuse Shopware\\Core\\Content\\Cms\\DataResolver\\CriteriaCollection;\nuse Shopware\\Core\\Content\\Cms\\DataResolver\\Element\\AbstractCmsElementResolver;\nuse Shopware\\Core\\Content\\Cms\\DataResolver\\Element\\ElementDataCollection;\nuse Shopware\\Core\\Content\\Cms\\DataResolver\\ResolverContext\\ResolverContext;\nuse Shopware\\Core\\Framework\\DataAbstractionLayer\\Search\\Criteria;\nuse Shopware\\Core\\Framework\\DataAbstractionLayer\\Search\\Filter\\EqualsFilter;\n\nclass SubcategoryListCmsElementResolver extends AbstractCmsElementResolver\n{\n\n public function getType(): string\n {\n return 'my-subcategory-list';\n }\n\n public function collect(CmsSlotEntity $slot, ResolverContext $resolverContext): ?CriteriaCollection\n {\n /** @var CategoryEntity $categoryEntity */\n $categoryEntity = $resolverContext->getEntity();\n $criteria = new Criteria([$categoryEntity->getId()]);\n $criteria->addAssociation('children');\n\n $criteriaCollection = new CriteriaCollection();\n $criteriaCollection->add('category_' . $slot->getUniqueIdentifier(), CategoryDefinition::class, $criteria);\n return $criteriaCollection;\n }\n\n public function enrich(CmsSlotEntity $slot, ResolverContext $resolverContext, ElementDataCollection $result): void\n {\n /** @var CategoryEntity $categoryEntity */\n $categoryEntity = $result->get('category_' . $slot->getUniqueIdentifier())?->getEntities()->first();\n $slot->setData($categoryEntity->getChildren()?->sortByPosition()->filter(static function ($child) {\n /** @var CategoryEntity $child */\n return $child->getActive();\n }));\n }\n}\n"
},
{
"answer_id": 74453250,
"author": "Lubna Altungi",
"author_id": 18530022,
"author_profile": "https://Stackoverflow.com/users/18530022",
"pm_score": -1,
"selected": false,
"text": "{% for item in category.item %}\n {% for subcategory in category.subcategory %}\n {{ subcategory.title}}\n {% endfor %}\n{% endfor %}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9310268/"
] |
74,447,314 | <p>I have a code that I am trying to convert but it's written in Python 2 and I would like to print this code in Python 3. However, it's not able to print in matrix format. I am getting output in an unrecognizable table format.</p>
<p>The code is following:</p>
<pre><code> for n in cols:
print('/t',n),
print
cost = 0
for g in sorted(costs):
print('\t', g)
for n in cols:
y = res[g][n]
if y != 0:
print (y),
cost += y * costs[g][n]
print ('\t'),
print
print ("\n\nTotal Cost = ", cost)
</code></pre>
<p>The expected output is in the following format:</p>
<pre><code>|0 |A |B |C |D |E |
|- |- |- |- |- |- |
|W | | |20| | |
|X | |40|10| |20|
|Y | |20| | |30|
|Z | | | | |60|
Total Cost = 1000
</code></pre>
<p>Could you suggest what changes I need to make in this code?</p>
| [
{
"answer_id": 74447720,
"author": "newgennerd",
"author_id": 12553209,
"author_profile": "https://Stackoverflow.com/users/12553209",
"pm_score": 3,
"selected": true,
"text": "// myPlugin/src/DataResolver/SubcategoryListCmsElementResolver.php\n<?php\n\nnamespace MyPlugin\\DataResolver;\n\nuse Shopware\\Core\\Content\\Category\\CategoryDefinition;\nuse Shopware\\Core\\Content\\Category\\CategoryEntity;\nuse Shopware\\Core\\Content\\Cms\\Aggregate\\CmsSlot\\CmsSlotEntity;\nuse Shopware\\Core\\Content\\Cms\\DataResolver\\CriteriaCollection;\nuse Shopware\\Core\\Content\\Cms\\DataResolver\\Element\\AbstractCmsElementResolver;\nuse Shopware\\Core\\Content\\Cms\\DataResolver\\Element\\ElementDataCollection;\nuse Shopware\\Core\\Content\\Cms\\DataResolver\\ResolverContext\\ResolverContext;\nuse Shopware\\Core\\Framework\\DataAbstractionLayer\\Search\\Criteria;\nuse Shopware\\Core\\Framework\\DataAbstractionLayer\\Search\\Filter\\EqualsFilter;\n\nclass SubcategoryListCmsElementResolver extends AbstractCmsElementResolver\n{\n\n public function getType(): string\n {\n return 'my-subcategory-list';\n }\n\n public function collect(CmsSlotEntity $slot, ResolverContext $resolverContext): ?CriteriaCollection\n {\n /** @var CategoryEntity $categoryEntity */\n $categoryEntity = $resolverContext->getEntity();\n $criteria = new Criteria([$categoryEntity->getId()]);\n $criteria->addAssociation('children');\n\n $criteriaCollection = new CriteriaCollection();\n $criteriaCollection->add('category_' . $slot->getUniqueIdentifier(), CategoryDefinition::class, $criteria);\n return $criteriaCollection;\n }\n\n public function enrich(CmsSlotEntity $slot, ResolverContext $resolverContext, ElementDataCollection $result): void\n {\n /** @var CategoryEntity $categoryEntity */\n $categoryEntity = $result->get('category_' . $slot->getUniqueIdentifier())?->getEntities()->first();\n $slot->setData($categoryEntity->getChildren()?->sortByPosition()->filter(static function ($child) {\n /** @var CategoryEntity $child */\n return $child->getActive();\n }));\n }\n}\n"
},
{
"answer_id": 74453250,
"author": "Lubna Altungi",
"author_id": 18530022,
"author_profile": "https://Stackoverflow.com/users/18530022",
"pm_score": -1,
"selected": false,
"text": "{% for item in category.item %}\n {% for subcategory in category.subcategory %}\n {{ subcategory.title}}\n {% endfor %}\n{% endfor %}\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18877602/"
] |
74,447,351 | <p>I have a bug that I need more than one result from a <code>foreach</code> without creating a new collection in the method. I need to get rid of the <code>foreach</code> however I don`t know what LINQ method to use.</p>
<p>I have tried,</p>
<pre><code>return basket.Items.SelectMany(
item => item.Id == orderComplimentaryUtilities.Where(o => o.Id));
public static IEnumerable<OrderItem> WhichUtilitiesAreAlreadyInBasket(
this
IEnumerable<OrderComplimentaryUtility.OrderComplimentaryUtility>
orderComplimentaryUtilities,
Order basket)
{
if (basket == null || orderComplimentaryUtilities == null)
{
return Enumerable.Empty<OrderItem>();
}
foreach (var orderComplimentaryUtility in orderComplimentaryUtilities)
{
return basket.Items.Where(item => item.Id == orderComplimentaryUtility.Id);
}
return Enumerable.Empty<OrderItem>();
}
</code></pre>
| [
{
"answer_id": 74447476,
"author": "D Stanley",
"author_id": 1081897,
"author_profile": "https://Stackoverflow.com/users/1081897",
"pm_score": 0,
"selected": false,
"text": "Contains"
},
{
"answer_id": 74448538,
"author": "Mike Hofer",
"author_id": 47580,
"author_profile": "https://Stackoverflow.com/users/47580",
"pm_score": 2,
"selected": false,
"text": "orderComplimentaryUtilities"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13011195/"
] |
74,447,365 | <p>I have a function that checks whether or not a worksheet named <code>wsName</code> exists already in the workbook. The issue I am having is getting the function to run with the restructuring and removal of <code>On Error Resume Next</code>. What I am expecting is the macro to run and produce copies of the worksheets that do not already exist in the workbook and if the worksheets do already exist, then print out <code>ErrorMsg</code> saying <code>"Unknown Error"</code>. What I see however, is the macro print out the <code>ErrorMsg</code> even if the worksheet does not exist and makes a copy of it. I am trying this approach to <code>SheetExists</code> to see if there is a way to get the function to run without using <code>On Error Resume Next</code> as I do not want to macro to ignore errors that are generated, rather I would want it to print out <code>"Unknown Error"</code></p>
<pre><code>Global Parameter As Long, RoutingStep As Long, wsName As String, version As String, ErrorMsg As String, SDtab As Worksheet
Global wb As Workbook, sysrow As Long, sysnum As String, ws As Worksheet
Public Sub Main()
Dim syswaiver As Long, axsunpart As Long
Dim startcell As String, cell As Range
Dim syscol As Long, dict As Object, wbSrc As Workbook
Set wb = Workbooks("SD3_KW.xlsm")
Set ws = wb.Worksheets("Data Sheet")
syswaiver = 3
axsunpart = 4
Set wbSrc = Workbooks.Open("Q:\Documents\Specification Document.xlsx")
Set dict = CreateObject("scripting.dictionary")
If Not syswaiver = 0 Then
startcell = ws.cells(2, syswaiver).Address
Else
ErrorMsg = "waiver number column index not found. Value needed to proceed"
GoTo Skip
End If
For Each cell In ws.Range(startcell, ws.cells(ws.Rows.Count, syswaiver).End(xlUp)).cells
sysnum = cell.value
sysrow = cell.row
syscol = cell.column
If Not dict.Exists(sysnum) Then
dict.Add sysnum, True
If Not SheetExists(sysnum, wb) Then
If Not axsunpart = 0 Then
wsName = cell.EntireRow.Columns(axsunpart).value
If SheetExists(wsName, wbSrc) Then
wbSrc.Worksheets(wsName).copy After:=ws
wb.Worksheets(wsName).Name = sysnum
Set SDtab = wb.Worksheets(ws.Index + 1)
Else
ErrorMsg = ErrorMsg & IIf(ErrorMsg = "", "", "") & "part number for " & sysnum & " sheet to be copied could not be found"
cell.Interior.Color = vbRed
GoTo Skip
End If
Else
ErrorMsg = "part number column index not found. Value needed to proceed"
End If
Else
MsgBox "Sheet " & sysnum & " already exists."
End If
End If
Skip:
Dim begincell As Long, logsht As Worksheet
Set logsht = wb.Worksheets("Log Sheet")
With logsht ' wb.Worksheets("Log Sheet")
begincell = .cells(Rows.Count, 1).End(xlUp).row
.cells(begincell + 1, 3).value = sysnum
.cells(begincell + 1, 3).Font.Bold = True
.cells(begincell + 1, 2).value = Date
.cells(begincell + 1, 2).Font.Bold = True
If Not ErrorMsg = "" Then
.cells(begincell + 1, 4).value = vbNewLine & "Complete with Erorr - " & vbNewLine & ErrorMsg
.cells(begincell + 1, 4).Font.Bold = True
.cells(begincell + 1, 4).Interior.Color = vbRed
Else
.cells(begincell + 1, 4).value = "All Sections Completed without Errors"
.cells(begincell + 1, 4).Font.Bold = True
.cells(begincell + 1, 4).Interior.Color = vbGreen
End If
End With
Next Cell
End Sub
</code></pre>
<pre><code>Function SheetExists(SheetName As String, wb As Workbook)
On Error GoTo Message
SheetExists = Not wb.Sheets(SheetName) Is Nothing
Exit Function
Message:
ErrorMsg = "Unknown Error"
End Function
</code></pre>
<pre><code></code></pre>
| [
{
"answer_id": 74447628,
"author": "FaneDuru",
"author_id": 2233308,
"author_profile": "https://Stackoverflow.com/users/2233308",
"pm_score": 2,
"selected": false,
"text": "Function SheetExists_(SheetName As String, wb As Workbook) As Boolean\nOn Error GoTo Message\nSheetExists_ = Not wb.Sheets(SheetName) Is Nothing\nIf Not wb.Sheets(SheetName) Is Nothing Then Exit Function\nMessage:\n MsgBox \"Unknown Error\"\nEnd Function\n"
},
{
"answer_id": 74447659,
"author": "Frank Ball",
"author_id": 5910169,
"author_profile": "https://Stackoverflow.com/users/5910169",
"pm_score": 0,
"selected": false,
"text": "SheetExists = Not wb.Sheets(SheetName) Is Nothing"
},
{
"answer_id": 74449236,
"author": "Notus_Panda",
"author_id": 19353309,
"author_profile": "https://Stackoverflow.com/users/19353309",
"pm_score": 0,
"selected": false,
"text": "Function SheetExists(SheetName As String, wb As Workbook)\n On Error GoTo Message\n SheetExists = Not wb.Sheets(SheetName) Is Nothing\n ErrorMsg = \"Unknown Error\" 'sheet exists\n Exit Function\nMessage: 'sheet doesn't exist, SheetExists remains false and no errormsg required\nEnd Function\n"
},
{
"answer_id": 74449689,
"author": "Red Hare",
"author_id": 19618751,
"author_profile": "https://Stackoverflow.com/users/19618751",
"pm_score": 0,
"selected": false,
"text": "Public Function sh_Exist(TheWorkbook As Workbook, SheetName As String) As Boolean\nDim s As String\nOn Error GoTo errHandler\ns = TheWorkbook.Sheets(SheetName).Name\nsh_Exist = True\nExit Function\nerrHandler:\nEnd Function\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20114520/"
] |
74,447,371 | <p>I have a script that I use to fire orders from a csv file, to an exchange using a for loop.</p>
<pre><code>data = pd.read_csv('orderparameters.csv')
df = pd.DataFrame(data)
for i in range(len(df)):
order = Client.new_order(...
...)
file = open('orderData.txt', 'a')
original_stdout = sys.stdout
with file as f:
sys.stdout = f
print(order)
file.close()
sys.stdout = original_stdout
</code></pre>
<p>I put the response from the exchange in a txt file like this...
<img src="https://i.stack.imgur.com/r7cVD.png" alt="enter image description here" /></p>
<p>I want to turn the multiple responses into 1 single dataframe. I would hope it would look something like...
<img src="https://i.stack.imgur.com/13SeR.png" alt="enter image description here" /></p>
<p>(I did that manually).
I tried;</p>
<pre><code>data = pd.read_csv('orderData.txt', header=None)
dfData = pd.DataFrame(data)
print(dfData)
</code></pre>
<p>but I got;
<img src="https://i.stack.imgur.com/r2cFO.png" alt="enter image description here" /></p>
<p>I have also tried</p>
<pre><code>
data = pd.read_csv('orderData.txt', header=None)
organised = data.apply(pd.Series)
print(organised)
</code></pre>
<p>but I got the same output.
I can print order['symbol'] within the loop etc.
I'm not certain whether I should be populating this dataframe within the loop, or by capturing and writing the response and processing it afterwards. Appreciate your advice.</p>
| [
{
"answer_id": 74447628,
"author": "FaneDuru",
"author_id": 2233308,
"author_profile": "https://Stackoverflow.com/users/2233308",
"pm_score": 2,
"selected": false,
"text": "Function SheetExists_(SheetName As String, wb As Workbook) As Boolean\nOn Error GoTo Message\nSheetExists_ = Not wb.Sheets(SheetName) Is Nothing\nIf Not wb.Sheets(SheetName) Is Nothing Then Exit Function\nMessage:\n MsgBox \"Unknown Error\"\nEnd Function\n"
},
{
"answer_id": 74447659,
"author": "Frank Ball",
"author_id": 5910169,
"author_profile": "https://Stackoverflow.com/users/5910169",
"pm_score": 0,
"selected": false,
"text": "SheetExists = Not wb.Sheets(SheetName) Is Nothing"
},
{
"answer_id": 74449236,
"author": "Notus_Panda",
"author_id": 19353309,
"author_profile": "https://Stackoverflow.com/users/19353309",
"pm_score": 0,
"selected": false,
"text": "Function SheetExists(SheetName As String, wb As Workbook)\n On Error GoTo Message\n SheetExists = Not wb.Sheets(SheetName) Is Nothing\n ErrorMsg = \"Unknown Error\" 'sheet exists\n Exit Function\nMessage: 'sheet doesn't exist, SheetExists remains false and no errormsg required\nEnd Function\n"
},
{
"answer_id": 74449689,
"author": "Red Hare",
"author_id": 19618751,
"author_profile": "https://Stackoverflow.com/users/19618751",
"pm_score": 0,
"selected": false,
"text": "Public Function sh_Exist(TheWorkbook As Workbook, SheetName As String) As Boolean\nDim s As String\nOn Error GoTo errHandler\ns = TheWorkbook.Sheets(SheetName).Name\nsh_Exist = True\nExit Function\nerrHandler:\nEnd Function\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20384302/"
] |
74,447,373 | <p>Does anyone know if there are any ways I can turn dataset from the left side to the right side in excel macro or other programming tools?</p>
<p><img src="https://i.stack.imgur.com/Y27tr.jpg" alt="enter image description here" /></p>
<p>Use R code to manipulate dataset on the left side to the one at the right side</p>
| [
{
"answer_id": 74447628,
"author": "FaneDuru",
"author_id": 2233308,
"author_profile": "https://Stackoverflow.com/users/2233308",
"pm_score": 2,
"selected": false,
"text": "Function SheetExists_(SheetName As String, wb As Workbook) As Boolean\nOn Error GoTo Message\nSheetExists_ = Not wb.Sheets(SheetName) Is Nothing\nIf Not wb.Sheets(SheetName) Is Nothing Then Exit Function\nMessage:\n MsgBox \"Unknown Error\"\nEnd Function\n"
},
{
"answer_id": 74447659,
"author": "Frank Ball",
"author_id": 5910169,
"author_profile": "https://Stackoverflow.com/users/5910169",
"pm_score": 0,
"selected": false,
"text": "SheetExists = Not wb.Sheets(SheetName) Is Nothing"
},
{
"answer_id": 74449236,
"author": "Notus_Panda",
"author_id": 19353309,
"author_profile": "https://Stackoverflow.com/users/19353309",
"pm_score": 0,
"selected": false,
"text": "Function SheetExists(SheetName As String, wb As Workbook)\n On Error GoTo Message\n SheetExists = Not wb.Sheets(SheetName) Is Nothing\n ErrorMsg = \"Unknown Error\" 'sheet exists\n Exit Function\nMessage: 'sheet doesn't exist, SheetExists remains false and no errormsg required\nEnd Function\n"
},
{
"answer_id": 74449689,
"author": "Red Hare",
"author_id": 19618751,
"author_profile": "https://Stackoverflow.com/users/19618751",
"pm_score": 0,
"selected": false,
"text": "Public Function sh_Exist(TheWorkbook As Workbook, SheetName As String) As Boolean\nDim s As String\nOn Error GoTo errHandler\ns = TheWorkbook.Sheets(SheetName).Name\nsh_Exist = True\nExit Function\nerrHandler:\nEnd Function\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20511239/"
] |
74,447,400 | <p>I have been looking at other similar posts on the topic, but as I am deeply learning Kotlin at the moment I'd like to discuss the problem, the solution, and why it happened if possible.</p>
<p>I am getting the following error:</p>
<pre><code>C:\Users\Paul\Documents\Projects\DataApp\app\src\main\java\com\example\dataapp\MyAdapter.kt: (19, 31): Unresolved reference: userId
</code></pre>
<p>Here is a sample of the code, the issue is happening in the ViewHolder class:</p>
<pre><code>package com.example.dataapp
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class MyAdapter (val context: Context, val userList: List<MyDataItem>): RecyclerView.Adapter<MyAdapter.ViewHolder>() {
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
var userId: TextView
var title: TextView
init {
userId = itemView.userId
title = itemView.title
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
var itemView = LayoutInflater.from(context).inflate(R.layout.row_items, parent, false)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.userId.text = userList[position].userId.toString()
holder.title.text = userList[position].title
}
override fun getItemCount(): Int {
return userList.size
}
}
</code></pre>
<p>In the XML I have set two text fields with id's of userId and title:</p>
<p><img src="https://i.ibb.co/0F2rTQg/SO.png" alt="Text" /></p>
<p>But I am getting this unresolved error for both. I am still working on my knowledge in Kotlin and Android and am very new, so no doubt will be something very basic.</p>
<p>I have so far:</p>
<p>Double checked the syntax matches
Checked I am binding correctly - I believe this is where the issue lies. I am following a tutorial that is not using binding and is just referencing using 'R.layout.activity_main' however I am using binding.root - could this be the issue?</p>
<p>Here is a link to the GitHub repo - <a href="https://github.com/Code4Wyatt/FetchDataKotlin" rel="nofollow noreferrer">https://github.com/Code4Wyatt/FetchDataKotlin</a></p>
<p>Thank you for any help! Please let me know if any more info is needed.</p>
| [
{
"answer_id": 74447628,
"author": "FaneDuru",
"author_id": 2233308,
"author_profile": "https://Stackoverflow.com/users/2233308",
"pm_score": 2,
"selected": false,
"text": "Function SheetExists_(SheetName As String, wb As Workbook) As Boolean\nOn Error GoTo Message\nSheetExists_ = Not wb.Sheets(SheetName) Is Nothing\nIf Not wb.Sheets(SheetName) Is Nothing Then Exit Function\nMessage:\n MsgBox \"Unknown Error\"\nEnd Function\n"
},
{
"answer_id": 74447659,
"author": "Frank Ball",
"author_id": 5910169,
"author_profile": "https://Stackoverflow.com/users/5910169",
"pm_score": 0,
"selected": false,
"text": "SheetExists = Not wb.Sheets(SheetName) Is Nothing"
},
{
"answer_id": 74449236,
"author": "Notus_Panda",
"author_id": 19353309,
"author_profile": "https://Stackoverflow.com/users/19353309",
"pm_score": 0,
"selected": false,
"text": "Function SheetExists(SheetName As String, wb As Workbook)\n On Error GoTo Message\n SheetExists = Not wb.Sheets(SheetName) Is Nothing\n ErrorMsg = \"Unknown Error\" 'sheet exists\n Exit Function\nMessage: 'sheet doesn't exist, SheetExists remains false and no errormsg required\nEnd Function\n"
},
{
"answer_id": 74449689,
"author": "Red Hare",
"author_id": 19618751,
"author_profile": "https://Stackoverflow.com/users/19618751",
"pm_score": 0,
"selected": false,
"text": "Public Function sh_Exist(TheWorkbook As Workbook, SheetName As String) As Boolean\nDim s As String\nOn Error GoTo errHandler\ns = TheWorkbook.Sheets(SheetName).Name\nsh_Exist = True\nExit Function\nerrHandler:\nEnd Function\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16776321/"
] |
74,447,402 | <p>I'm trying to append values to my dictionary, but I can't solve this error.</p>
<p>This is my dictionary:</p>
<pre><code>groups = {'group1': array([450, 449.]), 'group2': array([490, 489.]), 'group3': array([568, 567.])}
</code></pre>
<p>then I have a txt file (loaded using np.loadtxt) with many data and I have to iterate over this file and if a certain condition is met I should add that line to the correct key of my dictionary.
I used the if statement and I called the data that met the condition "parent".</p>
<pre><code>parent = [[449. 448.]]
[[489. 488.]]
[[567. 566.]]
</code></pre>
<p>I tried this:</p>
<pre><code>for i, x in enumerate(parent):
groups.setdefault(x, []).append(i)
</code></pre>
<p>expected output:</p>
<pre><code>groups = {'group1': array([450, 449.], [449, 448]), 'group2': array([490, 489.], [489, 488]), 'group3': array([568, 567.], [567, 566])}
</code></pre>
<p>but I get this error:</p>
<pre><code>TypeError: unhashable type: 'numpy.ndarray'
</code></pre>
| [
{
"answer_id": 74447628,
"author": "FaneDuru",
"author_id": 2233308,
"author_profile": "https://Stackoverflow.com/users/2233308",
"pm_score": 2,
"selected": false,
"text": "Function SheetExists_(SheetName As String, wb As Workbook) As Boolean\nOn Error GoTo Message\nSheetExists_ = Not wb.Sheets(SheetName) Is Nothing\nIf Not wb.Sheets(SheetName) Is Nothing Then Exit Function\nMessage:\n MsgBox \"Unknown Error\"\nEnd Function\n"
},
{
"answer_id": 74447659,
"author": "Frank Ball",
"author_id": 5910169,
"author_profile": "https://Stackoverflow.com/users/5910169",
"pm_score": 0,
"selected": false,
"text": "SheetExists = Not wb.Sheets(SheetName) Is Nothing"
},
{
"answer_id": 74449236,
"author": "Notus_Panda",
"author_id": 19353309,
"author_profile": "https://Stackoverflow.com/users/19353309",
"pm_score": 0,
"selected": false,
"text": "Function SheetExists(SheetName As String, wb As Workbook)\n On Error GoTo Message\n SheetExists = Not wb.Sheets(SheetName) Is Nothing\n ErrorMsg = \"Unknown Error\" 'sheet exists\n Exit Function\nMessage: 'sheet doesn't exist, SheetExists remains false and no errormsg required\nEnd Function\n"
},
{
"answer_id": 74449689,
"author": "Red Hare",
"author_id": 19618751,
"author_profile": "https://Stackoverflow.com/users/19618751",
"pm_score": 0,
"selected": false,
"text": "Public Function sh_Exist(TheWorkbook As Workbook, SheetName As String) As Boolean\nDim s As String\nOn Error GoTo errHandler\ns = TheWorkbook.Sheets(SheetName).Name\nsh_Exist = True\nExit Function\nerrHandler:\nEnd Function\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19719303/"
] |
74,447,404 | <p>In my Angular 12 application, I am making an API call in the service file and want to capture the response of the API in my component.
But since the API response is async, the console below always returns undefined. I have tried async await as well. Here is what I have tried:</p>
<p>INSIDE SERVICE:</p>
<pre><code>public checkEmail(emailToVerify: any) {
this.myService.emailValidate({ email: emailToVerify }).subscribe({
next: (data: { result: any) => {
console.log('updateEmail-res', data);
return data;
},
error: (err: any) => {
console.log('updateEmail-err', err);
}
});
}
</code></pre>
<p>INSIDE COMPONENT:</p>
<pre><code>this.apiResponse = await this.myService.checkEmail(customerEmail);
console.log("this.apiResponse", this.apiResponse)
</code></pre>
| [
{
"answer_id": 74447728,
"author": "Fenix9697",
"author_id": 13955961,
"author_profile": "https://Stackoverflow.com/users/13955961",
"pm_score": -1,
"selected": false,
"text": "this.apiResponse = await this.myService.emailValidate({ email: customerEmail});\n console.log(\"this.apiResponse\", this.apiResponse)\n"
},
{
"answer_id": 74456895,
"author": "Mukesh Soni",
"author_id": 11556649,
"author_profile": "https://Stackoverflow.com/users/11556649",
"pm_score": 0,
"selected": false,
"text": "validateEmail = async () => {\n const params = {\n emailAddress: 'test@gmail.com',\n };\n const apiResponse: boolean = await this.emailService.validateEmail(params);\n console.log(`apiResponse===`, apiResponse);\n };\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11989585/"
] |
74,447,415 | <p>I am working out a page that will have a quick-paced shuffle of images on one side, and would like to put bold and visually-attractive text that will lay over a corner of it as a mask and invert the colours of whatever is behind it. Are there any ways to style the text to do this in css?</p>
<p>I haven't been able to find any common solutions or workarounds for what I'm looking to achieve, only how to invert a selected colour.</p>
| [
{
"answer_id": 74447728,
"author": "Fenix9697",
"author_id": 13955961,
"author_profile": "https://Stackoverflow.com/users/13955961",
"pm_score": -1,
"selected": false,
"text": "this.apiResponse = await this.myService.emailValidate({ email: customerEmail});\n console.log(\"this.apiResponse\", this.apiResponse)\n"
},
{
"answer_id": 74456895,
"author": "Mukesh Soni",
"author_id": 11556649,
"author_profile": "https://Stackoverflow.com/users/11556649",
"pm_score": 0,
"selected": false,
"text": "validateEmail = async () => {\n const params = {\n emailAddress: 'test@gmail.com',\n };\n const apiResponse: boolean = await this.emailService.validateEmail(params);\n console.log(`apiResponse===`, apiResponse);\n };\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20023758/"
] |
74,447,446 | <p>I am implementing a kind of dataframe and I want to define a RandomAccessIterator over it, in order to execute the different std algorithms, such as the sorting one. The dataframe of the example contains two column "a" and "b":</p>
<pre><code>a; b;
20; 21;
20; 19;
10; 11;
40; 41;
10; 11;
</code></pre>
<p>After sorting with a trivial selection sort this is the result:</p>
<pre><code>a; b;
10; 11;
10; 11;
20; 19;
20; 21;
40; 41;
</code></pre>
<p>The problem that I am facing is that the std::sort does not work properly. And I don't know weather the implementation of the iterator is sound or not.</p>
<hr />
<p><strong>This is the code.</strong></p>
<p>File: <code>dataframe.hpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <iostream>
#include <charconv>
#include <vector>
#include <memory>
#include <cstring>
#include <numeric>
#include "iterator.hpp"
namespace df
{
class Record;
class Column;
class Dataframe;
namespace types
{
enum class Base : char
{
CHAR = 'A',
UNSIGNED = 'U',
// Other types..
};
class Dtype
{
public:
Dtype(types::Base base, std::size_t size) : m_base_dtype{base}, m_size{size} {}
[[nodiscard]] auto name() const
{
return std::string{static_cast<char>(m_base_dtype)} + std::to_string(m_size);
}
[[nodiscard]] auto base() const { return m_base_dtype; }
[[nodiscard]] auto size() const { return m_size; }
[[nodiscard]] auto is_primitive() const
{
switch (base())
{
case types::Base::CHAR:
return size() == 1;
case types::Base::UNSIGNED:
return size() == 1 or size() == 2 or size() == 4 or size() == 8;
}
return false;
}
private:
types::Base m_base_dtype;
std::size_t m_size;
};
[[nodiscard]] static auto CHAR(const std::size_t size) { return Dtype(types::Base::CHAR, size); }
[[nodiscard]] static auto UNSIGNED(const std::size_t size) { return Dtype(types::Base::UNSIGNED, size); }
}
class Column
{
public:
Column(std::vector<char> &raw, const types::Dtype dtype) : m_raw{std::move(raw)}, m_dtype{dtype} {}
Column &operator=(Column &&c) = default; // Move constructor
[[nodiscard]] const auto &dtype() const { return m_dtype; }
[[nodiscard]] auto &raw() { return m_raw; }
[[nodiscard]] const auto &raw() const { return m_raw; }
[[nodiscard]] auto *data() { return m_raw.data(); }
[[nodiscard]] const auto *data() const { return m_raw.data(); }
private:
std::vector<char> m_raw;
types::Dtype m_dtype;
};
class Dataframe
{
public:
Dataframe(std::vector<char> &raw, std::vector<std::string> names, std::vector<types::Dtype> dtypes)
{
m_raw = std::move(raw);
m_column_dtypes = dtypes;
m_column_names = names;
m_record_size = 0;
for (const auto dt : dtypes)
{
m_column_offsets.emplace_back(m_record_size);
m_record_size += dt.size();
}
m_record_count = m_raw.size() / m_record_size;
}
Dataframe(std::vector<char> &raw, std::vector<types::Dtype> dtypes) : Dataframe(raw, {}, dtypes) {}
Dataframe &operator=(Dataframe &&c) = default; // Move constructor
[[nodiscard]] auto &raw() { return m_raw; }
[[nodiscard]] const auto &raw() const { return m_raw; }
[[nodiscard]] auto *data() { return m_raw.data(); }
[[nodiscard]] const auto *data() const { return m_raw.data(); }
// Iterators
[[nodiscard]] df::Iterator begin()
{
return df::Iterator{m_raw.data(), m_record_size};
}
[[nodiscard]] df::Iterator end()
{
return df::Iterator{m_raw.data() + m_raw.size(), m_record_size};
}
[[nodiscard]] auto shape() const { return std::make_pair(m_record_count, m_column_dtypes.size()); }
[[nodiscard]] auto record_count() const { return m_record_count; }
[[nodiscard]] auto record_size() const { return m_record_size; }
[[nodiscard]] const auto &names() const { return m_column_names; }
[[nodiscard]] const auto &dtypes() const { return m_column_dtypes; }
[[nodiscard]] const auto &offsets() const { return m_column_offsets; }
void print() { print(m_record_count); }
void print(const std::size_t initial_records)
{
// Print header
for (auto column_name : m_column_names)
{
std::cout << column_name << "; ";
}
std::cout << std::endl;
// Print rows
std::size_t records_to_print = std::min(initial_records, m_record_count);
for (std::size_t i = 0; i < records_to_print; i++)
{
const auto start_p = i * record_size();
auto start_field = 0;
auto end_field = 0;
for (auto field : m_column_dtypes)
{
end_field += field.size();
switch (field.base())
{
case types::Base::UNSIGNED:
{
std::uint64_t uint_value = 0;
memcpy(&uint_value, m_raw.data() + start_p + start_field, field.size());
std::cout << uint_value;
break;
}
case types::Base::CHAR:
{
std::string str_value = std::string(m_raw.data() + start_p + start_field, field.size());
std::cout << str_value;
break;
}
}
start_field = end_field;
// New column
std::cout << "; ";
}
// New row
std::cout << std::endl;
}
}
std::shared_ptr<Dataframe> copy() const
{
auto x = std::vector<char>(m_raw);
return std::make_shared<Dataframe>(x, std::vector<std::string>(m_column_names), std::vector<types::Dtype>(m_column_dtypes));
}
private:
std::vector<char> m_raw = {};
std::vector<std::string> m_column_names = {};
std::vector<types::Dtype> m_column_dtypes = {};
std::vector<std::size_t> m_column_offsets = {};
std::size_t m_record_size = {};
std::size_t m_record_count = {};
};
using namespace types;
static std::shared_ptr<Dataframe> read_from_vector(const std::vector<std::vector<std::string>> values, const std::vector<std::string> names, const std::vector<Dtype> dtypes)
{
const auto record_size = std::accumulate(dtypes.begin(), dtypes.end(), std::size_t{0},
[](std::size_t accum, const auto &m)
{ return accum + m.size(); });
const auto total_size = values.size() * record_size;
const std::size_t INCR_RECORDS = std::max(total_size / (10 * record_size), std::size_t{65536});
auto raw = std::vector<char>{};
std::size_t written_records = 0;
auto offsets = std::vector<std::size_t>{};
for (int offset = 0; const auto &kd : dtypes)
{
offsets.push_back(offset);
offset += kd.size();
}
for (auto value : values)
{
if (written_records >= raw.size() / record_size)
{
raw.resize(raw.size() + INCR_RECORDS * record_size, char{' '});
}
for (int i = 0; i < names.size(); i++)
{
const auto name = names[i];
const auto dtype = dtypes[i];
const auto offset = offsets[i];
const auto pos = written_records * record_size + offset;
switch (dtype.base())
{
case df::Base::CHAR:
{
const auto v = value[i];
const auto byte_to_copy = std::min(v.size(), dtype.size());
std::memcpy(raw.data() + pos,
v.data() + v.size() - byte_to_copy, byte_to_copy); // Prendo gli ultimi byte
break;
}
case df::Base::UNSIGNED:
{
const auto v = std::stoull(value[i]);
const auto byte_to_copy = dtype.size();
std::memcpy(raw.data() + pos, &v, byte_to_copy); // Prendo gli ultimi byte
break;
}
default:
throw std::runtime_error("ColumnType non riconosciuto");
}
}
written_records++;
}
raw.resize(written_records * record_size);
raw.shrink_to_fit();
return std::make_shared<Dataframe>(raw, names, dtypes);
}
}
</code></pre>
<p>File: <code>iterator.hpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <iostream>
#include <cstring>
namespace df
{
class Iterator
{
std::size_t size;
char *ptr;
public:
struct record_reference;
struct record_value
{
std::size_t size;
char *ptr;
record_value(const record_reference &t) : record_value(t.size, t.ptr){};
record_value(const std::size_t m_size, char *m_ptr)
{
this->size = m_size;
this->ptr = new char[this->size];
std::memcpy(ptr, m_ptr, this->size);
}
~record_value()
{
delete[] this->ptr;
}
};
struct record_reference
{
std::size_t size;
char *ptr;
record_reference(const std::size_t m_size, char *m_ptr)
{
this->size = m_size;
this->ptr = m_ptr;
}
record_reference(const record_reference &t)
{
this->size = t.size;
this->ptr = t.ptr;
}
// record_reference(const record_value &t) : record_reference(t.size, t.ptr) {};
record_reference &operator=(const record_value &t)
{
std::memcpy(ptr, t.ptr, size);
return *this;
}
record_reference &operator=(const record_reference &t)
{
std::memcpy(ptr, t.ptr, size);
return *this;
}
record_reference &operator=(char *t)
{
std::memcpy(ptr, t, size);
return *this;
}
operator char *()
{
return ptr;
}
operator const char *() const { return ptr; }
};
using iterator_category = std::random_access_iterator_tag;
using value_type = record_value;
using reference = record_reference;
using difference_type = std::ptrdiff_t;
// default constructible
Iterator() : size(0), ptr(nullptr)
{
}
// copy assignable
Iterator &operator=(const Iterator &t)
{
size = t.size;
ptr = t.ptr;
return *this;
}
Iterator(char *ptr, const std::size_t size) : size{size}, ptr(ptr)
{
}
record_reference operator*() const
{
return {size, ptr};
}
// Prefix
Iterator &operator++()
{
ptr += size;
return *this;
}
// Postfix
Iterator operator++(int)
{
auto tmp = *this;
++*this;
return tmp;
}
Iterator &operator--()
{
ptr -= size;
return *this;
}
difference_type operator-(const Iterator &it) const
{
return (this->ptr - it.ptr) / size;
}
Iterator operator+(const difference_type &offset) const
{
return Iterator(ptr + offset * size, size);
}
friend Iterator operator+(const difference_type &diff, const Iterator &it)
{
return it + diff;
}
Iterator operator-(const difference_type &diff) const
{
return Iterator(ptr - diff * size, size);
}
reference operator[](const difference_type &offset) const
{
return {size, ptr + offset * size};
}
bool operator==(const Iterator &it) const
{
return this->ptr == it.ptr;
}
bool operator!=(const Iterator &it) const
{
return !(*this == it);
}
bool operator<(const Iterator &it) const
{
return this->ptr < it.ptr;
}
bool operator>=(const Iterator &it) const
{
return this->ptr >= it.ptr;
}
bool operator>(const Iterator &it) const
{
return this->ptr > it.ptr;
}
bool operator<=(const Iterator &it) const
{
return this->ptr <= it.ptr;
}
Iterator &operator+=(const difference_type &diff)
{
ptr += diff * size;
return *this;
}
operator Iterator() const
{
return Iterator(ptr, size);
}
};
void swap(df::Iterator::record_reference a, df::Iterator::record_reference b)
{
unsigned char *p;
unsigned char *q;
unsigned char *const sentry = (unsigned char *)a.ptr + a.size;
for (p = (unsigned char *)a.ptr, q = (unsigned char *)b.ptr; p < sentry; ++p, ++q)
{
const unsigned char t = *p;
*p = *q;
*q = t;
}
}
}
</code></pre>
<p>File: <code>comparator.hpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <memory>
#include <functional>
#include "dataframe.hpp"
#include "iterator.hpp"
namespace compare
{
using comparator_fn = std::function<int(const df::Iterator::record_reference, const df::Iterator::record_reference)>;
template <typename T, std::size_t offset = 0, std::size_t size = sizeof(T)>
static inline comparator_fn make_comparator()
{
if constexpr (size == 3 or size == 5 or size == 7 or size > 8)
return [=](const df::Iterator::record_reference a, const df::Iterator::record_reference b)
{ return std::memcmp(a + offset, b + offset, size); };
return [](const df::Iterator::record_reference a, const df::Iterator::record_reference b)
{ return *(T *)(a + offset) < *(T *)(b + offset) ? -1 : *(T *)(b + offset) < *(T *)(a + offset) ? +1
: 0; };
}
template <typename T>
static inline comparator_fn make_comparator(const std::size_t offset)
{
return [=](const df::Iterator::record_reference a, const df::Iterator::record_reference b)
{ return *(T *)(a + offset) < *(T *)(b + offset) ? -1 : *(T *)(b + offset) < *(T *)(a + offset) ? +1
: 0; };
}
static inline comparator_fn make_column_comparator(const df::Dtype dtype, const std::size_t offset)
{
switch (dtype.base())
{
case df::Base::CHAR:
{
if (dtype.size() == 1)
return make_comparator<std::uint8_t>(offset);
else if (dtype.size() == 2)
return [=](const df::Iterator::record_reference a, const df::Iterator::record_reference b)
{ return std::memcmp(a + offset, b + offset, 2); }; // C'� qualche beneficio a fissare il 2? o conviene trattarlo come uno unsigned short?
return [=](const df::Iterator::record_reference a, const df::Iterator::record_reference b)
{ return std::memcmp(a + offset, b + offset, dtype.size()); };
}
case df::Base::UNSIGNED:
{
return [=](const df::Iterator::record_reference a, const df::Iterator::record_reference b)
{
std::uint64_t uint_value_a = 0;
std::uint64_t uint_value_b = 0;
std::memcpy(&uint_value_a, a + offset, dtype.size());
std::memcpy(&uint_value_b, b + offset, dtype.size());
return (uint_value_a < uint_value_b ? -1 : uint_value_a > uint_value_b ? +1
: 0);
};
}
default:
throw std::runtime_error("Unsupported dtype");
break;
}
}
static inline comparator_fn make_composite_two_way_comparator(const std::shared_ptr<df::Dataframe> &T)
{
const auto K = T->dtypes().size();
std::vector<comparator_fn> F;
for (int i = 0; i < K; i++)
{
F.emplace_back(make_column_comparator(T->dtypes()[i], T->offsets()[i]));
}
const auto comparator = [=](const df::Iterator::record_reference a, const df::Iterator::record_reference b)
{
for (int i = 0; i < K; i++)
{
// If equal go to the next column, otherwise return the result
// The return value is true if the first argument is less than the second
// and false otherwise
if (const auto result = F[i](a, b); result != 0)
return result < 0;
}
return false;
};
return comparator;
}
}
</code></pre>
<p>File: <code>main.cpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <vector>
#include "dataframe.hpp"
#include "comparator.hpp"
template <typename RandomAccessIterator, typename Comparator>
static void selection_sort(RandomAccessIterator first, RandomAccessIterator last, Comparator comp)
{
for (auto i = first; i != last; ++i)
{
auto min = i;
for (auto j = i + 1; j != last; ++j)
{
if (comp(*j, *min))
min = j;
}
df::Iterator::value_type temp = *i;
*i = *min;
*min = temp;
// Alternative
// std::iter_swap(i, min);
}
}
int main(int argc, char const *argv[])
{
std::vector<std::string> values{"20", "21", "20", "19", "10", "11", "40", "41", "10", "11"};
// Create a vector that contains values grouped by 2
std::vector<std::vector<std::string>> v;
for (int i = 0; i < values.size(); i += 2)
{
std::vector<std::string> temp;
temp.push_back(values[i]);
temp.push_back(values[i + 1]);
v.push_back(temp);
}
std::vector<std::string> column_names = {"a", "b"};
df::Dtype d = df::Dtype(df::Base::UNSIGNED, 4);
std::vector dtypes = {d, d};
// Create a dataframe
std::shared_ptr<df::Dataframe> df = df::read_from_vector(v, column_names, dtypes);
std::cout << "Before sorting" << std::endl;
df->print();
// This comparator sorts the dataframe first by column a and then by column b in ascending order
auto comparator = compare::make_composite_two_way_comparator(df);
selection_sort(df->begin(), df->end(), comparator);
std::cout << "\nAfter sorting" << std::endl;
df->print();
// With the std::sort it does not work
std::sort(df->begin(), df->end(), comparator);
return 0;
}
</code></pre>
| [
{
"answer_id": 74447728,
"author": "Fenix9697",
"author_id": 13955961,
"author_profile": "https://Stackoverflow.com/users/13955961",
"pm_score": -1,
"selected": false,
"text": "this.apiResponse = await this.myService.emailValidate({ email: customerEmail});\n console.log(\"this.apiResponse\", this.apiResponse)\n"
},
{
"answer_id": 74456895,
"author": "Mukesh Soni",
"author_id": 11556649,
"author_profile": "https://Stackoverflow.com/users/11556649",
"pm_score": 0,
"selected": false,
"text": "validateEmail = async () => {\n const params = {\n emailAddress: 'test@gmail.com',\n };\n const apiResponse: boolean = await this.emailService.validateEmail(params);\n console.log(`apiResponse===`, apiResponse);\n };\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6247718/"
] |
74,447,452 | <p>I am trying to get hero name by hero id for my program.</p>
<p>Let's assume that I have an array with hero ids: <code>hero_ids = [1, 15, 27, 44, 135]</code></p>
<p>and a dict with a list of dicts with hero information:</p>
<pre><code>{
"heroes": [
{
"name": "hero1",
"id": 1,
},
{
"name": "hero2",
"id": 2,
},
{
"name": "hero3",
"id": 3,
},
</code></pre>
<p>Question: how do I get a list of hero names for each hero id?</p>
<p>I've spent 3 hours on this but don't understand the idea. I've tried list comprehensions (seems they can't be used with dicts), manual indexing going through hero_ids array or heroes array but no luck</p>
| [
{
"answer_id": 74447728,
"author": "Fenix9697",
"author_id": 13955961,
"author_profile": "https://Stackoverflow.com/users/13955961",
"pm_score": -1,
"selected": false,
"text": "this.apiResponse = await this.myService.emailValidate({ email: customerEmail});\n console.log(\"this.apiResponse\", this.apiResponse)\n"
},
{
"answer_id": 74456895,
"author": "Mukesh Soni",
"author_id": 11556649,
"author_profile": "https://Stackoverflow.com/users/11556649",
"pm_score": 0,
"selected": false,
"text": "validateEmail = async () => {\n const params = {\n emailAddress: 'test@gmail.com',\n };\n const apiResponse: boolean = await this.emailService.validateEmail(params);\n console.log(`apiResponse===`, apiResponse);\n };\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19131160/"
] |
74,447,485 | <p>I have</p>
<pre><code>// Input DTOs:
public class FeatureIn {
private String val1;
private String val2;
}
public class ContainerIn {
private List<FeatureIn> features;
}
public class PersonIn {
private String name;
private String age;
private List<ContainerIn> containers;
}
// Output DTOs:
public class FeatureOut {
private String val1;
private String val2;
}
public class PersonOut {
private String name;
private Integer age;
private List<FeatureOut> features;
}
</code></pre>
<p>What I have to do is to map PersonIn -> PersonOut. For name and age it is easy. For features is quite complicated. I'm receiving the PersonOut object that contains containers list (but this list is already filtered so it will always have only 1 object). I have to read first object of this list and then map List to List. In other words. PersonOut.containers.get(0).features should be mapped to PersonOut.features</p>
<p>I tried those two:</p>
<pre><code>@Mapper(componentModel = "spring")
public interface PersonMapper {
@Mapping(target = "features", source = "containers.features")
PersonOut toPersonOut(PersonIn personIn);
}
@Mapper(componentModel = "spring")
public interface PersonMapper {
@Mapping(target = "features", expression = "java(personIn.getContainers().get(0).getFeatures())")
PersonOut toPersonOut(PersonIn personIn);
}
</code></pre>
<p>but it doesn't work. How can I do it?</p>
<p>The second solution (expression) is almost working... Mapper is generated but I have compilation fail in this line:</p>
<pre><code>List<FeatureOut> features = personIn.getContainers().get(0).getFeatures();
</code></pre>
<p>because he tries to map List to List
but types are not compatible - how can I tell him how to map it?
I tried to add use = FeaturesMapper.class to my @Mapper but it was not working.</p>
| [
{
"answer_id": 74447980,
"author": "Gonzalo Lorieto",
"author_id": 6615581,
"author_profile": "https://Stackoverflow.com/users/6615581",
"pm_score": -1,
"selected": false,
"text": "\n@Mapper\npublic interface FeatureMapper {\n List<FeatureOut> map(List<FeatureIn> featureIn);\n}\n\n\n@Mapper(uses = { FeatureMapper.class })\npublic interface PersonMapper {\n List<PersonOut> map(List<PersonIn> peopleIn);\n}\n\n\n"
},
{
"answer_id": 74448076,
"author": "YCF_L",
"author_id": 5558072,
"author_profile": "https://Stackoverflow.com/users/5558072",
"pm_score": 2,
"selected": true,
"text": "qualifiedByName"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9313046/"
] |
74,447,495 | <p>I created a dataframe (Dates) of dates/times every 3 hours from 1981-2010 as follows:</p>
<pre><code># Create dates and times
start <- as.POSIXct("1981-01-01")
interval <- 60
end <- start + as.difftime(10957, units="days")
Dates = data.frame(seq(from=start, by=interval*180, to=end))
colnames(Dates) = "Date"
</code></pre>
<p>I now want to split the data into four separate columns with year, month, day and hour. I tried so split the dates using the following code:</p>
<pre><code>Date.split = strsplit(Dates, "-| ")
</code></pre>
<p>But I get the following error:</p>
<pre><code>Error in strsplit(Dates, "-| ") : non-character argument
</code></pre>
<p>If I try to convert the Dates data to characters then it completely changes the dates, e.g.</p>
<pre><code>Dates.char = as.character(Dates)
</code></pre>
<p>gives the following output:</p>
<pre><code>Dates.char Large Character (993.5 kB)
chr "c(347155200, 347166000 ...
</code></pre>
<p>I'm getting lost with the conversion between character and numeric and don't know where to go from here. Any insights much appreciated.</p>
| [
{
"answer_id": 74447980,
"author": "Gonzalo Lorieto",
"author_id": 6615581,
"author_profile": "https://Stackoverflow.com/users/6615581",
"pm_score": -1,
"selected": false,
"text": "\n@Mapper\npublic interface FeatureMapper {\n List<FeatureOut> map(List<FeatureIn> featureIn);\n}\n\n\n@Mapper(uses = { FeatureMapper.class })\npublic interface PersonMapper {\n List<PersonOut> map(List<PersonIn> peopleIn);\n}\n\n\n"
},
{
"answer_id": 74448076,
"author": "YCF_L",
"author_id": 5558072,
"author_profile": "https://Stackoverflow.com/users/5558072",
"pm_score": 2,
"selected": true,
"text": "qualifiedByName"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5427561/"
] |
74,447,529 | <p>I have a pandas dataframe, with two columns id and user_name.</p>
<p>Where the id column have this format (xxxxxx-xxx-A): r'[0-9]{6}-[0-9]{3}$'+alphabet letter.</p>
<p>Here's my dataframe example :</p>
<pre><code>id user name
095082-000-A name1
095772-101-A name2
095082-000-B name3
095772-101-E name4
095772-101-Z name5
095772-101-D name6
095082-000-F name7
015082-001-A name8
</code></pre>
<p>The expected result is to keep only the rows with the id that the part "xxxxxx-xxx-" not duplicate and with the last (by order) alphabet letter:</p>
<pre><code>id user name
095772-101-Z name5
095082-000-F name7
015082-001-A name8
</code></pre>
<p>What is the efficient way to do it? Thank you</p>
| [
{
"answer_id": 74447980,
"author": "Gonzalo Lorieto",
"author_id": 6615581,
"author_profile": "https://Stackoverflow.com/users/6615581",
"pm_score": -1,
"selected": false,
"text": "\n@Mapper\npublic interface FeatureMapper {\n List<FeatureOut> map(List<FeatureIn> featureIn);\n}\n\n\n@Mapper(uses = { FeatureMapper.class })\npublic interface PersonMapper {\n List<PersonOut> map(List<PersonIn> peopleIn);\n}\n\n\n"
},
{
"answer_id": 74448076,
"author": "YCF_L",
"author_id": 5558072,
"author_profile": "https://Stackoverflow.com/users/5558072",
"pm_score": 2,
"selected": true,
"text": "qualifiedByName"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19735352/"
] |
74,447,552 | <p>Question: HOW can I get the same result for the below query but without using GROUP BY?</p>
<p>Can someone provide me with a solution that does the same, <strong>but without using GROUP BY</strong>:</p>
<p>SELECT Klasse, COUNT(<em>) AS Anzahl FROM Charaktere
WHERE Schaden > 700
GROUP BY Klasse
HAVING COUNT(</em>) > 1</p>
<p>The statement MUST function on an oracle-server.</p>
<p>Test-data:</p>
<pre><code>CREATE TABLE Charaktere (
Charakter_ID varchar(300),
Name varchar(300),
Klasse varchar(300),
Rasse varchar(300),
Stufe varchar(300),
Leben_Multiplikator varchar(300),
Mana_Multiplikator varchar(300),
Rüstung varchar(300),
Waffen_ID varchar(300),
Schaden varchar(300)
);
CREATE TABLE Klassen (
Klassen_ID varchar(300),
Klasse varchar(300),
Basisleben varchar(300),
Basismana varchar(300),
Schwächen varchar(300)
);
CREATE TABLE Ausrüstung (
Ausrüstung_ID varchar(300),
Rüstung varchar(300),
Schmuck varchar(300)
);
CREATE TABLE Waffen (
Waffen_ID varchar(300),
Links varchar(300),
Rechts varchar(300)
);
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('1','Herald','Zauberer','Mensch','67','2','8','Heilig','4','718');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('2','Roderic','Paladin','Mensch','55','10','3','Schwer','2','691');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('3','Favian','Schurke','Ork','32','4','1','Leicht','3','243');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('4','Vega','Berserker','Zwerg','44','9','8','Schwer','2','118');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('5','Matep','Jäger','Dunkel Elf','24','3','6','Leicht','1','368');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('6','Euris','Kleriker','Mensch','77','7','8','Resistent','4','774');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('7','Dara’a','Nekromant','Blut Elf','99','6','1','Verdorben','5','966');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('8','Eodriel','Magier','Hoch Elf','24','2','3','Resistent','5','399');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('9','Kerodan','Magier','Blut Elf','20','6','2','Heilig','4','758');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('10','Hans','Paladin','Mensch','67','7','9','Schwer','2','632');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('11','Falk','Berserker','Mensch','13','8','6','Leicht','2','149');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('12','Sethrak','Paladin','Ork','54','5','1','Schwer','3','657');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('13','Hozen','Kleriker','Zwerg','68','6','3','Heilig','4','710');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('14','Venthyr','Jäger','Dunkel Elf','23','4','7','Leicht','1','197');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('15','Stanford','Paladin','Mensch','56','3','7','Resistent','2','370');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('16','Celoevalin','Zauberer','Blut Elf','8','3','6','Heilig','4','383');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('17','Sylvar','Berserker','Hoch Elf','76','9','4','Verdorben','2','837');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('18','Kyrian','Zauberer','Zwerg','69','6','3','Heilig','5','756');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('19','Ithris','Kleriker','Dunkel Elf','88','9','6','Resistent','4','500');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('20','Diedrich','Magier','Mensch','1','2','2','Heilig','2','102');
INSERT INTO Charaktere (Charakter_ID,Name,Klasse,Rasse,Stufe,Leben_Multiplikator,Mana_Multiplikator,Rüstung,Waffen_ID,Schaden) VALUES ('21','Dar’mir','Jäger','Blut Elf','14','1','7','Leicht','1','150');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('1','Zauberer','70','170','Paladin');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('2','Paladin','150','110','Zauberer');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('3','Schurke','100','100','Magier');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('4','Berserker','200','80','Jäger');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('5','Jäger','110','100','Schurke');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('6','Kleriker','95','120','Nekromant');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('7','Nekromant','50','200','Paladin');
INSERT INTO Klassen (Klassen_ID,Klasse,Basisleben,Basismana,Schwächen) VALUES ('8','Magier','85','150','Berserker');
INSERT INTO Ausrüstung (Ausrüstung_ID,Rüstung,Schmuck) VALUES ('1','Schwer','Kette');
INSERT INTO Ausrüstung (Ausrüstung_ID,Rüstung,Schmuck) VALUES ('2','Leicht','Armreif');
INSERT INTO Ausrüstung (Ausrüstung_ID,Rüstung,Schmuck) VALUES ('3','Resistent','Anhänger');
INSERT INTO Ausrüstung (Ausrüstung_ID,Rüstung,Schmuck) VALUES ('4','Heilig','Ring');
INSERT INTO Ausrüstung (Ausrüstung_ID,Rüstung,Schmuck) VALUES ('5','Verdorben','Talisman');
INSERT INTO Waffen (Waffen_ID,Links,Rechts) VALUES ('1','Bogen','Dolch');
INSERT INTO Waffen (Waffen_ID,Links,Rechts) VALUES ('2','Langschwert',NULL);
INSERT INTO Waffen (Waffen_ID,Links,Rechts) VALUES ('3','Axt','Axt');
INSERT INTO Waffen (Waffen_ID,Links,Rechts) VALUES ('4','Zauberstab','Zauberbuch');
INSERT INTO Waffen (Waffen_ID,Links,Rechts) VALUES ('5','Zauberbuch','Zauberbuch');
</code></pre>
<p>Please don't lecture me about the why's and so on ... I just need an answer to my question :-)</p>
| [
{
"answer_id": 74447980,
"author": "Gonzalo Lorieto",
"author_id": 6615581,
"author_profile": "https://Stackoverflow.com/users/6615581",
"pm_score": -1,
"selected": false,
"text": "\n@Mapper\npublic interface FeatureMapper {\n List<FeatureOut> map(List<FeatureIn> featureIn);\n}\n\n\n@Mapper(uses = { FeatureMapper.class })\npublic interface PersonMapper {\n List<PersonOut> map(List<PersonIn> peopleIn);\n}\n\n\n"
},
{
"answer_id": 74448076,
"author": "YCF_L",
"author_id": 5558072,
"author_profile": "https://Stackoverflow.com/users/5558072",
"pm_score": 2,
"selected": true,
"text": "qualifiedByName"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11558281/"
] |
74,447,578 | <p>I have built a login Automator using Selenium, and the code executes without errors but the script doesn't login. The page is stuck at login page, email and password are entered, but login is not completed.
<a href="https://i.stack.imgur.com/QOH0V.jpg" rel="nofollow noreferrer">enter image description here</a></p>
<p>I have tried 2 ways to login:</p>
<ol>
<li>By clicking on Login through Click ()</li>
</ol>
<pre><code>e = self.driver.find_element(By.XPATH, "//div[text()='Login']")
e.click()
</code></pre>
<ol start="2">
<li>Using Enter in password area</li>
</ol>
<pre><code>password_element.send_keys(Keys.ENTER)
</code></pre>
<p>But neither of them logs me in, even though I can see the button being clicked, and name and password being entered.
I also tried adding a wait time, but the problem is not solved. What an I doing wrong?</p>
<p>Here is the code:</p>
<pre><code>
import pandas as pd
from selenium import webdriver
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
class QuoraScraper:
def __init__(self):
self.driver = ''
self.dataframe = ''
self.credentials = {
'email': 'email',
'password': 'password'
}
self.questions = []
self.answers = []
def start_driver(self):
options = Options()
options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe'
self.driver = webdriver.Firefox(options=options)
def close_driver(self):
self.driver.close()
def open_url(self, url):
self.driver.get(url)
def initialize_columns(self, columns):
self.dataframe = pd.DataFrame(columns=columns)
def set_credentials(self, email, password):
self.credentials['email'] = email
self.credentials['password'] = password
def login(self):
self.open_url('https://www.quora.com/')
if (self.credentials['email'] and self.credentials['password']):
email_element = self.driver.find_element(By.ID, 'email')
password_element = self.driver.find_element(By.ID, 'password')
email_element.send_keys(self.credentials['email'])
password_element.send_keys(self.credentials['password'])
# I tried adding a wait time but the script is not successful either way
#self.driver.maximize_window() # For maximizing window
#self.driver.implicitly_wait(20) # gives an implicit wait for 20 seconds
# I tried clcking on Login through both Click and Enter but neither of them logs me in, even though I can see the button clicking
password_element.send_keys(Keys.ENTER)
e = self.driver.find_element(By.XPATH, "//div[text()='Login']")
e.click()
else:
print('Credentials not set. Error')
if __name__ == "__main__":
scraper = QuoraScraper()
scraper.start_driver()
email = "email"
password = "password"
scraper.set_credentials(email, password)
scraper.login()
</code></pre>
<p><strong>UPDATE 2:</strong> I get a login popup window after the email and password have been correctly entered and i try to close it by finding the xpath of the X button like this:
<a href="https://i.stack.imgur.com/rJf7E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rJf7E.png" alt="POPUP IMAGE" /></a></p>
<pre><code>cross = self.driver.find_element(By.XPATH, '//*[@id="close"]')
cross.click()
</code></pre>
<p>But the element cannot be located:</p>
<blockquote>
<p>selenium.common.exceptions.NoSuchElementException: Message: Unable to
locate element: //*[@id="close"]</p>
</blockquote>
| [
{
"answer_id": 74448305,
"author": "Archiee",
"author_id": 11756439,
"author_profile": "https://Stackoverflow.com/users/11756439",
"pm_score": 0,
"selected": false,
"text": "//div[text()='Login']"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5587119/"
] |
74,447,586 | <p><a href="https://i.stack.imgur.com/im2lv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/im2lv.png" alt="enter image description here" /></a></p>
<pre><code> class CardWidget extends StatefulWidget {
final String title;
final Color? color;
final IconData? icon;
final Widget? child;
const CardWidget({
super.key,
required this.title,
this.color,
this.icon,
this.child,
});
@override
State<CardWidget> createState() => _CardWidgetState();
}
final controllers = List.generate(12, (index) => TextEditingController());
class _CardWidgetState extends State<CardWidget> {
@override
Widget build(BuildContext context) {
return SizedBox(
height: 200,
width: 200,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
color: widget.color,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Icon(
widget.icon,
color: Colors.white,
size: 32,
),
Center(
child: Text(
widget.title,
),
GestureDetector(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30,
),
child: TextFormField(
controller: controllers[],
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: ((context) => AddCard())));
},
),
))
],
),
),
),
);
}
}
</code></pre>
<p>CardWidget I use to show on homepage</p>
<pre><code> class AddCard extends StatelessWidget {
const AddCard({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: GridView.builder(
padding: const EdgeInsets.all(50),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
),
itemCount: 12,
itemBuilder: (context, index) => ItemTile(
cardNo: index,
callback: (p0) {
controllers[index].text = p0.toString();
})),
),
);
}
}
</code></pre>
<p>The page where I redirect the user when clicking on the TextFormField.</p>
<pre><code> class ItemTile extends StatelessWidget {
final int cardNo;
const ItemTile(
this.cardNo,
);
@override
Widget build(BuildContext context) {
return ListTile(
onTap: () {
},
title: Center(
child: Text(
'Tuş ${cardNo + 1}',
key: Key('text_$cardNo'),
),
),
),
);
}
</code></pre>
<p>I have cards 1 to 12 and each card has numbers 1 to 12 inside. I want to pass these texts to <code>TextFormField</code> when the user clicks on the card.</p>
<p>There are 12 Card designs on my homepage. There is a textFormField inside each of these cards. When the TextFormField is clicked, it goes to a list that I created with GridView in AddCard. There are 12 elements in this list. There are numbers from 1 to 12 inside these 12 elements. When I click on one of them, I want the number there to be assigned to the one I clicked, in the 12 textFormField on the homepage.</p>
| [
{
"answer_id": 74447694,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": " onTap: () {\n Navigator.pop(context, \"cardNo\");\n },\n"
},
{
"answer_id": 74447729,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "TextEditingController"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17906689/"
] |
74,447,590 | <p>I have a table of colors. I want to combine the same colors into single field & also their sum of quantity will be shown in that row.</p>
<p>For example, In the table below I have 2 "black" colors with quantities 5 & 2. Now want to combine this 2 rows into one & the quantity field will be "5+2 = 7" .</p>
<p>what I want is---</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>th{
border:1px solid black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<thead>
<tr>
<th>Color</th>
<th>Rate</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<tr>
<td>white</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>Black</td>
<td>5</td>
<td>7</td>
</tr>
<tr>
<td>red</td>
<td>6</td>
<td>0</td>
</tr>
</tbody>
</table></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74447972,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 3,
"selected": true,
"text": "reduce()"
},
{
"answer_id": 74447974,
"author": "Valentin Marguerie",
"author_id": 15522586,
"author_profile": "https://Stackoverflow.com/users/15522586",
"pm_score": 2,
"selected": false,
"text": "v-for"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19813093/"
] |
74,447,595 | <p>I've got a vim setup that is close to my desired setup. I can type and see suggestions in my text as I type. That is my goal. I have a NerdFonts font installed and NerTree, and I can see icons in NerTree. I cannot see icons in the text that drops down as I type, and that is my problem.</p>
<pre><code> set clipboard=unnamedplus " using system clipboard
set number
set hidden
call plug#begin("~/.vim/plugged")
Plug 'neovim/nvim-lspconfig'
Plug 'hrsh7th/cmp-nvim-lsp'
Plug 'hrsh7th/cmp-buffer'
Plug 'hrsh7th/cmp-path'
Plug 'hrsh7th/cmp-cmdline'
Plug 'hrsh7th/nvim-cmp'
Plug 'dracula/vim', { 'as': 'dracula' } " better dracula
Plug 'preservim/nerdtree'
Plug 'vim-airline/vim-airline'
Plug 'williamboman/nvim-lsp-installer'
Plug 'neovim/nvim-lspconfig'
" start coc stuff here - auto complete js and python
Plug 'neoclide/coc.nvim', {'branch': 'release'} " this is for auto complete, prettier and tslinting
Plug 'jiangmiao/auto-pairs' "this will auto close ( [ {
" these two plugins will add highlighting and indenting to JSX and TSX files.
Plug 'yuezk/vim-js'
Plug 'HerringtonDarkholme/yats.vim'
Plug 'maxmellon/vim-jsx-pretty'
" Plug 'yamatsum/nvim-nonicons'
Plug 'ryanoasis/vim-devicons'
call plug#end()
colorscheme dracula
let g:coc_global_extensions = ['coc-tslint-plugin', 'coc-tsserver', 'coc-css', 'coc-html', 'coc-json', 'coc-prettier', 'coc-python', 'coc-pyright'] " list of CoC extensions needed
set encoding=UTF-8
" set guifont=agave\ Nerd\ Font\ Mono\ 12
" set guifont=DroidSansMono\ Nerd\ Font\ 12
" Start NERDTree. If a file is specified, move the cursor to its window.
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * NERDTree | if argc() > 0 || exists("s:std_in") | wincmd p | endif
" Close the tab if NERDTree is the only window remaining in it.
autocmd BufEnter * if winnr('$') == 1 && exists('b:NERDTree') && b:NERDTree.isTabTree() | quit | endif
set mouse=a
let g:NERDTreeMouseMode = 2
let g:airline_powerline_fonts = 1
if has("autocmd")
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
endif
let g:airline#extensions#tabline#enabled=1
let g:airline_theme='dracula' " 'badwolf'
let g:airline_powerline_fonts = 1
""""""""""""""""""""""""""""""""""""""""
"" keymaps
""""""""""""""""""""""""""""""""""""""""
lua <<EOF
require "keymap"
EOF
""""""""""""""""""""""""""""""""""""""""""""""
"" cmp
""""""""""""""""""""""""""""""""""""""""""""""
set completeopt=menu,menuone,noselect
set signcolumn=yes
" Use tab for trigger completion with characters ahead and navigate.
" NOTE: There's always complete item selected by default, you may want to enable
" no select by `"suggest.noselect": true` in your configuration file.
" NOTE: Use command ':verbose imap <tab>' to make sure tab is not mapped by
" other plugin before putting this into your config.
inoremap <silent><expr> <TAB>
\ coc#pum#visible() ? coc#pum#next(1) :
\ CheckBackspace() ? "\<Tab>" :
\ coc#refresh()
inoremap <expr><S-TAB> coc#pum#visible() ? coc#pum#prev(1) : "\<C-h>"
" Make <CR> to accept selected completion item or notify coc.nvim to format
" <C-g>u breaks current undo, please make your own choice.
inoremap <silent><expr> <CR> coc#pum#visible() ? coc#pum#confirm()
\: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"
function! CheckBackspace() abort
let col = col('.') - 1
return !col || getline('.')[col - 1] =~# '\s'
endfunction
</code></pre>
<p>nvim v0.7.2</p>
<p><a href="https://i.stack.imgur.com/ALQWC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ALQWC.png" alt="enter image description here" /></a></p>
<p>See, on the right, there are colored letters but not icons.</p>
| [
{
"answer_id": 74447972,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 3,
"selected": true,
"text": "reduce()"
},
{
"answer_id": 74447974,
"author": "Valentin Marguerie",
"author_id": 15522586,
"author_profile": "https://Stackoverflow.com/users/15522586",
"pm_score": 2,
"selected": false,
"text": "v-for"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/859559/"
] |
74,447,609 | <p>Hello i have a list that has the following information that is retrieved from a db</p>
<pre><code>test_list_1 = ['01/01/2022:79.86','02/01/2022:65.86','03/01/2022:600.23','04/01/2022:179.26']
test_list_2 = ['01/01/2022:55.86','02/01/2022:25.75','03/01/2022:300.23']
</code></pre>
<p>I would like to be able to produce the following output from that:</p>
<pre><code># Output of test_list_1
01/01/2022 (79.86) => 02/01/2022 (65.86) => Percentage Diff (-17%)
01/01/2022 (79.86) => 03/01/2022 (600.23) => Percentage Diff (+651%)
01/01/2022 (79.86) => 04/01/2022 (179.26) => Percentage Diff (+124%)
02/01/2022 (65.86) => 03/01/2022 (600.23) => Percentage Diff (+811%)
02/01/2022 (65.86) => 04/01/2022 (179.26) => Percentage Diff (+172%)
03/01/2022 (600.23) => 04/01/2022 (179.26) => Percentage Diff (-70%)
# Output of test_list_2
01/01/2022 (55.86) => 02/01/2022 (25.75) => Percentage Diff (-53%)
01/01/2022 (55.86) => 03/01/2022 (300.23) => Percentage Diff (+437%)
02/01/2022 (25.75) => 03/01/2022 (300.23) => Percentage Diff (+1065%)
</code></pre>
<p>I am having a lot of trouble even trying to figure out the logic on how to do this. If some one can please assist me with just getting started with this that would be amazing.</p>
<p>Thank you very much in advance.</p>
| [
{
"answer_id": 74448107,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 3,
"selected": true,
"text": "itertools"
},
{
"answer_id": 74448214,
"author": "riccardo.lobianco",
"author_id": 15851329,
"author_profile": "https://Stackoverflow.com/users/15851329",
"pm_score": 0,
"selected": false,
"text": "test_list_1 =['01/01/2022:79.86','02/01/2022:65.86','03/01/2022:600.23','04/01/2022:179.26']\n\ntest_list_1 = [el.split(':') for el in test_list_1]\n\nfor index, value in enumerate(test_list_1):\n for next_index, next_value in enumerate(test_list_1[index+1:]):\n v = 100*(float(next_value[1]) - float(value[1]))/float(value[1])\n print(f\"{value[0]} ({value[1]}) => {next_value[0]} ({next_value[1]}) => Percentage Diff ({int(v)})%\")\n"
},
{
"answer_id": 74448215,
"author": "ShadowRanger",
"author_id": 364696,
"author_profile": "https://Stackoverflow.com/users/364696",
"pm_score": 2,
"selected": false,
"text": "parsed_list_1 = []\nfor s in test_list_1:\n date, sep, price = s.partition(':')\n # Optionally test \"if sep:\" and raise an error if the data didn't have the expected colon in it\n parsed_list_1.append((date, float(price)) # Store a tuple of the date string and parsed prices\n"
},
{
"answer_id": 74448236,
"author": "HeadinCloud",
"author_id": 7450826,
"author_profile": "https://Stackoverflow.com/users/7450826",
"pm_score": 0,
"selected": false,
"text": "lst = ['01/01/2022:79.86','02/01/2022:65.86','03/01/2022:600.23','04/01/2022:179.26']\n\n\ndef pairings(pool):\n for i, m in enumerate(pool):\n for n in pool[i+1:]:\n yield (m, n)\n\nnew_list = list(pairings(lst))\n\nfor i,j in new_list:\n diff = int((float(j.split(\":\", 1)[1]) - float(i.split(\":\", 1)[1]))/float(i.split(\":\", 1)[1])*100)\n print(i + \" => \" + j + \" => Percentage Diff \" + str(diff) + \"%\")\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20511208/"
] |
74,447,649 | <p>In the following code I wanted to generate a color heatmap (w x h x 3) based on the values of a NumPy 2-d array, in the range [-1; 1], and, unsurprisingly, it is really slow on large arrays (10000 x 10000) compared to the rest of the program, which uses NumPy numerical operations. Colors are in the [B, G, R] format.</p>
<pre><code>def img_to_heatmap(arr):
height, width = arr.shape
heatmap = np.zeros((height, width, 3))
for i in range(width):
for j in range(height):
val = arr[i,j]
if(val < 0): # [-1 to 0)
val += 1
heatmap[i,j,:] = [0, val * 255, 255] # red -> yellow
else: # [0 to 1]
heatmap[i,j,:] = [0, 255, 255 - 255*val] # yellow -> green
return heatmap
</code></pre>
<p>How can this code run faster while using the exact same color map? I know OpenCV has built-in heatmap calculations, but not the exact color map I want.</p>
| [
{
"answer_id": 74448107,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 3,
"selected": true,
"text": "itertools"
},
{
"answer_id": 74448214,
"author": "riccardo.lobianco",
"author_id": 15851329,
"author_profile": "https://Stackoverflow.com/users/15851329",
"pm_score": 0,
"selected": false,
"text": "test_list_1 =['01/01/2022:79.86','02/01/2022:65.86','03/01/2022:600.23','04/01/2022:179.26']\n\ntest_list_1 = [el.split(':') for el in test_list_1]\n\nfor index, value in enumerate(test_list_1):\n for next_index, next_value in enumerate(test_list_1[index+1:]):\n v = 100*(float(next_value[1]) - float(value[1]))/float(value[1])\n print(f\"{value[0]} ({value[1]}) => {next_value[0]} ({next_value[1]}) => Percentage Diff ({int(v)})%\")\n"
},
{
"answer_id": 74448215,
"author": "ShadowRanger",
"author_id": 364696,
"author_profile": "https://Stackoverflow.com/users/364696",
"pm_score": 2,
"selected": false,
"text": "parsed_list_1 = []\nfor s in test_list_1:\n date, sep, price = s.partition(':')\n # Optionally test \"if sep:\" and raise an error if the data didn't have the expected colon in it\n parsed_list_1.append((date, float(price)) # Store a tuple of the date string and parsed prices\n"
},
{
"answer_id": 74448236,
"author": "HeadinCloud",
"author_id": 7450826,
"author_profile": "https://Stackoverflow.com/users/7450826",
"pm_score": 0,
"selected": false,
"text": "lst = ['01/01/2022:79.86','02/01/2022:65.86','03/01/2022:600.23','04/01/2022:179.26']\n\n\ndef pairings(pool):\n for i, m in enumerate(pool):\n for n in pool[i+1:]:\n yield (m, n)\n\nnew_list = list(pairings(lst))\n\nfor i,j in new_list:\n diff = int((float(j.split(\":\", 1)[1]) - float(i.split(\":\", 1)[1]))/float(i.split(\":\", 1)[1])*100)\n print(i + \" => \" + j + \" => Percentage Diff \" + str(diff) + \"%\")\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15591418/"
] |
74,447,695 | <p>I have a dataframe that look like:</p>
<pre><code> corpus zero_level_name time labels A B C
0 ff f 1 1
1 gg g G
2 hh h H 1 1 1
3 ii i I
4 jj j J 1
</code></pre>
<p>I want to add 0 to all the empty cells from columns A to C. Is it possible to do this in one goal?</p>
| [
{
"answer_id": 74447835,
"author": "markd227",
"author_id": 13650733,
"author_profile": "https://Stackoverflow.com/users/13650733",
"pm_score": 0,
"selected": false,
"text": "pd.concat([df[['corpus', 'zero_level_name', 'time', 'labels']],df[['A','B','C']].fillna(0)], axis=1)\n"
},
{
"answer_id": 74447849,
"author": "Filip",
"author_id": 10258933,
"author_profile": "https://Stackoverflow.com/users/10258933",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\nimport pandas as pd\n\ndf = pd.DataFrame(\n data=np.array([\n ['ff', 'gg', 'hh', 'ii', 'jj'],\n [None, 'g', 'h', 'i', 'j'],\n ['f', 'G', 'H', 'I', 'J'],\n [None, None, None, None, None],\n [1, None, 1, None, 1],\n [1, None, 1, None, None],\n [None, None, 1, None, None]\n\n ]).T,\n columns=['corpus', 'zero_level_name', 'time', 'labels', 'A', 'B', 'C'],\n)\n\ndf[['A', 'B', 'C']] = df[['A', 'B', 'C']].fillna(0)\n"
},
{
"answer_id": 74447880,
"author": "timgeb",
"author_id": 3620003,
"author_profile": "https://Stackoverflow.com/users/3620003",
"pm_score": 0,
"selected": false,
"text": "cols = ['A', 'B', 'C']\ndf[cols] = df[cols].mask(df[cols] == '', 0)\n"
},
{
"answer_id": 74447882,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "df.update(df.loc[:, 'A':'C'].replace('', 0).fillna(0))\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19381301/"
] |
74,447,698 | <p>I have a dataframe with 1.6 million rows and one of the columns is a list of character vectors.</p>
<p>Each element of this list column looks as follows : <code>c("A61K", "A61K", "A61K", "A61K", "A61K", "A61K", "A61K", "A61K", "A61K", "A61K", "A61Q", "B05B")</code>.</p>
<p>I would like for it to be <code>c("A61K","A61Q","B05B")</code>.</p>
<p>Meaning I just want to keep the unique values. This process should be repeated for each row.</p>
<p>I have tried this:</p>
<pre><code>sapply(strsplit(try, "|", function(x) paste0(unique(x), collapse = ",")))
</code></pre>
<p>And solutions using for loops but it takes very long and R stops running.</p>
| [
{
"answer_id": 74447809,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": false,
"text": "unique"
},
{
"answer_id": 74448468,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 0,
"selected": false,
"text": "duplicated"
},
{
"answer_id": 74450334,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": true,
"text": "unique()"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11329975/"
] |
74,447,759 | <p>i wanna create objects with intellij (jpa) system,</p>
<p>but after i create objects,</p>
<p>there's no change in h2 console.</p>
<p>i expect that the objects are made like this, <a href="https://i.stack.imgur.com/4IJNf.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>(wanna make ITEM and MOVIE objects)</p>
<p>but what i got is this. <a href="https://i.stack.imgur.com/dEyTt.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>these are the codes that i wrote.</p>
<pre><code>package hellojpa;
import javax.persistence.Entity;
@Entity
public class Album extends Item{
private String artist;
}
</code></pre>
<pre><code>package hellojpa;
import javax.persistence.Entity;
@Entity
public class Book extends Item{
private String author;
private String isbn;
}
</code></pre>
<pre><code>package hellojpa;
import org.hibernate.engine.internal.JoinSequence;
import org.hibernate.mapping.Join;
import javax.persistence.*;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Item {
@Id
@GeneratedValue
private Long id;
private String name;
private int price;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
</code></pre>
<pre><code>package hellojpa;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class JpaMain {
public static void main(String[] args){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
try{
Movie movie = new Movie();
movie.setDirector("aaaa");
movie.setActor("bbbb");
movie.setName("바람과 함께 사라지다");
movie.setPrice(10000);
tx.commit();
}catch(Exception e){
tx.rollback();
} finally{
em.close();
}
emf.close();
}
}
</code></pre>
<pre><code>package hellojpa;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
@Entity
public class Locker {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToOne(mappedBy = "locker")
private Member member;
}
</code></pre>
<pre><code>package hellojpa;
import net.bytebuddy.dynamic.TypeResolutionStrategy;
import org.hibernate.annotations.Fetch;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Member {
@Id @GeneratedValue
@Column(name = "MEMBER_ID")
private Long id;
@Column(name = "USERNAME")
private String username;
@ManyToOne
@JoinColumn(name = "Team_ID",insertable = false, updatable = false)
private Team team;
@OneToOne
@JoinColumn(name ="LOCKER_ID")
private Locker locker;
@OneToMany(mappedBy = "member")
private List<MemberProduct> memberProducts = new ArrayList<>();
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
public String getUsername() {return username;}
public void setUsername(String username) {this.username = username;}
}
</code></pre>
<pre><code>package hellojpa;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
public class MemberProduct {
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JoinColumn(name="MEMBER_ID")
private Member member;
@ManyToOne
@JoinColumn(name = "PRODUCT_ID")
private Product product;
private int count;
private int price;
private LocalDateTime orderDateTime;
}
</code></pre>
<pre><code>package hellojpa;
import javax.persistence.Entity;
@Entity
public class Movie extends Item{
private String director;
private String actor;
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getActor() {
return actor;
}
public void setActor(String actor) {
this.actor = actor;
}
}
</code></pre>
<pre><code>package hellojpa;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Product {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany (mappedBy = "product")
private List<MemberProduct> memberProducts = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
</code></pre>
<pre><code>package hellojpa;
public enum RoleType {
GUEST, USER, ADMIN
}
</code></pre>
<pre><code>package hellojpa;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Team {
@Id @GeneratedValue
@Column(name = "TEAM_ID")
private Long id;
private String name;
@OneToMany
@JoinColumn(name = "TEAM_ID")
private List<Member> members = new ArrayList<>();
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public List<Member> getMembers() {
return members;
}
public void setMembers(List<Member> members) {
this.members = members;
}
}
</code></pre>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
<persistence-unit name="hello">
<properties>
<!-- 필수 속성 -->
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/~/test"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<!-- 옵션 -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="10"/>
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
</persistence-unit>
</persistence>
</code></pre>
| [
{
"answer_id": 74447809,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": false,
"text": "unique"
},
{
"answer_id": 74448468,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 0,
"selected": false,
"text": "duplicated"
},
{
"answer_id": 74450334,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": true,
"text": "unique()"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20279399/"
] |
74,447,766 | <p>I want to delete part of a text widget's content, using only character offset (or bytes if possible).</p>
<p>I know how to do it for lines, words, etc. Looked around a lot of documentations:</p>
<ul>
<li><a href="https://www.tcl.tk/man/tcl8.6/TkCmd/text.html#M24" rel="nofollow noreferrer">https://www.tcl.tk/man/tcl8.6/TkCmd/text.html#M24</a></li>
<li><a href="https://tkdocs.com/tutorial/text.html" rel="nofollow noreferrer">https://tkdocs.com/tutorial/text.html</a></li>
<li><a href="https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/text-methods.html" rel="nofollow noreferrer">https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/text-methods.html</a></li>
<li><a href="https://web.archive.org/web/20120112185338/http://effbot.org/tkinterbook/text.htm" rel="nofollow noreferrer">https://web.archive.org/web/20120112185338/http://effbot.org/tkinterbook/text.htm</a></li>
</ul>
<p>Here is an example mre:</p>
<pre class="lang-py prettyprint-override"><code>import tkinter as tk
root = tk.Tk()
text = tk.Text(root)
txt = """Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Suspendisse enim lorem, aliquam quis quam sit amet, pharetra porta lectus.
Nam commodo imperdiet sapien, in maximus nibh vestibulum nec.
Quisque rutrum massa eget viverra viverra. Vivamus hendrerit ultricies nibh, ac tincidunt nibh eleifend a. Nulla in dolor consequat, fermentum quam quis, euismod dui.
Nam at gravida nisi. Cras ut varius odio, viverra molestie arcu.
Pellentesque scelerisque eros sit amet sollicitudin venenatis.
Proin fermentum vestibulum risus, quis suscipit velit rutrum id.
Phasellus nisl justo, bibendum non dictum vel, fermentum quis ipsum.
Nunc rutrum nulla quam, ac pretium felis dictum in. Sed ut vestibulum risus, suscipit tempus enim.
Nunc a imperdiet augue.
Nullam iaculis consectetur sodales.
Praesent neque turpis, accumsan ultricies diam in, fermentum semper nibh.
Nullam eget aliquet urna, at interdum odio. Nulla in mi elementum, finibus risus aliquam, sodales ante.
Aenean ut tristique urna, sit amet condimentum quam. Mauris ac mollis nisi.
Proin rhoncus, ex venenatis varius sollicitudin, urna nibh fringilla sapien, eu porttitor felis urna eu mi.
Aliquam aliquam metus non lobortis consequat.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aenean id orci dui."""
text.insert(tk.INSERT, txt)
def test_delete(event=None):
text.delete() # change this line here
text.pack(fill="both", expand=1)
text.pack_propagate(0)
text.bind('<Control-e>', test_delete)
root.mainloop()
</code></pre>
<p>It display an example text inside a variable, inside a text widget. I use a single key binding to test some of the possible ways to do what I want on that piece of text.</p>
<p>I tried a lot of things, both from the documentation(s) and my own desperation:</p>
<ul>
<li><code>text.delete(0.X)</code>: where X is any number. I thought since lines were <code>1.0</code>, maybe using 0.X would work on chars only. It only work with a single char, regardless of what X is (even with a big number).</li>
<li><code>text.delete(1.1, 1.3)</code>: This act on the same line, because I was trying to see if it would delete 3 chars in any direction on the same line. It delete 2 chars instead of 3, and it does so by omitting one char at the start of the first line, and delete 2 char <em>after</em> that.</li>
<li><code>text.delete("end - 9c")</code>: only work at the end (last line), and omit 7 chars starting from EOF, and then delete a single char after that.</li>
<li><code>text.delete(0.1, 0.2)</code>: Does not do anything. Same result for other <code>0.X, 0.X</code> combination.</li>
</ul>
<p>Example of what I try to achieve:</p>
<p>Using the example text above would take too long, so let's consider a smaller string, say "hello world".
Now let's say we use an index that start with 1 (doesn't matter but make things easier to explain), the first char is "h" and the last one is "d". So say I use chars range such as "2-7", that would be "ello w". Say I want to do "1-8"? -> "hello wo", and now starting from the end, "11-2", "ello world".</p>
<p>This is basically similar to what <a href="https://docs.python.org/3/tutorial/inputoutput.html" rel="nofollow noreferrer">f.tell() and f.seek() do</a>. I want to do something like that but using only the content <em>inside</em> of the text widget, and then do something on those bytes/chars ranges (in the example above, I'm deleting them, etc).</p>
| [
{
"answer_id": 74449163,
"author": "Thingamabobs",
"author_id": 13629335,
"author_profile": "https://Stackoverflow.com/users/13629335",
"pm_score": 2,
"selected": false,
"text": "f.seek"
},
{
"answer_id": 74450945,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 3,
"selected": false,
"text": "f.tell()"
},
{
"answer_id": 74461805,
"author": "Nordine Lotfi",
"author_id": 12349101,
"author_profile": "https://Stackoverflow.com/users/12349101",
"pm_score": 2,
"selected": true,
"text": "import tkinter as tk\nfrom tkinter import messagebox # https://stackoverflow.com/a/29780454/12349101\n\nroot = tk.Tk()\n\nmain_text = tk.Text(root)\n\nbox_text = tk.Text(root, height=1, width=10)\nbox_text.pack()\n\ntxt = \"\"\"hello world\"\"\"\n\nlen_txt = len(\n txt) # get the total length of the text content. Can be replaced by `os.path.getsize` or other alternatives for files\n\nmain_text.insert(tk.INSERT, txt)\n\n\ndef offset():\n inputValue = box_text.get(\"1.0\",\n \"end-1c\") # get the input of the text widget without newline (since it's added by default)\n\n # focusing the other text widget, deleting and re-insert the original text so that the selection/tag is updated (no need to move the mouse to the other widget in this example)\n main_text.focus()\n main_text.delete(\"1.0\", tk.END)\n main_text.insert(tk.INSERT, txt)\n\n\n to_do = inputValue.split(\"-\")\n\n if len(to_do) == 1: # if length is 1, it probably is a single offset for a single byte/char\n to_do.append(to_do[0])\n\n if not to_do[0].isdigit() or not to_do[1].isdigit(): # Only integers are supported\n messagebox.showerror(\"error\", \"Only integers are supported\")\n return # trick to prevent the failing range to be executed\n\n if int(to_do[0]) > len_txt or int(to_do[1]) > len_txt: # total length is the maximum range\n messagebox.showerror(\"error\",\n \"One of the integers in the range seems to be bigger than the total length\")\n return # trick to prevent the failing range to be executed\n\n if to_do[0] == \"0\" or to_do[1] == \"0\": # since we don't use a 0 index, this isn't needed\n messagebox.showerror(\"error\", \"Using zero in this range isn't useful\")\n return # trick to prevent the failing range to be executed\n\n if int(to_do[0]) > int(to_do[1]): # This is to support reverse range offset, so 11-2 -> 2-11, etc\n first = int(to_do[1]) - 1\n first = str(first).split(\"-\")[-1:][0]\n\n second = (int(to_do[0]) - len_txt) - 1\n second = str(second).split(\"-\")[-1:][0]\n else: # use the offset range normally\n first = int(to_do[0]) - 1\n first = str(first).split(\"-\")[-1:][0]\n\n second = (int(to_do[1]) - len_txt) - 1\n second = str(second).split(\"-\")[-1:][0]\n\n print(first, second)\n main_text.tag_add(\"sel\", '1.0 + {}c'.format(first), 'end - {}c'.format(second))\n\n\nbuttonCommit = tk.Button(root, text=\"use offset\",\n command=offset)\nbuttonCommit.pack()\nmain_text.pack(fill=\"both\", expand=1)\nmain_text.pack_propagate(0)\nroot.mainloop()\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12349101/"
] |
74,447,778 | <p>I'm currently in the process of migrating our REST application from Spring Boot 2.7.5 to 3.0.0-RC2. I want everything to be secure apart from the Open API URL. In Spring Boot 2.7.5, we used to do this:</p>
<pre class="lang-java prettyprint-override"><code>@Named
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/openapi/openapi.yml").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
</code></pre>
<p>and it worked fine. In Spring Boot 3, I had to change it to</p>
<pre class="lang-java prettyprint-override"><code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((requests) -> requests
.requestMatchers("/openapi/openapi.yml").permitAll()
.anyRequest()
.authenticated())
.httpBasic();
return http.build();
}
}
</code></pre>
<p>since WebSecurityConfigurerAdapter has been removed. It's not working though. The Open API URL is also secured via basic authentication. Have I made a mistake when upgrading the code or is that possibly an issue in Spring Boot 3 RC 2?</p>
<p><strong>Update</strong>
Since most of the new API was already available in 2.7.5, I've updated our code in our 2.7.5 code base to the following:</p>
<pre class="lang-java prettyprint-override"><code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests((requests) -> requests
.antMatchers(OPTIONS).permitAll() // allow CORS option calls for Swagger UI
.antMatchers("/openapi/openapi.yml").permitAll()
.anyRequest().authenticated())
.httpBasic();
return http.build();
}
}
</code></pre>
<p>In our branch for 3.0.0-RC2, the code is now as follows:</p>
<pre class="lang-java prettyprint-override"><code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests((requests) -> requests
.requestMatchers(OPTIONS).permitAll() // allow CORS option calls for Swagger UI
.requestMatchers("/openapi/openapi.yml").permitAll()
.anyRequest().authenticated())
.httpBasic();
return http.build();
}
}
</code></pre>
<p>As you can see, the only difference is that I call requestMatchers instead of antMatchers. This method seems to have been renamed. The method antMatchers is no longer available. The end effect is still the same though. On our branch for 3.0.0-RC2, Spring Boot asks for basic authentication for the OpenAPI URL. Still works fine on 2.7.5.</p>
| [
{
"answer_id": 74448071,
"author": "Julio César Estravis",
"author_id": 20121447,
"author_profile": "https://Stackoverflow.com/users/20121447",
"pm_score": 0,
"selected": false,
"text": "http\n .authorizeExchange((exchanges) ->\n exchanges\n .pathMatchers(\"/openapi/openapi.yml\").permitAll()\n .anyExchange().authenticated())\n .httpBasic();\n\nreturn http.build();\n"
},
{
"answer_id": 74674241,
"author": "Sharofiddin",
"author_id": 5862485,
"author_profile": "https://Stackoverflow.com/users/5862485",
"pm_score": 0,
"selected": false,
"text": " http.securityMatcher(\"<patterns>\")...\n"
},
{
"answer_id": 74674354,
"author": "James Grey",
"author_id": 3728901,
"author_profile": "https://Stackoverflow.com/users/3728901",
"pm_score": 0,
"selected": false,
"text": " @Bean\n public SecurityFilterChain configure(HttpSecurity http) throws Exception {\n http\n .authorizeHttpRequests((requests) -> requests\n .requestMatchers(new AntPathRequestMatcher(\"/openapi/openapi.yml\")).permitAll()\n .anyRequest().authenticated())\n .httpBasic();\n return http.build();\n }\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74447778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5515573/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.