qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,540,458
|
<p>I have a managed library that wraps a native library which has binaries for both 32-bit and 64-bit.</p>
<p>Currently, I have to do the following:</p>
<p>First, build the native library 32-bit and 64-bit builds using <a href="https://learn.microsoft.com/en-us/visualstudio/ide/how-to-build-multiple-configurations-simultaneously?view=vs-2022" rel="nofollow noreferrer">Batch Build</a>.</p>
<p>Second, build the managed library.</p>
<p>The managed library references binaries which are then loaded using <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.nativelibrary.load?view=net-7.0#system-runtime-interopservices-nativelibrary-load(system-string)" rel="nofollow noreferrer">NativeLibrary.Load</a> at runtime.</p>
<p>The whole thing ends up as a NuGet package ready for consumption.</p>
<p><strong>Question:</strong></p>
<p>How can I get that batch build step to be performed automatically instead of manually?</p>
|
[
{
"answer_id": 74540681,
"author": "Greg Pavlik",
"author_id": 12756381,
"author_profile": "https://Stackoverflow.com/users/12756381",
"pm_score": 2,
"selected": false,
"text": "system$wait select system$wait(5);\n"
},
{
"answer_id": 74622383,
"author": "Speedy",
"author_id": 13485533,
"author_profile": "https://Stackoverflow.com/users/13485533",
"pm_score": 1,
"selected": true,
"text": "call system\\$wait(60);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361899/"
] |
74,540,504
|
<p>I am currently using the random.sample function to extract individuals from a population.</p>
<p>ex:</p>
<p>n = range(1,1501)</p>
<p>result = random.sample(n, 500)
print(result)</p>
<p>in this example I draw 500 persons among 1500. So far, so good..</p>
<p>Now, I want to go further and launch a search with a list of exclude people.</p>
<p>exclude = [122,506,1100,56,76,1301]</p>
<p>So I want to get a list of people (1494 persons) while excluding this array (exclude)</p>
<p>I must confess that I am stuck on this question. Do you have an idea ?
thank you in advance!</p>
<p>I am learning Python language. I do a lot of exercise to train. Nevertheless I block ue on this one.</p>
|
[
{
"answer_id": 74540681,
"author": "Greg Pavlik",
"author_id": 12756381,
"author_profile": "https://Stackoverflow.com/users/12756381",
"pm_score": 2,
"selected": false,
"text": "system$wait select system$wait(5);\n"
},
{
"answer_id": 74622383,
"author": "Speedy",
"author_id": 13485533,
"author_profile": "https://Stackoverflow.com/users/13485533",
"pm_score": 1,
"selected": true,
"text": "call system\\$wait(60);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19767241/"
] |
74,540,508
|
<p>After I migrated my project to <code>.NET 7</code> I had to add the <code>TrustServerCertificate=true;</code> setting in the connection string otherwise the following error is thrown: <code>SqlException: A connection was successfully established with the server, but then an error occurred during the login process</code>.</p>
<p>In .NET 5 or 6 this is not necessary. Can anyone tell me why it is necessary to add this setting in the connection string?</p>
<p><strong>LOCAL CONNECTION STRING:</strong></p>
<pre><code>Server=localhost;Database=Xpz;Integrated Security=SSPI;TrustServerCertificate=true;
</code></pre>
|
[
{
"answer_id": 74645037,
"author": "Subarata Talukder",
"author_id": 3018627,
"author_profile": "https://Stackoverflow.com/users/3018627",
"pm_score": 0,
"selected": false,
"text": "\"ConnectionStrings\": {\n \"DefaultConnection\": \"Server=SERVER_NAME;Database=DB_NAME;Trusted_Connection=True;TrustServerCertificate=True;\",\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5137138/"
] |
74,540,525
|
<p>I am trying to edit the input entered for each day. I have created an input_sales_day function that contains a number of products to enter for a day, an input_sales function that takes the number of products and days as parameters, where I think the problem lies, and a final function that just prints. I've tried using split, but I always get the error or just print each word instead.</p>
<p>Here is the code, it prints:</p>
<pre><code>Product name: z1
quantity sold : 1
Product Name: z1
quantity sold : 1
Product name : z2
quantity sold : 2
Product Name: z2
quantity sold : 2
Product name : z3
quantity sold : 3
Product Name: z3
quantity sold: 3
Day 1 : ['1 z1', '1 z1']
Day 2 : ['1 z1', '1 z1', '2 z2', '2 z2']
Day 3: ['1 z1', '1 z1', '2 z2', '2 z2', '3 z3', '3 z3']
</code></pre>
<p>I try to print:</p>
<pre><code>Day 1: ['1 z1', '1 z1']
Day 2 : ['2 z2', '2 z2']
Day 3 : ['3 z3', '3 z3']
</code></pre>
<pre><code>p = []
def input_sales_day(nbp):
for i in range(nbp):
np = input("Product Name: ")
qv = input("quantity sold : ")
p.append('{} {}'.format(qv, np))
return p
def input_sales(nbp, d):
sl = []
for j in range(d):
n = input_sales_day(nbp)
sl.append('day {} : {}'.format(j+1, n))
return sl
def print_sales(sl):
return '\n'.join(sl)
print(print_sales(input_sales(2, 3)))
</code></pre>
|
[
{
"answer_id": 74540565,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 3,
"selected": true,
"text": "p input_sales_day p def input_sales_day(nbp):\n p = []\n for i in range(nbp):\n np = input(\"Product Name: \")\n qv = input(\"quantity sold : \")\n p.append('{} {}'.format(qv, np))\n return p\n\n\ndef input_sales(nbp, d):\n sl = []\n for j in range(d):\n n = input_sales_day(nbp)\n sl.append('day {} : {}'.format(j+1, n))\n return sl\n\n\ndef print_sales(sl):\n return '\\n'.join(sl)\n\n\nprint(print_sales(input_sales(2, 3)))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489036/"
] |
74,540,559
|
<p>I'm trying to prevent the user from liking photos more than once when refreshing the page.</p>
<p>So the current <strong>incorrect</strong> flow is: click like on desired photo > number increments > refresh the page > <code>click like on desired photo > number increments > refresh the page > *rinse & repeat*</code></p>
<p>The <strong>correct</strong> flow should be: <code>click like on desired photo > number increments > refresh the page > click like on desired photo > number decrements > *rinse & repeat*</code></p>
<p>I know I'll need to map the liked <code>UserID</code>s into local storage so that the browser remembers which photos were liked but I'm not sure how.</p>
<p>One of my many, many attempts in the <code>else{}</code> block is below. I've completely hit a wall and not sure how to achieve this.</p>
<p><strong>Note:</strong> using localstorage is not new to me as you can see I'm using it for something unrelated in the <code>return()</code>. However, this mapping stuff to localstorage is what has me stumped.</p>
<pre><code>useEffect(() => {
const headers = {
"Accept": 'application/json',
"Authorization": `Bearer ${authToken}`
};
axios.get('http://127.0.0.1:8000/api/get-user-uploads-data', {headers})
.then(resp => {
console.log(resp.data);
setGridData(resp.data);
}).catch(err => {
console.log(err);
});
}, []);
const handleLikesBasedOnUserId = (likedPhotoUserId, userName) => {
let mapOfLikes = {};
if(userLikedPhotos[likedPhotoUserId]) {
// dislike
delete userLikedPhotos[likedPhotoUserId];
gridData.find(photo => photo.UserID === likedPhotoUserId).likes--;
handleDislike(likedPhotoUserId, userName); // Send dislike incrementation via POST request
// localstorage logic?
} else {
// like
userLikedPhotos[likedPhotoUserId] = true;
gridData.find(photo => photo.UserID === likedPhotoUserId).likes++;
// attempt below
mapOfLikes[likedPhotoUserId] = mapOfLikes[likedPhotoUserId] ?? 1;
localStorage.setItem('mapOfLikes', JSON.stringify(mapOfLikes));
handleLike(likedPhotoUserId, userName); // Send like incrementation via POST request
// localstorage logic?
}
// Spread the userLikedPhotos to create a new object and force a rendering
setUserLikedPhotos({...userLikedPhotos});
};
return(
{
gridData.map((photos, index) => {
<span className="likesAmt">❤️ {photos.likes}</span><br/><Button variant="success" onClick={() => handleLikesBasedOnUserId(photos.UserID, photos.name)}>Like</Button><br/><span className="name">{photos.name} {localStorage.getItem('UserID') === photos.UserID ? <h6 className="you">(You)</h6> : null}</span>
})
}
);
</code></pre>
|
[
{
"answer_id": 74540565,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 3,
"selected": true,
"text": "p input_sales_day p def input_sales_day(nbp):\n p = []\n for i in range(nbp):\n np = input(\"Product Name: \")\n qv = input(\"quantity sold : \")\n p.append('{} {}'.format(qv, np))\n return p\n\n\ndef input_sales(nbp, d):\n sl = []\n for j in range(d):\n n = input_sales_day(nbp)\n sl.append('day {} : {}'.format(j+1, n))\n return sl\n\n\ndef print_sales(sl):\n return '\\n'.join(sl)\n\n\nprint(print_sales(input_sales(2, 3)))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9903235/"
] |
74,540,584
|
<p>I am developing a web app using React.JS.</p>
<p>I would like the input to be a default value, but the input can't be uneditable.</p>
<p>I have tried :</p>
<pre><code>let [inputValue, setInputValue] = useState<string>('Value of Input')
return (
<div className = "App">
<input value={inputValue}></input>
</div>
</code></pre>
<p>The problem with this is that i can't edit the input.</p>
|
[
{
"answer_id": 74540629,
"author": "Gia Huy Nguyễn",
"author_id": 20485039,
"author_profile": "https://Stackoverflow.com/users/20485039",
"pm_score": 0,
"selected": false,
"text": "<input value={inputValue} onChange={(e) => setInputValue(e.target.value)}></input>\n"
},
{
"answer_id": 74541035,
"author": "Chandra Raditya",
"author_id": 20330404,
"author_profile": "https://Stackoverflow.com/users/20330404",
"pm_score": 1,
"selected": false,
"text": "const handleOnChange = (event) => {\n setInputValue(event.target.value);\n };\n <h1>this is what inputValue state content: {inputValue}</h1>\n import { useState } from \"react\";\n\nexport default function App() {\n const [inputValue, setInputValue] = useState(\"Value of Input\");\n\n const handleOnChange = (event) => {\n setInputValue(event.target.value);\n };\n return (\n <div className=\"App\">\n <h1>this is the content of inputValue state: {inputValue}</h1>\n <input onChange={(event) => handleOnChange(event)}></input>\n </div>\n );\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19317235/"
] |
74,540,587
|
<p>So, I wrote the following program to determine the max element in a 2D array using LISP. Note, this is my first time using the language, so I am unfamiliar with many aspects.</p>
<p>The function should return the coordinates of the largest element in row-major order. In the below example, the largest element, 7, is found at index (2, 4). However, when the program is executed, it returns (3, 15).</p>
<p>It seems to be starting the index at 1, rather than 0, for the row. Additionally, it seems to be counting all indexes up to 15, where the max element is found. I am unsure how to fix this issue.</p>
<pre><code>(defun find-max-location (x)
(let (
(maxval -100)
(loc nil)
(cur 0)
(cur2 0)
(k 1)
(l 1)
(f 0))
(loop for i in x do
(loop for j in i do
(if (> j maxval)
(progn
(setf cur k)
(setf cur2 l)
(setf maxval j))
)
(setf l (+ l 1))
)
(setf k (+ k 1))
)
(list cur cur2)))
(find-max-location '((0 1 0 0 1) (0 2 2 0 0) (3 0 1 4 7) (0 1 2 0 0) (1 2 1 0 3)))
</code></pre>
|
[
{
"answer_id": 74541118,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 1,
"selected": false,
"text": "0 max max max max (defun find-max-in-row (lst &optional (pos 0) (max '()))\n (cond ((null lst) \n max)\n (or (null max) (> (car lst) (car max))\n (find-max-in-row (cdr lst) (1+ pos) (list (car lst) pos)))\n (t \n (find-max-in-row (cdr lst) (1+ pos) max))))\n\n(defvar foo '(1 6 8 2 7))\n\n(format t \"~a~%\" (find-max-in-row foo))\n (8 2)\n (format t \"~a~%\" \n (mapcar #'find-max-in-row \n '((0 1 0 0 1) \n (0 2 2 0 0) \n (3 0 1 4 7) \n (0 1 2 0 0) \n (1 2 1 0 3))))\n ((1 1) (2 1) (7 4) (2 2) (3 4))\n"
},
{
"answer_id": 74543905,
"author": "Renzo",
"author_id": 2382734,
"author_profile": "https://Stackoverflow.com/users/2382734",
"pm_score": 2,
"selected": false,
"text": "l 0 0 1 loc f when if (defun find-max-location (x)\n (let ((maxval -100)\n (cur 0)\n (cur2 0)\n (k 0)\n l)\n (loop for i in x\n do (setf l 0)\n (loop for j in i \n do (when (> j maxval)\n (setf cur k)\n (setf cur2 l)\n (setf maxval j))\n (setf l (+ l 1)))\n (setf k (+ k 1))) \n (list cur cur2)))\n\n(find-max-location '((0 1 0 0 1) (0 2 2 0 0) (3 0 1 4 7) (0 1 2 0 0) (1 2 1 0 3))) ; => (2 4)\n setf (defun find-max-location (x)\n (let ((maxval -100)\n (cur 0)\n (cur2 0)\n (k 0)\n l)\n (loop for i in x\n do (setf l 0)\n (loop for j in i \n do (when (> j maxval)\n (setf cur k\n cur2 l\n maxval j))\n (setf l (+ l 1)))\n (setf k (+ k 1))) \n (list cur cur2))\n loop with when (defun find-max-location (x)\n (loop with maxval = -100\n and cur = 0\n and cur2 = 0\n for i in x\n for k from 0\n do (loop for j in i\n for l from 0\n when (> j maxval)\n do (setf cur k\n cur2 l\n maxval j))\n finally (return (list cur cur2))))\n loop"
},
{
"answer_id": 74552723,
"author": "Gwang-Jin Kim",
"author_id": 9690090,
"author_profile": "https://Stackoverflow.com/users/9690090",
"pm_score": 1,
"selected": false,
"text": "setf max-val (defun find-max-location (lol)\n \"Find max element's coordinate in a lol\"\n (let ((max-val (caar lol))\n (max-coord '(0 . 0))) ;; start with first element\n (loop for il in lol\n for i from 0\n do (loop for e in il\n for j from 0\n when (> e max-val)\n do (setf max-val e\n max-coord (cons i j))))\n (values max-coord max-val)))\n values max-value ;; usage:\n\n(find-max-location '((0 1 9) (4 9) (6 7 8)))\n;; => (0 . 2)\n;; => 9\n\n;; capture max-val too:\n(multiple-value-bind (coord val) (find-max-location '((0 1 9) (4 9) (6 7 8)))\n (list val (car coord) (cdr coord)))\n;; => (9 0 2)\n\n;; or destructure coord:\n(multiple-value-bind (coord val) (find-max-location '((0 1 9) (4 5) (6 7 8)))\n (destructuring-bind (x . y) coord\n (list val x y)))\n max-val list-of-list"
},
{
"answer_id": 74598958,
"author": "coredump",
"author_id": 124319,
"author_profile": "https://Stackoverflow.com/users/124319",
"pm_score": 1,
"selected": false,
"text": "indexed-list-fold reduce fold_left loop (defun indexed-list-fold (function accumulator list)\n (loop\n :for acc = accumulator :then res\n :for elt :in list\n :for idx :from 0\n :for res = (funcall function acc elt idx)\n :finally (return acc)))\n for/then for elt in list acc nil accumulator (defun find-max-location-in-list (list)\n (flet ((fold (max.pos elt idx)\n (let ((max (car max.pos)))\n (if (or (null max) (< max elt))\n (cons elt idx)\n max.pos))))\n (indexed-list-fold #'fold (cons nil nil) list)))\n > (find-max-location-in-list '(1 3 8 3 12 -4 -200))\n(12 . 4)\n fold indexed-list-fold labels (defun find-max-location-in-tree (tree)\n (labels ((fold (max.pos elt idx)\n (let ((idx (alexandria:ensure-list idx)))\n (etypecase elt\n (real (let ((max (car max.pos)))\n (if (or (null max) (< max elt))\n (cons elt idx)\n max.pos)))\n (list \n (indexed-list-fold (lambda (max.pos elt child)\n (fold max.pos elt (cons child idx)))\n max.pos\n elt))))))\n (indexed-list-fold #'fold (cons nil nil) tree)))\n elt idx > (find-max-location-in-tree '(1 3 8 3 12 -4 -200))\n(12 4)\n cdr > (find-max-location-in-tree '((0 1 0 0 1)\n (0 2 2 0 0)\n (3 0 1 4 7)\n (0 1 2 0 0)\n (1 2 1 0 3)))\n(7 4 2)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17971741/"
] |
74,540,592
|
<p>I want to convert the long to wide format of my data using data.table. Normally I use <code>unstack()</code>, but I don't know how to do it in data.table. Below is an example. As output I expect three columns and three rows.</p>
<pre><code>library(data.table)
set.seed(1)
df <- data.frame(class = factor(rep(c("A", "B", "C"), times = 3)),
value = runif(9))
unstack(df, form = value ~ class)
#> A B C
#> 1 0.2655087 0.3721239 0.5728534
#> 2 0.9082078 0.2016819 0.8983897
#> 3 0.9446753 0.6607978 0.6291140
dt <- data.table(df)
dcast(dt, formula = value ~ class, value.var = "value")
#> value A B C
#> 1: 0.2016819 NA 0.2016819 NA
#> 2: 0.2655087 0.2655087 NA NA
#> 3: 0.3721239 NA 0.3721239 NA
#> 4: 0.5728534 NA NA 0.5728534
#> 5: 0.6291140 NA NA 0.6291140
#> 6: 0.6607978 NA 0.6607978 NA
#> 7: 0.8983897 NA NA 0.8983897
#> 8: 0.9082078 0.9082078 NA NA
#> 9: 0.9446753 0.9446753 NA NA
</code></pre>
<p>Additionally, I don't want to use an aggregate function, but in data.table on real data I see: <code>Aggregate function missing, defaulting to 'length'</code>, so there are fewer rows in the result.</p>
|
[
{
"answer_id": 74540750,
"author": "M.Viking",
"author_id": 10276092,
"author_profile": "https://Stackoverflow.com/users/10276092",
"pm_score": 3,
"selected": true,
"text": "dcast(dt, rowid(class) ~ class)\n# class A B C\n#1: 1 0.2655087 0.3721239 0.5728534\n#2: 2 0.9082078 0.2016819 0.8983897\n#3: 3 0.9446753 0.6607978 0.6291140\n"
},
{
"answer_id": 74544789,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "split dt dcast > dt[, split(value, class)]\n A B C\n1: 0.2655087 0.3721239 0.5728534\n2: 0.9082078 0.2016819 0.8983897\n3: 0.9446753 0.6607978 0.6291140\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11868027/"
] |
74,540,601
|
<p>I am struggling in a python undergraduate class that should have had fewer modules: for a grade, I have a code that reads a formatted file and "prints" a table. The problem is, the last entry of the table has a trailing space at the end. My print statement is</p>
<pre><code>for time in movieTiming[m]:
print(time, end=" ")
</code></pre>
<p>I really have no idea what to do here: i have a list that contains something like "11:30", "10:30", "9:00", and it should be printed as 11:30 10:30 9:00 (with no space after the 9:00). I have tried to join my list, but really, most of the concepts I need to do all of this were never even communicated or taught in the class. I guess that's how it goes, but I'm struggling. My approach is to appropriate existing code, try to understand it, and learn that way, but it's not making any sense to me.</p>
<p>I am taking Java I at the same time, and Java makes sense to me because the pace of the Java course is about 1/2 of the pace of the Python class: 2x the modules means 1/2 the time. If anyone can help, thank you.</p>
<p>Here's what I have (I'll remove the notes if it's not helpful?)</p>
<pre><code># First we open the file named "movies.csv" using the open()
f = open(input())
# f.readlines() reads the contents of the file and stores each line as a separate element in a list named movies.
movies = f.readlines()
# Next we declare 2 dictionaries named movieTiming and movieRating.
# movieTiming will store the timing of each movie.
# The key would be the movie name and the value would be the list of timings of the movie.
movieTiming = {}
# movieRating will store the rating of each movie.
# key would be the movie name and the value would be the rating of the respective movie.
movieRating = {}
# Now we traverse through the movies list to fill our dictionaries.
for m in movies:
# First we split each line into 3 parts that is, we split the line whenever a comma(",") occurs.
# split(",") would return a list of splitted words.
# For example: when we split "16:40,Wonders of the World,G", it returns a list ["16:40","Wonders of the World","G"]
movieDetails = m.split(",")
# movieDetails[1] indicates the movie name.
# So if the movie name is not present in the dictionary then we initialize the value with an empty list.
#need a for loop
if(movieDetails[1] not in movieTiming):
movieTiming[movieDetails[1]] = []
# movieDetails[0] indicates the timing of the movie.
# We append the time to the existing list of the movie.
movieTiming[movieDetails[1]].append(movieDetails[0])
# movieDetails[2] indicates the rating of the movie.
# We use strip() since a new line character will be appended at the end of the movie rating.
# So to remove the new line character at the end we use strip() and we assign the rating to the respective movie.
movieRating[movieDetails[1]] = movieDetails[2].strip()
# Now we traverse the movieRating dictionary.
for m in movieRating:
# In -44.44s, negative sign indicates left justification.
# 44 inidcates the width assigned to movie name.
# .44 indicates the number of characters allowed for the movie name.
# s indicates the data type string.
# print() generally prints a message and prints a new line at the end.
# So to avoid this and print the movie name, rating and timing in the same line, we use end=" "
# end is used to print all in the same line separated by a space.
print("%-44.44s"%m,"|","%5s"%movieRating[m],"|",end=" ")
# Now we traverse through the movieTiming[m] which indicates the list of timing for the particular movie m.
for time in movieTiming[m]:
print(time, end=" ")
# This print() will print a new line to print the next movie details in the new line.
print()
</code></pre>
|
[
{
"answer_id": 74540658,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 1,
"selected": false,
"text": "print ' '.join print(' '.join(movieTiming[m]))\n join print(movieTiming[m][0], end='')\nfor t in movieTiming[m][1:]:\n print(f' {t}', end=''\nprint()\n str.join"
},
{
"answer_id": 74540659,
"author": "Adrian Kurzeja",
"author_id": 8571154,
"author_profile": "https://Stackoverflow.com/users/8571154",
"pm_score": 1,
"selected": true,
"text": "my_list = ['11:00', '12:30', '13:00']\n\njoined = ' '.join(my_list)\n\nprint(joined)\n# 11:00 12:30 13:00\n"
},
{
"answer_id": 74540687,
"author": "str1ng",
"author_id": 12826055,
"author_profile": "https://Stackoverflow.com/users/12826055",
"pm_score": 0,
"selected": false,
"text": "time = [\"19:30\",\"19:00\",\"18:00\"]\n print(*time)\n print(*time, sep=', ')\n str.join() joined_string = ' '.join([str(v) for v in time])\nprint(joined_string)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20577208/"
] |
74,540,610
|
<p>Hi how can I display selected folder name in textbox. I have 3 Folder. It display the 2 folders in the textbox but the other one it won't display.</p>
<p>For example:</p>
<blockquote>
<p>C:\EmpRecord\Details\Name\MiddleName\Lastname</p>
</blockquote>
<p>The 2 folder name display without a problem.</p>
<p>For the Middlename here's the code:</p>
<pre><code>middleName.Text = Path.GetFileName(Path.GetDirectoryName(folderBrowserDialog1.SelectedPath));
</code></pre>
<p>Lastname:</p>
<pre><code>lastName.Text = new DirectoryInfo(folderBrowserDialog1.SelectedPath).Name;
</code></pre>
<p>For the <strong>Name</strong> it doesn't display in the textbox. How can I display it in textbox?</p>
|
[
{
"answer_id": 74540658,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 1,
"selected": false,
"text": "print ' '.join print(' '.join(movieTiming[m]))\n join print(movieTiming[m][0], end='')\nfor t in movieTiming[m][1:]:\n print(f' {t}', end=''\nprint()\n str.join"
},
{
"answer_id": 74540659,
"author": "Adrian Kurzeja",
"author_id": 8571154,
"author_profile": "https://Stackoverflow.com/users/8571154",
"pm_score": 1,
"selected": true,
"text": "my_list = ['11:00', '12:30', '13:00']\n\njoined = ' '.join(my_list)\n\nprint(joined)\n# 11:00 12:30 13:00\n"
},
{
"answer_id": 74540687,
"author": "str1ng",
"author_id": 12826055,
"author_profile": "https://Stackoverflow.com/users/12826055",
"pm_score": 0,
"selected": false,
"text": "time = [\"19:30\",\"19:00\",\"18:00\"]\n print(*time)\n print(*time, sep=', ')\n str.join() joined_string = ' '.join([str(v) for v in time])\nprint(joined_string)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20267940/"
] |
74,540,614
|
<p>I have a SQL table <code>Products</code> with 2 columns as below.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>ProductDetails</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td><code><XML></code></td>
</tr>
<tr>
<td>3</td>
<td><code><XML></code></td>
</tr>
</tbody>
</table>
</div>
<p>The XML column holds the following data:</p>
<pre><code><Products>
<product key="0" description="">Product1</product>
<product key="1" description="">Product2</product>
<product key="2" description="">Product3</product>
<product key="3" description="">Product4</product>
<product key="4" description="">Product5</product>
<product key="5" description="">Product6</product>
<product key="6" description="">Product7</product>
<product key="7" description="">Product8</product>
</Products>
</code></pre>
<p>How can I get the relevant node from the <code>ProductDetails</code> for <code>ProductTitle</code>?</p>
<p>For example: if the <code>ID</code> column has 3, I need to query the <code>ProductDetails</code> column and create a new column with just the <code>ProductTitle</code> to be <code>Product3</code>.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>ProductDetails</th>
<th>ProductTitle</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td><code><XML></code></td>
<td>Product5</td>
</tr>
<tr>
<td>3</td>
<td><code><XML></code></td>
<td>Product3</td>
</tr>
</tbody>
</table>
</div>
<p>Any help would be appreciated.</p>
|
[
{
"answer_id": 74540841,
"author": "T N",
"author_id": 12637193,
"author_profile": "https://Stackoverflow.com/users/12637193",
"pm_score": 0,
"selected": false,
"text": ".nodes() .value() SELECT P.*, X.N.value('text()[1]', 'nvarchar(max)')\nFROM @Products P\nCROSS APPLY @ProductXml.nodes('/Products/product[@key=sql:column(\"P.ID\")]') X(N)\n SELECT P.*, PN.ProductName\nFROM @Products P\nCROSS APPLY (\n SELECT ProductName = X.N.value('text()[1]', 'nvarchar(max)')\n FROM @ProductXml.nodes('/Products/product[@key=sql:column(\"P.ID\")]') X(N)\n) PN\n SELECT P.*, PN.ProductName\nFROM @Products P\nJOIN (\n SELECT\n ProductKey = X.N.value('@key', 'nvarchar(max)'),\n ProductName = X.N.value('text()[1]', 'nvarchar(max)')\n FROM @ProductXml.nodes('/Products/product') X(N)\n) PN ON PN.ProductKey = P.ID\n /Products/product [@key = ...] key sql:column(\"P.ID\") text() [1] nvarchar(max) .value()"
},
{
"answer_id": 74540893,
"author": "Yitzhak Khabinsky",
"author_id": 1932311,
"author_profile": "https://Stackoverflow.com/users/1932311",
"pm_score": 3,
"selected": true,
"text": "-- DDL and sample data population, start\nDECLARE @tbl TABLE (ID INT PRIMARY KEY, ProductDetails XML);\nINSERT @tbl (ID, ProductDetails) VALUES\n(3, N'<Products>\n <product key=\"0\" description=\"\">Product1</product>\n <product key=\"1\" description=\"\">Product2</product>\n <product key=\"2\" description=\"\">Product3</product>\n <product key=\"3\" description=\"\">Product4</product>\n <product key=\"4\" description=\"\">Product5</product>\n <product key=\"5\" description=\"\">Product6</product>\n <product key=\"6\" description=\"\">Product7</product>\n <product key=\"7\" description=\"\">Product8</product>\n</Products>');\n-- DDL and sample data population, end\n\nSELECT ID \n , ProductDetails.value('(/Products/product[@key=sql:column(\"ID\")]/text())[1]','VARCHAR(20)') AS ProductTitle\nFROM @tbl;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4045046/"
] |
74,540,632
|
<p>Here's the code that's causing the issue:</p>
<pre><code>DROP TABLE customers;
--1 create tables
CREATE TABLE customers (
customer_id NUMBER(10),
last_name VARCHAR2(25),
first_name VARCHAR2(25),
home_phone VARCHAR2(12),
address VARCHAR2(100),
city VARCHAR2(30),
state VARCHAR2(2),
email VARCHAR2(25),
cell_phone VARCHAR2(12),
CONSTRAINT pk_customer_customer_id PRIMARY KEY (customer_id),
CONSTRAINT not_null_customer_last_name NOT NULL (last_name),
CONSTRAINT not_null_customer_first_name NOT NULL (first_name),
CONSTRAINT not_null_customer_home_phone NOT NULL (home_phone),
CONSTRAINT not_null_customer_address NOT NULL (address),
CONSTRAINT not_null_customer_city NOT NULL (city),
CONSTRAINT not_null_customer_state NOT NULL (state)
);
</code></pre>
<p>I've tried formatting the constraints at the column level and that didn't seem to help. I'm an absolute beginner and am doing this for a class so I'm sure it's something simple and silly but I couldn't figure it out for the life of me. After a few hours of frustration I figured I'd see if there was someone out there who could point me in the right direction.</p>
<p>I am using Oracle APEX.</p>
|
[
{
"answer_id": 74540841,
"author": "T N",
"author_id": 12637193,
"author_profile": "https://Stackoverflow.com/users/12637193",
"pm_score": 0,
"selected": false,
"text": ".nodes() .value() SELECT P.*, X.N.value('text()[1]', 'nvarchar(max)')\nFROM @Products P\nCROSS APPLY @ProductXml.nodes('/Products/product[@key=sql:column(\"P.ID\")]') X(N)\n SELECT P.*, PN.ProductName\nFROM @Products P\nCROSS APPLY (\n SELECT ProductName = X.N.value('text()[1]', 'nvarchar(max)')\n FROM @ProductXml.nodes('/Products/product[@key=sql:column(\"P.ID\")]') X(N)\n) PN\n SELECT P.*, PN.ProductName\nFROM @Products P\nJOIN (\n SELECT\n ProductKey = X.N.value('@key', 'nvarchar(max)'),\n ProductName = X.N.value('text()[1]', 'nvarchar(max)')\n FROM @ProductXml.nodes('/Products/product') X(N)\n) PN ON PN.ProductKey = P.ID\n /Products/product [@key = ...] key sql:column(\"P.ID\") text() [1] nvarchar(max) .value()"
},
{
"answer_id": 74540893,
"author": "Yitzhak Khabinsky",
"author_id": 1932311,
"author_profile": "https://Stackoverflow.com/users/1932311",
"pm_score": 3,
"selected": true,
"text": "-- DDL and sample data population, start\nDECLARE @tbl TABLE (ID INT PRIMARY KEY, ProductDetails XML);\nINSERT @tbl (ID, ProductDetails) VALUES\n(3, N'<Products>\n <product key=\"0\" description=\"\">Product1</product>\n <product key=\"1\" description=\"\">Product2</product>\n <product key=\"2\" description=\"\">Product3</product>\n <product key=\"3\" description=\"\">Product4</product>\n <product key=\"4\" description=\"\">Product5</product>\n <product key=\"5\" description=\"\">Product6</product>\n <product key=\"6\" description=\"\">Product7</product>\n <product key=\"7\" description=\"\">Product8</product>\n</Products>');\n-- DDL and sample data population, end\n\nSELECT ID \n , ProductDetails.value('(/Products/product[@key=sql:column(\"ID\")]/text())[1]','VARCHAR(20)') AS ProductTitle\nFROM @tbl;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17654954/"
] |
74,540,633
|
<p>For example:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Team</th>
<th>User</th>
</tr>
</thead>
<tbody>
<tr>
<td>USA</td>
<td>Mark</td>
</tr>
<tr>
<td>England</td>
<td>Sean</td>
</tr>
<tr>
<td>India</td>
<td>Sri</td>
</tr>
</tbody>
</table>
</div>
<p>assigning users to different teams randomly</p>
|
[
{
"answer_id": 74540841,
"author": "T N",
"author_id": 12637193,
"author_profile": "https://Stackoverflow.com/users/12637193",
"pm_score": 0,
"selected": false,
"text": ".nodes() .value() SELECT P.*, X.N.value('text()[1]', 'nvarchar(max)')\nFROM @Products P\nCROSS APPLY @ProductXml.nodes('/Products/product[@key=sql:column(\"P.ID\")]') X(N)\n SELECT P.*, PN.ProductName\nFROM @Products P\nCROSS APPLY (\n SELECT ProductName = X.N.value('text()[1]', 'nvarchar(max)')\n FROM @ProductXml.nodes('/Products/product[@key=sql:column(\"P.ID\")]') X(N)\n) PN\n SELECT P.*, PN.ProductName\nFROM @Products P\nJOIN (\n SELECT\n ProductKey = X.N.value('@key', 'nvarchar(max)'),\n ProductName = X.N.value('text()[1]', 'nvarchar(max)')\n FROM @ProductXml.nodes('/Products/product') X(N)\n) PN ON PN.ProductKey = P.ID\n /Products/product [@key = ...] key sql:column(\"P.ID\") text() [1] nvarchar(max) .value()"
},
{
"answer_id": 74540893,
"author": "Yitzhak Khabinsky",
"author_id": 1932311,
"author_profile": "https://Stackoverflow.com/users/1932311",
"pm_score": 3,
"selected": true,
"text": "-- DDL and sample data population, start\nDECLARE @tbl TABLE (ID INT PRIMARY KEY, ProductDetails XML);\nINSERT @tbl (ID, ProductDetails) VALUES\n(3, N'<Products>\n <product key=\"0\" description=\"\">Product1</product>\n <product key=\"1\" description=\"\">Product2</product>\n <product key=\"2\" description=\"\">Product3</product>\n <product key=\"3\" description=\"\">Product4</product>\n <product key=\"4\" description=\"\">Product5</product>\n <product key=\"5\" description=\"\">Product6</product>\n <product key=\"6\" description=\"\">Product7</product>\n <product key=\"7\" description=\"\">Product8</product>\n</Products>');\n-- DDL and sample data population, end\n\nSELECT ID \n , ProductDetails.value('(/Products/product[@key=sql:column(\"ID\")]/text())[1]','VARCHAR(20)') AS ProductTitle\nFROM @tbl;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20577197/"
] |
74,540,642
|
<p>I keep reading things like <a href="https://www.reddit.com/r/FlutterDev/comments/a53afv/when_should_we_extend_an_existing_component/" rel="nofollow noreferrer">this post</a> explaining how Flutter heavily prefers composition over inheritance. While I partially understand why, I question what to do in scenarios where this practice becomes verbose. Plus, in Flutter's internal code, there's inheritance all over the place for built-in components. So philosophically, there must be scenarios when it is okay.</p>
<p>Consider this example (based on a real <code>Widget</code> I made):</p>
<pre class="lang-dart prettyprint-override"><code>class MyFadingAnimation extends StatefulWidget {
final bool activated;
final Duration duration;
final Curve curve;
final Offset transformOffsetStart;
final Offset transformOffsetEnd;
final void Function()? onEnd;
final Widget? child;
const MyFadingAnimation({
super.key,
required this.activated,
this.duration = const Duration(milliseconds: 500),
this.curve = Curves.easeOut,
required this.transformOffsetStart,
this.transformOffsetEnd = const Offset(0, 0),
this.onEnd,
this.child,
});
@override
State<MyFadingAnimation> createState() => _MyFadingAnimationBuilder();
}
class _MyFadingAnimationBuilder extends State<MyFadingAnimation> {
@override
Widget build(BuildContext context) {
return AnimatedContainer(
duration: widget.duration,
curve: widget.curve,
transform: Transform.translate(
offset: widget.activated ?
widget.transformOffsetStart : widget.transformOffsetEnd,
).transform,
onEnd: widget.onEnd,
child: AnimatedOpacity(
duration: widget.duration,
curve: widget.curve,
opacity: widget.activated ? 1 : 0,
child: widget.child
),
);
}
}
</code></pre>
<p>The goal of <code>MyFadingAnimation</code> is to perform both a translation and opacity animation on a <code>Widget</code> simultaneously. Great!</p>
<p>Now, let's say I wanted to make some "shortcuts" or "aliases" to this widget, like <code>MyHorizontalAnimation</code> for fading in horizontally, or <code>MyVerticalAnimation</code> for fading in vertically. Using composition, you would have to create something like this:</p>
<pre class="lang-dart prettyprint-override"><code>class MyHorizontalAnimation extends StatelessWidget {
final bool activated;
final Duration duration;
final Curve curve;
final double offsetStart;
final void Function()? onEnd;
final Widget? child;
const MyHorizontalAnimation({
super.key,
required this.activated,
this.duration = const Duration(milliseconds: 500),
this.curve = Curves.easeOut,
required this.offsetStart,
this.onEnd,
this.child,
});
@override
Widget build(BuildContext context) {
return MyFadingAnimation(
activated: activated,
duration: duration,
curve: curve,
transformOffsetStart: Offset(offsetStart, 0),
onEnd: onEnd,
child: child,
);
}
}
</code></pre>
<p>That seems... very verbose to me. So my initial thought was "well, maybe I should just try extending the class anyway..."</p>
<pre class="lang-dart prettyprint-override"><code>class MyHorizontalAnimation extends MyFadingAnimation {
final double offsetStart;
MyHorizontalAnimation({
super.key,
required super.activated,
super.duration,
super.curve,
this.offsetStart,
super.onEnd,
super.child,
}) : super(
transformOffsetStart: Offset(offsetStart, 0),
);
}
</code></pre>
<p>To me this looks cleaner. Plus it carries the added benefit that if I added functionality/props to <code>MyFadingAnimation</code>, it's <em>almost</em> automatically integrated into <code>MyHorizontalAnimation</code> (with the exception of having to add <code>super.newProp</code>). With the composition approach, I'd have to add a new property, possibly copy/maintain a default, add it to the constructor, and by the time I'm done it just feels like a chore.</p>
<p>My main issue with using inheritance though (and this is probably really petty) is I can't have a <code>const</code> constructor for anything except my base widget, <code>MyFadingAnimation</code>. That, coupled with the <em>strong</em> discouragement of inheritance, makes me feel like there's a better way.</p>
<p>So, to sum everything up, here are my two questions:</p>
<ol>
<li>How should I organize my code above to have <code>const</code> <code>Widget</code>s that redirect to other "base" <code>Widget</code>s?</li>
<li>When is it okay to use inheritance over composition? Is there a good rule of thumb for this?</li>
</ol>
|
[
{
"answer_id": 74540841,
"author": "T N",
"author_id": 12637193,
"author_profile": "https://Stackoverflow.com/users/12637193",
"pm_score": 0,
"selected": false,
"text": ".nodes() .value() SELECT P.*, X.N.value('text()[1]', 'nvarchar(max)')\nFROM @Products P\nCROSS APPLY @ProductXml.nodes('/Products/product[@key=sql:column(\"P.ID\")]') X(N)\n SELECT P.*, PN.ProductName\nFROM @Products P\nCROSS APPLY (\n SELECT ProductName = X.N.value('text()[1]', 'nvarchar(max)')\n FROM @ProductXml.nodes('/Products/product[@key=sql:column(\"P.ID\")]') X(N)\n) PN\n SELECT P.*, PN.ProductName\nFROM @Products P\nJOIN (\n SELECT\n ProductKey = X.N.value('@key', 'nvarchar(max)'),\n ProductName = X.N.value('text()[1]', 'nvarchar(max)')\n FROM @ProductXml.nodes('/Products/product') X(N)\n) PN ON PN.ProductKey = P.ID\n /Products/product [@key = ...] key sql:column(\"P.ID\") text() [1] nvarchar(max) .value()"
},
{
"answer_id": 74540893,
"author": "Yitzhak Khabinsky",
"author_id": 1932311,
"author_profile": "https://Stackoverflow.com/users/1932311",
"pm_score": 3,
"selected": true,
"text": "-- DDL and sample data population, start\nDECLARE @tbl TABLE (ID INT PRIMARY KEY, ProductDetails XML);\nINSERT @tbl (ID, ProductDetails) VALUES\n(3, N'<Products>\n <product key=\"0\" description=\"\">Product1</product>\n <product key=\"1\" description=\"\">Product2</product>\n <product key=\"2\" description=\"\">Product3</product>\n <product key=\"3\" description=\"\">Product4</product>\n <product key=\"4\" description=\"\">Product5</product>\n <product key=\"5\" description=\"\">Product6</product>\n <product key=\"6\" description=\"\">Product7</product>\n <product key=\"7\" description=\"\">Product8</product>\n</Products>');\n-- DDL and sample data population, end\n\nSELECT ID \n , ProductDetails.value('(/Products/product[@key=sql:column(\"ID\")]/text())[1]','VARCHAR(20)') AS ProductTitle\nFROM @tbl;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20027466/"
] |
74,540,663
|
<p>I added this to the csproj file</p>
<pre class="lang-xml prettyprint-override"><code><ItemGroup>
<None Update="Assets/*">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</code></pre>
<p>so I can access the asset folder after an install.</p>
<p>However, I can not find any documentation or help on how to access these files. I found this page:
<a href="https://learn.microsoft.com/en-us/uwp/api/windows.storage.storagefolder.getfolderfrompathasync?view=winrt-22621" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/uwp/api/windows.storage.storagefolder.getfolderfrompathasync?view=winrt-22621</a>
, but when I try it out, this line throws an InvalidOperationException</p>
<pre class="lang-cs prettyprint-override"><code>string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
</code></pre>
|
[
{
"answer_id": 74540841,
"author": "T N",
"author_id": 12637193,
"author_profile": "https://Stackoverflow.com/users/12637193",
"pm_score": 0,
"selected": false,
"text": ".nodes() .value() SELECT P.*, X.N.value('text()[1]', 'nvarchar(max)')\nFROM @Products P\nCROSS APPLY @ProductXml.nodes('/Products/product[@key=sql:column(\"P.ID\")]') X(N)\n SELECT P.*, PN.ProductName\nFROM @Products P\nCROSS APPLY (\n SELECT ProductName = X.N.value('text()[1]', 'nvarchar(max)')\n FROM @ProductXml.nodes('/Products/product[@key=sql:column(\"P.ID\")]') X(N)\n) PN\n SELECT P.*, PN.ProductName\nFROM @Products P\nJOIN (\n SELECT\n ProductKey = X.N.value('@key', 'nvarchar(max)'),\n ProductName = X.N.value('text()[1]', 'nvarchar(max)')\n FROM @ProductXml.nodes('/Products/product') X(N)\n) PN ON PN.ProductKey = P.ID\n /Products/product [@key = ...] key sql:column(\"P.ID\") text() [1] nvarchar(max) .value()"
},
{
"answer_id": 74540893,
"author": "Yitzhak Khabinsky",
"author_id": 1932311,
"author_profile": "https://Stackoverflow.com/users/1932311",
"pm_score": 3,
"selected": true,
"text": "-- DDL and sample data population, start\nDECLARE @tbl TABLE (ID INT PRIMARY KEY, ProductDetails XML);\nINSERT @tbl (ID, ProductDetails) VALUES\n(3, N'<Products>\n <product key=\"0\" description=\"\">Product1</product>\n <product key=\"1\" description=\"\">Product2</product>\n <product key=\"2\" description=\"\">Product3</product>\n <product key=\"3\" description=\"\">Product4</product>\n <product key=\"4\" description=\"\">Product5</product>\n <product key=\"5\" description=\"\">Product6</product>\n <product key=\"6\" description=\"\">Product7</product>\n <product key=\"7\" description=\"\">Product8</product>\n</Products>');\n-- DDL and sample data population, end\n\nSELECT ID \n , ProductDetails.value('(/Products/product[@key=sql:column(\"ID\")]/text())[1]','VARCHAR(20)') AS ProductTitle\nFROM @tbl;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13264143/"
] |
74,540,688
|
<p>How can I get the value of param2 based on name in angular?</p>
<p>http://localhost:4200/home#parma1=value1&param2=value2&param3=value3</p>
<p>Tried Below:</p>
<pre><code>constructor(
private router: Router,
private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.queryParams
.subscribe(params => {
console.log(params); // Out put : {}
}
);
console.log(this.router.url); // Output : /home#parma1=value1&param2=value2&param3=value3
</code></pre>
<p>}</p>
<p>Is there any standard approach to get the parameters when parameters separated with <code>#</code> instead of <code>?</code> ?</p>
|
[
{
"answer_id": 74541916,
"author": "bhathiya.m",
"author_id": 1080820,
"author_profile": "https://Stackoverflow.com/users/1080820",
"pm_score": 0,
"selected": false,
"text": "this.route.queryParams.subscribe(params => { this.name = params['name']; });"
},
{
"answer_id": 74542624,
"author": "Stacks Queue",
"author_id": 14820590,
"author_profile": "https://Stackoverflow.com/users/14820590",
"pm_score": 1,
"selected": false,
"text": "activatedRoute ? URLSearchParams param2 const params = new URLSearchParams(\"http://localhost:4200/home#parma1=value1¶m2=value2¶m3=value3\");\n\nconst param2 = params.get(\"param2\");\nconsole.log(param2)"
},
{
"answer_id": 74545924,
"author": "Chady BAGHDADI",
"author_id": 16227834,
"author_profile": "https://Stackoverflow.com/users/16227834",
"pm_score": 0,
"selected": false,
"text": "ngOnInit(): void {\nthis.route.queryParamMap\n .subscribe(params => {\n console.log(params);\n }\n)\n let param1 = this.route.snapshot.queryParamMap.get('param1')\n"
},
{
"answer_id": 74558339,
"author": "Jimmy",
"author_id": 4960765,
"author_profile": "https://Stackoverflow.com/users/4960765",
"pm_score": 0,
"selected": false,
"text": "fragment this.activatedRoute.fragment\n .subscribe(frgmt => {\n console.log(frgmt); // Output (type string): parma1=value1¶m2=value2¶m3=value3' \n }\n);\n param matrix"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4689560/"
] |
74,540,719
|
<p>When I click the submit button on my form the value of Submit is not displaying and at the same time my input fields at the top are still not autofilling like I'd like them to. I'm also trying to use the eye icon to hide the value on post request and clicking the eye icon will reveal the value on textbox.</p>
<p>index.cshtml</p>
<pre><code>@page "{id?}"
@model IndexModel
@{ViewData["Title"] = "Main";}
<div class=" container">
<div class="row">
<div class="text-center">
<h1 class="display-4">@Model.PageTitle</h1>
</div>
</div>
<div class="row">
<form class="mt-0" method="get">
<div class="row">
<div class="col-3 offset-2" id="DepartmentResult"></div>
<div class="col-4" id="EmployeeResult"></div>
</div>
</form>
<form class="mt=0" method="post">
<div class="row">
<label class="col-2 offset-3 col-form-label">Employee Name:</label>
<div class="col-2">
<input class="form-control" title="Employee name" asp-for="Name">
</div>
</div>
<br />
<div class="row">
<label class="col-2 offset-3 col-form-label">Department Name:</label>
<div class="col-2">
<input class="form-control" title="Department name" asp-for="DeptName">
</div>
</div>
<br />
<div class="row">
<button class="btn btn-outline-dark col-1 offset-5" type="submit" id="SubmitBtn" name="SubmitBtn" value="Submit" asp-page-handler="Submit">Submit</button>
</div>
<br />
<div class="row">
<div col-4>
<br />
<div class=" row">
<label class="col-6 col-form-label">Social Security #:</label>
<div class="col-5">
<input class="form-control" type="text" asp-for="OutputSSN" disabled />
<i class="fa fa-eye-slash"></i>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
@section Scripts {
<script>
$(document).ready(function()
{
$.ajax(
{
url: "/Index?handler=DisplayDepartment",
type: "GET",
data: { value: @Model.Id },
headers: { RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val() },
success: function(data) { $("#DepartmentResult").html(data); }
});
});
</script>
}
</code></pre>
<p>index.cs</p>
<pre><code>using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using PracticeApp.Models;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
// Namespaces
namespace PracticeApp.Pages
{
// Classes
public class IndexModel : PageModel
{
// Fields
public CompanyContext _context;
// Properties
[BindProperty(SupportsGet = true)] public int Id { get; set; }
[BindProperty] public string PageTitle { get; set; } = "Employee Check";
public Employee CheckEmployee { get; set; }
[BindProperty, DataMember] public string Name { get; set; }
[BindProperty, DataMember] public string DeptName { get; set; }
public string OutputSSN { get; set; }
// Constructors
public IndexModel(CompanyContext context) { _context = context; }
// Methods
public PartialViewResult OnGetDisplayDepartment(int value) => Partial("_DisplayDepartmentPartial", _context.Departments.Where(x => x.DepartmentId == value).ToList());
public PartialViewResult OnGetDisplayEmployee(string value) => Partial("_DisplayEmployeePartial", _context.Employees.Where(x => x.DepartmentName == value).GroupBy(x => x.EmployeeName).Select(x => x.First()).ToList());
public async Task<IActionResult> OnPostSubmit()
{
OutputSSN = $"{SubstringCheck(OutputSSN, 3)}-{SubstringCheck(OutputSSN, 3, 2)}-{SubstringCheck(OutputSSN, 5, 4)}";
return Page();
}
public string SubstringCheck(string s, int length)
{
int len = s.Length;
if (len > length)
{
len = length;
}
return s.Substring(0, len);
}
public string SubstringCheck(string s, int b, int length)
{
int len = s.Length;
if (len <= b)
{
return s;
}
len -= b;
if (len > length)
{
len = length;
}
return s.Substring(b, len);
}
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/gbmCH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gbmCH.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/kr5XV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kr5XV.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/bs2bT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bs2bT.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74541916,
"author": "bhathiya.m",
"author_id": 1080820,
"author_profile": "https://Stackoverflow.com/users/1080820",
"pm_score": 0,
"selected": false,
"text": "this.route.queryParams.subscribe(params => { this.name = params['name']; });"
},
{
"answer_id": 74542624,
"author": "Stacks Queue",
"author_id": 14820590,
"author_profile": "https://Stackoverflow.com/users/14820590",
"pm_score": 1,
"selected": false,
"text": "activatedRoute ? URLSearchParams param2 const params = new URLSearchParams(\"http://localhost:4200/home#parma1=value1¶m2=value2¶m3=value3\");\n\nconst param2 = params.get(\"param2\");\nconsole.log(param2)"
},
{
"answer_id": 74545924,
"author": "Chady BAGHDADI",
"author_id": 16227834,
"author_profile": "https://Stackoverflow.com/users/16227834",
"pm_score": 0,
"selected": false,
"text": "ngOnInit(): void {\nthis.route.queryParamMap\n .subscribe(params => {\n console.log(params);\n }\n)\n let param1 = this.route.snapshot.queryParamMap.get('param1')\n"
},
{
"answer_id": 74558339,
"author": "Jimmy",
"author_id": 4960765,
"author_profile": "https://Stackoverflow.com/users/4960765",
"pm_score": 0,
"selected": false,
"text": "fragment this.activatedRoute.fragment\n .subscribe(frgmt => {\n console.log(frgmt); // Output (type string): parma1=value1¶m2=value2¶m3=value3' \n }\n);\n param matrix"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9748930/"
] |
74,540,761
|
<p>I am trying to save a csv generated from a table.</p>
<p>If I 'Export all as CSV' from QPAD the file is 22MB.</p>
<p>If I do <code> `:path.csv 0: csv 0: table</code> the file is 496MB.</p>
<p>The file contains same data.</p>
<p>I do have some columns which are list of dates, list of symbols which cause some issues when parsing to csv.</p>
<p>To get over that I use this <code>{`$$[1=count x;string first x;`$" "sv string x]}</code></p>
<p>i.e. one of the cols is called allDates and looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>someOtherCol</th>
<th>allDates</th>
<th>stackedSymCol</th>
</tr>
</thead>
<tbody>
<tr>
<td>val1</td>
<td>, 2001.01.01</td>
<td>, `sym 1</td>
</tr>
<tr>
<td>val2</td>
<td>2001.01.01 2001.01.02</td>
<td>`sym 2`sym 3</td>
</tr>
</tbody>
</table>
</div>
<p>Where is this massive difference in size coming from and how can I reduce the the size.</p>
<p>If I remove these 3 columns which are lists of lists, the file goes down significantly.</p>
<p>Doing an <code>ungroup</code> is not an option.</p>
<p>I think the important question here is why is QPAD capable to handle columns which are lists of lists of type 'D' 'S' etc and how I can achieve that without casting those columns to a space delimited string. This is what is causing my saved csv to be so massive.</p>
<p>ie. I can do an 'Export all to csv' from QPAD on this and it is 21MB :
<a href="https://i.stack.imgur.com/od0Wx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/od0Wx.png" alt="enter image description here" /></a></p>
<p>but if I want to save it programatically, I need to change those allDates and DESK_NAME column and it goes up to 500MB</p>
<p>UPDATE: Thanks everyone. I did not know that QPAD is truncating data like that on exports. That is worrying.</p>
|
[
{
"answer_id": 74545042,
"author": "Matt Moore",
"author_id": 11828860,
"author_profile": "https://Stackoverflow.com/users/11828860",
"pm_score": 3,
"selected": false,
"text": "([]a:3#enlist til 1000;b:3#enlist til 1000)\n 30j, 31j ..."
},
{
"answer_id": 74545830,
"author": "Thomas Smyth - Treliant",
"author_id": 5620913,
"author_profile": "https://Stackoverflow.com/users/5620913",
"pm_score": 3,
"selected": true,
"text": "enlist q)example:{n:1 2 20;([]someOtherCol:3?10;allDates:n?\\:.z.d;stackedSymCol:n?\\:`3)}[]\nq)example\nsomeOtherCol allDates\n stackedSymCol\n-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n1 ,2006.01.13\n ,`hfg\n1 2008.04.06 2008.01.11\n `nha`plc\n4 2009.06.12 2016.01.24 2021.02.02 2018.09.02 2011.06.19 2022.09.26 2008.10.29 2010.03.11 2022.07.30 2012.09.06 2021.11.27 2017.11.24 2007.09.10 2012.11.27 2020.03.10 2003.07.02 2007.11.29 2010.07.18 2001.10.23 2000.11.07 `ifd`jgp`eln`kkb`ahm`cal`eni`idj`mod`omb`dkc`ogf`eaj`mbf`kdd`hip`gkg`eef`edi`jak\n C:/q/qpad.csv q)f:{`$$[1=count x;string first x;\" \"sv string x]}\nq)`:C:/q/q.csv 0: csv 0: update f'[allDates], f'[stackedSymCol] from example\n q)a:read0`:C:/q/q.csv\nq)b:read0`:C:/q/qpad.csv\n\nq)a~b\n0b\n .h.cd .h.d q).h.d:\" \";\nq).h.cd example\n\"someOtherCol,allDates,stackedSymCol\"\n\"8,2013.09.10,pii\"\n\"6,2007.08.09 2012.12.30,hbg blg\"\n\"8,2011.04.04 2020.08.21 2006.02.12 2005.01.15 2016.05.31 2015.01.03 2021.12.09 2022.03.26 2013.10.15 2001.10.29 2011.02.17 2010.03.28 2005.11.14 2003.08.16 2002.04.20 2004.08.07 2014.09.19 2000.05.24 2018.06.19 2017.08.14,cim pgm gha chp dio gfc beh mbo cfe kec jbn bjh eni obf agb dce gnk jif pci ppc\"\n\nq)`:somefile.csv 0: .h.cd example\n q)read0`:C:/q/q.csv\n\"someOtherCol,allDates,stackedSymCol\"\n\"8,2013.09.10,pii\"\n\"6,2007.08.09 2012.12.30,hbg blg\"\n\"8,2011.04.04 2020.08.21 2006.02.12 2005.01.15 2016.05.31 2015.01.03 2021.12.09 2022.03.26 2013.10.15 2001.10.29 2011.02.17 2010.03.28 2005.11.14 2003.08.16 2002.04.20 2004.08.07 2014.09.19 2000.05.24 2018.06.19 2017.08.14,cim pgm gha chp dio gfc beh mbo cfe kec jbn bjh eni obf agb dce gnk jif pci ppc\"\n\nq)count raze read0`:C:/q/q.csv\n383\n q)read0`:C:/q/qpad.csv\n\"someOtherCol,allDates,stackedSymCol\"\n\"1,enlist 2006.01.13,enlist `hfg\"\n\"1,2008.04.06 2008.01.11,`nha`plc\"\n\"4,2009.06.12 2016.01.24 2021.02.02 2018.09.02 2011.06.19 2022.09.26 2008.10.29 2010.03.11 2022.07.30 2012.09.06 2021.11.27 2017.11.24 2007.09.10 2012.11.27 ...,`ifd`jgp`eln`kkb`ahm`cal`eni`idj`mod`omb`dkc`ogf`eaj`mbf`kdd`hip`gkg`eef`edi`jak\"\n\nq)count raze read0`:C:/q/qpad.csv\n338\n enlist"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4463305/"
] |
74,540,765
|
<p>I have to write a program that requests a file name from the user and then counts all of the words in the file. The hypothetical file has 55 words in it, but my program counts 56 words.</p>
<p>Every change I've tried making to my code has only gotten me farther from the correct answer, either resulting in 0 words or causing it to become an infinite loop. I'm seriously stuck on where the extra word/character is coming from, so I was hoping someone might see an error that I'm missing.</p>
<pre><code>#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char filename[20];
cout << "Enter a file name: ";
cin >> filename;
ifstream fin;
fin.open(filename);
if (fin.fail())
{
exit(1);
}
char next;
int word = 0;
while (fin)
{
fin.get(next);
if (next == ' ' || next == '\n')
word++;
}
fin.close();
cout << "The file contains " << word << " words.";
return 0;
}
</code></pre>
|
[
{
"answer_id": 74540928,
"author": "waltermitty",
"author_id": 8020836,
"author_profile": "https://Stackoverflow.com/users/8020836",
"pm_score": 0,
"selected": false,
"text": "#include <fstream>\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n char filename[20];\n\n cout << \"Enter a file name: \";\n cin >> filename;\n\n ifstream fin;\n fin.open(filename);\n if (fin.fail()) {\n exit(1);\n }\n\n char next;\n // When the last char in file is not newline or space,\n // we need to count the last word manually\n bool hasWord = false;\n int word = 0;\n\n while (fin) {\n fin.get(next);\n\n if (fin.fail()) {\n if (hasWord)\n word++;\n break;\n }\n if (next == ' ' || next == '\\n') {\n word++;\n hasWord = false;\n } else\n hasWord = true;\n }\n\n fin.close();\n\n cout << \"\\nThe file contains \" << word << \" words.\";\n\n return 0;\n}\n ifstream eof() eof() next fin.fail() eof()"
},
{
"answer_id": 74540995,
"author": "heemi98",
"author_id": 20577241,
"author_profile": "https://Stackoverflow.com/users/20577241",
"pm_score": -1,
"selected": false,
"text": "#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\nint main()\n{\n\nchar filename[20];\n\ncout << \"Enter a file name: \";\ncin >> filename;\n\nifstream fin;\nfin.open(filename);\nif (fin.fail())\n{\n exit(1);\n}\n\nstd::string word;\nint count = 0;\n\nwhile (fin >> word)\n{\n count++;\n}\n\nfin.close();\n\ncout << \"The file contains \" << count << \" words.\";\n\nreturn 0;\n\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20577241/"
] |
74,540,816
|
<p>I have the <strong>cars_tables</strong> and in its <strong>name</strong> column I have names with special characters, for example:</p>
<pre><code>car_names = Car.pluck :name
=> ["Cárrozería", "Óther Cars", "Forede Lúis", "Ságara Mbobe"]
</code></pre>
<p>The values are automatically parameterized making the special characters disappear</p>
<pre><code>car_name_parameterize << ["Cárrozería", "Óther Cars", "Forede Lúis", "Ságara Mbobe"].map { |name| name.parameterize }.join(', ')
=> ["carrozeria", "other-cars", "forede-luis", "sagara-mbobe"]
</code></pre>
<p>and with the parameterized values I would like to do a query but I can't since the names have special characters that prevent me from doing so</p>
<pre><code>first_car_name = car_name_parameterize.first
=> carrozeria
Car.find_by('name ILIKE ?', "%first_car_name%")
=> nil ;; nil because the word **carrozeria** doesn't have í special character,
Car.find_by_name "carrozería"
=> #<Car:0x300312318 id: 1, name: "carrozería"...> ;; If it does the query without returning nil but it is because I consulted its name manually when placing "carrozería"
</code></pre>
<p>In short, I am looking to make the queries with the columns with the same name but with special characters (usually these characters usually have accents) recognized.</p>
<p>I am looking to make queries to the name of the cars table, canceling the special characters, such as the accent between the words for example</p>
<p>I have also tried the gsub method without success.</p>
<p>If you could help me I would be very happy and thank you for taking the time to read me.</p>
|
[
{
"answer_id": 74541000,
"author": "Samuel D.",
"author_id": 19189637,
"author_profile": "https://Stackoverflow.com/users/19189637",
"pm_score": 0,
"selected": false,
"text": "cart_name = \"carrozería\"\n\nCar.find_by(\"lower(unaccent(name)) LIKE ?\", \"%#{cart_name}%\")\n"
},
{
"answer_id": 74541005,
"author": "markets",
"author_id": 3033649,
"author_profile": "https://Stackoverflow.com/users/3033649",
"pm_score": 2,
"selected": true,
"text": "unaccent CREATE EXTENSION unaccent;\n unaccent() where(\"unaccent(name) LIKE ?\", \"%#{your_value}%\")\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19189637/"
] |
74,540,843
|
<p>I've tried writing my sql query to select multiple records on to one row but it isn't working the way I expected it to
Currently my table looks something like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>person id</th>
<th>fruit</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>apple</td>
</tr>
<tr>
<td>1</td>
<td>orange</td>
</tr>
<tr>
<td>1</td>
<td>banana</td>
</tr>
<tr>
<td>2</td>
<td>apple</td>
</tr>
<tr>
<td>2</td>
<td>orange</td>
</tr>
<tr>
<td>3</td>
<td>apple</td>
</tr>
</tbody>
</table>
</div>
<p>I've tried using CASE and GROUP BY but it just gave extra records and didn't display the way I wanted it to and is displaying like this</p>
<pre><code>SELECT DISTINCT
F.MEMBER
,F.GIVEN_NAMES
,F.SURNAME
--VALUES NEEDED
,CASE WHEN F.VALUE_NEEDED = 'Postal Address' THEN 'Yes' ELSE '' END POSTAL_ADDRESS
,CASE WHEN F.VALUE_NEEDED = 'Birthday' THEN 'Yes' ELSE '' END BIRTHDAY
,CASE WHEN F.VALUE_NEEDED = 'Email Address' THEN 'Yes' ELSE '' END EMAIL_ADDRESS
,CASE WHEN F.VALUE_NEEDED = 'First Name' THEN 'Yes' ELSE '' END FIRST_NAME
,CASE WHEN F.VALUE_NEEDED = 'Surname' THEN 'Yes' ELSE '' END SURNAME
,CASE WHEN F.VALUE_NEEDED = 'Title and Gender' THEN 'Yes' ELSE '' END 'TITLE|GENDER'
,CASE WHEN F.VALUE_NEEDED = 'Mobile' THEN 'Yes' ELSE '' END MOBILE
,CASE WHEN F.VALUE_NEEDED = 'Beneficiary' THEN 'Yes' ELSE '' END BENEFICIARY
FROM #FINAL F
GROUP BY F.MEMBER,F.GIVEN_NAMES
,F.SURNAME,VALUE_NEEDED
ORDER BY F.MEMBER
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>person id</th>
<th>apple</th>
<th>orange</th>
<th>banana</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>yes</td>
<td></td>
<td></td>
</tr>
<tr>
<td>1</td>
<td></td>
<td>yes</td>
<td></td>
</tr>
<tr>
<td>1</td>
<td></td>
<td></td>
<td>yes</td>
</tr>
</tbody>
</table>
</div>
<p>How do I write the query so it looks more like this?</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>person id</th>
<th>apple</th>
<th>orange</th>
<th>banana</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
</tr>
<tr>
<td>2</td>
<td>yes</td>
<td>yes</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td>yes</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74541000,
"author": "Samuel D.",
"author_id": 19189637,
"author_profile": "https://Stackoverflow.com/users/19189637",
"pm_score": 0,
"selected": false,
"text": "cart_name = \"carrozería\"\n\nCar.find_by(\"lower(unaccent(name)) LIKE ?\", \"%#{cart_name}%\")\n"
},
{
"answer_id": 74541005,
"author": "markets",
"author_id": 3033649,
"author_profile": "https://Stackoverflow.com/users/3033649",
"pm_score": 2,
"selected": true,
"text": "unaccent CREATE EXTENSION unaccent;\n unaccent() where(\"unaccent(name) LIKE ?\", \"%#{your_value}%\")\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14180750/"
] |
74,540,861
|
<blockquote>
<p>Unhandled Exception: type 'String' is not a subtype of type 'int' in
type cast</p>
</blockquote>
<pre><code>else if (value is List<int>) {
prefs.setStringList(
"itemsToLoanCats", [...value.map((e) => e.toString())]);
}
</code></pre>
<p>type of 'value' = <code>List<int></code></p>
<p>I don't see why this doesn't work, I'm using <code>.toString()</code></p>
<p>STACK TRACE</p>
<pre><code>I/flutter (16996): Person This is claiming to be itemsToLoanCats: [0]
I/flutter (16996): saveToPrefs converting GeoPoint...
E/flutter (16996): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'String' is not a subtype of type 'int' in type cast
E/flutter (16996): #0 _CastListBase.[] (dart:_internal/cast.dart:99:46)
E/flutter (16996): #1 ListMixin.elementAt (dart:collection/list.dart:78:33)
E/flutter (16996): #2 ListIterator.moveNext (dart:_internal/iterable.dart:342:26)
E/flutter (16996): #3 StringBuffer.writeAll (dart:core-patch/string_buffer_patch.dart:96:19)
E/flutter (16996): #4 IterableBase.iterableToFullString (dart:collection/iterable.dart:268:14)
E/flutter (16996): #5 ListMixin.toString (dart:collection/list.dart:588:37)
E/flutter (16996): #6 Person.saveToPrefs.<anonymous closure> (package:meloan/model/person.dart:635:72)
E/flutter (16996): #7 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:617:13)
E/flutter (16996): #8 Person.saveToPrefs (package:meloan/model/person.dart:593:20)
E/flutter (16996): #9 _PersonalDetailsScreenState._buildBody.<anonymous closure> (package:meloan/personal/edit_personal_details.dart:1231:30)
E/flutter (16996): #10 _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1072:21)
E/flutter (16996): #11 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:253:24)
E/flutter (16996): #12 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:627:11)
E/flutter (16996): #13 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:306:5)
E/flutter (16996): #14 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:276:7)
E/flutter (16996): #15 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:163:27)
E/flutter (16996): #16 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:464:20)
E/flutter (16996): #17 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:440:22)
E/flutter (16996): #18 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:337:11)
E/flutter (16996): #19 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:395:7)
E/flutter (16996): #20 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:357:5)
E/flutter (16996): #21 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:314:7)
E/flutter (16996): #22 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:295:7)
E/flutter (16996): #23 _invoke1 (dart:ui/hooks.dart:167:13)
E/flutter (16996): #24 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:341:7)
E/flutter (16996): #25 _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
</code></pre>
<p>ADDITION:</p>
<pre><code> List<String> encodedList = [];
for(int intValue in (value as List<int>)) {
print(LOG + "intValue: $intValue");
encodedList.add(int.parse(intValue).toString());
}
</code></pre>
<p>Doesn't work either, same Exception thrown.</p>
<p>Longer code snippet as requested:</p>
<pre><code> saveToPrefs(SharedPreferences prefs) {
(this.toMap()).forEach((key, value) {
//print("saveToPrefs entered with key: $key\nvalue: $value");
if (value != null) {
if (key == "dbProfilePicPath") {
print("PERSON " + "should be saving dbProfilePicPath");
}
if (value is String) {
prefs.setString(key, value);
} else if (key == "position") {
print("saveToPrefs converting GeoPoint...");
double latitude = value['geopoint'].latitude;
double longitude = value['geopoint'].longitude;
prefs.setDouble("latitude", latitude);
prefs.setDouble("longitude", longitude);
} else if (value is List<String>)
prefs.setStringList(key, value);
else if (value is double)
prefs.setDouble(key, value);
else if (value is int)
prefs.setInt(key, value);
else if (value is bool)
prefs.setBool(key, value);
else if (value is Map<String, String>) {
// needs to be stored as a list
List<String>? list = [];
value.forEach((key, value) {
list.add("$key:$value");
});
prefs.setStringList(key, list);
} else if (value is Map<String, bool>) {
// e.g. .Charateristics needs to be stored as a list
List<String>? list = [];
value.forEach((key, value) {
list.add("$key:${value.toString()}");
});
prefs.setStringList(key, list);
} else if (value is Map<String, dynamic>) {
// loanItemFinancials / loanItemDetails?
//prefs.setString('loanItemDetails', json.encode(value));
} else if (value is List<int>) {
// itemsToLoanCats, each loaning category encoded to int
value = value.cast<int>();
print(LOG + 'This is claiming to be itemsToLoanCats: ${value.toString()}');
prefs.setStringList("itemsToLoanCats", value.map((el) => el.toString()).toList());
//prefs.setStringList("itemsToLoanCats", [...value.map((e) => e.toString())]);
}
</code></pre>
|
[
{
"answer_id": 74541000,
"author": "Samuel D.",
"author_id": 19189637,
"author_profile": "https://Stackoverflow.com/users/19189637",
"pm_score": 0,
"selected": false,
"text": "cart_name = \"carrozería\"\n\nCar.find_by(\"lower(unaccent(name)) LIKE ?\", \"%#{cart_name}%\")\n"
},
{
"answer_id": 74541005,
"author": "markets",
"author_id": 3033649,
"author_profile": "https://Stackoverflow.com/users/3033649",
"pm_score": 2,
"selected": true,
"text": "unaccent CREATE EXTENSION unaccent;\n unaccent() where(\"unaccent(name) LIKE ?\", \"%#{your_value}%\")\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2514402/"
] |
74,540,869
|
<p>I am sending email when a job is posted. Emails are currently going well. The problem is Full Name of the users is going in emails, whereas i need to send the first name as full and only 1 initial of second name. Like John D.</p>
<p>Here is how i am doing in angular. By this way, my email sends and working properly.</p>
<pre><code>$user = JobPost::create($jobData);
$user = User::where('id', Auth::id())->with('profile')->first();
$msg = '<p>Hi. Thanks for posting your job</p>';
Mail::to($user->email)->send(new GeneralEmail(['name' =>$inputs['what_do_you'],'to' =>$user->name],' JobTasker', $msg));
</code></pre>
<p>But when i do like this to slice name, email doesn't go.</p>
<pre><code>Mail::to($user->email)->send(new GeneralEmail(['name' =>$inputs['what_do_you'],'to' =>$user->name.slice(0,1)],' JobTasker', $msg));
</code></pre>
|
[
{
"answer_id": 74540989,
"author": "Alexander Dyriavin",
"author_id": 8198671,
"author_profile": "https://Stackoverflow.com/users/8198671",
"pm_score": 0,
"selected": false,
"text": "// Your User Model \n public function nameForEmail()\n {\n $userName = explode(' ', $this->name ?? 'John Doe' ?? '');\n\n $firstName = $userName[0] ?? 'Unknown';\n\n $lastNameFull = $userName[count($userName) - 1];\n $lastNameInitial = $lastNameFull[0] ?? '';\n\n return \"$firstName $lastNameInitial\";\n }\n // Updated code to send email \n$user = JobPost::create($jobData);\n $user = User::where('id', Auth::id())->with('profile')->first();\n $msg = '<p>Hi. Thanks for posting your job</p>';\n Mail::to($user->email)->send(new GeneralEmail(['name' => $inputs['what_do_you'], 'to' => $user->nameForEmail()], ' JobTasker', $msg));\n"
},
{
"answer_id": 74566590,
"author": "Team Thunder",
"author_id": 14796728,
"author_profile": "https://Stackoverflow.com/users/14796728",
"pm_score": 2,
"selected": true,
"text": "$name = $user->name;\n$ar = explode(' ', $name);\n$setsc = substr($ar[1], 0, 1);\n$finalnm = $ar[0]. ' ' . $setsc;\n\nMail::to($user->email)->send(new GeneralEmail(['name' =>$inputs['what_do_you'],'to' =>$finalnm],' JobTasker', $msg));\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18853102/"
] |
74,540,891
|
<p>So im trying to force the user to give me purely an input between 1 and 0 and I managed to do so for the most part but it'll only work if all three inputs are above that and my code only gives me and input for a</p>
<pre class="lang-py prettyprint-override"><code>def AND(a, b):
return a and b
def OR(a, b):
return a and b
def NOR(a, b):
return a and b
user=[]
def main():
a= False
b= False
c= False
n_attempts = 1
for _ in range(n_attempts):
a_raw = input("for a, 1 or 0: ")
try:
a = int(a_raw)
except ValueError:
print(f"Invalid value for 'a': {a!r}")
continue
b_raw = input("for a, 1 or 0: ")
try:
b = int(b_raw)
except ValueError:
print(f"Invalid value for 'a': {b!r}")
continue
c_raw = input("for a, 1 or 0: ")
try:
c = int(c_raw)
except ValueError:
print(f"Invalid value for 'a': {c!r}")
continue
print ("Result of (A NOR B) OR (B AND C) is: " , int(OR(NOR(a, b), AND(b, c))))
main()
</code></pre>
<p>i tried if and elif statements and also work to some degree where itll activate if all inputs are above 1 or 0</p>
<pre class="lang-py prettyprint-override"><code>for _ in range(3):
a=input("for a, 1 or 0: ")
b=input("for b, 1 or 0: ")
c=input("for c, 1 or 0: ")
if a =="0" or a=="1":
break
else:
print("wrong input")
if b =="0" or b=="1":
break
else:
print("wrong input")
if c =="0" or c=="1":
break
else:
print("wrong input")
</code></pre>
<p>im supposed to writethe code as blocks in functions that will perform each gate. There will be one gate per function. Pass the inputs to the functions and the outputs from the functions.</p>
<p><a href="https://i.stack.imgur.com/yRy2m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yRy2m.png" alt="This is my reference for the gate" /></a></p>
<p>using that as a reference</p>
|
[
{
"answer_id": 74541007,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 0,
"selected": false,
"text": "while for values = {}\nfor name in 'a', 'b', 'c':\n while True:\n try:\n value = input(f'for {name}, 1 or 0: ')\n value = values[name] = int(value)\n assert value in (0, 1)\n break\n except (ValueError, AssertionError):\n print(f\"Invalid value for '{name}': {value!r}\")\n\nprint(values['a'], values['b'], values['c'])\n"
},
{
"answer_id": 74541025,
"author": "马春春",
"author_id": 13423088,
"author_profile": "https://Stackoverflow.com/users/13423088",
"pm_score": 0,
"selected": false,
"text": "value = input(\"some description here\")\nif value in [\"0\", \"1\"]:\n a = int(value)\nelse:\n break\n"
},
{
"answer_id": 74541036,
"author": "kenntnisse",
"author_id": 18318238,
"author_profile": "https://Stackoverflow.com/users/18318238",
"pm_score": 0,
"selected": false,
"text": "Q Q or ()or() def or_function(a, b):\n return a or b\n or_function((), ()) A nor B not (A or B) (not (A or B)) or () def nor_function(a, b):\n return not(a or b)\n or_function(nor_function(A, B), ()) B and C (not (A or B)) or (B and C) 0 False 1 True"
},
{
"answer_id": 74541279,
"author": "behnam",
"author_id": 18398219,
"author_profile": "https://Stackoverflow.com/users/18398219",
"pm_score": -1,
"selected": true,
"text": "a=bool\nb=bool\nc=bool\n\nwhile True:\n\n v=[\"1\",\"0\"]\n a=input(\"input 1 or 0: \")\n b=input(\"input 1 or 0: \")\n c=input(\"input 1 or 0: \")\n if (a and b and c in v):\n break\n else:\n print(\"wrong input\")\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20016166/"
] |
74,540,896
|
<p>I'd like to extract weight values from strings with the unit and the time of measurement using tidyverse.</p>
<p>My dataset is like as below:</p>
<pre><code>df <- tibble(ID = c("A","B","C"),
Weight = c("45kg^20221120", "51.5kg^20221015", "66.05kg^20221020"))
------
A tibble: 3 × 2
ID Weight
<chr> <chr>
1 A 45kg^20221120
2 B 11.5kg^20221015
3 C 66.05kg^20221020
</code></pre>
<p>I use stringr in the tidyverse package with regular expressions.</p>
<pre><code>library(tidyverse)
df %>%
mutate(Weight = as.numeric(str_extract(Measurement, "(\\d+\\.\\d+)|(\\d+)(?=kg)")))
----------
A tibble: 3 × 3
ID Measurement Weight
<chr> <chr> <dbl>
1 A 45kg^20221120 45
2 B 11.5kg^20221015 11.5
3 C 66.05kg^20221020 66.0
</code></pre>
<p>The second decimal place of C (.0<strong>5</strong>) doesn't extracted.
What's wrong with my code?
Any answers or comments are welcome.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 74541007,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 0,
"selected": false,
"text": "while for values = {}\nfor name in 'a', 'b', 'c':\n while True:\n try:\n value = input(f'for {name}, 1 or 0: ')\n value = values[name] = int(value)\n assert value in (0, 1)\n break\n except (ValueError, AssertionError):\n print(f\"Invalid value for '{name}': {value!r}\")\n\nprint(values['a'], values['b'], values['c'])\n"
},
{
"answer_id": 74541025,
"author": "马春春",
"author_id": 13423088,
"author_profile": "https://Stackoverflow.com/users/13423088",
"pm_score": 0,
"selected": false,
"text": "value = input(\"some description here\")\nif value in [\"0\", \"1\"]:\n a = int(value)\nelse:\n break\n"
},
{
"answer_id": 74541036,
"author": "kenntnisse",
"author_id": 18318238,
"author_profile": "https://Stackoverflow.com/users/18318238",
"pm_score": 0,
"selected": false,
"text": "Q Q or ()or() def or_function(a, b):\n return a or b\n or_function((), ()) A nor B not (A or B) (not (A or B)) or () def nor_function(a, b):\n return not(a or b)\n or_function(nor_function(A, B), ()) B and C (not (A or B)) or (B and C) 0 False 1 True"
},
{
"answer_id": 74541279,
"author": "behnam",
"author_id": 18398219,
"author_profile": "https://Stackoverflow.com/users/18398219",
"pm_score": -1,
"selected": true,
"text": "a=bool\nb=bool\nc=bool\n\nwhile True:\n\n v=[\"1\",\"0\"]\n a=input(\"input 1 or 0: \")\n b=input(\"input 1 or 0: \")\n c=input(\"input 1 or 0: \")\n if (a and b and c in v):\n break\n else:\n print(\"wrong input\")\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20375862/"
] |
74,540,930
|
<p>Here is my my program:</p>
<pre><code>def word_frequencies(words):
l=[]
l=words.split()
wordfreq=[l.count(p) for p in l]
return(dict(zip(l,wordfreq)))
if __name__ == '__main__':
words = input("Enter a sentence: ")
your_dictionary = word_frequencies(words)
sorted_keys = sorted(your_dictionary.keys())
for key in sorted_keys:
print(key + ': ' + str(your_dictionary[key]))
</code></pre>
<p>Here is my output:</p>
<p>Enter a sentence: ZyBooks now zyBooks later zyBooks forever</p>
<p>ZyBooks: 1
forever: 1
later: 1
now: 1
zyBooks: 2</p>
<p>Here is my expectation:</p>
<p>Enter a sentence: ZyBooks now zyBooks later zyBooks forever</p>
<p>forever: 1
later: 1
now: 1
zybooks: 3</p>
|
[
{
"answer_id": 74541007,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 0,
"selected": false,
"text": "while for values = {}\nfor name in 'a', 'b', 'c':\n while True:\n try:\n value = input(f'for {name}, 1 or 0: ')\n value = values[name] = int(value)\n assert value in (0, 1)\n break\n except (ValueError, AssertionError):\n print(f\"Invalid value for '{name}': {value!r}\")\n\nprint(values['a'], values['b'], values['c'])\n"
},
{
"answer_id": 74541025,
"author": "马春春",
"author_id": 13423088,
"author_profile": "https://Stackoverflow.com/users/13423088",
"pm_score": 0,
"selected": false,
"text": "value = input(\"some description here\")\nif value in [\"0\", \"1\"]:\n a = int(value)\nelse:\n break\n"
},
{
"answer_id": 74541036,
"author": "kenntnisse",
"author_id": 18318238,
"author_profile": "https://Stackoverflow.com/users/18318238",
"pm_score": 0,
"selected": false,
"text": "Q Q or ()or() def or_function(a, b):\n return a or b\n or_function((), ()) A nor B not (A or B) (not (A or B)) or () def nor_function(a, b):\n return not(a or b)\n or_function(nor_function(A, B), ()) B and C (not (A or B)) or (B and C) 0 False 1 True"
},
{
"answer_id": 74541279,
"author": "behnam",
"author_id": 18398219,
"author_profile": "https://Stackoverflow.com/users/18398219",
"pm_score": -1,
"selected": true,
"text": "a=bool\nb=bool\nc=bool\n\nwhile True:\n\n v=[\"1\",\"0\"]\n a=input(\"input 1 or 0: \")\n b=input(\"input 1 or 0: \")\n c=input(\"input 1 or 0: \")\n if (a and b and c in v):\n break\n else:\n print(\"wrong input\")\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20577449/"
] |
74,540,931
|
<p>I have a data frame...</p>
<pre><code>example <- data.frame(obs_val= c(20,15,3,7,5), patient = c("pt1","pt2","pt3","pt4","pt5"))
</code></pre>
<p>... where every row or "patient" is a unique observation.</p>
<p>My goal is to generate a data frame that subtracts each patient's observed value (<code>obs_val</code>) from another patient's <code>obs_val</code>. This subtraction would be a permutation, where i.e. <code>pt1</code> does not have their own <code>obs_val</code> subtracted from their self. Ideally, the final data frame should look something like the following:</p>
<pre><code> pt1-pt2 pt1-pt3 pt1-pt4 pt1-pt5 pt2-pt3 pt2-pt4 ...
obs_val_diff 5 17 13 15 12 8 ...
</code></pre>
<p>Any suggestions on solving this problem, or reformatting the final data frame?</p>
|
[
{
"answer_id": 74541007,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 0,
"selected": false,
"text": "while for values = {}\nfor name in 'a', 'b', 'c':\n while True:\n try:\n value = input(f'for {name}, 1 or 0: ')\n value = values[name] = int(value)\n assert value in (0, 1)\n break\n except (ValueError, AssertionError):\n print(f\"Invalid value for '{name}': {value!r}\")\n\nprint(values['a'], values['b'], values['c'])\n"
},
{
"answer_id": 74541025,
"author": "马春春",
"author_id": 13423088,
"author_profile": "https://Stackoverflow.com/users/13423088",
"pm_score": 0,
"selected": false,
"text": "value = input(\"some description here\")\nif value in [\"0\", \"1\"]:\n a = int(value)\nelse:\n break\n"
},
{
"answer_id": 74541036,
"author": "kenntnisse",
"author_id": 18318238,
"author_profile": "https://Stackoverflow.com/users/18318238",
"pm_score": 0,
"selected": false,
"text": "Q Q or ()or() def or_function(a, b):\n return a or b\n or_function((), ()) A nor B not (A or B) (not (A or B)) or () def nor_function(a, b):\n return not(a or b)\n or_function(nor_function(A, B), ()) B and C (not (A or B)) or (B and C) 0 False 1 True"
},
{
"answer_id": 74541279,
"author": "behnam",
"author_id": 18398219,
"author_profile": "https://Stackoverflow.com/users/18398219",
"pm_score": -1,
"selected": true,
"text": "a=bool\nb=bool\nc=bool\n\nwhile True:\n\n v=[\"1\",\"0\"]\n a=input(\"input 1 or 0: \")\n b=input(\"input 1 or 0: \")\n c=input(\"input 1 or 0: \")\n if (a and b and c in v):\n break\n else:\n print(\"wrong input\")\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11381129/"
] |
74,540,976
|
<p>I have two lists let's say</p>
<pre><code>list1 = ["apple","banana"]
list2 = ["M","T","W","TR","F","S"]
</code></pre>
<p>I want to create a data frame of two columns fruit and day so that the result will look something like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>fruit</th>
<th>day</th>
</tr>
</thead>
<tbody>
<tr>
<td>apple</td>
<td>M</td>
</tr>
<tr>
<td>apple</td>
<td>T</td>
</tr>
<tr>
<td>apple</td>
<td>W</td>
</tr>
<tr>
<td>apple</td>
<td>TR</td>
</tr>
<tr>
<td>apple</td>
<td>F</td>
</tr>
<tr>
<td>apple</td>
<td>S</td>
</tr>
<tr>
<td>banana</td>
<td>M</td>
</tr>
</tbody>
</table>
</div>
<p>and so on...</p>
<p>currently, my actual data is columnar meaning items in list2 are in columns, but I want them in rows, any help would be appreciated.</p>
|
[
{
"answer_id": 74541586,
"author": "ziying35",
"author_id": 16755671,
"author_profile": "https://Stackoverflow.com/users/16755671",
"pm_score": 2,
"selected": true,
"text": "from itertools import product\nimport pandas as pd\n\n\nlist1 = [\"apple\",\"banana\"]\nlist2 = [\"M\",\"T\",\"W\",\"TR\",\"F\",\"S\"]\ndf = pd.DataFrame(\n product(list1, list2),\n columns=['fruit', 'day']\n)\nprint(df)\n>>>\n fruit day\n0 apple M\n1 apple T\n2 apple W\n3 apple TR\n4 apple F\n5 apple S\n6 banana M\n7 banana T\n8 banana W\n9 banana TR\n10 banana F\n11 banana S\n"
},
{
"answer_id": 74543497,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 0,
"selected": false,
"text": "merge df = pd.merge(pd.Series(list1,name='fruit'),\n pd.Series(list2,name='day'),how='cross')\n\nprint(df)\n'''\n fruit day\n0 apple M\n1 apple T\n2 apple W\n3 apple TR\n4 apple F\n5 apple S\n6 banana M\n7 banana T\n8 banana W\n9 banana TR\n10 banana F\n11 banana S\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2813612/"
] |
74,540,996
|
<p>I'd like to extract the numbers from the string. (E.g. I want the <code>24</code> and <code>380</code> from the string <code>24:380</code>) I'd like to assign it in respective variables. Is there any way I could do that?</p>
<p>I couldn't find any solution to this problem.</p>
|
[
{
"answer_id": 74541586,
"author": "ziying35",
"author_id": 16755671,
"author_profile": "https://Stackoverflow.com/users/16755671",
"pm_score": 2,
"selected": true,
"text": "from itertools import product\nimport pandas as pd\n\n\nlist1 = [\"apple\",\"banana\"]\nlist2 = [\"M\",\"T\",\"W\",\"TR\",\"F\",\"S\"]\ndf = pd.DataFrame(\n product(list1, list2),\n columns=['fruit', 'day']\n)\nprint(df)\n>>>\n fruit day\n0 apple M\n1 apple T\n2 apple W\n3 apple TR\n4 apple F\n5 apple S\n6 banana M\n7 banana T\n8 banana W\n9 banana TR\n10 banana F\n11 banana S\n"
},
{
"answer_id": 74543497,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 0,
"selected": false,
"text": "merge df = pd.merge(pd.Series(list1,name='fruit'),\n pd.Series(list2,name='day'),how='cross')\n\nprint(df)\n'''\n fruit day\n0 apple M\n1 apple T\n2 apple W\n3 apple TR\n4 apple F\n5 apple S\n6 banana M\n7 banana T\n8 banana W\n9 banana TR\n10 banana F\n11 banana S\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74540996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16773147/"
] |
74,541,055
|
<p>I'm not sure if I am fighting with something impossible in PHP</p>
<p>I was trying to redirect and download or download and redirect, but either doesn't work.</p>
<p>After the user download the PDF, I want to redirect back to the main page</p>
<p>I've tried</p>
<pre><code>header("Location: https://www.main-page.com");
return Response::download($file,"file.pdf", $headers);
</code></pre>
<p>Ex</p>
<p><a href="https://www.main-page.com" rel="nofollow noreferrer">https://www.main-page.com</a></p>
<p><a href="https://www.main-page.com/pdf" rel="nofollow noreferrer">https://www.main-page.com/pdf</a> (show download PDF and return back to the main page)</p>
|
[
{
"answer_id": 74541128,
"author": "Muh Raswan Sualdi",
"author_id": 20551663,
"author_profile": "https://Stackoverflow.com/users/20551663",
"pm_score": -1,
"selected": false,
"text": "Response::download($file,\"file.pdf\", $headers); return redirect(\"path location you want to redirect\");"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4480164/"
] |
74,541,080
|
<p>I feel like there is an easy fix for this but I am not finding it. After I first open the page, type a number in the input and hit submit I get an empty array in the console and no number is displayed. When I hit enter again it works. How do I get the number to display the first time?</p>
<pre><code>import React from 'react';
import {useState} from 'react';
const ShowDays = () =>{
const [totalMiles, setTotalMiles] = useState([])
const [miles, setMiles] = useState([])
const [total, setTotal] = useState([])
const handleChange = (e) =>{
setMiles(e.target.value)
}
const handleSubmit = (e) =>{
e.preventDefault();
setTotalMiles([...totalMiles].concat(Number(miles)
))
if (totalMiles !== []){
let result = totalMiles.reduce((total, n) =>{
return total += n
})
setTotal(result)
}
}
return (
<div>
<form onSubmit={handleSubmit}>
<input type='text' placeholder='enter miles' onChange={handleChange} value={miles}/>
<button>Submit</button>
</form>
<p>{`Total Milage: ${total} `}</p>
</div>
)
}
export default ShowDays;
</code></pre>
<p>I've tried many different things but nothing seems to work</p>
|
[
{
"answer_id": 74541128,
"author": "Muh Raswan Sualdi",
"author_id": 20551663,
"author_profile": "https://Stackoverflow.com/users/20551663",
"pm_score": -1,
"selected": false,
"text": "Response::download($file,\"file.pdf\", $headers); return redirect(\"path location you want to redirect\");"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20384603/"
] |
74,541,082
|
<p>I have a database with over 30,000,000 entries. When performing queries (including an <code>ORDER BY</code> clause) on a <code>text</code> field, the <code>=</code> operator results in relatively fast results. However we have noticed that when using the <code>LIKE</code> operator, the query becomes remarkably slow, taking minutes to complete. For example:</p>
<p><code>SELECT * FROM work_item_summary WHERE manager LIKE '%manager' ORDER BY created;</code></p>
<p><a href="https://i.stack.imgur.com/l7NKV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l7NKV.jpg" alt="Query Plan" /></a></p>
<p>Creating indices on the keywords being searched will of course greatly speed up the query. The problem is we must support queries on any arbitrary pattern, and on any column, making this solution not viable.</p>
<p>My questions are:</p>
<ol>
<li>Why are <code>LIKE</code> queries this much slower than <code>=</code> queries?</li>
<li>Is there any other way these generic queries can be optimized, or is about as good as one can get for a database with so many entries?</li>
</ol>
|
[
{
"answer_id": 74541228,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 2,
"selected": false,
"text": "LIKE COLLATE \"C\""
},
{
"answer_id": 74564640,
"author": "SQLpro",
"author_id": 12659872,
"author_profile": "https://Stackoverflow.com/users/12659872",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE T_WRD\n(WRD_ID BIGINT IDENTITY PRIMARY KEY,\n WRD_WORD VARCHAR(64) NOT NULL UNIQUE,\n WRD_DROW GENERATED ALWAYS AS (REVERSE(WRD_WORD) NOT NULL UNIQUE) ;\nGO\n \nCREATE TABLE T_WORD_ROTATE_STRING_WRS\n(WRD_ID BIGINT NOT NULL REFERENCES T_WRD (WRD_ID),\n WRS_ROTATE SMALLINT NOT NULL,\n WRD_ID_PART BIGINT NOT NULL REFERENCES T_WRD (WRD_ID),\n PRIMARY KEY (WRD_ID, WRS_ROTATE));\nGO\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8685016/"
] |
74,541,098
|
<p>I am using an array of 51 positions, the same one that I traverse with map but I need it to be displayed only from position 2 to the end in order to avoid index 0 and 1 being displayed.</p>
<p>This is my code:</p>
<pre><code> <select
defaultValue={'DEFAULT'}
onChange={ (e) =>handlerPresentationSelected(e)}
className="border-solid border-2 border-slate-200 w-full p-2"
>
<option value="DEFAULT" disabled>Seleccione</option>
{ [...Array(51)].map( (value, index) => (
<option
key={index}
value={index}>
{ index }
</option>
))}
</select>
</code></pre>
<p>How can I achieve it? Thanks.</p>
|
[
{
"answer_id": 74541228,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 2,
"selected": false,
"text": "LIKE COLLATE \"C\""
},
{
"answer_id": 74564640,
"author": "SQLpro",
"author_id": 12659872,
"author_profile": "https://Stackoverflow.com/users/12659872",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE T_WRD\n(WRD_ID BIGINT IDENTITY PRIMARY KEY,\n WRD_WORD VARCHAR(64) NOT NULL UNIQUE,\n WRD_DROW GENERATED ALWAYS AS (REVERSE(WRD_WORD) NOT NULL UNIQUE) ;\nGO\n \nCREATE TABLE T_WORD_ROTATE_STRING_WRS\n(WRD_ID BIGINT NOT NULL REFERENCES T_WRD (WRD_ID),\n WRS_ROTATE SMALLINT NOT NULL,\n WRD_ID_PART BIGINT NOT NULL REFERENCES T_WRD (WRD_ID),\n PRIMARY KEY (WRD_ID, WRS_ROTATE));\nGO\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8977748/"
] |
74,541,100
|
<p>I'm having a hard time understanding the following <a href="https://docs.flutter.dev/development/ui/layout/constraints#:%7E:text=paints%20it%20red.-,Example%202,-content_copy" rel="nofollow noreferrer">example from the official Flutter docs</a>:</p>
<p><a href="https://i.stack.imgur.com/rRsWb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rRsWb.png" alt="enter image description here" /></a></p>
<p>Following the famous <a href="https://docs.flutter.dev/development/ui/layout/constraints#:%7E:text=Constraints%20go%20down.%20Sizes%20go%20up.%20Parent%20sets%20position." rel="nofollow noreferrer">"Constraints go down. Sizes go up. Parent sets position"</a> rule and assuming the screen size is <code>1024x800</code> shouldn't the conversation between the widgets look like this:</p>
<blockquote>
<p>Parent: "You must be from <code>0</code> to <code>1024</code> pixels wide and <code>0</code> to <code>800</code> pixels tall".</p>
<p>Child (the red container): "Ok. I want to be <code>100</code> pixels wide and <code>100</code> pixels tall".</p>
</blockquote>
<p>According to the docs, however, the parent is forcing the child to occupy the entire screen.</p>
<p>So why does it do this instead of letting the child be <code>100x100</code>?</p>
|
[
{
"answer_id": 74541271,
"author": "pmatatias",
"author_id": 12838877,
"author_profile": "https://Stackoverflow.com/users/12838877",
"pm_score": 3,
"selected": true,
"text": "Aligment Center Alignment.center"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4241959/"
] |
74,541,221
|
<p>I'm using Cypress for its component tests. These are integration-style tests, I mount my whole app (React) and then click through it. All API calls are mocked using the Cypress Intercept feature. So far this has been an incredibly powerful solution, far more robust than any other FE testing suite I've worked with.</p>
<p>One limitation I've run into is with the intercepted API calls. I've got this scenario where I've got an API that is called twice during the flow of a given test. One of the conditions I want to validate is that it is, indeed, called twice, as the second call is triggered by the logic I am testing.</p>
<p>So the specific Cypress validation I want to work is this:</p>
<pre><code>cy.get('#myButton').click(); // Triggers the second API call
cy.get('@myApi.all').should('have.length', 2);
</code></pre>
<p>Now, the problem is that the above code, on its own, fails because Cypress only registers a single call to the intercepted API named <code>myApi</code>. The reason for this is Cypress moves to immediately validate the number of calls to this intercepted API, rather than waiting for the action I just triggered in the UI.</p>
<p>The only way I know of to make the above code work is to add in explicit waiting, like this:</p>
<pre><code>cy.get('#myButton').click(); // Triggers the second API call
cy.wait(300);
cy.get('@myApi.all').should('have.length', 2);
</code></pre>
<p>Because I am explicitly waiting 300ms after clicking the button, enough time passes for the second API call to occur and Cypress to register it, so the test passes.</p>
<p>I don't like this solution. I don't like adding explicit waits to my test code, it feels like a band-aid and will likely be error prone as it relies on execution timing to succeed. However, I simply do not know of a better option.</p>
|
[
{
"answer_id": 74542167,
"author": "Jay Swan",
"author_id": 20578569,
"author_profile": "https://Stackoverflow.com/users/20578569",
"pm_score": 2,
"selected": false,
"text": "cy.wait(300) cy.wait('@myApi') cy.get('@myApi') cy.get('#myButton').click()\ncy.wait('@myApi')\ncy.get('@myApi.all').should('have.length', 2)\n"
},
{
"answer_id": 74544636,
"author": "Alcock",
"author_id": 20580470,
"author_profile": "https://Stackoverflow.com/users/20580470",
"pm_score": 2,
"selected": false,
"text": "cy.get('@myApi.all') it('makes 3 calls', () => {\n let count = 0\n cy.intercept('/favorite-fruits', () => {\n // we are not changing the request or response here\n // just counting the matched calls\n count += 1\n })\n cy.visit('/fruits.html')\n // ensure the fruits are loaded\n cy.get('.favorite-fruits li').should('have.length', 5)\n\n cy.reload()\n cy.get('.favorite-fruits li').should('have.length', 5)\n\n cy.reload()\n cy.get('.favorite-fruits li').should('have.length', 5)\n .then(() => {\n // by now the count should have been updated\n expect(count, 'network calls to fetch fruits').to.equal(3)\n })\n})\n"
},
{
"answer_id": 74549946,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": 0,
"selected": false,
"text": "cy.get('@myApi.all') .all // spy/stub with alias your reach component call\n\ncy.get('#myButton').click(); // Triggers the second API call\ncy.get('@myApi').should('have.been.calledOnce')\n// wait for your app to trigger the call\ncy.get('@myApi').should('have.been.calledTwice')\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2223059/"
] |
74,541,230
|
<p>Right now I am trying to delete all the lines of the file that has number 80000 or greater at the end of the line</p>
<p>For example</p>
<p>Jennifer Cowan:548-834-2348:583 Laurel Ave., Kingsville, TX 83745:10/1/35:58900<br />
Jon DeLoach:408-253-3122:123 Park St., San Jose, CA 04086:7/25/53:85100</p>
<p>When I run sed, the command should only delete the line of Jon DeLoach</p>
<p>I tried till</p>
<pre><code>sed '/:0*[1-9][0-9]{5,}|:0*[8-9][0-9]{4,}/d' datebook.txt
</code></pre>
<p>since</p>
<pre><code>egrep ':0*[1-9][0-9]{5,}|:0*[8-9][0-9]{4,}' datebook.txt
</code></pre>
<p>returns all the lines that has 800000 or greater</p>
<p>however, sed command actually does not work and find out that because regular expression that I made</p>
<pre><code> ':0*[1-9][0-9]{5,}|:0*[8-9][0-9]{4,}'
</code></pre>
<p>only work for egrep not grep</p>
<p>I am new to regular expression and kind of confuse how to change from egrep to grep</p>
|
[
{
"answer_id": 74541365,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 0,
"selected": false,
"text": "awk -F\":\" '$5 < 80000' datebook.txt\n -F\":\" $5"
},
{
"answer_id": 74541577,
"author": "jared_mamrot",
"author_id": 12957340,
"author_profile": "https://Stackoverflow.com/users/12957340",
"pm_score": 2,
"selected": true,
"text": "sed '/:[8-9][0-9]\\{3,\\}$/d; /:[0-9]\\{6,\\}$/d' file\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11645616/"
] |
74,541,251
|
<p>I have a ASP.NET Core 6 Web API with this disposable service class:</p>
<pre class="lang-cs prettyprint-override"><code>public interface IMyService: IDisposable { }
public class MyService: IMyService
{
public void Dispose() => Console.WriteLine("Disposing..."); // never called
}
</code></pre>
<p>In program.cs I have this service injected as a singleton:</p>
<pre class="lang-cs prettyprint-override"><code>builder.Services.AddSingleton<IMyService, MyService>();
</code></pre>
<p>According to all docs that I could find, the app should call <code>MyService.Dispose()</code> when it shuts down. However this doesn't happen.</p>
<p>What am I missing?</p>
<p>Steps to reproduce:</p>
<ol>
<li>Create a ASP.NET Core WebAPI project using default template (VS2022)</li>
<li>At the end of program.cs add this code:
<pre class="lang-cs prettyprint-override"><code> public interface IMyService : IDisposable { }
public class MyService : IMyService
{
public MyService()
{
}
public void Dispose() => Console.WriteLine("Disposing..."); // never called
}
</code></pre>
</li>
<li>Put a breakpoint on constructor and one on Dispose</li>
<li>Add this line somewhere at the top (after builder is created):
<pre class="lang-cs prettyprint-override"><code> // Add services to the container.
builder.Services.AddSingleton<IMyService, MyService>();
</code></pre>
</li>
<li>In WeatherForecastController.cs change the constructor signature like this:
<pre class="lang-cs prettyprint-override"><code> public WeatherForecastController(
ILogger<WeatherForecastController> logger, IMyService myService)
</code></pre>
</li>
<li>Run the app. In the browser click Get then Try it out then Execute</li>
<li>The break point in <code>MyService</code> constructor shd be hit</li>
<li>Close the browser. The <code>Dispose</code> breakpoint is not hit, Output message is not displayed</li>
</ol>
|
[
{
"answer_id": 74543048,
"author": "Xinran Shen",
"author_id": 17438579,
"author_profile": "https://Stackoverflow.com/users/17438579",
"pm_score": 0,
"selected": false,
"text": "using using (MyService service = new MyService())\n{\n service.xxxxxx();\n}\n Dispose() AddSingleton<IMyService, MyService>() \n AddSingleton AddScoped"
},
{
"answer_id": 74548692,
"author": "Steven",
"author_id": 264697,
"author_profile": "https://Stackoverflow.com/users/264697",
"pm_score": 0,
"selected": false,
"text": "Microsoft.Extensions.DependencyInjection using System;\nusing Microsoft.Extensions.DependencyInjection;\n\nvar services = new ServiceCollection();\n\nservices.AddSingleton<IMyService, MyService>();\n\nusing (var container = services.BuildServiceProvider())\n{\n container.GetRequiredService<IMyService>();\n}\n\npublic interface IMyService : IDisposable { }\n\npublic class MyService : IMyService\n{\n public void Dispose() => Console.WriteLine(\"Disposing...\");\n}\n Disposing...\n MyService"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/628661/"
] |
74,541,262
|
<p>How to get filter based data rows from Genre column coming from another dataframe?</p>
<p>I have a movies dataframe as follows:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Movie_Name</th>
<th style="text-align: center;">Genre</th>
<th style="text-align: right;">Rating</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">Halloween</td>
<td style="text-align: center;">Crime, Horror, Thriller</td>
<td style="text-align: right;">6.5</td>
</tr>
<tr>
<td style="text-align: left;">Nope</td>
<td style="text-align: center;">Horror, Mystery, Sci-Fi</td>
<td style="text-align: right;">6.9</td>
</tr>
<tr>
<td style="text-align: left;">The Midnight Club</td>
<td style="text-align: center;">Drama, Horror, Mystery</td>
<td style="text-align: right;">6.7</td>
</tr>
<tr>
<td style="text-align: left;">The Northman</td>
<td style="text-align: center;">Action, Adventure, Drama</td>
<td style="text-align: right;">7.1</td>
</tr>
<tr>
<td style="text-align: left;">Prey</td>
<td style="text-align: center;">Action, Adventure, Drama</td>
<td style="text-align: right;">7.2</td>
</tr>
<tr>
<td style="text-align: left;">Uncharted</td>
<td style="text-align: center;">Action, Adventure</td>
<td style="text-align: right;">6.3</td>
</tr>
<tr>
<td style="text-align: left;">Sherwood</td>
<td style="text-align: center;">Crime, Drama, Mystery</td>
<td style="text-align: right;">7.4</td>
</tr>
</tbody>
</table>
</div>
<p>And I have a user dataframe as follows:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">User_Id</th>
<th style="text-align: center;">User_Name</th>
<th style="text-align: right;">Genre</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">100</td>
<td style="text-align: center;">Christine</td>
<td style="text-align: right;">Horror, Thriller, Drama</td>
</tr>
</tbody>
</table>
</div>
<p>I want to get the following rows as output because the user likes horror, thriller, and drama genres.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Movie_Name</th>
<th style="text-align: center;">Genre</th>
<th style="text-align: right;">Rating</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">Halloween</td>
<td style="text-align: center;">Crime, Horror, Thriller</td>
<td style="text-align: right;">6.5</td>
</tr>
<tr>
<td style="text-align: left;">Nope</td>
<td style="text-align: center;">Horror, Mystery, Sci-Fi</td>
<td style="text-align: right;">6.9</td>
</tr>
<tr>
<td style="text-align: left;">The Midnight Club</td>
<td style="text-align: center;">Drama, Horror, Mystery</td>
<td style="text-align: right;">6.7</td>
</tr>
<tr>
<td style="text-align: left;">The Northman</td>
<td style="text-align: center;">Action, Adventure, Drama</td>
<td style="text-align: right;">7.1</td>
</tr>
<tr>
<td style="text-align: left;">Prey</td>
<td style="text-align: center;">Action, Adventure, Drama</td>
<td style="text-align: right;">7.2</td>
</tr>
<tr>
<td style="text-align: left;">Sherwood</td>
<td style="text-align: center;">Crime, Drama, Mystery</td>
<td style="text-align: right;">7.4</td>
</tr>
</tbody>
</table>
</div>
<p>How can I get the Movie rows where a value in the Genre column matches at least one of the User's Genre preferences?</p>
|
[
{
"answer_id": 74541541,
"author": "ziying35",
"author_id": 16755671,
"author_profile": "https://Stackoverflow.com/users/16755671",
"pm_score": 2,
"selected": false,
"text": "pattern = user['Genre'].str.replace(', ', '|')[0]\nresult = movies.query('Genre.str.contains(@pattern)')\nprint(result)\n"
},
{
"answer_id": 74541571,
"author": "wrbp",
"author_id": 16662333,
"author_profile": "https://Stackoverflow.com/users/16662333",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\ndf=pd.read_csv(\"db1.csv\",header=[0]) # movies\ndf2=pd.read_csv(\"db2.csv\",header=[0]) # users\n\nfor ir,row in df2.iterrows():\n gen=row[\"Genre\"].replace(\",\",\"|\").replace(\" \",\"\")\n filtereddf=df[df[\"Genre\"].str.contains(gen)]\n \n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17652342/"
] |
74,541,264
|
<p>I installed Python3.11 which is located <code>usr/local/bin/python3</code>, which came without pip. The old Python3.10 was located in <code>usr/bin/python3</code>.
I tried to install pip with <code>sudo apt-install python3-pip</code>, but it seems to be attached to the old Python3.10. If I check <code>pip --version</code>, the output will be this:
<code>pip 22.0.2 from /usr/lib/python3/dist-packages/pip (python 3.10)</code>, but I need it for Python3.11. For example if I try to <code>pip install requests</code> now, I get <code>Requirements already satisfied: requests in /usr/lib/python3/dist-packages (2.25.1)</code>, which is the Python3.10 folder.</p>
|
[
{
"answer_id": 74541356,
"author": "xunjie liu",
"author_id": 16934422,
"author_profile": "https://Stackoverflow.com/users/16934422",
"pm_score": 1,
"selected": false,
"text": "❯ pyenv global 3.10.5\n\n❯ pyenv versions\n system\n 3.7.10\n* 3.10.5 (set by /home/xunjie/.pyenv/version)\n 3.10.8\n\n❯ which python\n/home/xunjie/.pyenv/shims/python\n\n❯ which pip \n/home/xunjie/.pyenv/shims/pip\n"
},
{
"answer_id": 74541385,
"author": "Constantin Hong",
"author_id": 20307768,
"author_profile": "https://Stackoverflow.com/users/20307768",
"pm_score": 0,
"selected": false,
"text": "/usr/local/bin/python3 -m pip install pip\n /usr/local/bin/python3 -m pip install <package>\n python python3 whereis python3.11\n > python3.11: /usr/local/bin/python3.11 /usr/local/share/man/man1/python3.11.1\n which pip3.11\n > /usr/local/bin/pip3.11\n which python\nwhich python3\nwhich pip\nwhich pip3\n which python\n> /usr/bin/python\nwhich python3\n> /usr/bin/python3\nwhich pip\n> ~/.local/bin/pip\nwhich pip3\n> ~/.local/bin/pip3\n ln -sf /usr/local/bin/python3.11 /usr/bin/python\nln -sf /usr/local/bin/python3.11 /usr/bin/python3\nln -sf /usr/local/bin/pip3.11 ~/.local/bin/pip\nln -sf /usr/local/bin/pip3.11 ~/.local/bin/pip3\n ln -s -f ln"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17851346/"
] |
74,541,297
|
<p>i want to ask whether or not if it's possible to detect a website that isn't available or a website can't be reach in python?
<a href="https://i.stack.imgur.com/nxNzJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nxNzJ.png" alt="Odoo" /></a></p>
<p>And there is also a site where it says "The site can't be reached", and when checking the network it says status "(Failed)"</p>
<p><a href="https://i.stack.imgur.com/E1v90.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E1v90.png" alt="Status failed" /></a></p>
<p>To detect a site i used this code.</p>
<pre><code>import requests
exist=[]
for b in Phishing:
try:
request = requests.get(b)
if request.status_code == 200:
exist.append(b)
print('Exist')
elif request.status_code == 204:
print('user does not exist')
elif request.status_code == 304:
print('Not available')
elif request.status_code == 504:
print('Timeout')
elif request.status_code == (failed):
print('failed')
except:
print('Not Exist')
</code></pre>
<p>So far the code that i used to detect a website is this. I'm open for suggestion on how to improve the code.</p>
<p>Thank you!</p>
|
[
{
"answer_id": 74541356,
"author": "xunjie liu",
"author_id": 16934422,
"author_profile": "https://Stackoverflow.com/users/16934422",
"pm_score": 1,
"selected": false,
"text": "❯ pyenv global 3.10.5\n\n❯ pyenv versions\n system\n 3.7.10\n* 3.10.5 (set by /home/xunjie/.pyenv/version)\n 3.10.8\n\n❯ which python\n/home/xunjie/.pyenv/shims/python\n\n❯ which pip \n/home/xunjie/.pyenv/shims/pip\n"
},
{
"answer_id": 74541385,
"author": "Constantin Hong",
"author_id": 20307768,
"author_profile": "https://Stackoverflow.com/users/20307768",
"pm_score": 0,
"selected": false,
"text": "/usr/local/bin/python3 -m pip install pip\n /usr/local/bin/python3 -m pip install <package>\n python python3 whereis python3.11\n > python3.11: /usr/local/bin/python3.11 /usr/local/share/man/man1/python3.11.1\n which pip3.11\n > /usr/local/bin/pip3.11\n which python\nwhich python3\nwhich pip\nwhich pip3\n which python\n> /usr/bin/python\nwhich python3\n> /usr/bin/python3\nwhich pip\n> ~/.local/bin/pip\nwhich pip3\n> ~/.local/bin/pip3\n ln -sf /usr/local/bin/python3.11 /usr/bin/python\nln -sf /usr/local/bin/python3.11 /usr/bin/python3\nln -sf /usr/local/bin/pip3.11 ~/.local/bin/pip\nln -sf /usr/local/bin/pip3.11 ~/.local/bin/pip3\n ln -s -f ln"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20465007/"
] |
74,541,361
|
<p>I keep running into a "character string is not in a standard unambiguous format" error.</p>
<ul>
<li>I have multiple dataframes (close to 100) with several different <em>'Date'</em> columns, including some called <em>'Period'</em>... these are formatted slightly differently</li>
<li>The goal is to quickly iterate over the dataframes, identify any <em>'Period'</em> or <em>'Date'</em> columns and increase the date value by 1 year.</li>
<li>Some of the values in <em>'Period'</em> or <em>'Date'</em> columns may be blank/missing</li>
<li>This needs to be dynamic in the event another <em>'Date'</em> column is added to one of the dataframes in the future</li>
</ul>
<p>Here a simplified version of the problem I'm working on:</p>
<pre><code>grp = c("A","A","A","A","A","A","A")
Period =c('','','201901','201901','201902','201902','201903')
Date_Begin = c('','','2019-01-31','2019-01-13','2019-02-01','2019-02-01','2019-03-25')
Date_End = c('','','2019-03-31','2019-04-25','2019-03-01','2019-06-30','2019-07-25')
col4X = c(0,0,"",1.5,1.75,1,NA)
col5Y = c(2,2,2,2,2,2,2)
df1x = data.frame(grp,Period,Date_Begin,Date_End,col4X,col5Y)
grp = c("A","A","A","A","A","A","A")
Period =c('','','201904','201904','201907','201907','201908')
Date_Start = c('','','2019-04-30','2019-01-13','2019-02-01','2019-02-01','2019-03-25')
Date_End = c('','','2019-07-31','2019-04-25','2019-03-11','2019-06-25','2019-07-20')
Expected_Date = c('','','2019-02-28','2019-06-25','2019-03-06','2019-06-25','2019-07-20')
col4X = c(0,0,"",1.5,1.75,1,NA)
col5Y = c(2,2,2,2,2,2,2)
df2x = data.frame(grp,Period,Date_Start,Date_End,Expected_Date,col4X,col5Y)
df_list <- list(df1x, df2x)
rep_fun <- function(df){
mutate(df, across(matches("Date"), ~ as.Date(.) + 365),
across(matches("Period"), ~ (as.Date(paste0(., "01"), "%Y%m%d") + 365) %>% format("%Y%m")))
}
lapply(df_list, function(x) rep_fun(x))
</code></pre>
|
[
{
"answer_id": 74541356,
"author": "xunjie liu",
"author_id": 16934422,
"author_profile": "https://Stackoverflow.com/users/16934422",
"pm_score": 1,
"selected": false,
"text": "❯ pyenv global 3.10.5\n\n❯ pyenv versions\n system\n 3.7.10\n* 3.10.5 (set by /home/xunjie/.pyenv/version)\n 3.10.8\n\n❯ which python\n/home/xunjie/.pyenv/shims/python\n\n❯ which pip \n/home/xunjie/.pyenv/shims/pip\n"
},
{
"answer_id": 74541385,
"author": "Constantin Hong",
"author_id": 20307768,
"author_profile": "https://Stackoverflow.com/users/20307768",
"pm_score": 0,
"selected": false,
"text": "/usr/local/bin/python3 -m pip install pip\n /usr/local/bin/python3 -m pip install <package>\n python python3 whereis python3.11\n > python3.11: /usr/local/bin/python3.11 /usr/local/share/man/man1/python3.11.1\n which pip3.11\n > /usr/local/bin/pip3.11\n which python\nwhich python3\nwhich pip\nwhich pip3\n which python\n> /usr/bin/python\nwhich python3\n> /usr/bin/python3\nwhich pip\n> ~/.local/bin/pip\nwhich pip3\n> ~/.local/bin/pip3\n ln -sf /usr/local/bin/python3.11 /usr/bin/python\nln -sf /usr/local/bin/python3.11 /usr/bin/python3\nln -sf /usr/local/bin/pip3.11 ~/.local/bin/pip\nln -sf /usr/local/bin/pip3.11 ~/.local/bin/pip3\n ln -s -f ln"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10686274/"
] |
74,541,363
|
<p>I want to remove the underscore <strong>"_"</strong> from the column entries of <strong>col1</strong> only when the underscore is the last character.</p>
<p>Example:</p>
<pre><code>data1 <- c("foo_bar_","bar_foo","apple_","apple__beer_")
df <- data.frame("col1"=data1,"col2"=1:4)
df
</code></pre>
<pre><code> col1 col2
foo_bar_ 1
bar_foo 2
apple_ 3
apple__beer_ 4
</code></pre>
<p><strong>Desired output:</strong></p>
<pre><code> col1 col2
foo_bar 1
bar_foo 2
apple 3
apple__beer 4
</code></pre>
<p>Thank you in advance for your time and help!</p>
|
[
{
"answer_id": 74541356,
"author": "xunjie liu",
"author_id": 16934422,
"author_profile": "https://Stackoverflow.com/users/16934422",
"pm_score": 1,
"selected": false,
"text": "❯ pyenv global 3.10.5\n\n❯ pyenv versions\n system\n 3.7.10\n* 3.10.5 (set by /home/xunjie/.pyenv/version)\n 3.10.8\n\n❯ which python\n/home/xunjie/.pyenv/shims/python\n\n❯ which pip \n/home/xunjie/.pyenv/shims/pip\n"
},
{
"answer_id": 74541385,
"author": "Constantin Hong",
"author_id": 20307768,
"author_profile": "https://Stackoverflow.com/users/20307768",
"pm_score": 0,
"selected": false,
"text": "/usr/local/bin/python3 -m pip install pip\n /usr/local/bin/python3 -m pip install <package>\n python python3 whereis python3.11\n > python3.11: /usr/local/bin/python3.11 /usr/local/share/man/man1/python3.11.1\n which pip3.11\n > /usr/local/bin/pip3.11\n which python\nwhich python3\nwhich pip\nwhich pip3\n which python\n> /usr/bin/python\nwhich python3\n> /usr/bin/python3\nwhich pip\n> ~/.local/bin/pip\nwhich pip3\n> ~/.local/bin/pip3\n ln -sf /usr/local/bin/python3.11 /usr/bin/python\nln -sf /usr/local/bin/python3.11 /usr/bin/python3\nln -sf /usr/local/bin/pip3.11 ~/.local/bin/pip\nln -sf /usr/local/bin/pip3.11 ~/.local/bin/pip3\n ln -s -f ln"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15891880/"
] |
74,541,368
|
<p>when the batch job finish, what will the ApplicationCluster state suppose to be?
Is 'increase restartNonce' a by designed way to re-run the job?</p>
<p>i am trying to use flink operator to deploy a flink batch job, and trigger it with a kubernetes cronjob every day at a certain time</p>
|
[
{
"answer_id": 74556544,
"author": "gix",
"author_id": 15058454,
"author_profile": "https://Stackoverflow.com/users/15058454",
"pm_score": 0,
"selected": false,
"text": "2022-11-24 06:14:30,314 INFO org.apache.flink.runtime.executiongraph.ExecutionGraph [] - Job Streaming WordCount (24d8e9726de88ab201ea13d48e9cdc8e) switched from state RUNNING to FINISHED.\n2022-11-24 06:14:30,314 INFO org.apache.flink.runtime.checkpoint.CheckpointCoordinator [] - Stopping checkpoint coordinator for job 24d8e9726de88ab201ea13d48e9cdc8e.\n2022-11-24 06:14:30,315 INFO org.apache.flink.runtime.dispatcher.StandaloneDispatcher [] - Job 24d8e9726de88ab201ea13d48e9cdc8e reached terminal state FINISHED.\n2022-11-24 06:14:30,317 INFO org.apache.flink.runtime.jobmaster.JobMaster [] - Stopping the JobMaster for job 'Streaming WordCount' (24d8e9726de88ab201ea13d48e9cdc8e).\n2022-11-24 06:14:30,317 INFO org.apache.flink.runtime.checkpoint.StandaloneCompletedCheckpointStore [] - Shutting down\n2022-11-24 06:14:30,317 INFO org.apache.flink.runtime.jobmaster.slotpool.DefaultDeclarativeSlotPool [] - Releasing slot [5a259aa9f56d090c4c4df02ca2e4f189].\n2022-11-24 06:14:30,318 INFO org.apache.flink.runtime.jobmaster.slotpool.DefaultDeclarativeSlotPool [] - Releasing slot [7eb2fecceb9aff71e2daa4d358c8031a].\n2022-11-24 06:14:30,318 INFO org.apache.flink.runtime.jobmaster.JobMaster [] - Close ResourceManager connection abe9ce776ee288f79d2e0a1921fb0896: Stopping JobMaster for job 'Streaming WordCount' (24d8e9726de88ab201ea13d48e9cdc8e).\n2022-11-24 06:14:30,318 INFO org.apache.flink.runtime.resourcemanager.active.ActiveResourceManager [] - Disconnect job manager 00000000000000000000000000000000@akka.tcp://flink@gix-flink-cluster.flink-examples:6123/user/rpc/jobmanager_4 for job 24d8e9726de88ab201ea13d48e9cdc8e from the resource manager.\n2022-11-24 06:15:26,189 INFO org.apache.flink.runtime.resourcemanager.active.ActiveResourceManager [] - Stopping worker gix-flink-cluster-taskmanager-1-3.\n2022-11-24 06:15:26,189 INFO org.apache.flink.kubernetes.KubernetesResourceManagerDriver [] - Stopping TaskManager pod gix-flink-cluster-taskmanager-1-3.\n2022-11-24 06:15:26,189 INFO org.apache.flink.runtime.resourcemanager.active.ActiveResourceManager [] - Closing TaskExecutor connection gix-flink-cluster-taskmanager-1-3 because: TaskExecutor exceeded the idle timeout.\n2022-11-24 06:15:26,204 WARN org.apache.flink.runtime.resourcemanager.active.ActiveResourceManager [] - Discard registration from TaskExecutor gix-flink-cluster-taskmanager-1-3 at (akka.tcp://flink@10.238.15.21:6122/user/rpc/taskmanager_0) because the framework did not recognize it\n2022-11-24 06:15:26,626 WARN akka.remote.ReliableDeliverySupervisor [] - Association with remote system [akka.tcp://flink@10.238.15.21:6122] has failed, address is now gated for [50] ms. Reason: [Disassociated] \n2022-11-24 06:15:26,626 WARN akka.remote.ReliableDeliverySupervisor [] - Association with remote system [akka.tcp://flink-metrics@10.238.15.21:46779] has failed, address is now gated for [50] ms. Reason: [Disassociated] \n2022-11-24 06:20:29,079 ERROR org.apache.flink.runtime.rest.handler.job.JobCancellationHandler [] - Exception occurred in REST handler: Job could not be found.\n2022-11-24 06:20:31,111 ERROR org.apache.flink.runtime.rest.handler.job.JobCancellationHandler [] - Exception occurred in REST handler: Job could not be found.\n2022-11-24 06:20:33,122 ERROR org.apache.flink.runtime.rest.handler.job.JobCancellationHandler [] - Exception occurred in REST handler: Job could not be found.\n2022-11-24 06:20:36,152 ERROR org.apache.flink.runtime.rest.handler.job.JobCancellationHandler [] - Exception occurred in REST handler: Job could not be found.\n2022-11-24 06:20:40,663 ERROR org.apache.flink.runtime.rest.handler.job.JobCancellationHandler [] - Exception occurred in REST handler: Job could not be found.\n2022-11-24 06:20:47,427 ERROR org.apache.flink.runtime.rest.handler.job.JobCancellationHandler [] - Exception occurred in REST handler: Job could not be found.\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15058454/"
] |
74,541,372
|
<p>I have a pandas dataframe that looks like this...</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<th>my_column</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td></td>
</tr>
<tr>
<td>1</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td></td>
</tr>
<tr>
<td>6</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>What I need to do is conditionally assign values to 'my_column' depending on the index. The first three rows should have the values 'dog', 'cat', 'bird'. Then, the next three rows should also have 'dog', 'cat', 'bird'. That pattern should apply until the end of the dataset.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<th>my_column</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>dog</td>
</tr>
<tr>
<td>1</td>
<td>cat</td>
</tr>
<tr>
<td>2</td>
<td>bird</td>
</tr>
<tr>
<td>3</td>
<td>dog</td>
</tr>
<tr>
<td>4</td>
<td>cat</td>
</tr>
<tr>
<td>5</td>
<td>bird</td>
</tr>
<tr>
<td>6</td>
<td>dog</td>
</tr>
</tbody>
</table>
</div>
<p>I've tried the following code to no avail.</p>
<pre><code>for index, row in df.iterrows():
counter=3
my_column='dog'
if counter>3
break
else
counter+=1
my_column='cat'
counter+=1
if counter>3
break
else
counter+=1
my_column='bird'
if counter>3
break
</code></pre>
|
[
{
"answer_id": 74556544,
"author": "gix",
"author_id": 15058454,
"author_profile": "https://Stackoverflow.com/users/15058454",
"pm_score": 0,
"selected": false,
"text": "2022-11-24 06:14:30,314 INFO org.apache.flink.runtime.executiongraph.ExecutionGraph [] - Job Streaming WordCount (24d8e9726de88ab201ea13d48e9cdc8e) switched from state RUNNING to FINISHED.\n2022-11-24 06:14:30,314 INFO org.apache.flink.runtime.checkpoint.CheckpointCoordinator [] - Stopping checkpoint coordinator for job 24d8e9726de88ab201ea13d48e9cdc8e.\n2022-11-24 06:14:30,315 INFO org.apache.flink.runtime.dispatcher.StandaloneDispatcher [] - Job 24d8e9726de88ab201ea13d48e9cdc8e reached terminal state FINISHED.\n2022-11-24 06:14:30,317 INFO org.apache.flink.runtime.jobmaster.JobMaster [] - Stopping the JobMaster for job 'Streaming WordCount' (24d8e9726de88ab201ea13d48e9cdc8e).\n2022-11-24 06:14:30,317 INFO org.apache.flink.runtime.checkpoint.StandaloneCompletedCheckpointStore [] - Shutting down\n2022-11-24 06:14:30,317 INFO org.apache.flink.runtime.jobmaster.slotpool.DefaultDeclarativeSlotPool [] - Releasing slot [5a259aa9f56d090c4c4df02ca2e4f189].\n2022-11-24 06:14:30,318 INFO org.apache.flink.runtime.jobmaster.slotpool.DefaultDeclarativeSlotPool [] - Releasing slot [7eb2fecceb9aff71e2daa4d358c8031a].\n2022-11-24 06:14:30,318 INFO org.apache.flink.runtime.jobmaster.JobMaster [] - Close ResourceManager connection abe9ce776ee288f79d2e0a1921fb0896: Stopping JobMaster for job 'Streaming WordCount' (24d8e9726de88ab201ea13d48e9cdc8e).\n2022-11-24 06:14:30,318 INFO org.apache.flink.runtime.resourcemanager.active.ActiveResourceManager [] - Disconnect job manager 00000000000000000000000000000000@akka.tcp://flink@gix-flink-cluster.flink-examples:6123/user/rpc/jobmanager_4 for job 24d8e9726de88ab201ea13d48e9cdc8e from the resource manager.\n2022-11-24 06:15:26,189 INFO org.apache.flink.runtime.resourcemanager.active.ActiveResourceManager [] - Stopping worker gix-flink-cluster-taskmanager-1-3.\n2022-11-24 06:15:26,189 INFO org.apache.flink.kubernetes.KubernetesResourceManagerDriver [] - Stopping TaskManager pod gix-flink-cluster-taskmanager-1-3.\n2022-11-24 06:15:26,189 INFO org.apache.flink.runtime.resourcemanager.active.ActiveResourceManager [] - Closing TaskExecutor connection gix-flink-cluster-taskmanager-1-3 because: TaskExecutor exceeded the idle timeout.\n2022-11-24 06:15:26,204 WARN org.apache.flink.runtime.resourcemanager.active.ActiveResourceManager [] - Discard registration from TaskExecutor gix-flink-cluster-taskmanager-1-3 at (akka.tcp://flink@10.238.15.21:6122/user/rpc/taskmanager_0) because the framework did not recognize it\n2022-11-24 06:15:26,626 WARN akka.remote.ReliableDeliverySupervisor [] - Association with remote system [akka.tcp://flink@10.238.15.21:6122] has failed, address is now gated for [50] ms. Reason: [Disassociated] \n2022-11-24 06:15:26,626 WARN akka.remote.ReliableDeliverySupervisor [] - Association with remote system [akka.tcp://flink-metrics@10.238.15.21:46779] has failed, address is now gated for [50] ms. Reason: [Disassociated] \n2022-11-24 06:20:29,079 ERROR org.apache.flink.runtime.rest.handler.job.JobCancellationHandler [] - Exception occurred in REST handler: Job could not be found.\n2022-11-24 06:20:31,111 ERROR org.apache.flink.runtime.rest.handler.job.JobCancellationHandler [] - Exception occurred in REST handler: Job could not be found.\n2022-11-24 06:20:33,122 ERROR org.apache.flink.runtime.rest.handler.job.JobCancellationHandler [] - Exception occurred in REST handler: Job could not be found.\n2022-11-24 06:20:36,152 ERROR org.apache.flink.runtime.rest.handler.job.JobCancellationHandler [] - Exception occurred in REST handler: Job could not be found.\n2022-11-24 06:20:40,663 ERROR org.apache.flink.runtime.rest.handler.job.JobCancellationHandler [] - Exception occurred in REST handler: Job could not be found.\n2022-11-24 06:20:47,427 ERROR org.apache.flink.runtime.rest.handler.job.JobCancellationHandler [] - Exception occurred in REST handler: Job could not be found.\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443317/"
] |
74,541,391
|
<p>I need a css flex way to set 2 items per row and in each row the second item to expand with width auto.</p>
<p>I tried a lot of things, like setting margin-right:auto for second item in each row, but is not working.</p>
<p>Here is what I have now:</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>div{
display:flex;
flex-wrap:wrap;
}
div span{
background:red;
margin:2px;
white-space:nowrap;
}
div span:nth-child(2),
div span:nth-child(4),
div span:nth-child(6){
flex-basis:100%;
background:yellow;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<span>aaa</span>
<span>bbbbbb</span>
<span>ccccccccc</span>
<span>ddd</span>
<span>eee</span>
<span>fff</span>
</div></code></pre>
</div>
</div>
</p>
<p>The text inside a flex item should not wrap.</p>
<p>Here is the result I need:</p>
<p><a href="https://i.stack.imgur.com/UslIf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UslIf.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74541818,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 1,
"selected": false,
"text": "<style> <style>\ndiv {\n /* edit left span width here */\n --left-span-width: 150px;\n /* edit gap of span here */\n --span-gap: 2px;\n\n display: flex;\n flex-wrap: wrap;\n gap: var(--span-gap);\n}\n\ndiv span:nth-child(odd) {\n width: calc(var(--left-span-width) - var(--span-gap));\n background: red;\n text-overflow: ellipsis;\n overflow: hidden;\n white-space: nowrap;\n}\n\ndiv span:nth-child(even) {\n flex: 1 1 calc(100% - var(--left-span-width));\n background: yellow;\n text-overflow: ellipsis;\n overflow: hidden;\n white-space: nowrap;\n}\n</style>\n<div>\n <span>aaa</span>\n <span>bbbbbb</span>\n <span>ccccccccc ccccccccc ccccccccc</span>\n <span>ddd</span>\n <span>eee</span>\n <span>fff</span>\n</div>"
},
{
"answer_id": 74544626,
"author": "Spyr0",
"author_id": 16905893,
"author_profile": "https://Stackoverflow.com/users/16905893",
"pm_score": 0,
"selected": false,
"text": ".item {\n width: 100%\n}\n\n.container {\n display: flex;\n flex-wrap: wrap;\n}\n\n.container > span {\n flex: 50%; /* or - flex: 0 50% - or - flex-basis: 50% - */\n margin-bottom: 10px;\n} \nspan:nth-child(odd) {\n background-color: red;\n}\n\nspan:nth-child(even) {\n background-color: yellow;\n} <div class=\"container\">\n <span class=\"item\">aaa</span>\n <span class=\"item\">bbbbbb</span>\n <span class=\"item\">ccccccccccccccccccccccccccccccccccccc</span>\n <span class=\"item\">ddd</span>\n <span class=\"item\">eee</span>\n <span class=\"item\">fff</span>\n\n</div>"
},
{
"answer_id": 74551647,
"author": "Michael Benjamin",
"author_id": 3597276,
"author_profile": "https://Stackoverflow.com/users/3597276",
"pm_score": 3,
"selected": true,
"text": " div {\n display: grid;\n grid-template-columns: min-content 1fr;\n }\n\n div span {\n background: red;\n }\n\n div span:nth-child(2),\n div span:nth-child(4),\n div span:nth-child(6) {\n background: yellow;\n } <div>\n <span>aaa</span>\n <span>bbbbbb </span>\n <span>ccccccccc</span>\n <span>ddd</span>\n <span>eee</span>\n <span>fff</span>\n</div> grid-template-columns min-content 1fr"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7551933/"
] |
74,541,396
|
<p>I wanted a div to show after a number of seconds, thus I have made it into two parts, one is a php that echoes that div, and the second is a javascript that replaces the div with another div after some seconds. The problem is before that javascript is executed, The div code shows for 2-3 seconds. Which I do not want. May be we can do this in just PHP?
This is the PHP code</p>
<pre><code>if(isset($_GET['id']))
{
$slide = $_GET["id"];
$mytitle='Your id is '.$slide.' ,Welcome';
$murl='"https://example.com/?id='.$slide.'"';
echo '<div id="countdown"> </div>';
echo '<div id="loader"></div>';
echo '<div id="welcome"><a href='.$murl.'>'.$mytitle.'</a></div>';
</div>';
}
</code></pre>
<p>This is the javascript</p>
<pre><code><script>
window.onload = function() {
var countdownElement = document.getElementById("countdown"),
welcomeButton = document.getElementById("welcome"),
loader=document.getElementById("loader"),
seconds = 30,
second = 0,
interval;
welcomeButton.style.display = "none";
interval = setInterval(function() {
countdownElement.firstChild.data = "Preparing your welcome in " + (seconds - second) + " seconds, Please wait";
if (second >= seconds) {
welcomeButton.style.display = "block";
loader.style.display="none";
clearInterval(interval);
}
second++;
}, 1000);
}
</script>
</code></pre>
|
[
{
"answer_id": 74541603,
"author": "foder",
"author_id": 15083460,
"author_profile": "https://Stackoverflow.com/users/15083460",
"pm_score": 3,
"selected": true,
"text": "welcome style=\"display: none\" welcomeButton.style.display = \"none\";"
},
{
"answer_id": 74541638,
"author": "Maxim Mazurok",
"author_id": 4536543,
"author_profile": "https://Stackoverflow.com/users/4536543",
"pm_score": 1,
"selected": false,
"text": "?welcome=off header( \"refresh:5;url=wherever.php\" );"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913390/"
] |
74,541,416
|
<p>How can I remove text(e.g ["88664734","88639280","88676217"]) from a strReviewers string which contains list of Reviewers separated by semicolon and then join the whole string again either using JavaScript or jQuery?</p>
<p>I get a dynamic string(strReviewers) which contains multiple user records separated by comma:</p>
<p>I need to remove whole user record if I pass an array of ids. e.g ["88664734","88639280","88676217"]</p>
<pre class="lang-js prettyprint-override"><code>var strReviewers = "88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*";
</code></pre>
<p>strReviewers contains user records separated by semicolon and each user record is separated by <em>,</em>.</p>
<p>Each record contains 1 user which is in the shape of userid then following by name then following by roleid then following by txtSpeciality following by then rolelist.</p>
<pre class="lang-js prettyprint-override"><code>/*
88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;
*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;
*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;
*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;
*/
</code></pre>
<p>I have done it using the following code but wondering this can be achieved some other easier way?</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>var strReviewers = "88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*";
function removeReviewerByID(ids = []) {
return strReviewers
.split(";")
.map(item => item.split("*,*"))
.filter(item => item[0] !== "*")
.map(item => ({
userid:item[0],
name:item[1],
roleid:item[2],
txtSpeciality:item[3],
rolelist:item[4]
}))
.filter(item => (!ids.includes(item["userid"]) && !ids.includes(item["userid"].replace(/\*/g, ''))))
.map(item => ({
record: item["userid"].concat("*,*").concat(item["name"]).concat("*,*").concat(item["roleid"]).concat("*,*").concat(item["txtSpeciality"]).concat("*,*").concat(item["rolelist"]).concat(";")
}))
.reduce((accumulator, item) => {
return accumulator.concat(item["record"]);
}, "")
}
console.log(removeReviewerByID(["88664734","88639280","88676217"]));</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74541507,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 3,
"selected": true,
"text": "| .match(/.*?\\*;\\*/g) .split(\";\") * ,*;* var strReviewers = \"88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*\";\n\nfunction removeReviewerByID(ids = []) {\n const pattern = new RegExp(`^(?:${ids.join('|')})\\\\*`);\n return strReviewers\n .match(/.*?\\*;\\*/g)\n .filter(str => !pattern.test(str))\n .join('');\n}\n\nconsole.log(removeReviewerByID([\"88664734\", \"88639280\", \"88676217\"])); var strReviewers = \"88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*\";\n\nfunction removeReviewerByID(ids = []) {\n const pattern = new RegExp(\n String.raw`(?:^|(?<=\\*;\\*))(?:${ids.join('|')})\\*.*?\\*;\\*`,\n 'g'\n );\n return strReviewers.replace(pattern, '');\n}\n\nconsole.log(removeReviewerByID([\"88664734\", \"88639280\", \"88676217\"])); /(?:^|(?<=\\*;\\*))(?:88664734|88639280|88676217)\\*.*?\\*;\\*/g (?:^|(?<=\\*;\\*)) ^ (?<=\\*;\\*) *;* (?:88664734|88639280|88676217) \\* * .*? \\*;\\* *;*"
},
{
"answer_id": 74541562,
"author": "naveen",
"author_id": 17447,
"author_profile": "https://Stackoverflow.com/users/17447",
"pm_score": 0,
"selected": false,
"text": "var strReviewers = \"88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*\";\nvar excluded = [\"88664734\",\"88639280\",\"88676217\"];\nvar result = strReviewers\n .split(';')\n .reduce((acc, curr) => {\n let userid = curr.split('*,*')[0].replace(/\\*/, ''); //remove * from userid\n if(!excluded.includes(userid)) {\n acc.push(curr);\n }\n return acc;\n }, [])\n .join(';');\nconsole.log(result);"
},
{
"answer_id": 74542246,
"author": "Peter Thoeny",
"author_id": 7475450,
"author_profile": "https://Stackoverflow.com/users/7475450",
"pm_score": 1,
"selected": false,
"text": ".split() .filter() .join() var strReviewers = \"88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*\";\nvar excluded = [\"88664734\",\"88639280\",\"88676217\"];\nvar excludedRegex = new RegExp('\\\\*?(' + excluded.join('|') + ')\\\\b');\n//var excludedRegex = new RegExp(excluded.join('|'));\nvar result = strReviewers\n .split(';')\n .filter(item => !item.match(excludedRegex))\n .join(';');\nconsole.log(result); *88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*\n excludedRegex excluded"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/603380/"
] |
74,541,421
|
<p>To preface this question, I'm a hobby programmer that's been learning on/off for the past 7 years, and mostly dabbled with Node.JS in several different settings and projects. I now decided to take the leap to another major language and picked up C# to start learning game development and the likes. I am in the process of building a skill tree and I can't really understand how to store the information I need for each skill in a clean and orderly fashion without a bunch of empty GameObjects (Unity) holding that info.</p>
<p>I know (at least my favorite way of) how to do this in Node.JS, but I can't find the right information on converting this to C#.</p>
<p>Node.JS example</p>
<pre><code>var skillTree = [
{
name: "Skill1",
effect: skill1Func,
unlocked: true,
prereqs: [ ]
},
{
name: "Skill2",
effect: skill2Func,
unlocked: false,
prereqs: [1, 5]
}
];
</code></pre>
<p>As you can see, it's just an array of objects, all following the same properties, but the properties are pre-determined instead of added. I just can't find the right path to go to store this information for use in C#, so if anyone could help me out, that would be appreciated!</p>
|
[
{
"answer_id": 74541507,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 3,
"selected": true,
"text": "| .match(/.*?\\*;\\*/g) .split(\";\") * ,*;* var strReviewers = \"88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*\";\n\nfunction removeReviewerByID(ids = []) {\n const pattern = new RegExp(`^(?:${ids.join('|')})\\\\*`);\n return strReviewers\n .match(/.*?\\*;\\*/g)\n .filter(str => !pattern.test(str))\n .join('');\n}\n\nconsole.log(removeReviewerByID([\"88664734\", \"88639280\", \"88676217\"])); var strReviewers = \"88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*\";\n\nfunction removeReviewerByID(ids = []) {\n const pattern = new RegExp(\n String.raw`(?:^|(?<=\\*;\\*))(?:${ids.join('|')})\\*.*?\\*;\\*`,\n 'g'\n );\n return strReviewers.replace(pattern, '');\n}\n\nconsole.log(removeReviewerByID([\"88664734\", \"88639280\", \"88676217\"])); /(?:^|(?<=\\*;\\*))(?:88664734|88639280|88676217)\\*.*?\\*;\\*/g (?:^|(?<=\\*;\\*)) ^ (?<=\\*;\\*) *;* (?:88664734|88639280|88676217) \\* * .*? \\*;\\* *;*"
},
{
"answer_id": 74541562,
"author": "naveen",
"author_id": 17447,
"author_profile": "https://Stackoverflow.com/users/17447",
"pm_score": 0,
"selected": false,
"text": "var strReviewers = \"88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*\";\nvar excluded = [\"88664734\",\"88639280\",\"88676217\"];\nvar result = strReviewers\n .split(';')\n .reduce((acc, curr) => {\n let userid = curr.split('*,*')[0].replace(/\\*/, ''); //remove * from userid\n if(!excluded.includes(userid)) {\n acc.push(curr);\n }\n return acc;\n }, [])\n .join(';');\nconsole.log(result);"
},
{
"answer_id": 74542246,
"author": "Peter Thoeny",
"author_id": 7475450,
"author_profile": "https://Stackoverflow.com/users/7475450",
"pm_score": 1,
"selected": false,
"text": ".split() .filter() .join() var strReviewers = \"88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*\";\nvar excluded = [\"88664734\",\"88639280\",\"88676217\"];\nvar excludedRegex = new RegExp('\\\\*?(' + excluded.join('|') + ')\\\\b');\n//var excludedRegex = new RegExp(excluded.join('|'));\nvar result = strReviewers\n .split(';')\n .filter(item => !item.match(excludedRegex))\n .join(';');\nconsole.log(result); *88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*\n excludedRegex excluded"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11689154/"
] |
74,541,429
|
<p>I was trying to make a customizable grid (by default 16x16) but when it's created there's gaps in between cells.</p>
<p>CSS:</p>
<pre><code>#container{
position: relative;
margin: auto;
width: 800px;
height: 800px;
border: none;
outline: 2px solid red;
padding: 0;
}
.grid{
margin: 0;
padding: 0;
outline: 1px solid black;
border: none;
display: inline-block;
}
</code></pre>
<p>JavaScript:</p>
<pre><code>let gridSize = 0;
const btn = document.querySelector("#btn");
btn.addEventListener("click", function(){
let input = prompt("Enter a grid size (100 or lower):");
createGrid(input);
});
const container = document.querySelector("#container");
createGrid(16);
function createGrid(rows){
rows = parseInt(rows);
gridSize = rows * rows;
container.innerHTML = "";
for(let i = 0; i < gridSize; i++){
const div = document.createElement("div");
div.className = `grid`;
container.appendChild(div);
}
const style = document.createElement("style");
style.innerText = `
.grid{
height: ${800/rows}px;
width: ${800/rows}px;
}`;
const body = document.head.appendChild(style);
}
</code></pre>
<p>In summary the grid is made with Javascript by appending it to a container in html. I included it in case is relevant since there are some changes of styles and I imagine it has something to do with that.</p>
|
[
{
"answer_id": 74541507,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 3,
"selected": true,
"text": "| .match(/.*?\\*;\\*/g) .split(\";\") * ,*;* var strReviewers = \"88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*\";\n\nfunction removeReviewerByID(ids = []) {\n const pattern = new RegExp(`^(?:${ids.join('|')})\\\\*`);\n return strReviewers\n .match(/.*?\\*;\\*/g)\n .filter(str => !pattern.test(str))\n .join('');\n}\n\nconsole.log(removeReviewerByID([\"88664734\", \"88639280\", \"88676217\"])); var strReviewers = \"88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*\";\n\nfunction removeReviewerByID(ids = []) {\n const pattern = new RegExp(\n String.raw`(?:^|(?<=\\*;\\*))(?:${ids.join('|')})\\*.*?\\*;\\*`,\n 'g'\n );\n return strReviewers.replace(pattern, '');\n}\n\nconsole.log(removeReviewerByID([\"88664734\", \"88639280\", \"88676217\"])); /(?:^|(?<=\\*;\\*))(?:88664734|88639280|88676217)\\*.*?\\*;\\*/g (?:^|(?<=\\*;\\*)) ^ (?<=\\*;\\*) *;* (?:88664734|88639280|88676217) \\* * .*? \\*;\\* *;*"
},
{
"answer_id": 74541562,
"author": "naveen",
"author_id": 17447,
"author_profile": "https://Stackoverflow.com/users/17447",
"pm_score": 0,
"selected": false,
"text": "var strReviewers = \"88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*\";\nvar excluded = [\"88664734\",\"88639280\",\"88676217\"];\nvar result = strReviewers\n .split(';')\n .reduce((acc, curr) => {\n let userid = curr.split('*,*')[0].replace(/\\*/, ''); //remove * from userid\n if(!excluded.includes(userid)) {\n acc.push(curr);\n }\n return acc;\n }, [])\n .join(';');\nconsole.log(result);"
},
{
"answer_id": 74542246,
"author": "Peter Thoeny",
"author_id": 7475450,
"author_profile": "https://Stackoverflow.com/users/7475450",
"pm_score": 1,
"selected": false,
"text": ".split() .filter() .join() var strReviewers = \"88664734*,*Andrew Farmer*,*19042*,**,*,19013,19017,19042,19043,19051,*;*88639280*,*Sally Hopewell*,*19042*,**,*,19013,19017,19042,19043,*;*88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*88676217*,*James Wason*,*19042*,**,*,19013,19017,19042,19043,*;*\";\nvar excluded = [\"88664734\",\"88639280\",\"88676217\"];\nvar excludedRegex = new RegExp('\\\\*?(' + excluded.join('|') + ')\\\\b');\n//var excludedRegex = new RegExp(excluded.join('|'));\nvar result = strReviewers\n .split(';')\n .filter(item => !item.match(excludedRegex))\n .join(';');\nconsole.log(result); *88686221*,*Jonathan Rees*,*19042*,**,*,19013,19017,19042,19043,19060,*;*\n excludedRegex excluded"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20434868/"
] |
74,541,460
|
<p>I would like to get the bare minimum amount of words that would be needed to create a collection of strings. For
example:</p>
<p>"hi hello hello",
"hello",
"bye",
"bye bye",
"hello hello",</p>
<p>The intended output for this example would be string[] {"bye", "bye", "hello", "hello", "hi"} in no particular order.</p>
<p>I did a string.Join() on the starting array, and I wanted to use a HashSet to get the unique strings, but for some reason I couldn’t import it.</p>
<p>My goal was to get the highest count for each word, and then duplicate each word into the final string array.</p>
|
[
{
"answer_id": 74541791,
"author": "Tim Jarosz",
"author_id": 2452207,
"author_profile": "https://Stackoverflow.com/users/2452207",
"pm_score": -1,
"selected": false,
"text": "string[] strList = new string[] { \"hi hello hello\", \"hello\", \"bye\", \"bye bye\", \"hello hello\" };\n\nList<string> wordList = new List<string>();\n\n//Break each string into an array of words.\nforeach (string s in strList) {\n wordList.AddRange(s.Split(' '));\n}\n\n//Get a list of distinct words.\nList<string> distinctWords = wordList.Distinct().ToList();\n\n//Dictionary to hold the minimal count of words required to comprise the original strings\nDictionary<string, int> wordMinCountDict = new Dictionary<string, int>();\n\n//Loop through each distinct word.\n//Find the number of times it occurs in each of the original strings.\n//Collect the highest count of the number of times the word occurs in the string.\nforeach(string w in distinctWords)\n{\n foreach(string s in strList)\n {\n int instanceCount = s.Split(' ').ToList().FindAll(p => p == w).Count();\n if (instanceCount > 0)\n {\n if (wordMinCountDict.TryGetValue(w, out int i))\n {\n if (instanceCount > i)\n {\n wordMinCountDict.Remove(w);\n wordMinCountDict.Add(w, instanceCount);\n }\n }\n else\n {\n wordMinCountDict.Add(w, instanceCount);\n }\n }\n }\n}\n\n//Create a new list with the number of occurrences of each word.\nList<string> finalWords = new List<string>();\nforeach(KeyValuePair<string, int> kvp in wordMinCountDict)\n{\n if (kvp.Value < 1) continue;\n finalWords.AddRange(Enumerable.Repeat(kvp.Key, kvp.Value).ToList());\n}\n\n//Use .ToArray() to convert finalWords to final array. (not neccessary in the next statement but left in as an example.)\nConsole.WriteLine(string.Join(\" \", finalWords.ToArray()));\n"
},
{
"answer_id": 74541831,
"author": "shingo",
"author_id": 6196568,
"author_profile": "https://Stackoverflow.com/users/6196568",
"pm_score": 1,
"selected": false,
"text": "// (hi), (hello hello)\n// (hello)\n// (bye)\n// (bye bye)\n// (hello hello)\nvar strs = new string[]{\"hi hello hello\", \"hello\",\"bye\", \"bye bye\", \"hello hello\"};\nvar result = strs.Select(str => str.Split(' ').GroupBy(word => word))\n // hi => 1\n// hello => 2\n// hello => 1\n// bye => 1\n// bye => 2\n// hello => 2\n.SelectMany(groups => groups)\n.Select(group => KeyValuePair.Create(group.Key, group.Count()))\n Enumerable.Repeat // hi => 1\n// hello => 2, hello => 1, hello => 2\n// bye => 1, bye => 2\n.GroupBy(group => group.Key)\n.SelectMany(group => Enumerable.Repeat(group.Key, group.Max(g => g.Value)))\n.ToArray();\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8261220/"
] |
74,541,463
|
<p>I'd like to be able to do something like...</p>
<pre><code>typedef struct{
int type;
}foo_t;
foo_t *foo = foo_init();
*(int*)foo = 1;
</code></pre>
<p>or</p>
<pre><code>typedef struct{
int type;
}bar_t;
typedef struct{
bar_t header;
}foo_t;
foo_t *foo = foo_init();
((bar_t*)foo)->type = 1;
</code></pre>
<p>...do one or both of these violate C's strict aliasing rule? The latter seems more common and I wasn't sure if that was because of it's cleaner syntax or if the extra struct was necessary to get around strict aliasing.</p>
|
[
{
"answer_id": 74541695,
"author": "Joop Eggen",
"author_id": 984823,
"author_profile": "https://Stackoverflow.com/users/984823",
"pm_score": 0,
"selected": false,
"text": "foo->type = 1;\n\nfoo->header.type = 1;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2418731/"
] |
74,541,484
|
<p>I have a set of APIs purely for my own app, so I just have a simple API to create access token, when user provided the <code>email</code> and <code>password</code></p>
<p><code>/api/access_token</code> (return <code>access_token</code> when <code>email</code> and <code>password</code> matched)</p>
<p>The <code>access_token</code> was saved and matched against in the database <code>sessions</code> table with the <code>expiry</code> field, for now, the expiry is <code>one week</code>, so user need to re-login after one week.</p>
<p>So far it worked fine, but if I want to have the <code>remember me</code> functions as those Facebook / Twitter app, which mean user don't need to re-login so often, which I assume they are using something like the <code>OAuth refresh access tokens</code> approach.</p>
<p>Since I am not using those OAuth stuffs, given my current design and setup, what would be the simplest and secure way to achieve the same functionalities?</p>
|
[
{
"answer_id": 74634792,
"author": "regex",
"author_id": 9470979,
"author_profile": "https://Stackoverflow.com/users/9470979",
"pm_score": 0,
"selected": false,
"text": "/api/access_token /api/logout"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/398230/"
] |
74,541,506
|
<p>I have a date which look like this "Corporate Services\Corporate Affairs & Communications(DP19)"</p>
<p>I want to the result to be like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>Corporate Service</td>
<td>Corporate Affairs & Communications (DP19)</td>
</tr>
</tbody>
</table>
</div>
<p>I already tried using substring but no luck,
I am using Microsoft SQL</p>
|
[
{
"answer_id": 74634792,
"author": "regex",
"author_id": 9470979,
"author_profile": "https://Stackoverflow.com/users/9470979",
"pm_score": 0,
"selected": false,
"text": "/api/access_token /api/logout"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16302625/"
] |
74,541,535
|
<p>I have a table. In one of the columns of the table , the values have this form:</p>
<p><code>Value1(12) Value2(45) Value3(35) Value4(37) Value5(17)</code></p>
<p>How to delete the opening parenthesis, the value inside the parentheses and the closing parenthesis? So that after updating the values would take this form:</p>
<p><code>Value1 Value2 Value3 Value4 Value5</code></p>
<p><strong>P.s:</strong> It seems that regular expressions will help here, but how to form a query with them?</p>
|
[
{
"answer_id": 74634792,
"author": "regex",
"author_id": 9470979,
"author_profile": "https://Stackoverflow.com/users/9470979",
"pm_score": 0,
"selected": false,
"text": "/api/access_token /api/logout"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19980395/"
] |
74,541,585
|
<p>I have some patterns which detect questions and splits on top of that. there are some assumptions which I'm using like:</p>
<ol>
<li>Every pattern starts with a <code>\n</code></li>
<li>Every pattern ends with <code>\s+</code></li>
</ol>
<p>And how I define a pattern is like:</p>
<pre><code><NUM>.
Q <NUM>.
Q <NUM>
<Q.NUM.>
<NUM>
Question <NUM>
<Example>
Problem <NUM>
Problem:
<Alphabet><Number>.
<EXAMPLE>
Example <NUM>
</code></pre>
<p><a href="https://regex101.com/r/sxSUBM/1" rel="nofollow noreferrer">Someone suggested the below regex: try the demo</a></p>
<pre><code>((Q|Question|Problem:?|Example|EXAMPLE)\.? ?\d+\.? ?|(Question|Problem:?|Example|EXAMPLE) ?)
</code></pre>
<p>but it captures patterns in the middle which is problematic for me because I can have <code>Q.</code> , <code>Example. 2</code> in the middle of the string too and is not capturing <code><NUM>.</code></p>
<p>This list is based on priority so what I could come up with is building these many expressions and running a loop based on the priority for example:</p>
<pre><code>QUESTIONS = [
re.compile("\n\d+\."),
re.compile("\nQ.\s*\d+\."),
re.compile("\nExample.\s*\d+\.")
]
</code></pre>
<p>but it is very inefficient. How can I club these in one expression?</p>
<p><a href="https://i.stack.imgur.com/aukIy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aukIy.png" alt="enter image description here" /></a></p>
<p><strong>HERE IS THE TEST STRING</strong>:</p>
<pre><code>'TEStlabZ\nEDULABZ\nINTERNATIONAL\nLOGARITHMS AND INDICES\n\nQ.1. (A) Convert each of the following to logarithmic form.\n(i) \\( 5^{2}=25 \\)\n(ii) \\( 3^{-3}=\\frac{1}{27} \\)\n(iii) \\( (64)^{\\frac{1}{3}}=4 \\)\n(iv) \\( 6^{0}=1 \\)\n(v) \\( 10^{-2}=0.01 \\) (vi) \\( 4^{-1}=\\frac{1}{4} \\)\nAns. We know that \\( a^{b}=x \\Rightarrow b=\\log _{a} x \\)\n(i) \\( 5^{2}=25 \\quad \\therefore \\log _{5} 25=2 \\)\n(ii) \\( 3^{-3}=\\frac{1}{27} \\therefore \\log _{3}\\left(\\frac{1}{27}\\right)=-3 \\)\n(iii) \\( (64)^{\\frac{1}{3}}=4 \\therefore \\log _{64} 4=\\frac{1}{3} \\)\n(iv) \\( 6^{0}=1 \\quad \\therefore \\log _{6} 1=0 \\)\n(v) \\( 10^{-2}=0.01 \\therefore \\log _{10}(0.01)=-2 \\)\n(vi) \\( 4^{-1}=\\frac{1}{4} \\therefore \\log _{4}\\left(\\frac{1}{4}\\right)=-1 \\)\nQ.1. (B) Convert each of the following to exponential form.\n(i) \\( \\log _{3} 81=4 \\)\n(ii) \\( \\log _{8} 4=\\frac{2}{3} \\)\n(iii) \\( \\log _{2} \\frac{1}{8}=-3 \\)\n(iv) \\( \\log _{10}(0.01)=-2 \\)\n(v) \\( \\log _{5}\\left(\\frac{1}{5}\\right)=-1 \\) (vi) \\( \\log _{a} 1=0 \\)\nAns.\n(i) \\( \\log _{3} 81=4 \\quad \\therefore 3^{4}=81 \\)\n(ii) \\( \\log _{8} 4=\\frac{2}{3} \\quad \\therefore 8^{\\frac{2}{3}}=4 \\)\n(iii) \\( \\log _{2} \\frac{1}{8}=-3 \\quad \\therefore \\quad 2^{-3}=\\frac{1}{8} \\)\n(iv) \\( \\log _{10}(0.01)=-2 \\quad \\therefore \\quad 10^{-2}=0.01 \\)\n(v) \\( \\log _{5}\\left(\\frac{1}{5}\\right)=-1 \\quad \\therefore \\quad 5^{-1}=\\frac{1}{5} \\)\n(vi) \\( \\log _{a} 1=0 \\)\n\\( \\therefore a^{0}=1 \\)\nMath Class IX\n1\nQuestion Bank'
</code></pre>
|
[
{
"answer_id": 74541693,
"author": "dc-ddfe",
"author_id": 18709498,
"author_profile": "https://Stackoverflow.com/users/18709498",
"pm_score": 0,
"selected": false,
"text": "^(\\d+\\.|Q \\d+\\.|Q \\d+|Q\\.\\d+\\.|\\d+|Question \\d+|Example( \\d+)?|Problem \\d+|Problem:|[A-Z]\\d\\.|EXAMPLE)\\s+"
},
{
"answer_id": 74570282,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": true,
"text": "(?m)^(?!$)(?:((?i:Question|Problem:?|Example)|[A-Z])[. ]?)?(\\d+[. ]?)?(?=\\s)\n (?m)^ m ^ (?!$) (?:((?i:Question|Problem:?|Example)|[A-Z])[. ]?)? ((?i:Question|Problem:?|Example)|[A-Z]) Question Problem Problem: Example [. ]? . (\\d+[. ]?)? . (?=\\s)"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11725056/"
] |
74,541,604
|
<p>I have four textfields, a title field, a details field, a date field, and a time field. Both the date and time fields are wrapped within a gesture detector, and onTap calls a <code>pickDateAndTime</code> method. The problem is that when I click on the date field and try to manually change the time through the input rather than the dial way, the focus goes to the title field and when I am still on the time picker and type something in the time picker, the title field gets changed with the new input. The weird part is that this error just appeared out of nowhere, and there are no errors reported in the console.</p>
<pre><code>class TodoScreen extends StatefulWidget {
final int? todoIndex;
final int? arrayIndex;
const TodoScreen({Key? key, this.todoIndex, this.arrayIndex})
: super(key: key);
@override
State<TodoScreen> createState() => _TodoScreenState();
}
class _TodoScreenState extends State<TodoScreen> {
final ArrayController arrayController = Get.find();
final AuthController authController = Get.find();
final String uid = Get.find<AuthController>().user!.uid;
late TextEditingController _dateController;
late TextEditingController _timeController;
late TextEditingController titleEditingController;
late TextEditingController detailEditingController;
late String _setTime, _setDate;
late String _hour, _minute, _time;
late String dateTime;
late bool done;
@override
void initState() {
super.initState();
String title = '';
String detail = '';
String date = '';
String? time = '';
if (widget.todoIndex != null) {
title = arrayController
.arrays[widget.arrayIndex!].todos![widget.todoIndex!].title ??
'';
detail = arrayController
.arrays[widget.arrayIndex!].todos![widget.todoIndex!].details ??
'';
date = arrayController
.arrays[widget.arrayIndex!].todos![widget.todoIndex!].date!;
time = arrayController
.arrays[widget.arrayIndex!].todos![widget.todoIndex!].time;
}
_dateController = TextEditingController(text: date);
_timeController = TextEditingController(text: time);
titleEditingController = TextEditingController(text: title);
detailEditingController = TextEditingController(text: detail);
done = (widget.todoIndex == null)
? false
: arrayController
.arrays[widget.arrayIndex!].todos![widget.todoIndex!].done!;
}
DateTime selectedDate = DateTime.now();
TimeOfDay selectedTime = TimeOfDay(
hour: (TimeOfDay.now().minute > 55)
? TimeOfDay.now().hour + 1
: TimeOfDay.now().hour,
minute: (TimeOfDay.now().minute > 55) ? 0 : TimeOfDay.now().minute + 5);
Future<DateTime?> _selectDate() => showDatePicker(
builder: (context, child) {
return datePickerTheme(child);
},
initialEntryMode: DatePickerEntryMode.calendarOnly,
context: context,
initialDate: selectedDate,
initialDatePickerMode: DatePickerMode.day,
firstDate: DateTime.now(),
lastDate: DateTime(DateTime.now().year + 5));
Future<TimeOfDay?> _selectTime() => showTimePicker(
builder: (context, child) {
return timePickerTheme(child);
},
context: context,
initialTime: selectedTime,
initialEntryMode: TimePickerEntryMode.input);
Future _pickDateTime() async {
DateTime? date = await _selectDate();
if (date == null) return;
if (date != null) {
selectedDate = date;
_dateController.text = DateFormat("MM/dd/yyyy").format(selectedDate);
}
TimeOfDay? time = await _selectTime();
if (time == null) {
_timeController.text = formatDate(
DateTime(
DateTime.now().year,
DateTime.now().day,
DateTime.now().month,
DateTime.now().hour,
DateTime.now().minute + 5),
[hh, ':', nn, " ", am]).toString();
}
if (time != null) {
selectedTime = time;
_hour = selectedTime.hour.toString();
_minute = selectedTime.minute.toString();
_time = '$_hour : $_minute';
_timeController.text = _time;
_timeController.text = formatDate(
DateTime(2019, 08, 1, selectedTime.hour, selectedTime.minute),
[hh, ':', nn, " ", am]).toString();
}
}
@override
Widget build(BuildContext context) {
bool visible =
(_dateController.text.isEmpty && _timeController.text.isEmpty)
? false
: true;
final formKey = GlobalKey<FormState>();
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
title: Text((widget.todoIndex == null) ? 'New Task' : 'Edit Task',
style: menuTextStyle),
leadingWidth: (MediaQuery.of(context).size.width < 768) ? 90.0 : 100.0,
leading: Center(
child: Padding(
padding: (MediaQuery.of(context).size.width < 768)
? const EdgeInsets.only(left: 0)
: const EdgeInsets.only(left: 21.0),
child: TextButton(
style: const ButtonStyle(
splashFactory: NoSplash.splashFactory,
),
onPressed: () {
Get.back();
},
child: Text(
"Cancel",
style: paragraphPrimary,
),
),
),
),
centerTitle: true,
actions: [
Center(
child: Padding(
padding: (MediaQuery.of(context).size.width < 768)
? const EdgeInsets.only(left: 0)
: const EdgeInsets.only(right: 21.0),
child: TextButton(
style: const ButtonStyle(
splashFactory: NoSplash.splashFactory,
),
onPressed: () async {
},
child: Text((widget.todoIndex == null) ? 'Add' : 'Update',
style: paragraphPrimary),
),
),
)
],
),
body: SafeArea(
child: Container(
width: double.infinity,
padding: (MediaQuery.of(context).size.width < 768)
? const EdgeInsets.symmetric(horizontal: 15.0, vertical: 20.0)
: const EdgeInsets.symmetric(horizontal: 35.0, vertical: 15.0),
child: Column(
children: [
Form(
key: formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
validator: Validator.titleValidator,
controller: titleEditingController,
autofocus: true, // problem here
autocorrect: false,
cursorColor: Colors.grey,
maxLines: 1,
maxLength: 25,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
counterStyle: counterTextStyle,
hintStyle: hintTextStyle,
hintText: "Title",
border: InputBorder.none),
style: todoScreenStyle),
primaryDivider,
TextField(
controller: detailEditingController,
maxLines: null,
autocorrect: false,
cursorColor: Colors.grey,
textInputAction: TextInputAction.done,
decoration: InputDecoration(
counterStyle: counterTextStyle,
hintStyle: hintTextStyle,
hintText: "Notes",
border: InputBorder.none),
style: todoScreenDetailsStyle),
],
),
),
Visibility(
visible: (widget.todoIndex != null) ? true : false,
child: GestureDetector(
onTap: () {},
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Completed",
style: todoScreenStyle,
),
Transform.scale(
scale: 1.3,
child: Theme(
data: ThemeData(
unselectedWidgetColor: const Color.fromARGB(
255, 187, 187, 187)),
child: Checkbox(
shape: const CircleBorder(),
checkColor: Colors.white,
activeColor: primaryColor,
value: done,
side: Theme.of(context).checkboxTheme.side,
onChanged: (value) {
setState(() {
done = value!;
});
})),
)
],
),
),
),
GestureDetector(
onTap: () async {
await _pickDateTime();
setState(() {
visible = true;
});
},
child: Column(
children: [
Row(
children: [
Flexible(
child: TextField(
enabled: false,
controller: _dateController,
onChanged: (String val) {
_setDate = val;
},
decoration: InputDecoration(
hintText: "Date",
hintStyle: hintTextStyle,
border: InputBorder.none),
style: todoScreenStyle,
),
),
visible
? IconButton(
onPressed: () {
_dateController.clear();
_timeController.clear();
setState(() {});
},
icon: const Icon(
Icons.close,
color: Colors.white,
))
: Container()
],
),
primaryDivider,
TextField(
onChanged: (String val) {
_setTime = val;
},
enabled: false,
controller: _timeController,
decoration: InputDecoration(
hintText: "Time",
hintStyle: hintTextStyle,
border: InputBorder.none),
style: todoScreenStyle,
)
],
),
),
],
),
),
),
);
}
}
</code></pre>
<p>Should I open an issue on Github, as I had not made any changes to the code for it behave this way and also because there were no errors in the console</p>
<p>Here is the full code on <a href="https://github.com/Rohith-JN/Tasks-Android/blob/main/lib/View/TodoScreen.dart" rel="nofollow noreferrer">Github</a></p>
<p><strong>Update</strong></p>
<p>Here is a reproducible example:</p>
<pre><code>import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const TodoScreen(),
);
}
}
class TodoScreen extends StatefulWidget {
const TodoScreen({Key? key}) : super(key: key);
@override
State<TodoScreen> createState() => _TodoScreenState();
}
class _TodoScreenState extends State<TodoScreen> {
late TextEditingController _dateController;
late TextEditingController _timeController;
late TextEditingController titleEditingController;
late TextEditingController detailEditingController;
late String _setTime, _setDate;
late String _hour, _minute, _time;
late String dateTime;
@override
void initState() {
super.initState();
String title = '';
String detail = '';
String date = '';
String? time = '';
_dateController = TextEditingController(text: date);
_timeController = TextEditingController(text: time);
titleEditingController = TextEditingController(text: title);
detailEditingController = TextEditingController(text: detail);
}
@override
void dispose() {
super.dispose();
titleEditingController.dispose();
detailEditingController.dispose();
_timeController.dispose();
_dateController.dispose();
}
Theme timePickerTheme(child) => Theme(
data: ThemeData.dark().copyWith(
timePickerTheme: TimePickerThemeData(
backgroundColor: const Color.fromARGB(255, 70, 70, 70),
dayPeriodTextColor: Colors.green,
hourMinuteTextColor: MaterialStateColor.resolveWith((states) =>
states.contains(MaterialState.selected)
? Colors.white
: Colors.white),
dialHandColor: Colors.green,
helpTextStyle: TextStyle(
fontSize: 12, fontWeight: FontWeight.bold, color: Colors.green),
dialTextColor: MaterialStateColor.resolveWith((states) =>
states.contains(MaterialState.selected)
? Colors.white
: Colors.white),
entryModeIconColor: Colors.green,
),
textButtonTheme: TextButtonThemeData(
style: ButtonStyle(
foregroundColor:
MaterialStateColor.resolveWith((states) => Colors.green)),
),
),
child: child!,
);
Theme datePickerTheme(child) => Theme(
data: ThemeData.dark().copyWith(
colorScheme: ColorScheme.dark(
surface: Colors.green,
secondary: Colors.green,
onPrimary: Colors.white,
onSurface: Colors.white,
primary: Colors.green,
)),
child: child!,
);
DateTime selectedDate = DateTime.now();
TimeOfDay selectedTime = TimeOfDay(
hour: (TimeOfDay.now().minute > 55)
? TimeOfDay.now().hour + 1
: TimeOfDay.now().hour,
minute: (TimeOfDay.now().minute > 55) ? 0 : TimeOfDay.now().minute + 5);
Future<DateTime?> _selectDate() => showDatePicker(
builder: (context, child) {
return datePickerTheme(child);
},
initialEntryMode: DatePickerEntryMode.calendarOnly,
context: context,
initialDate: selectedDate,
initialDatePickerMode: DatePickerMode.day,
firstDate: DateTime.now(),
lastDate: DateTime(DateTime.now().year + 5));
Future<TimeOfDay?> _selectTime() => showTimePicker(
builder: (context, child) {
return timePickerTheme(child);
},
context: context,
initialTime: selectedTime,
initialEntryMode: TimePickerEntryMode.input);
Future _pickDateTime() async {
DateTime? date = await _selectDate();
if (date == null) return;
if (date != null) {
selectedDate = date;
_dateController.text = selectedDate.toString();
}
TimeOfDay? time = await _selectTime();
if (time != null) {
selectedTime = time;
_hour = selectedTime.hour.toString();
_minute = selectedTime.minute.toString();
_time = '$_hour : $_minute';
_timeController.text = _time;
_timeController.text =
DateTime(2019, 08, 1, selectedTime.hour, selectedTime.minute)
.toString();
}
}
@override
Widget build(BuildContext context) {
bool visible =
(_dateController.text.isEmpty && _timeController.text.isEmpty)
? false
: true;
final formKey = GlobalKey<FormState>();
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
centerTitle: true,
),
body: SafeArea(
child: Container(
width: double.infinity,
padding: (MediaQuery.of(context).size.width < 768)
? const EdgeInsets.symmetric(horizontal: 15.0, vertical: 20.0)
: const EdgeInsets.symmetric(horizontal: 35.0, vertical: 15.0),
child: Column(
children: [
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(14.0)),
padding: const EdgeInsets.symmetric(
horizontal: 24.0, vertical: 15.0),
child: Form(
key: formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: titleEditingController,
autofocus: true,
autocorrect: false,
cursorColor: Colors.grey,
maxLines: 1,
maxLength: 25,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
hintText: "Title", border: InputBorder.none),
),
Divider(color: Colors.black),
TextField(
controller: detailEditingController,
maxLines: null,
autocorrect: false,
cursorColor: Colors.grey,
textInputAction: TextInputAction.done,
decoration: InputDecoration(
hintText: "Notes", border: InputBorder.none),
),
],
),
)),
GestureDetector(
onTap: () async {
await _pickDateTime();
setState(() {
visible = true;
});
},
child: Container(
margin: const EdgeInsets.only(top: 20.0),
width: double.infinity,
padding: const EdgeInsets.symmetric(
horizontal: 24.0, vertical: 15.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(14.0)),
child: Column(
children: [
Row(
children: [
Flexible(
child: TextField(
enabled: false,
controller: _dateController,
onChanged: (String val) {
_setDate = val;
},
decoration: InputDecoration(
hintText: "Date", border: InputBorder.none),
),
),
visible
? IconButton(
onPressed: () {
_dateController.clear();
_timeController.clear();
setState(() {});
},
icon: const Icon(
Icons.close,
color: Colors.white,
))
: Container()
],
),
Divider(
color: Colors.blue,
),
TextField(
onChanged: (String val) {
_setTime = val;
},
enabled: false,
controller: _timeController,
decoration: InputDecoration(
hintText: "Enter", border: InputBorder.none),
)
],
)),
),
],
),
),
),
);
}
}
</code></pre>
|
[
{
"answer_id": 74541703,
"author": "Texv",
"author_id": 10841432,
"author_profile": "https://Stackoverflow.com/users/10841432",
"pm_score": 0,
"selected": false,
"text": "FocusNode focusNode = FocusNode();\n\nTextField(\n focusNode: focusNode,\n);\n FocusScope.of(context).requestFocus(FocusNode());\n"
},
{
"answer_id": 74541749,
"author": "Mashood .H",
"author_id": 12777999,
"author_profile": "https://Stackoverflow.com/users/12777999",
"pm_score": 0,
"selected": false,
"text": "FocusScope.of(context).requestFocus(FocusNode()); GestureDetector(\n onTap: () {\n FocusScope.of(context).requestFocus(FocusNode());\n },\n child: Scaffold()\n)\n"
},
{
"answer_id": 74541758,
"author": "Nice umang",
"author_id": 10835478,
"author_profile": "https://Stackoverflow.com/users/10835478",
"pm_score": 0,
"selected": false,
"text": " FocusScopeNode currentFocus = FocusScope.of(context);\n if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {\n currentFocus.unfocus();\n }\n"
},
{
"answer_id": 74543585,
"author": "Eric Aig",
"author_id": 3410660,
"author_profile": "https://Stackoverflow.com/users/3410660",
"pm_score": 2,
"selected": true,
"text": "main.dart void main() async {\n WidgetsFlutterBinding.ensureInitialized();\n\n runApp(const MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n const MyApp({Key? key}) : super(key: key);\n\n // This widget is the root of your application.\n @override\n Widget build(BuildContext context) {\n return GestureDetector(\n onTap: () {\n // This allows closing keyboard when tapping outside of a text field\n FocusScopeNode currentFocus = FocusScope.of(context);\n\n if (!currentFocus.hasPrimaryFocus &&\n currentFocus.focusedChild != null) {\n FocusManager.instance.primaryFocus!.unfocus();\n }\n },\n child: // your app's entry point,\n );\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15747757/"
] |
74,541,629
|
<p>I have a hash, i want to know if any param does not exist or is empty</p>
<p>how is does not exist? in this case does not exist the param 'b'</p>
<pre><code> {"a"=>"first", "c"=>"5"}
</code></pre>
<p>and empty element is like this: <code>"a"=>""</code></p>
<pre><code>{"a"=>"", "b"=>"b", "c"=>"5"}
</code></pre>
<p>this is my attempt:</p>
<pre><code>array.any?{|_,i| p i.blank?}
</code></pre>
<p><strong>output:</strong></p>
<p>if there is (all or any empty elements) then return true</p>
<p><code>[true, false]</code> output <code>true</code></p>
<p><code>[true, false,true]</code> output <code>true</code></p>
<p><code>[true, true]</code> output <code>true</code></p>
<p><code>[true, true, true]</code> output <code>true</code></p>
<p><code>[false, false]</code> output <code>false</code></p>
<p><code>[false, false, false]</code> output <code>false</code></p>
|
[
{
"answer_id": 74541678,
"author": "Rajagopalan",
"author_id": 9043475,
"author_profile": "https://Stackoverflow.com/users/9043475",
"pm_score": 2,
"selected": true,
"text": "h = { \"a\" => \"\", \"c\" => \"5\" }\n\nkeys = h.keys\nmissed_keys = [*keys.first..keys.last] - keys\n\nputs 'Missed Keys'\np missed_keys\n\nputs 'Keys which are having empty values'\np h.filter_map { |k, v| k if v.empty? }\n Missed Keys\n[\"b\"]\nKeys which are having empty values\n[\"a\"]\n p h.any? { |k, v| v.empty? }\n true\n"
},
{
"answer_id": 74542016,
"author": "Quân Hoàng",
"author_id": 7224480,
"author_profile": "https://Stackoverflow.com/users/7224480",
"pm_score": 0,
"selected": false,
"text": "blank? hash = {\"a\": 1, \"c\": \"\"}\n\ndef is_missing(hash, key)\n hash[key.to_sym].blank?\nend\n\nis_missing(hash, \"a\") => false \nis_missing(hash, \"b\") => true \nis_missing(hash, \"c\") => true \n\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503335/"
] |
74,541,634
|
<p>The regex contains a capture group, but the substitution pattern is not interpolated to reference the match variable <code>$1</code> in</p>
<pre><code>use strict;
use warnings;
my $regex = '([^ ]+)e s';
my $subst = '$1 ';
my $text = 'fine sand';
print $text =~ s/$regex/$subst/r;
print "\n";
</code></pre>
<p>The result is</p>
<blockquote>
<p>$1 and</p>
</blockquote>
<p>The solution to <a href="https://stackoverflow.com/questions/4089551/perl-regular-expression-variables-and-matched-pattern-substitution">Perl regular expression variables and matched pattern substitution</a> suggests to use the <code>e</code> modifier and <code>eval</code> in the substitution; and indeed</p>
<pre><code>print $text =~ s/$regex/eval $subst/er;
</code></pre>
<p>would give the desired</p>
<blockquote>
<p>finand</p>
</blockquote>
<p>However, in my situation, the pattern and substitution strings are read from third party user input, so they cannot be considered safe for <code>eval</code>. Is there a way to interpolate the substitution string in a more secure way than to execute it as code? All I seek here is to expand all match variables contained in the substitution string.</p>
<p>The best I can currently think of involves an idiom like</p>
<pre><code>$text =~ /$regex/;
sprintf $subst, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, ...
</code></pre>
<p>This would require a slight change in syntax for the substitution string, but I consider this acceptable. However, the set of imaginable match variables is infinite, in particular named match variables would not be supported.</p>
|
[
{
"answer_id": 74541817,
"author": "craigb",
"author_id": 20236884,
"author_profile": "https://Stackoverflow.com/users/20236884",
"pm_score": 2,
"selected": false,
"text": "$\\d+ $subst $subst use strict;\nuse warnings;\n\nmy $regex = '([^ ]+)e s';\nmy $subst = '$1 ';\n\nmy $text = 'fine sand';\n\nprint $text =~ s{$regex}{\n my @captured = @{^CAPTURE};\n $subst =~ s/\\$([1-9]\\d*)/$captured[$1-1]/rg\n}er . \"\\n\";\n @captured $ $regex"
},
{
"answer_id": 74541841,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 2,
"selected": false,
"text": "use String::Substitution qw( sub_copy );\n\nprint sub_copy( $text, $regex, $subst );\n '\\$1.00' '${1}00'"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889976/"
] |
74,541,649
|
<p>I have a db with 100 tables. I want to delete data from all tables using mysql command or in phpmyadmin</p>
|
[
{
"answer_id": 74541689,
"author": "Gowtham",
"author_id": 4082319,
"author_profile": "https://Stackoverflow.com/users/4082319",
"pm_score": 1,
"selected": false,
"text": "select concat('delete from ',TABLE_NAME,';') from information_schema.TABLES where TABLE_SCHEMA='databasename';\n"
},
{
"answer_id": 74541789,
"author": "Gowtham",
"author_id": 4082319,
"author_profile": "https://Stackoverflow.com/users/4082319",
"pm_score": 0,
"selected": false,
"text": "SET FOREIGN_KEY_CHECKS = 0;\n\nSET @TABLES = NULL;\nSELECT GROUP_CONCAT('delete from ', table_name,';') INTO @TABLES FROM information_schema.tables \n WHERE table_schema = 'databasename' and table_name in ('tbl_audit_trail','tbl_celery');\n \n\nSET @TABLES= replace( @TABLES,',','');\nselect @TABLES;\n"
},
{
"answer_id": 74541900,
"author": "Akina",
"author_id": 10138734,
"author_profile": "https://Stackoverflow.com/users/10138734",
"pm_score": 2,
"selected": false,
"text": "mysqldump --no-data"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19981866/"
] |
74,541,671
|
<p>I want to do some operations two seconds after every time a certain state is set.</p>
<p><em>Code inside viewModel:</em></p>
<pre><code>var isLoading = mutableStateOf(LoadingState.NONE)
set(value) {
Timber.d("Custom Setter") //Not Firing
//Do something when the state is set to success.
if(value.value == LoadingState.SUCCESS){
viewModelScope.launch {
delay(2000L)
dispatchEvent(//some event)
}
}
field = value
}
</code></pre>
<p>The set{} block is not running at all. But the value is being correctly set.</p>
<p>When using delegation with the <code>by</code> keyword,</p>
<p><code>Delegated property cannot have accessors with non-default implementations</code></p>
<p>Is there a way to make custom setter work for mutableStateOf() in Jetpack Compose?.</p>
|
[
{
"answer_id": 74542032,
"author": "Arpit Shukla",
"author_id": 13308991,
"author_profile": "https://Stackoverflow.com/users/13308991",
"pm_score": 4,
"selected": true,
"text": "Flow State var isLoading by mutableStateOf(LoadingState.NONE)\n private set\n\ninit {\n viewModelScope.launch {\n snapshotFlow { isLoading }\n .collect { \n if(it == LoadingState.SUCCESS) {\n delay(2000L)\n dispatchEvent(//some event)\n }\n }\n }\n}\n\n"
},
{
"answer_id": 74542351,
"author": "Amal",
"author_id": 3520225,
"author_profile": "https://Stackoverflow.com/users/3520225",
"pm_score": 0,
"selected": false,
"text": "var isLoading by mutableStateOf(LoadingState.NONE).also{ state ->\n viewModelScope.launch {\n snapshotFlow { state.value }\n .collect {\n if(it == LoadingState.SUCCESS) {\n delay(2000L)\n dispatchEvent(//Fire event)\n }\n }\n }\n }\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3520225/"
] |
74,541,684
|
<p>I am using Webview_Flutter.
The header of the site overlaps the position of the statusbar and I would like to add padding to avoid this.</p>
<p>This is the process of inserting padding to avoid the statusbar if the webview is opened or if there is a scroll position at the top.</p>
<pre><code> body: Padding(
padding: (controller?.getScrollY() == null || controller?.getScrollY() == 0)
? EdgeInsets.only(top: height)
: EdgeInsets.only(top: 0),
child: Expanded(
child: Padding(
padding: const EdgeInsets.only(bottom: 0.0),
child: WebView(
javascriptMode: JavascriptMode.unrestricted,
initialUrl: Uri.parse(widget.link).toString(),
onWebResourceError: (error) {
// print(error.domain);
},
onWebViewCreated: (controller) {
this.controller = controller;
},
onProgress: (progress) {
setState(() {
this.progress = progress / 100;
progressPercent = progress;
});
},
),
</code></pre>
|
[
{
"answer_id": 74552880,
"author": "i.AGUIR",
"author_id": 16349770,
"author_profile": "https://Stackoverflow.com/users/16349770",
"pm_score": 0,
"selected": false,
"text": "class _HomeScreenState extends State<HomeScreen> {\n WebViewController? _webViewController;\n ScrollController _scrollController = ScrollController();\n\n @override\n Widget build(BuildContext context) {\n return\n Scaffold(\n body:Scaffold(\n backgroundColor: Colors.green,\n appBar: AppBar(\n title: const Text('Flutter WebView example'),\n // This drop down menu demonstrates that Flutter widgets can be shown over the web view.\n actions: <Widget>[\n\n ],\n ),\n//NotificationListener(2)\n body: NotificationListener<ScrollNotification>(\n onNotification: (scrollNotification) {\n if (scrollNotification is ScrollStartNotification) {\n WidgetsBinding.instance.addPostFrameCallback((_) {\n print(\"ScrollStartNotification / pixel => ${scrollNotification.metrics.pixels}\");\n });\n\n } else if (scrollNotification is ScrollEndNotification) {\n WidgetsBinding.instance.addPostFrameCallback((_) {\n setState(() {\n print(\"ScrollEndNotification / pixel =>${scrollNotification.metrics.pixels}\");\n });\n });\n }\n\n return true;\n },\n child: ListView(\n physics: ClampingScrollPhysics(),\n controller: _scrollController,\n children: <Widget>[\n ConstrainedBox(\n constraints: BoxConstraints(maxHeight: 10000),\n child: WebView(\n initialUrl: 'https://flutter.dev',\n javascriptMode: JavascriptMode.unrestricted,\n onWebViewCreated: (WebViewController webViewController) {},\n onProgress: (int progress) {\n print('WebView is loading (progress : $progress%)');\n },\n javascriptChannels: <JavascriptChannel>{\n },\n onPageStarted: (String url) {},\n onPageFinished: (String url) {},\n gestureNavigationEnabled: true,\n backgroundColor: const Color(0x00000000),\n ),\n ),\n ],\n ),\n )));\n\n\n }\n\n @override\n void initState() {\n super.initState();\n//scrollListener(1)\n _scrollController.addListener(() {\n print(\"scrollListener / pixel =>${_scrollController.position.pixels}\");\n });\n }\n}\n"
},
{
"answer_id": 74567321,
"author": "Lorenzo Pichilli",
"author_id": 4637638,
"author_profile": "https://Stackoverflow.com/users/4637638",
"pm_score": 1,
"selected": false,
"text": "flutter_inappwebview InAppWebView.onScrollChanged AppBar.toolbarHeight 0 6.0.0-beta.16 import 'package:flutter/foundation.dart';\nimport 'package:flutter/material.dart';\nimport 'package:flutter_inappwebview/flutter_inappwebview.dart';\n\nFuture main() async {\n WidgetsFlutterBinding.ensureInitialized();\n if (!kIsWeb &&\n kDebugMode &&\n defaultTargetPlatform == TargetPlatform.android) {\n await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);\n }\n runApp(const MaterialApp(home: MyApp()));\n}\n\nclass MyApp extends StatefulWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n State<MyApp> createState() => _MyAppState();\n}\n\nclass _MyAppState extends State<MyApp> {\n final GlobalKey webViewKey = GlobalKey();\n\n InAppWebViewController? webViewController;\n\n int scrollY = 0;\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n toolbarHeight: 0,\n ),\n body: Padding(\n padding: EdgeInsets.only(top: scrollY <= 0 ? 25 : 0),\n child: Column(\n children: [\n Expanded(\n child: InAppWebView(\n key: webViewKey,\n initialUrlRequest:\n URLRequest(url: WebUri(\"https://github.com/flutter\")),\n onWebViewCreated: (controller) {\n webViewController = controller;\n },\n onScrollChanged: (controller, x, y) {\n setState(() {\n scrollY = y;\n });\n },\n ),\n )\n ],\n ),\n ));\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18096205/"
] |
74,541,705
|
<p>I have .txt file containing data like this. The first element is the column names sepparated by whitespace, and the next element is the data.</p>
<pre><code>['n Au[%] Ag[%] Cu[%] Zn[%] Ni[%] Pd[%] Fe[%] Cd[%] mq[ ]',
'1 71.085 4.6578 22.468 1.6971 0.0292 0.0000 0.0627 0.0000 1.1019',
'2 71.444 4.0611 22.946 1.4333 0.0400 0.0000 0.0763 0.0000 1.1298',
'3 71.845 4.2909 22.308 1.4234 0.0293 0.0000 0.1031 0.0000 1.0750',
'4 71.842 4.2794 22.290 1.4686 0.0339 0.0000 0.0856 0.0000 1.1334']
</code></pre>
<p>How can i convert this list of text into Pandas DataFrame?</p>
|
[
{
"answer_id": 74552880,
"author": "i.AGUIR",
"author_id": 16349770,
"author_profile": "https://Stackoverflow.com/users/16349770",
"pm_score": 0,
"selected": false,
"text": "class _HomeScreenState extends State<HomeScreen> {\n WebViewController? _webViewController;\n ScrollController _scrollController = ScrollController();\n\n @override\n Widget build(BuildContext context) {\n return\n Scaffold(\n body:Scaffold(\n backgroundColor: Colors.green,\n appBar: AppBar(\n title: const Text('Flutter WebView example'),\n // This drop down menu demonstrates that Flutter widgets can be shown over the web view.\n actions: <Widget>[\n\n ],\n ),\n//NotificationListener(2)\n body: NotificationListener<ScrollNotification>(\n onNotification: (scrollNotification) {\n if (scrollNotification is ScrollStartNotification) {\n WidgetsBinding.instance.addPostFrameCallback((_) {\n print(\"ScrollStartNotification / pixel => ${scrollNotification.metrics.pixels}\");\n });\n\n } else if (scrollNotification is ScrollEndNotification) {\n WidgetsBinding.instance.addPostFrameCallback((_) {\n setState(() {\n print(\"ScrollEndNotification / pixel =>${scrollNotification.metrics.pixels}\");\n });\n });\n }\n\n return true;\n },\n child: ListView(\n physics: ClampingScrollPhysics(),\n controller: _scrollController,\n children: <Widget>[\n ConstrainedBox(\n constraints: BoxConstraints(maxHeight: 10000),\n child: WebView(\n initialUrl: 'https://flutter.dev',\n javascriptMode: JavascriptMode.unrestricted,\n onWebViewCreated: (WebViewController webViewController) {},\n onProgress: (int progress) {\n print('WebView is loading (progress : $progress%)');\n },\n javascriptChannels: <JavascriptChannel>{\n },\n onPageStarted: (String url) {},\n onPageFinished: (String url) {},\n gestureNavigationEnabled: true,\n backgroundColor: const Color(0x00000000),\n ),\n ),\n ],\n ),\n )));\n\n\n }\n\n @override\n void initState() {\n super.initState();\n//scrollListener(1)\n _scrollController.addListener(() {\n print(\"scrollListener / pixel =>${_scrollController.position.pixels}\");\n });\n }\n}\n"
},
{
"answer_id": 74567321,
"author": "Lorenzo Pichilli",
"author_id": 4637638,
"author_profile": "https://Stackoverflow.com/users/4637638",
"pm_score": 1,
"selected": false,
"text": "flutter_inappwebview InAppWebView.onScrollChanged AppBar.toolbarHeight 0 6.0.0-beta.16 import 'package:flutter/foundation.dart';\nimport 'package:flutter/material.dart';\nimport 'package:flutter_inappwebview/flutter_inappwebview.dart';\n\nFuture main() async {\n WidgetsFlutterBinding.ensureInitialized();\n if (!kIsWeb &&\n kDebugMode &&\n defaultTargetPlatform == TargetPlatform.android) {\n await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);\n }\n runApp(const MaterialApp(home: MyApp()));\n}\n\nclass MyApp extends StatefulWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n State<MyApp> createState() => _MyAppState();\n}\n\nclass _MyAppState extends State<MyApp> {\n final GlobalKey webViewKey = GlobalKey();\n\n InAppWebViewController? webViewController;\n\n int scrollY = 0;\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n toolbarHeight: 0,\n ),\n body: Padding(\n padding: EdgeInsets.only(top: scrollY <= 0 ? 25 : 0),\n child: Column(\n children: [\n Expanded(\n child: InAppWebView(\n key: webViewKey,\n initialUrlRequest:\n URLRequest(url: WebUri(\"https://github.com/flutter\")),\n onWebViewCreated: (controller) {\n webViewController = controller;\n },\n onScrollChanged: (controller, x, y) {\n setState(() {\n scrollY = y;\n });\n },\n ),\n )\n ],\n ),\n ));\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9903641/"
] |
74,541,707
|
<p>I have <code>price</code> variable and which can contain:</p>
<pre><code>USD12.34
USD12,34
12,34
23.34
</code></pre>
<p>Now the output should be -</p>
<pre><code>USD12.34 - false
USD12,34 - false
12,34 - true
23.34 - true
</code></pre>
<p>Now, Using JavaScript I want to validate above data as integer which should accept <code>dot</code> and <code>comma</code>.</p>
<p>I got this code but no luck:</p>
<pre><code>const test = /^\d*(,\d{3})*(\.,\d*)?$/.test( price );
console.log( ( test ) );
</code></pre>
|
[
{
"answer_id": 74552880,
"author": "i.AGUIR",
"author_id": 16349770,
"author_profile": "https://Stackoverflow.com/users/16349770",
"pm_score": 0,
"selected": false,
"text": "class _HomeScreenState extends State<HomeScreen> {\n WebViewController? _webViewController;\n ScrollController _scrollController = ScrollController();\n\n @override\n Widget build(BuildContext context) {\n return\n Scaffold(\n body:Scaffold(\n backgroundColor: Colors.green,\n appBar: AppBar(\n title: const Text('Flutter WebView example'),\n // This drop down menu demonstrates that Flutter widgets can be shown over the web view.\n actions: <Widget>[\n\n ],\n ),\n//NotificationListener(2)\n body: NotificationListener<ScrollNotification>(\n onNotification: (scrollNotification) {\n if (scrollNotification is ScrollStartNotification) {\n WidgetsBinding.instance.addPostFrameCallback((_) {\n print(\"ScrollStartNotification / pixel => ${scrollNotification.metrics.pixels}\");\n });\n\n } else if (scrollNotification is ScrollEndNotification) {\n WidgetsBinding.instance.addPostFrameCallback((_) {\n setState(() {\n print(\"ScrollEndNotification / pixel =>${scrollNotification.metrics.pixels}\");\n });\n });\n }\n\n return true;\n },\n child: ListView(\n physics: ClampingScrollPhysics(),\n controller: _scrollController,\n children: <Widget>[\n ConstrainedBox(\n constraints: BoxConstraints(maxHeight: 10000),\n child: WebView(\n initialUrl: 'https://flutter.dev',\n javascriptMode: JavascriptMode.unrestricted,\n onWebViewCreated: (WebViewController webViewController) {},\n onProgress: (int progress) {\n print('WebView is loading (progress : $progress%)');\n },\n javascriptChannels: <JavascriptChannel>{\n },\n onPageStarted: (String url) {},\n onPageFinished: (String url) {},\n gestureNavigationEnabled: true,\n backgroundColor: const Color(0x00000000),\n ),\n ),\n ],\n ),\n )));\n\n\n }\n\n @override\n void initState() {\n super.initState();\n//scrollListener(1)\n _scrollController.addListener(() {\n print(\"scrollListener / pixel =>${_scrollController.position.pixels}\");\n });\n }\n}\n"
},
{
"answer_id": 74567321,
"author": "Lorenzo Pichilli",
"author_id": 4637638,
"author_profile": "https://Stackoverflow.com/users/4637638",
"pm_score": 1,
"selected": false,
"text": "flutter_inappwebview InAppWebView.onScrollChanged AppBar.toolbarHeight 0 6.0.0-beta.16 import 'package:flutter/foundation.dart';\nimport 'package:flutter/material.dart';\nimport 'package:flutter_inappwebview/flutter_inappwebview.dart';\n\nFuture main() async {\n WidgetsFlutterBinding.ensureInitialized();\n if (!kIsWeb &&\n kDebugMode &&\n defaultTargetPlatform == TargetPlatform.android) {\n await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);\n }\n runApp(const MaterialApp(home: MyApp()));\n}\n\nclass MyApp extends StatefulWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n State<MyApp> createState() => _MyAppState();\n}\n\nclass _MyAppState extends State<MyApp> {\n final GlobalKey webViewKey = GlobalKey();\n\n InAppWebViewController? webViewController;\n\n int scrollY = 0;\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n toolbarHeight: 0,\n ),\n body: Padding(\n padding: EdgeInsets.only(top: scrollY <= 0 ? 25 : 0),\n child: Column(\n children: [\n Expanded(\n child: InAppWebView(\n key: webViewKey,\n initialUrlRequest:\n URLRequest(url: WebUri(\"https://github.com/flutter\")),\n onWebViewCreated: (controller) {\n webViewController = controller;\n },\n onScrollChanged: (controller, x, y) {\n setState(() {\n scrollY = y;\n });\n },\n ),\n )\n ],\n ),\n ));\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1091439/"
] |
74,541,711
|
<p>I'm trying to apply use a loop to use the function fastp on a nextflow block, but I'm not sure how to set up a loop with two variables. I would want to change --in1 and --in2 to be the forward and reverse read pair to get an outputted file for each.</p>
<pre><code>#!/usr/bin/env nextflow
nextflow.enable.dsl=2
workflow {
FASTP()
}
process FASTP {
script:
"""
fastp
--in1 ${baseDir}/sequences/sequences_split/SRR19573234_R1.fastq
--in2 ${baseDir}/sequences/sequences_split/SRR19573234_R2.fastq
--out1 ${baseDir}/sequences/sequences_split/sequences_trimmed/trimmed_SRR19573234_R1.fastq
--out2 ${baseDir}/sequences/sequences_split/sequences_trimmed/trimmed_SRR19573234_R2.fastq
--html ${baseDir}/results/trimmed_SRR19573234.fastp.html
fastp
--in1 ${baseDir}/sequences/sequences_split/SRR19573260_R1.fastq
--in2 ${baseDir}/sequences/sequences_split/SRR19573260_R2.fastq
--out1 ${baseDir}/sequences/sequences_split/sequences_trimmed/trimmed_SRR19573260_R1.fastq
--out2 ${baseDir}/sequences/sequences_split/sequences_trimmed/trimmed_SRR19573260_R2.fastq
--html ${baseDir}/results/trimmed_SRR19573260.fastp.html
"""
}
</code></pre>
|
[
{
"answer_id": 74552880,
"author": "i.AGUIR",
"author_id": 16349770,
"author_profile": "https://Stackoverflow.com/users/16349770",
"pm_score": 0,
"selected": false,
"text": "class _HomeScreenState extends State<HomeScreen> {\n WebViewController? _webViewController;\n ScrollController _scrollController = ScrollController();\n\n @override\n Widget build(BuildContext context) {\n return\n Scaffold(\n body:Scaffold(\n backgroundColor: Colors.green,\n appBar: AppBar(\n title: const Text('Flutter WebView example'),\n // This drop down menu demonstrates that Flutter widgets can be shown over the web view.\n actions: <Widget>[\n\n ],\n ),\n//NotificationListener(2)\n body: NotificationListener<ScrollNotification>(\n onNotification: (scrollNotification) {\n if (scrollNotification is ScrollStartNotification) {\n WidgetsBinding.instance.addPostFrameCallback((_) {\n print(\"ScrollStartNotification / pixel => ${scrollNotification.metrics.pixels}\");\n });\n\n } else if (scrollNotification is ScrollEndNotification) {\n WidgetsBinding.instance.addPostFrameCallback((_) {\n setState(() {\n print(\"ScrollEndNotification / pixel =>${scrollNotification.metrics.pixels}\");\n });\n });\n }\n\n return true;\n },\n child: ListView(\n physics: ClampingScrollPhysics(),\n controller: _scrollController,\n children: <Widget>[\n ConstrainedBox(\n constraints: BoxConstraints(maxHeight: 10000),\n child: WebView(\n initialUrl: 'https://flutter.dev',\n javascriptMode: JavascriptMode.unrestricted,\n onWebViewCreated: (WebViewController webViewController) {},\n onProgress: (int progress) {\n print('WebView is loading (progress : $progress%)');\n },\n javascriptChannels: <JavascriptChannel>{\n },\n onPageStarted: (String url) {},\n onPageFinished: (String url) {},\n gestureNavigationEnabled: true,\n backgroundColor: const Color(0x00000000),\n ),\n ),\n ],\n ),\n )));\n\n\n }\n\n @override\n void initState() {\n super.initState();\n//scrollListener(1)\n _scrollController.addListener(() {\n print(\"scrollListener / pixel =>${_scrollController.position.pixels}\");\n });\n }\n}\n"
},
{
"answer_id": 74567321,
"author": "Lorenzo Pichilli",
"author_id": 4637638,
"author_profile": "https://Stackoverflow.com/users/4637638",
"pm_score": 1,
"selected": false,
"text": "flutter_inappwebview InAppWebView.onScrollChanged AppBar.toolbarHeight 0 6.0.0-beta.16 import 'package:flutter/foundation.dart';\nimport 'package:flutter/material.dart';\nimport 'package:flutter_inappwebview/flutter_inappwebview.dart';\n\nFuture main() async {\n WidgetsFlutterBinding.ensureInitialized();\n if (!kIsWeb &&\n kDebugMode &&\n defaultTargetPlatform == TargetPlatform.android) {\n await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);\n }\n runApp(const MaterialApp(home: MyApp()));\n}\n\nclass MyApp extends StatefulWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n State<MyApp> createState() => _MyAppState();\n}\n\nclass _MyAppState extends State<MyApp> {\n final GlobalKey webViewKey = GlobalKey();\n\n InAppWebViewController? webViewController;\n\n int scrollY = 0;\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n toolbarHeight: 0,\n ),\n body: Padding(\n padding: EdgeInsets.only(top: scrollY <= 0 ? 25 : 0),\n child: Column(\n children: [\n Expanded(\n child: InAppWebView(\n key: webViewKey,\n initialUrlRequest:\n URLRequest(url: WebUri(\"https://github.com/flutter\")),\n onWebViewCreated: (controller) {\n webViewController = controller;\n },\n onScrollChanged: (controller, x, y) {\n setState(() {\n scrollY = y;\n });\n },\n ),\n )\n ],\n ),\n ));\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19926037/"
] |
74,541,744
|
<p>I'm trying to get all constraint <code>DDL</code> from <code>ALL_CONSTRAINTS</code> using <code>SQL PLUS</code>. But <code>ORA-31603</code> arise. Like this constraint there have more constraint where name are same but their Owner are different.</p>
<p>I try this by following query</p>
<pre><code>-- Run this script in SQL*Plus.
-- don't print headers or other crap
set heading off;
set echo off;
set pagesize 0;
-- don't truncate the line output
-- trim the extra space from linesize when spooling
set long 99999;
set linesize 32767;
set trimspool on;
-- don't truncate this specific column's output
col object_ddl format A32000;
spool AIBLNGZDB_CONSTRAINT_ddl.sql;
SELECT dbms_metadata.get_ddl('CONSTRAINT', constraint_name, owner) || ';' AS object_ddl
FROM ALL_CONSTRAINTS
WHERE
OWNER = 'AIBLNGZDB'
-- AND OBJECT_TYPE IN (
-- 'CONSTRAINT'
---- 'INDEX'
---- , 'SEQUENCE'
---- , 'VIEW'
-- )
ORDER BY
OWNER
-- , OBJECT_TYPE
;
spool off;
SET LINESIZE 500
</code></pre>
|
[
{
"answer_id": 74542380,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "all_constraints all_objects SQL> select constraint_name from user_constraints;\n\nCONSTRAINT_NAME\n------------------------------\nBIN$7gsQxw2vJ/LgU8lkAQo5GQ==$0\nBIN$7gsQxw2rJ/LgU8lkAQo5GQ==$0\nSYS_C00106654\n<snip>\n\nSQL> SELECT DBMS_METADATA.get_ddl ('CONSTRAINT', c.constraint_name, c.owner)\n 2 || ';' AS object_ddl\n 3 FROM all_constraints c\n 4 WHERE c.owner = 'SCOTT'\n 5 ORDER BY c.owner;\nERROR:\nORA-31603: object \"BIN$7gsQxw2vJ/LgU8lkAQo5GQ==$0\" of type CONSTRAINT not found\nin schema \"SCOTT\"\nORA-06512: at \"SYS.DBMS_METADATA\", line 5805\nORA-06512: at \"SYS.DBMS_METADATA\", line 8344\nORA-06512: at line 1\n\n\n\nno rows selected\n\nSQL>\n all_objects SQL> SELECT DBMS_METADATA.get_ddl ('CONSTRAINT', c.constraint_name, c.owner)\n 2 || ';' AS object_ddl\n 3 FROM all_constraints c\n 4 JOIN all_objects o\n 5 ON o.owner = c.owner\n 6 AND o.object_name = c.table_name\n 7 WHERE c.owner = 'SCOTT'\n 8 ORDER BY c.owner;\n\nOBJECT_DDL\n--------------------------------------------------------------------------------\n\n ALTER TABLE \"SCOTT\".\"STUDENTS\" ADD PRIMARY KEY (\"ROLLNOSTUD\")\n USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255\n STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645\n PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n TABLESPACE \"USER_DATA\" ENABLE;\n\n\n ALTER TABLE \"SCOTT\".\"DEPARTMENT\" ADD PRIMARY KEY (\"DEPT_NO\")\n USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255\n TABLESPACE \"USER_DATA\" ENABLE;\n<snip>\n"
},
{
"answer_id": 74594991,
"author": "Jon Heller",
"author_id": 409172,
"author_profile": "https://Stackoverflow.com/users/409172",
"pm_score": 0,
"selected": false,
"text": "--Reference constraints:\nselect dbms_metadata.get_ddl('REF_CONSTRAINT', constraint_name) || ';' as object_ddl\nfrom all_constraints\nwhere owner = 'AIBLNGZDB'\n and constraint_type = 'R'\n and constraint_name not like 'BIN$%'\n\nunion all\n\n--Other kinds of constraints.\nselect dbms_metadata.get_ddl('CONSTRAINT', constraint_name) || ';' as object_ddl\nfrom all_constraints\nwhere owner = 'AIBLNGZDB'\n and constraint_type not in ('O', 'V', 'R')\n and constraint_name not like 'BIN$%';\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19930892/"
] |
74,541,750
|
<p>I have here a <code>map</code> function for an array of object
and also added some condition</p>
<pre><code> userList.map((item) => {
const newFilter = dailyData.filter((value) => {
return value.author == item.MSM;
});
let obj_idx = userList.findIndex(
(obj) => obj.MSM == newFilter[0]?.author
);
const newArr = userList?.map((obj, idx) => {
if (idx == obj_idx) {
return {
...obj,
storeTimeIn: newFilter[0]?.store,
timeIn: newFilter[0]?.date_posted,
storeTimeOut: newFilter[newFilter.length - 1]?.store,
timeOut: newFilter[newFilter.length - 1]?.date_posted,
};
} else {
return obj;
}
});
console.log(newArr);
setAttendanceData(newArr);
});
</code></pre>
<p>that just check if the Item exist in the array before updating it.</p>
<p>and this condition here works fine</p>
<pre><code>if (idx == obj_idx) {
return {
...obj,
storeTimeIn: newFilter[0]?.store,
timeIn: newFilter[0]?.date_posted,
storeTimeOut: newFilter[newFilter.length - 1]?.store,
timeOut: newFilter[newFilter.length - 1]?.date_posted,
};
}
</code></pre>
<p><a href="https://i.stack.imgur.com/PiBTB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PiBTB.png" alt="enter image description here" /></a></p>
<p>as seen in this picture</p>
<p>but when my condition becomes false the whole array of object becomes empty again</p>
<p><a href="https://i.stack.imgur.com/oz2BQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oz2BQ.png" alt="enter image description here" /></a></p>
<p>my hunch is I'm setting the state wrongly . which appear in the <code>setAttendanceData(newArr)</code>
this state is just an empty array state <code>const [attendanceData, setAttendanceData] = useState([]);</code>. is there a way to not update the whole array of object when the condition gets false like how can I use spread operator in this situation. TIA</p>
|
[
{
"answer_id": 74542380,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "all_constraints all_objects SQL> select constraint_name from user_constraints;\n\nCONSTRAINT_NAME\n------------------------------\nBIN$7gsQxw2vJ/LgU8lkAQo5GQ==$0\nBIN$7gsQxw2rJ/LgU8lkAQo5GQ==$0\nSYS_C00106654\n<snip>\n\nSQL> SELECT DBMS_METADATA.get_ddl ('CONSTRAINT', c.constraint_name, c.owner)\n 2 || ';' AS object_ddl\n 3 FROM all_constraints c\n 4 WHERE c.owner = 'SCOTT'\n 5 ORDER BY c.owner;\nERROR:\nORA-31603: object \"BIN$7gsQxw2vJ/LgU8lkAQo5GQ==$0\" of type CONSTRAINT not found\nin schema \"SCOTT\"\nORA-06512: at \"SYS.DBMS_METADATA\", line 5805\nORA-06512: at \"SYS.DBMS_METADATA\", line 8344\nORA-06512: at line 1\n\n\n\nno rows selected\n\nSQL>\n all_objects SQL> SELECT DBMS_METADATA.get_ddl ('CONSTRAINT', c.constraint_name, c.owner)\n 2 || ';' AS object_ddl\n 3 FROM all_constraints c\n 4 JOIN all_objects o\n 5 ON o.owner = c.owner\n 6 AND o.object_name = c.table_name\n 7 WHERE c.owner = 'SCOTT'\n 8 ORDER BY c.owner;\n\nOBJECT_DDL\n--------------------------------------------------------------------------------\n\n ALTER TABLE \"SCOTT\".\"STUDENTS\" ADD PRIMARY KEY (\"ROLLNOSTUD\")\n USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255\n STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645\n PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n TABLESPACE \"USER_DATA\" ENABLE;\n\n\n ALTER TABLE \"SCOTT\".\"DEPARTMENT\" ADD PRIMARY KEY (\"DEPT_NO\")\n USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255\n TABLESPACE \"USER_DATA\" ENABLE;\n<snip>\n"
},
{
"answer_id": 74594991,
"author": "Jon Heller",
"author_id": 409172,
"author_profile": "https://Stackoverflow.com/users/409172",
"pm_score": 0,
"selected": false,
"text": "--Reference constraints:\nselect dbms_metadata.get_ddl('REF_CONSTRAINT', constraint_name) || ';' as object_ddl\nfrom all_constraints\nwhere owner = 'AIBLNGZDB'\n and constraint_type = 'R'\n and constraint_name not like 'BIN$%'\n\nunion all\n\n--Other kinds of constraints.\nselect dbms_metadata.get_ddl('CONSTRAINT', constraint_name) || ';' as object_ddl\nfrom all_constraints\nwhere owner = 'AIBLNGZDB'\n and constraint_type not in ('O', 'V', 'R')\n and constraint_name not like 'BIN$%';\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17634969/"
] |
74,541,759
|
<p>I am writing some numerical value in a matplotlib textbox as</p>
<pre><code> textst = "$En_1={0:.4e}$".format(
*popt)
plt.text(.950,
.100,
textst,
bbox=props,
ha='right',
va='bottom',
transform=ax.transAxes)
</code></pre>
<p>Problem is, I am getting the numerical value as,say, <code>5 e +5</code>. I want the value as <code>5x10^5</code>, i.e. proper superscript.</p>
<p>Is there any easy way of doing this? (easy is the key here, I don't want a lot of regex etc to get the <code>e->10</code> etc)</p>
|
[
{
"answer_id": 74542380,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "all_constraints all_objects SQL> select constraint_name from user_constraints;\n\nCONSTRAINT_NAME\n------------------------------\nBIN$7gsQxw2vJ/LgU8lkAQo5GQ==$0\nBIN$7gsQxw2rJ/LgU8lkAQo5GQ==$0\nSYS_C00106654\n<snip>\n\nSQL> SELECT DBMS_METADATA.get_ddl ('CONSTRAINT', c.constraint_name, c.owner)\n 2 || ';' AS object_ddl\n 3 FROM all_constraints c\n 4 WHERE c.owner = 'SCOTT'\n 5 ORDER BY c.owner;\nERROR:\nORA-31603: object \"BIN$7gsQxw2vJ/LgU8lkAQo5GQ==$0\" of type CONSTRAINT not found\nin schema \"SCOTT\"\nORA-06512: at \"SYS.DBMS_METADATA\", line 5805\nORA-06512: at \"SYS.DBMS_METADATA\", line 8344\nORA-06512: at line 1\n\n\n\nno rows selected\n\nSQL>\n all_objects SQL> SELECT DBMS_METADATA.get_ddl ('CONSTRAINT', c.constraint_name, c.owner)\n 2 || ';' AS object_ddl\n 3 FROM all_constraints c\n 4 JOIN all_objects o\n 5 ON o.owner = c.owner\n 6 AND o.object_name = c.table_name\n 7 WHERE c.owner = 'SCOTT'\n 8 ORDER BY c.owner;\n\nOBJECT_DDL\n--------------------------------------------------------------------------------\n\n ALTER TABLE \"SCOTT\".\"STUDENTS\" ADD PRIMARY KEY (\"ROLLNOSTUD\")\n USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255\n STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645\n PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n TABLESPACE \"USER_DATA\" ENABLE;\n\n\n ALTER TABLE \"SCOTT\".\"DEPARTMENT\" ADD PRIMARY KEY (\"DEPT_NO\")\n USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255\n TABLESPACE \"USER_DATA\" ENABLE;\n<snip>\n"
},
{
"answer_id": 74594991,
"author": "Jon Heller",
"author_id": 409172,
"author_profile": "https://Stackoverflow.com/users/409172",
"pm_score": 0,
"selected": false,
"text": "--Reference constraints:\nselect dbms_metadata.get_ddl('REF_CONSTRAINT', constraint_name) || ';' as object_ddl\nfrom all_constraints\nwhere owner = 'AIBLNGZDB'\n and constraint_type = 'R'\n and constraint_name not like 'BIN$%'\n\nunion all\n\n--Other kinds of constraints.\nselect dbms_metadata.get_ddl('CONSTRAINT', constraint_name) || ';' as object_ddl\nfrom all_constraints\nwhere owner = 'AIBLNGZDB'\n and constraint_type not in ('O', 'V', 'R')\n and constraint_name not like 'BIN$%';\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2005559/"
] |
74,541,763
|
<p>I created a git bare repo today, and added some dotfiles and configs. The thing that mattered the most was my qtile config, since I worked a lot on it.</p>
<p>After adding everything, I pushed and all was good.</p>
<p>I did this because I was planning to distro hop, and I whipped my disk clean after that (all other important files are saved on the cloud).</p>
<p>Installed new distro (EndeavourOS, before I was using Manjaro) and created a new git bare repo.</p>
<p>This is were things went wrong. It did not allowed me to pull files after adding the remote repo, so I figured, let me just add and push everything I have in this PC (which is not much since it is a fresh install) now and even if it overwrites something, I'll just check git and copy the differences.</p>
<p>Well, I forced pushed the things I added and because I hadn't made a pull before, that commit overwrote the previous commit that I did before in which I added all the configs important to me.</p>
<p>I went to the repo in github and all files are lost, and there is only one commit showing (the one I force pushed).</p>
<p>I know I did several things wrong to put myself in this situation, but I wanted to know if there is any way to recover those files that I previously had in my repo and were overwritten.</p>
|
[
{
"answer_id": 74541827,
"author": "Pankaj Chandravanshi",
"author_id": 17743521,
"author_profile": "https://Stackoverflow.com/users/17743521",
"pm_score": 0,
"selected": false,
"text": "git reflog git reset git push git push --force"
},
{
"answer_id": 74541846,
"author": "LeGEC",
"author_id": 86072,
"author_profile": "https://Stackoverflow.com/users/86072",
"pm_score": 2,
"selected": false,
"text": "PushEvent \"before\" git fetch origin <sha> git checkout <sha>:README.md <sha> git fetch origin <sha>"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14433131/"
] |
74,541,772
|
<p>I have a list of key value pairs here.</p>
<p>stat = [{'id': 1, 'status': 'Not Fixed'}, {'id': 2, 'status': 'Not Fixed'}, {'id': 4, 'status': 'Not Fixed'}, {'id': 5, 'status': 'Not Fixed'}, {'id': 6, 'status': 'Not Fixed'}, {'id': 7, 'status': 'Not Fixed'}]</p>
<p>The id in this list represents the id(primary key) of my django model. How can I update the existing records in my database with this list?</p>
<p>Models.py file</p>
<pre><code>class bug(models.Model):
.......
.......
status = models.CharField(max_length=25, choices=status_choice, default="Pending")
</code></pre>
|
[
{
"answer_id": 74541786,
"author": "Đào Minh Hạt",
"author_id": 2281853,
"author_profile": "https://Stackoverflow.com/users/2281853",
"pm_score": 3,
"selected": true,
"text": "update_objects = []\nfor update_item in stat:\n update_objects.append(bug(**update_item))\n\nbug.objects.bulk_update(update_objects, [update_field in stat[0].keys() if update_field != 'id'])\n for update_item in stat:\n bug_id = update_item.pop('id')\n bug.objects.filter(id=bug_id).update(**update_item)\n status"
},
{
"answer_id": 74541837,
"author": "Hemal Patel",
"author_id": 16250404,
"author_profile": "https://Stackoverflow.com/users/16250404",
"pm_score": 1,
"selected": false,
"text": "update_obj = []\nfor item in stat:\n update_obj.append(bug(id=item['id'], status=item['status']))\n \nbug.objects.bulk_update(update_obj, ['status'])\n\n"
},
{
"answer_id": 74542744,
"author": "August Infotech",
"author_id": 20289335,
"author_profile": "https://Stackoverflow.com/users/20289335",
"pm_score": 0,
"selected": false,
"text": "stat = [{'id': 1, 'status': 'Not Fixed'}, {'id': 2, 'status': 'Not Fixed'}, {'id': 4, 'status': 'Not Fixed'}, {'id': 5, 'status': 'Not Fixed'}, {'id': 6, 'status': 'Not Fixed'}, {'id': 7, 'status': 'Not Fixed'}]\nfor record in stat:\n bug.objects.update_or_create(\n id=record['id'],\n defaults={'status': record['status']},\n )"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20529531/"
] |
74,541,779
|
<p>I want a phone number in the text file to show in the textbox without <code>input type="file"</code> in the website I have a text file name phone.txt inside <code>.txt</code> including one phone number like 8769382349 is possible?</p>
<pre><code><input type="number" class="form-control"
min="0" input mode="numeric" pattern="[0-9]*"
name="amount" id="gen-amount"
value="(value from text file)">
</code></pre>
|
[
{
"answer_id": 74541786,
"author": "Đào Minh Hạt",
"author_id": 2281853,
"author_profile": "https://Stackoverflow.com/users/2281853",
"pm_score": 3,
"selected": true,
"text": "update_objects = []\nfor update_item in stat:\n update_objects.append(bug(**update_item))\n\nbug.objects.bulk_update(update_objects, [update_field in stat[0].keys() if update_field != 'id'])\n for update_item in stat:\n bug_id = update_item.pop('id')\n bug.objects.filter(id=bug_id).update(**update_item)\n status"
},
{
"answer_id": 74541837,
"author": "Hemal Patel",
"author_id": 16250404,
"author_profile": "https://Stackoverflow.com/users/16250404",
"pm_score": 1,
"selected": false,
"text": "update_obj = []\nfor item in stat:\n update_obj.append(bug(id=item['id'], status=item['status']))\n \nbug.objects.bulk_update(update_obj, ['status'])\n\n"
},
{
"answer_id": 74542744,
"author": "August Infotech",
"author_id": 20289335,
"author_profile": "https://Stackoverflow.com/users/20289335",
"pm_score": 0,
"selected": false,
"text": "stat = [{'id': 1, 'status': 'Not Fixed'}, {'id': 2, 'status': 'Not Fixed'}, {'id': 4, 'status': 'Not Fixed'}, {'id': 5, 'status': 'Not Fixed'}, {'id': 6, 'status': 'Not Fixed'}, {'id': 7, 'status': 'Not Fixed'}]\nfor record in stat:\n bug.objects.update_or_create(\n id=record['id'],\n defaults={'status': record['status']},\n )"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20571374/"
] |
74,541,851
|
<p>I have used widely used packages(installed via pip) for a while in Jupyter notebook without any issues. I tried to do Python coding in VScode,but it somehow cannot load those packages.</p>
<p>I have tried changing python interpreter, but it did solve the issue. Does anyone know how to resolve this issue?</p>
|
[
{
"answer_id": 74542062,
"author": "Erik Sandoval",
"author_id": 17416260,
"author_profile": "https://Stackoverflow.com/users/17416260",
"pm_score": 0,
"selected": false,
"text": "pip install --upgrade pip\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18254760/"
] |
74,541,877
|
<p>I have two dataframes - the first contains a single column with 180k rows(i.e. 1x180k) and the other has a single row with 13 columns containing 13 growth rates (i.e. 13x1)</p>
<p>I am trying to multiply these dataframes so that I have a single dataframe that shows the growth of these values overtime.</p>
<p>I can multiply them but I can't work out how to make it compound overtime.</p>
<p>Effectively the dataframe I want will have the existing values in the first column, the second column will have the first column multiplied by the first growth rate, the third column will have the second column multiplied by the second growth rate etc.</p>
<p>Note - my growth rates are in percentages (i.e. 0.05 or 5%)</p>
<p>I have this, but I am not sure how to reflect compounding in it.</p>
<pre><code>LandValuesForecast <- LandValues[,1] %*% (1+t(unlist(GrowthRates[1,])))
</code></pre>
|
[
{
"answer_id": 74542065,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "# example data\nvalues <- data.frame(x0 = 1:10 * 100)\nrates <- data.frame(r1 = .1, r2 = .01, r3 = .05)\n\nfor (i in seq(ncol(rates))) {\n values[[paste0(\"x\", i)]] <- values[, i] * (1 + rates[, i])\n}\n\nvalues\n x0 x1 x2 x3\n1 100 110 111.1 116.655\n2 200 220 222.2 233.310\n3 300 330 333.3 349.965\n4 400 440 444.4 466.620\n5 500 550 555.5 583.275\n6 600 660 666.6 699.930\n7 700 770 777.7 816.585\n8 800 880 888.8 933.240\n9 900 990 999.9 1049.895\n10 1000 1100 1111.0 1166.550\n"
},
{
"answer_id": 74542376,
"author": "asd-tm",
"author_id": 5043424,
"author_profile": "https://Stackoverflow.com/users/5043424",
"pm_score": 0,
"selected": false,
"text": "outer library(dplyr) \n\ndf1 <- data.frame(aaa = c(1:10))\ndf2 <- data.frame(a1 = 1, a2 = 2, a3 = 3)\n\nouter(as.matrix(df1, ncol = 1), \nas.matrix(df2, nrow = 1), \n`*`) %>% as.data.frame\n aaa.1.a1 aaa.1.a2 aaa.1.a3\n1 1 2 3\n2 2 4 6\n3 3 6 9\n4 4 8 12\n5 5 10 15\n6 6 12 18\n7 7 14 21\n8 8 16 24\n9 9 18 27\n10 10 20 30\n"
},
{
"answer_id": 74542400,
"author": "Ritchie Sacramento",
"author_id": 2835261,
"author_profile": "https://Stackoverflow.com/users/2835261",
"pm_score": 1,
"selected": false,
"text": "Reduce() values <- data.frame(x0 = 1:10 * 100)\nrates <- data.frame(r1 = .1, r2 = .01, r3 = .05)\n\ndata.frame(Reduce(`*`, rates + 1, init = values, accumulate = TRUE))\n\n x0 x0.1 x0.2 x0.3\n1 100 110 111.1 116.655\n2 200 220 222.2 233.310\n3 300 330 333.3 349.965\n4 400 440 444.4 466.620\n5 500 550 555.5 583.275\n6 600 660 666.6 699.930\n7 700 770 777.7 816.585\n8 800 880 888.8 933.240\n9 900 990 999.9 1049.895\n10 1000 1100 1111.0 1166.550\n purrr::accumulate() library(purrr)\n\ndata.frame(accumulate(rates + 1, `*`, .init = values))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578202/"
] |
74,541,878
|
<p>I have installed Linoor theme which contains a post type called 'Events'. I want to implement the Events submission form for admin as well as visitors. The plugin Events Manager provides this facility for visitors to submit their events with admin approval. However, the plugin doesn't override the post type created by the theme. Also, in the admin side the 'Events' post type as duplicated fields for Event Address, location, timings, etc.</p>
<p>Is there a way to disable or remvoe this post type? Or hide/remove/disable the fields while creating a new event?</p>
<p>I looked up the theme and plugin's documentation but couldn't find the prooper way to solve this.</p>
|
[
{
"answer_id": 74542065,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "# example data\nvalues <- data.frame(x0 = 1:10 * 100)\nrates <- data.frame(r1 = .1, r2 = .01, r3 = .05)\n\nfor (i in seq(ncol(rates))) {\n values[[paste0(\"x\", i)]] <- values[, i] * (1 + rates[, i])\n}\n\nvalues\n x0 x1 x2 x3\n1 100 110 111.1 116.655\n2 200 220 222.2 233.310\n3 300 330 333.3 349.965\n4 400 440 444.4 466.620\n5 500 550 555.5 583.275\n6 600 660 666.6 699.930\n7 700 770 777.7 816.585\n8 800 880 888.8 933.240\n9 900 990 999.9 1049.895\n10 1000 1100 1111.0 1166.550\n"
},
{
"answer_id": 74542376,
"author": "asd-tm",
"author_id": 5043424,
"author_profile": "https://Stackoverflow.com/users/5043424",
"pm_score": 0,
"selected": false,
"text": "outer library(dplyr) \n\ndf1 <- data.frame(aaa = c(1:10))\ndf2 <- data.frame(a1 = 1, a2 = 2, a3 = 3)\n\nouter(as.matrix(df1, ncol = 1), \nas.matrix(df2, nrow = 1), \n`*`) %>% as.data.frame\n aaa.1.a1 aaa.1.a2 aaa.1.a3\n1 1 2 3\n2 2 4 6\n3 3 6 9\n4 4 8 12\n5 5 10 15\n6 6 12 18\n7 7 14 21\n8 8 16 24\n9 9 18 27\n10 10 20 30\n"
},
{
"answer_id": 74542400,
"author": "Ritchie Sacramento",
"author_id": 2835261,
"author_profile": "https://Stackoverflow.com/users/2835261",
"pm_score": 1,
"selected": false,
"text": "Reduce() values <- data.frame(x0 = 1:10 * 100)\nrates <- data.frame(r1 = .1, r2 = .01, r3 = .05)\n\ndata.frame(Reduce(`*`, rates + 1, init = values, accumulate = TRUE))\n\n x0 x0.1 x0.2 x0.3\n1 100 110 111.1 116.655\n2 200 220 222.2 233.310\n3 300 330 333.3 349.965\n4 400 440 444.4 466.620\n5 500 550 555.5 583.275\n6 600 660 666.6 699.930\n7 700 770 777.7 816.585\n8 800 880 888.8 933.240\n9 900 990 999.9 1049.895\n10 1000 1100 1111.0 1166.550\n purrr::accumulate() library(purrr)\n\ndata.frame(accumulate(rates + 1, `*`, .init = values))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14420014/"
] |
74,541,894
|
<p>Trying to install Scipy latest version (1.9.3) on python3.8-alpine image</p>
<pre><code>tiangolo/uwsgi-nginx-flask:python3.8-alpine
</code></pre>
<p>is not successful.</p>
<p>Scipy tries to install numpy 1.8.5 and it fails with following error.</p>
<pre><code>ImportError: cannot import name 'Log' from 'distutils.log' (/tmp/pip-build-env-28q9f6x4/overlay/lib/python3.8/site-packages/setuptools/_distutils/log.py)
</code></pre>
<p>I can goahead and install lower version of scipy. But I am having issue with Sklearn</p>
<p>While trying to install sklearn, it tries to install latest scipy and it fails.</p>
<p>Is there a way i can enforce scipy version to be installed for sklearn</p>
|
[
{
"answer_id": 74542737,
"author": "Antoine Dubuis",
"author_id": 4574633,
"author_profile": "https://Stackoverflow.com/users/4574633",
"pm_score": 1,
"selected": false,
"text": "python:3.8-alpine python:3.8-slim"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6448778/"
] |
74,541,899
|
<p>I'm a beginner in Flutter.</p>
<p>I designed this page:</p>
<p><a href="https://i.stack.imgur.com/dLYLS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dLYLS.jpg" alt="enter image description here" /></a></p>
<p>Instead of repeating the entire Listview.builder. I would like to use two instances of custom Listview.builder with two lists, one list for fruits, and the other for vegetables.</p>
<p>As appeared in the above screen, I tried to display vegetables in the vegetables section through the following:</p>
<p>Listview.builder Widget:</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:grocery_store/models/products_list.dart';
import '../utilities/add_product.dart';
import '../utilities/constants.dart';
class ProductsListView extends StatelessWidget {
final String? productImage;
final String? productName;
final String? productCategory;
final String? productPrice;
const ProductsListView({
Key? key,
this.productImage,
this.productName,
this.productCategory,
this.productPrice,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: fruitsList.length,
itemBuilder: (BuildContext context, int index) {
return ClipRect(
child: Container(
width: 140.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
color: Colors.white,
boxShadow: const [
BoxShadow(
blurRadius: 10,
color: Colors.black,
),
],
),
margin: const EdgeInsets.all(10.0),
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 10, 10, 10),
child: Column(
children: [
Image.asset(
fruitsList[index].fruitImage!,
height: 80.0,
width: 90.0,
),
const SizedBox(
height: 15,
),
Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
fruitsList[index].fruitName!,
style: const TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
Text(
fruitsList[index].fruitCategory!,
textAlign: TextAlign.left,
style: const TextStyle(
height: 1.5,
color: kDarkGrey,
fontSize: 12.5,
fontWeight: FontWeight.bold,
),
),
],
),
],
),
Row(
children: [
Text(
fruitsList[index].fruitPrice!,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
const Spacer(),
const AddProduct(),
],
)
],
),
),
),
);
},
);
}
}
</code></pre>
<p>Fruits and vegetables lists:</p>
<pre><code>import '../utilities/constants.dart';
class Fruits {
final String? fruitImage;
final String? fruitName;
final String? fruitCategory;
final String? fruitPrice;
Fruits(
{this.fruitImage, this.fruitName, this.fruitCategory, this.fruitPrice});
}
final Fruits bananas = Fruits(
fruitImage: '${kFruitsImagesAsset}bananas.png',
fruitName: 'Bananas',
fruitCategory: 'Organic',
fruitPrice: '\$4.99',
);
final Fruits apples = Fruits(
fruitImage: '${kFruitsImagesAsset}apples.png',
fruitName: 'Apples',
fruitCategory: 'Organic',
fruitPrice: '\$5.00',
);
final Fruits chikku = Fruits(
fruitImage: '${kFruitsImagesAsset}chikku.png',
fruitName: 'Chikku',
fruitCategory: 'Organic',
fruitPrice: '\$9.00',
);
final Fruits peaches = Fruits(
fruitImage: '${kFruitsImagesAsset}peaches.png',
fruitName: 'Peaches',
fruitCategory: 'Organic',
fruitPrice: '\$12.00',
);
List<Fruits> fruitsList = [bananas, apples, chikku, peaches];
class Vegetables {
final String? vegetableImage;
final String? vegetableName;
final String? vegetableCategory;
final String? vegetablePrice;
Vegetables(
{this.vegetableImage,
this.vegetableName,
this.vegetableCategory,
this.vegetablePrice});
}
final Vegetables okra = Vegetables(
vegetableImage: '${kVegetablesImagesAsset}okra.png',
vegetableName: 'Okra',
vegetableCategory: 'Organic',
vegetablePrice: '\$6.99',
);
final Vegetables peas = Vegetables(
vegetableImage: '${kVegetablesImagesAsset}peas.png',
vegetableName: 'Peas',
vegetableCategory: 'Organic',
vegetablePrice: '\$10.50',
);
final Vegetables potatoes = Vegetables(
vegetableImage: '${kVegetablesImagesAsset}potatoes.png',
vegetableName: 'Potatoes',
vegetableCategory: 'Organic',
vegetablePrice: '\$5.99',
);
final Vegetables taro = Vegetables(
vegetableImage: '${kVegetablesImagesAsset}taro.png',
vegetableName: 'Taro',
vegetableCategory: 'Organic',
vegetablePrice: '\$5.50',
);
List<Vegetables> vegetablesList = [okra, peas, potatoes, taro];
</code></pre>
<p>Homepage where I want to display the two lists:</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:grocery_store/models/product_cards_column.dart';
import 'package:grocery_store/utilities/constants.dart';
import 'package:grocery_store/utilities/grocery_text_field.dart';
import '../models/products_cards.dart';
import '../models/products_list.dart';
class GroceryPage extends StatelessWidget {
const GroceryPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
var discountPortrait =
MediaQuery.of(context).orientation == Orientation.portrait;
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(15.0),
child: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 1, 0),
child: Row(
children: [
const Text(
'Grocery',
style: kTitleTextStyle,
),
const Spacer(),
ClipRRect(
borderRadius: BorderRadius.circular(16.0),
child: Image.asset(
'images/apple.jpg',
width: 46.0,
height: 46.0,
fit: BoxFit.cover,
),
),
],
),
),
const SizedBox(height: 10.0),
Row(children: [
GroceryTextField.groceryTextField(
groceryText: 'Search...',
),
const SizedBox(width: 5.0),
Container(
height: 50.0,
width: 50.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(18.0),
color: kLightGrey,
),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: SvgPicture.asset(
'images/funnel.svg',
semanticsLabel: 'Funnel',
color: kDarkGrey,
),
),
),
]),
const SizedBox(height: 10.0),
Container(
height: 150,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30.0),
color: const Color(0xFFE9F9F2),
),
width: double.infinity,
child: Stack(
children: [
Positioned(
bottom: -150,
right: discountPortrait ? -30 : 30,
height: 290,
width: 430,
child: Image.asset(
'${kProductsImagesAsset}lettuce.png',
),
),
Positioned(
top: discountPortrait ? 35 : 15,
left: discountPortrait ? 25 : 100,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Get Up To',
style: kGreenTitleStyle.copyWith(
fontSize: discountPortrait ? 20 : 60,
),
),
Text(
'%10 off',
style: kGreenTitleStyle.copyWith(
fontSize: 40.0,
),
),
],
),
),
],
),
),
Column(
children: const [
ProductCardsRow(
groceryType: 'Fruits',
),
SizedBox(
height: 215,
width: double.infinity,
child: ProductsListView(
),
),
],
),
Column(
children: const [
ProductCardsRow(
groceryType: 'Vegetables',
),
SizedBox(
height: 215,
width: double.infinity,
child: ProductsListView(
),
),
],
),
],
),
),
),
),
);
}
}
</code></pre>
<p>Hope someone can help</p>
|
[
{
"answer_id": 74542737,
"author": "Antoine Dubuis",
"author_id": 4574633,
"author_profile": "https://Stackoverflow.com/users/4574633",
"pm_score": 1,
"selected": false,
"text": "python:3.8-alpine python:3.8-slim"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11878615/"
] |
74,541,901
|
<p>I have two python dictionaries like below :</p>
<pre><code>d1 ={'k1':{'a':100}, 'k2':{'b':200}, 'k3':{'b':300}, 'k4':{'c':400}}
d2 ={'k1':{'a':101}, 'k2':{'b':200}, 'k3':{'b':302}, 'k4':{'c':399}}
</code></pre>
<p>I want to compare same keys and find out the difference like below:</p>
<pre><code>{'k1':{'diff':1}, 'k2':{'diff':0}, 'k3':{'diff':2}, 'k4':{'diff':1}}
</code></pre>
<p>This is guaranteed that both of the input dictionaries have same keys.</p>
|
[
{
"answer_id": 74541973,
"author": "veekxt",
"author_id": 5417267,
"author_profile": "https://Stackoverflow.com/users/5417267",
"pm_score": 1,
"selected": false,
"text": "d1 = {'k1': {'a': 100}, 'k2': {'b': 200}, 'k3': {'b': 300}, 'k4': {'c': 400}}\nd2 = {'k1': {'a': 101}, 'k2': {'b': 200}, 'k3': {'b': 302}, 'k4': {'c': 399}}\n\nd3 = {}\nfor k in d1:\n d_tmp = {\n \"diff\": abs(list(d1[k].values())[0] - list(d2[k].values())[0])\n }\n d3[k] = d_tmp\n\nprint(d3)\n {'k1': {'diff': 1}, 'k2': {'diff': 0}, 'k3': {'diff': 2}, 'k4': {'diff': 1}}\n"
},
{
"answer_id": 74541976,
"author": "DeveloperRyan",
"author_id": 5348578,
"author_profile": "https://Stackoverflow.com/users/5348578",
"pm_score": 1,
"selected": true,
"text": "d1 d2 d2 ={'k1':{'a':101}, 'k2':{'b':200}, 'k3':{'b':302}, 'k4':{'c':399}}\n\noutput = {}\nfor k, v in d1.items():\n for k2, v2 in v.items():\n output[k] = {'diff': abs(d2[k][k2] - v2)}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2122502/"
] |
74,541,908
|
<p>I have an type with props that can be optional depending on a generic type:</p>
<pre><code>type MyType<R extends Record<string, string> | undefined, A extends string[] | undefined> = {
record: R
array: A
}
</code></pre>
<p>I have a function that takes a <code>MyType</code> object</p>
<pre><code>const myFunction = <R extends Record<string, string> | undefined, A extends string[] | undefined>(myObject: MyType<R, A>)=>{
// ... //
}
</code></pre>
<p>I want to be able to call <code>myFunction</code> and omit a <code>record</code> in the props if <code>R</code> is undefined, for example</p>
<pre><code>const record = getTheRecord() // Assuming getTheRecord() returns a undefined here
const array = ['a']
myFunction<undefined, string[]>({
array
})
</code></pre>
<p>How can I make some props optional depending on a generic type?</p>
|
[
{
"answer_id": 74541973,
"author": "veekxt",
"author_id": 5417267,
"author_profile": "https://Stackoverflow.com/users/5417267",
"pm_score": 1,
"selected": false,
"text": "d1 = {'k1': {'a': 100}, 'k2': {'b': 200}, 'k3': {'b': 300}, 'k4': {'c': 400}}\nd2 = {'k1': {'a': 101}, 'k2': {'b': 200}, 'k3': {'b': 302}, 'k4': {'c': 399}}\n\nd3 = {}\nfor k in d1:\n d_tmp = {\n \"diff\": abs(list(d1[k].values())[0] - list(d2[k].values())[0])\n }\n d3[k] = d_tmp\n\nprint(d3)\n {'k1': {'diff': 1}, 'k2': {'diff': 0}, 'k3': {'diff': 2}, 'k4': {'diff': 1}}\n"
},
{
"answer_id": 74541976,
"author": "DeveloperRyan",
"author_id": 5348578,
"author_profile": "https://Stackoverflow.com/users/5348578",
"pm_score": 1,
"selected": true,
"text": "d1 d2 d2 ={'k1':{'a':101}, 'k2':{'b':200}, 'k3':{'b':302}, 'k4':{'c':399}}\n\noutput = {}\nfor k, v in d1.items():\n for k2, v2 in v.items():\n output[k] = {'diff': abs(d2[k][k2] - v2)}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6592293/"
] |
74,541,919
|
<p>I am trying to write some function of data, however, my data is like this:</p>
<pre><code>noms sommets
0000 Abbesses
0001 Alexandre Dumas
0002 Paris
0004 Nice
...
coord sommets
0000 308 536
0001 472 386
0002 193 404
</code></pre>
<p>What I want to is to access from <code>nom sommets</code> to <code>0004 Nice</code> without knowing the number of line but base on the string value of txt</p>
|
[
{
"answer_id": 74542797,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 2,
"selected": true,
"text": "sommets with open('text.txt') as file:\n lines = [line.rstrip() for line in file]\n\ntest_loop = []\nfor item in lines:\n if 'sommets' in item: \n test_loop.append([item])\n else: \n test_loop[-1].append(item)\nprint(test_loop)\n list of lists [['noms sommets', '0000 Abbesses', '0001 Alexandre Dumas', '0002 Paris', '0004 Nice', '...'], ['coord sommets', '0000 308 536', '0001 472 386', '0002 193 404']]\n for sublist in test_loop[0]:\n print(sublist)\n noms sommets\n0000 Abbesses\n0001 Alexandre Dumas\n0002 Paris\n0004 Nice\n...\n"
},
{
"answer_id": 74554848,
"author": "Skycc",
"author_id": 7031759,
"author_profile": "https://Stackoverflow.com/users/7031759",
"pm_score": 0,
"selected": false,
"text": "re.DOTALL with open('text.txt') as f:\n txt = f.read()\n\nmatch = re.search('noms sommets.*?0004 Nice', a, re.DOTALL).group()\n# match = 'noms sommets\\n0000 Abbesses\\n0001 Alexandre Dumas\\n0002 Paris\\n0004 Nice'\n >>> print(match)\nnoms sommets\n0000 Abbesses\n0001 Alexandre Dumas\n0002 Paris\n0004 Nice\n>>>\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11315832/"
] |
74,541,921
|
<p>I have 3 classes <code>Person</code>, <code>Hobby</code> and <code>Customer</code></p>
<pre><code>public class Person {
public string Name {get;set;}
public List<Hobby> Hobbies {get;set;}
}
public class Hobby {
public string Type {get;set;}
}
public class Customer {
public string CustomerName {get;set;}
public string TypeOfHobby {get;set;}
}
</code></pre>
<p>With the following Automapper mapping</p>
<pre><code>CreateMap<Customer, Person>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(scr => src.CustomerName))
CreateMap<Customer, Hobby>()
.ForMember(dest => dest.Type, opt => opt.MapFrom(scr => src.TypeOfHobby))
</code></pre>
<p>I now create a list of Persons and Customers</p>
<pre><code>var persons = new List<Person>()
var customers = new List<Customers>(){
new(){
CustomerName = "john doe",
TypeOfHobby = "reading"
},
new(){
CustomerName = "jane doe",
TypeOfHobby = "sports"
}
}
</code></pre>
<p>I want to be able to map from the customers list to the persons list as follows:</p>
<pre><code>[
{
"name": "john doe",
"hobbies": [
{
"type": "reading"
}
]
},
{
"name": "jane doe",
"hobbies": [
{
"type": "sports"
}
]
}
]
</code></pre>
<p>I have tried the following:</p>
<pre><code>var mappedPersons = _mapper.Map<List<Person>>(customers)
</code></pre>
<p>but I'm not sure how to do the mapping for the <code>Hobbies</code> inside each <code>mappedPersons</code></p>
|
[
{
"answer_id": 74542526,
"author": "Yong Shun",
"author_id": 8017690,
"author_profile": "https://Stackoverflow.com/users/8017690",
"pm_score": 0,
"selected": false,
"text": "Hobbies CreateMap<Customer, Person>()\n .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.CustomerName))\n .ForMember(dest => dest.Hobbies, opt => opt.MapFrom((src, dest, destMember, ctx) =>\n {\n List<Hobby> hobbies = new List<Hobby>();\n hobbies.Add(ctx.Mapper.Map<Hobby>(src));\n return hobbies;\n }));\n"
},
{
"answer_id": 74543281,
"author": "Charles Han",
"author_id": 11514907,
"author_profile": "https://Stackoverflow.com/users/11514907",
"pm_score": 1,
"selected": false,
"text": "CreateMap<Customer, Person>()\n .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.CustomerName))\n .ForMember(dest => dest.Hobbies, opt => opt.MapFrom(src => new List<Hobby>\n {\n new Hobby\n {\n Type = src.TypeOfHobby\n }\n }));\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3102993/"
] |
74,541,923
|
<p>I try to find all elements <code><coordinates></code> into kml file, but not all of them have the same structure</p>
<p>for example:</p>
<pre><code><Placemark>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<coordinates>
-103.6705130315019, 18.9861834531002, 312.462181927998
-103.5618913951496, 18.98673753736649, 827.0547547230755
-103.6101814498474, 19.21464825463783, 601.556189231858
-103.6705130315019, 18.9861834531002, 312.462181927998
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</code></pre>
<p>And others files have other structure, for example:</p>
<pre><code><Placemark>
<MultiGeometry>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<coordinates>
-104.085929389248,19.3541278793555, 0
-104.085635763744,19.3536293022551, 0
-104.087174259165,19.3527060222406, 0
-104.087310816944,19.3536755662883, 0
-104.085929389248,19.3541278793555,0
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</MultiGeometry>
</Placemark>
</code></pre>
<p>I need to get all coordinates ignoring parent elements, also, some file, have one o more coordinates elements</p>
<p>The next code runs, but only get me one element,</p>
<pre><code>foreach( $xml->getDocNamespaces(TRUE) as $strPrefix => $strNamespace ) {
if(strlen($strPrefix)==0) {
$strPrefix="a"; //Assign an arbitrary namespace prefix.
}
$xml->registerXPathNamespace($strPrefix,$strNamespace);
}
$pieces = explode(" ", $xml->xpath("//a:coordinates")[0]);
foreach ($pieces as $coordinates) {
$args = explode(",", $coordinates);
if (strlen($args[1]) != 0 ){
$coordenadas .= '{"lat": ' . $args[1] . ', "lng": ' . $args[0] . '},';
}
}
</code></pre>
<p>If the file have other coordinates elements, I cant get it.</p>
|
[
{
"answer_id": 74544579,
"author": "Professor Abronsius",
"author_id": 3603681,
"author_profile": "https://Stackoverflow.com/users/3603681",
"pm_score": 0,
"selected": false,
"text": "SimpleXML DOMDocument DOMXPath # This source file has multiple separate Placemarks, each with many coordinates\n# and has several different associated namespaces.\n$file='/files/kml/cta.kml';\n$output=array();\n\n# load the XML/KML file\nlibxml_use_internal_errors( true );\n$dom=new DOMDocument;\n$dom->validateOnParse=false;\n$dom->strictErrorChecking=false;\n$dom->recover=true;\n$dom->load( $file );\nlibxml_clear_errors();\n\n# load XPath and register default namespace\n$xp=new DOMXPath( $dom );\n\n# Find & register all namespaces\n$expr='namespace::*';\n$col=$xp->query( $expr );\nif( $col && $col->length > 0 ){\n foreach( $col as $index => $node ){\n $xp->registerNameSpace( $node->localName, $node->nodeValue );\n # set a default... \n $def=$node->localName;\n }\n}\n\n# choose the default namespace and create the basic query\n# In **this** file the prefix is not important, this may not always be the case!\n$expr=sprintf('//%s:coordinates', $def );\n\n\n#Query the document to find matching nodes.\n$col=$xp->query( $expr );\nif( $col && $col->length > 0 ){\n foreach( $col as $node ){\n # each found node has a long list of coordinates/altitudes - create\n # an array by exploding on new line character.\n $lines=explode( PHP_EOL, $node->nodeValue );\n \n \n \n #iterate through found lines of coordinates and split into constituent pieces.\n foreach( $lines as $line ){\n # remove tabs and other control characters\n $line=preg_replace('@[\\t\\r]@', '', $line );\n \n # split the line at suitable point\n $line=preg_split( '@\\n@', $line );\n \n # remove empty items\n $line=array_filter( $line );\n \n foreach( $line as $coordinate ){\n # does each coordinate have an altitude or not?\n $count=substr_count( $coordinate, ',' );\n \n if( $count==1 ){\n \n # Only Long & Lat per coordinate\n list( $lng, $lat )=explode(',', $coordinate );\n $output[]=array( 'lat'=>trim($lat), 'lng'=>trim($lng), 'Altitude'=>0 );\n \n } elseif( $count==2 ) {\n \n # Long, Lat & Altitude per coordinate\n list( $lng, $lat, $alt )=explode(',', $coordinate );\n $output[]=array( 'lat'=>trim($lat), 'lng'=>trim($lng), 'Altitude'=>trim($alt) );\n }\n }\n }\n }\n}\n\nprintf('<pre>%s</pre>',print_r($output,true));\n Array\n(\n [0] => Array\n (\n [lat] => 41.97881025520548\n [lng] => -87.89289951324463\n [Altitude] => 0\n )\n [1] => Array\n (\n [lat] => 41.97788506340239\n [lng] => -87.89184808731079\n [Altitude] => 0\n )\n [2] => Array\n (\n [lat] => 41.97762983571196\n [lng] => -87.89150476455688\n [Altitude] => 0\n )\n"
},
{
"answer_id": 74546182,
"author": "ThW",
"author_id": 497139,
"author_profile": "https://Stackoverflow.com/users/497139",
"pm_score": 1,
"selected": false,
"text": "{http://www.opengis.net/kml/2.2}kml <kml xmlns=\"http://www.opengis.net/kml/2.2\"> <k:kml xmlns:k=\"http://www.opengis.net/kml/2.2\"> <keyhole:kml xmlns:keyhole=\"http://www.opengis.net/kml/2.2\"> \nconst XMLNS_KML = \"http://www.opengis.net/kml/2.2\";\n\n$kml = new SimpleXMLElement(getKMLString());\n$kml->registerXpathNamespace('k', XMLNS_KML);\n\n$coordinates = [];\nforeach ($kml->xpath('//k:Placemark//k:coordinates') as $coordinates) {\n var_dump(trim($coordinates));\n}\n\n\nfunction getKMLString(): string {\n return <<<'XML'\n<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n<Placemark>\n <Polygon>\n <outerBoundaryIs>\n <LinearRing>\n <coordinates>\n -103.6705130315019, 18.9861834531002, 312.462181927998 \n -103.5618913951496, 18.98673753736649, 827.0547547230755\n -103.6101814498474, 19.21464825463783, 601.556189231858\n -103.6705130315019, 18.9861834531002, 312.462181927998 \n </coordinates>\n </LinearRing>\n </outerBoundaryIs>\n </Polygon>\n</Placemark>\n<Placemark>\n <MultiGeometry>\n <Polygon>\n <outerBoundaryIs>\n <LinearRing>\n <coordinates>\n -104.085929389248,19.3541278793555, 0 \n -104.085635763744,19.3536293022551, 0\n -104.087174259165,19.3527060222406, 0\n -104.087310816944,19.3536755662883, 0\n -104.085929389248,19.3541278793555,0 \n </coordinates>\n </LinearRing>\n </outerBoundaryIs>\n </Polygon>\n </MultiGeometry>\n</Placemark>\n</kml>\nXML;\n}\n string(283) \"-103.6705130315019, 18.9861834531002, 312.462181927998 \n -103.5618913951496, 18.98673753736649, 827.0547547230755\n -103.6101814498474, 19.21464825463783, 601.556189231858\n -103.6705130315019, 18.9861834531002, 312.462181927998\"\nstring(285) \"-104.085929389248,19.3541278793555, 0 \n -104.085635763744,19.3536293022551, 0\n -104.087174259165,19.3527060222406, 0\n -104.087310816944,19.3536755662883, 0\n -104.085929389248,19.3541278793555,0\"\n $xpath DOMXpath::evaluate() $document = new DOMDocument();\n$document->loadXML(getKMLString());\n$xpath = new DOMXPath($document);\n$xpath->registerNamespace('k', XMLNS_KML);\n\n$coordinates = [];\nforeach ($xpath->evaluate('//k:Placemark//k:coordinates') as $coordinates) {\n var_dump(trim($coordinates->textContent));\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578287/"
] |
74,541,928
|
<p>I'd like to split a csv column containing a dictionary-like structure/values into component columns. For example input/output data, see <a href="https://docs.google.com/spreadsheets/d/1LXVWTdD96-ZjjmOLjfH1crPTAYFwRVk3wCVXWyaV0IY/edit?usp=sharing" rel="nofollow noreferrer">this spreadsheet</a>. Data will always come in that format ({"key":value,...}), with the number of key value pairs being arbitrary.</p>
<p>Not necessarily looking for a full solution here—more curious what the my options are for parsing data to create the output I want. Open to maybe using python to do some of this.</p>
|
[
{
"answer_id": 74542070,
"author": "mohagali",
"author_id": 2916090,
"author_profile": "https://Stackoverflow.com/users/2916090",
"pm_score": 0,
"selected": false,
"text": "=SPLIT(REGEXREPLACE(A1,\"\"\".*\"\":|\\{|\\}|\\n|\\r\",\"\"),\",\")\n"
},
{
"answer_id": 74544974,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 1,
"selected": false,
"text": "=INDEX(BYROW(A3:A5, LAMBDA(x, IFNA(HLOOKUP(B2:E2, \n TRANSPOSE(SPLIT(TRIM(FLATTEN(SPLIT(REGEXREPLACE(x, \"[\\}\\{\"\",]\", ), \n CHAR(10)))), \":\")), 2, 0)))))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10571775/"
] |
74,541,947
|
<p>I want to compare last 30 mins data and display in UI. Datetime needs be UTC. I tried using Moment but i am getting error</p>
<pre><code>Javascript - Operator '>' cannot be applied to types 'Date' and 'Moment'.
</code></pre>
<p>Below is my code :</p>
<pre><code> let d = moment();
let d_utc = moment.utc();
var customDate = new Date();
d_utc.minutes(-30);
filteredData = filteredData.filter((category) => {
return category.uploaded_time > d_utc;
});
</code></pre>
|
[
{
"answer_id": 74541971,
"author": "Slava Knyazev",
"author_id": 4088472,
"author_profile": "https://Stackoverflow.com/users/4088472",
"pm_score": 2,
"selected": true,
"text": "Date Moment Date .toDate() moment(date) return category.uploaded_time > d_utc.toDate()\n Moments diff return moment(category.uploaded_time).diff(d_utc) > 0\n"
},
{
"answer_id": 74542041,
"author": "Barış Can Yılmaz",
"author_id": 8784762,
"author_profile": "https://Stackoverflow.com/users/8784762",
"pm_score": 0,
"selected": false,
"text": "moment.utc().seconds(30).valueOf() === new Date().setUTCSeconds(30);\n\n let d_utc = moment.utc();\n let d_utc = moment.utc().minutes(-30).valueOf();\n\n filteredData = filteredData.filter((category) => {\n return category.uploaded_time.getUTCSeconds() > d_utc;\n });\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74541947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1309392/"
] |
74,542,007
|
<p>I have an issue redirecting from the http site to the https site.</p>
<p>This <strong>index.php</strong> file is in the root folder, redirecting to a suburl:</p>
<pre><code><?php
header("Location: /news/");
?>
</code></pre>
<p>the url <code>https://www.example.com</code> is correctly redirecting to <code>https://www.example.com/news/</code></p>
<p>the url <code>https://www.example.com/index.php</code> is correctly redirecting to <code>https://www.example.com/news/</code></p>
<p>the url <code>http://www.example.com/index.php</code> is correctly redirecting to <code>https://www.example.com/news/</code></p>
<p>however the url <code>http://www.example.com</code> is showing an empty directory, as in the image below:</p>
<p><a href="https://i.stack.imgur.com/CNKa3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CNKa3.png" alt="enter image description here" /></a></p>
<p>these are the config files:</p>
<p><strong>/etc/apache2/sites-available/www.example.com.conf</strong></p>
<pre><code><VirtualHost *:*>
ServerName www.example.com
DocumentRoot /var/www/vhosts/example.com/httpdocs
ServerAlias example.com
RewriteEngine on
RewriteCond %{SERVER_NAME} =example.com [OR]
RewriteCond %{SERVER_NAME} =www.example.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>
</code></pre>
<p><strong>/etc/apache2/sites-available/www.example.com-le-ssl.conf</strong></p>
<pre><code><IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName www.example.com
DocumentRoot /var/www/vhosts/example.com/httpdocs
ServerAlias example.com
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>
</IfModule>
</code></pre>
<p>How can I correctly redirect from <code>http://www.example.com</code> to <code>https://www.example.com/news/</code> ?</p>
|
[
{
"answer_id": 74645566,
"author": "MrCPlusPlus",
"author_id": 20614862,
"author_profile": "https://Stackoverflow.com/users/20614862",
"pm_score": 0,
"selected": false,
"text": "<VirtualHost *:80>\n RewriteEngine On\n RewriteCond %{HTTPS} !=on\n RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]\n</virtualHost>\n"
},
{
"answer_id": 74650547,
"author": "Krokomot",
"author_id": 19980636,
"author_profile": "https://Stackoverflow.com/users/19980636",
"pm_score": 2,
"selected": true,
"text": "# Listening for HTTP connections\n<VirtualHost *:80>\n ServerName www.example.com\n ServerAlias example.com\n\n # permanently redirects to the site's HTTPS version\n Redirect permanent / https://www.example.com/\n</VirtualHost>\n\n# Listening for HTTPS connections\n<VirtualHost _default_:443>\n ServerName www.example.com\n ServerAlias example.com\n DocumentRoot /usr/local/apache2/htdocs\n SSLEngine On\n\n # Further configurations...\n</VirtualHost>\n .htaccess LoadModule rewrite_module modules/mod_rewrite.so\n httpd.conf .htaccess # Enable rewriting\nRewriteEngine On \n# Check for HTTPS, if no, execute next line\nRewriteCond %{HTTPS} off\n# Redirect to HTTPS with status code 301 (moved permanently)\nRewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [L,R=301]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/913867/"
] |
74,542,017
|
<p>we are using ADAL to acquire tokens by a service account silently (no prompt, no redirect). This is our sample code:</p>
<pre class="lang-cs prettyprint-override"><code>var clientId = "";
var tenantDomain = "";
var userName = "";
var password = "";
var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantDomain));
var credential = new UserPasswordCredential(userName, password);
var result = await context.AcquireTokenAsync("https://management.core.windows.net/", clientId, credential);
</code></pre>
<p>How can I acquire tokens using MSAL?</p>
|
[
{
"answer_id": 74645566,
"author": "MrCPlusPlus",
"author_id": 20614862,
"author_profile": "https://Stackoverflow.com/users/20614862",
"pm_score": 0,
"selected": false,
"text": "<VirtualHost *:80>\n RewriteEngine On\n RewriteCond %{HTTPS} !=on\n RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]\n</virtualHost>\n"
},
{
"answer_id": 74650547,
"author": "Krokomot",
"author_id": 19980636,
"author_profile": "https://Stackoverflow.com/users/19980636",
"pm_score": 2,
"selected": true,
"text": "# Listening for HTTP connections\n<VirtualHost *:80>\n ServerName www.example.com\n ServerAlias example.com\n\n # permanently redirects to the site's HTTPS version\n Redirect permanent / https://www.example.com/\n</VirtualHost>\n\n# Listening for HTTPS connections\n<VirtualHost _default_:443>\n ServerName www.example.com\n ServerAlias example.com\n DocumentRoot /usr/local/apache2/htdocs\n SSLEngine On\n\n # Further configurations...\n</VirtualHost>\n .htaccess LoadModule rewrite_module modules/mod_rewrite.so\n httpd.conf .htaccess # Enable rewriting\nRewriteEngine On \n# Check for HTTPS, if no, execute next line\nRewriteCond %{HTTPS} off\n# Redirect to HTTPS with status code 301 (moved permanently)\nRewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [L,R=301]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3492807/"
] |
74,542,021
|
<p>I have been trying to solve a problem where I am given a list as input and I need to show an output with 7 attached to each string value if it doesn't contain a 7 already.</p>
<p>I have created a list and for the case of 7 not included I have attached the '7' using the for loop. So for example: for the input
<code>["a7", "g", "u"]</code>, I expect output as <code>["a7","g7","u7"]</code> but I am getting the output as follows<br />
<code>['a7', 'g', 'u', ['a77', 'g7', 'u7']]</code></p>
<p>I have tried to put the values in a new list using append but I am not sure how to remove the old values and replace it with new ones in existing list. Following is my code</p>
<pre><code>class Solution(object):
def jazz(self, list=[]):
for i in range(len(list)):
if '7' not in list[i]:
li = [i + '7' for i in list]
list.append(li)
return list
if __name__ == "__main__":
p = Solution()
lt = ['a7', 'g', 'u']
print(p.jazz(lt))
</code></pre>
|
[
{
"answer_id": 74645566,
"author": "MrCPlusPlus",
"author_id": 20614862,
"author_profile": "https://Stackoverflow.com/users/20614862",
"pm_score": 0,
"selected": false,
"text": "<VirtualHost *:80>\n RewriteEngine On\n RewriteCond %{HTTPS} !=on\n RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]\n</virtualHost>\n"
},
{
"answer_id": 74650547,
"author": "Krokomot",
"author_id": 19980636,
"author_profile": "https://Stackoverflow.com/users/19980636",
"pm_score": 2,
"selected": true,
"text": "# Listening for HTTP connections\n<VirtualHost *:80>\n ServerName www.example.com\n ServerAlias example.com\n\n # permanently redirects to the site's HTTPS version\n Redirect permanent / https://www.example.com/\n</VirtualHost>\n\n# Listening for HTTPS connections\n<VirtualHost _default_:443>\n ServerName www.example.com\n ServerAlias example.com\n DocumentRoot /usr/local/apache2/htdocs\n SSLEngine On\n\n # Further configurations...\n</VirtualHost>\n .htaccess LoadModule rewrite_module modules/mod_rewrite.so\n httpd.conf .htaccess # Enable rewriting\nRewriteEngine On \n# Check for HTTPS, if no, execute next line\nRewriteCond %{HTTPS} off\n# Redirect to HTTPS with status code 301 (moved permanently)\nRewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [L,R=301]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20502753/"
] |
74,542,043
|
<p>My goal is to make a countdown clock with custom inputs. Current it works fine, but the requirement is to make the input fields independent to the timer. That is, currently whatever is entered into the input field, it also changes the timer. The timer should change and start only when start button is clicked.
But using onChange in input, changes the timer on the go.</p>
<p>Codesandbox link: <a href="https://codesandbox.io/s/lively-grass-6o50xx?file=/src/Timer.js" rel="nofollow noreferrer">https://codesandbox.io/s/lively-grass-6o50xx?file=/src/Timer.js</a></p>
<p><strong>Code:</strong></p>
<pre><code>const START_DERATION = 10;
function Timer() {
const [currentMinutes, setMinutes] = useState("00");
const [currentSeconds, setSeconds] = useState("00");
const [isStop, setIsStop] = useState(false);
const [duration, setDuration] = useState(START_DERATION);
const [isRunning, setIsRunning] = useState(false);
const startHandler = async () => {
setDuration(
parseInt(currentSeconds, 10) + 60 * parseInt(currentMinutes, 10)
);
setIsRunning(true);
};
const stopHandler = () => {
setIsStop(true);
setIsRunning(false);
};
const resetHandler = () => {
setMinutes("00");
setSeconds("00");
setIsRunning(false);
setIsStop(false);
setDuration(START_DERATION);
};
const resumeHandler = () => {
let newDuration =
parseInt(currentMinutes, 10) * 60 + parseInt(currentSeconds, 10);
setDuration(newDuration);
setIsRunning(true);
setIsStop(false);
};
useEffect(() => {
if (isRunning === true) {
let timer = duration;
var minutes, seconds;
const interval = setInterval(function () {
if (--timer <= 0) {
resetHandler();
} else {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
setMinutes(minutes);
setSeconds(seconds);
}
}, 1000);
return () => clearInterval(interval);
}
}, [isRunning]);
return (
<div>
<span style={{ display: "flex" }}>
<input
type="number"
onChange={(e) => setMinutes(e.target.value + "")}
/>
<p>Minutes</p>
</span>
<span style={{ display: "flex" }}>
<input
type="number"
onChange={(e) => setSeconds(e.target.value + "")}
/>
<p>Seconds</p>
</span>
<button onClick={startHandler}>Start</button>
<button
onClick={isStop ? resumeHandler : stopHandler}
disabled={!isRunning && !isStop}
>
Pause/Resume
</button>
<button onClick={resetHandler} disabled={!isRunning && !isStop}>
Reset
</button>
<p>
{currentMinutes}:{currentSeconds}
</p>
</div>
);
}
</code></pre>
|
[
{
"answer_id": 74645566,
"author": "MrCPlusPlus",
"author_id": 20614862,
"author_profile": "https://Stackoverflow.com/users/20614862",
"pm_score": 0,
"selected": false,
"text": "<VirtualHost *:80>\n RewriteEngine On\n RewriteCond %{HTTPS} !=on\n RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]\n</virtualHost>\n"
},
{
"answer_id": 74650547,
"author": "Krokomot",
"author_id": 19980636,
"author_profile": "https://Stackoverflow.com/users/19980636",
"pm_score": 2,
"selected": true,
"text": "# Listening for HTTP connections\n<VirtualHost *:80>\n ServerName www.example.com\n ServerAlias example.com\n\n # permanently redirects to the site's HTTPS version\n Redirect permanent / https://www.example.com/\n</VirtualHost>\n\n# Listening for HTTPS connections\n<VirtualHost _default_:443>\n ServerName www.example.com\n ServerAlias example.com\n DocumentRoot /usr/local/apache2/htdocs\n SSLEngine On\n\n # Further configurations...\n</VirtualHost>\n .htaccess LoadModule rewrite_module modules/mod_rewrite.so\n httpd.conf .htaccess # Enable rewriting\nRewriteEngine On \n# Check for HTTPS, if no, execute next line\nRewriteCond %{HTTPS} off\n# Redirect to HTTPS with status code 301 (moved permanently)\nRewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [L,R=301]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9222818/"
] |
74,542,067
|
<p>I am trying to compile an already built angular application. Upgrading to latest version is not possible but already built app should just compile fine.</p>
<p>my package.config file is</p>
<pre><code>{
"name": "my name",
"version": "1.0.0",
"description": "what does this do?",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^5.2.10",
"@angular/common": "^5.2.10",
"@angular/compiler": "^5.2.10",
"@angular/compiler-cli": "^5.2.10",
"@angular/core": "^5.2.10",
"@angular/forms": "^5.2.10",
"@angular/http": "^5.2.10",
"@angular/platform-browser": "^5.2.10",
"@angular/platform-browser-dynamic": "^5.2.10",
"@angular/platform-server": "^5.2.10",
"@angular/router": "^5.2.10",
"angular2-focus": "^1.1.0",
"bootstrap": "^3.3.7",
"chart.js": "^2.7.2",
"classlist.js": "^1.1.20150312",
"core-js": "^2.4.1",
"file-saver": "^1.3.3",
"font-awesome": "^4.7.0",
"fullcalendar": "^3.2.0",
"fullcalendar-scheduler": "^1.5.1",
"jquery": "^3.1.1",
"moment": "^2.18.1",
"primeng": "^5.2.4",
"rxjs": "^5.2.0",
"typescript": "^2.8.1",
"web-animations-js": "^2.2.2",
"zone.js": "^0.8.5"
},
"devDependencies": {
"@angular/cli": "^1.6.6",
"@angular/compiler-cli": "^5.2.10",
"@types/core-js": "^0.9.34",
"@types/jasmine": "^2.5.35",
"@types/jquery": "^2.0.34",
"@types/lodash": "^4.14.40",
"@types/moment": "^2.13.0",
"@types/node": "^6.0.45",
"@types/q": "0.0.32",
"@types/selenium-webdriver": "^2.53.32",
"codelyzer": "^4.2.1",
"jasmine-core": "~2.5.2",
"jasmine-spec-reporter": "~3.2.0",
"karma": "~1.4.1",
"karma-chrome-launcher": "~2.0.0",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^0.2.0",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"lodash": "^4.16.2",
"primeng": "^4.0.1",
"protractor": "~5.1.0",
"ts-node": "~2.0.0",
"tslint": "~5.9.1",
"typescript": "^2.8.1"
}
}
</code></pre>
<p>I am getting this error when I run ng build</p>
<blockquote>
<p>Your global Angular CLI version (14.0.0) is greater than your local version (1.6.6). The local Angular CLI version is used.</p>
<p>To disable this warning use "ng config -g cli.warnings.versionMismatch false".</p>
<p>@angular/compiler-cli@5.2.11 requires typescript@'>=2.4.2 <2.7.0' but 2.9.2 was found instead.
Using this version can result in undefined behaviour and difficult to debug problems.</p>
<p>Please run the following command to install a compatible version of TypeScript.</p>
<pre><code>npm install typescript@'>=2.4.2 <2.7.0'
</code></pre>
<p>To disable this warning run "ng set
warnings.typescriptMismatch=false".</p>
<p>Date: 2022-11-23T02:55:08.478Z<br />
Hash: 9743454dc3930ee3a8f6 Time: 4325ms chunk {inline}
inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB [entry]
[rendered] chunk {main} main.bundle.js, main.bundle.js.map (main) 303
bytes [initial] [rendered] chunk {polyfills} polyfills.bundle.js,
polyfills.bundle.js.map (polyfills) 323 bytes [initial] [rendered]
chunk {scripts} scripts.bundle.js, scripts.bundle.js.map (scripts) 675
kB [initial] [rendered] chunk {styles} styles.bundle.js,
styles.bundle.js.map (styles) 588 kB [initial] [rendered]</p>
<p>ERROR in
src/app/nets/nets-configuration/configuration-view/configuration-view.component.ts(12,23):
error TS2307: Cannot find module 'primeng/table'.</p>
</blockquote>
<p>My Angular and node installation has</p>
<p><a href="https://i.stack.imgur.com/RrwEc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RrwEc.png" alt="enter image description here" /></a></p>
<p>npm i shows this error</p>
<p><a href="https://i.stack.imgur.com/PiJ9c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PiJ9c.png" alt="enter image description here" /></a></p>
<p>npm i --force has some warnings</p>
<p><a href="https://i.stack.imgur.com/hl2b5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hl2b5.png" alt="enter image description here" /></a></p>
<p>I can see the package folder inside node_modules</p>
<p><a href="https://i.stack.imgur.com/uk9wK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uk9wK.png" alt="enter image description here" /></a></p>
<p>I have deleted the node_modules folder and tried again but got this error</p>
<p><a href="https://i.stack.imgur.com/nxISS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nxISS.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74645566,
"author": "MrCPlusPlus",
"author_id": 20614862,
"author_profile": "https://Stackoverflow.com/users/20614862",
"pm_score": 0,
"selected": false,
"text": "<VirtualHost *:80>\n RewriteEngine On\n RewriteCond %{HTTPS} !=on\n RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]\n</virtualHost>\n"
},
{
"answer_id": 74650547,
"author": "Krokomot",
"author_id": 19980636,
"author_profile": "https://Stackoverflow.com/users/19980636",
"pm_score": 2,
"selected": true,
"text": "# Listening for HTTP connections\n<VirtualHost *:80>\n ServerName www.example.com\n ServerAlias example.com\n\n # permanently redirects to the site's HTTPS version\n Redirect permanent / https://www.example.com/\n</VirtualHost>\n\n# Listening for HTTPS connections\n<VirtualHost _default_:443>\n ServerName www.example.com\n ServerAlias example.com\n DocumentRoot /usr/local/apache2/htdocs\n SSLEngine On\n\n # Further configurations...\n</VirtualHost>\n .htaccess LoadModule rewrite_module modules/mod_rewrite.so\n httpd.conf .htaccess # Enable rewriting\nRewriteEngine On \n# Check for HTTPS, if no, execute next line\nRewriteCond %{HTTPS} off\n# Redirect to HTTPS with status code 301 (moved permanently)\nRewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [L,R=301]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/316199/"
] |
74,542,081
|
<p>I have one log file of mongodb. I want to display all output of grep command in greater than or less than given value"protocol:op_msg 523ms"</p>
<pre><code>sed -n '/2022-09-15T12:26/,/2022-09-15T14:03/p' mongod.log| grep "op_msg 523ms"
</code></pre>
<p>output of log file :</p>
<pre><code>7391:2022-11-22T09:23:23.047-0500 I COMMAND [conn26] command test.test appName: "MongoDB Shell" command: find { find: "test", filter: { creationDate: new Date(1663252936409) }, lsid: { id: UUID("7c1bb40c-5e99-4281-9351-893e3d23261d") }, $clusterTime: { clusterTime: Timestamp(1669126970, 1), signature: { hash: BinData(0, B141BFD0978167F8C023DFB4AB32BBB117B3CD80), keyId: 7136078726260850692 } }, $db: "test" } planSummary: COLLSCAN keysExamined:0 docsExamined:337738 cursorExhausted:1 numYields:2640 nreturned:1 queryHash:6F9DC23E planCacheKey:6F9DC23E reslen:304 locks:{ ReplicationStateTransition: { acquireCount: { w: 2641 } }, Global: { acquireCount: { r: 2641 } }, Database: { acquireCount: { r: 2641 } }, Collection: { acquireCount: { r: 2641 } }, Mutex: { acquireCount: { r: 1 } } } storage:{ data: { bytesRead: 28615999, timeReadingMicros: 288402 } } protocol:op_msg 523ms
</code></pre>
<p>I have tried below command , but this command is only giving exact value. I need to find all query of log file which is greater than 100ms.</p>
<pre><code>sed -n '/2022-09-15T12:26/,/2022-09-15T14:03/p' mongod.log| grep "op_msg 523ms"
</code></pre>
|
[
{
"answer_id": 74546659,
"author": "R2D2",
"author_id": 10415047,
"author_profile": "https://Stackoverflow.com/users/10415047",
"pm_score": 1,
"selected": false,
"text": "grep -P '\\d+ms' /log/mongodb/mongos.log | while read LINE; do querytime=\"$(echo \"$LINE\" | grep -oP '\\d+ms' | grep -oP '\\d+')\"; if [ \"$querytime\" -gt 6000 ]&&[ \"$querytime\" -lt 7000 ]; then echo \"$LINE\"; fi; done\n mlogfilter mongod.log --slow 7000 --fast 6000\n"
},
{
"answer_id": 74547222,
"author": "William Pursell",
"author_id": 140750,
"author_profile": "https://Stackoverflow.com/users/140750",
"pm_score": 0,
"selected": false,
"text": "protocol:op_msg awk '$(NF-1) ~ /protocol:op_msg/ && $NF > 100 { print $NF }'\n 250h 250ns"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578447/"
] |
74,542,097
|
<pre><code>class Plans(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
plan_type = models.CharField(max_length=255)
class Order(models.Model):
id = models.IntegerField(primary_key=True)
selected_plan_id = models.IntegerField(primary_key=True)
</code></pre>
<p><code>Order</code>'s <code>selected_plan_id</code> is <code>Plans</code>'s <code>id</code>.
Which model should I add a foreign key to? How?</p>
|
[
{
"answer_id": 74542111,
"author": "ilyasbbu",
"author_id": 16475089,
"author_profile": "https://Stackoverflow.com/users/16475089",
"pm_score": 3,
"selected": true,
"text": "id id class Order(models.Model):\n selected_plan_id = models.ForeignKey(Plans, on_delete=models.CASCADE)\n"
},
{
"answer_id": 74542566,
"author": "August Infotech",
"author_id": 20289335,
"author_profile": "https://Stackoverflow.com/users/20289335",
"pm_score": 0,
"selected": false,
"text": "class Order(models.Model):\n id = models.IntegerField(primary_key=True)\n selected_plan_id = models.IntegerField(primary_key=True)\nPlain= models.ForeignKey(Plain)\n"
},
{
"answer_id": 74543758,
"author": "Tümer",
"author_id": 19851429,
"author_profile": "https://Stackoverflow.com/users/19851429",
"pm_score": 1,
"selected": false,
"text": "class Order(models.Model):\n id = models.IntegerField(primary_key=True)\n selected_plan_id = models.ForeignKey(Plans, on_delete=models.CASCADE)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18395075/"
] |
74,542,101
|
<p>Looking at posts like "How do i return the last generated number in a for loop?", "How do I return a value from within a for loop?", and "Having trouble returning a value outside of a for loop with Java" did not help because the problems described in the posts seem tangent to the post titles.</p>
<p>I am receiving the error: "error: missing return statement".</p>
<p>I am trying to create a word count by first setting the word count to 1. The for loop is to traverse a String sentence. Each time a space is found in the String, word count will increase by 1.</p>
<p>Where do I put a return statement so that the program works as intended? I can't put a return statement on the outside of the loop because then 1, the initial value of wc, will be returned.</p>
<pre><code>// wc = word count
public static int wordCount(String sentence) {
int wc = 1;
for (int a = 0; a <= sentence.length()-1; a++) {
if (sentence.charAt(a) == ' ') {
wc += 1;
}
if (a == sentence.length()-1) {
return wc;
}
}
}
</code></pre>
|
[
{
"answer_id": 74542180,
"author": "cybvik",
"author_id": 5897686,
"author_profile": "https://Stackoverflow.com/users/5897686",
"pm_score": 0,
"selected": false,
"text": "public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a <= sentence.length() - 1; a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n }\n return wc;\n}\n"
},
{
"answer_id": 74542188,
"author": "franklysiva",
"author_id": 20470902,
"author_profile": "https://Stackoverflow.com/users/20470902",
"pm_score": 0,
"selected": false,
"text": "public static int wordCount(string sentence) {\n...\nfor(...) {\nif(condtion) {\n...\n}\nif(condition) {\n...\n}\n}\nreturn wc;\n}\n"
},
{
"answer_id": 74542265,
"author": "ThisaruG",
"author_id": 3615862,
"author_profile": "https://Stackoverflow.com/users/3615862",
"pm_score": 2,
"selected": true,
"text": "public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a <= sentence.length()-1; a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n if (a == sentence.length()-1) {\n break;\n }\n }\n return wc;\n}\n a = 0 a <= sentence.length()-1 for (int a = 0; a < sentence.length(); a++) {\n a = 0 a sentence a sentence 1 a == sentence.length() - 1 for public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a < sentence.length(); a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n }\n return wc;\n}\n public static int wordCount(String sentence) {\n String[] words = sentence.split(\" \");\n return words.length(); \n}\n public static int wordCount(String sentence) {\n return sentence.split(\" \").length(); \n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19833360/"
] |
74,542,105
|
<p>Basically, I know that 'socket.io' is a one-on-one communication between the server and the client.</p>
<p>But when I tried to do it myself, it wasn't</p>
<ol>
<li>Connect to the socket using a chrome browser.</li>
<li>Connect to the same page using the secret tab.</li>
</ol>
<p>in the same situation as described above
If an event occurs on client 1, it works on client 2.</p>
<p>How can I generate an event only on each client?</p>
<p>I connected different rooms to each client.</p>
<pre><code>//server
socket.join(`${socket.id}`)
socket.to(`${socket.id}`).emit('event')
</code></pre>
<p>It will not work anywhere.</p>
|
[
{
"answer_id": 74542180,
"author": "cybvik",
"author_id": 5897686,
"author_profile": "https://Stackoverflow.com/users/5897686",
"pm_score": 0,
"selected": false,
"text": "public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a <= sentence.length() - 1; a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n }\n return wc;\n}\n"
},
{
"answer_id": 74542188,
"author": "franklysiva",
"author_id": 20470902,
"author_profile": "https://Stackoverflow.com/users/20470902",
"pm_score": 0,
"selected": false,
"text": "public static int wordCount(string sentence) {\n...\nfor(...) {\nif(condtion) {\n...\n}\nif(condition) {\n...\n}\n}\nreturn wc;\n}\n"
},
{
"answer_id": 74542265,
"author": "ThisaruG",
"author_id": 3615862,
"author_profile": "https://Stackoverflow.com/users/3615862",
"pm_score": 2,
"selected": true,
"text": "public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a <= sentence.length()-1; a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n if (a == sentence.length()-1) {\n break;\n }\n }\n return wc;\n}\n a = 0 a <= sentence.length()-1 for (int a = 0; a < sentence.length(); a++) {\n a = 0 a sentence a sentence 1 a == sentence.length() - 1 for public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a < sentence.length(); a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n }\n return wc;\n}\n public static int wordCount(String sentence) {\n String[] words = sentence.split(\" \");\n return words.length(); \n}\n public static int wordCount(String sentence) {\n return sentence.split(\" \").length(); \n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578438/"
] |
74,542,115
|
<p>Let's say I've got the classic "School" app within my Django project. My <code>school/models.py</code> contains models for both <code>student</code> and <code>course</code>. All my project files live within a directory I named <code>config</code>.</p>
<p>How do I write an include statement(s) within <code>config/urls.py</code> that references two separate endpoints within <code>school/urls.py</code>? And then what do I put in <code>schools/urls.py</code>?</p>
<p>For example, if I were trying to define an endpoint just for <code>students</code>, in <code>config/urls.py</code> I would do something like this:</p>
<pre><code>from django.urls import path, include
urlpatterns = [
...
path("students/", include("school.urls"), name="students"),
...
]
</code></pre>
<p>And then in <code>school/urls.py</code> I would do something like this:</p>
<pre><code>from django.urls import path
from peakbagger.views import StudentCreateView, StudentDetailView, StudentListView, StudentUpdateView, StudentDeleteView
urlpatterns = [
# ...
path("", StudentListView.as_view(), name="student-list"),
path("add/", StudentCreateView.as_view(), name="student-add"),
path("<int:pk>/", StudentDetailView.as_view(), name="student-detail"),
path("<int:pk>/update/", StudentUpdateView.as_view(), name="student-update"),
path("<int:pk>/delete/", StudentDeleteView.as_view(), name="student-delete"),
]
</code></pre>
<p>But how do I do I add another urlpattern to config/urls.py along the lines of something like this? The <code>include</code> statement needs some additional info/parameters, no?</p>
<pre><code>from django.urls import path, include
urlpatterns = [
...
path("students/", include("school.urls"), name="students"),
path("courses/", include("school.urls"), name="courses"),
...
]
</code></pre>
<p>And then what happens inside of <code>school/urls.py</code>?</p>
<p>I'm open to suggestions, and definitely am a neophyte when it comes to the Django philosophy. Do I need an additional urls.py somewhere? I'd prefer not to put everything in <code>config/urls.py</code> and I'd prefer not to build a separate app for both students and courses.</p>
|
[
{
"answer_id": 74542180,
"author": "cybvik",
"author_id": 5897686,
"author_profile": "https://Stackoverflow.com/users/5897686",
"pm_score": 0,
"selected": false,
"text": "public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a <= sentence.length() - 1; a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n }\n return wc;\n}\n"
},
{
"answer_id": 74542188,
"author": "franklysiva",
"author_id": 20470902,
"author_profile": "https://Stackoverflow.com/users/20470902",
"pm_score": 0,
"selected": false,
"text": "public static int wordCount(string sentence) {\n...\nfor(...) {\nif(condtion) {\n...\n}\nif(condition) {\n...\n}\n}\nreturn wc;\n}\n"
},
{
"answer_id": 74542265,
"author": "ThisaruG",
"author_id": 3615862,
"author_profile": "https://Stackoverflow.com/users/3615862",
"pm_score": 2,
"selected": true,
"text": "public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a <= sentence.length()-1; a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n if (a == sentence.length()-1) {\n break;\n }\n }\n return wc;\n}\n a = 0 a <= sentence.length()-1 for (int a = 0; a < sentence.length(); a++) {\n a = 0 a sentence a sentence 1 a == sentence.length() - 1 for public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a < sentence.length(); a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n }\n return wc;\n}\n public static int wordCount(String sentence) {\n String[] words = sentence.split(\" \");\n return words.length(); \n}\n public static int wordCount(String sentence) {\n return sentence.split(\" \").length(); \n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7045589/"
] |
74,542,123
|
<pre><code>// int i=0;
// while(i<5){
// System.out.println(i);
// System.out.println("Java is great.");
// if (i==2){
// System.out.println("Ending the Loop.");
// break;
//
// }
// i++; //DOUBT:WHEN I WRITE i++ AFTER 4TH LINE WHY "2" IS NOT PRINTED IN OUTPUT.
// }
// int i=0;
// do{
// System.out.println(i);
// System.out.println("Java is Great.");
// if (i==2){
// System.out.println("Ending the Loop.");
// break;
// }
// i++;
// } while (i<5);
// for (int i=0; i<50; i++){
// if (i==2){
// System.out.println("Ending the Loop");
// continue;
// }
// System.out.println(i);
// System.out.println("Java is Great.");
// }
int i=0;
do{
i++;
if(i==2){
System.out.println("Ending the loop.");
continue;
}
System.out.println(i);
System.out.println("Java is Great.");
}while(i<5);
//DOUBT:WHY 5 IS GETTING PRINTED IN THIS EVEN IF THE CONDITION IS (i<5).
</code></pre>
<p>Basically in all these codes my doubt is how can i decide the exact posiiton of certain codes to get the appropriate results.
Like when i write i++; above the if statement and after the if statement then different results gets printed.</p>
|
[
{
"answer_id": 74542180,
"author": "cybvik",
"author_id": 5897686,
"author_profile": "https://Stackoverflow.com/users/5897686",
"pm_score": 0,
"selected": false,
"text": "public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a <= sentence.length() - 1; a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n }\n return wc;\n}\n"
},
{
"answer_id": 74542188,
"author": "franklysiva",
"author_id": 20470902,
"author_profile": "https://Stackoverflow.com/users/20470902",
"pm_score": 0,
"selected": false,
"text": "public static int wordCount(string sentence) {\n...\nfor(...) {\nif(condtion) {\n...\n}\nif(condition) {\n...\n}\n}\nreturn wc;\n}\n"
},
{
"answer_id": 74542265,
"author": "ThisaruG",
"author_id": 3615862,
"author_profile": "https://Stackoverflow.com/users/3615862",
"pm_score": 2,
"selected": true,
"text": "public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a <= sentence.length()-1; a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n if (a == sentence.length()-1) {\n break;\n }\n }\n return wc;\n}\n a = 0 a <= sentence.length()-1 for (int a = 0; a < sentence.length(); a++) {\n a = 0 a sentence a sentence 1 a == sentence.length() - 1 for public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a < sentence.length(); a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n }\n return wc;\n}\n public static int wordCount(String sentence) {\n String[] words = sentence.split(\" \");\n return words.length(); \n}\n public static int wordCount(String sentence) {\n return sentence.split(\" \").length(); \n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489939/"
] |
74,542,128
|
<p>I have a javascript class and Html file for Flutter web-app. Both these files are in web folder. I'm loading these using flutter class with below code :</p>
<pre><code>class WebClass implements CommonAbstractClass {
@override
Widget build(BuildContext context) {
ui.platformViewRegistry.registerViewFactory(
'hello-html',
(int viewId) => IFrameElement()
..width = '640'
..height = '360'
..src = 'myHtmlFile.html'
..style.border = 'none');
return Scaffold(
appBar: AppBar(title: const Text('Web App')),
body: Stack(
children: const [
SizedBox(
height: 500,
child: HtmlElementView(
viewType: 'hello-html',
)),
],
),
);
}
}
</code></pre>
<p>Above code loads html and works well. The javascript prints the result. What I'm looking for is to get that same result in flutter file. Is there any way to get result from html/javascript to flutter while using HtmlElementView ?</p>
|
[
{
"answer_id": 74542180,
"author": "cybvik",
"author_id": 5897686,
"author_profile": "https://Stackoverflow.com/users/5897686",
"pm_score": 0,
"selected": false,
"text": "public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a <= sentence.length() - 1; a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n }\n return wc;\n}\n"
},
{
"answer_id": 74542188,
"author": "franklysiva",
"author_id": 20470902,
"author_profile": "https://Stackoverflow.com/users/20470902",
"pm_score": 0,
"selected": false,
"text": "public static int wordCount(string sentence) {\n...\nfor(...) {\nif(condtion) {\n...\n}\nif(condition) {\n...\n}\n}\nreturn wc;\n}\n"
},
{
"answer_id": 74542265,
"author": "ThisaruG",
"author_id": 3615862,
"author_profile": "https://Stackoverflow.com/users/3615862",
"pm_score": 2,
"selected": true,
"text": "public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a <= sentence.length()-1; a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n if (a == sentence.length()-1) {\n break;\n }\n }\n return wc;\n}\n a = 0 a <= sentence.length()-1 for (int a = 0; a < sentence.length(); a++) {\n a = 0 a sentence a sentence 1 a == sentence.length() - 1 for public static int wordCount(String sentence) {\n int wc = 1;\n for (int a = 0; a < sentence.length(); a++) {\n if (sentence.charAt(a) == ' ') {\n wc += 1;\n }\n }\n return wc;\n}\n public static int wordCount(String sentence) {\n String[] words = sentence.split(\" \");\n return words.length(); \n}\n public static int wordCount(String sentence) {\n return sentence.split(\" \").length(); \n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3519241/"
] |
74,542,144
|
<p>This is the list I have :</p>
<pre><code>list_input = [432567,876323,124356]
</code></pre>
<p>This is the Output I need :</p>
<pre><code>List_output = [321456,765212,013245]
</code></pre>
<p>like so,</p>
<pre><code>for index, number in enumerate(list_input):
one_number = list_lnput(index)
one_digit_list = list(one_number[0])
</code></pre>
<p>and I don't have Idea after this step</p>
|
[
{
"answer_id": 74542217,
"author": "Michael Ruth",
"author_id": 4583620,
"author_profile": "https://Stackoverflow.com/users/4583620",
"pm_score": 0,
"selected": false,
"text": "list_input = [432567,876323,124356]\nlist_output = [''.join(str(int(digit)-1) for digit in str(s)) \n for s in list_input]\n list_input = [-4306]\nlist_output = [''.join(str(int(digit)-1) for digit in str(s)) \n for s in list_input]\nprint(list_output)\n\nTraceback (most recent call last):\n File \"/Users/michael.ruth/SO/solution.py\", line 2, in <module>\n list_output = [''.join(str(int(digit)-1) for digit in str(s))\n File \"/Users/michael.ruth/SO/solution.py\", line 2, in <listcomp>\n list_output = [''.join(str(int(digit)-1) for digit in str(s))\n File \"/Users/michael.ruth/SO/solution.py\", line 2, in <genexpr>\n list_output = [''.join(str(int(digit)-1) for digit in str(s))\nValueError: invalid literal for int() with base 10: '-'\n"
},
{
"answer_id": 74542270,
"author": "tdelaney",
"author_id": 642070,
"author_profile": "https://Stackoverflow.com/users/642070",
"pm_score": 1,
"selected": true,
"text": "divmod def digit_subtract(num):\n result = 0\n base = 1\n while num:\n num, remain = divmod(num, 10)\n result += (remain-1) * base\n base *= 10\n return result\n\nlist_input = [432567,876323,124356]\nList_output = [321456,765212,13245]\n\ntest = [digit_subtract(num) for num in list_input]\nprint(test)\nassert test == List_output\n"
},
{
"answer_id": 74542348,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 1,
"selected": false,
"text": "i int(math.log10(i)) + 1 (10 ** (int(math.log10(i)) + 1) - 1) // 9 import math\n\ndef decrement_digits(i):\n return i - (10 ** (int(math.log10(i)) + 1) - 1) // 9\n decrement_digits(432567) 321456\n List_output = list(map(decrement_digits, list_input))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14294926/"
] |
74,542,181
|
<p>I was learning JavaScript and kind of ran into problem that said like this :
<a href="https://i.stack.imgur.com/hStM1.png" rel="nofollow noreferrer">Error Image </a></p>
<p>Here's my package.json
<a href="https://i.stack.imgur.com/ciaeO.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>So to explain, this is my vanilla js where i have installed parcel</p>
<p>Vs code Terminal</p>
<ul>
<li>npm i parcel --save-dev</li>
<li>npm run start</li>
<li>npm run build</li>
</ul>
<p>theen this error pops up. I don't know if i added enough screenshots or details to make someone understand my problem. If you do have a solution help please.</p>
<p>Edit : I also tried,</p>
<p>"main" : "17th.html" as suggested which then threw new error saying the extension should be of .js</p>
<p>Final edit : So , i deleted "main" and then it worked like a charm. Dont know why it works but it works . If someone could explain why it works then i would be very grateful.</p>
<p>I was expeccting a successful build</p>
|
[
{
"answer_id": 74542217,
"author": "Michael Ruth",
"author_id": 4583620,
"author_profile": "https://Stackoverflow.com/users/4583620",
"pm_score": 0,
"selected": false,
"text": "list_input = [432567,876323,124356]\nlist_output = [''.join(str(int(digit)-1) for digit in str(s)) \n for s in list_input]\n list_input = [-4306]\nlist_output = [''.join(str(int(digit)-1) for digit in str(s)) \n for s in list_input]\nprint(list_output)\n\nTraceback (most recent call last):\n File \"/Users/michael.ruth/SO/solution.py\", line 2, in <module>\n list_output = [''.join(str(int(digit)-1) for digit in str(s))\n File \"/Users/michael.ruth/SO/solution.py\", line 2, in <listcomp>\n list_output = [''.join(str(int(digit)-1) for digit in str(s))\n File \"/Users/michael.ruth/SO/solution.py\", line 2, in <genexpr>\n list_output = [''.join(str(int(digit)-1) for digit in str(s))\nValueError: invalid literal for int() with base 10: '-'\n"
},
{
"answer_id": 74542270,
"author": "tdelaney",
"author_id": 642070,
"author_profile": "https://Stackoverflow.com/users/642070",
"pm_score": 1,
"selected": true,
"text": "divmod def digit_subtract(num):\n result = 0\n base = 1\n while num:\n num, remain = divmod(num, 10)\n result += (remain-1) * base\n base *= 10\n return result\n\nlist_input = [432567,876323,124356]\nList_output = [321456,765212,13245]\n\ntest = [digit_subtract(num) for num in list_input]\nprint(test)\nassert test == List_output\n"
},
{
"answer_id": 74542348,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 1,
"selected": false,
"text": "i int(math.log10(i)) + 1 (10 ** (int(math.log10(i)) + 1) - 1) // 9 import math\n\ndef decrement_digits(i):\n return i - (10 ** (int(math.log10(i)) + 1) - 1) // 9\n decrement_digits(432567) 321456\n List_output = list(map(decrement_digits, list_input))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15098194/"
] |
74,542,189
|
<p>A MEX (Minimum Excluded) is the minimum non-negative integer that is excluded from the collection/list.
Eg :</p>
<pre><code>MEX [] = 0
MEX [1,2,3,4,5,10,10000] = 0
MEX [0,1,2,3,4,5,6] = 7
MEX [0,1,3,4,1000] = 2
MEX [0,2,3,4,5,6] =1
</code></pre>
<p>Given a list of non negative integers, find the MEX of the list.</p>
<p>So, I tried sorting the array and then comparing the number at each position with its index to find the minimum number which is missing. The time complexity of this approach is O(nlogn + n). I am looking for a more optimised solution!</p>
|
[
{
"answer_id": 74542217,
"author": "Michael Ruth",
"author_id": 4583620,
"author_profile": "https://Stackoverflow.com/users/4583620",
"pm_score": 0,
"selected": false,
"text": "list_input = [432567,876323,124356]\nlist_output = [''.join(str(int(digit)-1) for digit in str(s)) \n for s in list_input]\n list_input = [-4306]\nlist_output = [''.join(str(int(digit)-1) for digit in str(s)) \n for s in list_input]\nprint(list_output)\n\nTraceback (most recent call last):\n File \"/Users/michael.ruth/SO/solution.py\", line 2, in <module>\n list_output = [''.join(str(int(digit)-1) for digit in str(s))\n File \"/Users/michael.ruth/SO/solution.py\", line 2, in <listcomp>\n list_output = [''.join(str(int(digit)-1) for digit in str(s))\n File \"/Users/michael.ruth/SO/solution.py\", line 2, in <genexpr>\n list_output = [''.join(str(int(digit)-1) for digit in str(s))\nValueError: invalid literal for int() with base 10: '-'\n"
},
{
"answer_id": 74542270,
"author": "tdelaney",
"author_id": 642070,
"author_profile": "https://Stackoverflow.com/users/642070",
"pm_score": 1,
"selected": true,
"text": "divmod def digit_subtract(num):\n result = 0\n base = 1\n while num:\n num, remain = divmod(num, 10)\n result += (remain-1) * base\n base *= 10\n return result\n\nlist_input = [432567,876323,124356]\nList_output = [321456,765212,13245]\n\ntest = [digit_subtract(num) for num in list_input]\nprint(test)\nassert test == List_output\n"
},
{
"answer_id": 74542348,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 1,
"selected": false,
"text": "i int(math.log10(i)) + 1 (10 ** (int(math.log10(i)) + 1) - 1) // 9 import math\n\ndef decrement_digits(i):\n return i - (10 ** (int(math.log10(i)) + 1) - 1) // 9\n decrement_digits(432567) 321456\n List_output = list(map(decrement_digits, list_input))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20414487/"
] |
74,542,196
|
<p>I set <code>window.commandCenter: true</code>, but I accidentally hide <code>launch Command Center</code> <code>Go Back</code> <code>Go Forward</code>.</p>
<p>Now when I right-click the title bar, there is nothing about them.</p>
<p>It used to be like this
<a href="https://i.stack.imgur.com/vImzX.png" rel="nofollow noreferrer">old-img</a></p>
<p>But now it's this, I cann't open that three
<a href="https://i.stack.imgur.com/VitA1.png" rel="nofollow noreferrer">now-img</a></p>
<p>I try reset <code>window.commandCenter: true</code> but nothing happened</p>
|
[
{
"answer_id": 74542217,
"author": "Michael Ruth",
"author_id": 4583620,
"author_profile": "https://Stackoverflow.com/users/4583620",
"pm_score": 0,
"selected": false,
"text": "list_input = [432567,876323,124356]\nlist_output = [''.join(str(int(digit)-1) for digit in str(s)) \n for s in list_input]\n list_input = [-4306]\nlist_output = [''.join(str(int(digit)-1) for digit in str(s)) \n for s in list_input]\nprint(list_output)\n\nTraceback (most recent call last):\n File \"/Users/michael.ruth/SO/solution.py\", line 2, in <module>\n list_output = [''.join(str(int(digit)-1) for digit in str(s))\n File \"/Users/michael.ruth/SO/solution.py\", line 2, in <listcomp>\n list_output = [''.join(str(int(digit)-1) for digit in str(s))\n File \"/Users/michael.ruth/SO/solution.py\", line 2, in <genexpr>\n list_output = [''.join(str(int(digit)-1) for digit in str(s))\nValueError: invalid literal for int() with base 10: '-'\n"
},
{
"answer_id": 74542270,
"author": "tdelaney",
"author_id": 642070,
"author_profile": "https://Stackoverflow.com/users/642070",
"pm_score": 1,
"selected": true,
"text": "divmod def digit_subtract(num):\n result = 0\n base = 1\n while num:\n num, remain = divmod(num, 10)\n result += (remain-1) * base\n base *= 10\n return result\n\nlist_input = [432567,876323,124356]\nList_output = [321456,765212,13245]\n\ntest = [digit_subtract(num) for num in list_input]\nprint(test)\nassert test == List_output\n"
},
{
"answer_id": 74542348,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 1,
"selected": false,
"text": "i int(math.log10(i)) + 1 (10 ** (int(math.log10(i)) + 1) - 1) // 9 import math\n\ndef decrement_digits(i):\n return i - (10 ** (int(math.log10(i)) + 1) - 1) // 9\n decrement_digits(432567) 321456\n List_output = list(map(decrement_digits, list_input))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578554/"
] |
74,542,278
|
<p>I need a two-column layout, where the left (sidebar) is fixed and the right (main content) is scrollable.</p>
<p>I've done so with bootstrap's flex grid/layout:</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>#left { width: 10rem; }
#right { margin-left: 10rem; } /* <------------- PROBLEM */</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="row g-0">
<nav id="left" class="col vh-100 position-fixed bg-success">test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test</nav>
<main id="right" class="col bg-warning">START test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test FINISH</main>
</div></code></pre>
</div>
</div>
</p>
<p>The problem is the right column knows about the left column's width. I tried bootstrap's <code>col-auto</code> but that doesn't help.</p>
<p>In reality, the left column is an imported sidebar component, which is self-contained. So the rest of my design (and the right column) should not have any knowledge of its dimensions. For example:</p>
<pre class="lang-html prettyprint-override"><code><div class="container">
<sidebar />
<main id="right"><!-- whatever --></main>
</div>
</code></pre>
<p><em>How can I change this layout so the sidebar's width is not needed by the rest of the design?</em> Is that even possible?</p>
<p>Note:</p>
<ul>
<li>It doesn't need to be in bootstrap (it can be plain css)</li>
<li>There's no JavaScript in my wasm SPA framework, so I can't use it (and regardless, it must be a self-contained component)</li>
</ul>
|
[
{
"answer_id": 74542344,
"author": "Boguz",
"author_id": 5509709,
"author_profile": "https://Stackoverflow.com/users/5509709",
"pm_score": 2,
"selected": false,
"text": "* {\n margin: 0;\n padding;\n 0;\n box-sizing: border-box;\n}\n\n.row {\n display: grid;\n grid-template-columns: auto 1fr;\n position: relative;\n}\n\n.col {\n height: fit-content;\n padding: 1rem;\n}\n\n.col--left {\n width: 10rem;\n background-color: lightgreen;\n position: sticky;\n top: 0;\n}\n\n.col--right {\n background-color: lightblue;\n} <div class=\"row g-0\">\n <nav id=\"left\" class=\"col col--left\">SIDEBAR test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test</nav>\n <main id=\"right\" class=\"col col--right\">START test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test testtest test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test testtest test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test testtest test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test\n test test test test test test test test test test test test test test FINISH</main>\n</div>"
},
{
"answer_id": 74542657,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 2,
"selected": true,
"text": "position: sticky fixed #left #left fixed #right flex: 1 width #left /* Try any value */\n#left { width: 10rem }\n/* Auto-fill */\n#right { flex: 1 }\n\n* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\n.container {\n display: flex;\n}\n\nnav {\n position: sticky;\n top: 0;\n height: 100vh;\n background-color: pink;\n}\n\nmain {\n background-color: beige;\n} <div class=\"container\">\n<nav id=\"left\">test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test</nav>\n<main id=\"right\">START test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test FINISH</main>\n</div>"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9971404/"
] |
74,542,280
|
<p>I tried to create a gradient text with tailwindcss but the bottom of the string is getting cut off.</p>
<p>Letters like 'g' or 'p' that hand below the text line get partially cut off when making a string gradient with tailwindcss (see image below). I think this is happening because the gradient only goes to the bottom of the text line, so anything below it does not have a gradient background, but I don't know how to fix it.</p>
<p><a href="https://i.stack.imgur.com/fD5WG.png" rel="nofollow noreferrer">Bottom of letters get cut off</a></p>
<p>I am using <a href="https://tailwindcss.com/docs/background-clip#cropping-to-text" rel="nofollow noreferrer">tailwinds cropping to text</a> to create a gradient background behind my text.</p>
<p>This is the exact code in my app:</p>
<pre><code><div class="px-10 sm:px-10 md:px-12 bg-white border-2 border-white border-t-pglightgrey">
<div class='relative max-w-6xl mx-auto pt-20 sm:pt-24 lg:pt-32'>
<h1 class="font-semibold text-4xl sm:text-5xl lg:text-6xl tracking-tight text-center bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500">Testing Image grapes plane page</span></h1>
</div>
</div>
</code></pre>
<p>I have tried using the with the sting in a different and I even tried using one of the <a href="https://tailwindui.com/components/preview" rel="nofollow noreferrer">boilerplate components</a>(the one at the bottom of the page) from the tailwindcss website but the issue still persisted.</p>
<p>If anyone could help that would be greatly appreciated!</p>
|
[
{
"answer_id": 74542656,
"author": "Manjesh Kumar Sharma",
"author_id": 19296050,
"author_profile": "https://Stackoverflow.com/users/19296050",
"pm_score": 1,
"selected": true,
"text": "<div class=\"px-10 sm:px-10 md:px-12 bg-white border-2 border-white border-t-pglightgrey\">\n <div class='relative max-w-6xl mx-auto pt-20 sm:pt-24 lg:pt-32'>\n <h1 class=\"h-[8rem] sm:h-[4rem] font-semibold text-4xl sm:text-5xl lg:text-6xl tracking-tight text-center bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500\"><span class=\"text-center\">Testing Image grapes plane page<span/></h1>\n </div>\n</div>"
},
{
"answer_id": 74546320,
"author": "Nirmal Singh",
"author_id": 4903005,
"author_profile": "https://Stackoverflow.com/users/4903005",
"pm_score": 1,
"selected": false,
"text": "<div class=\"px-10 sm:px-10 md:px-12 bg-white border-2 border-white border-t-pglightgrey\">\n<div class='relative max-w-6xl mx-auto pt-20 sm:pt-24 lg:pt-32'>\n <h1 class=\"font-semibold text-4xl pb-3 sm:text-5xl leading-tight sm:leading-tight lg:leading-relaxed lg:text-6xl tracking-tight text-center bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500\">Testing Image grapes plane page</h1>\n</div>\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578257/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.