qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,576,804
|
<p>I'm very new to this. I just started programming last week. I need some basic help. My assignment is to input five numbers and get the output to print out "odd" or "even" for each one. This is how I have started:</p>
<pre class="lang-py prettyprint-override"><code>num = int(input())
if (num % 2) == 0:
print('even')
else:
print('odd')
</code></pre>
<p>How can I have five numbers in the input? I don't want to make a hardcoded list; the program has to work with different numbers each time. I hope you understand my question. Thank you for helping out.</p>
<p>EDIT:
I am not supposed to import anything, so I can't use <code>import random</code>. I'm supposed to input 5 numbers. For example:</p>
<p><strong>input</strong></p>
<pre><code>3
5
2
1
33
</code></pre>
<p><strong>Output</strong></p>
<pre><code>Odd
Odd
Even
Odd
Odd
</code></pre>
<p>So I have made some progress but it's still wrong.</p>
<pre class="lang-py prettyprint-override"><code>for _ in range(5):
num = int(input())
if (num % 2) == 0:
print('even')
else:
print('odd')
</code></pre>
<p>I now get the output (odd or even) before I have written all numbers in the input. I don't know how to change that. I want to write the five numbers and then get the output. I hope I have explained this well. Sorry for the confusion.</p>
|
[
{
"answer_id": 74576844,
"author": "Volodymyr Pivoshenko",
"author_id": 20554409,
"author_profile": "https://Stackoverflow.com/users/20554409",
"pm_score": 1,
"selected": false,
"text": "import random\n\n# you can define your own limits\n# or you can use numpy to generate random numbers from the different distributions\nnumber = random.randint(0, 999)\nprint(f\"Current number: {number}.\")\n\nprint(\"Even!\") if number % 2 == 0 else print(\"Odd!\")\n"
},
{
"answer_id": 74576857,
"author": "Aarav Dave",
"author_id": 13177027,
"author_profile": "https://Stackoverflow.com/users/13177027",
"pm_score": 1,
"selected": false,
"text": "nums = input('Enter your numbers: ').split()\nfor num in nums:\n if int(num) % 2 == 0:\n print('even')\n else:\n print('odd')\n"
},
{
"answer_id": 74577048,
"author": "aVral",
"author_id": 13063076,
"author_profile": "https://Stackoverflow.com/users/13063076",
"pm_score": 0,
"selected": false,
"text": "ls = [(print(num, \"Even\") if (num % 2) == 0 else print(num, \"Odd\")) for num in range(1,6)]\n 1 Odd\n2 Even\n3 Odd\n4 Even\n5 Odd\n"
},
{
"answer_id": 74577051,
"author": "Yaman Jain",
"author_id": 2756517,
"author_profile": "https://Stackoverflow.com/users/2756517",
"pm_score": 0,
"selected": false,
"text": "import random\n\nexperiment_to_run = int(input()) # how many times you want to run the experiment, let us say default is 5, but that can be user input as well\nlower_bound_of_numbers = int(input()) # lower bound of the integer range\nupper_bound_of_numbers = int(input()) # upper bound of the integer range\n\ndef print_even_or_odd(experiment_to_run = 5, lower_bound_of_numbers = 1, upper_bound_of_numbers = 10):\n for current_experiment_run in range(experiment_to_run):\n current_number = random.randint(lower_bound_of_numbers, upper_bound_of_numbers) # this generates random integer between lower_bound_of_numbers (inclusive) and upper_bound_of_numbers (exclusive)\n \n if current_number % 2 == 0:\n print ('even')\n else:\n print ('odd')\n\n# dry run \nprint_even_or_odd(experiment_to_run, lower_bound_of_numbers, upper_bound_of_numbers) # feel to add current_number also to the log if needed for debugging purpose\n"
},
{
"answer_id": 74578028,
"author": "Lecdi",
"author_id": 16768672,
"author_profile": "https://Stackoverflow.com/users/16768672",
"pm_score": 0,
"selected": false,
"text": "input for for # Create a list to store the five numbers\nnums = []\n\n# Fill the list with five inputs from the user\nfor _ in range(5):\n nums.append(int(input()))\n # Explanation of above line:\n # - The `append` function adds a new item to a list\n # - So this line gets input from the user,\n # turns it into an integer,\n # and adds it to the list\n\n# Finally, output whether each number is odd or even\n# Iterate over the `nums` list using a for loop\nfor num in nums:\n # The code here will run one time for each item in the `nums` list\n # Each time the code runs, the variable `num` will store the current item\n # So we can do a test on `num` to see if each item is odd or even\n if (num % 2) == 0:\n print(num, \"is even\")\n else:\n print(num, \"is odd\")\n if __name__ == \"__main__:\" #!/usr/bin/env python3\n\"\"\"This script gets five integers from the user and outputs whether each is odd or even\"\"\"\n\ndef main():\n nums = [get_user_num() for _ in range(5)]\n for num in nums:\n if is_even(num):\n print(num, \"is even\")\n else:\n print(num, \"is odd\")\n\n\ndef get_user_num():\n num = input(\"Enter an integer: \")\n while True:\n # Repeat until the user enters a valid integer\n try:\n return int(num)\n except ValueError:\n num = input(\"That was not an integer - please try again: \")\n\n\ndef is_even(num):\n return (num % 2) == 0\n\n\nif __name__ == \"__main__\":\n main()\n if __name__ == \"__main__\":"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20582982/"
] |
74,576,820
|
<p>If I have a React array state created with the <code>useState</code> hook, is it possible to somehow find out what elements have been updated? My intention is to run some code whenever the state updates, inside of a <code>useEffect</code> hook, but I would like to have access to the index(es) of the updated array elements. Is this possible?</p>
|
[
{
"answer_id": 74576893,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 2,
"selected": true,
"text": "const [myArray, setMyArray] = useState([]);\nconst [myPreviousArray, setMyPreviousArray] = useState([]);\n\n// Assume we have a function that updates the state\nconst handleArrayDataChange = (newValue) => {\n setMyPreviousArray([...myArray]);\n setMyArray(newValue);\n}\n\nuseEffect(() => {\n myArray.forEach((item, index) => {\n if(JSON.stringify(item) !== JSON.stringify(myPreviousArray[index])) {\n // The item is updated\n }\n });\n}, [myArray]);\n"
},
{
"answer_id": 74576934,
"author": "Abhishek Chandrasenan",
"author_id": 19547606,
"author_profile": "https://Stackoverflow.com/users/19547606",
"pm_score": -1,
"selected": false,
"text": "const [nameArray, setNameArray] = useState([]);\n\nuseEffect(() => {\n// things you want to do\n},[nameArray]);\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18956037/"
] |
74,576,878
|
<p>I would like to set up my XMonad such that I have a keybinding that switches to a specific layout when a key is being pressed down and held, and then switches back to the other specific layout when the same key is released.</p>
<p>To switch to the first layout on key down, I have my keybindings in XMonad defined like this:</p>
<pre><code>myKeyDownBindings :: XConfig l -> M.Map ( KeyMask, KeySym ) ( X () )
myKeyDownBindings conf@(XConfig {XMonad.modMask = myModMask}) = mkKeymap conf $
[
, ("M-<Space>", sendMessage $ JumpToLayout "mySpecialLayout")
-- ...
]
</code></pre>
<p>To switch back to the other layout on key release, I have another key binding defined like this:</p>
<pre><code>myKeyUpBindings :: XConfig l -> M.Map ( KeyMask, KeySym ) ( X () )
myKeyUpBindings conf@(XConfig {XMonad.modMask = myModMask}) = mkKeymap conf $
[
("M-<Space>", sendMessage $ JumpToLayout "myRegularLayout")
]
</code></pre>
<p>...and I made an event hook module very closely based on <a href="https://stackoverflow.com/a/11308086/5294916">this</a> answer that takes <code>myKeyUpBindings</code> as an argument:</p>
<pre><code>module Hooks.KeyUp (keyUpEventHook) where
import XMonad
import Data.Monoid
import qualified Data.Map as M (Map, lookup)
keyUpEventHook :: M.Map ( KeyMask, KeySym ) ( X () ) -> Event -> X All
keyUpEventHook ks ev =
handle ev ks
>> return (All True)
handle :: Event -> M.Map ( KeyMask, KeySym ) ( X () ) -> X ()
handle (KeyEvent {ev_event_type = t, ev_state = m, ev_keycode = code}) ks
| t == keyRelease =
withDisplay $ \dpy -> do
s <- io $ keycodeToKeysym dpy code 0
mClean <- cleanMask m
userCodeDef () $ whenJust (M.lookup (mClean, s) ks) id
handle _ _ = return ()
</code></pre>
<p>Then I pass both <code>myKeyUpBindings</code> and <code>myKeyDownBindings</code> to XMonad like this:</p>
<pre><code>myEventHook :: Event -> X All
myEventHook ev = keyUpEventHook (myKeyUpBindings myConfig)
$ ev
myConfig = def
{
keys = myKeyDownBindings
, handleEventHook = myEventHook
-- ...
}
</code></pre>
<p>This nearly works; it switches to <code>"mySpecialLayout"</code> on key down and <code>"myRegularLayout"</code> on key up...but the problem is that when I hold down spacebar for more than a moment, XMonad starts to flicker really fast between the two layouts, instead of just switching once to <code>"mySpecialLayout"</code>. How can I make it so that XMonad runs the <code>X ()</code> action from <code>keys</code> only once when the key is pressed?</p>
<h3>Possible approach?</h3>
<p>I am thinking it may be possible to do this by using <a href="https://hackage.haskell.org/package/xmonad-contrib-0.17.1/docs/XMonad-Util-ExtensibleState.html" rel="nofollow noreferrer"><code>XMonad.Util.ExtensibleState</code></a> to toggle a boolean variable on key down and again on key up, and have my key down <code>X ()</code> action be either <code>return ()</code> (if the value is <code>True</code>) or <code>sendMessage $ JumpToLayout "mySpecialLayout"</code> (if the value is <code>False</code>), but I am not sure how I would implement this. How would I read the boolean value from the mutable state--say, in an <code>if</code> statement?
I know this is incorrect, but this is along the lines of my thinking:</p>
<pre><code>myKeyDownBindings :: XConfig l -> M.Map ( KeyMask, KeySym ) ( X () )
myKeyDownBindings conf@(XConfig {XMonad.modMask = myModMask}) = mkKeymap conf $
[
("M-<Space>", jumpToKeyDownLayout)
]
myKeyUpBindings :: XConfig l -> M.Map ( KeyMask, KeySym ) ( X () )
myKeyUpBindings conf@(XConfig {XMonad.modMask = myModMask}) = mkKeymap conf $
[
("M-<Space>", jumpToKeyUpLayout)
]
data KeyDownStatus = KeyDownStatus Bool
instance ExtensionClass KeyDownStatus where
initialValue = KeyDownStatus False
jumpToKeyUpLayout :: X ()
jumpToKeyUpLayout = XS.put (KeyDownStatus False)
>> (sendMessage $ JumpToLayout "myRegularLayout")
jumpToKeyDownLayout :: X ()
jumpToKeyDownLayout = (XS.get :: X KeyDownStatus)
>>= \keyAlreadyDown -> -- this is the wrong type
case keyAlreadyDown of -- how do I do the equivalent of this for my type?
True -> return ()
False -> XS.put (KeyDownStatus True)
>> (sendMessage $ JumpToLayout "mySpecialLayout")
</code></pre>
<p>This yields the following compilation error, which I kind of expected but do not know how to resolve:</p>
<pre><code> • Couldn't match expected type ‘KeyDownStatus’
with actual type ‘Bool’
• In the pattern: True
In a case alternative: True -> return ()
In the expression:
case keyAlreadyDown of
True -> return ()
False
-> XS.put (KeyDownStatus True)
>> (sendMessage $ JumpToLayout "grid")
|
118 | True -> return ()
| ^^^^
</code></pre>
<p>I looked at <a href="https://www.reddit.com/r/xmonad/comments/24jcvf/i_want_to_toggle_a_boolean_variable_xpost_from/" rel="nofollow noreferrer">this</a> Reddit post with an answer about that module and only got more confused.</p>
<h1>UPDATE #1</h1>
<p>Fixed the compilation error thanks to a provided answer. Here is my current code for switching the workspaces:</p>
<pre><code>data KeyStatus = Down | Up deriving (Eq, Read, Show)
instance ExtensionClass KeyStatus where initialValue = Up
myLayoutToggle :: KeyStatus -> String -> X ()
myLayoutToggle s l = (XS.get :: X KeyStatus)
>>= \key ->
if key == s then return ()
else XS.put (s)
>> (sendMessage $ JumpToLayout l)
</code></pre>
<p>and then I call it like:</p>
<pre><code>myKeyUpBindings conf@(XConfig {XMonad.modMask = myModMask}) = mkKeymap conf $
[
("M-<Space>", myLayoutToggle Up "myRegularLayout")
]
myKeyDownBindings conf@(XConfig {XMonad.modMask = myModMask}) = mkKeymap conf $
[
("M-<Space>", myLayoutToggle Down "mySpecialLayout")
]
</code></pre>
<p>This works exactly as it did before; it still flickers. If I replace a line in <code>myLayoutToggle</code> to debug...</p>
<pre><code>myLayoutToggle s l = (XS.get :: X KeyStatus)
>>= \key ->
if key == s then (spawn $ "echo Returning because key is already " ++ (show s) ++ ">>" ++ myPath ++ ".tmp" )
>> return ()
else XS.put (s)
>> (spawn $ "echo Key switched status to " ++ (show s) ++ ">>" ++ myPath ++ ".tmp" )
</code></pre>
<p>...and then press down <code>M-<Space></code> once and hold for roughly one second, this is what gets written to <code>.tmp</code>:</p>
<pre><code>Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Down
Key switched status to Up
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Down
Key switched status to Up
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
Key switched status to Down
Key switched status to Up
</code></pre>
<p>What is happening here? Why is <code>key == s</code> never returning <code>True</code>?</p>
|
[
{
"answer_id": 74577707,
"author": "Daniel Wagner",
"author_id": 791604,
"author_profile": "https://Stackoverflow.com/users/791604",
"pm_score": 2,
"selected": true,
"text": "KeyDownStatus case keyAlreadyDown of\n KeyDownStatus True -> ...\n KeyDownStatus False -> ...\n newtype data newtype data newtype KeyDownStatus = KeyDownStatus Bool\n-- OR, you could mimic the declaration `data Bool = False | True` directly\ndata KeyDownStatus = Down | Up\n"
},
{
"answer_id": 74595171,
"author": "Oh Fiveight",
"author_id": 5294916,
"author_profile": "https://Stackoverflow.com/users/5294916",
"pm_score": 0,
"selected": false,
"text": "else myLayoutToggle data KeyStatus = Down | Up deriving (Eq, Read, Show)\ninstance ExtensionClass KeyStatus where initialValue = Up\n\nmyLayoutToggle :: KeyStatus -> String -> X ()\nmyLayoutToggle s l = (XS.get :: X KeyStatus)\n >>= \\key ->\n if key == s then return ()\n else XS.put (s)\n >> (sendMessage $ JumpToLayout l)\n >> (spawn $ \"xdotool key F1\")\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5294916/"
] |
74,576,940
|
<p>To set the scene, I have a set of data where two columns of the data have been mixed up. To give a simple example:</p>
<pre class="lang-r prettyprint-override"><code>df1 <- data.frame(Name = c("Bob", "John", "Mark", "Will"), City=c("Apple", "Paris", "Orange", "Berlin"), Fruit=c("London", "Pear", "Madrid", "Orange"))
df2 <- data.frame(Cities = c("Paris", "London", "Berlin", "Madrid", "Moscow", "Warsaw"))
</code></pre>
<p>As a result, we have two small data sets:</p>
<pre class="lang-r prettyprint-override"><code>> df1
Name City Fruit
1 Bob Apple London
2 John Paris Pear
3 Mark Orange Madrid
4 Will Berlin Orange
> df2
Cities
1 Paris
2 London
3 Berlin
4 Madrid
5 Moscow
6 Warsaw
</code></pre>
<p>My aim is to create a new column where the cities are in the correct place using df2. I am a bit new to R so I don't know how this would work.</p>
<p>I don't really know where to even start with this sort of a problem. My full dataset is much larger and it would be good to have an efficient method of unpicking this issue!</p>
|
[
{
"answer_id": 74576971,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "df1[] <- t(apply(df1, 1, function(x) \n {\n i1 <- x %in% df2$Cities\n i2 <- !i1\n x1 <- x[i2]\n c(x1[1], x[i1], x1[2])}))\n > df1\n Name City Fruit\n1 Bob London Apple\n2 John Paris Pear\n3 Mark Madrid Orange\n4 Will Berlin Orange\n"
},
{
"answer_id": 74577012,
"author": "Vida",
"author_id": 9620304,
"author_profile": "https://Stackoverflow.com/users/9620304",
"pm_score": 2,
"selected": true,
"text": "library(dplyr)\ndf1$corrected_City <- case_when(df1$City %in% df2$Cities ~ df1$City,\n df1$Fruit%in% df2$Cities ~ df1$Fruit,\n TRUE ~ \"\")\n > df1\n Name City Fruit corrected_City\n1 Bob Apple London London\n2 John Paris Pear Paris\n3 Mark Orange Madrid Madrid\n4 Will Berlin Orange Berlin\n"
},
{
"answer_id": 74577192,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\nlibrary(tidyr)\n\ndf1 %>% \n mutate(across(1:3, ~case_when(. %in% df2$Cities ~ .), .names = 'new_{col}')) %>%\n unite(New_Col, starts_with('new'), na.rm = TRUE, sep = ' ')\n Name City Fruit New_Col\n1 Bob Apple London London\n2 John Paris Pear Paris\n3 Mark Orange Madrid Madrid\n4 Will Berlin Orange Berlin\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19640936/"
] |
74,576,960
|
<p>I found this in Javascript.info : <a href="https://plnkr.co/edit/Q6Aafx11IW6CnC8k?p=preview&preview" rel="nofollow noreferrer">enter link description here</a>.</p>
<p>Well it's a event delegation demonstration : a 9-cells table, when we click one of cells, the cell (<code>event.target</code>) changes its color into red and the cell we clicked just before will return to its original color.</p>
<p>And I'm wandering how is that possible declaring a <code>let</code> variable <code>selectedTd</code> without assigning a value ? (I made a comment in the js code in order to show you where the code confuses me). Thanks for your help.</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>let table = document.getElementById('bagua-table');
let selectedTd;
table.onclick = function(event) {
let target = event.target;
while (target != this) {
if (target.tagName == 'TD') {
highlight(target);
return;
}
target = target.parentNode;
}
}
function highlight(node) {
if (selectedTd) { // what does the "selectedTd" representes while it doesn't even has a value ?
selectedTd.classList.remove('highlight');
}
selectedTd = node;
selectedTd.classList.add('highlight');
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#bagua-table th {
text-align: center;
font-weight: bold;
}
#bagua-table td {
width: 150px;
white-space: nowrap;
text-align: center;
vertical-align: bottom;
padding-top: 5px;
padding-bottom: 12px;
}
#bagua-table .nw {
background: #999;
}
#bagua-table .n {
background: #03f;
color: #fff;
}
#bagua-table .ne {
background: #ff6;
}
#bagua-table .w {
background: #ff0;
}
#bagua-table .c {
background: #60c;
color: #fff;
}
#bagua-table .e {
background: #09f;
color: #fff;
}
#bagua-table .sw {
background: #963;
color: #fff;
}
#bagua-table .s {
background: #f60;
color: #fff;
}
#bagua-table .se {
background: #0c3;
color: #fff;
}
#bagua-table .highlight {
background: red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <table id="bagua-table">
<tr>
<th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th>
</tr>
<tr>
<td class="nw"><strong>Northwest</strong>
<br>Metal
<br>Silver
<br>Elders
</td>
<td class="n"><strong>North</strong>
<br>Water
<br>Blue
<br>Change
</td>
<td class="ne"><strong>Northeast</strong>
<br>Earth
<br>Yellow
<br>Direction
</td>
</tr>
<tr>
<td class="w"><strong>West</strong>
<br>Metal
<br>Gold
<br>Youth
</td>
<td class="c"><strong>Center</strong>
<br>All
<br>Purple
<br>Harmony
</td>
<td class="e"><strong>East</strong>
<br>Wood
<br>Blue
<br>Future
</td>
</tr>
<tr>
<td class="sw"><strong>Southwest</strong>
<br>Earth
<br>Brown
<br>Tranquility
</td>
<td class="s"><strong>South</strong>
<br>Fire
<br>Orange
<br>Fame
</td>
<td class="se"><strong>Southeast</strong>
<br>Wood
<br>Green
<br>Romance
</td>
</tr>
</table></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74576971,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "df1[] <- t(apply(df1, 1, function(x) \n {\n i1 <- x %in% df2$Cities\n i2 <- !i1\n x1 <- x[i2]\n c(x1[1], x[i1], x1[2])}))\n > df1\n Name City Fruit\n1 Bob London Apple\n2 John Paris Pear\n3 Mark Madrid Orange\n4 Will Berlin Orange\n"
},
{
"answer_id": 74577012,
"author": "Vida",
"author_id": 9620304,
"author_profile": "https://Stackoverflow.com/users/9620304",
"pm_score": 2,
"selected": true,
"text": "library(dplyr)\ndf1$corrected_City <- case_when(df1$City %in% df2$Cities ~ df1$City,\n df1$Fruit%in% df2$Cities ~ df1$Fruit,\n TRUE ~ \"\")\n > df1\n Name City Fruit corrected_City\n1 Bob Apple London London\n2 John Paris Pear Paris\n3 Mark Orange Madrid Madrid\n4 Will Berlin Orange Berlin\n"
},
{
"answer_id": 74577192,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\nlibrary(tidyr)\n\ndf1 %>% \n mutate(across(1:3, ~case_when(. %in% df2$Cities ~ .), .names = 'new_{col}')) %>%\n unite(New_Col, starts_with('new'), na.rm = TRUE, sep = ' ')\n Name City Fruit New_Col\n1 Bob Apple London London\n2 John Paris Pear Paris\n3 Mark Orange Madrid Madrid\n4 Will Berlin Orange Berlin\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12233694/"
] |
74,576,965
|
<pre><code>int count_letters(string text, int length);
int count_words(string text);
int count_sentences(string text);
void final(int letters, int words, int sentences);
int main(void)
{
string text = get_string("Text: \n");
int length = strlen(text);
//printf("%i\n",length);
int letters = count_letters(text, length);
</code></pre>
<p>Here I need variable "length" in all these four functions but all these functions already have a string type parameter.Is it possible to pass different types of parameters in a function?</p>
<p>Basically i want to know if this is correct (line 1 and line 13) and if no then how can i use this length variable in all these functions without having to locally define it in each functtion ?</p>
|
[
{
"answer_id": 74577155,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 3,
"selected": true,
"text": "int count_letters(string text) //better to return size_t\n{\n int result = 0;\n for(int index = 0; text[index] != '\\0'; index++) \n {\n if(isalpha((unsigned char)text[index]))\n {\n result += 1;\n } \n }\n return result;\n}\n"
},
{
"answer_id": 74577169,
"author": "user253751",
"author_id": 106104,
"author_profile": "https://Stackoverflow.com/users/106104",
"pm_score": 1,
"selected": false,
"text": "int count_letters(string text, int length);\n count_letters string text int length printf(\"the magic number is %d\\n\", 42);\n// ^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^\n// function const char * int\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20574604/"
] |
74,576,986
|
<p>How could I sort an array of events by the month they are occuring in?</p>
<p>For instance, I want to sort this <code>events</code> array:</p>
<pre><code>[{ event: 'prom', month: 'MAY' },
{ event: 'graduation', month: 'JUN' },
{ event: 'dance', month: 'JAN' }]
</code></pre>
<p>to become this array:</p>
<pre><code>[{ event: 'dance', month: 'JAN' },
{ event: 'prom', month: 'MAY' },
{ event: 'graduation', month: 'JUN' }]
</code></pre>
<p>An array of MONTHS is also provided:</p>
<pre><code>const MONTHS = [
'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN',
'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'
];
</code></pre>
<p>I'm trying to sort the <code>events</code> array using the sort method, but it is only sorting in alphabetical order. Could anyone help give me guidance to figure out how I can sort by the calendar order of months?</p>
<pre><code>
const MONTHS = [
'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN',
'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'
];
function sortByMonth(events) {
events.sort((a,b) =>
a.month.localeCompare(b.month)
)
}
</code></pre>
|
[
{
"answer_id": 74577155,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 3,
"selected": true,
"text": "int count_letters(string text) //better to return size_t\n{\n int result = 0;\n for(int index = 0; text[index] != '\\0'; index++) \n {\n if(isalpha((unsigned char)text[index]))\n {\n result += 1;\n } \n }\n return result;\n}\n"
},
{
"answer_id": 74577169,
"author": "user253751",
"author_id": 106104,
"author_profile": "https://Stackoverflow.com/users/106104",
"pm_score": 1,
"selected": false,
"text": "int count_letters(string text, int length);\n count_letters string text int length printf(\"the magic number is %d\\n\", 42);\n// ^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^\n// function const char * int\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601836/"
] |
74,577,033
|
<p>For example please find the below data:</p>
<p><img src="https://i.stack.imgur.com/TBTBh.png" alt="enter image description here" /></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>account</th>
<th>balance</th>
</tr>
</thead>
<tbody>
<tr>
<td>9999</td>
<td>110</td>
</tr>
<tr>
<td>9998</td>
<td>111</td>
</tr>
<tr>
<td>9997</td>
<td>112</td>
</tr>
<tr>
<td>9996</td>
<td>113</td>
</tr>
<tr>
<td>9995</td>
<td>114</td>
</tr>
<tr>
<td>9994</td>
<td>115</td>
</tr>
<tr>
<td>9993</td>
<td>116</td>
</tr>
<tr>
<td>9992</td>
<td>117</td>
</tr>
<tr>
<td>9991</td>
<td>118</td>
</tr>
<tr>
<td>9990</td>
<td>119</td>
</tr>
</tbody>
</table>
</div>
<p>The output should be in such a way that there are 5 rows in Table_A and 5 Rows in Table_B and sum of balance column should almost be similar.</p>
<p>Want the output in SAS or PROC SQL.</p>
<p>I tried many ways in proc sql but not able to generate an output</p>
|
[
{
"answer_id": 74577155,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 3,
"selected": true,
"text": "int count_letters(string text) //better to return size_t\n{\n int result = 0;\n for(int index = 0; text[index] != '\\0'; index++) \n {\n if(isalpha((unsigned char)text[index]))\n {\n result += 1;\n } \n }\n return result;\n}\n"
},
{
"answer_id": 74577169,
"author": "user253751",
"author_id": 106104,
"author_profile": "https://Stackoverflow.com/users/106104",
"pm_score": 1,
"selected": false,
"text": "int count_letters(string text, int length);\n count_letters string text int length printf(\"the magic number is %d\\n\", 42);\n// ^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^\n// function const char * int\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13311915/"
] |
74,577,087
|
<p>I have :</p>
<pre><code>const chars = 'abcdefghijklmnopqrstuvwxyz';
</code></pre>
<p>I would like to create an array of strings containing</p>
<pre><code>[aa,ab,ac .. zz ]
</code></pre>
<p>I could do it with loops but wanted to try using map.</p>
<p>I tried:</p>
<pre><code>const baseStrings = [chars].map(x=>chars[x]).map(y=>y+chars[y]);
console.log(baseStrings);
</code></pre>
<p>This gives:</p>
<pre><code>[NaN]
</code></pre>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 74577109,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": true,
"text": "split const chars = 'abcdefghijklmnopqrstuvwxyz';\nconst array = chars.split('')\nconsole.log(array) flatMap const chars = 'abcdefghijklmnopqrstuvwxyz';\nconst array = chars.split('')\n\nconst result = array.flatMap(c1 => array.map(c2 => c1 + c2))\nconsole.log(result)"
},
{
"answer_id": 74577122,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 1,
"selected": false,
"text": "spread-operator Array#flatMap Array#map const chars = 'abcdefghijklmnopqrstuvwxyz';\n\nconst list = [...chars];\nconst baseStrings = list.flatMap(c1 => list.map(c2 => `${c1}${c2}`));\n\nconsole.log(baseStrings);"
},
{
"answer_id": 74577375,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 1,
"selected": false,
"text": "[...string] console.log([...'abcdefghijklmnopqrstuvwxyz']\n .flatMap((i,_,a)=>a.map(j=>i+j)))"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1592380/"
] |
74,577,093
|
<h2>Update 1</h2>
<p>I changed delegate from <code>viewModels</code> to <code>hiltNavGraphViewModels</code> and it's works. Thanks to ianhanniballake's comments. But now is another issue. If app have killed (Logcat -> Terminate App), occurs exception <code>No destination with ID 2131296453 is on the NavController's back stack. The current destination is null</code> (stacktrace below). How can I restore back stack in order to <code>hiltNavGraphViewModels</code> don't fail?</p>
<pre class="lang-kotlin prettyprint-override"><code>@AndroidEntryPoint
class ScriptDetailFragment: Fragment(R.layout.component_detail_script) {
private val viewModel: SharedViewModel by hiltNavGraphViewModels(R.id.scriptFragment)
}
@AndroidEntryPoint
class ScriptFragment : Fragment(R.layout.component_script) {
private val viewModel: SharedViewModel by hiltNavGraphViewModels(R.id.scriptFragment)
fun navigateToDetail(navDirection: NavDirections) {
findNavController().navigate(navDirection)
}
}
@HiltViewModel
class SharedViewModel @Inject constructor(
private val componentWrapper: ComponentWrapper
) : ViewModel() {
}
</code></pre>
<pre><code>dependencies {
implementation 'androidx.core:core-ktx:1.8.0'
implementation 'com.google.dagger:hilt-android:2.38'
implementation("androidx.hilt:hilt-navigation-fragment:1.0.0")
kapt 'com.google.dagger:hilt-compiler:2.38'
kapt 'androidx.hilt:hilt-compiler:1.0.0'
implementation "androidx.activity:activity-ktx:1.5.1"
implementation "androidx.fragment:fragment-ktx:1.5.4"
implementation "androidx.navigation:navigation-fragment-ktx:2.5.3"
implementation "androidx.navigation:navigation-ui-ktx:2.5.3"
}
</code></pre>
<pre><code> Caused by: java.lang.IllegalArgumentException: No destination with ID 2131296453 is on the NavController's back stack. The current destination is null
at androidx.navigation.NavController.getBackStackEntry(NavController.kt:2209)
at *.pages.departure.ScriptFragment$special$$inlined$hiltNavGraphViewModels$1.invoke(HiltNavGraphViewModelLazy.kt:49)
at *.pages.departure.ScriptFragment$special$$inlined$hiltNavGraphViewModels$1.invoke(Unknown Source:0)
at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
at *.pages.departure.ScriptFragment$special$$inlined$hiltNavGraphViewModels$3.invoke(HiltNavGraphViewModelLazy.kt:57)
at *.pages.departure.ScriptFragment$special$$inlined$hiltNavGraphViewModels$3.invoke(Unknown Source:0)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.kt:47)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.kt:35)
at *.pages.departure.ScriptFragment.getViewModel(ScriptFragment.kt:15)
at *.pages.departure.ScriptFragment.onViewCreated(ScriptFragment.kt:20)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3128)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:552)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1433)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2977)
at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:2888)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3129)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:552)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1433)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2977)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2895)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:263)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:351)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:248)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1335)
at android.app.Activity.performStart(Activity.java:7043)
</code></pre>
<p>activity_main.xml</p>
<pre><code> <androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
tools:context=".screens.MainActivity" />
</code></pre>
<p>MainActivity.ki</p>
<pre><code>@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
configureNavHost()
}
override fun onSupportNavigateUp() = navController.navigateUp() || super.onSupportNavigateUp()
private fun configureNavHost() {
val resId = if (dsr.isFirstLaunch.value) R.id.welcomeFragment else R.id.webViewFragment
navController = (supportFragmentManager.findFragmentById(R.id.nav_host) as NavHostFragment).navController
navController.navInflater.inflate(R.navigation.nav_graph).let { graph ->
graph.setStartDestination(resId)
navController.graph = graph
}
}
}
</code></pre>
|
[
{
"answer_id": 74670403,
"author": "diziaq",
"author_id": 2774914,
"author_profile": "https://Stackoverflow.com/users/2774914",
"pm_score": 1,
"selected": false,
"text": "NavController onSaveInstanceState() Fragment Activity NavController Fragment @AndroidEntryPoint\nclass MyFragment : Fragment() {\n\n private val navController by lazy { findNavController() }\n\n override fun onSaveInstanceState(outState: Bundle) {\n super.onSaveInstanceState(outState)\n // Save the state of the NavController and the back stack\n navController.saveState(outState)\n }\n\n override fun onViewStateRestored(savedInstanceState: Bundle?) {\n super.onViewStateRestored(savedInstanceState)\n // Restore the state of the NavController and the back stack\n savedInstanceState?.let { navController.restoreState(it) }\n }\n}\n NavController hiltNavGraphViewModels()"
},
{
"answer_id": 74679380,
"author": "kppro",
"author_id": 10955397,
"author_profile": "https://Stackoverflow.com/users/10955397",
"pm_score": 0,
"selected": false,
"text": "@AndroidEntryPoint\nclass ScriptFragment : Fragment(R.layout.component_script) {\n\n private val viewModel: SharedViewModel by hiltNavGraphViewModels(R.id.scriptFragment)\n\n override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n super.onViewCreated(view, savedInstanceState)\n\n // Pop the current destination off the back stack to restore the back stack\n childFragmentManager.popBackStack()\n }\n\n fun navigateToDetail(navDirection: NavDirections) {\n findNavController().navigate(navDirection)\n }\n}\n @AndroidEntryPoint\nclass ScriptFragment : Fragment(R.layout.component_script) {\n\n private val viewModel: SharedViewModel by hiltNavGraphViewModels(R.id.scriptFragment)\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n\n // Pop the current destination off the back stack to restore the back stack\n childFragmentManager.popBackStackImmediate()\n }\n\n fun navigateToDetail(navDirection: NavDirections) {\n findNavController().navigate(navDirection)\n }\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5894542/"
] |
74,577,108
|
<p>Is there a way to remove all words that are before code=" and after "> in my file so I'm left with clearsky_night or cloudy, or sun etc?</p>
<p>I have tried grep -o -P '(?<=>).*(?=>)' but get an error message sating unknown option to 's'</p>
<p>I also tried grep -o -P '(?<=code=").*(?=" )' but that didn't work either.
This is what's in my file:</p>
<pre><code> <symbol id="Sun" number="1" code="clearsky_night"></symbol>
<symbol id="Sun" number="1" code="clearsky_night"></symbol>
<symbol id="Sun" number="1" code="clearsky_night"></symbol>
<symbol id="Cloud" number="4" code="cloudy"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="Cloud" number="4" code="cloudy"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="Cloud" number="4" code="cloudy"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="Cloud" number="4" code="cloudy"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="Cloud" number="4" code="cloudy"></symbol>
<symbol id="Cloud" number="4" code="cloudy"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="Cloud" number="4" code="cloudy"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="Cloud" number="4" code="cloudy"></symbol>
<symbol id="Cloud" number="4" code="cloudy"></symbol>
<symbol id="Cloud" number="4" code="cloudy"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="LightCloud" number="2" code="fair_night"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="Sun" number="1" code="clearsky_night"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="LightCloud" number="2" code="fair_night"></symbol>
<symbol id="LightCloud" number="2" code="fair_night"></symbol>
<symbol id="LightCloud" number="2" code="fair_night"></symbol>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"></symbol>
<symbol id="LightCloud" number="2" code="fair_night"></symbol>
<symbol id="Cloud" number="4" code="cloudy"></symbol>
<symbol id="Cloud" number="4" code="cloudy"></symbol>
<symbol id="Cloud" number="4" code="cloudy"></symbol>
</code></pre>
|
[
{
"answer_id": 74670403,
"author": "diziaq",
"author_id": 2774914,
"author_profile": "https://Stackoverflow.com/users/2774914",
"pm_score": 1,
"selected": false,
"text": "NavController onSaveInstanceState() Fragment Activity NavController Fragment @AndroidEntryPoint\nclass MyFragment : Fragment() {\n\n private val navController by lazy { findNavController() }\n\n override fun onSaveInstanceState(outState: Bundle) {\n super.onSaveInstanceState(outState)\n // Save the state of the NavController and the back stack\n navController.saveState(outState)\n }\n\n override fun onViewStateRestored(savedInstanceState: Bundle?) {\n super.onViewStateRestored(savedInstanceState)\n // Restore the state of the NavController and the back stack\n savedInstanceState?.let { navController.restoreState(it) }\n }\n}\n NavController hiltNavGraphViewModels()"
},
{
"answer_id": 74679380,
"author": "kppro",
"author_id": 10955397,
"author_profile": "https://Stackoverflow.com/users/10955397",
"pm_score": 0,
"selected": false,
"text": "@AndroidEntryPoint\nclass ScriptFragment : Fragment(R.layout.component_script) {\n\n private val viewModel: SharedViewModel by hiltNavGraphViewModels(R.id.scriptFragment)\n\n override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n super.onViewCreated(view, savedInstanceState)\n\n // Pop the current destination off the back stack to restore the back stack\n childFragmentManager.popBackStack()\n }\n\n fun navigateToDetail(navDirection: NavDirections) {\n findNavController().navigate(navDirection)\n }\n}\n @AndroidEntryPoint\nclass ScriptFragment : Fragment(R.layout.component_script) {\n\n private val viewModel: SharedViewModel by hiltNavGraphViewModels(R.id.scriptFragment)\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n\n // Pop the current destination off the back stack to restore the back stack\n childFragmentManager.popBackStackImmediate()\n }\n\n fun navigateToDetail(navDirection: NavDirections) {\n findNavController().navigate(navDirection)\n }\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400773/"
] |
74,577,147
|
<p>I have the following <a href="https://storybook.js.org/docs/react/essentials/toolbars-and-globals" rel="nofollow noreferrer">globalTypes</a> to enable a toolbar in storybook that lets me select the theme:</p>
<pre><code>export const globalTypes = {
theme: {
name: 'Theme',
description: 'Global theme',
defaultValue: MyTheme.Light,
toolbar: {
icon: 'mirror',
items: [MyTheme.Light, MyTheme.Dark],
showName: true,
dynamicTitle: true,
},
},
};
</code></pre>
<p>This works fine and I can switch the theme through the toolbar:</p>
<p><a href="https://i.stack.imgur.com/36CjA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/36CjA.png" alt="theme switcher" /></a></p>
<p>Now I want to set the <a href="https://storybook.js.org/docs/react/essentials/backgrounds" rel="nofollow noreferrer">background color of the story</a> (background-color of the body) according to the theme, but I cannot figure out how to do that for all stories globally.</p>
<p>I know how to configure different background colors, but I have no idea how to switch them based on the theme set in <code>context.globals</code>. How does this work?</p>
|
[
{
"answer_id": 74670403,
"author": "diziaq",
"author_id": 2774914,
"author_profile": "https://Stackoverflow.com/users/2774914",
"pm_score": 1,
"selected": false,
"text": "NavController onSaveInstanceState() Fragment Activity NavController Fragment @AndroidEntryPoint\nclass MyFragment : Fragment() {\n\n private val navController by lazy { findNavController() }\n\n override fun onSaveInstanceState(outState: Bundle) {\n super.onSaveInstanceState(outState)\n // Save the state of the NavController and the back stack\n navController.saveState(outState)\n }\n\n override fun onViewStateRestored(savedInstanceState: Bundle?) {\n super.onViewStateRestored(savedInstanceState)\n // Restore the state of the NavController and the back stack\n savedInstanceState?.let { navController.restoreState(it) }\n }\n}\n NavController hiltNavGraphViewModels()"
},
{
"answer_id": 74679380,
"author": "kppro",
"author_id": 10955397,
"author_profile": "https://Stackoverflow.com/users/10955397",
"pm_score": 0,
"selected": false,
"text": "@AndroidEntryPoint\nclass ScriptFragment : Fragment(R.layout.component_script) {\n\n private val viewModel: SharedViewModel by hiltNavGraphViewModels(R.id.scriptFragment)\n\n override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n super.onViewCreated(view, savedInstanceState)\n\n // Pop the current destination off the back stack to restore the back stack\n childFragmentManager.popBackStack()\n }\n\n fun navigateToDetail(navDirection: NavDirections) {\n findNavController().navigate(navDirection)\n }\n}\n @AndroidEntryPoint\nclass ScriptFragment : Fragment(R.layout.component_script) {\n\n private val viewModel: SharedViewModel by hiltNavGraphViewModels(R.id.scriptFragment)\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n\n // Pop the current destination off the back stack to restore the back stack\n childFragmentManager.popBackStackImmediate()\n }\n\n fun navigateToDetail(navDirection: NavDirections) {\n findNavController().navigate(navDirection)\n }\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/554340/"
] |
74,577,162
|
<p>I made some wrapping aroung routing</p>
<pre><code>func (p Page) MainInitHandlers() {
http.HandleFunc("/", p.mainHandler)
http.HandleFunc("/save", p.saveHandler)
}
</code></pre>
<p>If something wrong will happen inside my hadlers (mainHandler, saveHandler), can I get it somehow? I want to return that error further and analyze like</p>
<pre><code>err := MainInitHandlers
</code></pre>
<p>It it possible?</p>
|
[
{
"answer_id": 74579060,
"author": "Steve D",
"author_id": 931760,
"author_profile": "https://Stackoverflow.com/users/931760",
"pm_score": 1,
"selected": false,
"text": "type withError func(ctx context.Context, r *http.Request, w http.ResponseWriter) error\n\nfunc wrap(f withError) http.Handler {\n return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n processErr(f(r.Context(), r, w))\n })\n}\n\nhttp.Handle(\"\", wrap(...))\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5654843/"
] |
74,577,254
|
<p>I am trying to import and pass an image as a prop to my Skill component from my Skills.tsx file. The image path is the following:</p>
<p>public/images/skill-logos/html.png.</p>
<p>Here is what my Skills.tsx file looks like:</p>
<pre><code>import React from 'react';
import Skill from './Skill';
import HtmlLogo from '../public/image/skill-logos/html.png';
function Skills({}: Props) {
return (
<div>
<h3>Skills</h3>
<h3>Hover over a skill for current proficiency</h3>
<div>
<Skill
imageSource={HtmlLogo}
proficiency="80"
/>
</div>
</div>
);
};
export default Skills;
</code></pre>
<p>And this is what my Skill.tsx file looks like:</p>
<pre><code>import React from 'react';
type Props = {
imageSource: string;
proficiency: string;
};
function Skill({ imageSource, proficiency }: Props) {
return (
<div>
<img
src={imageSource}
alt=''
/>
<div>
<p>{proficiency}%</p>
</div>
</div>
);
};
export default Skill;
</code></pre>
<p>So far, it does not render the image, but it does render the proficiency.</p>
<p>So far i've tried using require('image_path') to import the image, but it didn't work. If anyone knows which method works, I would highly appreaciate it.</p>
|
[
{
"answer_id": 74579060,
"author": "Steve D",
"author_id": 931760,
"author_profile": "https://Stackoverflow.com/users/931760",
"pm_score": 1,
"selected": false,
"text": "type withError func(ctx context.Context, r *http.Request, w http.ResponseWriter) error\n\nfunc wrap(f withError) http.Handler {\n return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n processErr(f(r.Context(), r, w))\n })\n}\n\nhttp.Handle(\"\", wrap(...))\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20602121/"
] |
74,577,264
|
<p>Need help to make htaccess.
I use 2 domains: abc.domain1.com and domain2.com.
the htaccess will be in domain2.com.
i want to use it for vbulletin shorturl.</p>
<p>The idea are;</p>
<ol>
<li><p>redirect <code>domain2.com/[numbers]</code> (example= <code>domain2.com/678</code>)
to <code>abc.domain1.com/threads/[same numbers]</code> (example = <code>abc.domain1.com/threads/678</code>)</p>
</li>
<li><p>redirect <code>domain2.com/a[numbers]</code> (example= <code>domain2.com/a1234</code>)
to <code>abc.domain1.com/forums/[same numbers]</code> (example = <code>abc.domain1.com/forums/1234</code>)</p>
</li>
</ol>
<p>i tried for the case 1, is works with:</p>
<pre><code>RedirectMatch ^/(.*) https://abc.domain1.com/threads/$1
</code></pre>
<p>but it doesn't work for case 2. i tried</p>
<pre><code>RedirectMatch ^/f(.*) https://abc.domain1.com/forums/$1
</code></pre>
<p>but it gives me /threads/f[numbers]</p>
|
[
{
"answer_id": 74577499,
"author": "amphetamachine",
"author_id": 237955,
"author_profile": "https://Stackoverflow.com/users/237955",
"pm_score": 3,
"selected": true,
"text": "/f1234 ^/(.*) https://abc.domain1.com/threads/f1234 RedirectMatch RedirectMatch ^/f(.*) https://abc.domain1.com/forums/$1\nRedirectMatch ^/(.*) https://abc.domain1.com/threads/$1\n"
},
{
"answer_id": 74586871,
"author": "MrWhite",
"author_id": 369434,
"author_profile": "https://Stackoverflow.com/users/369434",
"pm_score": 1,
"selected": false,
"text": "RedirectMatch ^/(\\d*)$ https://abc.domain1.com/threads/$1\nRedirectMatch ^/f(\\d*)$ https://abc.domain1.com/forums/$1\n \\d $ / /f"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10656184/"
] |
74,577,287
|
<p>I'm trying to consume an endpoint from ABAP, by instantiate a <code>if_http_client</code> from <code>cl_http_client=>create_by_url</code>. That process works fine when I don't need to use a signed certificate. Usually I just include the certificate using the <code>STRUST</code> transaction.</p>
<p>But for this specific case I have two certificate files: <code>.crt</code> and the <code>.key</code>. I'm able fetch the endpoint from <code>Postman</code>, because I can insert those files in <code>Settings -> Certificates</code>:</p>
<p><a href="https://i.stack.imgur.com/GFh6m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GFh6m.png" alt="enter image description here" /></a></p>
<p>So, how can I have it working from ABAP? How to insert those files in my http request? Should I pass them from ABAP code, or config it in STRUST or some other transation?</p>
|
[
{
"answer_id": 74579758,
"author": "phil soady",
"author_id": 1347784,
"author_profile": "https://Stackoverflow.com/users/1347784",
"pm_score": 2,
"selected": false,
"text": " cl_http_client=>create_by_url(\n EXPORTING\n url = 'url' \n ssl_id = 'CL_ID' \"Ident created in step above \n IMPORTING\n client = lo_client \n ).\n CALL METHOD cl_http_client=>create_by_destination\n EXPORTING\n destination = lv_destination \"the new sm59 destination \n IMPORTING\n client = lo_http_client.\n DATA: lo_client TYPE REF TO if_http_client.\n\n cl_http_client=>create_by_url(\n EXPORTING\n url = 'url' \n ssl_id = 'ANONYM' \"Start SSL handshake as Anonymous SSL\n IMPORTING\n client = lo_client \n ).\n lo_client->request->set_header_field(\n EXPORTING\n name = 'Client-Cert' \"Check HTTP header name with called Service docu\n value = '<cert> in string format'\n ).\n \n \"lo_client->send( .. )\n \"lo_client->receive( .. )\n"
},
{
"answer_id": 74657594,
"author": "mkysoft",
"author_id": 2847159,
"author_profile": "https://Stackoverflow.com/users/2847159",
"pm_score": 0,
"selected": false,
"text": "sapgenpse import_p12 -p c:\\client.pse c:\\client.pfx\n REPORT ZMKY_SSL_CLIENT.\n\n DATA: lo_client TYPE REF TO if_http_client,\n lv_code TYPE i,\n lv_REASON type string.\n\n cl_http_client=>create_by_url(\n EXPORTING\n url = 'https://mysslclienthost.com'\n ssl_id = 'MYSSLC' \"Your SSL Client identity\n IMPORTING\n client = lo_client\n ).\n\n lo_client->SEND( ).\n\n lo_client->RECEIVE( ).\n\n lo_client->RESPONSE->GET_STATUS( IMPORTING CODE = lv_code\n REASON = lv_reason ).\n\n WRITE: lv_code, lv_reason.\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257304/"
] |
74,577,313
|
<p>I am still new to React Native and I would like to let users use a google account on my React Native app. My question is if signInWithRedirect function is available in native apps. I first wrote signInWithPopup, but I got an error and found out I couldn't use it in native apps. Also, I used a redirect function, but it didn't work well.</p>
<p>I deleted all my code and used createUserWithEmailAndPassword, but honestly, I still want users to log in with their google accounts.</p>
|
[
{
"answer_id": 74577455,
"author": "criszz77",
"author_id": 14056591,
"author_profile": "https://Stackoverflow.com/users/14056591",
"pm_score": 2,
"selected": true,
"text": "Firebase Authentication Firebase Authentication google-signin"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16295143/"
] |
74,577,324
|
<p>I have a DataFrame with a column that contains a dictionary as follows:</p>
<pre><code>df:
date dictionary
0 2021-01-01 00:00:00 + 00:00 'Total':{'USD':100, 'size':20}, 'country':{'USA': {'income': 20000}, 'fees': {'total': 55}}
1 2021-01-01 00:00:00 + 00:00 'Total':{'EUR':200, 'size':40}, 'country':{'France': {'income': 10000}, 'fees': {'total': 30}}
1 2021-01-02 00:00:00 + 00:00 'Total':{'GBP':100, 'size':30}, 'country':{'UK': {'income': 23000}, 'fees': {'total': 24}}
</code></pre>
<p>What I want is to set <code>USA</code> as a column name and take the value of <code>total</code> from the <code>fees</code> and set that as the value, to get the following:</p>
<pre><code>df_final:
date USA France UK
0 2021-01-01 00:00:00 + 00:00 55 30 NaN
1 2021-01-02 00:00:00 + 00:00 NaN NaN 24
</code></pre>
<p>My DataFrame has hundreds of columns. I have tried the following:</p>
<pre><code>df_list = []
for idx, row in df.iterrows():
for dct in row['dictionary']:
dct['date'] = row['date']
df_list.append(dct)
</code></pre>
<p>But I get the following error: <code>TypeError: 'str' object does not support item assignment</code>. This happened specifically at <code>dct['date']</code>.</p>
<p>How can this be done?</p>
<p>EDIT: I added a few more rows to my DataFrame to better represent my problem.</p>
|
[
{
"answer_id": 74577391,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 0,
"selected": false,
"text": "aux = pd.json_normalize(df.dictionary, sep='_')\n(aux.filter(like='income').loc[0]\n .index.str.extract(r'.*_(.*)_.*').join(aux['country_fees_total']).join(df)\n .pivot(index='date', columns=0, values='country_fees_total').reset_index()\n .rename_axis(None, axis=1))\n date France UK USA\n0 2021-01-01 00:00:00 + 00:00 30.0 NaN 55.0\n1 2021-01-02 00:00:00 + 00:00 NaN 24.0 NaN\n"
},
{
"answer_id": 74583670,
"author": "DataFace",
"author_id": 10761390,
"author_profile": "https://Stackoverflow.com/users/10761390",
"pm_score": 2,
"selected": true,
"text": "df = pd.DataFrame({\n 'date': [\n '2021-01-01 00:00:00', \n '2021-01-01 00:00:00',\n '2021-01-02 00:00:00', \n ],\n 'dictionary': [ \n '{\"Total\":{\"USD\":100, \"size\":20}, \"country\":{\"USA\": {\"income\": 20000}, \"fees\": {\"total\": 55}}}',\n '{\"Total\":{\"EUR\":200, \"size\":40}, \"country\":{\"France\": {\"income\": 10000}, \"fees\": {\"total\": 30}}}',\n '{\"Total\":{\"GBP\":100, \"size\":30}, \"country\":{\"UK\": {\"income\": 23000}, \"fees\": {\"total\": 24}}}',\n ]\n})\n\ndf.date = pd.to_datetime(df.date)\ndf\n import json\n\nfor idx, row in df.iterrows():\n dict = json.loads(row.dictionary)\n dict_keys = list(dict[\"country\"].keys())\n df.loc[idx, dict_keys[0]] = dict[\"country\"][\"fees\"][\"total\"]\n\ndf_final = df.groupby(df.date.dt.date) \\\n .agg('first') \\\n .drop(columns=['date', 'dictionary']) \\\n .reset_index()\n \ndf_final\n df = pd.DataFrame({\n 'date': [\n '2021-01-01 00:00:00', \n '2021-01-01 00:00:00',\n '2021-01-02 00:00:00', \n ],\n 'dictionary': [ \n {\"Total\":{\"USD\":100, \"size\":20}, \"country\":{\"USA\": {\"income\": 20000}, \"fees\": {\"total\": 55}}},\n {\"Total\":{\"EUR\":200, \"size\":40}, \"country\":{\"France\": {\"income\": 10000}, \"fees\": {\"total\": 30}}},\n {\"Total\":{\"GBP\":100, \"size\":30}, \"country\":{\"UK\": {\"income\": 23000}, \"fees\": {\"total\": 24}}},\n ]\n})\n\ndf.date = pd.to_datetime(df.date)\ndf\n import json\n\nfor idx, row in df.iterrows():\n dict = row.dictionary\n dict_keys = list(dict[\"country\"].keys())\n df.loc[idx, dict_keys[0]] = dict[\"country\"][\"fees\"][\"total\"]\n # df.loc[index, row]\n\ndf_final = df.groupby(df.date.dt.date) \\\n .agg('first') \\\n .drop(columns=['date', 'dictionary']) \\\n .reset_index()\n\ndf_final\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12244355/"
] |
74,577,363
|
<p>We use a bi-monthly payroll where employees get paid on the 15th and last days of the month.</p>
<p>If those days fall on a Saturday, Sunday or holiday, then we get paid on the last day before then that isn't a Saturday, Sunday or holiday.</p>
<p>For example, take this week, April 15th is a Friday but its defined as a holiday so people should be paid on Thursday April 14.</p>
<p>I managed to get a partial query working where I can exclude weekends and holidays but I can use some help figuring out what DATE people should be paid on. My output should only include pay days. I would like to produce a years output Jan-dec for the current year.</p>
<p>I was thinking perhaps last_day() for the last pay day of the month once holidays and weekends were excluded?</p>
<pre><code>
CREATE OR REPLACE FUNCTION generate_dates(i_from_date IN DATE, i_end_date IN DATE, i_min_delta IN NUMBER, i_max_delta IN NUMBER, i_num_rows IN NUMBER)
RETURN VARCHAR2
SQL_MACRO
IS
BEGIN
RETURN q'{
SELECT start_date, end_date
FROM (
SELECT pivot_date AS start_date, pivot_date + NUMTODSINTERVAL( i_min_delta + (i_max_delta-i_min_delta) * DBMS_RANDOM.VALUE(), 'hour') AS end_date
FROM (
SELECT pivot_date + DBMS_RANDOM.VALUE() AS pivot_date
FROM (
SELECT rownum AS rn, pivot_date AS pivot_date FROM (
SELECT TRUNC(i_from_date)+level-1 AS pivot_date FROM DUAL
CONNECT BY TRUNC(i_from_date)+level-1<=TRUNC(i_end_date)
)
)
CONNECT BY LEVEL <= i_num_rows AND PRIOR rn = rn AND PRIOR sys_guid() IS NOT NULL
)
)
}' ;
END;
/
create table holidays(
holiday_date DATE not null,
holiday_name VARCHAR2(20),
constraint holidays_pk primary key (holiday_date),
constraint is_midnight check ( holiday_date = trunc ( holiday_date ) )
);
INSERT into holidays (HOLIDAY_DATE,HOLIDAY_NAME)
WITH dts as (
select to_date('15-APR-2022 00:00:00','DD-MON-YYYY HH24:MI:SS'), 'Passover 2022' from dual union all
select to_date('31-DEC-2022 00:00:00','DD-MON-YYYY HH24:MI:SS'), 'New Year Eve 2022' from dual
)
SELECT * from dts;
SELECT
c.dt,
to_char(c.dt, 'DY') as dow
FROM generate_dates(
TIMESTAMP '2022-01-01 00:00:00',
TIMESTAMP '2022-04-30 00:00:00',
1, 'DAY') c
where
to_char(c.dt, 'DY') NOT IN ('SAT', 'SUN')
AND NOT EXISTS (
SELECT 1
FROM holidays h
WHERE c.dt = h.holiday_date
);
</code></pre>
|
[
{
"answer_id": 74577861,
"author": "EdmCoff",
"author_id": 5504922,
"author_profile": "https://Stackoverflow.com/users/5504922",
"pm_score": 0,
"selected": false,
"text": "WITH noholidays AS\n(\nSELECT dt\nFROM \n generate_dates(\n TIMESTAMP '2022-01-01 00:00:00',\n TIMESTAMP '2022-04-30 00:00:00',\n 1, 'DAY') c\nWHERE to_char(dt, 'DY') NOT IN ('SAT', 'SUN')\n AND dt NOT IN (SELECT holiday_date FROM holidays)\n)\n union SELECT max(dt) payday\n FROM noholidays\n GROUP BY to_char(dt, 'YYYY-MM')\nUNION ALL\n SELECT max(dt)\n FROM noholidays\n WHERE to_number(to_char(dt, 'DD')) <= 15\n GROUP BY to_char(dt, 'YYYY-MM')\nORDER BY payday\n generate_dates generate_dates WITH \nnoholidays AS (\n SELECT dt\n FROM generate_dates(\n TIMESTAMP '2022-01-01 00:00:00',\n TIMESTAMP '2022-04-30 00:00:00',\n 1, 'DAY')\n WHERE to_char(dt, 'DY') NOT IN ('SAT', 'SUN')\n AND dt NOT IN (SELECT holiday_date FROM holidays)\n)\nSELECT max(dt) payday\nFROM noholidays\nGROUP BY to_char(dt, 'YYYY-MM')\nUNION ALL\nSELECT max(dt)\nFROM noholidays\nWHERE to_number(to_char(dt, 'DD')) <= 15\nGROUP BY to_char(dt, 'YYYY-MM')\nORDER BY payday\n"
},
{
"answer_id": 74578040,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 3,
"selected": true,
"text": "WITH pay_dates (dt) AS (\n SELECT ADD_MONTHS(TRUNC(SYSDATE, 'YY'), LEVEL) - INTERVAL '1' DAY\n FROM DUAL\n CONNECT BY LEVEL <= 12\nUNION ALL\n SELECT ADD_MONTHS(TRUNC(SYSDATE, 'YY'), LEVEL - 1) + INTERVAL '14' DAY\n FROM DUAL\n CONNECT BY LEVEL <= 12\n),\nskip_weekends (dt) AS (\n SELECT CASE dt - TRUNC(dt, 'IW')\n WHEN 6 THEN dt - 2 -- Sunday\n WHEN 5 THEN dt - 1 -- Saturday\n ELSE dt -- Weekday\n END\n FROM pay_dates\n),\nskip_holidays (dt, holiday_date) AS (\n SELECT w.dt, h.holiday_date\n FROM skip_weekends w\n LEFT OUTER JOIN holidays h\n ON (w.dt = h.holiday_date)\nUNION ALL\n SELECT CASE s.dt - TRUNC(s.dt, 'IW')\n WHEN 0\n THEN s.dt - 3 -- Monday\n ELSE s.dt - 1 -- Other weekday\n END,\n h.holiday_date\n FROM skip_holidays s\n LEFT OUTER JOIN holidays h\n ON ( CASE s.dt - TRUNC(s.dt, 'IW')\n WHEN 0\n THEN s.dt - 3\n ELSE s.dt - 1\n END = h.holiday_date )\n WHERE s.holiday_date IS NOT NULL\n)\nSELECT dt\nFROM skip_holidays\nWHERE holiday_date IS NULL\nORDER BY dt;\n CREATE TABLE holidays (holiday_date) AS\nSELECT TRUNC(SYSDATE, 'YY') + INTERVAL '12' DAY FROM DUAL UNION ALL\nSELECT TRUNC(SYSDATE, 'YY') + INTERVAL '13' DAY FROM DUAL UNION ALL\nSELECT TRUNC(SYSDATE, 'YY') + INTERVAL '14' DAY FROM DUAL UNION ALL\nSELECT TRUNC(SYSDATE, 'YY') + INTERVAL '45' DAY FROM DUAL;\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16771377/"
] |
74,577,374
|
<p>I'm trying to get values in column z that contains null values or integers:</p>
<pre><code>df = pd.DataFrame({'X': [1, 2, 3, 4],
'Y': [2, 10, 13, 18],
'Z': [3, None, 5, None]})
a = df[(df.X == 1) & (df.Y == 2)].Z.item()
print(a)
#output: 3
b = df[(df.X == 7) & (df.Y == 18)].Z.item()
print(b)
#output: error
</code></pre>
<p>It throws a value error: can only convert an array of size 1 to a Python scalar. Because the data frame resulting from filtering the X and Y columns is empty. I want to assign variable b to <code>None</code> if the data frame is empty.</p>
<p>I tried the following, and it works:</p>
<pre><code>#checking the length of the dataframe
b = df[(df.X == 1) & (df.Y == 2)].Z.item() if (len(df[(df.X == 7) & (df.Y == 18)]) == 1) else None
print(b)
# output: None
</code></pre>
<p>Is there a better way to do it?</p>
|
[
{
"answer_id": 74577421,
"author": "Psidom",
"author_id": 4983450,
"author_profile": "https://Stackoverflow.com/users/4983450",
"pm_score": 1,
"selected": false,
"text": "next(..., None) b = next(iter(df[(df.X == 7) & (df.Y == 18)].Z), None)\nprint(b)\n# None\n"
},
{
"answer_id": 74577427,
"author": "Grzegorz Skibinski",
"author_id": 11610186,
"author_profile": "https://Stackoverflow.com/users/11610186",
"pm_score": 0,
"selected": false,
"text": ".item() pd.Series >>> b = df.loc[(df.X == 7) & (df.Y == 18), \"Z\"].values\n>>> if len(b) == 0: b=None\n...\n .item()"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18086775/"
] |
74,577,392
|
<p>I was trying to implement a RecyclerView, it shows no errors while debugging but it crushes when ckick on the textView to intent to dayone.xml activity (RecyclerView layout).</p>
<p>I get this in logcat:</p>
<pre><code> Process: com.example.mozillaevent, PID: 15060
java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.TextView
at com.example.mozillaevent.Adapter$ViewHolder.<init>(Adapter.kt:37)
at com.example.mozillaevent.Adapter.onCreateViewHolder(Adapter.kt:16)
at com.example.mozillaevent.Adapter.onCreateViewHolder(Adapter.kt:11)
at androidx.recyclerview.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:7078)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6235)
at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
at android.view.View.layout(View.java:22496)
at android.view.ViewGroup.layout(ViewGroup.java:6528)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:334)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at android.view.View.layout(View.java:22496)
at android.view.ViewGroup.layout(ViewGroup.java:6528)
at androidx.appcompat.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:536)
at android.view.View.layout(View.java:22496)
at android.view.ViewGroup.layout(ViewGroup.java:6528)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:334)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at android.view.View.layout(View.java:22496)
at android.view.ViewGroup.layout(ViewGroup.java:6528)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1857)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1701)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1610)
at android.view.View.layout(View.java:22496)
at android.view.ViewGroup.layout(ViewGroup.java:6528)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:334)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:1146)
at android.view.View.layout(View.java:22496)
at android.view.ViewGroup.layout(ViewGroup.java:6528)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3743)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3207)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:2166)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8887)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1280)
at android.view.Choreographer.doCallbacks(Choreographer.java:1019)
at android.view.Choreographer.doFrame(Choreographer.java:911)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1248)
at android.os.Handler.handleCallback(Handler.java:900)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:219)
at android.app.ActivityThread.main(ActivityThread.java:8668)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1109)
</code></pre>
<p>these are the following classes:</p>
<ul>
<li>class Adapter</li>
<li>data class Items</li>
<li>MainActvity + ScreenOne class</li>
</ul>
<pre><code>class Adapter(val items: List<Items>) : RecyclerView.Adapter<Adapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val item = LayoutInflater.from(parent.context).inflate(R.layout.day1, parent, false)
return ViewHolder(item)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val items = items[position]
holder.bind(items)
}
override fun getItemCount(): Int {
return (items.size)
}
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var image: ImageView
var cardName: TextView
var day: TextView
var description: TextView
init {
image = view.findViewById<ImageView>(R.id.imageBox)
description = view.findViewById<TextView>(R.id.descriptionBox)
day = view.findViewById(R.id.tvDay)
cardName = view.findViewById(R.id.tvName)
}
fun bind(element: Items) {
image.setImageResource(element.image)
description.text = element.description
cardName.text = element.cardName
day.text = element.day
}
}
}
</code></pre>
<p>//data class</p>
<pre><code>data class Items (
val image: Int,
val cardName: String,
val day: String,
val description: String
)
</code></pre>
<pre><code>class ScreenOne : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.dayone)
val recyclerview =findViewById<RecyclerView>(R.id.recyclerView)
val elements = listOf(
Items(R.drawable.img, "Android workshop", "tuesday", "Make your first app"
),
Items(R.drawable.img, "Android workshop", "tuesday", "Make your first app"
),
Items(R.drawable.img, "Android workshop", "tuesday", "Make your first app"
),
Items(R.drawable.img, "Android workshop", "tuesday", "Make your first app"
),
Items(R.drawable.img, "Android workshop", "tuesday", "Make your first app"
),
)
recyclerview.apply {
layoutManager = LinearLayoutManager(this@ScreenOne)
}
recyclerview.adapter= Adapter(elements)
}
}
</code></pre>
<pre><code>class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val intent = Intent(this, ScreenOne::class.java)
val btn = findViewById<TextView>(R.id.tvDayOne)
btn.setOnClickListener {
startActivity(intent)
}
}
}
</code></pre>
<p>//activity.main</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/day1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:gravity="center"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.cardview.widget.CardView
android:id="@+id/cardOne"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_weight="1"
android:backgroundTint="@color/lightGray"
android:elevation="30dp"
android:layout_margin="20dp"
app:cardCornerRadius="15dp"
app:cardElevation="15dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvDayOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="DAY 1"
android:textAlignment="center"
android:textSize="100sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_weight="1"
android:backgroundTint="@color/lightGray"
android:layout_margin="20dp"
app:cardCornerRadius="15dp"
app:cardElevation="15dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="DAY 2"
android:textAlignment="center"
android:textSize="100sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_weight="1"
android:layout_margin="20dp"
android:backgroundTint="@color/Orange"
app:cardCornerRadius="15dp"
app:cardElevation="15dp"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="DAY 3"
android:textAlignment="center"
android:textSize="100sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_weight="1"
android:layout_margin="20dp"
android:backgroundTint="@color/lightGray"
app:cardCornerRadius="15dp"
app:cardElevation="15dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="DAY 4"
android:textAlignment="center"
android:textSize="100sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p>//day1.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_margin="20dp"
android:layout_marginBottom="400dp"
app:cardCornerRadius="15dp"
app:cardElevation="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteX="9dp"
tools:layout_editor_absoluteY="239dp">
<androidx.cardview.widget.CardView
android:id="@+id/descriptionBox"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvDes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/dateLayout"
android:layout_alignParentStart="true"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
tools:text="Mozilla description "
tools:textColor="@color/black"
tools:textSize="15dp">
</TextView>
<LinearLayout
android:id="@+id/dateLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tvName"
android:layout_alignStart="@+id/tvName"
android:layout_alignParentLeft="true"
android:orientation="horizontal">
<TextView
android:id="@+id/tvDay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
tools:text="Thursday">
</TextView>
</LinearLayout>
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/descriptionBox"
android:layout_marginLeft="10dp"
tools:ignore="NotSibling"
android:text="Workshop Name"
android:textColor="@color/black"
android:textSize="25dp">
</TextView>
</RelativeLayout>
</androidx.cardview.widget.CardView>
<ImageView
android:id="@+id/imageBox"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_above="@+id/descriptionBox"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:scaleType="centerCrop"
app:srcCompat="@drawable/img">
</ImageView>
</RelativeLayout>
</androidx.cardview.widget.CardView>
</code></pre>
<p>//dayone.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</code></pre>
|
[
{
"answer_id": 74577421,
"author": "Psidom",
"author_id": 4983450,
"author_profile": "https://Stackoverflow.com/users/4983450",
"pm_score": 1,
"selected": false,
"text": "next(..., None) b = next(iter(df[(df.X == 7) & (df.Y == 18)].Z), None)\nprint(b)\n# None\n"
},
{
"answer_id": 74577427,
"author": "Grzegorz Skibinski",
"author_id": 11610186,
"author_profile": "https://Stackoverflow.com/users/11610186",
"pm_score": 0,
"selected": false,
"text": ".item() pd.Series >>> b = df.loc[(df.X == 7) & (df.Y == 18), \"Z\"].values\n>>> if len(b) == 0: b=None\n...\n .item()"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17545414/"
] |
74,577,408
|
<p>I have a dataframe with OHLC data. I need to get the close price into the pandas series, using the timestamp column as the index.</p>
<p>I am reading from a sqlite db into my df:</p>
<pre><code>conn = sql.connect('allStockData.db')
price = pd.read_sql_query("SELECT * from ohlc_minutes", conn)
price['timestamp'] = pd.to_datetime(price['timestamp'])
print(price)
</code></pre>
<p>Which returns:</p>
<pre><code> timestamp open high low close volume trade_count vwap symbol volume_10_day
0 2022-09-16 08:00:00+00:00 3.19 3.570 3.19 3.350 66475 458 3.404240 AAOI NaN
1 2022-09-16 08:05:00+00:00 3.35 3.440 3.33 3.430 28925 298 3.381131 AAOI NaN
2 2022-09-16 08:10:00+00:00 3.44 3.520 3.35 3.400 62901 643 3.445096 AAOI NaN
3 2022-09-16 08:15:00+00:00 3.37 3.390 3.31 3.360 17943 184 3.339721 AAOI NaN
4 2022-09-16 08:20:00+00:00 3.36 3.410 3.34 3.400 29123 204 3.383370 AAOI NaN
... ... ... ... ... ... ... ... ... ... ...
8759 2022-09-08 23:35:00+00:00 1.35 1.360 1.35 1.355 3835 10 1.350613 RUBY 515994.5
8760 2022-09-08 23:40:00+00:00 1.36 1.360 1.35 1.350 2780 7 1.353687 RUBY 515994.5
8761 2022-09-08 23:45:00+00:00 1.35 1.355 1.35 1.355 7080 11 1.350424 RUBY 515994.5
8762 2022-09-08 23:50:00+00:00 1.35 1.360 1.33 1.360 11664 30 1.351104 RUBY 515994.5
8763 2022-09-08 23:55:00+00:00 1.36 1.360 1.33 1.340 21394 32 1.348223 RUBY 515994.5
[8764 rows x 10 columns]
</code></pre>
<p>When I try to get the close into a series with the timestamp:</p>
<pre><code>price = pd.Series(price['close'], index=price['timestamp'])
</code></pre>
<p>It returns a bunch of NaNs:</p>
<pre><code>2022-09-16 08:00:00+00:00 NaN
2022-09-16 08:05:00+00:00 NaN
2022-09-16 08:10:00+00:00 NaN
2022-09-16 08:15:00+00:00 NaN
2022-09-16 08:20:00+00:00 NaN
..
2022-09-08 23:35:00+00:00 NaN
2022-09-08 23:40:00+00:00 NaN
2022-09-08 23:45:00+00:00 NaN
2022-09-08 23:50:00+00:00 NaN
2022-09-08 23:55:00+00:00 NaN
Name: close, Length: 8764, dtype: float64
</code></pre>
<p>If I remove the index:</p>
<pre><code>price = pd.Series(price['close'])
</code></pre>
<p>The close is returned normally:</p>
<pre><code>0 3.350
1 3.430
2 3.400
3 3.360
4 3.400
...
8759 1.355
8760 1.350
8761 1.355
8762 1.360
8763 1.340
Name: close, Length: 8764, dtype: float64
</code></pre>
<p>How can I return the close column as a pandas series, using my timestamp column as the index?</p>
|
[
{
"answer_id": 74577421,
"author": "Psidom",
"author_id": 4983450,
"author_profile": "https://Stackoverflow.com/users/4983450",
"pm_score": 1,
"selected": false,
"text": "next(..., None) b = next(iter(df[(df.X == 7) & (df.Y == 18)].Z), None)\nprint(b)\n# None\n"
},
{
"answer_id": 74577427,
"author": "Grzegorz Skibinski",
"author_id": 11610186,
"author_profile": "https://Stackoverflow.com/users/11610186",
"pm_score": 0,
"selected": false,
"text": ".item() pd.Series >>> b = df.loc[(df.X == 7) & (df.Y == 18), \"Z\"].values\n>>> if len(b) == 0: b=None\n...\n .item()"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7317408/"
] |
74,577,433
|
<p>I'm a beginner and I don't understand why it doesn't work. I have code that allows you to move a circle on the screen. I also need to make a popup appear when clicking on a circle.Also, I want a popup to appear in the middle of the screen when the circle is clicked</p>
<p>I have code that allows you to move a circle. It chooses a random point to move to. Also, I want a popup to appear in the middle of the screen when the circle is clicked</p>
<p>HTML:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>Circle</title>
</head>
<body>
<header></header>
<main>
<label name="popup" id="popup" class="popup"></label>
<div class="button">
<input type="checkbox" name="popup" id="popup" class="popup__check">
</div>
</main>
<footer></footer>
<script src="js/script.js"></script>
</body>
</html>
</code></pre>
<p>CSS:</p>
<pre><code>*,*::before,*::after {
margin: 0;
padding: 0;
border: none;
box-sizing: border-box;
}
body main html{
width: 100%;
height: 100%;
position: relative;
}
.button {
width: 200px;
height: 200px;
border-radius: 100%;
background: linear-gradient(#e66465, #9198e5);;
position: absolute;
transition: linear 4s;
}
.popup {
display: none;
width: 1000px;
background: rgba(61, 55, 61);
height: 1000px;
overflow: auto;
font-size: 1rem;
padding: 20px;
position: absolute;
box-shadow: 0px 0px 10px 0px rgba(61, 55, 61, 0.7);
align-self: center;
}
.popup__check {
position: absolute;
width: 100%;
height: 100%;
border-radius: 100%;
cursor: pointer;
z-index: 3;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
}
.popup__check:checked ~ .popup{
display: block;
}
</code></pre>
<p>JS:</p>
<pre><code>let elem = document.querySelector('.button');
const changePosition = () => {
let randX = Math.random();
let randY = Math.random();
const circleSize = {
width: elem.clientWidth,
heigth: elem.clientHeight
};
const windowWidth = window.innerWidth - circleSize.width;
const windowheigth = window.innerHeight - circleSize.heigth;
let randXMult = windowheigth * randX;
let randXP = randXMult + 'px';
let randYMult = windowWidth * randY;
let randYP = randYMult + 'px';
elem.style.left = randYP;
elem.style.top = randXP;
};
setInterval(changePosition,1000);
</code></pre>
|
[
{
"answer_id": 74577799,
"author": "Carl-Christian Hänsel",
"author_id": 20276225,
"author_profile": "https://Stackoverflow.com/users/20276225",
"pm_score": 1,
"selected": false,
"text": "<main>\n <div class=\"button\" data-popup=\"false\"></div>\n <label name=\"popup\" id=\"popup\" class=\"popup\"></label>\n</main>\n .popup {\n display: none;\n width: 100px;\n background: rgba(61, 55, 61);\n height: 100px;\n overflow: auto;\n font-size: 1rem;\n padding: 20px;\n position: absolute;\n box-shadow: 0px 0px 10px 0px rgba(61, 55, 61, 0.7); \n align-self: center;\n}\n\n.button[data-popup='true'] + .popup{\n display: block;\n}\n const btn = document.querySelector(\".button\")\n\nconst onClick = () => {\n console.log(\"onCLick\")\n const current = btn.getAttribute(\"data-popup\") == \"true\";\n btn.setAttribute(\"data-popup\", !current);\n}\n\nbtn.addEventListener(\"click\", onClick);\n"
},
{
"answer_id": 74577853,
"author": "George Chond",
"author_id": 17730652,
"author_profile": "https://Stackoverflow.com/users/17730652",
"pm_score": 1,
"selected": true,
"text": ":checked let elem = document.querySelector('.button');\n\nconst changePosition = () => {\n let randX = Math.random();\n let randY = Math.random();\n const circleSize = {\n width: elem.clientWidth,\n heigth: elem.clientHeight\n };\n\n const windowWidth = window.innerWidth - circleSize.width;\n const windowheigth = window.innerHeight - circleSize.heigth;\n\n let randXMult = windowheigth * randX;\n let randXP = randXMult + 'px';\n let randYMult = windowWidth * randY;\n let randYP = randYMult + 'px';\n\n\n elem.style.left = randYP;\n elem.style.top = randXP;\n};\n\n\nsetInterval(changePosition, 1000); *,\n*::before,\n*::after {\n margin: 0;\n padding: 0;\n border: none;\n box-sizing: border-box;\n}\n\nmain {\n width: 100%;\n height: 100%;\n position: relative;\n}\n\n.button {\n width: 200px;\n height: 200px;\n border-radius: 100%;\n background: linear-gradient(#e66465, #9198e5);\n position: absolute;\n transition: linear 4s;\n}\n\n.popup {\n display: none;\n width: 100%;\n height: 100%;\n background: rgba(61, 55, 61);\n font-size: 4rem;\n padding: 20px;\n position: fixed;\n left: 0;\n top: 0;\n box-shadow: 0px 0px 10px 0px rgba(61, 55, 61, 0.7);\n justify-content: center;\n align-items: center;\n color: #fff;\n}\n\n.popup__check {\n position: absolute;\n width: 100%;\n height: 100%;\n border-radius: 100%;\n cursor: pointer;\n z-index: 3;\n appearance: none;\n -webkit-appearance: none;\n -moz-appearance: none;\n}\n\n.popup__check:checked+.popup {\n display: flex;\n} <main>\n <div class=\"button\">\n <input type=\"checkbox\" name=\"popup\" id=\"popup\" class=\"popup__check\">\n <label name=\"popup\" id=\"popup\" class=\"popup\">So you clicked on that thing...</label>\n </div>\n</main>"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601932/"
] |
74,577,444
|
<p>I would like to do the following validation:</p>
<ul>
<li>If it was necessary to inform a coupon, the error message would appear, but even with the following code this is not possible.</li>
</ul>
<pre><code>import * as yup from 'yup';
export type FormValues = {
promotionalCode: string;
requirePromotionalCode: boolean;
};
export const validationSchema = yup.object().shape({
requirePromotionalCode: yup.boolean(),
promotionalCode: yup.string().when('requirePromotionalCode', {
is: true,
then: yup.string().required('Please, enter a coupon'),
otherwise: yup.string().notRequired(),
}),
});
</code></pre>
<p>I tried as follows, but nothing worked.</p>
<pre><code>import * as yup from 'yup';
export type FormValues = {
promotionalCode: string;
requirePromotionalCode: boolean;
};
export const validationSchema = yup.object().shape({
requirePromotionalCode: yup.boolean(),
promotionalCode: yup.string().when('requirePromotionalCode', {
is: (requirePromotionalCode, promotionalCode) =>
requirePromotionalCode && !promotionalCode,
then: yup.string().required('Please, enter a coupon'),
otherwise: yup.string().notRequired(),
}),
});
</code></pre>
|
[
{
"answer_id": 74577799,
"author": "Carl-Christian Hänsel",
"author_id": 20276225,
"author_profile": "https://Stackoverflow.com/users/20276225",
"pm_score": 1,
"selected": false,
"text": "<main>\n <div class=\"button\" data-popup=\"false\"></div>\n <label name=\"popup\" id=\"popup\" class=\"popup\"></label>\n</main>\n .popup {\n display: none;\n width: 100px;\n background: rgba(61, 55, 61);\n height: 100px;\n overflow: auto;\n font-size: 1rem;\n padding: 20px;\n position: absolute;\n box-shadow: 0px 0px 10px 0px rgba(61, 55, 61, 0.7); \n align-self: center;\n}\n\n.button[data-popup='true'] + .popup{\n display: block;\n}\n const btn = document.querySelector(\".button\")\n\nconst onClick = () => {\n console.log(\"onCLick\")\n const current = btn.getAttribute(\"data-popup\") == \"true\";\n btn.setAttribute(\"data-popup\", !current);\n}\n\nbtn.addEventListener(\"click\", onClick);\n"
},
{
"answer_id": 74577853,
"author": "George Chond",
"author_id": 17730652,
"author_profile": "https://Stackoverflow.com/users/17730652",
"pm_score": 1,
"selected": true,
"text": ":checked let elem = document.querySelector('.button');\n\nconst changePosition = () => {\n let randX = Math.random();\n let randY = Math.random();\n const circleSize = {\n width: elem.clientWidth,\n heigth: elem.clientHeight\n };\n\n const windowWidth = window.innerWidth - circleSize.width;\n const windowheigth = window.innerHeight - circleSize.heigth;\n\n let randXMult = windowheigth * randX;\n let randXP = randXMult + 'px';\n let randYMult = windowWidth * randY;\n let randYP = randYMult + 'px';\n\n\n elem.style.left = randYP;\n elem.style.top = randXP;\n};\n\n\nsetInterval(changePosition, 1000); *,\n*::before,\n*::after {\n margin: 0;\n padding: 0;\n border: none;\n box-sizing: border-box;\n}\n\nmain {\n width: 100%;\n height: 100%;\n position: relative;\n}\n\n.button {\n width: 200px;\n height: 200px;\n border-radius: 100%;\n background: linear-gradient(#e66465, #9198e5);\n position: absolute;\n transition: linear 4s;\n}\n\n.popup {\n display: none;\n width: 100%;\n height: 100%;\n background: rgba(61, 55, 61);\n font-size: 4rem;\n padding: 20px;\n position: fixed;\n left: 0;\n top: 0;\n box-shadow: 0px 0px 10px 0px rgba(61, 55, 61, 0.7);\n justify-content: center;\n align-items: center;\n color: #fff;\n}\n\n.popup__check {\n position: absolute;\n width: 100%;\n height: 100%;\n border-radius: 100%;\n cursor: pointer;\n z-index: 3;\n appearance: none;\n -webkit-appearance: none;\n -moz-appearance: none;\n}\n\n.popup__check:checked+.popup {\n display: flex;\n} <main>\n <div class=\"button\">\n <input type=\"checkbox\" name=\"popup\" id=\"popup\" class=\"popup__check\">\n <label name=\"popup\" id=\"popup\" class=\"popup\">So you clicked on that thing...</label>\n </div>\n</main>"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19387169/"
] |
74,577,448
|
<p>I'm trying to alternate between 2 threads:</p>
<pre class="lang-py prettyprint-override"><code>import threading
def test1():
for _ in range(3):
print("Test1")
def test2():
for _ in range(3):
print("Test2")
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
t1.start()
t2.start()
t1.join()
t2.join()
</code></pre>
<p>But, the result is as shown below:</p>
<pre class="lang-none prettyprint-override"><code>Test1
Test1
Test1
Test2
Test2
Test2
</code></pre>
<p>I want the result as shown below:</p>
<pre class="lang-none prettyprint-override"><code>Test1
Test2
Test1
Test2
Test1
Test2
</code></pre>
<p>Are there any ways to do that?</p>
|
[
{
"answer_id": 74577503,
"author": "Krumelur",
"author_id": 292477,
"author_profile": "https://Stackoverflow.com/users/292477",
"pm_score": -1,
"selected": false,
"text": "multiprocessing"
},
{
"answer_id": 74582387,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 0,
"selected": false,
"text": "while import threading\nowner = \"Test1\"\nlock = threading.Lock()\n\ndef test1():\n global owner\n i = 0\n while i < 3:\n lock.acquire()\n if owner == \"Test1\":\n print(\"Test1\")\n owner = \"Test2\"\n i += 1\n lock.release()\n\ndef test2():\n global owner\n i = 0\n while i < 3:\n lock.acquire()\n if owner == \"Test2\":\n print(\"Test2\")\n owner = \"Test1\"\n i += 1\n lock.release()\n\nt1 = threading.Thread(target=test1)\nt2 = threading.Thread(target=test2)\n\nt1.start()\nt2.start()\n\nt1.join()\nt2.join()\n Test1\nTest2\nTest1\nTest2\nTest1\nTest2\n while import queue\nimport threading\nlock = threading.Lock()\n\ndef test1(owner):\n i = 0\n while i < 3:\n lock.acquire()\n if owner.queue[0] == \"Test1\":\n print(\"Test1\")\n owner.queue[0] = \"Test2\"\n i += 1\n lock.release()\n\ndef test2(owner):\n i = 0\n while i < 3:\n lock.acquire()\n if owner.queue[0] == \"Test2\":\n print(\"Test2\")\n owner.queue[0] = \"Test1\"\n i += 1\n lock.release()\n \nowner = queue.Queue()\nowner.put(\"Test1\")\n\nt1 = threading.Thread(target=test1, args=(owner,))\nt2 = threading.Thread(target=test2, args=(owner,))\n\nt1.start()\nt2.start()\n\nt1.join()\nt2.join()\n Test1\nTest2\nTest1\nTest2\nTest1\nTest2\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8172439/"
] |
74,577,453
|
<p>I getting an incompatible-pointer-types error when trying to Initialize a typedef struct with a pointer to a char buffer.
The struct looks like this:</p>
<pre><code>typedef struct otCryptoKey
{
const uint8_t *mKey; ///< Pointer to the buffer containing key. NULL indicates to use `mKeyRef`.
uint16_t mKeyLength; ///< The key length in bytes (applicable when `mKey` is not NULL).
uint32_t mKeyRef; ///< The PSA key ref (requires `mKey` to be NULL).
} otCryptoKey;
</code></pre>
<p>This is what i have tried, and i also tried to initialize with all the parameters in the struct.</p>
<pre><code> uint8_t mKey[16] = "1234567891012131";
uint8_t *mKeyPointer = mKey;
otCryptoKey *aKey = {mKeyPointer};
</code></pre>
<p>Can anyone figure out why i get this error?</p>
|
[
{
"answer_id": 74577514,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 0,
"selected": false,
"text": "otCryptoKey aKey = {mKeyPointer}; otCryptoKey aKey = { .mKey = mKey };"
},
{
"answer_id": 74577523,
"author": "dbush",
"author_id": 1687119,
"author_profile": "https://Stackoverflow.com/users/1687119",
"pm_score": 2,
"selected": true,
"text": "otCryptoKey uint8_t otCryptoKey mKey otCryptoKey aKey = {mKey, sizeof mKey, 0};\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11372980/"
] |
74,577,462
|
<p>I have the problem of finding the point which is closest to a line from an array of x- and y-data.
The line is <strong>semi-infinite</strong> originating from the origin at (0,0) and running into the direction of a given angle.</p>
<p>The x,y data of the points are given in relation to the origin.</p>
<p><strong>How do I find the closest point (and its distance) to the line in line direction (not opposite)?</strong></p>
<p>This is an example of the data I have:</p>
<pre><code> import numpy as np
import matplotlib.pyplot as plt
def main():
depth = np.random.random((100))*20+50
angle = np.linspace(0, 2*np.pi, 100)
x,y = depth2xy(depth, angle)
line = np.random.random_sample()*2*np.pi
# fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
plt.scatter(x, y)
plt.plot([0,100*np.cos(line)], [0, 100*np.sin(line)], markersize=10, color = "r")
plt.show()
def depth2xy(depth, angle):
x, y = np.zeros(len(depth)), np.zeros(len(depth))
for i in range(len(depth)):
x[i] = depth[i]*np.cos(angle[i])
y[i] = depth[i]*np.sin(angle[i])
return x,y
if __name__ == "__main__": main()
</code></pre>
<p>I could try a brute force approach, iterating over different distances along the line to find the ultimate smallest distance.</p>
<p>But as time efficiency is critical my case and the algorithm would not perform as well as I think it could, I would rather try an analytical approach.</p>
<p>I also thought about <code>scipy.spatial.distance</code>, but I am not sure how this would work for a line.</p>
|
[
{
"answer_id": 74577514,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 0,
"selected": false,
"text": "otCryptoKey aKey = {mKeyPointer}; otCryptoKey aKey = { .mKey = mKey };"
},
{
"answer_id": 74577523,
"author": "dbush",
"author_id": 1687119,
"author_profile": "https://Stackoverflow.com/users/1687119",
"pm_score": 2,
"selected": true,
"text": "otCryptoKey uint8_t otCryptoKey mKey otCryptoKey aKey = {mKey, sizeof mKey, 0};\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20315765/"
] |
74,577,465
|
<p>In my game I have a shooting enemy that I want to attack the player only when he's in range, and to attack him once every 3 seconds. This is the code I need repeated</p>
<p><a href="https://i.stack.imgur.com/fT479.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fT479.png" alt="enter image description here" /></a>
Whatever I try doing just results in the enemy shooting a metric ton of bullets at the player to the point when it sometimes crashes my project(tried for loops, while loops, played with booleans and timing with Time.deltaTime). Can someone smarter than me give me some pointers how I could do this?</p>
|
[
{
"answer_id": 74577816,
"author": "Max Play",
"author_id": 5593150,
"author_profile": "https://Stackoverflow.com/users/5593150",
"pm_score": 0,
"selected": false,
"text": "Transform target;\n\nprivate void OnTriggerEnter2D(Collider2D other)\n{\n if (other.CompareTag(\"Player\"))\n target = other.transform;\n}\n\nprivate void OnTriggerExit2D(Collider2D other)\n{\n if (other.CompareTag(\"Player\"))\n target = null;\n}\n target private void Update()\n{\n if (target != null)\n ShootAt(target.position);\n}\n\nprivate void ShootAt(Vector3 position)\n{\n // Spawn your stuff here to shoot at the given location\n}\n Update private float shootCooldown;\n\nprivate void Update()\n{\n if (target != null)\n {\n shootCooldown -= Time.deltaTime;\n if (shootCooldown <= 0.0f)\n {\n shootCooldown += 3.0f;\n ShootAt(target.position);\n }\n }\n}\n 0.0f shootCooldown -= Time.deltaTime if 0"
},
{
"answer_id": 74594020,
"author": "Sek",
"author_id": 17075435,
"author_profile": "https://Stackoverflow.com/users/17075435",
"pm_score": 1,
"selected": false,
"text": "private void OnTriggerEnter2D(Collider2D other) {\n if (other.tag == \"Player\") {\n StartCoroutine(ShootAtPlayer());\n }\n}\n\nprivate void OnTriggerExit2D(Collider2D other) {\n if (other.tag == \"Player\") {\n StopAllCoroutines();\n }\n}\n\nprivate IEnumerator ShootAtPlayer() {\n while (true) {\n Instantiate(enemyBullet, enemy.transform.localPosition, transform.LocalRotation);\n yield return new WaitForSeconds(3.0f);\n }\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20324453/"
] |
74,577,488
|
<p>I have a project that includes c++ binaries and python scripts, it's setup such that it should be installed using setuptools. One of the python files is intended to be both used as a script "
<code>python3 script_name.py params</code>
and for it's primary function to be used in other python projects <code>from script_name import function</code>.
The primary function calls a binary which is in a known relative location before the installation (the user is expected to call <code>pip install project_folder</code>). So in order to call the binary I want to get this files location (pre installation)</p>
<p>To get this I used something like</p>
<pre><code>Path(__file__).resolve().parent
</code></pre>
<p>however, since the installation moves the file to another folder like <code>~/.local/...</code> this doesn't work when imported after the installation.</p>
<p>Is there a way to get the original file path, or to make the installation save that path somewhere?</p>
<p>EDIT:
After @sinoroc 's suggestion I tried including the binary as a resource by putting an __init__.py in the build folder and putting</p>
<pre><code>from importlib.resources import files
import build
binary = files(build).joinpath("binary")
</code></pre>
<p>in the main init. After that <code>package.binary</code> still gives me a path to my <code>.local/lib</code> and <code>binary.is_file()</code> still returns <code>False</code></p>
<pre><code>from importlib_resources import files
GenerateHistograms = files("build").joinpath("GenerateHistograms")
</code></pre>
<p>gave the same result</p>
|
[
{
"answer_id": 74581950,
"author": "suvayu",
"author_id": 289784,
"author_profile": "https://Stackoverflow.com/users/289784",
"pm_score": 2,
"selected": true,
"text": "setup.py from setuptools import setup, find_packages\n\nsetup(\n name=\"mypkg\",\n packages=find_packages(exclude=[\"tests\"]),\n package_data={\n \"mypkg\": [\n \"binary\", # relative path to your package directory\n ]\n },\n include_package_data=True,\n)\n pkg_resources from pathlib import Path\n\nfrom pkg_resources import resource_filename\n\n# \"binary\" is whatever relative path you put in package_data\npath_to_binary = Path(resource_filename(\"mypkg\", \"binary\"))\n pkg_resources setuptools importlib.resources pkg_resources"
},
{
"answer_id": 74582187,
"author": "Chalky",
"author_id": 3271145,
"author_profile": "https://Stackoverflow.com/users/3271145",
"pm_score": 0,
"selected": false,
"text": "package_data={'package':['build/*']}\ninclude_package_data=True\n from importlib.resources import files\nbinary = files(\"package.build\").joinpath(\"binary\")\n from package import binary"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3271145/"
] |
74,577,534
|
<p>I have 5 tables:
1.event - id, name, location
2.location - id, country_id, county_id, city_id
3.country - id, name
4.county - id, name, country_id,
5. city - id, name, county_id</p>
<p>I can get to work for populate city select box</p>
<p>I have 2 form types
EventLocationType and LocationType</p>
<p>Thank you in advance!</p>
<p>I have try to make city box to work but i don;t know how to do it!
Thanks!</p>
<pre class="lang-php prettyprint-override"><code>class EventLocationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name')
->add('location', LocationType::class, [
'label' => false,
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => EventLocation::class,
]);
}
}
</code></pre>
<pre class="lang-php prettyprint-override"><code>class LocationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('country', CountryTypeSelect::class, [
'label' => false,
'constraints' => [
new NotBlank([
'message' => 'not null',
]),
],
])
->add('county', ChoiceType::class, [
'label' => false,
'placeholder' => 'Choose an option',
'constraints' => [
new NotBlank([
'message' => 'not null',
]),
],
])
->add('city', ChoiceType::class, [
'label' => false,
'attr' => [ 'class' => 'form-control'],
'placeholder' => 'Choose an option',
'constraints' => [
new NotBlank([
'message' => 'not null',
]),
],
]);
$formModifier = function (FormInterface $form, Country $country = null) {
$counties_array = [];
if($country != null) {
$g = new GeoNamesClient('djmichael');
[$countryGeoNames] = $g->countryInfo([
'country' => $country->getName(),
]);
$country_name = $countryGeoNames->geonameId;
$counties_json = $g->children(['geonameId' => $country_name]);
foreach($counties_json as $counties_j) {
//dd($counties_j->toponymName);
$counties_array[$counties_j->toponymName] = $counties_j->geonameId;
}
//dd($counties);
}
//var_dump($counties);
$counties = null === $counties_array ? [] : $counties_array;
$form->add('county', ChoiceType::class, [
'placeholder' => 'Choose an option',
'required' => false,
'attr' => [
'class' => 'form-control'
],
'choices' => $counties,
//'mapped' => false,
'constraints' => [
new NotBlank([
'message' => 'not null',
]),
],
]);
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
// this would be your entity, i.e. SportMeetup
$data = $event->getData();
//
$country = null;
if($data != null) {
$country = $data->getCountry();
//dd($data);
}
$formModifier($event->getForm(), $country);
}
);
$builder->get('country')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$country = $event->getForm()->getData();
if($country->getName() != null) {
$formModifier($event->getForm()->getParent(), $country);
} else {
$formModifier2($event->getForm(), $county);
}
//dd($country);
}
);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Location::class,
]);
}
}
</code></pre>
<pre><code>var $country = $('#event_location_location_country_name');
var $token = $('#event_location__token');
var $county = $('#event_location_location_county');
// When country gets selected ...
$country.change(function () {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected country value.
var data = {};
data[$country.attr('name')] = $country.val();
data[$token.attr('name')] = $token.val();
// Submit data via AJAX to the form's action path.
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: data,
complete: function (html) {
//console.log(html.responseText);
// Replace current state field ...
$('#event_location_location_county').replaceWith(
// ... with the returned one from the AJAX response.
$(html.responseText).find('#event_location_location_county')
);
},
});
});
$county.change(function () {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected country value.
var data = {};
data[$country.attr('name')] = $county.val();
data[$token.attr('name')] = $token.val();
console.log(data);
// Submit data via AJAX to the form's action path.
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: data,
complete: function (html) {
//console.log(html.responseText);
// Replace current state field ...
$('#event_location_city').replaceWith(
// ... with the returned one from the AJAX response.
$(html.responseText).find('#event_location_city')
);
},
});
});
</code></pre>
<pre class="lang-php prettyprint-override"><code>#[ORM\Entity(repositoryClass: EventLocationRepository::class)]
class EventLocation
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 128, nullable: true)]
private ?string $name = null;
#[ORM\ManyToOne(inversedBy: 'eventLocations', cascade: ['persist', 'remove'])]
#[Assert\NotBlank]
#[ORM\JoinColumn(nullable: false)]
private ?Location $location = null;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): self
{
$this->name = $name;
return $this;
}
public function getLocation(): ?Location
{
return $this->location;
}
public function setLocation(?Location $location): self
{
$this->location = $location;
return $this;
}
}
</code></pre>
<pre class="lang-php prettyprint-override"><code>#[ORM\Entity(repositoryClass: LocationRepository::class)]
class Location
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\ManyToOne(inversedBy: 'locations', cascade: ['persist', 'remove'])]
#[ORM\JoinColumn(nullable: false)]
#[Assert\NotBlank]
private ?Country $country = null;
#[ORM\ManyToOne(inversedBy: 'locations', cascade: ['persist', 'remove'])]
#[ORM\JoinColumn(nullable: false)]
#[Assert\NotBlank]
private ?County $county = null;
#[ORM\ManyToOne(inversedBy: 'locations')]
#[ORM\JoinColumn(nullable: false)]
#[Assert\NotBlank]
private ?City $city = null;
#[ORM\OneToMany(mappedBy: 'location', targetEntity: EventLocation::class)]
private Collection $eventLocations;
public function __construct()
{
$this->eventLocations = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getCountry(): ?Country
{
return $this->country;
}
public function setCountry(?Country $country): self
{
$this->country = $country;
return $this;
}
public function getCounty(): ?County
{
return $this->county;
}
public function setCounty(?County $county): self
{
$this->county = $county;
return $this;
}
public function getCity(): ?City
{
return $this->city;
}
public function setCity(?City $city): self
{
$this->city = $city;
return $this;
}
/**
* @return Collection<int, EventLocation>
*/
public function getEventLocations(): Collection
{
return $this->eventLocations;
}
public function addEventLocation(EventLocation $eventLocation): self
{
if (!$this->eventLocations->contains($eventLocation)) {
$this->eventLocations->add($eventLocation);
$eventLocation->setLocation($this);
}
return $this;
}
public function removeEventLocation(EventLocation $eventLocation): self
{
if ($this->eventLocations->removeElement($eventLocation)) {
// set the owning side to null (unless already changed)
if ($eventLocation->getLocation() === $this) {
$eventLocation->setLocation(null);
}
}
return $this;
}
}
</code></pre>
<pre class="lang-php prettyprint-override"><code>#[ORM\Entity(repositoryClass: CountryRepository::class)]
class Country
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 128, nullable: true)]
private ?string $name = null;
#[ORM\OneToMany(mappedBy: 'country', targetEntity: County::class)]
private Collection $counties;
#[ORM\OneToMany(mappedBy: 'country', targetEntity: Location::class)]
private Collection $locations;
public function __construct()
{
$this->counties = new ArrayCollection();
$this->locations = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): self
{
$this->name = $name;
return $this;
}
/**
* @return Collection<int, County>
*/
public function getCounties(): Collection
{
return $this->counties;
}
public function addCounty(County $county): self
{
if (!$this->counties->contains($county)) {
$this->counties->add($county);
$county->setCountry($this);
}
return $this;
}
public function removeCounty(County $county): self
{
if ($this->counties->removeElement($county)) {
// set the owning side to null (unless already changed)
if ($county->getCountry() === $this) {
$county->setCountry(null);
}
}
return $this;
}
/**
* @return Collection<int, Location>
*/
public function getLocations(): Collection
{
return $this->locations;
}
public function addLocation(Location $location): self
{
if (!$this->locations->contains($location)) {
$this->locations->add($location);
$location->setCountry($this);
}
return $this;
}
public function removeLocation(Location $location): self
{
if ($this->locations->removeElement($location)) {
// set the owning side to null (unless already changed)
if ($location->getCountry() === $this) {
$location->setCountry(null);
}
}
return $this;
}
}
</code></pre>
<pre class="lang-php prettyprint-override"><code>#[ORM\Entity(repositoryClass: CountyRepository::class)]
class County
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 128, nullable: true)]
private ?string $name = null;
#[ORM\ManyToOne(inversedBy: 'counties')]
private ?Country $country = null;
#[ORM\OneToMany(mappedBy: 'county', targetEntity: City::class)]
private Collection $cities;
#[ORM\OneToMany(mappedBy: 'county', targetEntity: Location::class)]
private Collection $locations;
public function __construct()
{
$this->cities = new ArrayCollection();
$this->locations = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): self
{
$this->name = $name;
return $this;
}
public function getCountry(): ?Country
{
return $this->country;
}
public function setCountry(?Country $country): self
{
$this->country = $country;
return $this;
}
/**
* @return Collection<int, City>
*/
public function getCities(): Collection
{
return $this->cities;
}
public function addCity(City $city): self
{
if (!$this->cities->contains($city)) {
$this->cities->add($city);
$city->setCounty($this);
}
return $this;
}
public function removeCity(City $city): self
{
if ($this->cities->removeElement($city)) {
// set the owning side to null (unless already changed)
if ($city->getCounty() === $this) {
$city->setCounty(null);
}
}
return $this;
}
/**
* @return Collection<int, Location>
*/
public function getLocations(): Collection
{
return $this->locations;
}
public function addLocation(Location $location): self
{
if (!$this->locations->contains($location)) {
$this->locations->add($location);
$location->setCounty($this);
}
return $this;
}
public function removeLocation(Location $location): self
{
if ($this->locations->removeElement($location)) {
// set the owning side to null (unless already changed)
if ($location->getCounty() === $this) {
$location->setCounty(null);
}
}
return $this;
}
}
</code></pre>
<pre class="lang-php prettyprint-override"><code>#[ORM\Entity(repositoryClass: CityRepository::class)]
class City
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 128, nullable: true)]
private ?string $name = null;
#[ORM\ManyToOne(inversedBy: 'cities')]
private ?County $county = null;
#[ORM\OneToMany(mappedBy: 'city', targetEntity: Location::class)]
private Collection $locations;
public function __construct()
{
$this->locations = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): self
{
$this->name = $name;
return $this;
}
public function getCounty(): ?County
{
return $this->county;
}
public function setCounty(?County $county): self
{
$this->county = $county;
return $this;
}
/**
* @return Collection<int, Location>
*/
public function getLocations(): Collection
{
return $this->locations;
}
public function addLocation(Location $location): self
{
if (!$this->locations->contains($location)) {
$this->locations->add($location);
$location->setCity($this);
}
return $this;
}
public function removeLocation(Location $location): self
{
if ($this->locations->removeElement($location)) {
// set the owning side to null (unless already changed)
if ($location->getCity() === $this) {
$location->setCity(null);
}
}
return $this;
}
}
</code></pre>
|
[
{
"answer_id": 74581950,
"author": "suvayu",
"author_id": 289784,
"author_profile": "https://Stackoverflow.com/users/289784",
"pm_score": 2,
"selected": true,
"text": "setup.py from setuptools import setup, find_packages\n\nsetup(\n name=\"mypkg\",\n packages=find_packages(exclude=[\"tests\"]),\n package_data={\n \"mypkg\": [\n \"binary\", # relative path to your package directory\n ]\n },\n include_package_data=True,\n)\n pkg_resources from pathlib import Path\n\nfrom pkg_resources import resource_filename\n\n# \"binary\" is whatever relative path you put in package_data\npath_to_binary = Path(resource_filename(\"mypkg\", \"binary\"))\n pkg_resources setuptools importlib.resources pkg_resources"
},
{
"answer_id": 74582187,
"author": "Chalky",
"author_id": 3271145,
"author_profile": "https://Stackoverflow.com/users/3271145",
"pm_score": 0,
"selected": false,
"text": "package_data={'package':['build/*']}\ninclude_package_data=True\n from importlib.resources import files\nbinary = files(\"package.build\").joinpath(\"binary\")\n from package import binary"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20602324/"
] |
74,577,545
|
<p>I have a sample code for the Sklearn taken from the website. I am trying to learn how to classify points using Sklearn(Scikit-Learn). Here is the code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons, make_circles, make_classification
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.inspection import DecisionBoundaryDisplay
names = [
"Nearest Neighbors",
]
classifiers = [
KNeighborsClassifier(3),
]
X, y = make_classification(
n_features=2, n_redundant=0, n_informative=2, random_state=1, n_clusters_per_class=1
)
rng = np.random.RandomState(2)
X += 2 * rng.uniform(size=X.shape)
linearly_separable = (X, y)
datasets = [
linearly_separable,
]
figure = plt.figure(figsize=(27, 9))
i = 1
# iterate over datasets
for ds_cnt, ds in enumerate(datasets):
# preprocess dataset, split into training and test part
X, y = ds
X = StandardScaler().fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.4, random_state=42
)
x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
# just plot the dataset first
cm = plt.cm.RdBu
cm_bright = ListedColormap(["#FF0000", "#0000FF"])
ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
if ds_cnt == 0:
ax.set_title("Input data")
# Plot the training points
ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright, edgecolors="k")
# Plot the testing points
ax.scatter(
X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6, edgecolors="k"
)
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xticks(())
ax.set_yticks(())
i += 1
# iterate over classifiers
for name, clf in zip(names, classifiers):
ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
clf.fit(X_train, y_train)
score = clf.score(X_test, y_test)
All_Value_Response = DecisionBoundaryDisplay.from_estimator(
clf, X, cmap=cm, alpha=0.8, ax=ax, eps=0.5
)
# Plot the training points
ax.scatter(
X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright, edgecolors="k"
)
# Plot the testing points
ax.scatter(
X_test[:, 0],
X_test[:, 1],
c=y_test,
cmap=cm_bright,
edgecolors="k",
alpha=0.6,
)
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xticks(())
ax.set_yticks(())
if ds_cnt == 0:
ax.set_title(name)
ax.text(
x_max - 0.3,
y_min + 0.3,
("%.2f" % score).lstrip("0"),
size=15,
horizontalalignment="right",
)
i += 1
plt.tight_layout()
plt.show()
</code></pre>
<p>Here is the output:</p>
<p><a href="https://i.stack.imgur.com/aTU6a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aTU6a.png" alt="Output Image" /></a></p>
<p>Now as one can see the areas formed are not regular shapes, so it is becoming a little difficult to understand how to know if a new point arrives and will lie in which region. I managed to capture the data of the regions (<code>All_Value_Response</code> variable stores that information) but it seems not helpful to me.</p>
<p>So I want to know if I want to know in which region does the point <code>(1,3)</code> lies then how I can deduce it through code. I can do it by seeing on the graph but how to make it work using the code?</p>
<p>Please help me find a solution to my problem.</p>
|
[
{
"answer_id": 74581950,
"author": "suvayu",
"author_id": 289784,
"author_profile": "https://Stackoverflow.com/users/289784",
"pm_score": 2,
"selected": true,
"text": "setup.py from setuptools import setup, find_packages\n\nsetup(\n name=\"mypkg\",\n packages=find_packages(exclude=[\"tests\"]),\n package_data={\n \"mypkg\": [\n \"binary\", # relative path to your package directory\n ]\n },\n include_package_data=True,\n)\n pkg_resources from pathlib import Path\n\nfrom pkg_resources import resource_filename\n\n# \"binary\" is whatever relative path you put in package_data\npath_to_binary = Path(resource_filename(\"mypkg\", \"binary\"))\n pkg_resources setuptools importlib.resources pkg_resources"
},
{
"answer_id": 74582187,
"author": "Chalky",
"author_id": 3271145,
"author_profile": "https://Stackoverflow.com/users/3271145",
"pm_score": 0,
"selected": false,
"text": "package_data={'package':['build/*']}\ninclude_package_data=True\n from importlib.resources import files\nbinary = files(\"package.build\").joinpath(\"binary\")\n from package import binary"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4948889/"
] |
74,577,560
|
<p>So i have a regular method and a HttpGet method:</p>
<pre><code> //Create a new note
public ActionResult EditNote()
{
return View();
}
//Edit a selected note
[HttpGet]
public ActionResult EditNote(int id)
{
var model = NotesProcessor.LoadNote(id);
return View(model);
}
</code></pre>
<p>They both use the same views page, but only the HttpGet method will fill up the page with details since the user will be editing an existing note here.
So the first method should open up a page that is not filled with data.</p>
<p>My issue is that i don't know how to call the non HttpGet method from my views page since it will automatically call the HttpGet method and the page will give me an error:</p>
<blockquote>
<p>The parameters dictionary contains a null entry for parameter 'id'</p>
</blockquote>
<p>This is how I'm trying to call the regular method: (Which worked fine before adding the other one)</p>
<pre><code>@Html.ActionLink("Create New", "EditNote")
</code></pre>
<p>And this is for the HttpGet method:</p>
<pre><code>@Html.ActionLink("Edit", "EditNote", new { id = Model.Id })
</code></pre>
<p>Honestly i thought it would detect the non overloaded syntax and call the right method but it doesn't.</p>
<p>I could make another views page for creating a blank note but that's not very 'DRY'...</p>
<p>What should i do?</p>
|
[
{
"answer_id": 74581950,
"author": "suvayu",
"author_id": 289784,
"author_profile": "https://Stackoverflow.com/users/289784",
"pm_score": 2,
"selected": true,
"text": "setup.py from setuptools import setup, find_packages\n\nsetup(\n name=\"mypkg\",\n packages=find_packages(exclude=[\"tests\"]),\n package_data={\n \"mypkg\": [\n \"binary\", # relative path to your package directory\n ]\n },\n include_package_data=True,\n)\n pkg_resources from pathlib import Path\n\nfrom pkg_resources import resource_filename\n\n# \"binary\" is whatever relative path you put in package_data\npath_to_binary = Path(resource_filename(\"mypkg\", \"binary\"))\n pkg_resources setuptools importlib.resources pkg_resources"
},
{
"answer_id": 74582187,
"author": "Chalky",
"author_id": 3271145,
"author_profile": "https://Stackoverflow.com/users/3271145",
"pm_score": 0,
"selected": false,
"text": "package_data={'package':['build/*']}\ninclude_package_data=True\n from importlib.resources import files\nbinary = files(\"package.build\").joinpath(\"binary\")\n from package import binary"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20268332/"
] |
74,577,564
|
<p>I've seen <a href="https://stackoverflow.com/a/72656286/11832197">this</a>, but it doesn't return the desired result, which would be:</p>
<pre><code>[
[4, "frente", 196],
[5, "frente", 196]
]
</code></pre>
<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>function getUniqueData(arr = [
[4, "frente", 196],
[4, "frente", 196],
[5, "frente", 196]
], uniqueCols = [0]) {
const uniqueData = arr.filter((currentRow, i) => {
const currentCombo = uniqueCols.map(index => currentRow[index]);
return !arr.some((row, j) => {
const combo = uniqueCols.map(index => row[index]);
return combo.every((c1, k) => c1 === currentCombo[k]) && i !== j;
});
});
return uniqueData;
}
console.log(getUniqueData())</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74577677,
"author": "cmgchess",
"author_id": 13583510,
"author_profile": "https://Stackoverflow.com/users/13583510",
"pm_score": 1,
"selected": true,
"text": "function getUniqueData(arr = [\n [4, \"frente\", 196],\n [4, \"frente\", 196],\n [5, \"frente\", 196] \n], uniqueCols = [0]) {\n const uniqueData = arr.filter((currentRow, i, self) => {\n return i === self.findIndex((t) => {\n return uniqueCols.every((col) => t[col] === currentRow[col])\n })\n });\n return uniqueData;\n}\nconsole.log(getUniqueData()) function getUniqueData(arr = [\n [4, \"frente\", 196],\n [4, \"frente\", 196],\n [5, \"frente\", 196] \n], uniqueCols = [1]) {\n const uniqueData = arr.filter((currentRow, i, self) => {\n return i === self.findIndex((t) => {\n return uniqueCols.every((col) => t[col] === currentRow[col])\n })\n });\n return uniqueData;\n}\nconsole.log(getUniqueData()) function getUniqueData(arr = [\n [4, \"a\", 196],\n [4, \"frente\", 196],\n [5, \"frente\", 196] \n], uniqueCols = [1]) {\n const uniqueData = arr.filter((currentRow, i, self) => {\n return i === self.findIndex((t) => {\n return uniqueCols.every((col) => t[col] === currentRow[col])\n })\n });\n return uniqueData;\n}\nconsole.log(getUniqueData()) function getUniqueData(arr = [\n [4, \"frente\", 196],\n [4, \"frente\", 196],\n [5, \"frente\", 196] \n], uniqueCols = [0,1]) {\n const uniqueData = arr.filter((currentRow, i, self) => {\n return i === self.findIndex((t) => {\n return uniqueCols.every((col) => t[col] === currentRow[col])\n })\n });\n return uniqueData;\n}\nconsole.log(getUniqueData())"
},
{
"answer_id": 74578007,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 1,
"selected": false,
"text": "function getUniqueData(arr = [[4, \"frente\", 196], [4, \"frente\", 196], [5, \"frente\", 196]]) {\n let uA = [];\n let jA = []\n arr.forEach((r, i) => {\n if (!~jA.indexOf(arr[i].join())) {\n uA.push(r);\n jA.push(arr[i].join())\n }\n });\n Logger.log(uA);\n}\n\nExecution log\n2:32:02 PM Notice Execution started\n2:32:03 PM Info [[4.0, frente, 196.0], [5.0, frente, 196.0]]\n2:32:04 PM Notice Execution completed\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11832197/"
] |
74,577,567
|
<p>I would like to print some specific lines from a file, only those lines that come after a certain word appears on a line ('Ingredients:') and before another word appears ('Instructions:').
The file is a list of recipes and I want to be able to print out only the ingredients.</p>
<p>example of the text:</p>
<pre><code>RECIPE : CACIO E PEPE #PASTA
Ingredients:
spaghetti: 200-g
butter: 25-gr
black pepper: as needed
pecorino: 50-gr
Instructions:
</code></pre>
<p>I tried this way and many others but nothing seems to work:</p>
<pre><code>def find_line_after(target):
with open('recipes.txt', 'r') as f:
line = f.readline().strip()
while line:
if line == target:
line = f.readline().strip()
return f.readline()
</code></pre>
|
[
{
"answer_id": 74577800,
"author": "CreepyRaccoon",
"author_id": 18342123,
"author_profile": "https://Stackoverflow.com/users/18342123",
"pm_score": 0,
"selected": false,
"text": "start, stop = 0, 0\nwith open('recipes.txt', 'r') as f:\n lines = f.readlines()\nfor n in range(len(lines)):\n if 'Ingredients' in lines[n]:\n start = n + 1\n elif 'Instructions' in lines[n]:\n stop = n\ningredients = list(filter(('\\n').__ne__, lines[start:stop]))\nfor i in ingredients:\n print(i, end='')\n spaghetti: 200-g\nbutter: 25-gr\nblack pepper: as needed\npecorino: 50-gr\n"
},
{
"answer_id": 74578068,
"author": "NahuelBrandan",
"author_id": 6125910,
"author_profile": "https://Stackoverflow.com/users/6125910",
"pm_score": 2,
"selected": true,
"text": "def get_all_ingredients():\n flag = False\n with open('recipes.txt', 'r') as f:\n for line in f:\n if 'Instructions' in line:\n flag = False\n\n if flag:\n print(line.rstrip())\n\n if 'Ingredients' in line:\n flag = True\n\n\nget_all_ingredients()\n RECIPE : CACIO E PEPE #PASTA\nIngredients:\nspaghetti: 200-g\nbutter: 25-gr\nblack pepper: as needed\npecorino: 50-gr\nInstructions:\nasd\nRECIPE : CACIO E PEPE #PASTA\nIngredients:\nsalt: 200-g\nchicken: 25-gr\nInstructions:\nqwe\nqwe\nRECIPE : CACIO E PEPE #PASTA\nIngredients:\ncarrot: 200-g\nrabbit: 25-gr\nInstructions:\nqwe\nqwe\n spaghetti: 200-g\nbutter: 25-gr\nblack pepper: as needed\npecorino: 50-gr\nsalt: 200-g\nchicken: 25-gr\ncarrot: 200-g\nrabbit: 25-gr\n"
},
{
"answer_id": 74578093,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 0,
"selected": false,
"text": "is_ingredient is_ingredient = False\nwith open(\"recipes.txt\", \"r\", encoding=\"utf-8\") as stream:\n for line in stream:\n if line.startswith(\"Ingredients:\"):\n is_ingredient = True\n elif line.startswith(\"Instructions:\"):\n is_ingredient = False\n print(\"---\")\n elif is_ingredient:\n print(line, end=\"\")\n ---"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20234680/"
] |
74,577,582
|
<p>I am using DRF and I have these pieces of code as models, register view and serializer
But anytime I signup a user the password does not hashed and I can't see to figure out why.</p>
<p>models.py</p>
<pre><code>class UserManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
if not email:
raise ValueError("Users must have an email")
email = self.normalize_email(email).lower()
user = self.model(email=email, **kwargs)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
if not password:
raise ValueError("Password is required")
user = self.create_user(email, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
role = models.CharField(max_length=255)
department = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_verified = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = UserManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["first_name", "last_name", "role", "department"]
def __str__(self):
return self.email
</code></pre>
<p>serializers.py</p>
<pre><code>class RegisterSerializer(serializers.ModelSerializer):
email = serializers.CharField(max_length=255)
password = serializers.CharField(min_length=8, write_only=True)
first_name = serializers.CharField(max_length=255)
last_name = serializers.CharField(max_length=255)
role = serializers.CharField(max_length=255)
department = serializers.CharField(max_length=255)
class Meta:
model = User
fields = ["email", "password", "first_name", "last_name", "role", "department"]
def create(self, validated_data):
return User.objects.create(**validated_data)
def validate_email(self, value):
if User.objects.filter(email=value).exists():
raise serializers.ValidationError("This email already exists!")
return value
</code></pre>
<p>views.py</p>
<pre><code>class RegisterView(APIView):
serializer_class = RegisterSerializer
def post(self, request, *args):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
user = User.objects.get(email=user_data.get("email"))
return Response(user_data, status=status.HTTP_201_CREATED)
</code></pre>
<p>for some reason, which I don't know anytime a user is created the password is save in clear text. It does not hash the passwords. The superuser's password is however hashed because I created it with the command line but the api doesn't hash the password. I some help to fix this.</p>
<p><a href="https://i.stack.imgur.com/Nq7Si.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nq7Si.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74577800,
"author": "CreepyRaccoon",
"author_id": 18342123,
"author_profile": "https://Stackoverflow.com/users/18342123",
"pm_score": 0,
"selected": false,
"text": "start, stop = 0, 0\nwith open('recipes.txt', 'r') as f:\n lines = f.readlines()\nfor n in range(len(lines)):\n if 'Ingredients' in lines[n]:\n start = n + 1\n elif 'Instructions' in lines[n]:\n stop = n\ningredients = list(filter(('\\n').__ne__, lines[start:stop]))\nfor i in ingredients:\n print(i, end='')\n spaghetti: 200-g\nbutter: 25-gr\nblack pepper: as needed\npecorino: 50-gr\n"
},
{
"answer_id": 74578068,
"author": "NahuelBrandan",
"author_id": 6125910,
"author_profile": "https://Stackoverflow.com/users/6125910",
"pm_score": 2,
"selected": true,
"text": "def get_all_ingredients():\n flag = False\n with open('recipes.txt', 'r') as f:\n for line in f:\n if 'Instructions' in line:\n flag = False\n\n if flag:\n print(line.rstrip())\n\n if 'Ingredients' in line:\n flag = True\n\n\nget_all_ingredients()\n RECIPE : CACIO E PEPE #PASTA\nIngredients:\nspaghetti: 200-g\nbutter: 25-gr\nblack pepper: as needed\npecorino: 50-gr\nInstructions:\nasd\nRECIPE : CACIO E PEPE #PASTA\nIngredients:\nsalt: 200-g\nchicken: 25-gr\nInstructions:\nqwe\nqwe\nRECIPE : CACIO E PEPE #PASTA\nIngredients:\ncarrot: 200-g\nrabbit: 25-gr\nInstructions:\nqwe\nqwe\n spaghetti: 200-g\nbutter: 25-gr\nblack pepper: as needed\npecorino: 50-gr\nsalt: 200-g\nchicken: 25-gr\ncarrot: 200-g\nrabbit: 25-gr\n"
},
{
"answer_id": 74578093,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 0,
"selected": false,
"text": "is_ingredient is_ingredient = False\nwith open(\"recipes.txt\", \"r\", encoding=\"utf-8\") as stream:\n for line in stream:\n if line.startswith(\"Ingredients:\"):\n is_ingredient = True\n elif line.startswith(\"Instructions:\"):\n is_ingredient = False\n print(\"---\")\n elif is_ingredient:\n print(line, end=\"\")\n ---"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14752392/"
] |
74,577,602
|
<p>I have a LAMBDA function nested in a <em>lambda helper function</em> (<code>MAKEARRAY</code>) to create a column with a series of dates. The series starts with the last day of the month defined in cell <code>start_date</code> followed by the last day of the following month. This one month interval goes on a number of times defined by the value in cell <code>number_months</code>.</p>
<p>The formula is the following:</p>
<p><code>=MAKEARRAY(number_months,1,LAMBDA(r,c,EOMONTH(start_date,r-1)))</code></p>
<p><strong>I would like:</strong></p>
<ul>
<li>This sequence to repeat just below.</li>
<li>Repetition needs to take place a certain number of times, as defined by value in <code>number_repeats</code>.</li>
</ul>
<p>Since I have the series as the <strong>row heading</strong> of another Sheet, I have tried using TRANSPOSE(ARRAYFORMULA(INDIRECT to select the variable range, rather than generating again the repeated series of dates. However, in such case I have to figure out how to repeat that array a certain number of times without using REPT and SPLIT because it exceeds the character capacity by far.</p>
<p>That being said, if possible my preference is for a solution based on the transposed LAMBDA function that created the row heading in the other Sheet, rather than referring to the heading using ARRAYFORMULA.</p>
<p>I feel I could use SEQUENCE for that, but I am not sure how to combine it with the LAMBDA function to repeat the series a certain number of times.</p>
|
[
{
"answer_id": 74577800,
"author": "CreepyRaccoon",
"author_id": 18342123,
"author_profile": "https://Stackoverflow.com/users/18342123",
"pm_score": 0,
"selected": false,
"text": "start, stop = 0, 0\nwith open('recipes.txt', 'r') as f:\n lines = f.readlines()\nfor n in range(len(lines)):\n if 'Ingredients' in lines[n]:\n start = n + 1\n elif 'Instructions' in lines[n]:\n stop = n\ningredients = list(filter(('\\n').__ne__, lines[start:stop]))\nfor i in ingredients:\n print(i, end='')\n spaghetti: 200-g\nbutter: 25-gr\nblack pepper: as needed\npecorino: 50-gr\n"
},
{
"answer_id": 74578068,
"author": "NahuelBrandan",
"author_id": 6125910,
"author_profile": "https://Stackoverflow.com/users/6125910",
"pm_score": 2,
"selected": true,
"text": "def get_all_ingredients():\n flag = False\n with open('recipes.txt', 'r') as f:\n for line in f:\n if 'Instructions' in line:\n flag = False\n\n if flag:\n print(line.rstrip())\n\n if 'Ingredients' in line:\n flag = True\n\n\nget_all_ingredients()\n RECIPE : CACIO E PEPE #PASTA\nIngredients:\nspaghetti: 200-g\nbutter: 25-gr\nblack pepper: as needed\npecorino: 50-gr\nInstructions:\nasd\nRECIPE : CACIO E PEPE #PASTA\nIngredients:\nsalt: 200-g\nchicken: 25-gr\nInstructions:\nqwe\nqwe\nRECIPE : CACIO E PEPE #PASTA\nIngredients:\ncarrot: 200-g\nrabbit: 25-gr\nInstructions:\nqwe\nqwe\n spaghetti: 200-g\nbutter: 25-gr\nblack pepper: as needed\npecorino: 50-gr\nsalt: 200-g\nchicken: 25-gr\ncarrot: 200-g\nrabbit: 25-gr\n"
},
{
"answer_id": 74578093,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 0,
"selected": false,
"text": "is_ingredient is_ingredient = False\nwith open(\"recipes.txt\", \"r\", encoding=\"utf-8\") as stream:\n for line in stream:\n if line.startswith(\"Ingredients:\"):\n is_ingredient = True\n elif line.startswith(\"Instructions:\"):\n is_ingredient = False\n print(\"---\")\n elif is_ingredient:\n print(line, end=\"\")\n ---"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19398081/"
] |
74,577,606
|
<p>I made a simple code and my question is if is there a way to avoid globals in tkinter in this kind of scenario:</p>
<pre><code>root = Tk()
root.title('Main')
root.minsize(400, 450)
toggle = True
def change_now():
global toggle
root.config(bg='blue') if toggle else root.config(bg='black')
toggle = not toggle
my_button = Button(root, text='Click me!', command=change_now)
my_button.pack()
root.mainloop()
</code></pre>
<p>I know the best option is an object-oriented approach, but that means refactoring the entire code, is there a quick solution in this example? I know using global variables is bad practice.</p>
|
[
{
"answer_id": 74577662,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "from tkinter import Tk, Button, BooleanVar\nroot = Tk()\nroot.title('Main')\nroot.minsize(400, 450)\n\ntoggle_tkinter = BooleanVar(value=True)\n\ndef change_now():\n root.config(bg='blue') if toggle_tkinter.get() else root.config(bg='black')\n toggle_tkinter.set(not toggle_tkinter.get())\n\nmy_button = Button(root, text='Click me!', command=change_now)\nmy_button.pack()\n\nroot.mainloop()\n"
},
{
"answer_id": 74585777,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 0,
"selected": false,
"text": "def chande_now():\n color = “black” if root.cget(“bg”) == “blue” else “blue”\n root.configure(bg=color)\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19934155/"
] |
74,577,614
|
<p>I have defined a table like this:</p>
<pre><code>create or replace TABLE TEST_TABLE cluster by LINEAR(ARTICLE, ORDER_DATE) (
ORDER_DATE DATE
ARTICLE VARCHAR(1555)
note VARCHAR(1555)
);
</code></pre>
<p>If I try to rename the column <code>ORDER_DATE</code>, I get an error that it cannot be renamed since it belongs to a clustering key. There is data inside this table that I do not want to get rid of. It is also not convenient to create a new table and copy the entire data into it since there is a lot of data.</p>
<p>Is there any way to temporarily remove the clustering key, rename it and add the key again?</p>
<p>or is there a way to do use a single statement that renames the column and changes the clustering col name at the same time?</p>
|
[
{
"answer_id": 74577831,
"author": "Himanshu Kandpal",
"author_id": 11227919,
"author_profile": "https://Stackoverflow.com/users/11227919",
"pm_score": 0,
"selected": false,
"text": "create or replace TABLE TEST_TABLE --cluster by LINEAR(ARTICLE, ORDER_DATE)\n(\n ORDER_DATE DATE , \n ARTICLE VARCHAR(1555) ,\n note VARCHAR(1555)\n);\n\nalter table TEST_TABLE rename column ARTICLE to ARTICLE_new;\nalter table TEST_TABLE rename column ORDER_DATE to ORDER_DATE_new;\n"
},
{
"answer_id": 74590172,
"author": "Gokhan Atil",
"author_id": 12550965,
"author_profile": "https://Stackoverflow.com/users/12550965",
"pm_score": 1,
"selected": false,
"text": "alter table TEST_TABLE rename column ORDER_DATE to ORDERDATE;\n-- Cannot rename column 'ORDER_DATE' which belongs to a clustering key\n\nalter table TEST_TABLE DROP CLUSTERING KEY;\n\nalter table TEST_TABLE cluster by (ARTICLE, ORDERDATE);\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12304000/"
] |
74,577,631
|
<p>I have the following entities:</p>
<pre><code>public class Book {
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public int? AddedByUserId { get; set; }
public virtual ICollection<Author> Authors { get; set; } = new HashSet<Author>();
}
public class Author {
public int Id { get; set; }
public int BookId { get; set; }
public string Name { get; set; } = string.Empty;
public int? AddedByUserId { get; set; }
public Book Book { get; set; } = new Book();
}
</code></pre>
<p>I try to add an <code>Author</code> and set the <code>BookId</code> to an existing value.</p>
<pre><code>var newAuthor = new Author();
newAuthor.BookId = 1;
_dbContext.Authors.Add(author);
</code></pre>
<p>When I inspect the <code>ChangeTracker</code> to see what DbContext is going to do:</p>
<pre><code>var longView = _dbContext.ChangeTracker.DebugView.LongView;
</code></pre>
<p>It indicates that <code>Author</code>, <code>Book</code>, and <code>User</code> will all be added.</p>
<pre><code>Author {Id: -2147482646} **Added**
Id: -2147482646 PK Temporary
AddedByUserId: 1
DateAdded: '11/25/2022 8:22:11 PM'
Name: 'My Author Name'
BookId: -2147482643 FK Temporary
Book: {Id: -2147482643}
Book {Id: -2147482643} **Added**
Id: -2147482643 PK Temporary
AddedByUserId: -2147482645 FK Temporary
DateAdded: '1/1/0001 12:00:00 AM'
Name: ''
AddedByUserId: {Id: -2147482645}
User {Id: -2147482645} **Added**
Id: -2147482645 PK Temporary
DateAdded: '1/1/0001 12:00:00 AM'
Name: <null>
RowVersion: <null>
</code></pre>
<p>How can I do it so that only the new <code>Author</code> gets added when the <code>BookId</code> foreign key is set? Should I be setting objects instead of Ids?</p>
<pre><code>newAuthor.Book = _dbContext.Book.Find(1);
</code></pre>
|
[
{
"answer_id": 74577758,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 3,
"selected": true,
"text": "newAuthor.Book var newAuthor = new Author();\nnewAuthor.BookId = 1;\nnewAuthor.Book = null;\n var newAuthor = new Author();\nnewAuthor.Book.Id = 1;\n_dbContext.Books.Attach(newAuthor.Book);\n\n_dbContext.Authors.Add(author);\n"
},
{
"answer_id": 74578214,
"author": "flutebox",
"author_id": 19024203,
"author_profile": "https://Stackoverflow.com/users/19024203",
"pm_score": 1,
"selected": false,
"text": "new() public Book Book { get; set; } = new Book();\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20326571/"
] |
74,577,648
|
<p>I've been playing with various ways of using generics and have hit a road block.</p>
<p>Consider the following classes:</p>
<pre><code>public abstract class DataElement
{
public int Id { get; set; }
}
public class School : DataElement
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
public class Course : DataElement
{
public int Id { get; set; }
public int SchoolId { get; set; }
public string Name { get; set; } = string.Empty;
}
public class Student : DataElement
{
public int Id { get; set; }
public int CourseId { get; set; }
public string Name { get; set; } = string.Empty;
public string Phone { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
</code></pre>
<p>Considering a hypothetical scenario where none of this data changes, I'm trying to create a DataDictionary class to house those objects in their respective Lists all within one top-level List property. This crazy idea came to me, when I was writing code to load the different data types from JSON files. I was able to write one load method that could read all three types of data using generics, and that sent me down this particular rabbit hole.</p>
<pre><code>public interface IDataDictionary
{
public List<T> GetAllItemsFromList<T>();
public T GetSingleItemFromList<T>(int id);
}
public class DataDictionary : IDataDictionary
{
public List<IList> Data = new List<IList>();
// Return all objects from the list of type T
public List<T> GetAllItemsFromList<T>()
{
return Data.OfType<T>().ToList(); // This works, returning the appropriate list.
}
// Return specific object from the list of type T by Id property value
public T GetSingleItemFromList<T>(int id)
{
List<T> list = Data.OfType<List<T>>().First(); // This works, resolving to the correct list (e.g. Courses).
return list.Where(i => i.Id == id).First(); // This doesn't work. It doesn't appear to know about the Id property in this context.
}
}
</code></pre>
<p>GetAllItemsFromList works fine, returning the appropriate list of items</p>
<pre><code>List<School> newList = GetAllItemsFromList<School>();
</code></pre>
<p>However, I am unable to figure out how to return a single item by Id from its respective list.</p>
<pre><code>School newSchool = GetSingleItemFromList<School>(1);
</code></pre>
<p>It could be that I'm just trying to be too clever with this, but I can't help but think there is a way to do this, and I'm just missing it.</p>
|
[
{
"answer_id": 74577758,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 3,
"selected": true,
"text": "newAuthor.Book var newAuthor = new Author();\nnewAuthor.BookId = 1;\nnewAuthor.Book = null;\n var newAuthor = new Author();\nnewAuthor.Book.Id = 1;\n_dbContext.Books.Attach(newAuthor.Book);\n\n_dbContext.Authors.Add(author);\n"
},
{
"answer_id": 74578214,
"author": "flutebox",
"author_id": 19024203,
"author_profile": "https://Stackoverflow.com/users/19024203",
"pm_score": 1,
"selected": false,
"text": "new() public Book Book { get; set; } = new Book();\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62706/"
] |
74,577,651
|
<p>I am learning python and wanted to try and make a little script to handle "pulling names from a hat" to decide who has who for Christmas. I have no doubt that there is a more efficient way than this, but it works for the moment.</p>
<p>My issue is that it's taking a very inconsistent amount of time to complete. I can run this once, and it spits out the results instantly, but then the next time or few times it will just spin and I've let it sit for 5 minutes and it's still not complete.</p>
<p>Looking for some advice on why this is occurring and how to fix to make sure it doesn't take such a long time.</p>
<p>To start, I have two identical lists of the same names and then I shuffle them up:</p>
<pre><code>fam1 = ["name1", "name2", "name3", "name4", "name5", "name6", "name7"]
fam2 = ["name1", "name2", "name3", "name4", "name5", "name6", "name7"]
fam1_shuffled = random.sample(fam1, len(fam1))
fam2_shuffled = random.sample(fam2, len(fam2))
</code></pre>
<p>I then have a dictionary of name pairs that are not allowed (so that husband: wife and wife: husband from the same house don't pull each other's names for example):</p>
<pre><code>not_allowed_pairs = {
"name1": "name4",
"name4": "name1",
"name3": "name6",
"name6": "name3"
}
</code></pre>
<p>Then I have the function itself:</p>
<pre><code>def pick_names(list1, list2):
pairs = {}
gifters = list1
used_names = []
while len(pairs) < len(gifters):
for i in range(len(list1)):
if ((gifters[i] != list2[i]) & (list2[i] not in used_names)):
k = gifters[i]
v = list2[i]
if (k, v) not in non_allowed_pairs.items():
pairs[k] = v
used_names.append(v)
return pairs
</code></pre>
<p>Finally, just to separate it out, I have the following function to print out who picked who.</p>
<pre><code>def print_picks(pair_dict):
for k, v in pair_dict.items():
print(f"{k} picked: {v}")
</code></pre>
|
[
{
"answer_id": 74577758,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 3,
"selected": true,
"text": "newAuthor.Book var newAuthor = new Author();\nnewAuthor.BookId = 1;\nnewAuthor.Book = null;\n var newAuthor = new Author();\nnewAuthor.Book.Id = 1;\n_dbContext.Books.Attach(newAuthor.Book);\n\n_dbContext.Authors.Add(author);\n"
},
{
"answer_id": 74578214,
"author": "flutebox",
"author_id": 19024203,
"author_profile": "https://Stackoverflow.com/users/19024203",
"pm_score": 1,
"selected": false,
"text": "new() public Book Book { get; set; } = new Book();\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20074479/"
] |
74,577,658
|
<h2>I'd like to upgrade magento from 2.3.4 to 2.4.3.
But I cannot upgrade it.
this is error.</h2>
<p>Your requirements could not be resolved to an installable set of packages.</p>
<p>Problem 1
- Root composer.json requires magento/product-community-edition 2.4.3 -> satisfiable by magento/product-community-edition[2.4.3].
- magento/product-community-edition 2.4.3 requires php ~7.3.0||~7.4.0 -> your php version (7.2.34) does not satisfy that requirement.
Problem 2
- Root composer.json requires dealerdirect/phpcodesniffer-composer-installer ^0.5.0 -> satisfiable by dealerdirect/phpcodesniffer-composer-installer[v0.5.0].
- dealerdirect/phpcodesniffer-composer-installer v0.5.0 requires composer-plugin-api ^1.0 -> found composer-plugin-api[2.2.0] but it does not match the constraint.</p>
<h2>Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.</h2>
<h2>I am using cpanel now. In cpanel I set php version is 7.4</h2>
<h2>PHP 7.4.33 (cli) (built: Nov 10 2022 11:12:07) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.33, Copyright (c), by Zend Technologies</h2>
<p>what is the reason?</p>
|
[
{
"answer_id": 74577758,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 3,
"selected": true,
"text": "newAuthor.Book var newAuthor = new Author();\nnewAuthor.BookId = 1;\nnewAuthor.Book = null;\n var newAuthor = new Author();\nnewAuthor.Book.Id = 1;\n_dbContext.Books.Attach(newAuthor.Book);\n\n_dbContext.Authors.Add(author);\n"
},
{
"answer_id": 74578214,
"author": "flutebox",
"author_id": 19024203,
"author_profile": "https://Stackoverflow.com/users/19024203",
"pm_score": 1,
"selected": false,
"text": "new() public Book Book { get; set; } = new Book();\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19948367/"
] |
74,577,665
|
<p>I've just been debugging a slow SQL query.</p>
<p>It's a join between 2 tables, with a WHERE clause conditioning on either a property of 1 table OR the other.</p>
<p>If I re-write it as a UNION then it's suddenly 2 orders of magnitude faster, even though those 2 queries produce identical outputs:</p>
<pre><code>DECLARE @UserId UNIQUEIDENTIFIER = '0019813D-4379-400D-9423-56E1B98002CB'
SELECT *
FROM Bookings
LEFT JOIN BookingPricings ON Booking = Bookings.ID
WHERE (BookingPricings.[Owner] in (@UserId) OR Bookings.MixedDealBroker in (@UserId))
--Execution time: ~4000ms
SELECT *
FROM Bookings
LEFT JOIN BookingPricings ON Booking = Bookings.ID
WHERE (BookingPricings.[Owner] in (@UserId))
UNION
SELECT *
FROM Bookings
LEFT JOIN BookingPricings ON Booking = Bookings.ID
WHERE (Bookings.MixedDealBroker in (@UserId))
--Execution time: ~70ms
</code></pre>
<p>This seems rather surprising to me! I would have expected the SQL compiler to be entirely capable of identifying that the 2nd form was equivalent and would have used that compilation approach if it were available.</p>
<p>Some context notes:</p>
<ul>
<li>I've checked and <code>IN (@UserId)</code> vs <code>= @UserId</code> makes no difference.</li>
<li>Nor does <code>JOIN</code> vs <code>LEFT JOIN</code>.</li>
<li>Those tables each have 100,000s records, and the filter cuts it down to ~100.</li>
<li>In the slow version it seems to be reading every row of both tables.</li>
</ul>
<p>So:</p>
<ul>
<li>Does anyone have any ideas for how this comes about.</li>
<li>What (if anything) can I do to fix the performance without just re-writing the query as a series of <code>UNIONs</code> (not viable for a variety of reasons.)</li>
</ul>
<p>=-=-=-=-=-=-=</p>
<p>Execution Plans:
<a href="https://i.stack.imgur.com/SPWBa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SPWBa.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74577843,
"author": "J.D.",
"author_id": 5059085,
"author_profile": "https://Stackoverflow.com/users/5059085",
"pm_score": 2,
"selected": false,
"text": "OR OR UNION Bookings UNION"
},
{
"answer_id": 74578149,
"author": "T N",
"author_id": 12637193,
"author_profile": "https://Stackoverflow.com/users/12637193",
"pm_score": 1,
"selected": false,
"text": "OR SELECT <complex select list>\nFROM (\n SELECT Bookings.ID AS BookingsID, BookingPricings.ID AS BookingPricingsID\n FROM Bookings\n LEFT JOIN BookingPricings ON Booking = Bookings.ID\n WHERE (BookingPricings.[Owner] in (@UserId))\n UNION\n SELECT Bookings.ID AS BookingsID, BookingPricings.ID AS BookingPricingsID\n FROM Bookings B\n LEFT JOIN BookingPricings ON Booking = Bookings.ID\n WHERE (Bookings.MixedDealBroker in (@UserId))\n) PRE\nJOIN Bookings B ON B.ID = PRE.BookingsID\nJOIN BookingPricings BP ON BP.ID = PRE.BookingPricingsID\n<more joins>\nWHERE <more conditions>\n AND Bookings.MixedDealBroker <> @UserId"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1662268/"
] |
74,577,671
|
<p>I have an WPF usercontrol which is used in a winforms applications. WPF usercontrol is contained within an ElementHost container.</p>
<p>This WPF usercontrol has some images, button with images, labels, etc.</p>
<p>I have a dictionary with some geometries, the following is one of them.</p>
<pre><code> <Geometry x:Key="hlpGeometry">F0 M22,22z M0,0z M11,22C17.0751,22 22,17.0751 22,11 22,4.92487 17.0751,0 11,0 4.92487,0 0,4.92487 0,11 0,17.0751 4.92487,22 11,22z M12.1901,16.6889L10.2662,16.6889 10.2662,18.6998 12.1901,18.6998 12.1901,16.6889z M8.18758,5.59005C7.40125,6.43439,7.00808,7.55265,7.00808,8.94484L8.72898,8.94484C8.76121,8.10695 8.89334,7.46564 9.12537,7.02091 9.53787,6.2217 10.2823,5.82209 11.3587,5.82209 12.2288,5.82209 12.8508,6.05412 13.2246,6.51818 13.6049,6.98224 13.795,7.53009 13.795,8.16173 13.795,8.61291 13.6661,9.04797 13.4083,9.46691 13.2665,9.70539 13.0796,9.9342 12.8475,10.1533L12.0741,10.9171C11.3329,11.6454 10.8527,12.2932 10.6336,12.8604 10.4144,13.4211 10.3049,14.1623 10.3049,15.084L12.0258,15.084C12.0258,14.2719 12.116,13.6596 12.2965,13.2471 12.4834,12.8281 12.8862,12.319 13.505,11.7195 14.3557,10.8945 14.9197,10.2694 15.1969,9.84396 15.4804,9.41857 15.6222,8.86427 15.6222,8.18107 15.6222,7.05314 15.2387,6.12824 14.4718,5.40636 13.7112,4.67804 12.6961,4.31388 11.4263,4.31388 10.0535,4.31388 8.9739,4.73927 8.18758,5.59005z</Geometry>
<DrawingGroup x:Key="hlpDrawingGroup" ClipGeometry="M0,0 V22 H22 V0 H0 Z">
<GeometryDrawing Brush="#FF00AA2B" Geometry="{StaticResource hlpGeometry}" />
</DrawingGroup>
<DrawingImage x:Key="ico_helpDrawingImage" Drawing="{StaticResource hlpDrawingGroup}" />
</code></pre>
<p>I have an WPF Image and I bound above DrawingImage to it using the Source attribute. I bind the source attribute to a property in the view model.</p>
<p>Something like below:</p>
<pre><code><Image x:Name="MyImage"
Height="24"
Width="24"
VerticalAlignment="Center"
Source="{Binding Path=MyIcon}"/>
</code></pre>
<p>It is working fine when windows is scaled to 100% but when scaled to a higher one, let's say, 125%, then the image gets fuzzy.</p>
<p>Also the image look like gets bigger than 24x24 and it is being cut-off when I set a scale greater than 100% (125%).</p>
<p>How can I make image to not get fuzzy and set image to always be the same size 24x24?</p>
|
[
{
"answer_id": 74577843,
"author": "J.D.",
"author_id": 5059085,
"author_profile": "https://Stackoverflow.com/users/5059085",
"pm_score": 2,
"selected": false,
"text": "OR OR UNION Bookings UNION"
},
{
"answer_id": 74578149,
"author": "T N",
"author_id": 12637193,
"author_profile": "https://Stackoverflow.com/users/12637193",
"pm_score": 1,
"selected": false,
"text": "OR SELECT <complex select list>\nFROM (\n SELECT Bookings.ID AS BookingsID, BookingPricings.ID AS BookingPricingsID\n FROM Bookings\n LEFT JOIN BookingPricings ON Booking = Bookings.ID\n WHERE (BookingPricings.[Owner] in (@UserId))\n UNION\n SELECT Bookings.ID AS BookingsID, BookingPricings.ID AS BookingPricingsID\n FROM Bookings B\n LEFT JOIN BookingPricings ON Booking = Bookings.ID\n WHERE (Bookings.MixedDealBroker in (@UserId))\n) PRE\nJOIN Bookings B ON B.ID = PRE.BookingsID\nJOIN BookingPricings BP ON BP.ID = PRE.BookingPricingsID\n<more joins>\nWHERE <more conditions>\n AND Bookings.MixedDealBroker <> @UserId"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1624552/"
] |
74,577,695
|
<p>I am trying to create a button for my personal portfolio website that allows users to download my CV from clicking on a button. I am not sure went wrong in my HTML5 file. Right now, when the button is clicked on, it simply opens up the CV on a new page.</p>
<pre><code><div class="d-block d-sm-flex align-items-center"><a class="btn content-download button-main button-scheme" href="resume/BenZhaoResumeSWE.pdf" download="" role="button">Download CV</a>
</code></pre>
<p>Let me know if further context around the code is needed. Here is what the frontend looks like the on webpage so far. <a href="https://i.stack.imgur.com/cLmS5.jpg" rel="nofollow noreferrer">The button itself is there and clicking on opens up a new webpage with the CV instead of downloading it.</a>](<a href="https://i.stack.imgur.com/cLmS5.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/cLmS5.jpg</a>)</p>
<p>I tried using the above line of code and expected it to download the CV straight from the webpage. Instead it opens up a new page with the CV. Is this simply because I have not yet put the webpage on a host domain or is this a coding issue?</p>
|
[
{
"answer_id": 74577843,
"author": "J.D.",
"author_id": 5059085,
"author_profile": "https://Stackoverflow.com/users/5059085",
"pm_score": 2,
"selected": false,
"text": "OR OR UNION Bookings UNION"
},
{
"answer_id": 74578149,
"author": "T N",
"author_id": 12637193,
"author_profile": "https://Stackoverflow.com/users/12637193",
"pm_score": 1,
"selected": false,
"text": "OR SELECT <complex select list>\nFROM (\n SELECT Bookings.ID AS BookingsID, BookingPricings.ID AS BookingPricingsID\n FROM Bookings\n LEFT JOIN BookingPricings ON Booking = Bookings.ID\n WHERE (BookingPricings.[Owner] in (@UserId))\n UNION\n SELECT Bookings.ID AS BookingsID, BookingPricings.ID AS BookingPricingsID\n FROM Bookings B\n LEFT JOIN BookingPricings ON Booking = Bookings.ID\n WHERE (Bookings.MixedDealBroker in (@UserId))\n) PRE\nJOIN Bookings B ON B.ID = PRE.BookingsID\nJOIN BookingPricings BP ON BP.ID = PRE.BookingPricingsID\n<more joins>\nWHERE <more conditions>\n AND Bookings.MixedDealBroker <> @UserId"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19311334/"
] |
74,577,699
|
<p>I am trying to understand why first code run only once vs second code is running until it checks all the items in the list.</p>
<p>1.</p>
<pre><code>def get_word_over_10_char(list_of_words):
for word in list_of_words:
if len(word) > 10:
return word
else:
return ""
</code></pre>
<ol start="2">
<li></li>
</ol>
<pre><code>for word in list_of_words:
if len(word) > 10:
return word
return ''
</code></pre>
<p>word_list = ['soup', 'parameter', 'intuition', 'house-maker', 'fabrication']</p>
<p>Trying to return a word if length is more than 10, and return empty string if less than equal to 10.</p>
|
[
{
"answer_id": 74577755,
"author": "Timo",
"author_id": 12888866,
"author_profile": "https://Stackoverflow.com/users/12888866",
"pm_score": 1,
"selected": false,
"text": "return return if else list_of_words return word list_of_words"
},
{
"answer_id": 74578067,
"author": "Anton B",
"author_id": 15870626,
"author_profile": "https://Stackoverflow.com/users/15870626",
"pm_score": 0,
"selected": false,
"text": "return return def get_word_over_10_char(list_of_words):\n more_than_10 = []\n for word in list_of_words:\n if len(word) > 10:\n more_than_10.append(word)\n if len(more_than_10)==0:\n return \"Nothing longer than 10\"\n return more_than_10\n \nword_list = ['soup', 'parameter', 'intuition', 'house-maker', 'fabrication']\n\nprint(get_word_over_10_char(word_list))\n more_than_10 def get_word_over_10_char_v2(list_of_words):\n more_than_10 = [word for word in list_of_words if len(word) > 10]\n if len(more_than_10)==0:\n return \"Nothing longer than 10\"\n return more_than_10\n \nword_list = ['soup', 'parameter', 'intuition', 'house-maker', 'fabrication']\n\nprint(get_word_over_10_char_v2(word_list))\n\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20602484/"
] |
74,577,701
|
<p><strong>Note:</strong></p>
<p>Please note that I have tried the following to solve my problem before posting:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/11322801/transpose-reshape-dataframe-without-timevar-from-long-to-wide-format">Transpose / reshape dataframe without "timevar" from long to wide format</a></li>
<li><a href="https://stackoverflow.com/questions/64216839/how-to-reshape-long-to-wide-while-preserving-some-variables-in-r">How to Reshape Long to Wide While Preserving Some Variables in R</a></li>
<li><a href="https://stackoverflow.com/questions/10589693/convert-data-from-long-format-to-wide-format-with-multiple-measure-columns">Convert data from long format to wide format with multiple measure columns</a></li>
</ul>
<p>to try to solve my problem, but haven't been successful</p>
<p><strong>Problem</strong></p>
<p>Suppose I have the following data that shows the way that items have flowed from a start to an end</p>
<pre><code>> run = c(1, 2, 3, 3, 4, 5, 5, 5, 6, 7, 7, 7, 8, 9, 10, 10, 11)
> start_location = c("A", "C", "A", "B", "A", "B", "C", "A", "B", "C", "B", "A", "A", "A", "A", "B", "C")
> end_location = c("B", "B", "B", "C", "C", "C", "A", "C", "A", "B", "A", "C", "B", "C", "B", "C", "B")
> df = data.frame(run, start_site, end_site)
> df
run start_site end_site
1 1 A B
2 2 A C
3 3 A B
4 3 B C
5 4 A C
6 5 B C
7 5 C A
8 5 A C
9 6 B A
10 7 C B
11 7 B A
12 7 A C
13 8 A B
14 9 A C
15 10 A B
16 10 B C
17 11 C B
</code></pre>
<p>I would like to convert the data into a "wide" format that looks like the following, with a new column for every instance of a stage by the run.</p>
<pre><code>> # Desired result
run first_location second_location third_location fourth_location
[1,] "1" "A" "B" NA NA
[2,] "2" "C" "B" NA NA
[3,] "3" "A" "B" "C" NA
[4,] "4" "A" "C" NA NA
[5,] "5" "B" "C" "A" "C"
[6,] "6" "C" "A" NA NA
[7,] "7" "C" "B" "A" "C"
[8,] "8" "A" "B" NA NA
[9,] "9" "A" "C" NA NA
[10,] "10" "A" "B" "C" NA
[11,] "11" "C" "B" NA NA
</code></pre>
<p><strong>Attempted Solution</strong></p>
<p>I have tried the following but I haven't got the desired result. I have more columns than I need.</p>
<pre><code>> library(dplyr)
> library(tidyr)
>
> # Unsuccessful attempt
> df_long = melt(df, id.vars=c("run"))
> df_long %>%
select(!variable) %>%
group_by(run) %>%
dplyr::mutate(rn = paste0("location_",row_number())) %>%
spread(rn, value)
# A tibble: 11 x 7
# Groups: run [11]
run location_1 location_2 location_3 location_4 location_5 location_6
<dbl> <chr> <chr> <chr> <chr> <chr> <chr>
1 1 A B NA NA NA NA
2 2 A C NA NA NA NA
3 3 A B B C NA NA
4 4 A C NA NA NA NA
5 5 B C A C A C
6 6 B A NA NA NA NA
7 7 C B A B A C
8 8 A B NA NA NA NA
9 9 A C NA NA NA NA
10 10 A B B C NA NA
11 11 C B NA NA NA NA
</code></pre>
<p>Can someone help me figure out my mistake and help me get the desired output please?</p>
<p>Thank you for looking at my post.</p>
|
[
{
"answer_id": 74577755,
"author": "Timo",
"author_id": 12888866,
"author_profile": "https://Stackoverflow.com/users/12888866",
"pm_score": 1,
"selected": false,
"text": "return return if else list_of_words return word list_of_words"
},
{
"answer_id": 74578067,
"author": "Anton B",
"author_id": 15870626,
"author_profile": "https://Stackoverflow.com/users/15870626",
"pm_score": 0,
"selected": false,
"text": "return return def get_word_over_10_char(list_of_words):\n more_than_10 = []\n for word in list_of_words:\n if len(word) > 10:\n more_than_10.append(word)\n if len(more_than_10)==0:\n return \"Nothing longer than 10\"\n return more_than_10\n \nword_list = ['soup', 'parameter', 'intuition', 'house-maker', 'fabrication']\n\nprint(get_word_over_10_char(word_list))\n more_than_10 def get_word_over_10_char_v2(list_of_words):\n more_than_10 = [word for word in list_of_words if len(word) > 10]\n if len(more_than_10)==0:\n return \"Nothing longer than 10\"\n return more_than_10\n \nword_list = ['soup', 'parameter', 'intuition', 'house-maker', 'fabrication']\n\nprint(get_word_over_10_char_v2(word_list))\n\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8447442/"
] |
74,577,740
|
<p>I have an Msbuild project and a solution with 20 projects. This needs to compile both under VS and under dotnet cli (w/o special arguments)</p>
<p>Some of the projects are on the root of the solution and others are in sub folders:</p>
<pre><code>SolutionRoot
/Proj1
/Proj2
/Tests
/Proj1Tests
/Proj2Tests
/shared
CommonSettings.target
</code></pre>
<p>I have an Imported target file which contains a bunch of rules, GlobalSupressions that are shared among the products:</p>
<pre><code><Project>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup>
<WarningsNotAsErrors>618, 672</WarningsNotAsErrors>
<NoWarn>1701;1702;AD0001;CA5394</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference .../>
</ItemGroup>
<ItemGroup>
<Compile Include="..\shared\GlobalSuppressions.cs" Link="GlobalSuppressions.cs" />
</ItemGroup>
</Project>
</code></pre>
<p>However, this will not work for the projects in the subfolders because the path is relative to the loading project. To make it work there, I'd need `....\shared\CommonSettings.target</p>
<p>How can I make this work across sub-folders?</p>
<p>I can make this work in VS by using $(SolutionDir), but for msbuild, I am not sure.</p>
|
[
{
"answer_id": 74577755,
"author": "Timo",
"author_id": 12888866,
"author_profile": "https://Stackoverflow.com/users/12888866",
"pm_score": 1,
"selected": false,
"text": "return return if else list_of_words return word list_of_words"
},
{
"answer_id": 74578067,
"author": "Anton B",
"author_id": 15870626,
"author_profile": "https://Stackoverflow.com/users/15870626",
"pm_score": 0,
"selected": false,
"text": "return return def get_word_over_10_char(list_of_words):\n more_than_10 = []\n for word in list_of_words:\n if len(word) > 10:\n more_than_10.append(word)\n if len(more_than_10)==0:\n return \"Nothing longer than 10\"\n return more_than_10\n \nword_list = ['soup', 'parameter', 'intuition', 'house-maker', 'fabrication']\n\nprint(get_word_over_10_char(word_list))\n more_than_10 def get_word_over_10_char_v2(list_of_words):\n more_than_10 = [word for word in list_of_words if len(word) > 10]\n if len(more_than_10)==0:\n return \"Nothing longer than 10\"\n return more_than_10\n \nword_list = ['soup', 'parameter', 'intuition', 'house-maker', 'fabrication']\n\nprint(get_word_over_10_char_v2(word_list))\n\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/594571/"
] |
74,577,761
|
<p>I have a df with a column that some values are having <code>...</code> and some <code>..</code> and some are without dots.</p>
<pre><code> Type range
Mike 10..13
Ni 3..4
NANA 2...3
Gi 2
</code></pre>
<p>desired output should look like this</p>
<pre><code>Type range
Mike 10
Mike 11
Mike 12
MIke 13
Ni 3
Ni 4
NANA 2
NANA 3
Gi 2
</code></pre>
<p>So dots represnt the range of between to number ( inclusive the end number).</p>
<p>How am I suppsoed to do it in pandas?</p>
|
[
{
"answer_id": 74577830,
"author": "Psidom",
"author_id": 4983450,
"author_profile": "https://Stackoverflow.com/users/4983450",
"pm_score": 3,
"selected": true,
"text": "import re\ndef str_to_list(s):\n if not s: return []\n nums = re.split('\\.{2,3}', s)\n if len(nums) == 1:\n return nums\n return list(range(int(nums[0]), int(nums[1]) + 1))\n\ndf['range'] = df['range'].astype(str).map(str_to_list)\ndf.explode('range')\n\n Type range\n0 Mike 10\n0 Mike 11\n0 Mike 12\n0 Mike 13\n1 Ni 3\n1 Ni 4\n2 NANA 2\n2 NANA 3\n3 Gi 2\n"
},
{
"answer_id": 74577956,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 0,
"selected": false,
"text": "numpy.arange pandas.DataFrame.explode out = (\n df\n .assign(range=\n df[\"range\"]\n .str.replace(\"\\.+\", \"-\", regex=True)\n .str.split(\"-\")\n .apply(lambda x: np.arange(list(map(int, x))[0], list(map(int, x))[-1]+1, 1) if len(x)>1 else x))\n .explode(\"range\", ignore_index=True)\n )\n print(out)\n\n Type range\n0 Mike 10\n1 Mike 11\n2 Mike 12\n3 Mike 13\n4 Ni 3\n5 Ni 4\n6 NANA 2\n7 NANA 3\n8 Gi 2\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17561414/"
] |
74,577,765
|
<p>I have a question reagarding my code, if anybody has some clues how to solve it. I need to write only one line of code, which outputs the line numbers of those lines that don´t include spaces between the words. My attempt was the following:</p>
<pre><code>[line for line in range(len(open('test.txt').readlines())) if ' ' not in open('test.txt').readlines(line)]
</code></pre>
<p>I tried to use enumerate. But it didn`t work out as I intended. I would appreciate any clue on how to change my code, if anything of my code is correct.</p>
|
[
{
"answer_id": 74577977,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 2,
"selected": false,
"text": "lines = []\n\nfor line in range(len(open('test.txt').readlines()):\n if ' ' not in open('test.txt').readlines(line):\n lines.append(line)\n readlines() enumerate() (index, value) for num, line in enumerate(open('test.txt')):\n if ' ' not in line:\n lines.append(num)\n"
},
{
"answer_id": 74577978,
"author": "Swifty",
"author_id": 20267366,
"author_profile": "https://Stackoverflow.com/users/20267366",
"pm_score": 2,
"selected": true,
"text": "print([i for i,line in (enumerate(open(\"test.txt\").readlines())) if \" \" not in line])\n apricot\na p p l e\nmango\nbanana\nche rry\n [0, 2, 3]\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20594803/"
] |
74,577,766
|
<p>I have a dictionary with multiple keys, and multiple values per key (sometimes). The dictionary is zipped from two lists which I've pulled from an excel sheet using pandas. I've converted the values to integers. My dictionary looks like this:</p>
<pre><code>dictionary = {'A223':[1,4,5],'B224':[7,8,9],'A323':[4,5],'B456':[3,3,4,5] }
</code></pre>
<p>What I need now is to modify the dictionary so that each Key only shows the min value. So desired output would look like this:</p>
<pre><code>dictionary = {'A223':1,'B224':7,'A323':4,'B456':3}
</code></pre>
<p>I can return the key with the lowest value, however this doesn't help me.</p>
<p>Here is my code thus far:</p>
<pre><code>df = pd.read_excel(PT, sheet_name= "Permit Tracker")
permit_list = ['1.Planning', '2.Survey Complete', '3.Design Complete', '4.Permit Submitted', '5.Permit Approved','6.IFC', '7.As-Built', '8.On-Hold', '9.Cancelled'] #original values column, to be converted to int.
dicto = {
'1.Planning': 1, '2.Survey Complete': 2, '3.Design Complete': 3, '4.Permit Submitted': 4, '5.Permit Approved': 5,
'6.IFC': 6, '7.As-Built': 7, '8.On-Hold': 8, '9.Cancelled': 9
}
new_int = [dicto[k] for k in permit_list]
dfint = df['Permit Status'].dropna().tolist()
dfkeys = df['RPATS#'] #this is the keys column in my excel sheet
new_conversion = [dicto[k] for k in dfint]
dictionary = {}
for i, j in zip(dfkeys,new_conversion):
dictionary.setdefault(i, []).append(j)
print(dictionary)
</code></pre>
<p>My steps thus far:
1 - read excel into df with the two columns I need
2 - Convert string values in values column into int.
3 - Create a list for values column, dropping na
4 - zipping together keys and values, customizing a dictionary to accept multiple values per key.</p>
<p>I'm new, and really at a loss here. Any help would be very much appreciated!</p>
<p>I have tried something like:</p>
<pre><code>dictionary = {'A223':[1,4,5],'B224':[7,8,9,],'A323':[4,5],'B456':[3,3,4,5] }
min(dictionary, key=dictionary.get)
</code></pre>
<p>Although this only, and obviously, returns the key with the lowest value.</p>
|
[
{
"answer_id": 74577787,
"author": "Grzegorz Skibinski",
"author_id": 11610186,
"author_profile": "https://Stackoverflow.com/users/11610186",
"pm_score": 3,
"selected": true,
"text": ">>> dictionary\n{'A223': [1, 4, 5], 'B224': [7, 8, 9], 'A323': [4, 5], 'B456': [3, 3, 4, 5]}\n>>> dict(map(lambda x: (x[0], min(x[1])), dictionary.items()))\n{'A223': 1, 'B224': 7, 'A323': 4, 'B456': 3}\n"
},
{
"answer_id": 74577928,
"author": "user19077881",
"author_id": 19077881,
"author_profile": "https://Stackoverflow.com/users/19077881",
"pm_score": 1,
"selected": false,
"text": "newdic = {key: min(value) for key, value in dictionary.items()}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19164227/"
] |
74,577,769
|
<p>A customer has multiple resource groups in Azure with multiple virtual networks and many private DNS zones to enable private endpoints. Some of the private DNS zones are in different resource groups, but with the same domain name (e.g. privatelink.azurewebsites.net).
I have some virtual networks, where I want to know what private DNS zones are connected to them via Virtual network links.</p>
<p>I have a list of the virtual networks that are connected to a specific private DNS zone, but I don't see the corresponding list at the virtual network. Is there a list inside the portal where I can see the Virtual network links?</p>
|
[
{
"answer_id": 74639678,
"author": "dbgalz11",
"author_id": 18746184,
"author_profile": "https://Stackoverflow.com/users/18746184",
"pm_score": 1,
"selected": false,
"text": "\n$subscriptionId = your subscription ID\"\nSet-AzContext -SubscriptionId $subscriptionId\n$subName = \"your Subscription Name\"\n\n$reportName1 = \"PrivateDNSZone.csv\"\nSelect-AzSubscription $subscriptionId\n$report = @()\n$Zones = Get-AzPrivateDnsZone\nforeach ($zone in $Zones){ \n $vnet_link = Get-AzPrivateDnsVirtualNetworkLink -ResourceGroupName $zone.ResourceGroupName -ZoneName $zone.Name\n $record_set = Get-AzPrivateDnsRecordSet -ResourceGroupName $zone.ResourceGroupName -ZoneName $zone.Name\n foreach ($record in $record_set){\n foreach ($link in $vnet_link){ \n $info = \"\" | Select Subscription, ResourceGroupName, PrivateDNSZoneName, RecordSet, RecordType, Records, Ttl, IsAutoRegistered, VnetLinkName, VnetLinkId, RegistrationEnabled, VirtualNetworkLinkState, ProvisioningState\n $info.Subscription = $subName\n $info.ResourceGroupName = $zone.ResourceGroupName\n #$info.Location = $zone.Location\n $info.PrivateDNSZoneName = $zone.Name\n\n $info.RecordSet = $record.Name\n $info.RecordType = $record.RecordType\n if ($record.RecordType -eq 'A'){\n $info.Records = $record.Records.Ipv4Address -join \",\"\n }\n elseif ($record.RecordType -eq 'CNAME'){\n $info.Records = $record.Records.Cname -join \",\"\n }\n elseif ($record.RecordType -eq 'SOA') {\n $info.Records = $record.Records.Host -join \",\"\n }\n else{\n $info.Records = $record.Records\n }\n $info.Ttl = $record.Ttl\n $info.IsAutoRegistered = $record.IsAutoRegistered\n\n $info.VnetLinkName = $link.Name \n $info.VnetLinkId = $link.VirtualNetworkId\n $info.RegistrationEnabled = $link.RegistrationEnabled\n $info.VirtualNetworkLinkState = $link.VirtualNetworkLinkState\n $info.ProvisioningState = $link.ProvisioningState\n\n $report += $info \n }\n }\n}\n$report | ft Subscription, ResourceGroupName, PrivateDNSZoneName, RecordSet, RecordType, Records, Ttl, IsAutoRegistered, VnetLinkName, VnetLinkId, RegistrationEnabled, VirtualNetworkLinkState, ProvisioningState\n$report | Export-CSV \"$reportName1\" -Encoding Default\n\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456886/"
] |
74,577,791
|
<p>I have this table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>subs_id</th>
<th>amount</th>
<th>flag</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>15</td>
<td>target</td>
</tr>
<tr>
<td>1</td>
<td>10</td>
<td>taker</td>
</tr>
<tr>
<td>2</td>
<td>30</td>
<td>target</td>
</tr>
<tr>
<td>3</td>
<td>20</td>
<td>taker</td>
</tr>
<tr>
<td>3</td>
<td>10</td>
<td>target</td>
</tr>
</tbody>
</table>
</div>
<p>I want to create a new table that does the following:</p>
<ol>
<li>calculate the total sum of the variable amount by each subs_id</li>
<li>a column that just shows the value of the variable amount when the subs_id has the variable flag equal to "taker", and 0 otherwise.</li>
</ol>
<p>The resulting table should look like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>subs_id</th>
<th>ttl_amount</th>
<th>amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>25</td>
<td>10</td>
</tr>
<tr>
<td>2</td>
<td>30</td>
<td>0</td>
</tr>
<tr>
<td>3</td>
<td>30</td>
<td>20</td>
</tr>
</tbody>
</table>
</div>
<p>Here is what I tried to get the result:</p>
<pre><code>df%>%
group_by(subs_id)%>%
summarise(ttl_amount=sum(amt),
amount=case_when(flag=="taker"~amt[which(flag=="taker")[1]],TRUE~0))
</code></pre>
<p>This gives the following error:
! 'names' attribute [1] must be the same length as the vector [0]</p>
<p>Note that the solution should preferably be using summarise, as multiple other aggregation will happen in it.</p>
|
[
{
"answer_id": 74577852,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "left_join amount library(tidyverse)\n\nt <- tibble(subs_id=c(1,1,2,3,3),\n amount=c(15,10,30,20,10),\n flag=c(\"target\", \"taker\", \"target\", \"taker\", \"target\"))\n\nt %>%\n group_by(subs_id)%>%\n summarise(ttl_amount=sum(amount)) %>%\n left_join(select(filter(t, flag==\"taker\"), \"subs_id\", \"amount\", \"flag\"), by=\"subs_id\") %>%\n select(-flag) %>%\n replace_na(list(amount=0))\n subs_id ttl_amount amount\n1 25 10 \n2 30 0 \n3 30 20 \n"
},
{
"answer_id": 74577866,
"author": "Cameron",
"author_id": 14306416,
"author_profile": "https://Stackoverflow.com/users/14306416",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\nsubs_id <- c(1, 1, 2, 3, 3)\namount <- c(15, 10, 30, 20, 10)\nflag <- c(\"target\", \"taker\", \"target\", \"taker\", \"target\")\n\ndata <- data.frame(subs_id, amount, flag)\n\ndata_new <- data %>% group_by(subs_id) %>% \n mutate(column_summary = sum(amount))\n\ndata_new$column_id <- ifelse(data_new$flag == \"taker\", data_new$amount, 0)\n"
},
{
"answer_id": 74577911,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n group_by(subs_id) %>% \n summarize(\n ttl_amount = sum(amount), \n amount = sum(amount * (flag == \"taker\"))\n )\n # A tibble: 3 × 3\n subs_id ttl_amount amount\n <dbl> <dbl> <dbl>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74577912,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 3,
"selected": true,
"text": "df %>%\n group_by(subs_id) %>%\n summarise(\n ttl_amount = sum(amount),\n amount = coalesce(amount[flag == 'taker'][1L], 0L)\n )\n # A tibble: 3 x 3\n subs_id ttl_amount amount\n <int> <int> <int>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74578098,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf |>\n group_by(subs_id) |>\n summarise(\n ttl_amount = sum(amount),\n amount= sum(amount[flag == \"taker\"]))\n#> # A tibble: 3 x 3\n#> subs_id ttl_amount amount\n#> <dbl> <dbl> <dbl>\n#> 1 1 25 10\n#> 2 2 30 0\n#> 3 3 30 20\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8758029/"
] |
74,577,795
|
<p>So for context, there is a popular problem called the "Fibbonaci Clock." Essentially, you have a list of colors, for example ["white","blue","red","green","white"]. The first item in the list holds a value, of 1, then the second holds again a value of 1, the third holds a value of 2, the fourth holds a value of 3, and the 5th holds a value of 5. [1,1,2,3,5]. To find the time of ["white","blue","red","green","white"], you would add the values of Red and Blue to get the hour, and do 5*(Green + Blue) for the minutes. In this case, the blue color is in the second box, meaning it holds a value of 1, and the red value is in the third box, meaning it holds a value of 2. so 1 + 2 = 3, so the hour is 3. The minute is 5*(G + B), green is in the 4th slot, holding a value of 3, and blue is in the second spot, holding a value of 1. 5(3 + 1) = 5(4) = 20. So the time is 3:20.</p>
<p>So I'm trying to write a program for this, but I have a problem. There can be repeats of Red, Green, and Blue. For example, ["Red","Red","Blue","Green","White]. In this case, when adding Red and Blue, you would have to add both values of Red, and Blue. This is where I'm confused on how to code it.</p>
<p>This is my code:</p>
<pre><code>x = [1,1,2,3,5]
y = []
r = []
for t in range(1,6,1):
print("give me a color")
s = input()
y.append(s)
if "r" in y:
if "b" in y:
if "g" in y:
r_index = y.index("r")
r_index2 = y.index("b")
r_index3 = y.index("g")
r.append(r_index)
r.append(r_index2)
if r_index == 0:
r_index = 1
if r_index == 4:
r_index = 5
if r_index2 == 0:
r_index2 = 1
if r_index2 == 4:
r_index2 = 5
hour = int(r_index) + int(r_index2)
minute = 5*(r_index2 + r_index3)
print("The final time is",hour,":",minute)
</code></pre>
<p>If there are ever repeats of Red, Green, Or Blue, my code only adds the smallest value, resulting in the wrong time.</p>
<p>I would appreciate an answer on how to fix this, and a fixed code</p>
|
[
{
"answer_id": 74577852,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "left_join amount library(tidyverse)\n\nt <- tibble(subs_id=c(1,1,2,3,3),\n amount=c(15,10,30,20,10),\n flag=c(\"target\", \"taker\", \"target\", \"taker\", \"target\"))\n\nt %>%\n group_by(subs_id)%>%\n summarise(ttl_amount=sum(amount)) %>%\n left_join(select(filter(t, flag==\"taker\"), \"subs_id\", \"amount\", \"flag\"), by=\"subs_id\") %>%\n select(-flag) %>%\n replace_na(list(amount=0))\n subs_id ttl_amount amount\n1 25 10 \n2 30 0 \n3 30 20 \n"
},
{
"answer_id": 74577866,
"author": "Cameron",
"author_id": 14306416,
"author_profile": "https://Stackoverflow.com/users/14306416",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\nsubs_id <- c(1, 1, 2, 3, 3)\namount <- c(15, 10, 30, 20, 10)\nflag <- c(\"target\", \"taker\", \"target\", \"taker\", \"target\")\n\ndata <- data.frame(subs_id, amount, flag)\n\ndata_new <- data %>% group_by(subs_id) %>% \n mutate(column_summary = sum(amount))\n\ndata_new$column_id <- ifelse(data_new$flag == \"taker\", data_new$amount, 0)\n"
},
{
"answer_id": 74577911,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n group_by(subs_id) %>% \n summarize(\n ttl_amount = sum(amount), \n amount = sum(amount * (flag == \"taker\"))\n )\n # A tibble: 3 × 3\n subs_id ttl_amount amount\n <dbl> <dbl> <dbl>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74577912,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 3,
"selected": true,
"text": "df %>%\n group_by(subs_id) %>%\n summarise(\n ttl_amount = sum(amount),\n amount = coalesce(amount[flag == 'taker'][1L], 0L)\n )\n # A tibble: 3 x 3\n subs_id ttl_amount amount\n <int> <int> <int>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74578098,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf |>\n group_by(subs_id) |>\n summarise(\n ttl_amount = sum(amount),\n amount= sum(amount[flag == \"taker\"]))\n#> # A tibble: 3 x 3\n#> subs_id ttl_amount amount\n#> <dbl> <dbl> <dbl>\n#> 1 1 25 10\n#> 2 2 30 0\n#> 3 3 30 20\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13995670/"
] |
74,577,832
|
<p>I'm applying vgg16 as feature extraction method, However my instructor require a high recall. (90%-95%). I will explain about my dataset my data are labeled videos of traffic sign in a foggy weather (they are labeled as visible, not visible, poor viability) I extracted frames from the video as image and randomly stored the data in training & test/val folder
I'm trying to apply deep learning to classify the images. As you can see my model is doing good but not very good. I can't get more videos from my instructor.</p>
<ul>
<li><p>How can I possibly improve my model?</p>
</li>
<li><p>can I add more layers to my model?</p>
</li>
<li><p>can I feed feature extraction base model to a conv2d model that I
create?</p>
</li>
<li><p>can I apply feed feature extraction from vgg16 to transfer learning ?</p>
</li>
<li><p>How can I feed feature extraction vgg16 to svm?</p>
</li>
</ul>
<pre><code>
BATCH = 50
IMG_WIDTH = 224
IMG_HEIGHT = 224
from keras.applications import VGG16
conv_base = VGG16(weights='imagenet',
include_top=False,
input_shape=(IMG_HEIGHT, IMG_WIDTH, 3)) # This is the Size of the image
conv_base.trainable= False
datagen = ImageDataGenerator(rescale=1.0/255.0
# ,brightness_range=(1,1.5),
# zoom_range=0.1,
# rotation_range=45,
# horizontal_flip=True,
# vertical_flip=True,
)
train = datagen.flow_from_directory(train_path
,class_mode='categorical'
,batch_size = BATCH
,target_size=(IMG_HEIGHT, IMG_WIDTH))
#test data val = datagen.flow_from_directory(val_path
,class_mode='categorical'
,batch_size = BATCH
,target_size=(IMG_HEIGHT, IMG_WIDTH))
model = tf.keras.models.Sequential()
#We now add the vggModel directly to our new model
model.add(conv_base)
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(129, activation='relu'))
model.add(tf.keras.layers.Dropout((0.5)))
model.add(tf.keras.layers.Dense(5, activation='softmax'))
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001)
,loss='categorical_crossentropy'
, metrics=["accuracy",
tf.keras.metrics.Precision(),
tf.keras.metrics.Recall()]
)
early_stopping = EarlyStopping(monitor='val_loss'
,patience=2
)
history_1 = model.fit(train
,validation_data=val
,epochs=10
,steps_per_epoch=len(train)
,validation_steps=len(val)
,verbose=1
,callbacks =[early_stopping]
)
Training loss : 0.5572120547294617
Training accuracy : 0.8088889122009277
Training precision: 0.9959514141082764
Training recall: 0.437333345413208
Test loss : 0.5427007079124451
Test accuracy : 0.8233333230018616
Test precision: 1.0
Test recall: 0.44333332777023315
</code></pre>
|
[
{
"answer_id": 74577852,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "left_join amount library(tidyverse)\n\nt <- tibble(subs_id=c(1,1,2,3,3),\n amount=c(15,10,30,20,10),\n flag=c(\"target\", \"taker\", \"target\", \"taker\", \"target\"))\n\nt %>%\n group_by(subs_id)%>%\n summarise(ttl_amount=sum(amount)) %>%\n left_join(select(filter(t, flag==\"taker\"), \"subs_id\", \"amount\", \"flag\"), by=\"subs_id\") %>%\n select(-flag) %>%\n replace_na(list(amount=0))\n subs_id ttl_amount amount\n1 25 10 \n2 30 0 \n3 30 20 \n"
},
{
"answer_id": 74577866,
"author": "Cameron",
"author_id": 14306416,
"author_profile": "https://Stackoverflow.com/users/14306416",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\nsubs_id <- c(1, 1, 2, 3, 3)\namount <- c(15, 10, 30, 20, 10)\nflag <- c(\"target\", \"taker\", \"target\", \"taker\", \"target\")\n\ndata <- data.frame(subs_id, amount, flag)\n\ndata_new <- data %>% group_by(subs_id) %>% \n mutate(column_summary = sum(amount))\n\ndata_new$column_id <- ifelse(data_new$flag == \"taker\", data_new$amount, 0)\n"
},
{
"answer_id": 74577911,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n group_by(subs_id) %>% \n summarize(\n ttl_amount = sum(amount), \n amount = sum(amount * (flag == \"taker\"))\n )\n # A tibble: 3 × 3\n subs_id ttl_amount amount\n <dbl> <dbl> <dbl>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74577912,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 3,
"selected": true,
"text": "df %>%\n group_by(subs_id) %>%\n summarise(\n ttl_amount = sum(amount),\n amount = coalesce(amount[flag == 'taker'][1L], 0L)\n )\n # A tibble: 3 x 3\n subs_id ttl_amount amount\n <int> <int> <int>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74578098,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf |>\n group_by(subs_id) |>\n summarise(\n ttl_amount = sum(amount),\n amount= sum(amount[flag == \"taker\"]))\n#> # A tibble: 3 x 3\n#> subs_id ttl_amount amount\n#> <dbl> <dbl> <dbl>\n#> 1 1 25 10\n#> 2 2 30 0\n#> 3 3 30 20\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20527442/"
] |
74,577,833
|
<p>The question was to find the factorial and this is what I did</p>
<pre><code>//Factorial of n numbers
#include<stdio.h>
int main()
{
int num, i, fact, s;
printf("Enter the value: ");
scanf("%d",&num);
fact = num;
i = num;
while(i>1)
{
s = i-1;
fact = fact * s;
}
i--;
printf("The factorial of the number is %d.",fact);
}
</code></pre>
<p>Hii, I was trying to find the factorial of a number n. The code is not showing any error but I am not getting the required solution. The output screen showed nothing but the input statement. What is wrong with my code? If anyone could help, that would be great.</p>
<p>Thank you in advance!</p>
|
[
{
"answer_id": 74577852,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "left_join amount library(tidyverse)\n\nt <- tibble(subs_id=c(1,1,2,3,3),\n amount=c(15,10,30,20,10),\n flag=c(\"target\", \"taker\", \"target\", \"taker\", \"target\"))\n\nt %>%\n group_by(subs_id)%>%\n summarise(ttl_amount=sum(amount)) %>%\n left_join(select(filter(t, flag==\"taker\"), \"subs_id\", \"amount\", \"flag\"), by=\"subs_id\") %>%\n select(-flag) %>%\n replace_na(list(amount=0))\n subs_id ttl_amount amount\n1 25 10 \n2 30 0 \n3 30 20 \n"
},
{
"answer_id": 74577866,
"author": "Cameron",
"author_id": 14306416,
"author_profile": "https://Stackoverflow.com/users/14306416",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\nsubs_id <- c(1, 1, 2, 3, 3)\namount <- c(15, 10, 30, 20, 10)\nflag <- c(\"target\", \"taker\", \"target\", \"taker\", \"target\")\n\ndata <- data.frame(subs_id, amount, flag)\n\ndata_new <- data %>% group_by(subs_id) %>% \n mutate(column_summary = sum(amount))\n\ndata_new$column_id <- ifelse(data_new$flag == \"taker\", data_new$amount, 0)\n"
},
{
"answer_id": 74577911,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n group_by(subs_id) %>% \n summarize(\n ttl_amount = sum(amount), \n amount = sum(amount * (flag == \"taker\"))\n )\n # A tibble: 3 × 3\n subs_id ttl_amount amount\n <dbl> <dbl> <dbl>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74577912,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 3,
"selected": true,
"text": "df %>%\n group_by(subs_id) %>%\n summarise(\n ttl_amount = sum(amount),\n amount = coalesce(amount[flag == 'taker'][1L], 0L)\n )\n # A tibble: 3 x 3\n subs_id ttl_amount amount\n <int> <int> <int>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74578098,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf |>\n group_by(subs_id) |>\n summarise(\n ttl_amount = sum(amount),\n amount= sum(amount[flag == \"taker\"]))\n#> # A tibble: 3 x 3\n#> subs_id ttl_amount amount\n#> <dbl> <dbl> <dbl>\n#> 1 1 25 10\n#> 2 2 30 0\n#> 3 3 30 20\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20602588/"
] |
74,577,836
|
<p>I want to update a series if it is missing a key, but my code is generating an error.</p>
<p>This is my code:</p>
<pre><code>for item in list:
if item not in my_series.keys():
my_series = my_series[item] = 0
</code></pre>
<p>Where my_series is a series of dtype int64. It's actually a value count.</p>
<p>My code above is generating the following error</p>
<pre><code>'int' object does not support item assignment
</code></pre>
|
[
{
"answer_id": 74577852,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "left_join amount library(tidyverse)\n\nt <- tibble(subs_id=c(1,1,2,3,3),\n amount=c(15,10,30,20,10),\n flag=c(\"target\", \"taker\", \"target\", \"taker\", \"target\"))\n\nt %>%\n group_by(subs_id)%>%\n summarise(ttl_amount=sum(amount)) %>%\n left_join(select(filter(t, flag==\"taker\"), \"subs_id\", \"amount\", \"flag\"), by=\"subs_id\") %>%\n select(-flag) %>%\n replace_na(list(amount=0))\n subs_id ttl_amount amount\n1 25 10 \n2 30 0 \n3 30 20 \n"
},
{
"answer_id": 74577866,
"author": "Cameron",
"author_id": 14306416,
"author_profile": "https://Stackoverflow.com/users/14306416",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\nsubs_id <- c(1, 1, 2, 3, 3)\namount <- c(15, 10, 30, 20, 10)\nflag <- c(\"target\", \"taker\", \"target\", \"taker\", \"target\")\n\ndata <- data.frame(subs_id, amount, flag)\n\ndata_new <- data %>% group_by(subs_id) %>% \n mutate(column_summary = sum(amount))\n\ndata_new$column_id <- ifelse(data_new$flag == \"taker\", data_new$amount, 0)\n"
},
{
"answer_id": 74577911,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n group_by(subs_id) %>% \n summarize(\n ttl_amount = sum(amount), \n amount = sum(amount * (flag == \"taker\"))\n )\n # A tibble: 3 × 3\n subs_id ttl_amount amount\n <dbl> <dbl> <dbl>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74577912,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 3,
"selected": true,
"text": "df %>%\n group_by(subs_id) %>%\n summarise(\n ttl_amount = sum(amount),\n amount = coalesce(amount[flag == 'taker'][1L], 0L)\n )\n # A tibble: 3 x 3\n subs_id ttl_amount amount\n <int> <int> <int>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74578098,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf |>\n group_by(subs_id) |>\n summarise(\n ttl_amount = sum(amount),\n amount= sum(amount[flag == \"taker\"]))\n#> # A tibble: 3 x 3\n#> subs_id ttl_amount amount\n#> <dbl> <dbl> <dbl>\n#> 1 1 25 10\n#> 2 2 30 0\n#> 3 3 30 20\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2738545/"
] |
74,577,851
|
<p>I know that React will render twice when using a hook like this one:</p>
<pre><code>const [userPermissions, setUserPermissions] = useState();
//Use GET from myService to save to state
useEffect(() => {
myService.canUserAccess(userId)
.then(({userPermissions}) => setUserPermissions(userPermissions));
});
</code></pre>
<p>This is a huge problem given my application's logic because i need to check for the user permissions and redirect the user if the permissions are not right:</p>
<pre><code>useEffect(() => {
console.log(userPermissions); //This is the output
if(!userPermissions){ redirect(...)}
},[userPermissions, redirect]);
</code></pre>
<p>I have been debugging this and it seems that there is a first 'render': that outputs this:</p>
<pre><code>undefined
</code></pre>
<p>And right after:</p>
<pre><code>{ userPermissions: {...} }
</code></pre>
<p>Following my application's logic, when the state of userPermissions is first set to undefined, it will be redirected. I need to fetch this userPermissions object but the 'double render' of React is preventing me to execute the logic as desired.</p>
<p>Is there a way to 'load' the userPermissions object and setting it to the useState hook without triggering the 'double render' ?</p>
|
[
{
"answer_id": 74577852,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "left_join amount library(tidyverse)\n\nt <- tibble(subs_id=c(1,1,2,3,3),\n amount=c(15,10,30,20,10),\n flag=c(\"target\", \"taker\", \"target\", \"taker\", \"target\"))\n\nt %>%\n group_by(subs_id)%>%\n summarise(ttl_amount=sum(amount)) %>%\n left_join(select(filter(t, flag==\"taker\"), \"subs_id\", \"amount\", \"flag\"), by=\"subs_id\") %>%\n select(-flag) %>%\n replace_na(list(amount=0))\n subs_id ttl_amount amount\n1 25 10 \n2 30 0 \n3 30 20 \n"
},
{
"answer_id": 74577866,
"author": "Cameron",
"author_id": 14306416,
"author_profile": "https://Stackoverflow.com/users/14306416",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\nsubs_id <- c(1, 1, 2, 3, 3)\namount <- c(15, 10, 30, 20, 10)\nflag <- c(\"target\", \"taker\", \"target\", \"taker\", \"target\")\n\ndata <- data.frame(subs_id, amount, flag)\n\ndata_new <- data %>% group_by(subs_id) %>% \n mutate(column_summary = sum(amount))\n\ndata_new$column_id <- ifelse(data_new$flag == \"taker\", data_new$amount, 0)\n"
},
{
"answer_id": 74577911,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n group_by(subs_id) %>% \n summarize(\n ttl_amount = sum(amount), \n amount = sum(amount * (flag == \"taker\"))\n )\n # A tibble: 3 × 3\n subs_id ttl_amount amount\n <dbl> <dbl> <dbl>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74577912,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 3,
"selected": true,
"text": "df %>%\n group_by(subs_id) %>%\n summarise(\n ttl_amount = sum(amount),\n amount = coalesce(amount[flag == 'taker'][1L], 0L)\n )\n # A tibble: 3 x 3\n subs_id ttl_amount amount\n <int> <int> <int>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74578098,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf |>\n group_by(subs_id) |>\n summarise(\n ttl_amount = sum(amount),\n amount= sum(amount[flag == \"taker\"]))\n#> # A tibble: 3 x 3\n#> subs_id ttl_amount amount\n#> <dbl> <dbl> <dbl>\n#> 1 1 25 10\n#> 2 2 30 0\n#> 3 3 30 20\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/931724/"
] |
74,577,878
|
<p>Would anyone know how to conditionally change a symbol color for example to be representative of the Azure Maps JS SDK symbol layer?</p>
<p>I am already utilizing the CustomJSProperties of ASPXGridview and on grid's init i'm creating a datasource & symbol layer for a map..</p>
<p>the datasource has an id property (guid) from the grid, I was wondering if anyone had any quick tips on dynamically changing the Pin marker's color for example based on the ever changing FocusedRowIndex?</p>
<p>possibly utilizing the iconOptions in the datasource? like this example?</p>
<p><a href="https://github.com/Azure-Samples/AzureMapsCodeSamples/blob/main/Samples/Symbol%20Layer/Styled%20Symbol%20Layer/Styled%20Symbol%20Layer.html" rel="nofollow noreferrer">https://github.com/Azure-Samples/AzureMapsCodeSamples/blob/main/Samples/Symbol%20Layer/Styled%20Symbol%20Layer/Styled%20Symbol%20Layer.html</a></p>
|
[
{
"answer_id": 74577852,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "left_join amount library(tidyverse)\n\nt <- tibble(subs_id=c(1,1,2,3,3),\n amount=c(15,10,30,20,10),\n flag=c(\"target\", \"taker\", \"target\", \"taker\", \"target\"))\n\nt %>%\n group_by(subs_id)%>%\n summarise(ttl_amount=sum(amount)) %>%\n left_join(select(filter(t, flag==\"taker\"), \"subs_id\", \"amount\", \"flag\"), by=\"subs_id\") %>%\n select(-flag) %>%\n replace_na(list(amount=0))\n subs_id ttl_amount amount\n1 25 10 \n2 30 0 \n3 30 20 \n"
},
{
"answer_id": 74577866,
"author": "Cameron",
"author_id": 14306416,
"author_profile": "https://Stackoverflow.com/users/14306416",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\nsubs_id <- c(1, 1, 2, 3, 3)\namount <- c(15, 10, 30, 20, 10)\nflag <- c(\"target\", \"taker\", \"target\", \"taker\", \"target\")\n\ndata <- data.frame(subs_id, amount, flag)\n\ndata_new <- data %>% group_by(subs_id) %>% \n mutate(column_summary = sum(amount))\n\ndata_new$column_id <- ifelse(data_new$flag == \"taker\", data_new$amount, 0)\n"
},
{
"answer_id": 74577911,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n group_by(subs_id) %>% \n summarize(\n ttl_amount = sum(amount), \n amount = sum(amount * (flag == \"taker\"))\n )\n # A tibble: 3 × 3\n subs_id ttl_amount amount\n <dbl> <dbl> <dbl>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74577912,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 3,
"selected": true,
"text": "df %>%\n group_by(subs_id) %>%\n summarise(\n ttl_amount = sum(amount),\n amount = coalesce(amount[flag == 'taker'][1L], 0L)\n )\n # A tibble: 3 x 3\n subs_id ttl_amount amount\n <int> <int> <int>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74578098,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf |>\n group_by(subs_id) |>\n summarise(\n ttl_amount = sum(amount),\n amount= sum(amount[flag == \"taker\"]))\n#> # A tibble: 3 x 3\n#> subs_id ttl_amount amount\n#> <dbl> <dbl> <dbl>\n#> 1 1 25 10\n#> 2 2 30 0\n#> 3 3 30 20\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719076/"
] |
74,577,896
|
<p>I have a png image that I want to crop, removing the top and bottom white space.</p>
<p>I use the following code:</p>
<pre><code>from PIL import Image
for f in pa_files:
img = f
im = Image.open(img)
width, height = im.size
pixels = list(im.getdata())
pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]
white_lines = 0
for line in pixels:
white_count = sum([sum(x) for x in line]) - im.width * 255*4
if (white_count) == 0:
white_lines += 1
else:
break
crop_from_top = white_lines
pixels.reverse()
white_lines = 0
for line in pixels:
white_count = sum([sum(x) for x in line]) - im.width * 255*4
if (white_count) == 0:
white_lines += 1
#print(white_count)
else:
break
crop_from_bottom = white_lines
crop_from_bottom, crop_from_top, im.size
# Setting the points for cropped image
left = 0
top = crop_from_top - 5
right = im.width
bottom = im.height - (crop_from_bottom- 5)
im1 = im.crop((left, top, right, bottom))
im1.save(img)
</code></pre>
<p>this works for a 32 bit png</p>
<p><a href="https://i.stack.imgur.com/ekm24.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ekm24.png" alt="enter image description here" /></a></p>
<p>but now I come across an 8 bit png, and tried running the same script, but came across this error:</p>
<p><code>TypeError: 'int' object is not iterable</code></p>
<p><a href="https://i.stack.imgur.com/Wapev.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wapev.png" alt="enter image description here" /></a></p>
<p>Looking further, I see that each pixel is represented by 0:255
<a href="https://i.stack.imgur.com/SuFdo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SuFdo.png" alt="enter image description here" /></a></p>
<p>and we see pixel value 153 appears 2m times.</p>
<p>I played around cropping with the following:</p>
<pre><code>im = Image.open(f).convert('L')
im = im.crop((x1, y1, x2, y2))
im.save('_0.png')
</code></pre>
<p>successfully, but then my image returned grayscale.</p>
<p>before:
<a href="https://i.stack.imgur.com/3F7KL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3F7KL.png" alt="enter image description here" /></a></p>
<p>after:</p>
<p><a href="https://i.stack.imgur.com/4Fkps.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Fkps.png" alt="enter image description here" /></a></p>
<p>it went from blue to grayscale.</p>
<p>How is it possible to crop the margins dynamically of an 8bit type image, and save it again in colour?</p>
|
[
{
"answer_id": 74577852,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "left_join amount library(tidyverse)\n\nt <- tibble(subs_id=c(1,1,2,3,3),\n amount=c(15,10,30,20,10),\n flag=c(\"target\", \"taker\", \"target\", \"taker\", \"target\"))\n\nt %>%\n group_by(subs_id)%>%\n summarise(ttl_amount=sum(amount)) %>%\n left_join(select(filter(t, flag==\"taker\"), \"subs_id\", \"amount\", \"flag\"), by=\"subs_id\") %>%\n select(-flag) %>%\n replace_na(list(amount=0))\n subs_id ttl_amount amount\n1 25 10 \n2 30 0 \n3 30 20 \n"
},
{
"answer_id": 74577866,
"author": "Cameron",
"author_id": 14306416,
"author_profile": "https://Stackoverflow.com/users/14306416",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\nsubs_id <- c(1, 1, 2, 3, 3)\namount <- c(15, 10, 30, 20, 10)\nflag <- c(\"target\", \"taker\", \"target\", \"taker\", \"target\")\n\ndata <- data.frame(subs_id, amount, flag)\n\ndata_new <- data %>% group_by(subs_id) %>% \n mutate(column_summary = sum(amount))\n\ndata_new$column_id <- ifelse(data_new$flag == \"taker\", data_new$amount, 0)\n"
},
{
"answer_id": 74577911,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n group_by(subs_id) %>% \n summarize(\n ttl_amount = sum(amount), \n amount = sum(amount * (flag == \"taker\"))\n )\n # A tibble: 3 × 3\n subs_id ttl_amount amount\n <dbl> <dbl> <dbl>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74577912,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 3,
"selected": true,
"text": "df %>%\n group_by(subs_id) %>%\n summarise(\n ttl_amount = sum(amount),\n amount = coalesce(amount[flag == 'taker'][1L], 0L)\n )\n # A tibble: 3 x 3\n subs_id ttl_amount amount\n <int> <int> <int>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74578098,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf |>\n group_by(subs_id) |>\n summarise(\n ttl_amount = sum(amount),\n amount= sum(amount[flag == \"taker\"]))\n#> # A tibble: 3 x 3\n#> subs_id ttl_amount amount\n#> <dbl> <dbl> <dbl>\n#> 1 1 25 10\n#> 2 2 30 0\n#> 3 3 30 20\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2123706/"
] |
74,577,899
|
<p>I have a data frame containing 5 probes which are my variables in a dataframe, cg02823866, cg13474877, cg14305799, cg15837913 and cg19724470. I want to create a boxplot that will group cg02823866 and cg14305799 into a group called 'GeneBody' and then cg13474877, cg14305799 and cg19724470 into a group called 'Promoter'. I then want to colour code the boxplots to represent the probe names. I can't figure out how to group those variables into groups to plot the graph.</p>
<p><a href="https://i.stack.imgur.com/cR2QL.png" rel="nofollow noreferrer">I created an ungrouped boxplot of the five probes and it looked like this.</a></p>
<p>I want there to be the titles 'Promoter' and 'GeneBody' on the x axis. Above the 'GeneBody' title there are the 2 boxplots for the cg02823866 and cg14305799 probes. Then a 'Promoter' label with the boxplots for cg13474877, cg14305799 and cg19724470. I then want each boxplots colour coded to represent each different probe.
My data frame that I imported into RStudio looks like this: <a href="https://i.stack.imgur.com/r4gEC.png" rel="nofollow noreferrer">https://i.stack.imgur.com/r4gEC.png</a></p>
|
[
{
"answer_id": 74577852,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "left_join amount library(tidyverse)\n\nt <- tibble(subs_id=c(1,1,2,3,3),\n amount=c(15,10,30,20,10),\n flag=c(\"target\", \"taker\", \"target\", \"taker\", \"target\"))\n\nt %>%\n group_by(subs_id)%>%\n summarise(ttl_amount=sum(amount)) %>%\n left_join(select(filter(t, flag==\"taker\"), \"subs_id\", \"amount\", \"flag\"), by=\"subs_id\") %>%\n select(-flag) %>%\n replace_na(list(amount=0))\n subs_id ttl_amount amount\n1 25 10 \n2 30 0 \n3 30 20 \n"
},
{
"answer_id": 74577866,
"author": "Cameron",
"author_id": 14306416,
"author_profile": "https://Stackoverflow.com/users/14306416",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\nsubs_id <- c(1, 1, 2, 3, 3)\namount <- c(15, 10, 30, 20, 10)\nflag <- c(\"target\", \"taker\", \"target\", \"taker\", \"target\")\n\ndata <- data.frame(subs_id, amount, flag)\n\ndata_new <- data %>% group_by(subs_id) %>% \n mutate(column_summary = sum(amount))\n\ndata_new$column_id <- ifelse(data_new$flag == \"taker\", data_new$amount, 0)\n"
},
{
"answer_id": 74577911,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n group_by(subs_id) %>% \n summarize(\n ttl_amount = sum(amount), \n amount = sum(amount * (flag == \"taker\"))\n )\n # A tibble: 3 × 3\n subs_id ttl_amount amount\n <dbl> <dbl> <dbl>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74577912,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 3,
"selected": true,
"text": "df %>%\n group_by(subs_id) %>%\n summarise(\n ttl_amount = sum(amount),\n amount = coalesce(amount[flag == 'taker'][1L], 0L)\n )\n # A tibble: 3 x 3\n subs_id ttl_amount amount\n <int> <int> <int>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74578098,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf |>\n group_by(subs_id) |>\n summarise(\n ttl_amount = sum(amount),\n amount= sum(amount[flag == \"taker\"]))\n#> # A tibble: 3 x 3\n#> subs_id ttl_amount amount\n#> <dbl> <dbl> <dbl>\n#> 1 1 25 10\n#> 2 2 30 0\n#> 3 3 30 20\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20602598/"
] |
74,577,957
|
<p>im having trouble figuring out how to fetch a url that contains an array in react</p>
<p>the parent component fetches data that gets sent to two components.</p>
<pre><code>export default class ParentComponent extends Component<AuthProps, ChannelState> {
constructor(props: AuthProps) {
super(props)
this.state = {
...
}
}
getChannel = () => {
console.log("get channel called")
fetch(`${APIURL}/channel/mine`, {
method: "GET",
headers: new Headers({
"Content-Type": "application/json",
"Authorization": `${this.props.sessionToken}`
})
})
.then(response => response.json())
.then(data => {
console.log(data)
this.setState({
channel: data
})
console.log(this.state.channel, "channel called")
})
.catch(err => console.log(err))
}
</code></pre>
<p>the state gets sent to two child components. childcomponent1 is a route that uses channelId in the fetch method. childcomponent2 displays a dynamic link to component1 using channelId as a key</p>
<pre><code>export default class ChildComponent1 extends Component<AuthProps, ChannelEntryState> {
constructor(props: AuthProps) {
super(props)
this.state = {
...
}
}
getChannelEntry = () => {
console.log("get channel entry called")
console.log(this.props.channel.length)
fetch(`${APIURL}/channel/${this.props.channel[1].channelId}/channelentry`, {
method: "GET",
headers: new Headers({
"Content-Type": "application/json",
"Authorization": `${this.props.sessionToken}`
})
})
.then(response => response.json())
.then(data => {
console.log(data)
this.setState({
channelEntry: data.messages
})
console.log(this.state.channelEntry, "channel entry called")
})
.catch(err => console.log(err))
}
const ChildComponent2 = (props: AuthProps) => {
return(
<Row>
{props.channel.map((cprops: ChannelType) => {
return(
<>
<Col>
<div>
<ul className="sidebar-list list-unstyled" key={cprops.channelId}>
<li><Link to={`/channelEntry/${cprops.channelId}`}><Button onClick={() => {console.log('button clicked')}}>{cprops.name}</Button></Link></li>
</ul>
</div>
</Col>
</>
)
})}
</code></pre>
<p>Ive looked into useParams but i believe its only possible in a functional component. I believe i shouldnt use functional components when states can change. How can i fetch the url in component1 dynamically.</p>
|
[
{
"answer_id": 74577852,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "left_join amount library(tidyverse)\n\nt <- tibble(subs_id=c(1,1,2,3,3),\n amount=c(15,10,30,20,10),\n flag=c(\"target\", \"taker\", \"target\", \"taker\", \"target\"))\n\nt %>%\n group_by(subs_id)%>%\n summarise(ttl_amount=sum(amount)) %>%\n left_join(select(filter(t, flag==\"taker\"), \"subs_id\", \"amount\", \"flag\"), by=\"subs_id\") %>%\n select(-flag) %>%\n replace_na(list(amount=0))\n subs_id ttl_amount amount\n1 25 10 \n2 30 0 \n3 30 20 \n"
},
{
"answer_id": 74577866,
"author": "Cameron",
"author_id": 14306416,
"author_profile": "https://Stackoverflow.com/users/14306416",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\nsubs_id <- c(1, 1, 2, 3, 3)\namount <- c(15, 10, 30, 20, 10)\nflag <- c(\"target\", \"taker\", \"target\", \"taker\", \"target\")\n\ndata <- data.frame(subs_id, amount, flag)\n\ndata_new <- data %>% group_by(subs_id) %>% \n mutate(column_summary = sum(amount))\n\ndata_new$column_id <- ifelse(data_new$flag == \"taker\", data_new$amount, 0)\n"
},
{
"answer_id": 74577911,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n group_by(subs_id) %>% \n summarize(\n ttl_amount = sum(amount), \n amount = sum(amount * (flag == \"taker\"))\n )\n # A tibble: 3 × 3\n subs_id ttl_amount amount\n <dbl> <dbl> <dbl>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74577912,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 3,
"selected": true,
"text": "df %>%\n group_by(subs_id) %>%\n summarise(\n ttl_amount = sum(amount),\n amount = coalesce(amount[flag == 'taker'][1L], 0L)\n )\n # A tibble: 3 x 3\n subs_id ttl_amount amount\n <int> <int> <int>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74578098,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf |>\n group_by(subs_id) |>\n summarise(\n ttl_amount = sum(amount),\n amount= sum(amount[flag == \"taker\"]))\n#> # A tibble: 3 x 3\n#> subs_id ttl_amount amount\n#> <dbl> <dbl> <dbl>\n#> 1 1 25 10\n#> 2 2 30 0\n#> 3 3 30 20\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16292742/"
] |
74,577,981
|
<pre class="lang-js prettyprint-override"><code>function.getElementById("a")
{
var input= document.getElementById("a")
console.log("input")
}
</code></pre>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="index.js">
</script>
<div class="a">
<input id="a" placeholder="enter here..." >
</div>
</body>
</html>
</code></pre>
<p>I want to print the name of user as same he enters in the input box.</p>
|
[
{
"answer_id": 74577852,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "left_join amount library(tidyverse)\n\nt <- tibble(subs_id=c(1,1,2,3,3),\n amount=c(15,10,30,20,10),\n flag=c(\"target\", \"taker\", \"target\", \"taker\", \"target\"))\n\nt %>%\n group_by(subs_id)%>%\n summarise(ttl_amount=sum(amount)) %>%\n left_join(select(filter(t, flag==\"taker\"), \"subs_id\", \"amount\", \"flag\"), by=\"subs_id\") %>%\n select(-flag) %>%\n replace_na(list(amount=0))\n subs_id ttl_amount amount\n1 25 10 \n2 30 0 \n3 30 20 \n"
},
{
"answer_id": 74577866,
"author": "Cameron",
"author_id": 14306416,
"author_profile": "https://Stackoverflow.com/users/14306416",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\nsubs_id <- c(1, 1, 2, 3, 3)\namount <- c(15, 10, 30, 20, 10)\nflag <- c(\"target\", \"taker\", \"target\", \"taker\", \"target\")\n\ndata <- data.frame(subs_id, amount, flag)\n\ndata_new <- data %>% group_by(subs_id) %>% \n mutate(column_summary = sum(amount))\n\ndata_new$column_id <- ifelse(data_new$flag == \"taker\", data_new$amount, 0)\n"
},
{
"answer_id": 74577911,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n group_by(subs_id) %>% \n summarize(\n ttl_amount = sum(amount), \n amount = sum(amount * (flag == \"taker\"))\n )\n # A tibble: 3 × 3\n subs_id ttl_amount amount\n <dbl> <dbl> <dbl>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74577912,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 3,
"selected": true,
"text": "df %>%\n group_by(subs_id) %>%\n summarise(\n ttl_amount = sum(amount),\n amount = coalesce(amount[flag == 'taker'][1L], 0L)\n )\n # A tibble: 3 x 3\n subs_id ttl_amount amount\n <int> <int> <int>\n1 1 25 10\n2 2 30 0\n3 3 30 20\n"
},
{
"answer_id": 74578098,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf |>\n group_by(subs_id) |>\n summarise(\n ttl_amount = sum(amount),\n amount= sum(amount[flag == \"taker\"]))\n#> # A tibble: 3 x 3\n#> subs_id ttl_amount amount\n#> <dbl> <dbl> <dbl>\n#> 1 1 25 10\n#> 2 2 30 0\n#> 3 3 30 20\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74577981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17449755/"
] |
74,578,041
|
<p>I am trying to create an update view that allows users to update their data. I am trying to access the data by using primary keys. My problem is that I do not know the syntax to implement it.</p>
<p>models.py</p>
<pre><code>class Detail(models.Model):
"""
This is the one for model.py
"""
username = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default="")
matricno = models.CharField(max_length=9, default="")
email = models.EmailField(default="")
first_name = models.CharField(max_length=200, default="")
last_name = models.CharField(max_length=255, default="")
class Meta:
verbose_name_plural = "Detail"
def __str__(self):
return self.first_name+ " "+self.last_name
</code></pre>
<p>views.py</p>
<pre><code>def success(request):
return render(request, "success.html", {})
@login_required(login_url="signin")
def details(request):
form = Details()
if request.method == "POST":
form = Details(request.POST)
if form.is_valid():
detail = form.save(commit=False)
detail.username = request.user
detail.save()
return redirect(success)
else:
form = Details(initial={"matricno":request.user.username})
return render(request, "details.html", {"form":form})
def updatedetails(request, pk):
detail = Detail.objects.get(id=pk)
form = Details(instance=detail)
if request.method == "POST":
form = Details(request.POST, instance=detail)
if form.is_valid():
form.save()
return redirect(success)
return render(request, "details.html", {"form":form})
</code></pre>
<p>urls.py</p>
<pre><code>from django.urls import path
from . import views
urlpatterns = [
path("details/", views.details, name="details"),
path("success/", views.success, name="success"),
path("edit/<str:pk>/", views.updatedetails, name="updatedetails"),
]
</code></pre>
<p>my html template</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Success</title>
</head>
<body>
<h1>Thank You for Filling Out the Form</h1>
<p><a href="/edit/{{request.detail.id}}/">Click Here To Edit</a></p>
</body>
</html>
</code></pre>
<p>So what I am trying to figure out is how to call the primary key in my template.</p>
|
[
{
"answer_id": 74578121,
"author": "s-knocks",
"author_id": 18580279,
"author_profile": "https://Stackoverflow.com/users/18580279",
"pm_score": 0,
"selected": false,
"text": "href=\"{% url 'updatedetails' pk=request.detail.id %}\"\n"
},
{
"answer_id": 74579770,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 2,
"selected": true,
"text": "<str:pk> <int:pk> updatedetails from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"details/\", views.details, name=\"details\"),\n path(\"success/<int:pk>/\", views.success, name=\"success\"),\n path(\"edit/<int:pk>/\", views.updatedetails, name=\"updatedetails\"),\n]\n get_object_or_404() get() \"\" redirect(success) redirect(\"success\") from django.shortcuts import get_object_or_404\n\ndef updatedetails(request, pk):\n detail = get_object_or_404(Detail,id=pk)\n form = Details(instance=detail)\n if request.method == \"POST\":\n form = Details(request.POST, instance=detail)\n if form.is_valid():\n form.save()\n return redirect(\"success\", args=(pk))\n return render(request, \"details.html\", {\"form\":form})\n\n@login_required(login_url=\"signin\")\ndef details(request):\n form = Details()\n if request.method == \"POST\":\n form = Details(request.POST)\n if form.is_valid():\n detail = form.save(commit=False)\n detail.username = request.user\n detail.save()\n return redirect(success,args=(detail.id))\n else:\n form = Details(initial={\"matricno\":request.user.username})\n return render(request, \"details.html\", {\"form\":form})\n\n\ndef success(request,pk):\n \n return render(request, \"success.html\", {\"id\":pk})\n\n url tags id updatedetails <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Success</title>\n</head>\n<body>\n <h1>Thank You for Filling Out the Form</h1>\n <p><a href=\"{% url 'updatedetails' id %}\">Click Here To Edit</a></p>\n</body>\n</html>\n"
},
{
"answer_id": 74585582,
"author": "raphael",
"author_id": 10951070,
"author_profile": "https://Stackoverflow.com/users/10951070",
"pm_score": 2,
"selected": false,
"text": "# forms.py\n\nfrom django.forms import ModelForm\nfrom .models import Detail\n\nclass DetailForm(ModelForm):\n class Meta:\n model = Detail\n # Include below the fields from the Detail model you\n # would like to include in your form\n fields = ['username', 'matricno', 'email', 'first_name', 'last_name', ]\n #views.py\n\nfrom .models import Detail\nfrom .forms import DetailForm\n\ndef success(request, pk):\n # NOTE that here you must receive the pk\n return render(request, \"success.html\", {'pk': pk})\n\n@login_required(login_url=\"signin\")\ndef details(request):\n form = DetailForm()\n if request.method == \"POST\":\n form = DetailForm(request.POST)\n if form.is_valid():\n detail = form.save(commit=False)\n detail.username = request.user\n detail.save()\n # NOTE: here you can send the detail primary key, pk, or id\n # to the success view where you are trying to use it\n return redirect('success', pk=detail.pk)\n else:\n form = Details(initial={\"matricno\": request.user.username})\n return render(request, \"details.html\", {\"form\": form})\n\ndef updatedetails(request, pk):\n detail = Detail.objects.get(id=pk)\n form = DetailForm(instance=detail)\n if request.method == \"POST\":\n form = Details(request.POST, instance=detail)\n if form.is_valid():\n form.save()\n return redirect('success', pk=detail.pk)\n return render(request, \"details.html\", {\"form\":form})\n <!--html template -->\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Success</title>\n</head>\n<body>\n <h1>Thank You for Filling Out the Form</h1>\n <p><a href=\"{% url 'updatedetails' pk %}\">Click Here To Edit</a></p>\n</body>\n</html>\n # urls.py\nfrom django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"details/\", views.details, name=\"details\"),\n path(\"success/<int:pk>/\", views.success, name=\"success\"),\n path(\"edit/<int:pk>/\", views.updatedetails, name=\"updatedetails\"),\n]\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13397363/"
] |
74,578,055
|
<p>In order to prevent my machine learning algorithm from tending to a certain data, I want to reduce the frequency differences in my dataset, which is a pandas table,</p>
<p>for example, in column X;</p>
<ul>
<li>A value is 1500 times</li>
<li>B value is 3000 times</li>
<li>C value is 1300 times</li>
</ul>
<p>Is there a way to get 1250 of them all?</p>
|
[
{
"answer_id": 74578141,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 1,
"selected": false,
"text": "df2=pd.concat(df[df['X']=='A'][:1250],df[df['X']=='B'][:1250],df[df['X']=='C'][:1250])\n"
},
{
"answer_id": 74578409,
"author": "Anton B",
"author_id": 15870626,
"author_profile": "https://Stackoverflow.com/users/15870626",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n\n#Creating a Panda dafatframme with the number of elements\nd = {'X': 1500*[\"A\"]+3000*[\"B\"]+1300*[\"C\"]}\ndf = pd.DataFrame(data=d)\n\n#Create a dictionnary containing 1 dataframe for each unique value\ndfDict = dict(iter(df.groupby('X'))) \n\n#Keep only the first n values for each and add them to filtered dataframe\nfor unique_val in dfDict:\n dfDict[unique_val] = dfDict[unique_val][:1250]\n filetered = pd.concat(dfDict, ignore_index=True)\n"
},
{
"answer_id": 74607145,
"author": "AomineDaici",
"author_id": 13149512,
"author_profile": "https://Stackoverflow.com/users/13149512",
"pm_score": 2,
"selected": true,
"text": "df = df.groupby('X').head(1250)\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14701032/"
] |
74,578,081
|
<p>I have been successfully using python with elasticsearch-dsl (<a href="https://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html#" rel="nofollow noreferrer">https://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html#</a>) and composite aggregations for some time now but have come across a problem I can't solve. The data I'm querying is asset data for multiple organizations and consists of one row for each asset. Each row includes two dates (scan_date and timestamp) for each asset and I need the search result to give me the maximum of (timestamp - scan_date), i.e., the oldest "scan_age," for each organization. In SQL terms:</p>
<pre><code>SELECT organization, MAX(timestamp - scan_date) as oldest_scan_age
FROM database
GROUP BY organization
</code></pre>
<p>The elasticsearch-dsl library includes the function script_fields() to define calculated fields, but from what I've read (and tried) I can't perform aggregations on script fields. The elasticsearch feature I need seems to be "runtime fields" but elasticsearch-dsl does not appear to provide a function I can call to specify a runtime field. If such a function existed, I could call it to define a new field called "scan_age" then find its maximum by agency using a standard composite aggregation.</p>
<p>How can I perform this query <em>using elasticsearch-dsl</em>?</p>
<p>Please note that (1) I already know how to do this using the JSON syntax typically associated with querying elasticsearch. What I'm looking for is how to do it in elasticsearch-dsl. (2) I would happily create my own JSON to define just the runtime field if I had a way to use it programatically to modify my elasticsearch-dsl search object.</p>
|
[
{
"answer_id": 74578141,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 1,
"selected": false,
"text": "df2=pd.concat(df[df['X']=='A'][:1250],df[df['X']=='B'][:1250],df[df['X']=='C'][:1250])\n"
},
{
"answer_id": 74578409,
"author": "Anton B",
"author_id": 15870626,
"author_profile": "https://Stackoverflow.com/users/15870626",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n\n#Creating a Panda dafatframme with the number of elements\nd = {'X': 1500*[\"A\"]+3000*[\"B\"]+1300*[\"C\"]}\ndf = pd.DataFrame(data=d)\n\n#Create a dictionnary containing 1 dataframe for each unique value\ndfDict = dict(iter(df.groupby('X'))) \n\n#Keep only the first n values for each and add them to filtered dataframe\nfor unique_val in dfDict:\n dfDict[unique_val] = dfDict[unique_val][:1250]\n filetered = pd.concat(dfDict, ignore_index=True)\n"
},
{
"answer_id": 74607145,
"author": "AomineDaici",
"author_id": 13149512,
"author_profile": "https://Stackoverflow.com/users/13149512",
"pm_score": 2,
"selected": true,
"text": "df = df.groupby('X').head(1250)\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/950673/"
] |
74,578,120
|
<p>I'm trying to pass a "dino" struct object that has been declared in C using typedef struct format. I'm then assigning values to this object, named d0, and then passing the whole object to a function, which is meant to write to a file in byte format, writing all of the parameters of d0. Then I am attempting to take this file, and then read to a new dino object, d1, and assign the values for each parameter to this new dino. When I run it, there are a few errors. Namely, my save_dino argument is incompatible. The save_dino function declaration uses dino *d and I'm just passing in d0. I don't understand exactly what I'm supposed to pass in instead of d0. Secondly, d is a pointer, and gcc is telling me I should have used -> instead of .</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// your code here (define the dino struct)
// use typedef struct, not just struct
typedef struct Dino {
double lat;
double lng;
char *name;
} dino;
void save_dino(dino *d, char *ofn)
{
FILE *fp = fopen(ofn, "wb");
fwrite(&d.lat, sizeof(double), 1, fp);
fwrite(&d.lng, sizeof(double), 1, fp);
fwrite(d.name, strlen(d.name), 1, fp);
fclose(fp);
}
void load_dino(dino *d, char *ifn)
{
FILE *fp = fopen(ifn, "rb");
fread(d.lat, sizeof(double), 1, fp);
fread(d.lng, sizeof(double), 1, fp);
while(!feof(fp))
{
fscanf(fp, "%s", d.name);
}
}
int main(int argc, char **argv)
{
if(argc != 2)
return 1;
char *fn = argv[1];
// create a dino struct and give it the following values:
// latitude = 51.083332
// longitude = -1.166667
//name = "Aves indet."
// do NOT hardcode the string length, get it with strlen() instead
dino d0;
d0.lat = 51.083332;
d0.lng = -1.166667;
strcpy(d0.name, "Aves indet.");
// call save_dino() and save d0 to the given filename (fn)
save_dino(d0, fn);
dino d1;
// call load_dino() and load the file you just saved into d1 (NOT d0)
load_dino(d1, fn);
printf("d1.lat %f\n", d1.lat);
printf("d1.lng %f\n", d1.lng);
printf("d1.name %s\n", d1.name);
return 0;
}
</code></pre>
<p>This is my code.</p>
|
[
{
"answer_id": 74578513,
"author": "rfermi",
"author_id": 2890384,
"author_profile": "https://Stackoverflow.com/users/2890384",
"pm_score": 0,
"selected": false,
"text": "void save_dino(Dino *d, char *ofn) {\n FILE *fp; \n if ( (fp = fopen(ofn, \"wb\")) == NULL ){\n return;\n }\n fwrite(d, sizeof(Dino), 1, fp);\n fclose(fp); \n}\n\nvoid load_dino(Dino **d, char *ifn)\n{\n FILE *fp;\n if ( (fp = fopen(ofn, \"rb\")) == NULL ){\n return;\n }\n fread(&(*d), sizeof(Dino), 1, fp);\n return;\n}\n"
},
{
"answer_id": 74578533,
"author": "user3121023",
"author_id": 3121023,
"author_profile": "https://Stackoverflow.com/users/3121023",
"pm_score": 1,
"selected": false,
"text": "name name #include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct Dino {\n double lat;\n double lng;\n char *name;\n} dino;\n\nvoid save_dino(dino *d, char *ofn)\n{\n FILE *fp = fopen(ofn, \"wb\");\n fwrite(&d->lat, 1, sizeof(double), fp);\n fwrite(&d->lng, 1, sizeof(double), fp);\n size_t len = strlen ( d->name);\n fwrite(&len, 1, sizeof(size_t), fp);\n fwrite(d->name, 1, len, fp);\n fclose(fp);\n}\n\nvoid load_dino(dino *d, char *ifn)\n{\n FILE *fp = fopen(ifn, \"rb\");\n fread(&d->lat, 1, sizeof(double), fp);\n fread(&d->lng, 1, sizeof(double), fp);\n size_t len = 0;\n fread(&len, 1, sizeof(size_t), fp);\n if ( NULL == ( d->name = malloc ( len + 1))) {\n fprintf ( stderr, \"problem malloc\\n\");\n fclose ( fp);\n return;\n }\n fread(d->name, 1, len, fp);\n d->name[len] = 0;\n fclose(fp);\n}\n\nint main(int argc, char **argv)\n{\n if(argc != 2)\n return 1;\n\n char *fn = argv[1];\n\n // create a dino struct and give it the following values:\n // latitude = 51.083332\n // longitude = -1.166667\n //name = \"Aves indet.\"\n // do NOT hardcode the string length, get it with strlen() instead\n dino d0;\n d0.lat = 51.083332;\n d0.lng = -1.166667;\n d0.name = strdup ( \"Aves indet.\");\n\n // call save_dino() and save d0 to the given filename (fn)\n save_dino(&d0, fn);\n free ( d0.name);\n\n dino d1 = { 0.0, 0.0, NULL};\n\n // call load_dino() and load the file you just saved into d1 (NOT d0)\n load_dino(&d1, fn);\n\n printf(\"d1.lat %f\\n\", d1.lat);\n printf(\"d1.lng %f\\n\", d1.lng);\n printf(\"d1.name %s\\n\", d1.name);\n free ( d1.name);\n\n return 0;\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20602773/"
] |
74,578,122
|
<p>I have the following image that I'm trying to display under my navigation bar.</p>
<p><a href="https://i.stack.imgur.com/8PUa3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8PUa3.png" alt="car" /></a></p>
<p>The image dimensions are 234 x 156 px</p>
<p>For some reason, the image is coming out blurry and the entire image cannot be seen. Is it because it's too small to begin with in terms of height/width? or some other factor?</p>
<p>Here is the code snippet that displays the image:</p>
<pre><code> <div class="flex w-full justify-center">
<img
src="../images/cars.png" alt= ""
class= "h-48 w-full object-cover" />
</div>
</code></pre>
|
[
{
"answer_id": 74578513,
"author": "rfermi",
"author_id": 2890384,
"author_profile": "https://Stackoverflow.com/users/2890384",
"pm_score": 0,
"selected": false,
"text": "void save_dino(Dino *d, char *ofn) {\n FILE *fp; \n if ( (fp = fopen(ofn, \"wb\")) == NULL ){\n return;\n }\n fwrite(d, sizeof(Dino), 1, fp);\n fclose(fp); \n}\n\nvoid load_dino(Dino **d, char *ifn)\n{\n FILE *fp;\n if ( (fp = fopen(ofn, \"rb\")) == NULL ){\n return;\n }\n fread(&(*d), sizeof(Dino), 1, fp);\n return;\n}\n"
},
{
"answer_id": 74578533,
"author": "user3121023",
"author_id": 3121023,
"author_profile": "https://Stackoverflow.com/users/3121023",
"pm_score": 1,
"selected": false,
"text": "name name #include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct Dino {\n double lat;\n double lng;\n char *name;\n} dino;\n\nvoid save_dino(dino *d, char *ofn)\n{\n FILE *fp = fopen(ofn, \"wb\");\n fwrite(&d->lat, 1, sizeof(double), fp);\n fwrite(&d->lng, 1, sizeof(double), fp);\n size_t len = strlen ( d->name);\n fwrite(&len, 1, sizeof(size_t), fp);\n fwrite(d->name, 1, len, fp);\n fclose(fp);\n}\n\nvoid load_dino(dino *d, char *ifn)\n{\n FILE *fp = fopen(ifn, \"rb\");\n fread(&d->lat, 1, sizeof(double), fp);\n fread(&d->lng, 1, sizeof(double), fp);\n size_t len = 0;\n fread(&len, 1, sizeof(size_t), fp);\n if ( NULL == ( d->name = malloc ( len + 1))) {\n fprintf ( stderr, \"problem malloc\\n\");\n fclose ( fp);\n return;\n }\n fread(d->name, 1, len, fp);\n d->name[len] = 0;\n fclose(fp);\n}\n\nint main(int argc, char **argv)\n{\n if(argc != 2)\n return 1;\n\n char *fn = argv[1];\n\n // create a dino struct and give it the following values:\n // latitude = 51.083332\n // longitude = -1.166667\n //name = \"Aves indet.\"\n // do NOT hardcode the string length, get it with strlen() instead\n dino d0;\n d0.lat = 51.083332;\n d0.lng = -1.166667;\n d0.name = strdup ( \"Aves indet.\");\n\n // call save_dino() and save d0 to the given filename (fn)\n save_dino(&d0, fn);\n free ( d0.name);\n\n dino d1 = { 0.0, 0.0, NULL};\n\n // call load_dino() and load the file you just saved into d1 (NOT d0)\n load_dino(&d1, fn);\n\n printf(\"d1.lat %f\\n\", d1.lat);\n printf(\"d1.lng %f\\n\", d1.lng);\n printf(\"d1.name %s\\n\", d1.name);\n free ( d1.name);\n\n return 0;\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8397835/"
] |
74,578,124
|
<p>I just started unit testing in python using pytest. Well, when I have a function with a return value, with the "assert" I can compare a certain value with the value that the function return.
But if I had a void function that returns nothing and does a print at the end, for example:</p>
<pre><code>def function() -> None:
number = randint(0, 4)
if (number == 0):
print("Number 0")
elif (number == 1):
print("Number 1")
elif (number == 2):
print("Number 2")
elif (number == 3):
print("Number 3")
elif (number == 4):
print("Number 4")
</code></pre>
<p>How can i test this simple function to get 100% code coverage?</p>
<p>One method I've found to test this function is to do a return of the value (instead of print) and print it later, and then use the assert. But I wanted to know if it was possible to avoid this and do a test directly on the print statemant.</p>
|
[
{
"answer_id": 74578155,
"author": "snakecharmerb",
"author_id": 5320906,
"author_profile": "https://Stackoverflow.com/users/5320906",
"pm_score": 1,
"selected": false,
"text": "sys.stdout print >>> import io\n>>> import contextlib\n>>> \n>>> def f():print('X')\n... \n>>> buf = io.StringIO()\n>>> with contextlib.redirect_stdout(buf):\n... f()\n... \n>>> print(repr(buf.getvalue()))\n'X\\n'\n>>> \n>>> buf.close()\n end '\\n'"
},
{
"answer_id": 74582378,
"author": "Cpt.Hook",
"author_id": 20599896,
"author_profile": "https://Stackoverflow.com/users/20599896",
"pm_score": 0,
"selected": false,
"text": "# production.py \n\ndef say_hello() -> None:\n print('Hello World.')\n # production_test.py\nfrom production import say_hello\n\ndef test_greeting(mocker):\n # The \"mocker\" fixture is auto-magicall inserted by pytest, \n # once the extenson 'pytest-mock' is installed\n printer = mocker.patch('builtins.print')\n say_hello()\n assert printer.call_count == 1\n printer # deep_though.py\n\nclass DeepThought:\n #: Seven and a half million years in seconds\n SEVEN_HALF_MIO_YEARS = 2.366771e14\n\n @staticmethod\n def compute_answer() -> int:\n time.sleep(DeepThought.SEVEN_HALF_MIO_YEARS)\n return 42\n # deep_thought_test.py \nfrom deep_thought import DeepThought\n\ndef test_define_return_value(mocker) -> None:\n # We use the internal python lookup path to the method \n # as an identifier (from the location it is called) \n mocker.patch('deep_thought.DeepThought.compute_answer', return_value=12)\n assert DeepThought.compute_answer() == 12\n print"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20602700/"
] |
74,578,132
|
<p>I am trying to understand how $emit event works in vue so following this Guide: <a href="https://learnvue.co/tutorials/vue-emit-guide" rel="nofollow noreferrer">https://learnvue.co/tutorials/vue-emit-guide</a>,
I tried to do in similar way but with vue2 js and everytime I click the button its gives me rounded number but not random number as the Guide link.</p>
<p>I want to know where I am doing wrong and why in the guide line they are passing i variable
like this:</p>
<blockquote>
<p><ChildComponent @add="(i) => count += i" /></p>
</blockquote>
<p>My child component:</p>
<pre><code><template>
<div class="inline-emit">
<h1 class="mesg-text">{{ msg }}</h1>
<p>We can send data up from Child.vue</p>
<button class="btn" @click="$emit('add', Math.random())">
Add Math.random()
</button>
</div>
</template>
<script>
export default {
name: "InlineEmitEventChild",
props: {
msg: {
type: String,
default: "Example of an inline Emit",
},
},
};
</script>
</code></pre>
<p>my App.vue</p>
<pre><code>
<template>
<div id="app">
<h1>Emitting and Listening to Events</h1>
<InlineEmitEventChild @add="add(10)" />
<p class="count-text">
Count: <strong>{{ count }}</strong>
</p>
</div>
</template>
<script>
import InlineEmitEventChild from "./components/InlineEmitEventChild.vue";
export default {
name: "App",
components: {
InlineEmitEventChild,
},
data() {
return {
count: 0,
};
},
methods: {
add(i) {
this.count += i;
},
},
};
</script>
</code></pre>
<p>Getting always rounded number :</p>
<p><a href="https://i.stack.imgur.com/uodtf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uodtf.png" alt="enter image description here" /></a></p>
<p><strong>Should be as below:</strong></p>
<p><a href="https://i.stack.imgur.com/8xIKV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8xIKV.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74578155,
"author": "snakecharmerb",
"author_id": 5320906,
"author_profile": "https://Stackoverflow.com/users/5320906",
"pm_score": 1,
"selected": false,
"text": "sys.stdout print >>> import io\n>>> import contextlib\n>>> \n>>> def f():print('X')\n... \n>>> buf = io.StringIO()\n>>> with contextlib.redirect_stdout(buf):\n... f()\n... \n>>> print(repr(buf.getvalue()))\n'X\\n'\n>>> \n>>> buf.close()\n end '\\n'"
},
{
"answer_id": 74582378,
"author": "Cpt.Hook",
"author_id": 20599896,
"author_profile": "https://Stackoverflow.com/users/20599896",
"pm_score": 0,
"selected": false,
"text": "# production.py \n\ndef say_hello() -> None:\n print('Hello World.')\n # production_test.py\nfrom production import say_hello\n\ndef test_greeting(mocker):\n # The \"mocker\" fixture is auto-magicall inserted by pytest, \n # once the extenson 'pytest-mock' is installed\n printer = mocker.patch('builtins.print')\n say_hello()\n assert printer.call_count == 1\n printer # deep_though.py\n\nclass DeepThought:\n #: Seven and a half million years in seconds\n SEVEN_HALF_MIO_YEARS = 2.366771e14\n\n @staticmethod\n def compute_answer() -> int:\n time.sleep(DeepThought.SEVEN_HALF_MIO_YEARS)\n return 42\n # deep_thought_test.py \nfrom deep_thought import DeepThought\n\ndef test_define_return_value(mocker) -> None:\n # We use the internal python lookup path to the method \n # as an identifier (from the location it is called) \n mocker.patch('deep_thought.DeepThought.compute_answer', return_value=12)\n assert DeepThought.compute_answer() == 12\n print"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183650/"
] |
74,578,145
|
<p>`</p>
<pre><code>Already up to date.
venv "C:\StableDiffusion\stable-diffusion-webui\venv\Scripts\Python.exe"
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)]
Commit hash: 828438b4a190759807f9054932cae3a8b880ddf1
Installing requirements for Web UI
Launching Web UI with arguments:
Traceback (most recent call last):
File "launch.py", line 251, in <module>
start()
File "launch.py", line 242, in start
import webui
File "C:\StableDiffusion\stable-diffusion-webui\webui.py", line 13, in <module>
from modules import devices, sd_samplers, upscaler, extensions, localization
File "C:\StableDiffusion\stable-diffusion-webui\modules\sd_samplers.py", line 11, in <module>
from modules import prompt_parser, devices, processing, images
File "C:\StableDiffusion\stable-diffusion-webui\modules\processing.py", line 15, in <module>
import modules.sd_hijack
File "C:\StableDiffusion\stable-diffusion-webui\modules\sd_hijack.py", line 10, in <module>
import modules.textual_inversion.textual_inversion
File "C:\StableDiffusion\stable-diffusion-webui\modules\textual_inversion\textual_inversion.py", line 13, in <module>
from modules import shared, devices, sd_hijack, processing, sd_models, images, sd_samplers
File "C:\StableDiffusion\stable-diffusion-webui\modules\shared.py", line 8, in <module>
import gradio as gr
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\gradio\__init__.py", line 3, in <module>
import gradio.components as components
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\gradio\components.py", line 31, in <module>
from gradio import media_data, processing_utils, utils
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\gradio\processing_utils.py", line 20, in <module>
from gradio import encryptor, utils
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\gradio\utils.py", line 35, in <module>
import httpx
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\httpx\__init__.py", line 2, in <module>
from ._api import delete, get, head, options, patch, post, put, request, stream
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\httpx\_api.py", line 4, in <module>
from ._client import Client
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\httpx\_client.py", line 29, in <module>
from ._transports.default import AsyncHTTPTransport, HTTPTransport
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\httpx\_transports\default.py", line 30, in <module>
import httpcore
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\httpcore\__init__.py", line 1, in <module>
from ._api import request, stream
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\httpcore\_api.py", line 5, in <module>
from ._sync.connection_pool import ConnectionPool
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\httpcore\_sync\__init__.py", line 1, in <module>
from .connection import HTTPConnection
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\httpcore\_sync\connection.py", line 13, in <module>
from .http11 import HTTP11Connection
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\httpcore\_sync\http11.py", line 44, in <module> class HTTP11Connection(ConnectionInterface):
File "C:\StableDiffusion\stable-diffusion-webui\venv\lib\site-packages\httpcore\_sync\http11.py", line 140, in HTTP11Connection
self, event: h11.Event, timeout: Optional[float] = None
AttributeError: module 'h11' has no attribute 'Event'
Appuyez sur une touche pour continuer...
</code></pre>
<p>`</p>
<p>Hello everyone
I'm a newbie trying to use Stable Diffusion :'(
I tried to launch it for the first time but it got stuck each time to this error, I honestly don't really know what i'm supposed to do right now.</p>
|
[
{
"answer_id": 74578155,
"author": "snakecharmerb",
"author_id": 5320906,
"author_profile": "https://Stackoverflow.com/users/5320906",
"pm_score": 1,
"selected": false,
"text": "sys.stdout print >>> import io\n>>> import contextlib\n>>> \n>>> def f():print('X')\n... \n>>> buf = io.StringIO()\n>>> with contextlib.redirect_stdout(buf):\n... f()\n... \n>>> print(repr(buf.getvalue()))\n'X\\n'\n>>> \n>>> buf.close()\n end '\\n'"
},
{
"answer_id": 74582378,
"author": "Cpt.Hook",
"author_id": 20599896,
"author_profile": "https://Stackoverflow.com/users/20599896",
"pm_score": 0,
"selected": false,
"text": "# production.py \n\ndef say_hello() -> None:\n print('Hello World.')\n # production_test.py\nfrom production import say_hello\n\ndef test_greeting(mocker):\n # The \"mocker\" fixture is auto-magicall inserted by pytest, \n # once the extenson 'pytest-mock' is installed\n printer = mocker.patch('builtins.print')\n say_hello()\n assert printer.call_count == 1\n printer # deep_though.py\n\nclass DeepThought:\n #: Seven and a half million years in seconds\n SEVEN_HALF_MIO_YEARS = 2.366771e14\n\n @staticmethod\n def compute_answer() -> int:\n time.sleep(DeepThought.SEVEN_HALF_MIO_YEARS)\n return 42\n # deep_thought_test.py \nfrom deep_thought import DeepThought\n\ndef test_define_return_value(mocker) -> None:\n # We use the internal python lookup path to the method \n # as an identifier (from the location it is called) \n mocker.patch('deep_thought.DeepThought.compute_answer', return_value=12)\n assert DeepThought.compute_answer() == 12\n print"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20602797/"
] |
74,578,175
|
<p>I am using Selenium in Python to scrape the videos from Youtube channels' websites. Below is a set of code. The line <code>videos = driver.find_elements(By.CLASS_NAME, 'style-scope ytd-grid-video-renderer')</code> repeatedly returns no links to the videos (a.k.a. the <code>print(videos)</code> after it outputs an empty list). How would you modify it to find all the videos on the loaded page?</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get('https://www.youtube.com/wendoverproductions/videos')
videos = driver.find_elements(By.CLASS_NAME, 'style-scope ytd-grid-video-renderer')
print(videos)
urls = []
titles = []
dates = []
for video in videos:
video_url = video.find_element(by=By.XPATH, value='.//*[@id="video-title"]').get_attribute('href')
urls.append(video_url)
video_title = video.find_element(by=By.XPATH, value='.//*[@id="video-title"]').text
titles.append(video_title)
video_date = video.find_element(by=By.XPATH, value='.//*[@id="metadata-line"]/span[2]').text
dates.append(video_date)
</code></pre>
|
[
{
"answer_id": 74578155,
"author": "snakecharmerb",
"author_id": 5320906,
"author_profile": "https://Stackoverflow.com/users/5320906",
"pm_score": 1,
"selected": false,
"text": "sys.stdout print >>> import io\n>>> import contextlib\n>>> \n>>> def f():print('X')\n... \n>>> buf = io.StringIO()\n>>> with contextlib.redirect_stdout(buf):\n... f()\n... \n>>> print(repr(buf.getvalue()))\n'X\\n'\n>>> \n>>> buf.close()\n end '\\n'"
},
{
"answer_id": 74582378,
"author": "Cpt.Hook",
"author_id": 20599896,
"author_profile": "https://Stackoverflow.com/users/20599896",
"pm_score": 0,
"selected": false,
"text": "# production.py \n\ndef say_hello() -> None:\n print('Hello World.')\n # production_test.py\nfrom production import say_hello\n\ndef test_greeting(mocker):\n # The \"mocker\" fixture is auto-magicall inserted by pytest, \n # once the extenson 'pytest-mock' is installed\n printer = mocker.patch('builtins.print')\n say_hello()\n assert printer.call_count == 1\n printer # deep_though.py\n\nclass DeepThought:\n #: Seven and a half million years in seconds\n SEVEN_HALF_MIO_YEARS = 2.366771e14\n\n @staticmethod\n def compute_answer() -> int:\n time.sleep(DeepThought.SEVEN_HALF_MIO_YEARS)\n return 42\n # deep_thought_test.py \nfrom deep_thought import DeepThought\n\ndef test_define_return_value(mocker) -> None:\n # We use the internal python lookup path to the method \n # as an identifier (from the location it is called) \n mocker.patch('deep_thought.DeepThought.compute_answer', return_value=12)\n assert DeepThought.compute_answer() == 12\n print"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8141320/"
] |
74,578,191
|
<p>I have a messy character variable like:</p>
<pre><code>df<-c("_oun_", "0000ff", "03815", "?3jhdb", "test", "1,000", "1.000")
</code></pre>
<p>and I would like to filter out all values that are not words. I thought a start would be to filter out all values not starting with a character.</p>
<p>How can I do this with <code>tidyverse</code>? For the above mentioned example, the desired output would be <code>test</code>.</p>
|
[
{
"answer_id": 74578260,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 3,
"selected": true,
"text": "stringr ^ [:alpha:] + str_subset(df, \"^[:alpha:]+\")\n[1] \"test\"\n df[str_detect(df, \"^[:alpha:]+\")]\n[1] \"test\"\n df[str_which(df, \"^[:alpha:]+\")]\n[1] \"test\"\n str_extract(df, \"^[:alpha:]+\")\n[1] NA NA NA NA \"test\" NA NA\n"
},
{
"answer_id": 74587253,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "words df<-c(\"_oun_\", \"0000ff\", \"03815\", \"?3jhdb\", \"test\", \"1,000\", \"1.000\")\n\ndf[df %in% words::words$word]\n#> [1] \"test\"\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/906592/"
] |
74,578,211
|
<p>I am creating app which will comunicate with API of shop. I have written around 30 classes representing requests to API and I am wondering how to run these request parallel.</p>
<p>I have tried to done it with <code>List</code> of tasks but it does not work beacouse of imprecise returning type of function.</p>
<p><strong>For example these are request classes:</strong></p>
<pre><code>public class GetOrderStatusList : IRequest<GetOrderStatusList.Response> {
public class Status {
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
}
public class Response : Output {
[JsonPropertyName("statuses")]
public List<Status> Statuses { get; set; }
}
}
</code></pre>
<pre><code>public class GetProductsPrices : IRequest<GetProductsPrices.Response> {
[JsonPropertyName("storage_id")]
public string StorageId { get; set; }
public class Product {
public class Variant {
[JsonPropertyName("variant_id")]
public int VariantId { get; set; }
[JsonPropertyName("price")]
public decimal Price { get; set; }
}
[JsonPropertyName("product_id")]
public int ProductId { get; set; }
[JsonPropertyName("price")]
public decimal Price { get; set; }
[JsonPropertyName("variants")]
public List<Variant> Variants { get; set; }
}
public class Response : Output {
[JsonPropertyName("storage_id")]
public string StorageId { get; set; }
[JsonPropertyName("products")]
public List<Product> Products { get; set; }
}
}
</code></pre>
<p><strong>Output, IRequest and method which sends request to server:</strong></p>
<pre><code>public interface IRequest<TResponse> { }
public class Output {
[JsonPropertyName("status")]
public string Status { get; set; }
[JsonPropertyName("error_message")]
public string? ErrorMessage { get; set; }
[JsonPropertyName("error_code")]
public string? ErrorCode { get; set; }
}
public async Task<TResponse> SendRequestAsync<TResponse>(IRequest<TResponse> userRequest) where TResponse : Output {
var client = new RestClient(_url);
var method = GetRequestMethodName(userRequest);
var request = CreateRequest(method, userRequest);
var response = await ExecuteRequestAsync(client, request);
var serializedResponse = JsonSerializer.Deserialize<TResponse>(response.Content);
if( serializedResponse.Status == "ERROR") {
throw new BaselinkerException(serializedResponse.ErrorMessage, serializedResponse.ErrorCode);
}
return serializedResponse;
}
</code></pre>
|
[
{
"answer_id": 74578604,
"author": "Stephen Cleary",
"author_id": 263693,
"author_profile": "https://Stackoverflow.com/users/263693",
"pm_score": 1,
"selected": false,
"text": "List<Task<Output>> List<Task>"
},
{
"answer_id": 74586252,
"author": "tymtam",
"author_id": 581076,
"author_profile": "https://Stackoverflow.com/users/581076",
"pm_score": -1,
"selected": false,
"text": "using System.Diagnostics;\n\nvar sw = Stopwatch.StartNew();\n\nvar t1 = F1();\nvar t2 = F2();\n\n\nvar n = await t1;\nvar s = await t2;\n\nConsole.WriteLine($\"Elapsed {sw.ElapsedMilliseconds}\");\n\nasync Task<int> F1()\n{\n await Task.Delay(TimeSpan.FromMilliseconds(100));\n return 7;\n}\n\nasync Task<string> F2()\n{\n await Task.Delay(TimeSpan.FromMilliseconds(200));\n return \"waves\";\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20444760/"
] |
74,578,213
|
<p>In my folder Templates I created 2 html files:</p>
<ul>
<li>main.html</li>
<li>user.html</li>
</ul>
<p>The structure of the main.html is:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DJANGO</title>
</head>
<body>
{% block userinfo %}
{% endblock userinfo %}
</body>
</html>
</code></pre>
<p>The structure of the user.html is:</p>
<pre><code>{% extends "main.html" %}
{% block userinfo %}
<h2>John Doe</h2>
<p>Explorer of life.</p>
{% endblock userinfo %}
</code></pre>
<p>I don't understand why</p>
<pre><code><h2>John Doe</h2>
<p>Explorer of life.</p>
</code></pre>
<p>doesn't appear in the browser when I call main.html</p>
<p>I have tried writing in this way too</p>
<pre><code>{% extends "main.html" %}
{% block userinfo %}
<h2>John Doe</h2>
<p>Explorer of life.</p>
{% endblock %}
</code></pre>
<p>without user in the endblock but it does not work.</p>
<p>In settings.py file in Templates list and DIR list I added:</p>
<pre><code>os.path.join(BASE_DIR,'templates'),
</code></pre>
<p>and I importend os too.</p>
<p>In views.py file that I've created I have written</p>
<pre><code>
from django.shortcuts import render
from django.http import HttpResponse
def main(request):
return render(request,'main.html')
</code></pre>
<p>In urls.py file that I've created I have written</p>
<pre><code>from django.urls import path
from . import views
urlpatterns = [
path('main/',views.main,name='')
]
</code></pre>
<p>When I call the page with http://localhost:8000/main/
I don't have any error. The only problem is that the page is blank.
And If I try to add some text in main.html it appers on the screen, but the content from user.html doesn't appear.</p>
<p>Can someone help me?</p>
|
[
{
"answer_id": 74578604,
"author": "Stephen Cleary",
"author_id": 263693,
"author_profile": "https://Stackoverflow.com/users/263693",
"pm_score": 1,
"selected": false,
"text": "List<Task<Output>> List<Task>"
},
{
"answer_id": 74586252,
"author": "tymtam",
"author_id": 581076,
"author_profile": "https://Stackoverflow.com/users/581076",
"pm_score": -1,
"selected": false,
"text": "using System.Diagnostics;\n\nvar sw = Stopwatch.StartNew();\n\nvar t1 = F1();\nvar t2 = F2();\n\n\nvar n = await t1;\nvar s = await t2;\n\nConsole.WriteLine($\"Elapsed {sw.ElapsedMilliseconds}\");\n\nasync Task<int> F1()\n{\n await Task.Delay(TimeSpan.FromMilliseconds(100));\n return 7;\n}\n\nasync Task<string> F2()\n{\n await Task.Delay(TimeSpan.FromMilliseconds(200));\n return \"waves\";\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20602742/"
] |
74,578,223
|
<p>I have a text file, named my_data.txt, with the following contents:</p>
<pre><code># define var1 and var2
var1=101
var2=202
// display var1 and var2
echo ${var1}
echo ${var2}
</code></pre>
<p>I want search all occurrences of var1 but not those in a line starts with '#' or '//'. I can do this:</p>
<pre><code>grep var1 my_data.txt | grep -v '^#' | grep -v '^//'
</code></pre>
<p>output:</p>
<pre><code>var1=101
echo ${var1}
</code></pre>
<p>The results is correct. The question: is there any way to pass both values '^#' and '^//' to a single -v option?</p>
|
[
{
"answer_id": 74578238,
"author": "Cyrus",
"author_id": 3776858,
"author_profile": "https://Stackoverflow.com/users/3776858",
"pm_score": 2,
"selected": false,
"text": "grep -v -e '^#' -e '^//' file | grep 'var1'\n -E grep -v -E '^(#|//)' file | grep 'var1'\n"
},
{
"answer_id": 74580809,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 1,
"selected": false,
"text": "grep -P \"^(?!#|//).*\\bvar1\\b\" my_data.txt\n ^ (?!#|//) # // .*\\bvar1\\b awk awk '/^(#|\\/\\/)/{next};index($0, \"var1\")' my_data.txt\n var1=101\necho ${var1}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1667163/"
] |
74,578,232
|
<p>I am using bootstraps navigation bar and I inserted an image to the navbar brand yet because of the size it messes up the alignment. I want the text that goes along with it to line up with the middle of it like it is, yet I can't figure out how to get the other button text to line up with it as well.</p>
<p>This is what it looks like <a href="https://i.stack.imgur.com/QoiNL.png" rel="nofollow noreferrer">Output</a></p>
<pre><code><a class ="navbar-brand" id="home" href="/">
<img src="https://cdn.discordapp.com/attachments/901496285759168554/1045812932535128084/jeffersonlogo.webp" width="40" height="60" class="d-inline-block align-middle" alt="">
Jefferson Robotics</a>
<a class="nav-item nav-link" id="water" href="/underwater">Underwater</a>
<a class="nav-item nav-link" id="sky" href="/aerial">Aerial</a>
<a class="nav-item nav-link" id="earth" href="/land">Land</a>
</code></pre>
<p>I tried using alignments on the nav-items but it doesn't change anything no matter what I do, this is my first time using bootstrap and I have limited html knowledge so I am quite lost on what to do :(</p>
|
[
{
"answer_id": 74578238,
"author": "Cyrus",
"author_id": 3776858,
"author_profile": "https://Stackoverflow.com/users/3776858",
"pm_score": 2,
"selected": false,
"text": "grep -v -e '^#' -e '^//' file | grep 'var1'\n -E grep -v -E '^(#|//)' file | grep 'var1'\n"
},
{
"answer_id": 74580809,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 1,
"selected": false,
"text": "grep -P \"^(?!#|//).*\\bvar1\\b\" my_data.txt\n ^ (?!#|//) # // .*\\bvar1\\b awk awk '/^(#|\\/\\/)/{next};index($0, \"var1\")' my_data.txt\n var1=101\necho ${var1}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20163139/"
] |
74,578,252
|
<p>Methods are underlined in red. I have tried to figure out why this is happening, but I keep running into cannot resolve method. I have the methods in the main TextoToSpeechExample1 class and am invoking the methods in my gui class.</p>
<pre><code>
class TextToSpeechExample1 {
public static void main(String args[]) throws IOException, EngineException, AudioException, InterruptedException {
static void start(){
// code to be executed
String fileName = "/Users/stevenshivayka/Documents/kjv.txt";
Path path = Paths.get(fileName);
byte[] bytes = Files.readAllBytes(path);
List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);
//setting properties as Kevin Dictionary
System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us" + ".cmu_us_kal.KevinVoiceDirectory");
//registering speech engine
Central.registerEngineCentral("com.sun.speech.freetts" + ".jsapi.FreeTTSEngineCentral");
//create a Synthesizer that generates voice
Synthesizer synthesizer = Central.createSynthesizer(new SynthesizerModeDesc(Locale.US));
//allocates a synthesizer
synthesizer.allocate();
//resume a Synthesizer
synthesizer.resume();
//speak the specified text until the QUEUE become empty
synthesizer.speakPlainText(allLines.toString(), null);
synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
//deallocating the Synthesizer
synthesizer.deallocate();
}
public static void pause(){
Synthesizer synthesizer = Central.createSynthesizer(new SynthesizerModeDesc(Locale.US));
synthesizer.allocate();
synthesizer.resume();
synthesizer.deallocate();
synthesizer.pause();
}
}
}
class gui {
public static void main(String args[]) {
JFrame frame = new JFrame("Babbel Audio Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLayout(new FlowLayout());
JButton button = new JButton("Start Audio");
frame.add(button); // Adds Button to content pane of frame
frame.setVisible(true);
JButton button2 = new JButton("Pause Audio");
frame.add(button2);
frame.setVisible(true);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//your actions
TextToSpeechExample1.start();
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//your actions
pause();
}
});
}
}
</code></pre>
<p>`</p>
<p>I expected the methods to be invoked. Please if you can review this and see what I am doing wrong I would greatly appreciate it. This is a project I am working on myself.</p>
|
[
{
"answer_id": 74578238,
"author": "Cyrus",
"author_id": 3776858,
"author_profile": "https://Stackoverflow.com/users/3776858",
"pm_score": 2,
"selected": false,
"text": "grep -v -e '^#' -e '^//' file | grep 'var1'\n -E grep -v -E '^(#|//)' file | grep 'var1'\n"
},
{
"answer_id": 74580809,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 1,
"selected": false,
"text": "grep -P \"^(?!#|//).*\\bvar1\\b\" my_data.txt\n ^ (?!#|//) # // .*\\bvar1\\b awk awk '/^(#|\\/\\/)/{next};index($0, \"var1\")' my_data.txt\n var1=101\necho ${var1}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20602859/"
] |
74,578,262
|
<p>I have a Google Sheet with daily ranked items expanding with new data everyday in the Raw Data Table A2:C.</p>
<p>I would like to generate a report matrix similar to table in E2:J using one formula so that we don't need to manually copy formulas in each cells in the report table from time to time.</p>
<p>It would be ideal to have one formula at cell E2 (or E3, F1, F2) only that will automatically generate as many rows and columns in the report table based on the data in Raw Data Table. This way, the report table will not needed to be maintained on a daily basis (like copying formula everyday as data expanded).</p>
<p>There are less elegant ways to do it like pre-copy formula into a large number of cells or using Google App Script to generate the table. However, I believe an advance query() or a complex formula mixing query(), filters() and/or arrayformula() can do the job! Just wonder if anyone of the Google Sheets query() expert can help!</p>
<p><a href="https://i.stack.imgur.com/0DHVi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0DHVi.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74578364,
"author": "ztiaa",
"author_id": 17887301,
"author_profile": "https://Stackoverflow.com/users/17887301",
"pm_score": 0,
"selected": false,
"text": "=ArrayFormula(LAMBDA(dates,ranks,{A2,ranks;dates,IFNA(VLOOKUP(dates&ranks,{A3:A&B3:B,C3:C},2,0))})\n(UNIQUE(A3:A),TRANSPOSE(UNIQUE(SORT(B3:B)))))\n"
},
{
"answer_id": 74578427,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 1,
"selected": false,
"text": "=QUERY(A2:C; \"select A,max(C) where A is not null group by A pivot B\"; 1)\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7570858/"
] |
74,578,272
|
<p>I am making a simple game, at the beginning you can choose the amount of players, which is between 2 and 5 (shown below) I am having problem with assigning the initial amount of points, which is 100 points. Also, not sure where to place the code regarding the points in my woring code below.
When I start working on the game, after each dice moevent the score would increase.</p>
<pre><code>players_list= []
max_players= 5
max_players = int(input(" Please, insert the number of players? : "))
while (max_players <2) or (max_players > 5) :
max_players = int(input(" Number of players must be between 2 and 5.Number of players ?"))
players_list = []
while len(players_list) < max_players:
player1 = input(" Enter your first and last name? : ")
players_list.append(player1)
print("Players in the game : ")
print(players_list)
</code></pre>
<p>Should I change the players list into a dictionary?</p>
<p>The code with the score system that does not work</p>
<pre><code>score=100
players_list= []
max_players= 5
max_players = int(input(" Please, insert the number of players? : "))
while (max_players <2) or (max_players > 5) :
max_players = int(input(" Number of players must be between 2 and 5.Number of players ?"))
players_list = []
while len(players_list) < max_players:
player1 = input(" Enter your first and last name? : ")
players_list.append(player1)
print("Players in the game : ")
players_list.appened (players)= { score:100}
print(players_list)
print(score)
</code></pre>
|
[
{
"answer_id": 74578567,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "players_dict = {}\nscore = 100\n\nmax_players = -1\nwhile not (2 <= max_players <= 5):\n max_players = int(input(\"Please, insert the number of players: \"))\n\nwhile len(players_dict) < max_players:\n player = input(\"Enter your first and last name: \")\n if player in players_dict:\n print(f\"Player {player} already exists, choose another name\")\n else:\n players_dict[player] = score\n\nprint(players_dict)\n Please, insert the number of players: 1\nPlease, insert the number of players: 3\nEnter your first and last name: John\nEnter your first and last name: Adam\nEnter your first and last name: John\nPlayer John already exists, choose another name\nEnter your first and last name: Lucy\n{'John': 100, 'Adam': 100, 'Lucy': 100}\n"
},
{
"answer_id": 74578655,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 0,
"selected": false,
"text": "score=100\nplayers_list= []\nmax_players= 0\nwhile (max_players <2) or (max_players > 5) :\n try:\n max_players = int(input(\" Number of players must be between 2 and 5.Number of players ?\"))\n except Exception as e:\n print(f\"Invalid input: {e}\")\nwhile len(players_list) < max_players:\n name, surname = input(\" Enter your first and last name? : \").split(\" \")\n player = {\"name\": name, \"surname\": surname, \"points\": score}\n players_list.append(player)\n print(f\"Players in the game : {players_list}\")\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20543942/"
] |
74,578,308
|
<p>I am looking to create a repetitive pattern from a single shape (in the example below, the starting shape would be the smallest centre star) using Python. The pattern would look something like this:</p>
<p><a href="https://i.stack.imgur.com/2Gck9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2Gck9.png" alt="pattern to be generated" /></a></p>
<p>To give context, I am working on a project that uses a camera to detect a shape on a rectangle of sand. The idea is that the ripple pattern is drawn out around the object using a pen plotter-type mechanism in the sand to create a zen garden-type feature.</p>
<p>Currently, I am running the Canny edge detection algorithm to create a png (in this example it would be the smallest star). I am able to convert this into an SVG using potrace, but am not sure how to create the ripple pattern (and at what stage, i.e. before converting to an SVG, or after).</p>
<p>Any help would be appreciated!</p>
|
[
{
"answer_id": 74578567,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "players_dict = {}\nscore = 100\n\nmax_players = -1\nwhile not (2 <= max_players <= 5):\n max_players = int(input(\"Please, insert the number of players: \"))\n\nwhile len(players_dict) < max_players:\n player = input(\"Enter your first and last name: \")\n if player in players_dict:\n print(f\"Player {player} already exists, choose another name\")\n else:\n players_dict[player] = score\n\nprint(players_dict)\n Please, insert the number of players: 1\nPlease, insert the number of players: 3\nEnter your first and last name: John\nEnter your first and last name: Adam\nEnter your first and last name: John\nPlayer John already exists, choose another name\nEnter your first and last name: Lucy\n{'John': 100, 'Adam': 100, 'Lucy': 100}\n"
},
{
"answer_id": 74578655,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 0,
"selected": false,
"text": "score=100\nplayers_list= []\nmax_players= 0\nwhile (max_players <2) or (max_players > 5) :\n try:\n max_players = int(input(\" Number of players must be between 2 and 5.Number of players ?\"))\n except Exception as e:\n print(f\"Invalid input: {e}\")\nwhile len(players_list) < max_players:\n name, surname = input(\" Enter your first and last name? : \").split(\" \")\n player = {\"name\": name, \"surname\": surname, \"points\": score}\n players_list.append(player)\n print(f\"Players in the game : {players_list}\")\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11283294/"
] |
74,578,326
|
<p>I am completely new to SpringBoot and i have following along with a Course on YT.</p>
<p><strong>Request:</strong></p>
<p><a href="https://i.stack.imgur.com/csgPS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/csgPS.png" alt="enter image description here" /></a></p>
<p><strong>DemoApplication.java</strong></p>
<pre><code>package com.sbt.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping
public String hello() {
return "Hello World";
}
}
</code></pre>
<p>In the course he is able to get a response of "Hello World" but i keep getting</p>
<pre><code>Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Nov 25 16:24:31 CST 2022
There was an unexpected error (type=Not Found, status=404).
</code></pre>
<p>I've added the <code>@RestController</code> annotation like other similar questions with answers to recommend, but i keep getting the error.</p>
<p>I also restarted the server and retried and keeping getting the error.</p>
<p><strong>pom.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"
>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.0</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.sbt</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
</code></pre>
|
[
{
"answer_id": 74578480,
"author": "Nick",
"author_id": 9249298,
"author_profile": "https://Stackoverflow.com/users/9249298",
"pm_score": 0,
"selected": false,
"text": " @GetMapping(\"/\")\n public String hello() {\n return \"Hello World\";\n }\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9249298/"
] |
74,578,340
|
<p>How to run the same query multiple times in SQL Server?</p>
<p>Simple example, I have a query</p>
<pre><code>select * from sys.databases
</code></pre>
<p>I wanted to run it N times, because I wanted to return the data in a dashboard in "real time", until I stopped the execution, the select would need to continue running "example: as SQL Server Profiler does, while I don't stop, it keeps bringing the information in the screen".</p>
<p>What would be the best way for this type of situation?</p>
<p>Remembering that the query and SQL Server profiler are just examples.</p>
|
[
{
"answer_id": 74578480,
"author": "Nick",
"author_id": 9249298,
"author_profile": "https://Stackoverflow.com/users/9249298",
"pm_score": 0,
"selected": false,
"text": " @GetMapping(\"/\")\n public String hello() {\n return \"Hello World\";\n }\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14706560/"
] |
74,578,365
|
<p>I would like to "transform" JSON data with a specific syntax in HTML.
look at the code below</p>
<p>any idea?</p>
<p>tk</p>
<p>JSON :</p>
<pre><code>[
{
"name_host": "test",
"ip": "127.0.0.1",
"place": "local",
"status": "online"
},
{
"name_host": "test2",
"ip": "127.0.0.1",
"place": "local",
"status": "online"
}
]
</code></pre>
<p>HTML expected :</p>
<pre><code><tbody>
<tr>
<td>"value of name_host"</td>
<td>"value of ip</td>
<td>"value of place"</td>
<td>"value of status"</td>
</tr>
</tbody>
</code></pre>
|
[
{
"answer_id": 74578480,
"author": "Nick",
"author_id": 9249298,
"author_profile": "https://Stackoverflow.com/users/9249298",
"pm_score": 0,
"selected": false,
"text": " @GetMapping(\"/\")\n public String hello() {\n return \"Hello World\";\n }\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20316788/"
] |
74,578,381
|
<p>I have</p>
<pre><code>df<-c("That's","you're", "'am")
</code></pre>
<p>and I would like to remove the part of a word after and including the apostrophe which should return</p>
<pre><code>c("That", "you", "")
</code></pre>
<p><code>tidyverse</code> solution or a solution usable within a pipe <code>|></code> structure preferable</p>
|
[
{
"answer_id": 74578441,
"author": "Jonathan V. Solórzano",
"author_id": 9022665,
"author_profile": "https://Stackoverflow.com/users/9022665",
"pm_score": 3,
"selected": true,
"text": "' str_replace stringr library(stringr)\n\nstr_replace(df, \"'.*\", \"\") \n#[1] \"That\" \"you\" \"\" \n"
},
{
"answer_id": 74578506,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": false,
"text": "sub > sub(\"'.*\", \"\", df)\n[1] \"That\" \"you\" \"\" \n"
},
{
"answer_id": 74578729,
"author": "shaun_m",
"author_id": 18289387,
"author_profile": "https://Stackoverflow.com/users/18289387",
"pm_score": 1,
"selected": false,
"text": "gsub(\"'\\\\w*\\\\b\",\"\",df)\n"
},
{
"answer_id": 74579477,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "trimws base R trimws(df, whitespace = \"'.*\")\n[1] \"That\" \"you\" \"\" \n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/906592/"
] |
74,578,393
|
<p>There is an array <code>[350, 456, "Not Found"]</code>. I want to sort it, and I want to get the lowest value(350). Could you help?</p>
<pre><code>
var urunAdi = [350, 456, "NotFound"];
urunAdi.sort(function(a,b){return a-b});
var lowestPrice = urunAdi[0];
</code></pre>
<p>After sorting like this (350 - 456 - "NotFound"), I want it to find 350 as the lowest value.</p>
|
[
{
"answer_id": 74578441,
"author": "Jonathan V. Solórzano",
"author_id": 9022665,
"author_profile": "https://Stackoverflow.com/users/9022665",
"pm_score": 3,
"selected": true,
"text": "' str_replace stringr library(stringr)\n\nstr_replace(df, \"'.*\", \"\") \n#[1] \"That\" \"you\" \"\" \n"
},
{
"answer_id": 74578506,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": false,
"text": "sub > sub(\"'.*\", \"\", df)\n[1] \"That\" \"you\" \"\" \n"
},
{
"answer_id": 74578729,
"author": "shaun_m",
"author_id": 18289387,
"author_profile": "https://Stackoverflow.com/users/18289387",
"pm_score": 1,
"selected": false,
"text": "gsub(\"'\\\\w*\\\\b\",\"\",df)\n"
},
{
"answer_id": 74579477,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "trimws base R trimws(df, whitespace = \"'.*\")\n[1] \"That\" \"you\" \"\" \n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20599565/"
] |
74,578,414
|
<p>In a current assignment I am trying to print out the array which has the highest value along with the array number itself. However with the code I have it is printing the array number as the same as the the array value. With the input values of 4, 9, 3, 7, and 6 the output should be Day #2 with 9 hours worked, but it outputs Day #9 with 9 hours worked. Any help appreciated!</p>
<pre><code>import java.util.*;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Scanner userinput = new Scanner(System.in);
System.out.print("Enter hours worked on day #1: ");
int Day1hours = userinput.nextInt();
System.out.print("Enter hours worked on day #2: ");
int Day2hours = userinput.nextInt();
System.out.print("Enter hours worked on day #3: ");
int Day3hours = userinput.nextInt();
System.out.print("Enter hours worked on day #4: ");
int Day4hours = userinput.nextInt();
System.out.print("Enter hours worked on day #5: ");
int Day5hours = userinput.nextInt();
ArrayList<Integer> day = new ArrayList<Integer>();
day.add(Day1hours);
day.add(Day2hours);
day.add(Day3hours);
day.add(Day4hours);
day.add(Day5hours);
double avg;
int sum = 0;
int mosthours = Collections.max(day);
System.out.println("The most hours worked was on: ");
for (int i = 0; i < day.size(); i++) {
int daywithmosthours = day.get(i);
if (day.get(i) == mosthours) {
System.out.println("Day #" + daywithmosthours + " when you worked " + mosthours + " Hours.");
}
}
}
}
</code></pre>
|
[
{
"answer_id": 74578441,
"author": "Jonathan V. Solórzano",
"author_id": 9022665,
"author_profile": "https://Stackoverflow.com/users/9022665",
"pm_score": 3,
"selected": true,
"text": "' str_replace stringr library(stringr)\n\nstr_replace(df, \"'.*\", \"\") \n#[1] \"That\" \"you\" \"\" \n"
},
{
"answer_id": 74578506,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": false,
"text": "sub > sub(\"'.*\", \"\", df)\n[1] \"That\" \"you\" \"\" \n"
},
{
"answer_id": 74578729,
"author": "shaun_m",
"author_id": 18289387,
"author_profile": "https://Stackoverflow.com/users/18289387",
"pm_score": 1,
"selected": false,
"text": "gsub(\"'\\\\w*\\\\b\",\"\",df)\n"
},
{
"answer_id": 74579477,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "trimws base R trimws(df, whitespace = \"'.*\")\n[1] \"That\" \"you\" \"\" \n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20602944/"
] |
74,578,433
|
<p>I have a simple backend code which works well with Rest API</p>
<p>updated code</p>
<p>ClientSchema.js</p>
<pre><code>const mongoose = require('mongoose');
var Schema = mongoose.Schema;
const customerSchema = new Schema({
paymentReferenceCode:{
type: String,
required: true
},
paymentType:{
type: String,
required: true
},
paymentDescription:{
type: String,
required: true
},
procedureAmount:{
type: String,
required: true
},
paymentDiscount:{
type: Number,
required: true
},
AmountPaid:{
type: Number,
required: true
},
Total:{
type: Number,
required: true
},
clientdetails: {
ref: 'Client',
type: mongoose.Schema.Types.ObjectId
},
}, { timestamps: true })
module.exports = mongoose.model('Customer',customerSchema);
</code></pre>
<p>Client.js</p>
<pre><code>const mongoose = require('mongoose');
const ClientSchema = new mongoose.Schema({
fullName:{
type:String,
required: true
},
dateofBirth:{
type:Date,
required: true
},
gender:{
type:String,
required: true
},
nationality:{
type:String,
required: true
},
address:{
type:String,
required: true
},
date:{
type:Date,
default:Date.now
}
});
module.exports = mongoose.model('Client', ClientSchema)
</code></pre>
<p>Router.js</p>
<pre><code>router.post("/addbill",async(req,res)=>{
try {
console.log(req.params);
const clientid = await clients.findOne({ _id: req.params.id });
await new Customer({
clientdetails:clientid,
paymentReferenceCode:req.body.paymentReferenceCode,
paymentType:req.body.paymentType,
paymentDescription:req.body.paymentDescription,
procedureAmount:req.body.procedureAmount,
paymentDiscount:req.body.paymentDiscount,
AmountPaid:req.body.AmountPaid,
Total:req.body.Total
}).save(async (err, data) => {
if (err) {
console.log('err:', err);
res.status(500).json({
message: 'Something went wrong, please try again later.'
});
} else {
res.status(200).json({
message: 'Bill Created',
data,
id: data._id
});
}
});
} catch (error) {
res.status(422).json(error);
}
})
router.get('/', async (req, res) => {
try{
const data = await clients.find();
res.json(data)
}
catch(error){
res.status(500).json({message: error.message})
}
})
</code></pre>
<p>Frontend</p>
<p>Billing.js</p>
<pre><code>import React, {Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css"
import axios from "axios"
import SimpleReactValidator from "simple-react-validator"
import TextField from '@mui/material/TextField';
import $ from 'jquery'
import Select,{components} from "react-select";
import Box from '@mui/material/Box';
import NativeSelect from "@mui/material/NativeSelect";
import Button from "@mui/material/Button";
class Billing extends Component {
constructor(){
super()
this.state = {
clientdetails :{},
paymentReferenceCode: "",
paymentType: "",
paymentDescription: "",
procedureAmount: "",
paymentDiscount: "",
AmountPaid: "",
Total: "",
}
this.changePaymentReferenceCode = this.changePaymentReferenceCode.bind(this)
this.changePaymentType = this.changePaymentType.bind(this)
this.changePaymentDescription = this.changePaymentDescription.bind(this)
this.changeProcedureAmount = this.changeProcedureAmount.bind(this)
this.changePaymentDiscount = this.changePaymentDiscount.bind(this)
this.changeAMountPaid = this.changeAMountPaid.bind(this)
this.changeTOtal = this.changeTOtal.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
}
changePaymentReferenceCode(event){
this.setState({
paymentReferenceCode:event.target.value
})
}
changeProcedureAmount(event){
this.setState({
procedureAmount:event.target.value
})
}
changePaymentType(event){
this.setState({
paymentType:event.target.value
})
}
changePaymentDescription(event){
this.setState({
paymentDescription:event.target.value
})
}
changePaymentAmount(event){
this.setState({
paymentAmount:event.target.value
})
}
changePaymentDiscount(event){
this.setState({
paymentDiscount:event.target.value
})
}
changeAMountPaid(event){
this.setState({
AmountPaid:event.target.value
})
}
changeTOtal(event){
this.setState({
Total:event.target.value
})
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
})
}
componentDidMount(){
this.loadData();
}
loadData = () => {
axios.get('http://localhost:4000/clients', {
headers: {"Access-Control-Allow-Origin": true,
'Access-Control-Allow-Credentials' : true,
'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
crossorigin : true,
},
responseType : 'json'
})
.then((result) => {
console.log(result.data);
this.setState({
clients : result.data,
})
})
.catch((error) => {
console.log(error);
})
}
customFilter = (option, searchText) => {
if(
option.data.fullName.toLowerCase().includes(searchText.toLowerCase())
)
return true;
return false;
}
handleSubmit(event){
event.preventDefault()
const entry = {
paymentReferenceCode: this.state.paymentReferenceCode,
paymentType: this.state.paymentType,
paymentDescription: this.state.paymentDescription,
procedureAmount: this.state.procedureAmount,
paymentDiscount: this.state.paymentDiscount,
AmountPaid: this.state.AmountPaid,
Total: this.state.Total,
}
axios.post('http://localhost:4000/Bill/addbill', entry)
.then(response => {
this.setState({clientdetails: response.data})
console.log(response.data)
})
this.setState({
clientdetails:{},paymentReferenceCode: "",paymentType: "",paymentDescription: "",procedureAmount: "",
paymentDiscount: "",AmountPaid: "",Total: "",
})}
render() {
const displayNone = { display: 'none' }
return (
<div>
<div className="container">
<div className="form-div">
<p className="text-capitalize">Billing</p>
<Box component="form" onSubmit={this.handleSubmit} noValidate sx={{ mt: 1}}>
<Select
closeMenuOnSelect={true}
hideSelectedOptions={true}
options={this.state.clientdetails}
filterOption = {this.customFilter}
isClearable={true}
search={true}
components={{IndicatorSeparator: () => null,}}
placeholder={'Select Client'}
getOptionLabel={option => `${option.fullName} ${option._id}`}
onchange={this.customFilter}
></Select>
<TextField
margin="normal"
fullWidth
id="paymentReferenceCode"
label="PaymentRefernceCode"
name="paymentReferenceCode"
autoComplete="off"
value={this.state.paymentReferenceCode}
onChange={this.handleChange}
autoFocus
/>
<NativeSelect
fullWidth
onChange={this.handleChange}
value={this.state.paymentType}
inputProps={{
name: 'paymentType',
id: 'paymentType',
}}
>
<option >PaymentType</option>
<option value="Cash">Cash</option>
<option value="PayPal">PayPal</option>
<option value="MasterCard">MasterCard</option>
</NativeSelect>
<TextField
margin="normal"
fullWidth
InputLabelProps={{style : {color : 'black'} }}
id="paymentDescription"
label="Payment Description"
name="paymentDescription"
autoComplete="paymentDescription"
onChange={this.handleChange}
value={this.state.paymentDescription}
autoFocus
/>
<TextField
margin="normal"
fullWidth
id="AmountPaid"
label="Amount Paid"
name="AmountPaid"
autoComplete="AmountPaid"
onChange={this.handleChange}
value={this.state.AmountPaid}
autoFocus
/><TextField
margin="normal"
fullWidth
id="paymentDiscount"
label="Payment Discount"
name="paymentDiscount"
autoComplete="paymentDiscount"
onChange={this.handleChange}
value={this.state.paymentDiscount}
autoFocus
/>
<TextField
margin="normal"
fullWidth
id="procedureAmount"
label="Procedure Amount"
name="procedureAmount"
autoComplete="procedureAmount"
onChange={this.handleChange}
value={this.state.procedureAmount}
autoFocus
/>
<TextField
margin="normal"
fullWidth
id="Total"
label="Total Bill"
name="Total"
autoComplete="Total"
onChange={this.handleChange}
value={this.state.Total}
autoFocus
/>
<div id='loginSuccess' className="alert alert-success" style={displayNone} role="alert">
<strong>Success! </strong>Client Bill Entered Successful.
</div>
<Button
type="submit"
fullWidth
sx={{ mt: 3, mb: 2}}
>
<span className='btn btn-warning btn-block form-control form-group'>Submit</span>
</Button>
</Box>
</div>
</div>
</div>
);
}
}
export default Billing;
</code></pre>
<p>I tried to use axios.post and submit the form. However, am not able to retrieve clientdetails data to the frontend in particular the select part of the form, it returns null. But the other entries go through to the backend. This is what am getting in the console.
data:
AmountPaid: 100
Total: 100
createdAt: "2022-11-25T22:31:57.306Z"
<strong>clientdetails: null</strong>
paymentDescription: "accomodation"
paymentDiscount: 100
paymentReferenceCode: "2345"
paymentType: "Cash"
procedureAmount: "3"
updatedAt: "2022-11-25T22:31:57.306Z"
__v: 0
_id: "6381425db019f3f9a48047ae"
[[Prototype]]: Objectid: "6381425db019f3f9a48047ae"</p>
<p>I would like to retrieve the clientdetails data to the frontend select section, select an option and be able to submit all the data.Thank you</p>
|
[
{
"answer_id": 74578441,
"author": "Jonathan V. Solórzano",
"author_id": 9022665,
"author_profile": "https://Stackoverflow.com/users/9022665",
"pm_score": 3,
"selected": true,
"text": "' str_replace stringr library(stringr)\n\nstr_replace(df, \"'.*\", \"\") \n#[1] \"That\" \"you\" \"\" \n"
},
{
"answer_id": 74578506,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": false,
"text": "sub > sub(\"'.*\", \"\", df)\n[1] \"That\" \"you\" \"\" \n"
},
{
"answer_id": 74578729,
"author": "shaun_m",
"author_id": 18289387,
"author_profile": "https://Stackoverflow.com/users/18289387",
"pm_score": 1,
"selected": false,
"text": "gsub(\"'\\\\w*\\\\b\",\"\",df)\n"
},
{
"answer_id": 74579477,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "trimws base R trimws(df, whitespace = \"'.*\")\n[1] \"That\" \"you\" \"\" \n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20183888/"
] |
74,578,476
|
<p>I have a <code>Cheques</code> and a <code>Payees</code> collection, every cheque has its corresponding <code>Payee ID</code>.</p>
<p>What I'm trying to do is to write some queries on cheques, but I need to preform the searching after populating the payee (to get the name)</p>
<pre><code>const search = req.query.search || "";
const cheques = await Cheque
.find({
isCancelled: false,
dueDate: { $gte: sinceDate, $lte: tillDate }
})
.select("_id serial dueDate value payee")
.skip(page * limit)
.limit(limit)
.sort({ dueDate: -1, serial: 1 })
.populate({
path: "payee",
select: "name"
})
</code></pre>
<p>I guess what I'm trying do is fit this somewhere in my code,</p>
<pre><code>match: {
name: { $regex: search, $options: "i" }
},
</code></pre>
<p>I have tried to put the match within the populate, but then it will still find all cheques even if they don't satisfy the population match but populate as null.</p>
|
[
{
"answer_id": 74580057,
"author": "Marc Simon",
"author_id": 19699404,
"author_profile": "https://Stackoverflow.com/users/19699404",
"pm_score": 0,
"selected": false,
"text": "populate() Cheques payee _id"
},
{
"answer_id": 74580085,
"author": "Normal",
"author_id": 18387350,
"author_profile": "https://Stackoverflow.com/users/18387350",
"pm_score": 2,
"selected": true,
"text": "$lookup .find() .aggregate() const search = req.query.search || \"\";\n const cheques = await Cheque\n .aggregate([\n {\n $lookup: { // similar to .populate() in mongoose\n from: 'payees', // the other collection name\n localField: 'payee', // the field referencing the other collection in the curent collection\n foreignField: '_id', // the name of the column where the cell in the current collection can be found in the other collection\n as: 'payee' // the field you want to place the db response in. this will overwrite payee id with the actual document in the response (it only writes to the response, not on the database, no worries)\n },\n { // this is where you'll place your filter object you used to place inside .find()\n $match: {\n isCancelled: false,\n dueDate: { $gte: sinceDate, $lte: tillDate }\n 'payee.branch': 'YOUR_FILTER', // this is how you access the actual object from the other collection after population, using the dot notation but inside a string.\n }\n },\n { // this is similar to .select()\n $project: {_id: 1, serial: 1, dueDate: 1, value: 1, payee: 1}\n },\n {\n $unwind: '$payee' // this picks the only object in the field payee: [ { payeeDoc } ] --> { payeeDoc }\n }\n ])\n .skip(page * limit)\n .limit(limit)\n .sort({ dueDate: -1, serial: 1 })\n .select() .populate() .find() .aggregate() .projcet() .select()"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15325671/"
] |
74,578,497
|
<p>I have problem with Laravel migrations. I want to make a relationship between two tables but</p>
<blockquote>
<p>I am getting error General error: 1005 Can't create table
<code>eshopper</code>.<code>prices</code> (errno: 150 "Foreign key constraint is incorrectly
formed") (SQL: alter table <code>prices</code> add constraint <code>pri ces_product_id_foreign</code> foreign key (<code>product_id</code>) references
<code>products</code> (<code>id</code>) .</p>
</blockquote>
<p>Here is my code. Tables are prices and products.</p>
<p>Prices</p>
<pre><code>public function up()
{
Schema::create('prices', function (Blueprint $table) {
$table->id();
$table->float('amount');
$table->unsignedBigInteger('product_id')->unsigned()->index();
$table->foreign('product_id')->references('id')->on('products')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
}
</code></pre>
<p>Products</p>
<pre><code>public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string("title",100);
$table->text("description");
$table->timestamps();
});
}
</code></pre>
<p><a href="https://i.stack.imgur.com/rZIJd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rZIJd.png" alt="enter image description here" /></a></p>
<p><strong>NOTE</strong>: In my migrations products table is under prices table, I know that the first created table is prices than products and that is error.
My question is do I have to put products frst or I can keep same layout(prices first, than products) and change something in code?</p>
|
[
{
"answer_id": 74580057,
"author": "Marc Simon",
"author_id": 19699404,
"author_profile": "https://Stackoverflow.com/users/19699404",
"pm_score": 0,
"selected": false,
"text": "populate() Cheques payee _id"
},
{
"answer_id": 74580085,
"author": "Normal",
"author_id": 18387350,
"author_profile": "https://Stackoverflow.com/users/18387350",
"pm_score": 2,
"selected": true,
"text": "$lookup .find() .aggregate() const search = req.query.search || \"\";\n const cheques = await Cheque\n .aggregate([\n {\n $lookup: { // similar to .populate() in mongoose\n from: 'payees', // the other collection name\n localField: 'payee', // the field referencing the other collection in the curent collection\n foreignField: '_id', // the name of the column where the cell in the current collection can be found in the other collection\n as: 'payee' // the field you want to place the db response in. this will overwrite payee id with the actual document in the response (it only writes to the response, not on the database, no worries)\n },\n { // this is where you'll place your filter object you used to place inside .find()\n $match: {\n isCancelled: false,\n dueDate: { $gte: sinceDate, $lte: tillDate }\n 'payee.branch': 'YOUR_FILTER', // this is how you access the actual object from the other collection after population, using the dot notation but inside a string.\n }\n },\n { // this is similar to .select()\n $project: {_id: 1, serial: 1, dueDate: 1, value: 1, payee: 1}\n },\n {\n $unwind: '$payee' // this picks the only object in the field payee: [ { payeeDoc } ] --> { payeeDoc }\n }\n ])\n .skip(page * limit)\n .limit(limit)\n .sort({ dueDate: -1, serial: 1 })\n .select() .populate() .find() .aggregate() .projcet() .select()"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17440063/"
] |
74,578,511
|
<p>I sometimes write modules that will only contain module methods (as opposed to module <em>instance</em> methods) (are there better names for these?). These modules should not be included in classes because that would have no effect and be misleading to a reader. So I'd like it to be as clear as possible to the reader that these modules contain no instance methods.</p>
<p>If I define all methods with <code>.self</code>, then a reader has to inspect all methods to ensure that this module contains no instance methods. If I instead use <code>class << self</code> or <code>extend self</code> then it is automatic; as soon as the reader sees this, they know.</p>
<p>I think <code>extend self</code> is best becuase with <code>class << self</code> one has to find its corresponding <code>end</code>; that is, it may not apply to <em>all</em> methods in the module.</p>
<p>So is it a good idea, and a best practice, to use <code>extend self</code> in cases like this?</p>
<p>Also, is there any difference <em>at runtime</em> between enclosing all methods in <code>class << self</code> as opposed to using <code>extend self</code>?</p>
|
[
{
"answer_id": 74578737,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 2,
"selected": false,
"text": "extend self extend self YourModule.extend(YourModule) module YourModule\n def some_method\n 23\n end\n\n extend self\nend\n module YourModule\n def some_method\n 23\n end\nend\n\nYourModule.extend(YourModule)\n module YourModule\n def some_method\n 23\n end\n\n def self.some_method\n 23\n end\nend\n YourModule.some_method\n class SomeClass\n extend YourModule\nend\n\nSomeClass.some_method\n class << self def self.method module_function extend self class << self attr_accessor def self.method def self.method self. attr_accessor extend self YourModule.method extend YourModule module_function extend self YourModule.method extend YourModule module_function extend self class << self extend self private"
},
{
"answer_id": 74586391,
"author": "Cary Swoveland",
"author_id": 256970,
"author_profile": "https://Stackoverflow.com/users/256970",
"pm_score": 1,
"selected": false,
"text": "module M\n # This module is not to be included in a class because\n # it contains no instance methods.\n \n def self.included(klass)\n raise \"\\nYou intended to include this module in #{klass}. You must be out of\\nyour mind! It does no harm but there is no point in doing so\\nbecause this module contains no instance methods. Duh!\"\n end\n \n def self.hi\n puts \"Hi, guys\"\n end\nend\n M.hi\nHi, guys\n class C\n include M\nend\nRuntimeError: \nYou intended to include this module in C. You must be out of\nyour mind! It does no harm but there is no point in doing so\nbecause this module contains no instance methods. Duh!\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/501266/"
] |
74,578,519
|
<p>I try to get some CSV formatted string as input and then to print it to an actual CSV file. It works but it prints the first string 2 times.</p>
<p>My code looks like this:</p>
<pre><code>func main() {
scanner := bufio.NewScanner(os.Stdin)
n := 0
inputFile, err := os.Create("input.csv") //create the input.csv file
if err != nil {
log.Fatal(err)
}
csvwriter := csv.NewWriter(inputFile)
fmt.Println("How many records ?")
fmt.Scanln(&n)
fmt.Println("Enter the records")
var lines [][]string
for i := 0; i < n; i++ {
scanner.Scan()
text := scanner.Text()
lines = append(lines, []string{text})
err := csvwriter.WriteAll(lines)
if err != nil {
return
}
}
csvwriter.Flush()
inputFile.Close()
}
</code></pre>
<p>for n=2 and the records:</p>
<pre><code>abcd, efgh, ijklmn
opq, rstu, vwxyz
</code></pre>
<p>the output looks like this:</p>
<pre><code>"abcd, efgh, ijklmn"
"abcd, efgh, ijklmn"
"opq, rstu, vwxyz"
</code></pre>
<p>It is my first time working with Golang and I am a little bit lost :D</p>
|
[
{
"answer_id": 74578905,
"author": "Shahriar Ahmed",
"author_id": 6607562,
"author_profile": "https://Stackoverflow.com/users/6607562",
"pm_score": 1,
"selected": true,
"text": "package main\n\nimport (\n \"bufio\"\n \"encoding/csv\"\n \"fmt\"\n \"log\"\n \"os\"\n)\n\nfunc main() {\n scanner := bufio.NewScanner(os.Stdin)\n n := 0\n inputFile, err := os.Create(\"input.csv\") //create the input.csv file\n if err != nil {\n log.Fatal(err)\n }\n defer func() {\n inputFile.Close()\n }()\n\n csvwriter := csv.NewWriter(inputFile)\n defer func() {\n csvwriter.Flush()\n }()\n fmt.Println(\"How many records ?\")\n fmt.Scanln(&n)\n fmt.Println(\"Enter the records\")\n var lines [][]string\n for i := 0; i < n; i++ {\n scanner.Scan()\n text := scanner.Text()\n lines = append(lines, []string{text})\n\n }\n err = csvwriter.WriteAll(lines)\n if err != nil {\n return\n }\n}\n\n"
},
{
"answer_id": 74578907,
"author": "Vishal Jangid",
"author_id": 11065323,
"author_profile": "https://Stackoverflow.com/users/11065323",
"pm_score": 1,
"selected": false,
"text": "csvwriter.WriteAll(lines) WriteAll w func main() {\n scanner := bufio.NewScanner(os.Stdin)\n n := 0\n inputFile, err := os.Create(\"input.csv\") //create the input.csv file\n if err != nil {\n log.Fatal(err)\n }\n defer inputFile.Close()\n\n csvwriter := csv.NewWriter(inputFile)\n\n fmt.Println(\"How many records ?\")\n fmt.Scanln(&n)\n fmt.Println(\"Enter the records\")\n var lines [][]string\n for i := 0; i < n; i++ {\n scanner.Scan()\n text := scanner.Text()\n lines = append(lines, []string{text})\n }\n err = csvwriter.WriteAll(lines)\n if err != nil {\n return\n }\n \n}\n\n\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20603022/"
] |
74,578,521
|
<p>I have a folder which contain 5 folders, with round 450-550 text files each. The text file has around 1-12 sentences varying in length, seperated by a tab, like this:</p>
<pre><code>i love burgers
i want to eat a burger
etc
</code></pre>
<p>I want to create a code which asks the user to input a search term and then goes inside each folder, opens and reads each text file, and matches how many times that search term appears. Then, go back out to the next folder, rinse and repeat till it goes through every folder and every text file.</p>
<p>So the output should be something like this:</p>
<pre><code>input search term: good
the search term appears this many times __ in the following files
file name 001.txt
file name 002.txt
file name 003.txt
</code></pre>
<p>Here is some of the code I have so far:</p>
<pre class="lang-py prettyprint-override"><code>from pathlib import Path
import os
from os.path import isdir, isfile
import nltk
search_word = input("Please enter the word you want to search for: ")
punctuation = "he fold!,:;-_'.?"
location = Path(r'the folder')
os.chdir(location)
print(Path.cwd())
fileslist = os.listdir(Path.cwd())
print(fileslist)
for file in fileslist:
if isdir(file):
os.chdir(file)
print(Path.cwd())
content = os.listdir(Path.cwd())
for document in content:
with open(document,'r') as infile:
data = []
for line in infile:
data += [line.strip(punctuation)]
print(data)
os.chdir('../')
print(Path.cwd())
else:
os.chdir(location)
</code></pre>
<p>I have tried watching some YouTube videos on how to do it, but I haven't been able to figure it out.</p>
|
[
{
"answer_id": 74578905,
"author": "Shahriar Ahmed",
"author_id": 6607562,
"author_profile": "https://Stackoverflow.com/users/6607562",
"pm_score": 1,
"selected": true,
"text": "package main\n\nimport (\n \"bufio\"\n \"encoding/csv\"\n \"fmt\"\n \"log\"\n \"os\"\n)\n\nfunc main() {\n scanner := bufio.NewScanner(os.Stdin)\n n := 0\n inputFile, err := os.Create(\"input.csv\") //create the input.csv file\n if err != nil {\n log.Fatal(err)\n }\n defer func() {\n inputFile.Close()\n }()\n\n csvwriter := csv.NewWriter(inputFile)\n defer func() {\n csvwriter.Flush()\n }()\n fmt.Println(\"How many records ?\")\n fmt.Scanln(&n)\n fmt.Println(\"Enter the records\")\n var lines [][]string\n for i := 0; i < n; i++ {\n scanner.Scan()\n text := scanner.Text()\n lines = append(lines, []string{text})\n\n }\n err = csvwriter.WriteAll(lines)\n if err != nil {\n return\n }\n}\n\n"
},
{
"answer_id": 74578907,
"author": "Vishal Jangid",
"author_id": 11065323,
"author_profile": "https://Stackoverflow.com/users/11065323",
"pm_score": 1,
"selected": false,
"text": "csvwriter.WriteAll(lines) WriteAll w func main() {\n scanner := bufio.NewScanner(os.Stdin)\n n := 0\n inputFile, err := os.Create(\"input.csv\") //create the input.csv file\n if err != nil {\n log.Fatal(err)\n }\n defer inputFile.Close()\n\n csvwriter := csv.NewWriter(inputFile)\n\n fmt.Println(\"How many records ?\")\n fmt.Scanln(&n)\n fmt.Println(\"Enter the records\")\n var lines [][]string\n for i := 0; i < n; i++ {\n scanner.Scan()\n text := scanner.Text()\n lines = append(lines, []string{text})\n }\n err = csvwriter.WriteAll(lines)\n if err != nil {\n return\n }\n \n}\n\n\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20603013/"
] |
74,578,532
|
<p>I'm trying to make website which will enable button when the certain condition is met. But when I run it within simple if the condiiton is checked only at the beginning and it doesn't enable and disable on changing condition. Condition is changing inside other event listener so the condition is dynamically. The condition is met when the dicitonary consists only of true which means that input is proper</p>
<pre><code>`var submitButton = document.getElementById("submit_button");`
</code></pre>
<p>And after some event listeners connected to inputs</p>
<pre><code>`if(Object.values(check_dict).filter(x=>x==true).length === 6)
{
submitButton.disabled = false;
}
else
{
submitButton.disabled = true ;
}`
</code></pre>
|
[
{
"answer_id": 74578905,
"author": "Shahriar Ahmed",
"author_id": 6607562,
"author_profile": "https://Stackoverflow.com/users/6607562",
"pm_score": 1,
"selected": true,
"text": "package main\n\nimport (\n \"bufio\"\n \"encoding/csv\"\n \"fmt\"\n \"log\"\n \"os\"\n)\n\nfunc main() {\n scanner := bufio.NewScanner(os.Stdin)\n n := 0\n inputFile, err := os.Create(\"input.csv\") //create the input.csv file\n if err != nil {\n log.Fatal(err)\n }\n defer func() {\n inputFile.Close()\n }()\n\n csvwriter := csv.NewWriter(inputFile)\n defer func() {\n csvwriter.Flush()\n }()\n fmt.Println(\"How many records ?\")\n fmt.Scanln(&n)\n fmt.Println(\"Enter the records\")\n var lines [][]string\n for i := 0; i < n; i++ {\n scanner.Scan()\n text := scanner.Text()\n lines = append(lines, []string{text})\n\n }\n err = csvwriter.WriteAll(lines)\n if err != nil {\n return\n }\n}\n\n"
},
{
"answer_id": 74578907,
"author": "Vishal Jangid",
"author_id": 11065323,
"author_profile": "https://Stackoverflow.com/users/11065323",
"pm_score": 1,
"selected": false,
"text": "csvwriter.WriteAll(lines) WriteAll w func main() {\n scanner := bufio.NewScanner(os.Stdin)\n n := 0\n inputFile, err := os.Create(\"input.csv\") //create the input.csv file\n if err != nil {\n log.Fatal(err)\n }\n defer inputFile.Close()\n\n csvwriter := csv.NewWriter(inputFile)\n\n fmt.Println(\"How many records ?\")\n fmt.Scanln(&n)\n fmt.Println(\"Enter the records\")\n var lines [][]string\n for i := 0; i < n; i++ {\n scanner.Scan()\n text := scanner.Text()\n lines = append(lines, []string{text})\n }\n err = csvwriter.WriteAll(lines)\n if err != nil {\n return\n }\n \n}\n\n\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20602664/"
] |
74,578,549
|
<p>I am trying to full join several dataframes (d1, d2,...) based on several conditions:
Either the ID has to match exactly beetween the two dataframes (id1 and id2) OR the location value of d2 has to be between the min and max columns of d1.</p>
<pre><code>data1 <- data.frame(id1 = c("A","B","C","D"),
location1 = c(123,247,335,454),
min1 = c(100,200,300,400),
max1 = c(199,299,399,499))
data2 <- data.frame(id2 = c("A","E","F"),
location2 = c(123,221,522),
min2 = c(100,212,500),
max2 = c(199,221,599))
What I want is:
id1 location1 min1 max1 id2 location2 min2 max2
1 A 123 100 199 A 123 100 199
2 B 247 200 299 E 221 212 221
3 C 335 300 399 NA NA NA NA
4 D 454 400 499 NA NA NA NA
5 NA NA NA NA F 522 500 599
</code></pre>
<ul>
<li>row1: ids are a perfect match, look no further</li>
<li>row2: ids are not a match but location2 is between min1 and max1,so this appears on same row</li>
<li>row3/4: no match, retained from d1</li>
<li>row5:nomatch, retained from d2</li>
</ul>
|
[
{
"answer_id": 74578632,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 0,
"selected": false,
"text": "data1 <- data.frame(id1 = c(\"A\",\"B\",\"C\",\"D\"), \n location1 = c(123,247,335,454),\n min1 = c(100,200,300,400),\n max1 = c(199,299,399,499))\n\n\ndata2 <- data.frame(id2 = c(\"A\",\"E\",\"F\"), \n location2 = c(123,221,522),\n min2 = c(100,212,500),\n max2 = c(199,221,599))\n\nlibrary(dplyr) \n\naux_data <-\n data1 %>% \n full_join(data2, by = character()) %>% \n filter(\n # id's are a perfect match\n id1 == id2 |\n # id's are not a match but location2 is between min1 and max1\n location2 >= min1 & location2 <= max1 \n ) \n\naux_id <- unique(c(aux_data$id1,aux_data$id2))\n\naux_data %>% \n # no match, retained from d1\n bind_rows(\n data1 %>% anti_join(data2, by = c(\"id1\" = \"id2\")) %>% filter(!(id1 %in% aux_id))\n ) %>% \n bind_rows(\n # no match, retained from d2 \n data2 %>% anti_join(data1, by = c(\"id2\" = \"id1\")) %>% filter(!(id2 %in% aux_id))\n )\n \n id1 location1 min1 max1 id2 location2 min2 max2\n1 A 123 100 199 A 123 100 199\n2 B 247 200 299 E 221 212 221\n3 C 335 300 399 <NA> NA NA NA\n4 D 454 400 499 <NA> NA NA NA\n5 <NA> NA NA NA F 522 500 599\n"
},
{
"answer_id": 74578686,
"author": "shaun_m",
"author_id": 18289387,
"author_profile": "https://Stackoverflow.com/users/18289387",
"pm_score": 2,
"selected": false,
"text": "sqldf library(sqldf)\n\nsqldf(\n \"select * \n from data1 d1 full join data2 d2\n on d1.id1 = d2.id2 or (d1.id1 <> d2.id2 and d1.min1 <= d2.location2 and d1.max1 >= d2.location2)\"\n )\n\n id1 location1 min1 max1 id2 location2 min2 max2\n1 A 123 100 199 A 123 100 199\n2 B 247 200 299 E 221 212 221\n3 C 335 300 399 <NA> NA NA NA\n4 D 454 400 499 <NA> NA NA NA\n5 <NA> NA NA NA F 522 500 599\n sqldf library(sqldf)\nlibrary(dplyr)\n\nsqldf(\n \"select * \n from data1 d1 left join data2 d2\n on d1.id1 = d2.id2 or (d1.id1 <> d2.id2 and d1.min1 <= d2.location2 and d1.max1 >= d2.location2)\n \n union\n \n select d1.*, d2.*\n from data2 d2 left join data1 d1 \n on d1.id1 = d2.id2 or (d1.id1 <> d2.id2 and d1.min1 <= d2.location2 and d1.max1 >= d2.location2)\n where d1.id1 is null\"\n) %>% \n arrange(id1, id2)\n\n# id1 location1 min1 max1 id2 location2 min2 max2\n# 1 A 123 100 199 A 123 100 199\n# 2 B 247 200 299 E 221 212 221\n# 3 C 335 300 399 <NA> NA NA NA\n# 4 D 454 400 499 <NA> NA NA NA\n# 5 <NA> NA NA NA F 522 500 599\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20537657/"
] |
74,578,552
|
<p>I have the list <code>['a','b','c','d','e','f','g']</code>. I want to print it a certain way like this:</p>
<pre><code>a b c
d e f
g
</code></pre>
<p>this is what I've tried:</p>
<pre><code>result = ''
for i in range(len(example)):
result += example[i] + ' '
if len(result) == 3:
print('\n')
print(result)
</code></pre>
<p>but with this I continue to get one single line</p>
|
[
{
"answer_id": 74578581,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 2,
"selected": false,
"text": "3 >>> a = ['a','b','c','d','e','f','g']\n>>> for i in range(0, len(a), 3):\n... print(a[i:i+3])\n... \n['a', 'b', 'c']\n['d', 'e', 'f']\n['g']\n>>> \n ' ' sep print >>> for i in range(0, len(a), 3):\n... print(' '.join(a[i:i+3]))\n... \na b c\nd e f\ng\n>>> for i in range(0, len(a), 3):\n... print(*a[i:i+3], sep=' ', end='\\n')\n... \na b c\nd e f\ng\n>>> \n"
},
{
"answer_id": 74578595,
"author": "E. Mancebo",
"author_id": 3537430,
"author_profile": "https://Stackoverflow.com/users/3537430",
"pm_score": -1,
"selected": false,
"text": "enumerate example = ['a','b','c','d','e','f','g'] \nmax_rows = 3\nresult = \"\"\nfor index, element in enumerate(example):\n if (index % max_rows) == 0:\n result += \"\\n\"\n result += element\n\nprint(result)\n\n"
},
{
"answer_id": 74578599,
"author": "nigh_anxiety",
"author_id": 17030540,
"author_profile": "https://Stackoverflow.com/users/17030540",
"pm_score": 0,
"selected": false,
"text": "\"\\n\" end i = 0\nwhile True:\n print(example[i], end=' ')\n i += 1\n if i >= len(example):\n break\n if i % 3 == 0:\n print() # new line\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20579620/"
] |
74,578,607
|
<p>I tried creating just a simple Service account in Kubernetes by running the command on my AWS EC2 cli <code>kubectl create serviceaccount jenkins --dry-run=client -o yaml > jenkins-sa.yaml</code> and I have my <code>kube/config</code> file on my <code>/home/ec2-user</code>.</p>
<p>I applied the new config jenkins-sa.yaml by running <code>kubectl apply -f jenkins-sa.yaml</code> and then I tried to see more info about the newly created service account by running <code>kubectl describe serviceaccount jenkins</code> which displays some information but without the secret token that should be associated to the jenkins service account by default.</p>
<p>Please I would be grateful if someone can point out what i'm doing wrong because I'm pretty new to Kubernetes. Below is a screenshot</p>
<p><a href="https://i.stack.imgur.com/x0jdK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x0jdK.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74579486,
"author": "P....",
"author_id": 6309601,
"author_profile": "https://Stackoverflow.com/users/6309601",
"pm_score": 2,
"selected": false,
"text": "Kubectl create token\n"
},
{
"answer_id": 74581156,
"author": "user2311578",
"author_id": 2311578,
"author_profile": "https://Stackoverflow.com/users/2311578",
"pm_score": 2,
"selected": false,
"text": "apiVersion: v1\nkind: Secret\ntype: kubernetes.io/service-account-token\nmetadata:\n name: jenkins-sa-token\n namespace: default\n annotations:\n kubernetes.io/service-account.name: \"jenkins\"\n jenkins-sa-token"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7418125/"
] |
74,578,658
|
<p>What commands to combine column1 and column2 relative to the content and then remove column2?
In addition, if both columns contain something, consider the content of column1 as the first choice.
It's about SQLite. Please note that these are permanent changes to the database and column layout, not a JOIN for SELECT.</p>
<p>Input SQLite database:</p>
<pre><code>|column1 | column2 |column_a|
|========|=========|========|
|"test" | |1 |
|"test2" |"test3" |2 |
| |"xxx" |3 |
</code></pre>
<p>Pseudocode:</p>
<p>column1 = column1 + column2
column2.delete()</p>
<p>Wyjściowa baza SQLite:</p>
<pre><code>|column1 |column_a|
|========|========|
|"test" |1 |
|"test2" |2 |
|"xxx" |3 |
</code></pre>
|
[
{
"answer_id": 74578664,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "COALESCE() SELECT COALESCE(column1, column2) AS column1,\n column_a\nFROM yourTable;\n"
},
{
"answer_id": 74579176,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 0,
"selected": false,
"text": "myTable DROP TABLE IF EXISTS myTable;\nCREATE TABLE IF NOT EXISTS myTable(column1, column2, column_a);\nINSERT INTO myTable VALUES(\"test\", null, 1);\nINSERT INTO myTable VALUES(\"test2\", \"test3\", 2);\nINSERT INTO myTable VALUES(null, \"xxx\", 3);\n COALESCE CASE SELECT (CASE WHEN column1 is NULL THEN column2 ELSE column1 END) as column1,\n column_a\nFROM myTable;\n"
},
{
"answer_id": 74579893,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 2,
"selected": false,
"text": "tab_dev CREATE TABLE INSERT INTO create table tab_dev\nas\nselect COALESCE(column1, column2) as column1,\n columna\n from tab_prod;\n tab_prod tab_dev alter table tab_prod rename to tab_prod_backup;\n tab_dev tab_prod alter table tab_dev rename to tab_prod;\n tab_prod tab_prod_backup"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18030381/"
] |
74,578,667
|
<p>I am attempting to answer the following exercise.</p>
<blockquote>
<p>Write a macro function OUR-IF that translates the following macro calls.</p>
<pre><code>(our-if a then b) translates to (cond (a b))
(our-if a then b else c) translates to (cond (a b) (t c))
</code></pre>
</blockquote>
<p>My solution is the following:</p>
<pre><code>(defmacro our-if (test then then-clause &optional else else-clause)
(if (equal 'else else)
`(cond (,test ,then-clause) (t ,else-clause))
`(cond (,test ,then-clause))))
</code></pre>
<p>That works fine, but I'm not totally satisfied by it. There's no syntax checking on the "then" and "else" arguments. Then could be anything. And if I gave the wrong symbol for "else", I'd get the wrong behaviour. The symbols aren't even checked to be symbols.</p>
<p>I could model them as keyword arguments and get close, but that's not exactly right either. It reminds me of the LOOP macro, which is a much more complicated example of the same thing. That made me wonder: how does LOOP do it? Maybe there's some pattern for "mini languages in macro arguments". But I couldn't find anything.</p>
<p>I found <a href="http://www.lispworks.com/documentation/HyperSpec/Body/m_loop.htm" rel="nofollow noreferrer">the hyperspec page for LOOP</a> which confirms that the grammar is complicated. But I don't know if there's a nice way to implement it.</p>
|
[
{
"answer_id": 74578664,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "COALESCE() SELECT COALESCE(column1, column2) AS column1,\n column_a\nFROM yourTable;\n"
},
{
"answer_id": 74579176,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 0,
"selected": false,
"text": "myTable DROP TABLE IF EXISTS myTable;\nCREATE TABLE IF NOT EXISTS myTable(column1, column2, column_a);\nINSERT INTO myTable VALUES(\"test\", null, 1);\nINSERT INTO myTable VALUES(\"test2\", \"test3\", 2);\nINSERT INTO myTable VALUES(null, \"xxx\", 3);\n COALESCE CASE SELECT (CASE WHEN column1 is NULL THEN column2 ELSE column1 END) as column1,\n column_a\nFROM myTable;\n"
},
{
"answer_id": 74579893,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 2,
"selected": false,
"text": "tab_dev CREATE TABLE INSERT INTO create table tab_dev\nas\nselect COALESCE(column1, column2) as column1,\n columna\n from tab_prod;\n tab_prod tab_dev alter table tab_prod rename to tab_prod_backup;\n tab_dev tab_prod alter table tab_dev rename to tab_prod;\n tab_prod tab_prod_backup"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4681998/"
] |
74,578,669
|
<p>The string is the value that i have taken from the input.When the user is going to put the numbers which the seperates them with a comma.And when he push asc the form with the asc order will be seen and the same with the desc order.I CAN NOT USE THE SORT FUNCTION BUT TO MAKE THE ORDER FUNCTION MYSELF.
Below i am going to send the code of the HTML.</p>
<pre><code><html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Numbers</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<style>
p {
margin-top: 30px;
margin-left: 70px;
}
</style>
</head>
<body>
<div>
<nav class="navbar bg-light">
<div class="container-fluid">
<span class="navbar-brand mb-0 h1" style="margin-left: 70px;">Sort the numbers</span>
</div>
</nav>
</div>
<div>
<p>Put the numbers you want to sort below</p>
</div>
<input class="form-control" list="datalistOptions" id="numb"
placeholder="Type the numbers seperated by a comma">
<div class="dropdown" style="margin-top: 20px; margin-bottom: 20px;">
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown button
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#" onclick="show()">Ascending</a></li>
<li><a class="dropdown-item" href="#" onclick="show()">Desecending</a></li>
</ul>
</div>
</body>
<template id="form-template">
<input class="form-control" list="datalistOptions" id="exampleDataList">
</template>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4"
crossorigin="anonymous"></script>
<script src="page.js"></script>
</html>
</code></pre>
<p>I cant sort them.Below i am going to send the js code that i cant do it.I want help with this.</p>
<pre><code>let temp = document.getElementsByTagName("template")[0];
function show(){
let clon = temp.content.cloneNode(true);
document.body.appendChild(clon);
}
function showNumber(){
let number = document.getElementById("numb").value;
console.log(number);
let array = number.split(" ");
console.log(array);
}
</code></pre>
|
[
{
"answer_id": 74578664,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "COALESCE() SELECT COALESCE(column1, column2) AS column1,\n column_a\nFROM yourTable;\n"
},
{
"answer_id": 74579176,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 0,
"selected": false,
"text": "myTable DROP TABLE IF EXISTS myTable;\nCREATE TABLE IF NOT EXISTS myTable(column1, column2, column_a);\nINSERT INTO myTable VALUES(\"test\", null, 1);\nINSERT INTO myTable VALUES(\"test2\", \"test3\", 2);\nINSERT INTO myTable VALUES(null, \"xxx\", 3);\n COALESCE CASE SELECT (CASE WHEN column1 is NULL THEN column2 ELSE column1 END) as column1,\n column_a\nFROM myTable;\n"
},
{
"answer_id": 74579893,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 2,
"selected": false,
"text": "tab_dev CREATE TABLE INSERT INTO create table tab_dev\nas\nselect COALESCE(column1, column2) as column1,\n columna\n from tab_prod;\n tab_prod tab_dev alter table tab_prod rename to tab_prod_backup;\n tab_dev tab_prod alter table tab_dev rename to tab_prod;\n tab_prod tab_prod_backup"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74578669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19745206/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.