instruction stringlengths 0 30k ⌀ |
|---|
|excel|vba|outlook|hyperlink| |
Note I have my repository `brambor-fork` which is a fork of the official repo `origin`
1. I got this whenever `git fetch`:
```cmd
C:\GitHub\Cataclysm-DDA>git fetch brambor-fork
Auto packing the repository in background for optimum performance.
See "git help gc" for manual housekeeping.
Enumerating objects: 17718, done.
Counting objects: 100% (1818/1818), done.
fatal: unable to read ff4619146ebcafe968cdfcd1689eec7740b68b43
fatal: failed to run repack
error: task 'gc' failed
```
1. I followed [VonC's answer][1]. From testing around I got:
```cmd
C:\GitHub\Cataclysm-DDA>git fsck --name-objects
Checking object directories: 100% (256/256), done.
Checking objects: 100% (754983/754983), done.
Checking connectivity: 755270, done.
broken link from commit 9654131119da18822995291049e541b15b5fb372 (refs/remotes/brambor-fork/gh-pages~7)
to commit ff4619146ebcafe968cdfcd1689eec7740b68b43 (refs/remotes/brambor-fork/gh-pages~8)
```
1. I tried and failed to fetch the commit from `origin`:
```cmd
C:\GitHub\Cataclysm-DDA>git fetch origin ff4619146ebcafe968cdfcd1689eec7740b68b43
remote: Total 0 (delta 0), reused 0 (delta 0), pack-reused 0
fatal: bad object ff4619146ebcafe968cdfcd1689eec7740b68b43
error: https://github.com/CleverRaven/Cataclysm-DDA.git did not send all necessary objects
```
1. Since I didn't need the `brambor-fork/gh-pages` anyway, I simply deleted it
```cmd
C:\GitHub\Cataclysm-DDA>git push brambor-fork -d gh-pages
To https://github.com/Brambor/Cataclysm-DDA.git
- [deleted] gh-pages
```
1. Now `git fetch brambor-fork` works without any errors!
- I got `fatal: Unable to create 'C:/GitHub/Cataclysm-DDA/.git/objects/info/commit-graph.lock': File exists.` but I simply deleted that file and all was fine™.
[1]: https://stackoverflow.com/a/38598015/5057078 |
|architecture|local-storage| |
|javascript|node.js| |
|python|html|bootstrap-4| |
**short answer:** yes, if it's there and active it will be rendered
**long answer:** if there is a material that can be transparent unity don't know if it's 0% transparent or 80% or 100% it will be rendered, if it's completely transparent unity HAVE to render it to know that, it means when unity understand it that it's already too late :)
if you want anything not to render, deactivate it. |
|github|netbeans|repository|git-repo| |
New to coding and getting this error message "Cannot convert value of type 'Tab.Type' to expected argument type 'Binding<Tab>'"
What can I change to fix this? here's my code:
``
enum Tab: String, CaseIterable{
case house
case person
case message
case gearshape
}
struct ContentView: View {
@Binding var selectedTab: Tab
private var fillImage: String {
selectedTab.rawValue + ".fill"
}
var body: some View {
VStack {
HStack {
}
.frame(width: nil, height: 60)
.background(.thinMaterial)
.cornerRadius(10)
.padding()
}
}
}`
`` |
How to correct cannot covert value error? |
|swiftui| |
null |
Im creating my own version of a `MarkDown` render. My goal is to read a string or file line by line then return the `MD` rendered as `HTML`. The problem im facing is my return and line by line functionaility is not-returning what I want and I dont know why. Ive tried debugging but everything seemed fine. Ive also tried chaning my for loop but still no luck.
```js
//function used to render MD for the user
function render(md){
let code = ""; //For functions return
let mdLines = md.split('\n');
for(let i = 0; i < mdLines.length; i++){
//Statements to see what kind of MD header a line is.
//I only have these statments as I just started this and am still figuring how I want to approach.
if(mdLines[i].slice(0, 1) == "#"){
code += code.concat("<h1>" + mdLines[i].replace("#", "") + "</h1>")
}
else if(mdLines[i].slice(0, 2) == "##"){
code += code.concat("<h2>" + mdLines[i].replace("##", "") + "</h2>")
}
else if(mdLines[i].slice(0, 3) == "###"){
code += code.concat("<h3>" + mdLines[i].replace("###", "") + "</h3>")
}
else if(mdLines[i].slice(0, 4) == "####"){
code += code.concat("<h4>" + mdLines[i].replace("#", "") + "</h4>")
}
else if(mdLines[i].slice(0, 5) == "#####"){
code += code.concat("<h5>" + mdLines[i].replace("#", "") + "</h5>")
}
else if(mdLines[i].slice(0, 6) == "######"){
code += code.concat("<h6>" + mdLines[i].replace("######", "") + "</h6>")
}
};
return code;
}
//editor
//This is what the user's .js file would be.
//I have it set up like this for testing.
let text1 = "## he#llo \n there \n# yooo"
let text2 = "# he#llo \n there \n## yooo"
console.log(render(text1));
console.log(render(text2));
```
text1 returns `<h1># he#llo </h1><h1># he#llo </h1><h2> he#llo </h2>`
text2 reutrns `<h1> he#llo </h1>`
text1 should return `<h2>he#llo</h2> there <h1> yooo </h1>`
text2 should return `<h1> he#llo </h1> there <h2> yooo </h2>`
If someone could help me get the proper returns and some potentially reusable code for this issue it would be greatly appreciated.
Ive also looked up the issue with some select terms but it seems no one has documented my very specific issue.
## Follow Up
I originally had it as multiple `if` statements but changed it to `else if` to not make it a duplicate.
I would also like to shorten this code and not use multiple `else if` statements if possible. My theories would be regEX or `case`
***NOTE*** if you were looking to render MD without coding your own render there are many librays to help you do that.
Renders: https://byby.dev/js-markdown-libs
|
CGAL K-D trees - How do I associate information to a point when range searching? |
|c++|boost|cgal| |
null |
How to route traffic between overlapping subnets on GCP from different projects/VPCs |
You can define those links as `inline-block`s, then they won't be split/broken like regular text. For this, add the following rule:
a.work,
a.podcast,
a.speak {
display: inline-block;
}
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
a.work,
a.podcast,
a.speak {
display: inline-block;
}
a.work {
background-color: #b7ad68;
font-size: .5em;
font-family: "helvetica", san-serif;
letter-spacing: 2px;
font-weight: 500;
padding: 10px 20px 10px 20px;
border-radius: 50px;
color: white;
}
a:hover.work {
background-color: #ffffff;
border: solid 2px #b7ad68;
color: #b7ad68;
}
a.podcast {
background-color: #f1b36e;
font-size: .5em;
font-family: "helvetica", san-serif;
letter-spacing: 2px;
font-weight: 500;
padding: 10px 20px 10px 20px;
border-radius: 50px;
color: white;
}
a:hover.podcast {
background-color: #ffffff;
border: solid 2px #f1b36e;
color: #f1b36e;
}
a.speak {
background-color: #e58059;
font-size: .5em;
font-family: "helvetica", san-serif;
letter-spacing: 2px;
font-weight: 500;
padding: 10px 20px 10px 20px;
border-radius: 50px;
color: white;
}
a:hover.speak {
background-color: #ffffff;
border: solid 2px #e58059;
color: #e58059;
}
<!-- language: lang-html -->
<p style="text-align: center;">
<a class="work" href="/work-with-me">
<span style="font-family: ETmodules; font-size: 1.5em; font-weight: 300; padding-top: 10px; position: relative; top: .15em;"></span> WORK WITH ME</a> <a class="podcast" href="/work-with-me"><span style="font-family: ETmodules; font-size: 1.5em; font-weight: 300; position: relative; top: .15em;"></span> PODCAST</a>
<a
class="speak"><span style="font-family: ETmodules; font-size: 1.5em; font-weight: 300;position: relative; top: .15em;"></span> SPEAKING</a>
</p>
<!-- end snippet -->
|
im working on a custom "Library" of sorts in vba, because otherwise i would program it over and over again. For example an Errorhandler or standard stuff like swap, sort or pathfinding algorithms. For better highlighting i do the writing in VSCode and just copy paste it into VBA. After some time this became tedious so i got XVBA, which helps significantly. I have ordered my files in folders, which correspond to a Module in VBA and the files are the Subprocedures. Using XVBA i havent found a way how i can create 1 Module (The Foldername) to put in all Subprocedures (Files)?
I would like to prefer to keep the files seperated for better overview and not merge them into one big .bas / .frm / .cls file. I would also prefer to not have so many modules for the same reason. |
Organize files in folders corresponding to subs in a module in vba |
on my wordpress site using an external cookie service, they provide me with a script to insert into the head tag
```
<script src='https://acconsento.click/script.js' id='acconsento-script' data-key='dBLtIvrsCoonhdR1zC1boEzG4YVBO1ebja0gFyOW'></script>
```
The problem is that a popup should appear to accept cookies, but this does not happen.
In the browser console I saw the following error message:Failed to load resource: the server responded with a status of 403 ()
Even on the network you can see a blocked request, I'll attach all the screens, to see for yourself the link is [caseigerolalogisticspark.com](https://caseigerolalogisticspark.com/)
By inspecting any page you can see the error message[enter image description here](https://i.stack.imgur.com/1rGuX.png)[enter image description here](https://i.stack.imgur.com/ZZBIP.png)
I insert the HT access file here, but it should be the standard WP one
I thought it was an error with my Godaddy hosting provider, something related to DNS pointing or you have a firewall, but they say that everything is ok and that nothing is blocking the request.
What do you recommend me to do? |
Failed to load resource: the server responded with a status of 403 () - SCRIPT - WordPress |
|javascript|ajax|wordpress|api| |
null |
The problem of not having "Search State Persistence" arises because adminUserList.php is apparently initially posted to thus you use $_POST to get the params, but then your generated pagination are just anchor tags, where you'd need to use $_GET to get at the params, which you dont have.
There are at least two ways to correct the issue:
(1) Modify your page that initially posts to adminUserList and make it pass the params on the url itself. Then in adminUserList.php change each $_POST to $_GET.
(2) The 2nd way is to modify adminUserList.php so that it can handle both post and get type params.
|
Here's a fully reproducible PoC of the problem, posted on Compiler Explorer: https://godbolt.org/z/x78Ksro88.
I'm encountering the following problem: the compiler is reporting an error because it cannot convert argument 2 (in the `search_in` function) from type `T` to the actual type in a situation where `T` represents a template type.
template <typename T>
void analyze(vegtable& type, const std::vector<std::uint8_t>& dee, T& pee, int ole, std::uint16_t cee)
{
switch (type)
{
case type::banana:
beta::search_in(dee, pee, ole, cee);
break;
case type::orange:
gemma::search_in(dee, pee, ole, cee);
break;
case type::lemon:
zeta::search_in(dee, pee, ole, cee);
break;
default:
break;
}
}
`vegetable` is a typed class enum of type `std::uint8_t`.
I call the analyze function as follows (`sample` is of type `potato`):
analyze<potato>(organic, data, sample, 12);
where some of the types are defined as follows, for example:
vegetable organic;
organic = vegetable::banana;
struct potato
{
int x;
int y;
int z;
};
potato sample;
If I delete the function calls for the switch cases `type::orange:` and `type::lemon:`, the code compiles and works as expected, but if I leave the analyze function as shown, the compiler throws the error stated in the prologue of this question. This is a weird behaviour!
Note: there are other types too that I pass with the `T` argument other than the `potato` type, as shown in the PoC.
I can guarantee at the time of calling the `analyze` function, that the `T` type passed to each of the cases through the `search_in` function call is of the correct type. It seems that the compiler is not able to figure it out! |
Before the `dir` change is made, get all the `.drawer-side` elements and hide them from view:
```js
const drawers = document.querySelectorAll('.drawer-side');
drawers.forEach(drawer => {
drawer.style.display = 'none';
});
```
Make the `dir` change, then wait one render frame before resetting the style. This is so that CSS transitions don't play:
```js
requestAnimationFrame(() => {
drawers.forEach(drawer => {
drawer.style.display = '';
});
});
```
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-js -->
// Function to switch the HTML direction
function switchDir() {
let page = document.getElementsByTagName('html')[0];
const drawers = document.querySelectorAll('.drawer-side');
drawers.forEach(drawer => {
drawer.style.display = 'none';
});
if (page.dir == 'rtl') {
page.dir = 'ltr';
} else {
page.dir = 'rtl';
}
requestAnimationFrame(() => {
drawers.forEach(drawer => {
drawer.style.display = '';
});
});
};
<!-- language: lang-html -->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/daisyui@4.6.1/dist/full.min.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<label id="lng" class="btn btn-primary drawer-button m-1" onclick="switchDir()">Switch Html Dir</label>
<div class="drawer">
<input id="my-drawer" type="checkbox" class="drawer-toggle" />
<div class="drawer-content">
<!-- Page content here -->
<label for="my-drawer" class="btn btn-primary drawer-button m-1">Open drawer</label>
</div>
<div class="drawer-side">
<label for="my-drawer" aria-label="close sidebar" class="drawer-overlay"></label>
<ul class="menu p-4 w-80 min-h-full bg-base-200 text-base-content">
<!-- Sidebar content here -->
<li><a>Sidebar Item 1</a></li>
<li><a>Sidebar Item 2</a></li>
</ul>
</div>
</div>
</body>
<!-- end snippet -->
|
I have this markup:
```
<div className="wrapper w-full h-full flex flex-col justify-between my-7">
{/*first*/}
<div className="w-full h-full min-h-0 outline-dotted outline-green-300 outline-2 p-7 bg-black overflow-y-auto whitespace-break-spaces text-nowrap">
{data.text}
</div>
{/*second*/}
<div
className="w-full h-16 mt-5 outline-dotted outline-green-300 outline-2 p-3 bg-black flex justify-between items-center">
<span className="text-lg font-bold">From: <span className="bg-gray-900 p-1">01/01/2024</span></span>
<span className="text-lg font-bold">Due: <span className="bg-gray-900 p-1">05/02/2024</span></span>
</div>
</div>
```
It's parent:
```
<main className="flex flex-col w-full h-full">
<div className="flex justify-between align-middle items-center h-header w-full border-b border-gray-500">
<span className="font-bold text-2xl">Display</span>
<CreateEditModalCallerButton buttonClassName="flex items-center justify-center p-2 hover:bg-opacity-15 hover:bg-black" mode="CREATE">
<Image className="mr-2 w-6 h-6" src="/assets/plus-solid.svg" alt="pic" width="16" height="16"/>
<span className="min-md:text-sm max-md:text-base">Add</span>
</CreateEditModalCallerButton>
</div>
<div className="grid grid-rows-1 grid-cols-2 w-full h-full divide-x-2 divide-gray-600 px-7">
<div className="flex flex-col w-full h-full max-sm:col-span-2 pr-7">
<HometaskList initialData={initialHometasks}/>
</div>
<div className="flex flex-col w-full h-full pl-7 max-sm:hidden">
<HometaskInfo/>
</div>
</div>
</main>
```
And root layout:
```
<html lang="en">
<body className={`${font.className} w-screen h-screen flex max-md:flex-col`}>
<StoreProvider>
<Nav />
<div className="root_content w-full h-screen">
{children}
</div>
</StoreProvider>
</body>
</html>
```
There are two `div`s in a flex wrapper. First one is supposed to contain a long multiline text, so I use `overflow-y-auto` to add vertical scroll when needed. This block should take all space left after placing second `div`.
The problem is that when resizing the window, first block begins to shrink freely only after bottom edge of the window meets it's border. Also, it shrinks a little bit if it has free space between bottom border and text including it's padding.
Perhaps you can better understand my problem by watching [this GIF](https://i.imgur.com/iT6Hg3i.gif).
I tried using `flex-shrink` and `flex-grow` but neither solved this problem. I also tried doing like [in the answer for this question](https://stackoverflow.com/questions/15955178/how-to-start-shrinking-sibling-div-when-there-is-not-enough-space), but it stops shrinking at all.
The thing I want to achieve is to make first (large) div shrink and become scrollable when there is not enough space for **other children** left inside the flexbox. How can I do this? If possible, I would like to do it with Tailwind, but using standard CSS is not a problem. I would also like to know why this is happening even though first `div` has `h-full`.
Any advice is appreciated. |
|sql|mysql| |
Pls try.
```vb
Option Explicit
Sub AlphaCites()
Application.ScreenUpdating = False
Dim ArrTxt() As String, i As Long, j As Long
Dim aTxt As Variant
With ActiveDocument.Content
With .Find
.ClearFormatting
.Text = "\([!\(]@\)"
.Format = False
.Forward = True
.MatchWildcards = True
.Wrap = wdFindStop
End With
Do While .Find.Execute
If InStr(.Text, "; ") > 0 Then
.Start = .Start + 1
.End = .End - 1
aTxt = Split(.Text, "; ")
ReDim ArrTxt(UBound(aTxt))
For j = 0 To UBound(aTxt)
ArrTxt(j) = aTxt(j)
Next j
WordBasic.SortArray ArrTxt()
.Text = Join(ArrTxt(), "; ")
End If
.Collapse wdCollapseEnd
DoEvents
Loop
End With
Application.ScreenUpdating = True
End Sub
```
|
If you're writing something that does "the same thing, with just one thing changing at each step", that's a loop. You don't use separate `if` statements. Not even when, as you say, "you're being lazy": being lazy is an _excellent_ trait to have when you're a programmer, because it means you want to do as little work as possible for the maximum result. Of course, in this case that means "why am I even doing this, [`npm install marked`](https://www.npmjs.com/package/marked), my work here is done", but even if you insist on implementing a markdown parser yourself (because sometimes you just want to write code to see if you can do it) you don't use a sequence of `if` statements because it takes more time to write, and will take more time to fix or update (as you discovered).
That said, even if you _do_ use `if` statements, resolve them either such that you handle "the largest thing first", to ensure there's no fall-through, _or_ with if-else statements, so there's no fall-though. (And based on your question about whether to use a switch: you almost never want switches in JS. The switch statement is a hold-over from programming languages that didn't have dictionaries/key-value objects to perform O(1) lookups with, which JS, Pything, etc. all do. So in JS you're almost _always_ better off using a mapping object with your case values as property keys, turning an O(n) code path with a switch into an O(1) immediate lookup)
However, you don't need any of this, because what you're really doing is simple text matching, so you can use the best tool in the toolset for that: you can trivially get both the `#` sequence and "remaining text" with a regex, and then generate the replacement HTML [using the captured data](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#replacement):
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function markdownToHTML(doc) {
return convertMultiLineMD(doc.split(`\n`)).join(`\n`);
}
function convertMultiLineMD(lines) {
// convert tables, lists, etc, while also making sure
// to perform inline markup conversion for any content
// that doesn't span multiple lines. For the purpose of
// this answer, we're going to ignore multi-line entirely:
return convertInlineMD(lines);
}
function convertInlineMD(lines) {
return lines.map((line) => {
// convert headings
line = line.replace(
// two capture groups, one for the markup, and one for the heading,
// with a third optional group so we don't capture EOL whitespace.
/^(#+)\s+(.+?)(\s+)?$/,
// and we extract the first group's length immediately
(_, { length: h }, text) => `<h${h}>${text}</h${h}>`
);
// then wrap bare text in <p>, convert bold, italic, etc. etc.
return line;
});
}
// And a simple test based on what you indicated:
const docs = [`## he#llo\nthere\n# yooo `, `# he#llo\nthere\n## yooo`];
docs.forEach((doc, i) => console.log(`[doc ${i + 1}]\n`, markdownToHTML(doc)));
<!-- end snippet -->
However, this is also a naive approach to writing a transpiler, and will have rather poor runtime performance compared to writing [a stack parser](https://spec.commonmark.org/0.31.2/#appendix-a-parsing-strategy) or [a DFA](https://en.wikipedia.org/wiki/Deterministic_finite_automaton) based on the markdown grammar (the "markup language specification" grammar, i.e. the rules that say which tokens can follow which other tokens), where you run through your document by tracking what kind of token we're dealing with, and convert on the fly as we pass token terminations.
(This is, in fact, how regular expressions work: they generate a DFA from the [regular grammar](https://en.wikipedia.org/wiki/Regular_grammar) pattern you specify, then run the input through that DFA, achieving near-perfect runtime performance)
Explaining how to get started with stack parsing or DFAs is of course wildly beyond the scope of this answer, but absolutely worth digging into if you're doing this "just to see if you can": anyone can write code "that works" but is extremely inefficient, so that's not an exercise that's going to improve your skill as a programmer. |
Add them to `config.json`, then append the `.ts` extension after every import.
```json
{
"noEmit": true,
"allowImportingTsExtensions": true
}
``` |
how i can move element of dynamic vector in argument of function push_back for dynamic vector. Probably, i’ve said something and it isn’t right. Sorry, but i don't know English so good…
```
vector<int> *ans = new vector<int>();
vector<int> *x = new vector<int>();
ans->push_back(x[i]);
``` |
On the app router, you should use version 5 of `next auth` which is currently in beta. I will show you step-by-step to how migrate your code to V5.
##### Step 1: Update next-auth dependency
```bash
npm install next-auth@5.0.0-beta.16
```
##### Step 2: Change the code in the `route.js` file
###### util/auth.js
```js
import NextAuth from 'next-auth'
import Credentials from 'next-auth/providers/credentials'
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
export const authConfig = {
providers: [
Credentials({
name: 'Credentials',
credentials: {
username: { label: 'username', type: 'text' },
password: { label: 'password', type: 'password' }
},
async authorize(credentials) {
// const { username, password } = credentials;
// mocking API request (doesn't work, just refreshes immediately)
await delay(3000);
try {
return { user: "Shiawase" };
} catch (error) {
throw new Error('Failed to authenticate user');
}
},
})
],
pages: {
signIn: '/auth/login'
}
}
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth(authConfig);
```
###### app/api/auth/[...nextauth]/route.js
```js
export { GET, POST } from "../../../../util/auth.js";
```
##### Step 3: SignIn the user
Keep in mind that the `signIn`, `signOut` and `auth` functions should run on the server side and NOT in client. You can put `signIn` and `signOut` in the server actions to use them:
```js
import { auth, signIn } from "util/auth.js"
export const MyServerComponent = async () => {
const session = await auth();
if(session) {
redirect("/");
}
return (
<div>
<button
formAction={async () => {
"use server";
await signIn("Credentials");
}}
>
Sign In
</button>
</div>
);
}
``` |
|excel|vba| |
null |
{"OriginalQuestionIds":[4260280],"Voters":[{"Id":523612,"DisplayName":"Karl Knechtel","BindingReason":{"GoldTagBadge":"python"}}]} |
If java code doesn't mark a parameter as Nullable or NotNull, then it has a so called platform type in kotlin, meaning we can use it as both Nullable and Not Nullable, putting or omitting a question mark at the end of the parameter type respectively.
For example, i have a java class:
```
public class Main{
public void hi(String[] string){
}
}
```
and a kotlin class:
```
class A: Main(){
override fun hi(string: Array<String?>?){
super.hi(null)
}
}
```
The kotlin class perfectly gets compiled.
So i was trying to override one of the methods in Android sdk. It is defined in a java class and looks like the following:
```
@UnstableApi
public class DefaultLoadControl implements LoadControl {
...
@Override
public void onTracksSelected(
Timeline timeline,
MediaPeriodId mediaPeriodId,
Renderer[] renderers,
TrackGroupArray trackGroups,
ExoTrackSelection[] trackSelections) {
targetBufferBytes =
targetBufferBytesOverwrite == C.LENGTH_UNSET
? calculateTargetBufferBytes(renderers, trackSelections)
: targetBufferBytesOverwrite;
allocator.setTargetBufferSize(targetBufferBytes);
}
...
}
```
I did the next thing expecting that everything will be alright:
```
@UnstableApi
class OwnLoadControl:DefaultLoadControl() {
override fun onTracksSelected(
timeline: Timeline,
mediaPeriodId: MediaSource.MediaPeriodId,
renderers: Array<out Renderer>,
trackGroups: TrackGroupArray,
trackSelections: Array<ExoTrackSelection?>?
) {
super.onTracksSelected(timeline, mediaPeriodId, renderers, trackGroups, null)
}
}
```
But i get this:
[![enter image description here][1]][1]
[![enter image description here][2]][2]
For some reason the last parameter is seen as non-null type instead of a platform one, despite it comes from a typical java class. Why ?
**UPD:**
I've got an answer in the comments: "Nullability annotations are not the only way of marking nullability for Kotlin inter-op. They can be defined in a separate file.".
Can someone show me an example of this ?
[1]: https://i.stack.imgur.com/6vD01.png
[2]: https://i.stack.imgur.com/pPm4A.png |
{"Voters":[{"Id":893254,"DisplayName":"FreelanceConsultant"},{"Id":2511795,"DisplayName":"0andriy"},{"Id":9214357,"DisplayName":"Zephyr"}],"SiteSpecificCloseReasonIds":[18]} |
I was able to fix this by deleting cookies between page loads:
```r
url <- "https://investors.alvotech.com/news-events/news-releases?page=1"
remDr$navigate(url)
remDr$deleteAllCookies()
url <- "https://investors.alvotech.com/news-events/news-releases?page=2"
remDr$navigate(url)
```
I have no idea why I need to delete cookies. I don't have to do this if I'm navigating to google searches, but if I am doing pagination on many different websites I had to do it.
If someone can come up with a more complete answer, please let me know. I'm really curious why I had to delete cookies. |
This is similar to @Arnav solution, but cleaned a bit.
The idea is to iterate over array preparing resulting array `res` and test each element. If item is not found by `id` in resulting array - we add it. If item with the same `id` already in resulting array we then check if it has greater `quantity`, if so - we replace the _whole_ item in resulting array, that suits for complex items with many properties.
```
const res = [];
arr.forEach(it => {
const i = res.findIndex(v => v.id === it.id)
if (i === -1) res.push(it)
else if (res[i].quantity < it.quantity) res[i] = it
})
``` |
First of all [`EF.Functions.Like`][1] accepts only strings for the `matchExpression` parameter so you can't work with anything but that, so your method signature should reflect that:
```
public static IQueryable<TSource> WhereLike<TSource>(
this IQueryable<TSource> source,
Expression<Func<TSource, string>> expression, // selector should return the string
string[] words)
```
You need to correctly build the expression tree.
Possibly the easiest approach would be to try to utilize library like [LINQKit][2] and it's `AsExpandable`:
```c#
return source.AsExpandable()
.Where(x => words.Any(w => EF.Functions.Like(expression.Invoke(x), "%" + w + "%")));
```
But you can try to build needed expressions manually. Something along these lines:
```csharp
// to save some reflection manipulations
Expression<Func<string, string, bool>> efLikeSource = (o, s) => EF.Functions.Like(o, "%" + s + "%");
Expression<Func<TSource, bool>> wordsAny = x => words.Any(word => true);
var wordsAnyBody = wordsAny.Body as MethodCallExpression;
var efLikeBody = new ReplacingExpressionVisitor(new[] { efLikeSource.Parameters[0] }, new[] { expression.Body }).Visit(efLikeSource.Body);
var efLikeLambda = Expression.Lambda<Func<string, bool>>(efLikeBody, efLikeSource.Parameters[1]);
var wordsAnyNewBody = Expression.Call(wordsAnyBody.Method, wordsAnyBody.Arguments.First(), efLikeLambda);
var result = Expression.Lambda<Func<TSource, bool>>(wordsAnyNewBody, expression.Parameters);
return source.Where(result);
```
[1]: https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbfunctionsextensions.like?view=efcore-8.0
[2]: https://github.com/scottksmith95/LINQKit |
I need to write a function that sorts this array based on dialog_node key and previous_sibling keys. The previous_sibling of the next object matches the dialog_node value of the previous object in the array.
```
export function orderDialogNodes(nodes) {
// Create a mapping of dialog_node to its corresponding index in the array
const nodeIndexMap = {};
nodes.forEach((node, index) => {
nodeIndexMap[node.dialog_node] = index;
});
// Sort the array based on the previous_sibling property
nodes.sort((a, b) => {
const indexA = nodeIndexMap[a.previous_sibling];
const indexB = nodeIndexMap[b.previous_sibling];
return indexA - indexB;
});
return nodes;
}
const inputArray = [
{
type: "folder",
dialog_node: "node_3_1702794877277",
previous_sibling: "node_2_1702794723026",
}, {
type: "folder",
dialog_node: "node_2_1702794723026",
previous_sibling: "node_9_1702956631016",
},
{
type: "folder",
dialog_node: "node_9_1702956631016",
previous_sibling: "node_7_1702794902054",
},
];
const orderedArray = orderDialogNodes(inputArray);
console.log(orderedArray);
```
|
I have HTML table with following structure:
```
<table>
<thead>..</thead>
<tbody>
<tr>
<td>some</td>
<td>content</td>
<td>etc</td>
</tr>
<tr class="certain">
<td><div class="that-one"></div>some</td>
<td>content</td>
<td>etc</td>
</tr>
several other rows..
<tbody>
</table>
```
And I am trying to figure out what to do with the `<div class="that-one">` (or any other element, if needed) inside the table so it can be painted outside the table.
I have tried negative left property, transform: translateX(-20px) and overflow: visible.
I know that there is something different with rendering HTML tables. I cannot change structure of the table just can add whetever element inside.
Finding: both negative left property and transform: translateX(-20px) work in Firefox but dont work in Chrome (behaves like overflow: hidden).
Have some Javascript workaround on my mind, but would rather stay without it.
Also, I dont want it as CSS pseudoelement, because there will be some click event binded. |
I have an element in my HTML like this (inspiration from [this blog](https://www.digitalocean.com/community/tutorials/angular-viewchild-access-component)). While the user types, I'm showing successive filtrations in a list to pick from. Once the user clicks on that component, I want to update the value typed in the search box below and replace it with the full name available in the clicked item.
<input #userSelector (keyup)="onKeyUpUser($event)">
In order to communicate easily, I have set up a view child as shown below. Then, in the handler of the click, I set the value picked.
@ViewChild("userSelector") userSelector: ElementRef;
...
onClickUser(user: User) {
this.userSelector.nativeElement.value = user.name;
...
}
This works as expected. Now, I wanted to be clever and realized that the view child is not only a general `ElementRef` but, in fact, `HTMLInputElement`, so I replaced the code like this.
@ViewChild("userSelector") userSelector: HTMLInputElement;
...
onClickUser(user: User) {
this.userSelector.value = user.name;
...
}
To my surprise, it doesn't update the contents visible on the screen. In the console, I can see that the field `value` has appeared and has the value I assigned. But it won't show. It's the same element, so I'm confused why this happens.
What's the reason this occurs and (how) can I use the more specific type of the view child (hence allowing to avoid the detour through `nativeElement` to get to the value field? |
```
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<!--<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
background-color: #373737 !important;
}
.modal-container {
position: relative !important;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: #373737;
z-index: 10;
display: none;
align-items: center;
justify-content: center;
}
.modal-dialog {
margin: 20px auto 0;
width: 100% !important;
height: 100% !important;
display: flex;
align-items: center;
justify-content: center;
}
.modal-content {
align-self: center;
background-color: transparent;
border: none;
margin: 0;
position: absolute !important;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.modal-body-container {
width: 80%;
max-height: 80vh;
background-color: black;
display: flex;
justify-content: center; /* Center horizontally */
border-radius: 10px;
overflow: hidden;
}
.modal-body img {
max-width: 100%;
max-height: 100%;
height: auto;
width: auto;
margin: 0 auto;
display: block;
border-radius: 10px;
}
.btn-primary {
background-color: #ffc107;
border-color: #ffc107;
color: #000;
padding: 10px 20px;
border-radius: 5px;
margin-right: 10px;
border-bottom: none;
text-decoration: none;
}
.btn-primary:hover,
.btn-primary:focus {
background-color: #ffcd38;
border-color: #ffcd38;
color: #000;
}
body.modal-open {
overflow: visible;
position: relative;
}
.btn-secondary {
background-color: #007bff;
border-color: #007bff;
color: #fff;
padding: 10px 20px;
border-radius: 5px;
}
.btn-secondary:hover,
.btn-secondary:focus {
background-color: #0056b3;
border-color: #0056b3;
color: #fff;
}
.modal-footer {
align-self: center;
text-align: left;
border-top: none;
}
.modal-footer .btn {
margin-right: 10px;
}
}
</style>
</head>
<body>
<!-- Your existing gallery code here -->
<!-- Container for modal background -->
<div class="modal-container">
<!-- Modal HTML -->
<div id="imageModal" class="modal fade" tabindex="-1" role="dialog">
<div class=" d-flex flex-column modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body-container">
<img id="modalImage" src="" class="img-fluid">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<a id="downloadLink" href="javascript" download="image" class="btn btn-primary">Download</a>
</div>
</div>
</div>
</div>
</div>
<!-- Your existing script code here -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
jQuery(document).ready(function($) {
$('.elementor-gallery-item').each(function() {
$(this).on('click', function(e) {
e.preventDefault();
var imageUrl = $(this).attr('href');
$('#modalImage').attr('src', imageUrl);
$('#downloadLink').attr('href', imageUrl);
var imagePosition = $(this).offset();
var imageTop = imagePosition.top;
var imageLeft = imagePosition.left;
$('#modalImage').css({
'top': imageTop + 'px',
'left': imageLeft + 'px'
});
$('#imageModal').modal('show');
$('.modal-container').show(); // Show the modal background container
// window.scrollTo(0, 0);
});
});
// Close the modal and hide the background container
$('#imageModal').on('hidden.bs.modal', function (e) {
$('.modal-container').hide();
});
});
jQuery(document).ready(function($) {
// Your existing script code
// Adjust z-index dynamically when modal is shown
$('#imageModal').on('shown.bs.modal', function() {
// Ensure backdrop and modal are siblings
$(this).before($('.modal-backdrop'));
// Set z-index of modal greater than backdrop
$(this).css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 1);
});
});
</script>
</body>
</html>
```
this is working fine on the desktop size screen but when the screen size is smaller than 768px and I click in any Image the Modal shows in the centre of the screen
You can see this behaviour by opening [\[tweakball\](www.tweakball.com)][1] all wallpapers navgation on mobile screen
I want the modal to be shown exactly at that point of website where the image is clicked
kindly help
[1]: https://tweakball.com |
I have a program that gets requests (an array of strings of size `n`) from different domains (each input value is called as a domain) for each second `i`.
Within 5 seconds for a given domain the program should accept at most 2 successful requests.
Also at most 5 successful requests in 30 seconds.
For each request the program should return either "success" if accepted or "error" if not accepted.
**Example:**
n = 9, requests = ["xyz", "abc", "xyz", "pqr", "abc", "xyz", "xyz", "abc", "xyz"]
Result =
["success", "success", "success", "success", "success", "success", "error", "success", "success"]
**Explanation:**
domain xyz occurs at indices = [0,2,5,6,8]
domain abc = [1,4,7]
domain pqr = [3]
If we pick index 6, if we pick 5 seconds range there are 2 successful requests at 2 and 5, so we get an error response at index 6.
Remaining cases we get success response.
**Constraints**
n range is 1 to 10^4
input string contains lowercase English letters.
Here is what I tried:
public static List<String> solve(List<String> requests) {
List<String> result = new ArrayList<>();
Map<String, List<Integer>> map = new HashMap<>();
int n = requests.size();
for(int i=0; i<n; i++) {
String s = requests.get(i);
int time = i;
// remove items older than 30 seconds
while(!map.getOrDefault(s, new ArrayList<>()).isEmpty() && time - map.get(s).get(0) >= 30) {
map.get(s).remove(0);
}
// remove items older than 5 seconds
while(!map.getOrDefault(s, new ArrayList<>()).isEmpty() && time - map.get(s).get(0) >= 5) {
map.get(s).remove(0);
}
//check if we have 2 successful requests for given domain
if(map.getOrDefault(s, new ArrayList<>()).size() >= 2) {
map.get(s).remove(0);
result.add("error");
} else {
result.add("success");
map.computeIfAbsent(s, k-> new ArrayList<>()).add(time);
}
}
return result;
}
When I tried to solve it my program fails saying wrong output for many test cases. What is the correct approach to solve this problem. |
Cannot convert template argument to the actual type being passed |
|c++|templates| |
Thank you for your answer.
I investigated and it came from the linear network (lpp2). I cleaned
- the raw data (topology and short segments),
- rebuilt ways (using Morpheo plug-in in QGIS)
- mafa_geom_to_segment: https://jgravier.github.io/mafa/reference/mafa_geom_to_segment.html
- st_cast function
Then it worked.
Note: I used explode lines from QGIS processings and it was not working whereas the number of segments was identical.
Most of the "inf" distances were corrected then.
|
I want to use Clean Architecture for a simple game in Flutter.
The game consists of a timer and a few fields that can be clicked.
I am trying to keep the game logic inside the domain layer.
So far I have the two UseCases `StartGameUseCase` and `SelectFieldUseCase`.
The `StartGameUseCase` has a timer property and starts this timer.
It also prepares the fields and returns a `List<Fields>`.
When I tap on a `Field` I want some logic to be executed inside the `SelectFieldUseCase`.
Then I want my UI to be notified (or my Bloc which then notifies the UI) about the changes.
In addition to that the UI should also be notified when the timer ends.
So the `SelectFieldUseCase` and the timer in the `StartGameUseCase` should update the state of the `Field` and then transmit this state change to the Bloc.
1. What is the "Clean Architecture Way" to implement game logic like this?
2. How can I establish a communication way from the UseCases to a Bloc?
3. Is Clean Architecture maybe the wrong way to implement games like this and is there a better pattern / way that fits in well in a clean architecture app?
So far I tried implementing a Stream which gets returned by the `StartGameUseCase` and then is listened to by the Bloc but that doesn't seem like a clean solution.
```
class StartGameUseCase {
final GameRepository _gameRepository;
Timer _timer;
StartGameUseCase({
required GameRepository gameRepository,
required Timer timer,
}) : _gameRepository = gameRepository,
_timer = timer;
Future<Stream<List<Field>>> call(NoParams params) async {
// Get the Fields from the repository
List<Fields> fields = _gameRepository.getFields();
// Start the timer
final gameDuration = Duration(seconds: 60);
_timer = Timer(gameDuration, () {});
// Generate the game state stream
return _generateGameStateStream(fields);
}
Stream<List<Fields>> _generateGameStateStream(List<Fields> fields) async* {
while (_timer.isActive) {
await Future.delayed(const Duration(milliseconds: 10));
// Generate the fields
List<Fields> fields = _gameRepository.getFields();
yield fields;
}
// Timer finished
yield [];
}
}
``` |
Flutter Clean Architecture communication between Use Cases and Blocs |
|flutter|dart|bloc|clean-architecture| |
null |
OK, turns out to have a simple solution: I created an additional function that is wrapped with the cache decorator, and changed the handle function to call it:
```
create or replace function get_key(which varchar) returns varchar
language python runtime_version = '3.11'
packages = ('snowflake-snowpark-python')
handler = 'main'
AS $$
import functools
@functools.cache
def get_key(which):
if which == 'PN':
return 'toomanysecrets'
else:
return ''
def main(which):
return get_key(which)
$$;
``` |
I was trying to code a bot with Discord.JS V14 since i always coded with the v12 and i watched the documentation and a few tutorials and i watched two. One for the clear command and the other for the ban and unban command, the clear command is showing and its totally functional when i type "/" and clear but when i wanna put /ban or /unban it doesnt show anything, my console doesnt shows any error
here is my code, some things are in spansish cuz im spanish but i can translate them if anyone need.
index:
```
const Discord = require('discord.js');
const configuracion = require('./config.json')
const cliente = new Discord.Client({
intents: [
Discord.GatewayIntentBits.Guilds
]
});
module.exports = cliente
cliente.on('interactionCreate', (interaction) => {
if(interaction.type === Discord.InteractionType.ApplicationCommand){
const cmd = cliente.slashCommands.get(interaction.commandName);
if(!cmd) return interaction.reply(`Error`);
interaction["member"] = interaction.guild.members.cache.get(interaction.user.id);
cmd.run(cliente, interaction)
}
})
cliente.on('ready', () => {
console.log(` Sesión iniciada como ${cliente.user.username}`)
})
cliente.slashCommands = new Discord.Collection()
require('./handler')(cliente)
cliente.login(configuracion.token)
```
index/handler
```
const fs = require('fs');
const Discord = require('discord.js');
module.exports = async (client) => {
const SlashArray = [];
fs.readdir('./Comandos', (error, folder) => {
if (error) {
console.error('Error al leer el directorio:', error);
return;
}
if (!folder || folder.length === 0) {
console.error('No se encontraron carpetas en el directorio.');
return;
}
folder.forEach(subfolder => {
fs.readdir(`./Comandos/${subfolder}/`, (error, files) => {
if (error) {
console.error('Error al leer archivos en la carpeta:', error);
return;
}
files.forEach(file => {
if (!file.endsWith('.js')) return;
const filePath = `../Comandos/${subfolder}/${file}`;
const command = require(filePath);
if (!command.name) return;
client.slashCommands.set(command.name, command);
SlashArray.push(command);
});
});
});
});
client.on('ready', async () => {
client.guilds.cache.forEach(guild => guild.commands.set(SlashArray));
});
};
```
clear cmd
```
const fs = require('fs');
const Discord = require('discord.js');
module.exports = async (client) => {
const SlashArray = [];
fs.readdir('./Comandos', (error, folder) => {
if (error) {
console.error('Error al leer el directorio:', error);
return;
}
if (!folder || folder.length === 0) {
console.error('No se encontraron carpetas en el directorio.');
return;
}
folder.forEach(subfolder => {
fs.readdir(`./Comandos/${subfolder}/`, (error, files) => {
if (error) {
console.error('Error al leer archivos en la carpeta:', error);
return;
}
files.forEach(file => {
if (!file.endsWith('.js')) return;
const filePath = `../Comandos/${subfolder}/${file}`;
const command = require(filePath);
if (!command.name) return;
client.slashCommands.set(command.name, command);
SlashArray.push(command);
});
});
});
});
client.on('ready', async () => {
client.guilds.cache.forEach(guild => guild.commands.set(SlashArray));
});
};
```
ban cmd
```
const { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits} = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName("ban")
.setDescription("⛔ → Banea a un usuario determinado del servidor.")
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.addUserOption(option =>
option.setName("usuario")
.setDescription("Usuario que será baneado.")
.setRequired(true)
)
.addStringOption(option =>
option.setName("motivo")
.setDescription("Un motivo para el baneo")
),
async execute(interaction) {
const usuario = interaction.options.getUser("usuario");
const motivo = interaction.options.getString("motivo") || "No se proporcionó una razón.";
const miembro = await interaction.guild.members.fetch(usuario.id);
const errEmbed = new EmbedBuilder()
.setTitle("️ Error 702")
.setDescription(`No puedes tomar acciones sobre ${usuario.username} ya que tiene un rol superior al tuyo.`)
.setColor("RED")
.setTimestamp()
.setFooter({ text: ` Comando enviado por ${interaction.user.tag} con id ${interaction.user.id}`, iconURL: interaction.user.displayAvatarURL() });
if (miembro.roles.highest.position >= interaction.member.roles.highest.position)
return interaction.reply({ embeds: [errEmbed] })
await miembro.ban({ reason: motivo });
const embedban = new EmbedBuilder()
.setTitle("️ Acciones de baneo tomadas.")
.setDescription(`ℹ️ El usuario ${usuario.tag} ha sido baneado\n **Motivo:** \`${motivo}\``)
.setColor("GREEN")
.setTimestamp()
.setFooter({ text: ` Comando enviado por ${interaction.user.tag} con id ${interaction.user.id}`, iconURL: interaction.user.displayAvatarURL() });
await interaction.reply({
embeds: [embedban]
});
}
}
```
as you can see in the image it doesnt show any ban / unban commands only the ping one and clear / purge
I tried 2 diffferent ways of slash commands and thought it was gonna work but its not, i dont know what is, and ive been struggling for around 1 day, any suggestions? |
My unban and ban commands arent showing when i put the slash |
|node.js|discord|discord.js|command| |
null |
Have you ever tried [json-server][1]? Usually I mock compatible data and I work with this for mvps
Put the following into the db.json file
`db.json`
```json
{
"users":[
{
"id":1,
"name":"John Doe",
"email":"john.doe@example.com",
"age":25
},
{
"id":2,
"name":"Jane Doe",
"email":"[jane.doe@example.com]",
"age":28
},
{
"id":3,
"name":"Bob Smith",
"email":"[bob.smith@example.com",
"age":30
}
]
}
```
run `npx json-server db.json`
trough Angular `HttpClient` you will be able to perform the following HTTP calls:
- GET /users
- POST /users
- PUT /users/{id}
- DELETE /users/{id}
- PATCH /users/{id}
You can also use OData like syntax by visiting the following [url][2]
[1]: https://www.npmjs.com/package/json-server
[2]: https://www.npmjs.com/package/json-server#params |
I am using Polars (`{ version = "0.38.3", features = ["lazy", "streaming", "parquet", "fmt", "polars-io", "json"] }`) with Rust (`v1.77.0`) to process a large dataset (larger than available memory) inside a Docker container. The Docker container's memory is intentionally limited to 6GB using `--memory=6gb` and `--shm-size=6gb`. I am encountering an out of memory error while performing calculations on the dataset.
Here's an overview of my workflow:
1- Load the dataset from a Parquet file using scan_parquet to create a LazyDataframe.
2- Perform various calculations and transformations on the dataframe, including unnesting, exploding, and joining.
3- Group the data and aggregate using group_by and agg.
4- Write the resulting data to disk as a JSON file using sink_json.
Here is a code snippet that demonstrates the relevant parts of my Rust code:
```rust
use jemallocator::Jemalloc;
use polars::{
lazy::dsl::{col, len},
prelude::*,
};
use std::time::Instant;
#[global_allocator]
static GLOBAL: Jemalloc = Jemalloc;
fn main() {
let now = Instant::now();
let mut lf = LazyFrame::scan_parquet(
"./dataset.parquet",
ScanArgsParquet {
low_memory: true,
..Default::default()
},
)
.unwrap();
lf = lf.unnest(["fields"]);
let exploded_lf = lf
.select([
col("id"),
col("url").alias("source_url"),
col("content"),
col("links"),
])
.explode([col("links")])
.unnest(["links"])
.drop_nulls(None);
let mut links_lf = exploded_lf.clone().with_streaming(true).inner_join(
exploded_lf,
col("url"),
col("source_url"),
);
links_lf = links_lf
.select([
col("id"),
col("url"),
col("url").alias("link_url"),
col("source_url"),
col("link_text").alias("link_text"),
])
.unique(None, UniqueKeepStrategy::First);
let result_lf = links_lf
.group_by([col("link_text")])
.agg([len().alias("count"), col("url").first(), col("id").first()]);
let query_plan = result_lf
.clone()
.with_streaming(true)
.explain(true)
.unwrap();
println!("{}", query_plan);
result_lf.with_streaming(true)
.sink_json("./result.json".into(), Default::default())
.unwrap();
let elapsed = now.elapsed();
println!("Elapsed: {:.2?}", elapsed);
}
```
Despite using LazyFrame and enabling low_memory mode in ScanArgsParquet, I still encounter an out of memory error during the execution of the code.
I have tried the following:
- Using the jemallocator crate as the global allocator.
- Enabling streaming mode using with_streaming(true) for the LazyFrame operations.
- Using the `low_memory: true,` in the scan_parquet function.
The printed plan indicates that every operation should be run in the streaming engine:
```
--- STREAMING
AGGREGATE
[len().alias("count"), col("url").first(), col("id").first()] BY [col("link_text")] FROM
UNIQUE[maintain_order: false, keep_strategy: First] BY None
SELECT [col("id"), col("url"), col("url").alias("link_url"), col("source_url"), col("text").alias("link_text")] FROM
FAST_PROJECT: [url, id, source_url, link_text]
INNER JOIN:
LEFT PLAN ON: [col("url")]
WITH_COLUMNS:
[col("url"), col("link_text")]
FILTER col("id").is_not_null().all_horizontal([col("source_url").is_not_null(), col("content").is_not_null(), col("url").is_not_null(), col("link_text").is_not_null()]) FROM
UNNEST by:[inlinks]
EXPLODE
SELECT [col("id"), col("url").alias("source_url"), col("content"), col("links")] FROM
WITH_COLUMNS:
[col("content"), col("links"), col("url")]
UNNEST by:[fields]
Parquet SCAN ./dataset.parquet
PROJECT 2/2 COLUMNS
RIGHT PLAN ON: [col("source_url")]
WITH_COLUMNS:
[col("url"), col("link_text")]
FILTER col("id").is_not_null().all_horizontal([col("source_url").is_not_null(), col("content").is_not_null(), col("url").is_not_null(), col("link_text").is_not_null()]) FROM
UNNEST by:[links]
EXPLODE
SELECT [col("id"), col("url").alias("source_url"), col("content"), col("links")] FROM
WITH_COLUMNS:
[col("content"), col("links"), col("url")]
UNNEST by:[fields]
Parquet SCAN ./dataset.parquet
PROJECT 2/2 COLUMNS
END INNER JOIN --- END STREAMING
DF []; PROJECT */0 COLUMNS; SELECTION: "None"
```
However, I am still running into memory issues when processing the large dataset.
My questions are:
- Why I'm getting the OOM error while everything is indicating it is using the streaming engine ?
- Is there another way to leverage disk-based processing or chunking the data to handle datasets larger than memory?
Any guidance or suggestions on how to resolve this issue would be greatly appreciated. Thank you in advance! |
Polars with Rust: Out of Memory Error when Processing Large Dataset in Docker Using with_streaming(true) |
|docker|rust|memory-management|parquet|rust-polars| |
I've been searching for days now but cannot find what's wrong. I'm trying to update a user after creating a username and password.
Backend updating user
```
app.put('/users/:userId', async (req, res) => {
const client = new MongoClient(uri)
const formData = req.body;
try {
await client.connect();
const database = client.db('app-data')
const users = database.collection('users');
console.log("Form data", formData);
const query = {user_id: formData.userId}
const updateDocument = {
$set: {
first_name: formData?.first_name,
last_name: formData?.last_name,
birthdate: formData?.birthdate,
birth_month: formData?.birth_month,
birth_year: formData?.birth_year,
gender: formData?.gender,
major: formData?.major,
cleanliness: formData?.cleanliness,
bio: formData?.bio
},
}
const insertedUser = await users.updateOne(query, updateDocument);
return res.json(insertedUser);
```
Frontend form submission
```
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import React from "react";
const Survey = () => {
const [formData, setFormData] = useState({
first_name: '',
last_name: '',
birthdate: '',
birth_month: '',
birth_year: '',
gender: '',
class_rank: '',
major: '',
cleanliness: '',
major_interest: '',
bio: ''
})
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
try {
console.log("Form data: ", formData);
const userId = localStorage.getItem('userId');
const response = await axios.put(`http://localhost:8000/users/${userId}`, formData);
navigate('/feed');
return response;
} catch(err) {
console.log(err);
}
}
const handleChange = (e) => {
const value = e.target.value
const name = e.target.name
console.log("Updating:", {[name]: value})
setFormData((prevState) => ({
...prevState,
[name]: value
}))
}
return (
// HTML form for above values
)
```
I'm wanting it update user with these entries in the database but it does not on console logging the form data, it gives.
```
Form data undefined
{
acknowledged: true,
modifiedCount: 0,
upsertedId: null,
upsertedCount: 0,
matchedCount: 0
}
```
At this point, that is the only error message. I've tried getting the item from local storage on the server side, setting as cookies, and some other suggestions I'm unsure of.
|
I have a situation where there are 5 csv files open between 2 different Python programs running on a single computer. Lines of data are written to the csv files using using `writer.writerow(self.ROW_HEADER)`. Each csv file had approximately 1 column of data saved every second. The programs were set to run for weeks on end and after one weekend both programs had crashed without any error message. After reviewing the csv files, it appeared that data wasn't being written to some of the text files for a long time before the program crashed which makes me think it was a sort of memory overflow. Any recommendations on how to handle this?
Here's the class I instantiate to create each csv file.
class csv_file:
ROW_HEADER = ["Column 1", "Column 2", "Column 3"]
def __init__(self, name: str, path: str) -> None:
self.file_name = f"{name}.csv"
self.file_path = path
self.file = None
self.lock = threading.RLock()
self.start_time = time.time()
def create_file(self) -> None:
'''
Creates a csv file with the name and path specified in the constructor.
Appends the row header to the file.
'''
with self.lock:
os.makedirs(self.file_path, exist_ok=True) # Create the directory if it doesn't exist (nothing happens if it does)
self.file = open(os.path.join(self.file_path, self.file_name), 'w')
self.writer = csv.writer(self.file)
self.writer.writerow(self.ROW_HEADER)
def _create_row(self, row:list) -> None:
'''
Adds a row to the csv file. The row must be the same
size as the row header.
'''
with self.lock:
self.writer.writerow(row)
def add_row(self, val1:float, val2:float, val3:float) -> None:
with self.lock:
row = []
row.append(val1)
row.append(val2)
row.append(val3)
self._create_row(row)
|
Writing data to csv files using csvwriter crashed computer over weekend |
|python|csv|memory| |
You can change:
class ImageForm(forms.ModelForm):
class Meta:
model = Image
fields = ['photo', ]
widgets = {
'photo': forms.ClearableFileInput(attrs={'multiple': True})
}
to:
class ImageForm(forms.ModelForm):
class Meta:
model = Image
fields = ['photo', ]
widgets = {
'photo': forms.ClearableFileInput(attrs={'allow_multiple_selected': True})
} |
Add this conditional JavaScript to your main page:
```javascript
const params = new URLSearchParams(window.location.search)
if (params.get('stripe_portal') === "success") {
// track conversion
}
``` |
I don't know if you found a solution to you problem, but what you need to do is to configure `CosmosClient` to use `Gateway` mode instead of the default `Direct` mode, Testcontainers Cosmos DB module needs this :
var cosmosClientOptions = new CosmosClientOptions
{
ConnectionMode = ConnectionMode.Gateway,
HttpClientFactory = () => cosmosDbContainer.HttpClient,
};
var connectionString = cosmosDbContainer.GetConnectionString();
var cosmosClient = new CosmosClient(connectionString, cosmosClientOptions); |
I use a workspace into my app
"workspaces": [
"firstapp/web",
"secondapp"
]
Into second app, into package.json I get into dependencies:
"anotherapp": "https://github.com/me/anotherapp.git",
From root I run `yarn workspaces foreach -Apt install` everething is ok
I run `yarn workspaces foreach -Apt build` but get `Cannot find module 'anotherapp' or its corresponding type declarations.`
I get this both in CI and during dev (on local)
I don't know what is wrong
If I import my anotherapp as `"anotherapp": "../anotherapp"` on local it's working.
So I don't know how to fix it.
**EDIT**: the concerned repo: https://github.com/Ludea/lucle-plugins
secondapp, where I import a package from GH is speedupdate
And the app imported from GH is https://github.com/Ludea/mui-file-dropzone |
**2024 Updated version on 0.73 - TurboModules - New Architecture enabled**
const SourceCode = TurboModuleRegistry.getEnforcing("SourceCode");
const scriptURL = SourceCode.getConstants().scriptURL;
const address = scriptURL.split('://')[1].split('/')[0];
const hostname = address.split(':')[0];
const port = address.split(':')[1]; |
Deleted because OP changed the question significantly hours after posting. It's unclear what OP is doing.
**Remove Transforms from Parent Element**
As @Paulie_D commented:
> A position: fixed element is always positioned in relation to the body
> but you have to specify where it is positioned.
However, OP broke this relationship by using a translate transform to center the parent element on the page. The transform affects the child element too.
To fix the problem, we need to center the parent element without using a transform. Adding Tailwind flex classes to the container is one alternative. This centers the parent without affecting the fixed positioning of the child element.
*Tailwind References:* [Flex][1] , [Align Items][2] , [Align Content][3]
**Code Snippet**
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-html -->
<div class="flex justify-center items-center h-screen bg-blue-100">
<div class="fixed top-20 h-80 w-80 bg-red-300">
parent - centered
<div class="fixed top-10 left-0 h-40 w-40 bg-green-600 text-white">
child - fixed to body
</div>
</div>
</div>
<script src="https://cdn.tailwindcss.com"></script>
<!-- end snippet -->
[1]: https://tailwindcss.com/docs/flex
[2]: https://tailwindcss.com/docs/align-items
[3]: https://tailwindcss.com/docs/align-content |
|excel|vba|outlook| |
|javascript|ajax|wordpress| |
As mentioned in the comments, it's not advisable to keep dates in a text format. Instead, always use a date or timestamp type.
The problem with your query is that you're attempting to concatenate strings using the operator `+`, when you should be using the `CONCAT()` function instead :
WHERE month.ty LIKE CONCAT('%', YEAR(current_timestamp), '%') |
`<script>
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var end =setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
//window.location = "http://www.YouTube.com";
clearInterval(end);
}``your text``
}, 1000);}
window.onload = function () {
var fiveMinutes = 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
`Hello`</script>
</head>
<body>
`your text`<div>Redirect in <span id="time">05:00</span></div>
<form id="form1" runat="server">
</form>`
I cannot get this to actually redirect. the countdown works but it doesn't redirect. I just get the timer. the timer counts down and hits zero and it goes absolutely nowhere. |
On the server side, it returns undefined but on the client side, logs the values no problem |
|javascript|reactjs|mongodb|jsx|crud| |
null |
New to coding and getting this error message:
> "Cannot convert value of type 'Tab.Type' to expected argument type 'Binding<Tab>'"
What can I change to fix this? Here's my code:
```
enum Tab: String, CaseIterable{
case house
case person
case message
case gearshape
}
struct ContentView: View {
@Binding var selectedTab: Tab
private var fillImage: String {
selectedTab.rawValue + ".fill"
}
var body: some View {
VStack {
HStack {
}
.frame(width: nil, height: 60)
.background(.thinMaterial)
.cornerRadius(10)
.padding()
}
}
}
```
|
`helpText` is only a wrapper for `span(class = "help-block", ...` and `.help-block` has a grey color which is responsible for the low "brightness". Hence, you just can add a `style` argument and apply arbitrary `CSS` in order to display the text as you wish, e.g., with black color:
```
helpText(
"$$\\log_{10}p_w = \\frac{-1.1489t}{273.1+t}-1.330\\text{e-}05t^2 + 9.084\\text{e-}08t^3 - 1.08\\text{e-}09t^4 +\\log_{10}p_i\\\\[15pt]
\\log_{10}p_i=\\frac{-2445.5646}{273.1+t}+8.2312\\log_{10}\\left(273.1+t\\right)-0.01677006\\left(273.1+t\\right)+1.20514\\text{e-}05\\left(273.1+t\\right)^2-6.757169\\\\[15pt]
p_i=saturated\\space vapor\\space pressure\\space over\\space ice\\space \\left(mmHg\\right)$$"
,
style = "color: black;"
)
```
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/Wczo4.png |
The AI of ChatGPT has not learned from code written by the best batch file code writers. The produced code examples are not working for that reason for your task and are all not good for any user input string validation done with the *Windows Command Processor* `cmd.exe` during processing of a batch file.
Here is a working batch code example for the task with explaining comments (remarks).
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem The user is prompted until entering something.
:UserPrompt
set "YouTubeUrl="
set /P "YouTubeUrl=Please enter or drag & drop the YouTube playlist url: " || goto UserPrompt
rem Remove all double quotes from user input string.
set "YouTubeUrl=%YouTubeUrl:"=%"
rem The environment variable YouTubeUrl is not defined anymore on user
rem has input before by mistake just one or more double quote characters.
if not defined YouTubeUrl goto UserPrompt
rem The url string must contain the string "list" which is verified by
rem comparing the url string with all occurrences of case-insensitive
rem found "list" in the string replaced by an empty string with the
rem unmodified url string. The string "list" is missing in the url
rem string if the two compared strings are identical.
if "%YouTubeUrl:list=%" == "%YouTubeUrl%" echo That is not a valid playlist url!& goto UserPrompt
rem The value of the environment variable YouTubeUrl can be used here in
rem further command lines before the command endlocal is finally executed.
endlocal
The remarks – the lines beginning with the command `rem` – can be removed from the the batch file for faster execution with less file system accesses. The batch file would look without the comment lines:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
:UserPrompt
set "YouTubeUrl="
set /P "YouTubeUrl=Please enter or drag & drop the YouTube playlist url: " || goto UserPrompt
set "YouTubeUrl=%YouTubeUrl:"=%"
if not defined YouTubeUrl goto UserPrompt
if "%YouTubeUrl:list=%" == "%YouTubeUrl%" echo That is not a valid playlist url!& goto UserPrompt
rem ... command lines using "%YouTubeUrl%" ...
endlocal
For a full explanation of this code example see my answer on [How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?](https://stackoverflow.com/a/49834019/3074564) and [single line with multiple commands using Windows batch file](https://stackoverflow.com/a/25344009/3074564) for an explanation of the operators `||` and `&`. |
|c#|asp.net|api|asp.net-core| |
To verify if a cookie was set, pass a callback to the setCookie(3rd argument).
Create a subclass of CefSetCookieCallback
class MyCookieCallback: public CefSetCookieCallback {
void OnComplete(bool success) {
//success will tell if you cookie was set or not.
}
}
Also try adding cookie.path as well. |
Regex can be used here, but it is way too heavy and expensive for such a simple check.
We can use discrete statements to check for your requirements. It will also make the code more readable and the messages would be specific to the actual issue of that particular input.
```kotlin
init {
//check that the input is not null
require(port_range_from != null) { "port_range_from must not be null" }
val portInt = port_range_from.toIntOrNull()
//if portInt is null, it means that the String could not be parsed to Int
require(portInt != null) { "port_range_from must be a valid integer" }
//we don't need to check for leading 0s, if the input is actually just `0`
if (port_range_from.length > 1) require(!port_range_from.startsWith('0')) { "port_range_from must not have leading 0s" }
//check to see that the port is not negative
require(portInt > -1) { "port_range_from must be non-negative integer" }
}
```
We can then do stuff with `portInt` or not, we know that if we call `port_range_from.toInt()` afterwards, it will have a value that we want.
---
We could also combine the first two `require` and just do:
```
val portInt = port_range_from?.toIntOrNull()
require(portInt != null) { "port_range_from must be a non-null valid integer" }
```
But then again, merging different checks in the same `require` muddles the reason the input was rejected.
---
Another things is that this may be an XY problem. If we could use a normal class, we could ignore the leading 0s in the input, and just create a new Int field without them.
```
class Foo(port_range_from: String?) {
val port_range_from : Int
init {
//check that the input is not null
require(port_range_from != null) { "port_range_from must not be null" }
val portInt = port_range_from.toIntOrNull()
//if portInt is null, it means that the String could not be parsed to Int
require(portInt != null) { "port_range_from must be a valid integer" }
//check to see that the port is not negative
require(portInt > -1) { "port_range_from must be non-negative integer" }
this.port_range_from = portInt
}
}
```
|
Just for record, because I had similiar problem, and maybe this answer will help someone: in my case I was using library which was using `.js` files and I didn't had such extension in webpack resolve extensions. Adding proper extension fixed problem:
```js
module.exports = {
// ...
resolve: {
extensions: ['.ts', '.js'],
}
}
```` |
null |
Instead of "undoing" all of your previous style changes, you can duplicate a cell style (that you didn't change) to your desired reset cell/range.
> @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
```php
function resetStyle(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, string $range): void
{
$worksheet->duplicateStyle(
$worksheet->getStyle('ZZ99999'),
$range
);
}
``` |
I cannot get this to redirect. The timer works but it doesn't go anywhere. I need this to redirect to another webpage |
|timer|http-redirect| |
null |
This would best be accomplished in the following manner:
- Set the background color of the body to what you want the bottom half
to be.
- Set the background color of the element and give it the clip-path.
This will ensure you always have the nice separation.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
html {
height: 100%;
box-sizing: border-box;
}
*, *::before, *::after {
box-sizing: inherit;
}
body {
margin: 0;
min-height: 100%;
background: #313131;
}
.bg {
top: 0;
left: 0;
right: 0;
bottom: 0;
position: fixed;
background: #099dd7;
clip-path: ellipse(148% 70% at 91% -14%);
}
<!-- language: lang-html -->
<body><div class="bg"></div></body>
<!-- end snippet -->
The reason that the linear gradient doesn't work is that the clip-path that is being applied hides the bottom half of it. |
I want to implement an actor which uses "legacy" components which are classes using a dispatch queue for calling callbacks.
These "legacy" components are actually classes from Apples NWNetwork framework. These classes require a dispatch queue and callback functions to be specified. The callback functions will be called by the framework on the specified dispatch queue.
What I want to avoid is, to implement the callbacks like:
```Swift
@Sendable
nonisolated
private func callback(to newState: NWListener.State) {
Task {
await self.send(.listenerStateChange(newState))
}
}
```
i.e. dispatching into a Task which runs on the isolated context.
Instead, I want to run the whole actor on a custom Executor - a `SerialDispatchQueue` - which is also the queue for the "legacy" components.
Then, my actor provides the callback function as a member function like:
```Swift
@Sendable
nonisolated
private func callback(to newState: NWListener.State) {
dispatchPrecondition(condition: .onQueue(self.queue))
self.assumeIsolated { thisActor in
thisActor.send(.listenerStateChange(newState))
}
}
```
The callback function must be `@Sendable` and `nonisolated`. Due to the design, it's guaranteed that the callback function is called on the given dispatch queue `self.queue`.
Now, when executing the actor, I get the following runtime error when executing `self.assumeIsolated(:_)`:
```Console
Fatal error: Incorrect actor executor assumption; Expected same executor as MyLib.TestActor.
```
I wrote a minimal test to demonstrate the issue:
```Swift
public final actor TestActor {
let queue = DispatchSerialQueue(label: "test_actor_queue")
nonisolated
public var unownedExecutor: UnownedSerialExecutor {
queue.asUnownedSerialExecutor()
}
func isolatedFunc() {
self.preconditionIsolated()
}
@Sendable
nonisolated
func nonIsolatedFunc() {
self.queue.async {
self.callback()
}
}
@Sendable
nonisolated
func callback() {
dispatchPrecondition(condition: .onQueue(queue))
self.assumeIsolated { this in // <== Runtime error
this.isolatedFunc()
}
}
}
```
#### Test
```Swift
final class HTTPServerTests: XCTestCase {
func testExample() async throws {
let actor = TestActor()
await actor.isolatedFunc()
actor.nonIsolatedFunc()
}
}
```
The statement `await actor.isolatedFunc()` runs OK as expected.
`actor.nonIsolatedFunc()` simply simulates the "legacy" framework to call the callback on the specified dispatch queue. It fails during runtime with the given error.
### Stack trace
The stack trace at the time of the runtime error also clearly shows, that we are running on the specified dispatch queue - as expected:
```Console
Thread 4 Queue : test_actor_queue (serial)
#0 0x000000019326df68 in _swift_runtime_on_report ()
#1 0x000000019330614c in _swift_stdlib_reportFatalErrorInFile ()
#2 0x0000000192fcb2d8 in _assertionFailure(_:_:file:line:flags:) ()
#3 0x00000002099cb298 in Actor.assumeIsolated<τ_0_0>(_:file:line:) ()
#4 0x00000001053a2918 in TestActor.callback@Sendable () at /Users/agrosam/Developer/HTTPServer-NWNetwork-Actor/HTTPServer/Sources/HTTPServer/HTTPServer.swift:77
#5 0x00000001053a27a0 in closure #1 in TestActor.nonIsolatedFunc@Sendable () at /Users/agrosam/Developer/HTTPServer-NWNetwork-Actor/HTTPServer/Sources/HTTPServer/HTTPServer.swift:68
#6 0x00000001053a2978 in thunk for @escaping @callee_guaranteed @Sendable () -> () ()
```
My understanding is, that DispatchLib already implemented everything to have a `DispatchSerialQueue` as a well behaving citizen of a `SerialExecutor` in the actor's realm.
**So, I would expect, the runtime assertion would succeed.**
### See also:
https://github.com/apple/swift-evolution/blob/main/proposals/0424-custom-isolation-checking-for-serialexecutor.md
|
> Will this impact the integrity of data?
**No**. This exception was triggered in a `ReadStage` thread - This type of thread is responsible for local reads, which don't modify the dataset in any way.
> And is there something I can do to avoid the error e.g. resize some param on Cassandra.yaml?
**Yes**. I would start by finding the root cause and addressing it, rather than changing configuration. I can think of likely 2 scenarios here this exception would be triggered:
1. The client scanned through a **large partition** in a single query (exceeding ~128 MiB). To validate this you can verify what's the max partition uncompressed size by running the following:
1. Cassandra 4.1.X and above: `nodetool tablestats -s compacted_partition_maximum_bytes -t 1`
2. Previous versions: `nodetool tablestats | grep "Compacted partition maximum bytes" | awk '{print $5}' | sort -n | tail -1`
If you see a partition over 128MiB, then it may be necessary to check if there is a query reading whole partitions in the correspondent table. And if there is one, rethink the data model in order to control partition size. One common solution to this problem is to bucket partitions by time or other arbitrary fields that can split the partitions in a balanced way.
2. A client is issuing a **range scan**. This includes read queries that read multiple partitions, such as queries that need `ALLOW FILTERING` and don't filter by partition key, and it's usually very expensive in Cassandra. Generally you'll be able to catch those in `debug.log` through **slow query logs**. If this is the case, I strongly recommend to consider [modeling a table for each of those queries][1] so that all reads are single-partition reads and the database performance scales well with the workload.
------------------
Finally, the quick configuration fix (in Cassandra 4.X) is to edit the following parameters in **cassandra.yaml** and restart nodes to apply changes:
`internode_application_send_queue_reserve_endpoint_capacity_in_bytes` - defaults to 134217728
`internode_application_receive_queue_reserve_endpoint_capacity_in_bytes` - defaults to 134217728
Feel free to check the official documentation on internode messaging [here][2].
[1]: https://cassandra.apache.org/doc/stable/cassandra/data_modeling/data_modeling_rdbms.html#query-first-design
[2]: https://cassandra.apache.org/doc/4.0/cassandra/new/messaging.html#resource-limits-on-queued-messages |
Your posted programs are defining the following 4 distinct `int` variables:
1. The variable with the name `first`.
2. The variable with the name `second`.
3. The variable with the name `third` in the outer [scope](https://en.cppreference.com/w/c/language/scope).
4. The variable with the name `third` in the inner scope.
Variables #3 and #4 are distinct, despite both variables having the same name. When using the identifier `third` in the inner scope, you are referring to variable #4. When using that identifier in the outer scope, you are referring to variable #3.
> I don't think there can be two variables with same name inside the curly braces inside main.
There can, and there indeed are. This is not good programming style, but the language allows you to do this.
> I personally think that this code should give an error
If you want the compiler to emit a warning when one variable's name shadows another variable's name, then, with the compilers gcc and clang, you can compile with the `-Wshadow` command-line option.
> then I compiled this code on vs code and it gave an error
Since your posted code is valid C code, it should not give an error message, only maybe a warning message (unless you tell the compiler that you want to treat warnings as errors).
> then how can we access both the variables inside those curly braces
You cannot access the variable in the outer scope from the inner scope directly. However, you can still access that variable from the inner scope indirectly, via a pointer:
```
#include <stdio.h>
int main(void)
{
int first = 10;
int second = 20;
int third = 30;
int *p = &third;
{
int third = second - first;
printf("%d\n", third);
printf("%d\n", *p );
}
printf("%d\n", third);
return 0;
}
```
This will print:
```none
10
30
30
``` |
The simplest
ans->push_back(x->at(i));
But I don't understand why you call that "move element."
BTW `vector<int>*` is nonsense. `x` manages a dynamically allocated memory and `vector<int>*` never looks good. |
{"Voters":[{"Id":14098260,"DisplayName":"Alexander Nenashev"},{"Id":5459839,"DisplayName":"trincot"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[11]} |
Why doesn't the PHP info webpage appear when testing PHP 8.1, installed during the LAMP setup on Ubuntu 22.04?
Could someone provide a command-line add-on with an explanation? Additionally, could you give details on PHP configuration, such as php.ini, and some common errors encountered during the LAMP stack setup with Ubuntu 22.04? |
Setting up LAMP on Ubuntu 22.04: PHP info not displaying in browser |
Trying to upload large files using multipart upload where I generate pre-signed URL for each chunk and the push files to S3. When I upload large files for some of the chunks I'm getting '**net::ERR_CONNECTION_RESET**' intermittently and the upload is getting failed. Is there any way to over come this ? or Do I need to configure anything on AWS so that this issue will not occur ? Any suggestions are really appreciated. Also are there any ways to make the file upload successful(like retrying to upload the failed chunk again) ? [Attaching screenshot of network calls while uploading a file](https://i.stack.imgur.com/vEEPk.jpg)
Note: The expiry time set for pre-signed URL is 60 minutes.
I am using NodeJS as backend where I have API's to generate Upload Id, Pre-Signed URL from AWS etc and the UI is built on Next JS, where I am using pre-signed URL to upload the file to AWS. |