qid
int64 4
22.2M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,477,214
|
<p>I have a pandas dataframe</p>
<pre><code>df_flat = pd.DataFrame({'dim1': ['a', 'a', 'b', 'b'], 'dim2': ['x', 'y', 'x', 'y'], 'val': [2, 4, 6, 8]})
</code></pre>
<p>I want to transform this dataframe, unflatten for want of a better words and transform it to a np ND array such that is looks like:</p>
<pre><code>df_unflatten = pd.DataFrame({'dim1': ['a', 'b'], 'x': [2, 6], 'y': [4, 8]}).set_index('dim1').to_numpy()
</code></pre>
<p>Edit: The 2D example was the wrong example to use here. The 3D example better highlights what i wish to do.</p>
<pre><code>pd.DataFrame({'dim1': ['a', 'a', 'b', 'b', 'a', 'a', 'b', 'b'], 'dim2': ['x', 'y', 'x', 'y', 'x', 'y', 'x', 'y'], 'dim3': ['i', 'i', 'i', 'i', 'j', 'j', 'j', 'j'], 'val': [2, 4, 6, 8, 1, 3, 5, 7]})
</code></pre>
<p>which i hope to convert to a ND np array:</p>
<pre><code>np.array([[[2, 1], [4, 3]],[[6, 5],[8, 7]]])
</code></pre>
<p>Note the extra square brackets, which gives this N levels of indexation (3 here). e.g. np.array([[[2, 1], [4, 3]],[[6, 5],[8, 7]]])[0][0][0]</p>
<p>I want this method to be flexible, such that if I add another dimension my 'unflattened' dataframe would become a numpy ndarray.</p>
<p>Are there any in built pandas functions that can help me achieve this. I am aware of functions that do the opposite e.g. .flatten() . unstack() etc. but I could not find any which achieve what I desire.</p>
|
[
{
"answer_id": 74619623,
"author": "Jib",
"author_id": 20124358,
"author_profile": "https://Stackoverflow.com/users/20124358",
"pm_score": 0,
"selected": false,
"text": "// <o>ISR FIFO Queue \n// <4=> 4 entries <8=> 8 entries <12=> 12 entries <16=> 16 entries\n// <24=> 24 entries <32=> 32 entries <48=> 48 entries <64=> 64 entries\n// <96=> 96 entries <128=> 128 entries <196=> 196 entries <256=> 256 entries\n// <i> RTOS Functions called from ISR store requests to this buffer.\n// <i> Default: 16 entries\n#ifndef OS_ISR_FIFO_QUEUE\n#define OS_ISR_FIFO_QUEUE 16\n#endif\n"
},
{
"answer_id": 74638712,
"author": "Zhubei Federer",
"author_id": 10769406,
"author_profile": "https://Stackoverflow.com/users/10769406",
"pm_score": 2,
"selected": true,
"text": "{\n \"target_overrides\": {\n \"*\": {\n \"OS_ISR_FIFO_QUEUE\": 32\n }\n }\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17033672/"
] |
74,477,223
|
<p>Based on this query: <a href="https://stackoverflow.com/questions/74458691/jmeter-execute-bash-script-using-os-process-sampler">Jmeter - Execute bash script using OS Process Sampler via Windows os</a></p>
<p>I was able to execute bash command on Windows using Os Process sampler.</p>
<p>Now I need to execute using JSR223 Sampler.</p>
<pre><code>String playerToken = vars.get("playerToken");
String command = "C:/Windows/System32/bash.exe /c cd C:/app/docs/release/ && ./no_longer_duplicate.bash ${playerToken} 6565";
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
log.warn(output.toString());
</code></pre>
<p>But I am not getting any output from the execution.
Any help is appreciated.</p>
|
[
{
"answer_id": 74477329,
"author": "Dmitri T",
"author_id": 2897748,
"author_profile": "https://Stackoverflow.com/users/2897748",
"pm_score": 1,
"selected": false,
"text": " SampleResult.setResponseData(output.toString(), 'UTF-8')\n"
},
{
"answer_id": 74507431,
"author": "vlatko606",
"author_id": 5210482,
"author_profile": "https://Stackoverflow.com/users/5210482",
"pm_score": -1,
"selected": true,
"text": "Runtime.getRuntime().exec"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5210482/"
] |
74,477,234
|
<p>I have two dataframes:</p>
<pre><code>
set.seed(1)
df1 <- data.frame(k1 = "AFD(1);Acf(2);Vgr7(2);"
,k2 = "ABC(7);BHG(46);TFG(675);")
df2 <- data.frame(site =c("AFD(1);AFD(2);", "Acf(2);", "TFG(677);",
"XX(275);", "ABC(7);", "ABC(9);")
,p1 = rnorm(6, mean = 5, sd = 2)
,p2 = rnorm(6, mean = 6.5, sd = 2))
</code></pre>
<p>The first dataframe is in fact a list of often very long strings, made of 'elements". Each "element" is made of a few letters/numbers, followed by a number in brackets, followed by a semicolon. In this example I only put 3 "elements" into each string, but in my real dataframe there are tens to hundreds of them.</p>
<pre><code>> df1
k1 k2
1 AFD(1);Acf(2);Vgr7(2); ABC(7);BHG(46);TFG(675);
</code></pre>
<p>The second dataframe shares some of the "elements" with <code>df1</code>. Its first column, called <code>site</code>, contains some (not all) "elements" from the first dataframe, sometimes the "element" forms the whole string, and sometimes is a part of a longer string:</p>
<pre><code>> df2
site p1 p2
1 AFD(1);AFD(2); 4.043700 3.745881
2 Acf(2); 5.835883 5.670011
3 TFG(677); 7.717359 5.711420
4 XX(275); 4.794425 6.381373
5 ABC(7); 5.775343 8.700051
6 ABC(9); 4.892390 8.026351
</code></pre>
<p>I would like to filter the whole <code>df2</code> using <code>df2$site</code> and each <code>k</code> column from <code>df1</code> (there are many K columns, not all of them contain <code>k</code> in the names).</p>
<p>The easiest way to explain this is to show how the desired output would look like.</p>
<pre><code>> outcome
k site p1 p2
1 k1 AFD(1);AFD(2): 4.043700 3.745881
2 k1 Acf(2); 5.835883 5.670011
3 k2 ABC(7); 5.775343 8.700051
</code></pre>
<p>The first column of the <code>outcome</code> dataframe corresponds to the column names in <code>df1</code>. The second column corresponds to the <code>site</code> column of <code>df2</code> and contains only <code>sites</code> from <code>df1</code> columns that were found in <code>df2$sites</code>. Other columns are from <code>df2</code>.</p>
<p>I appreciate that this question is made of two separate "problems", one grepping-related and one related to looping through <code>df1</code> columns. I decided to show the task in its entirety in case there exists a solution that addresses both in one go.</p>
<h4>FAILED SOLUTION 1</h4>
<p>I can create a string to grep, but for each column separately:</p>
<pre><code># this replaces the semicolons with "|", but does not escape the brackets.
k1_pattern <- df1 %>%
select(k1) %>%
deframe() %>%
str_replace_all(";","|")
</code></pre>
<p>And then I am not sure how to use it. This (below) didn't work, maybe because I didn't escape brackets, but I am struggling with doing it:</p>
<pre><code>k1_result <- df2 %>%
filter(grepl(pattern = k1_pattern, site))
</code></pre>
<p>But even if it did work, it would only deal with a single column from <code>df1</code>, and I have many, and would like to perform this operation on all <code>df1</code> columns at the same time.</p>
<h4>FAILED SOLUTION 2</h4>
<p>I can create a list of <code>sites</code> to search in <code>df2</code> from columns in <code>df1</code>:</p>
<pre><code>k1_sites<- df1 %>%
select(k1) %>%
deframe() %>%
strsplit(., "[;]") %>%
unlist()
</code></pre>
<p>but the delimiter is lost here, and <code>%in%</code> cannot be used, as the match will sometimes be partial.</p>
|
[
{
"answer_id": 74477864,
"author": "M--",
"author_id": 6461462,
"author_profile": "https://Stackoverflow.com/users/6461462",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf2 %>% \n mutate(site_list = strsplit(site, \";\")) %>% \n rowwise() %>% \n filter(length(intersect(site_list,\n unlist(strsplit(x = paste0(c(t(df1)), collapse=\"\"), \n split = \";\")))) != 0) %>% \n select(-site_list)\n"
},
{
"answer_id": 74478950,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 1,
"selected": true,
"text": "library(dplyr)\nlibrary(tidyr)\ndf1_long = df1 |> stack() |>\n separate_rows(values, sep = \";\") |>\n filter(values != \"\")\n\ndf2 |>\n mutate(id = row_number()) |>\n separate_rows(site, sep = \";\") |>\n filter(site != \"\") |>\n left_join(df1_long, by = c(\"site\" = \"values\")) %>%\n group_by(id) |>\n filter(any(!is.na(ind))) %>%\n summarize(\n site = paste(site, collapse = \";\"),\n across(-site, \\(x) first(na.omit(x)))\n )\n# # A tibble: 3 × 5\n# id site p1 p2 ind \n# <int> <chr> <dbl> <dbl> <fct>\n# 1 1 AFD(1);AFD(2) 3.75 7.47 k1 \n# 2 2 Acf(2) 5.37 7.98 k1 \n# 3 5 ABC(7) 5.66 9.52 k2 \n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9283607/"
] |
74,477,279
|
<p>I've made a TextField that is suppose to update the user's info.</p>
<p>The user has to type either 11 or 14 numbers, so the mask for the textfield has to change if someone types more than 11 numbers. How do I do that?</p>
<p>Masks:</p>
<pre><code>var mascaraCpf = MaskTextInputFormatter(
mask: '###.###.###-##',
filter: {"#": RegExp(r'[0-9]')},
type: MaskAutoCompletionType.lazy);
var mascaraCnpj = MaskTextInputFormatter(
mask: '##.###.###/####-##',
filter: {"#": RegExp(r'[0-9]')},
type: MaskAutoCompletionType.lazy);
</code></pre>
<p>TextField:</p>
<pre><code>TextField(
keyboardType: TextInputType.number,
inputFormatters: [
mascaraCpf,
FilteringTextInputFormatter.digitsOnly
],
controller: cpfController,
decoration: InputDecoration(
filled: true,
fillColor: Color(0xffFCF9F4),
border: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(5))),
hintText: appModel.usuario!.cpf,
),
),
</code></pre>
|
[
{
"answer_id": 74477864,
"author": "M--",
"author_id": 6461462,
"author_profile": "https://Stackoverflow.com/users/6461462",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf2 %>% \n mutate(site_list = strsplit(site, \";\")) %>% \n rowwise() %>% \n filter(length(intersect(site_list,\n unlist(strsplit(x = paste0(c(t(df1)), collapse=\"\"), \n split = \";\")))) != 0) %>% \n select(-site_list)\n"
},
{
"answer_id": 74478950,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 1,
"selected": true,
"text": "library(dplyr)\nlibrary(tidyr)\ndf1_long = df1 |> stack() |>\n separate_rows(values, sep = \";\") |>\n filter(values != \"\")\n\ndf2 |>\n mutate(id = row_number()) |>\n separate_rows(site, sep = \";\") |>\n filter(site != \"\") |>\n left_join(df1_long, by = c(\"site\" = \"values\")) %>%\n group_by(id) |>\n filter(any(!is.na(ind))) %>%\n summarize(\n site = paste(site, collapse = \";\"),\n across(-site, \\(x) first(na.omit(x)))\n )\n# # A tibble: 3 × 5\n# id site p1 p2 ind \n# <int> <chr> <dbl> <dbl> <fct>\n# 1 1 AFD(1);AFD(2) 3.75 7.47 k1 \n# 2 2 Acf(2) 5.37 7.98 k1 \n# 3 5 ABC(7) 5.66 9.52 k2 \n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531062/"
] |
74,477,282
|
<p>Im not sure if my strategy or logic is correct to achieve this, but I have 2 Lists coming from 2 different jsondata mysql quieries, lets say they look like this:</p>
<pre><code>List newsAgency = [{id: 1, name: 9news, image: x}
{id: 2, name: abcnews, image: y}
{id: 3, name: bbcnews, image:z}];
List following = [{userid: 41, username: x, newsid: 2}
{userid: 41, username: x newsid: 3}];
</code></pre>
<p>I want to see if the id in newsAgency matches the newsid in following list, and to return true or false correspondingly.</p>
<p>The idea is to say that I am following 2 news agencies out of 3, so my goal is to display the button to follow or unfollow based on the results.</p>
<p>I tried everything suggested from this post <a href="https://stackoverflow.com/questions/60726347/how-can-i-find-a-list-contains-in-any-element-another-list-in-flutter">how can I find a list contains in any element another list in flutter?</a> but couldnt get it.</p>
<p>This is my code example:</p>
<pre><code>Listview.builder(
itemCount: newsAgency.length,
itemBuilder: (BuildContext context, int index) {
bool following = false;
return Card(
elevation: 10.0,
child: Row(
children: [
Text(newsAgency[index]['name'],
following
? TextButton(onPressed: () {//unfollow function},
child: const Text('unfollow')),
: TextButton(onPressed: () {//follow function},
child: const Text('follow')),
]));});
</code></pre>
<p>Any help is highly appreciated</p>
|
[
{
"answer_id": 74478188,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 2,
"selected": true,
"text": " bool checkIsFollowing(Map<String, dynamic> current) {\n for(int index = 0; index < following.length; index+=1) {\n if(current[\"id\"] == following[index][\"newsid\"]) {\n return true;\n }\n }\n return false;\n }\n"
},
{
"answer_id": 74478323,
"author": "Pawan",
"author_id": 15514420,
"author_profile": "https://Stackoverflow.com/users/15514420",
"pm_score": 0,
"selected": false,
"text": "following.contains(newsAgency[index]['name'].toString())"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10841432/"
] |
74,477,286
|
<p>I have a list in which I have a combination of key and some additional objects, that are not related to each other in other way.</p>
<p>Considering this structure:</p>
<pre><code>record A0(String id, String name, B b, C c) {}
record A(String id, String name, Set<B> bs, Set<C> cs) {}
record B(String id, String name) {}
record C(String id, String name) {}
</code></pre>
<pre><code>a0s.add(new A0("1", "n1", new B("1", "nb1"), new C("1", "nc1")));
a0s.add(new A0("1", "n1", new B("1", "nb1"), new C("2", "nc2")));
a0s.add(new A0("1", "n1", new B("2", "nb2"), new C("3", "nc3")));
a0s.add(new A0("2", "n2", new B("2", "nb2"), new C("4", "nc4")));
a0s.add(new A0("2", "n2", new B("1", "nb1"), new C("5", "nc5")));
a0s.add(new A0("2", "n2", new B("2", "nb2"), new C("6", "nc6")));
a0s.add(new A0("3", "n3", new B("3", "nb3"), new C("7", "nc7")));
a0s.add(new A0("3", "n3", new B("3", "nb3"), new C("8", "nc8")));
a0s.add(new A0("4", "n4", new B("4", "nb4"), new C("9", "nc9")));
a0s.add(new A0("4", "n4", new B("5", "nb5"), new C("10", "nc10")));
</code></pre>
<p><code>I want to achieve this with java-streams:</code></p>
<pre><code>[ {
"id" : "1",
"name" : "n1",
"bs" : [ {
"id" : "1",
"name" : "nb1"
}, {
"id" : "2",
"name" : "nb2"
} ],
"cs" : [ {
"id" : "1",
"name" : "nc1"
}, {
"id" : "2",
"name" : "nc2"
}, {
"id" : "3",
"name" : "nc3"
} ]
}, {
"id" : "2",
"name" : "n2",
"bs" : [ {
"id" : "2",
"name" : "nb2"
}, {
"id" : "1",
"name" : "nb1"
} ],
"cs" : [ {
"id" : "4",
"name" : "nc4"
}, {
"id" : "5",
"name" : "nc5"
}, {
"id" : "6",
"name" : "nc6"
} ]
}, {
"id" : "3",
"name" : "n3",
"bs" : [ {
"id" : "3",
"name" : "nb3"
} ],
"cs" : [ {
"id" : "7",
"name" : "nc7"
}, {
"id" : "8",
"name" : "nc8"
} ]
}, {
"id" : "4",
"name" : "n4",
"bs" : [ {
"id" : "4",
"name" : "nb4"
}, {
"id" : "5",
"name" : "nb5"
} ],
"cs" : [ {
"id" : "10",
"name" : "nc10"
}, {
"id" : "9",
"name" : "nc9"
} ]
} ]
</code></pre>
<p>Here is my code without(obviously) java-streams:</p>
<pre><code>import java.util.*;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
class Scratch {
record A0(String id, String name, B b, C c) {}
record A(String id, String name, Set<B> bs, Set<C> cs) {}
record B(String id, String name) {}
record C(String id, String name) {}
public static void main(String[] args) throws JsonProcessingException {
List<A0> a0s = new ArrayList<>();
a0s.add(new A0("1", "n1", new B("1", "nb1"), new C("1", "nc1")));
a0s.add(new A0("1", "n1", new B("1", "nb1"), new C("2", "nc2")));
a0s.add(new A0("1", "n1", new B("2", "nb2"), new C("3", "nc3")));
a0s.add(new A0("2", "n2", new B("2", "nb2"), new C("4", "nc4")));
a0s.add(new A0("2", "n2", new B("1", "nb1"), new C("5", "nc5")));
a0s.add(new A0("2", "n2", new B("2", "nb2"), new C("6", "nc6")));
a0s.add(new A0("3", "n3", new B("3", "nb3"), new C("7", "nc7")));
a0s.add(new A0("3", "n3", new B("3", "nb3"), new C("8", "nc8")));
a0s.add(new A0("4", "n4", new B("4", "nb4"), new C("9", "nc9")));
a0s.add(new A0("4", "n4", new B("5", "nb5"), new C("10", "nc10")));
Set<A> collectA = new HashSet<>();
Map<String, Set<B>> mapAB = new HashMap<>();
Map<String, Set<C>> mapAC = new HashMap<>();
a0s.forEach(
a0 -> {
mapAB.computeIfAbsent(a0.id, k -> new HashSet<>());
mapAC.computeIfAbsent(a0.id, k -> new HashSet<>());
mapAB.get(a0.id).add(a0.b);
mapAC.get(a0.id).add(a0.c);
collectA.add(new A(a0.id, a0.name, new HashSet<>(), new HashSet<>()));
});
Set<A> outA = new HashSet<>();
collectA.forEach(
a -> {
outA.add(new A(a.id, a.name, mapAB.get(a.id), mapAC.get(a.id)));
});
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
String json =
objectMapper.writeValueAsString(
outA.stream()
.sorted(Comparator.comparing(A::id))
.collect(Collectors.toList()));
System.out.println(json);
}
}
</code></pre>
<p>I have red posts and docs, but was unable to achieve it.
<a href="https://stackoverflow.com/questions/70598461/list-of-unique-objects-containing-unique-sub-objects">This</a> pointed me in some direction, but I was unable to continue combining with other solution and reading API docs.
What "bugs", me is that I have <em>multiple</em> repeated objects to group(collect) and be unique. I am using Set to get advantage of the uniqueness, but could be List as well.</p>
|
[
{
"answer_id": 74477728,
"author": "user7",
"author_id": 4405757,
"author_profile": "https://Stackoverflow.com/users/4405757",
"pm_score": 2,
"selected": false,
"text": "Collectors.teeing"
},
{
"answer_id": 74477768,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 3,
"selected": true,
"text": "id"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20529765/"
] |
74,477,317
|
<p>How can i fix this problem in react native version 0.68.2</p>
<pre><code>Invariant Violation: Picker has been removed from React Native. It can now be installed and imported from '@react-native-picker/picker' instead of 'react-native'. See https://github.com/react-native-picker/picker
</code></pre>
|
[
{
"answer_id": 74477379,
"author": "JaRoMaster",
"author_id": 17873944,
"author_profile": "https://Stackoverflow.com/users/17873944",
"pm_score": 1,
"selected": false,
"text": "npm install @react-native-picker/picker --save\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,477,345
|
<p>I need to:</p>
<p>localStorage.setItem('user', user);
router.navigate(['/profile']);</p>
<p>The problem is that navigation may occur before storage is set.</p>
<p>Please tell me I don't need to route parameters, create asynchronous classes, callbacks, promisses, or timers for this to work.</p>
|
[
{
"answer_id": 74477379,
"author": "JaRoMaster",
"author_id": 17873944,
"author_profile": "https://Stackoverflow.com/users/17873944",
"pm_score": 1,
"selected": false,
"text": "npm install @react-native-picker/picker --save\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2811570/"
] |
74,477,349
|
<p>how to get the actual enum values instead of its int values</p>
<p>I have a enum class like below</p>
<pre><code>public enum gender
{
male,
female,
others
}
</code></pre>
<p>and this is my model create method</p>
<pre><code>public async Task<IActionResult> CreateCanditae(Canditateinfo caninfo)
{
if (ModelState.IsValid)
{
Canditateinfo canditateinfo = new Canditateinfo()
{
CanditateAadhar = caninfo.CanditateAadhar,
CanditateActDoa = caninfo.CanditateActDoa,
CanditateName = caninfo.CanditateName,
CanditateAddress = caninfo.CanditateAddress,
CanditateAltNumber = caninfo.CanditateAltNumber,
CanditateId = caninfo.CanditateId,
CanditateDepartment = caninfo.CanditateDepartment,
CanditateDesignation = caninfo.CanditateDesignation,
CanditateDoj = caninfo.CanditateDoj,
CanditateEmail = caninfo.CanditateEmail,
CanditateGender = caninfo.CanditateGender,
CanditateIdNumber = caninfo.CanditateIdNumber,
CanditateLocation = caninfo.CanditateLocation,
CanditateMaritialStatus = caninfo.CanditateMaritialStatus,
CanditatePancard = caninfo.CanditatePancard,
CanditateTeam = caninfo.CanditateTeam,
CanditateBaseLocation = caninfo.CanditateBaseLocation,
CanditateManager = caninfo.CanditateManager,
CanditateMobile = caninfo.CanditateMobile,
EnteredBy = HttpContext.Session.GetString("username"),
EnteredDate = DateTime.Now,
IsActive = 1,
DeleteFlag =0
};
_context.Canditateinfos.Add(canditateinfo);
_context.SaveChanges();
}
return View(nameof(Create));
}
</code></pre>
<p>i am saving this in mysql db. here when i save the gender it is showing as '1' instead of 'male'
how to achieve it</p>
<p>i am saving this in mysql db. here when i save the gender it is showing as '1' instead of 'male'
how to achieve it</p>
<p>in my model it is of type enum as follows</p>
<p>public gender Gender {get; set;}</p>
<p>i cant save it as int in db because they will use ssrs to take report.also i cant have a table for them in db because of the process.</p>
|
[
{
"answer_id": 74477580,
"author": "ahmadradwan",
"author_id": 20525121,
"author_profile": "https://Stackoverflow.com/users/20525121",
"pm_score": -1,
"selected": false,
"text": "//just pass it as a string in the database\n\nenum.GetName(typeOf(male),1);\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531071/"
] |
74,477,362
|
<p>I am trying to practice JLabel/JFrame and I am have trouble having my image "key2.png" appear.
I am using Visual Studio Code and I have both my code and the image in the same src folder.</p>
<p>`</p>
<pre><code>import javax.swing.ImageIcon;
import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.JPanel;
class Main {
public static void main(String[] args) {
ImageIcon icon = new ImageIcon("key2.png");
JLabel label = new JLabel();
label.setText("Hello");
label.setIcon(icon);
JPanel redPanel = new JPanel();
redPanel.setBackground(Color.red);
redPanel.setBounds(0, 0, 250, 250);
JPanel bluePanel = new JPanel();
bluePanel.setBackground(Color.blue);
bluePanel.setBounds(250, 0, 250, 250);
JPanel greenPanel = new JPanel();
greenPanel.setBackground(Color.green);
greenPanel.setBounds(0, 250, 500, 250);
MyFrame myFrame = new MyFrame(); //makes frame
myFrame.setLayout(null); //disable defualt layout
myFrame.add(redPanel);
redPanel.add(label); //add text and image to panel
myFrame.add(bluePanel);
myFrame.add(greenPanel);
}
}
</code></pre>
<p>`</p>
<p>Output:
<a href="https://i.stack.imgur.com/nh890.png" rel="nofollow noreferrer">Output</a></p>
<p>Expecting to see a black key image in the red panel.</p>
|
[
{
"answer_id": 74477580,
"author": "ahmadradwan",
"author_id": 20525121,
"author_profile": "https://Stackoverflow.com/users/20525121",
"pm_score": -1,
"selected": false,
"text": "//just pass it as a string in the database\n\nenum.GetName(typeOf(male),1);\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20380700/"
] |
74,477,376
|
<p>i have a switch like this</p>
<pre><code>switch (value){
case 1 : {
res = value+"Hirukami Murakmi"
break;
}
case 2 : {
res = value+"Josephine"
break;
}
default: {
res = value+"Mikey n Blaky"
break;
}
</code></pre>
<p>it is not working, it always show default value.
i add value just to know the value, and it is correctly define</p>
<p>but if else is working well</p>
<pre><code> if (value == 1) { res = "Hirukami Murakmi"}
else if (value == 2) { res = "Josephine"}
else { res = "Mikey n Blaky"}
</code></pre>
<p>i don't know what is wrong with my switch</p>
|
[
{
"answer_id": 74477440,
"author": "Miguel",
"author_id": 13319845,
"author_profile": "https://Stackoverflow.com/users/13319845",
"pm_score": 1,
"selected": false,
"text": "value == 1"
},
{
"answer_id": 74477628,
"author": "Mirko Martinovic",
"author_id": 10950171,
"author_profile": "https://Stackoverflow.com/users/10950171",
"pm_score": 0,
"selected": false,
"text": "switch (value) {\n case \"1\": {\n res = value + \"Hirukami Murakmi\";\n break;\n }\n case \"2\": {\n res = value + \"Josephine\";\n break;\n }\n default: {\n res = value + \"Mikey n Blaky\";\n break;\n }\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609511/"
] |
74,477,391
|
<p>I have the following list :</p>
<pre><code>StringTest = ['A','B','C','D']
</code></pre>
<p>The output excepted is :</p>
<pre><code>"'A','B','C','D'"
</code></pre>
<p>but it seems that the '' are perma deleted.</p>
<p>Below is the code I tried :</p>
<pre><code>StringTest = ['A','B','C','D']
StringTest = ','.join(StringTest )
print(StringTest )
</code></pre>
<p>which returns :</p>
<pre><code>"A,B,C,D"
</code></pre>
<p>How can I do ?</p>
|
[
{
"answer_id": 74477428,
"author": "Marcus",
"author_id": 16528000,
"author_profile": "https://Stackoverflow.com/users/16528000",
"pm_score": 0,
"selected": false,
"text": "StringTest = \"'\"+\"','\".join(StringTest)+\"'\"\n"
},
{
"answer_id": 74477512,
"author": "MrMattBusby",
"author_id": 8507777,
"author_profile": "https://Stackoverflow.com/users/8507777",
"pm_score": 0,
"selected": false,
"text": "\"'A'\""
},
{
"answer_id": 74477529,
"author": "Chandler Bong",
"author_id": 19576917,
"author_profile": "https://Stackoverflow.com/users/19576917",
"pm_score": 0,
"selected": false,
"text": "str_edit = '\"'+ str(StringTest).replace('[', '').replace(']', '') + '\"'\nprint(str_edit.replace(\" \", ''))\n"
},
{
"answer_id": 74477535,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 3,
"selected": true,
"text": "StringTest = ['A','B','C','D']\n\nprint('\"'+','.join(f\"'{s}'\" for s in StringTest)+'\"')\n"
},
{
"answer_id": 74477624,
"author": "GordonAitchJay",
"author_id": 3589122,
"author_profile": "https://Stackoverflow.com/users/3589122",
"pm_score": 1,
"selected": false,
"text": "str.join"
},
{
"answer_id": 74477685,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 2,
"selected": false,
"text": "repr"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11167163/"
] |
74,477,394
|
<p>I need to dynamically creates controllers in a ASP.NET Core 6 MVC application.</p>
<p>I found some way to somewhat achieve this but not quite.</p>
<p>I'm able to dynamically add my controller but somehow it reflects only on the second request.</p>
<p>So here is what I do: first I initialize my console app as follows:</p>
<pre><code>using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc.Infrastructure;
namespace DynamicControllerServer
{
internal class Program
{
static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
ApplicationPartManager partManager = builder.Services.AddMvc().PartManager;
// Store thePartManager in my Middleware to be able to add controlelr after initialization is done
MyMiddleware._partManager = partManager;
// Register controller change event
builder.Services.AddSingleton<IActionDescriptorChangeProvider>(MyActionDescriptorChangeProvider.Instance);
builder.Services.AddSingleton(MyActionDescriptorChangeProvider.Instance);
var app = builder.Build();
app.UseAuthorization();
app.MapControllers();
// Add Middleware which is responsible to cactn the request and dynamically add the missing controller
app.UseMiddleware<MyMiddleware>();
app.RunAsync();
Console.WriteLine("Server has been started successfully ...");
Console.ReadLine();
}
}
}
</code></pre>
<p>Then my middleware looks like this: it basically detects that there is the "dynamic" keyword in the url. If so, it will load the assembly containing the <code>DynamicController</code>:</p>
<pre><code>using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using System;
using System.Reflection;
namespace DynamicControllerServer
{
public class MyMiddleware
{
public RequestDelegate _next { get; }
private string dllName = "DynamicController1.dll";
static public ApplicationPartManager _partManager = null;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
if (httpContext.Request.Path.HasValue)
{
var queryParams = httpContext.Request.Path.Value;
if(httpContext.Request.Path.Value.Contains("api/dynamic"))
{
// Dynamically load assembly
Assembly assembly = assembly = Assembly.LoadFrom(@"C:\Temp\" + dllName);
// Add controller to the application
AssemblyPart _part = new AssemblyPart(assembly);
_partManager.ApplicationParts.Add(_part);
// Notify change
MyActionDescriptorChangeProvider.Instance.HasChanged = true;
MyActionDescriptorChangeProvider.Instance.TokenSource.Cancel();
}
}
await _next(httpContext); // calling next middleware
}
}
}
</code></pre>
<p>The <code>ActionDescriptorChange</code> provider looks like this:</p>
<pre><code>using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Primitives;
namespace DynamicControllerServer
{
public class MyActionDescriptorChangeProvider : IActionDescriptorChangeProvider
{
public static MyActionDescriptorChangeProvider Instance { get; } = new MyActionDescriptorChangeProvider();
public CancellationTokenSource TokenSource { get; private set; }
public bool HasChanged { get; set; }
public IChangeToken GetChangeToken()
{
TokenSource = new CancellationTokenSource();
return new CancellationChangeToken(TokenSource.Token);
}
}
}
</code></pre>
<p>Dynamic controller is in separate dll and is very simple:</p>
<pre><code>using Microsoft.AspNetCore.Mvc;
namespace DotNotSelfHostedOwin
{
[Route("api/[controller]")]
[ApiController]
public class DynamicController : ControllerBase
{
public string[] Get()
{
return new string[] { "dynamic1", "dynamic1", DateTime.Now.ToString() };
}
}
}
</code></pre>
<p>Here are the packages used in that project:</p>
<pre><code><PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</code></pre>
<p>This works "almost" fine ... when first request is made to:</p>
<pre><code>https://localhost:5001/api/dynamic
</code></pre>
<p>then it goes in the middleware and load the assembly, but returns a 404 error.</p>
<p>Then second request will actually work as expected:</p>
<p><a href="https://i.stack.imgur.com/e06bg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e06bg.png" alt="enter image description here" /></a></p>
<p>Second request returns the expected result:</p>
<p><a href="https://i.stack.imgur.com/eX8qU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eX8qU.png" alt="enter image description here" /></a></p>
<p>I must doing it wrong and probably my middleware is executed too late in the flow to reflect the dynamic controller right away.</p>
<p>Question is: what should be the proper way to achieve this?</p>
<p>Second question I have is say now the external dll holding our dynamic controller is updated.</p>
<p>How can I reload that controller to get the new definition?</p>
<p>Any help would be appreciated</p>
<p>Thanks in advance</p>
<p>Nick</p>
|
[
{
"answer_id": 74477428,
"author": "Marcus",
"author_id": 16528000,
"author_profile": "https://Stackoverflow.com/users/16528000",
"pm_score": 0,
"selected": false,
"text": "StringTest = \"'\"+\"','\".join(StringTest)+\"'\"\n"
},
{
"answer_id": 74477512,
"author": "MrMattBusby",
"author_id": 8507777,
"author_profile": "https://Stackoverflow.com/users/8507777",
"pm_score": 0,
"selected": false,
"text": "\"'A'\""
},
{
"answer_id": 74477529,
"author": "Chandler Bong",
"author_id": 19576917,
"author_profile": "https://Stackoverflow.com/users/19576917",
"pm_score": 0,
"selected": false,
"text": "str_edit = '\"'+ str(StringTest).replace('[', '').replace(']', '') + '\"'\nprint(str_edit.replace(\" \", ''))\n"
},
{
"answer_id": 74477535,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 3,
"selected": true,
"text": "StringTest = ['A','B','C','D']\n\nprint('\"'+','.join(f\"'{s}'\" for s in StringTest)+'\"')\n"
},
{
"answer_id": 74477624,
"author": "GordonAitchJay",
"author_id": 3589122,
"author_profile": "https://Stackoverflow.com/users/3589122",
"pm_score": 1,
"selected": false,
"text": "str.join"
},
{
"answer_id": 74477685,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 2,
"selected": false,
"text": "repr"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6475390/"
] |
74,477,420
|
<p>What is the meaning of:
shape=(1, 224, 224, 3)</p>
<p>I mean what are all the values specifying given here for shape?</p>
|
[
{
"answer_id": 74477428,
"author": "Marcus",
"author_id": 16528000,
"author_profile": "https://Stackoverflow.com/users/16528000",
"pm_score": 0,
"selected": false,
"text": "StringTest = \"'\"+\"','\".join(StringTest)+\"'\"\n"
},
{
"answer_id": 74477512,
"author": "MrMattBusby",
"author_id": 8507777,
"author_profile": "https://Stackoverflow.com/users/8507777",
"pm_score": 0,
"selected": false,
"text": "\"'A'\""
},
{
"answer_id": 74477529,
"author": "Chandler Bong",
"author_id": 19576917,
"author_profile": "https://Stackoverflow.com/users/19576917",
"pm_score": 0,
"selected": false,
"text": "str_edit = '\"'+ str(StringTest).replace('[', '').replace(']', '') + '\"'\nprint(str_edit.replace(\" \", ''))\n"
},
{
"answer_id": 74477535,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 3,
"selected": true,
"text": "StringTest = ['A','B','C','D']\n\nprint('\"'+','.join(f\"'{s}'\" for s in StringTest)+'\"')\n"
},
{
"answer_id": 74477624,
"author": "GordonAitchJay",
"author_id": 3589122,
"author_profile": "https://Stackoverflow.com/users/3589122",
"pm_score": 1,
"selected": false,
"text": "str.join"
},
{
"answer_id": 74477685,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 2,
"selected": false,
"text": "repr"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531084/"
] |
74,477,432
|
<p>On Emba's <a href="https://docwiki.embarcadero.com/RADStudio/Alexandria/en/Parameters_(Delphi)" rel="nofollow noreferrer">website</a>, it is stated that an OUT parameter (does not say which type, so I assume it applies to all types) should not be used for input because its value is "discarded".<br />
By discarded, I interpret (even though we are not at the Bible Study hour) that the value is zeroed.</p>
<blockquote>
<p>With an out parameter, however, the initial value of the referenced
variable is discarded by the routine it is passed to.</p>
</blockquote>
<p>But this simple code shows that the value stored in "i" is not discarded, in none of the cases (integer/record)!</p>
<pre><code>Procedure TestInteger(OUT i: Integer);
Begin
if i = 7
then i:= 14;
End;
TYPE TMyRec = record
i: Integer;
end;
Procedure TestRec(OUT R: TMyRec);
Begin
End;
procedure TfrmTest.btnTestClick(Sender: TObject);
begin
VAR i: Integer:= 7;
TestInteger(i);
VAR MyRecord: TMyRec;
MyRecord.i:= 7;
TestRec(MyRecord);
Caption:= IntToStr(MyRecord.i);
end;
</code></pre>
<p>So, is the documentation wrong? Is my "interpretation" wrong, or is the compiler wrong?</p>
|
[
{
"answer_id": 74477691,
"author": "Andreas Rejbrand",
"author_id": 282848,
"author_profile": "https://Stackoverflow.com/users/282848",
"pm_score": 3,
"selected": true,
"text": "out"
},
{
"answer_id": 74480435,
"author": "Brian",
"author_id": 685746,
"author_profile": "https://Stackoverflow.com/users/685746",
"pm_score": 1,
"selected": false,
"text": "TYPE TMyRec = record\n i: Integer ;\n class operator Initialize (out Dest: TMyRec);\nend;\n\nclass operator TMyRec.Initialize (out Dest: TMyRec);\nbegin\n dest.i := 0;\nend;\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46207/"
] |
74,477,513
|
<p>Okay so my vs code was normal, then i restarted my laptop without closing the app. I opened it after and almost all the text was white. It isnt the theme, because its always been on Dark+. I dont think i clicked anything major that would cause this. Its really hard to code like this. It is javascript file btw.</p>
<p>This is a screenshot of what it looks like:
<a href="https://i.stack.imgur.com/LnX1E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LnX1E.png" alt="enter image description here" /></a></p>
<p>As you can see, the comments that are meant to be green are white, the file imports and text that are meant to be orange are white. 'await' that is meant to be purple is white. even 'const' is white. anyone know how to fix this?</p>
|
[
{
"answer_id": 74477691,
"author": "Andreas Rejbrand",
"author_id": 282848,
"author_profile": "https://Stackoverflow.com/users/282848",
"pm_score": 3,
"selected": true,
"text": "out"
},
{
"answer_id": 74480435,
"author": "Brian",
"author_id": 685746,
"author_profile": "https://Stackoverflow.com/users/685746",
"pm_score": 1,
"selected": false,
"text": "TYPE TMyRec = record\n i: Integer ;\n class operator Initialize (out Dest: TMyRec);\nend;\n\nclass operator TMyRec.Initialize (out Dest: TMyRec);\nbegin\n dest.i := 0;\nend;\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15975299/"
] |
74,477,571
|
<p>I'm using postgresql to calculate if different points are inside a specific range (calculated using pythagoras).</p>
<p>The thing is that I would like to get the results ordered by the proximity instead of randomly.</p>
<p>This is my query:</p>
<p><code>select * from point l where ((abs(l.lat*111139 - myPointLat*111139)^2) + (abs(l.lng*111139 - (myPointLng*111139))^2)) <= metres^2;</code></p>
<p>And I would like to sort it using this part of the query:</p>
<blockquote>
<p>((abs(l.lat<em>111139 - myPointLat</em>111139)^2) + (abs(l.lng<em>111139 - (myPointLng</em>111139))^2))</p>
</blockquote>
<p>How could I achieve this?</p>
<p>Thank you very much!</p>
|
[
{
"answer_id": 74477688,
"author": "user3738870",
"author_id": 3738870,
"author_profile": "https://Stackoverflow.com/users/3738870",
"pm_score": 3,
"selected": true,
"text": "select Column1, Column2, Column3 from \n(\n select *,\n (\n (abs(l.lat*111139 - myPointLat*111139)^2) + \n (abs(l.lng*111139 - (myPointLng*111139))^2)\n ) as proximity\n from point l\n)\nwhere proximity <= metres^2\norder by proximity\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7657219/"
] |
74,477,577
|
<p>I'm very new to programming so forgive if this question is a bit stupid. Anyway I'm making this console program that is supposed to calculate total damage per hit after bonus damage is applied.
Example: damage is 100 per hit with 0 initial bonus damage that increases by 50 per hit. The program is supposed to calculate the total damage after N amounts of hits.</p>
<p>This is what I came up with:</p>
<pre><code>#include <stdio.h>
int main(){
int n;
int bonusDam = 0;
int i;
int b;
int a;
scanf("%d", &n);
for (i = 1; i <= n; i++){
b = 100 + bonusDam;
bonusDam = bonusDam + 50;
printf("Hit %d : %d\n", i, b);
}
return 0;
}
</code></pre>
<p>I figured out how to calculate the bonus damage but not the total damage after N amounts of hits.
Is a for loop a good idea or no? If i input 3 it'll output "100, 150, 200" but what I want to do is to add them all up like "100 + 150 + 200 = 450" Where in the end the console only shows "450"</p>
|
[
{
"answer_id": 74477688,
"author": "user3738870",
"author_id": 3738870,
"author_profile": "https://Stackoverflow.com/users/3738870",
"pm_score": 3,
"selected": true,
"text": "select Column1, Column2, Column3 from \n(\n select *,\n (\n (abs(l.lat*111139 - myPointLat*111139)^2) + \n (abs(l.lng*111139 - (myPointLng*111139))^2)\n ) as proximity\n from point l\n)\nwhere proximity <= metres^2\norder by proximity\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531181/"
] |
74,477,609
|
<p>I have an Excel spreadsheet (Mac OS) with approximately 500 rows and 50+ columns. In all 500 rows, but only half of the columns, are URLs that I am looking to change in bulk.</p>
<p>The domain name and first two category names (paths) are the same. The third path is different but will always contain two letters only. And the final/last text path before the numbers/integers is different.</p>
<p>I am looking to remove the entire URL, including the .html extension, but keep the unique numbers/integers.</p>
<pre><code>https://www.website.com/category/product/oh/brody/3302.html
https://www.website.com/category/product/in/greene/6648.html
https://www.website.com/category/product/ca/ronald/9858.html
https://www.website.com/category/product/nj/brick/2464.html
https://www.website.com/category/product/tx/allen/1104.html`
</code></pre>
<ul>
<li><strong>Desired result</strong></li>
</ul>
<pre><code> 3302
6648
9858
2462
1104
</code></pre>
<p>I am open to doing this in Excel or Google Sheets, as well as multiple steps to accomplish this task</p>
<ul>
<li>Find "https://www.website.com/category/product" and replace with nothing</li>
<li>Find ".html" and replace with nothing</li>
<li>This still leaves thousands of almost-complete results:</li>
</ul>
<pre><code> /oh/brody/3302
/in/greene/6648
/ca/ronald/9858
/nj/brick/2464
/tx/allen/1104
</code></pre>
<p>I want to be left with only this:</p>
<pre><code> 3302
6648
9858
2462
1104
</code></pre>
|
[
{
"answer_id": 74478673,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 1,
"selected": false,
"text": "=INDEX(IFNA(REGEXEXTRACT(A1:A, \"\\d+\")*1))\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531152/"
] |
74,477,641
|
<p>I have created a class function called trick_winner(self) within the class Cards which take the value within self.trick1 for example self.trick1 = ('AH' 'JH' 'KH' '2H') and returns the pairs in order from great to least, being that 'A' is the highest value followed by '7', 'J', 'K', 'Q', '6', '5', '4', '3', '2'. But when I use the built in sort function sorted is returns the value in but they are not pairs, they are treating each value as its own seperate value.</p>
<p>I have tried to used the built in sort function, but it does not come out the way I want it to show. I am expecting if I type in a = Cards('AH' '4H' 'KH' '2H') and when I run the class function is it will return the pairs in order from greatest to least 'A' 'KH' '4H' '2H'.</p>
<p>I have created the function</p>
<pre><code>class Cards:
def __init__(self, trick)
self.trick1 = trick
def trick_winner(self):
R = {'2': 0, '3': 0, '4': 0, '5': 0, '6': 0,
'J': 4, 'Q': 3, 'K': 5, '7': 10, 'A': 11}
self.trick1 = self.trick1.upper()
a = sorted(self.trick1)
print(a)
</code></pre>
<p>and running the funcntion:
c = cards('7H' ' JH' ' KH' ' 2H')
c.trick_winner()</p>
<p>the outcome was:
[' ', ' ', ' ', '2', '7', 'H', 'H', 'H', 'H', 'J', 'K']</p>
|
[
{
"answer_id": 74478673,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 1,
"selected": false,
"text": "=INDEX(IFNA(REGEXEXTRACT(A1:A, \"\\d+\")*1))\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20487839/"
] |
74,477,657
|
<p>I'm getting 404's from my own site (regardless of browser) as well as the <a href="https://www.bing.com/api/maps/sdk/mapcontrol/isdk" rel="nofollow noreferrer">Bing Maps V8 Interactive SDK</a>. On my site this leads to <code>Uncaught TypeError: Microsoft.Maps.Location is not a constructor</code> errors. I'm guessing this means Bing Maps is having problems and not my code because of the missing .js file? Anything I can do to mitigate this?</p>
<p>Looks like Microsoft fixed their issue. It is working now.</p>
|
[
{
"answer_id": 74478673,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 1,
"selected": false,
"text": "=INDEX(IFNA(REGEXEXTRACT(A1:A, \"\\d+\")*1))\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5094258/"
] |
74,477,658
|
<p>I am writing a userscript for a website to change link targets from "_blank" to "_self".</p>
<p>The website's links are all handled by an EventListener on Click action, which reviews the <code>id</code> attribute for every <code><a></code> element to set the click URL and load it in a new tab. None of the <code><a></code> elements have a <code>href</code> or <code>target</code> attribute.</p>
<p>I would like all clicked links to load in the same tab (rather than a new tab).</p>
<p>Is there any way to modify link targets set by an event listener, or to simply set/override the default link target for all links on a webpage?</p>
|
[
{
"answer_id": 74477925,
"author": "Farbod Shabani",
"author_id": 14712252,
"author_profile": "https://Stackoverflow.com/users/14712252",
"pm_score": 0,
"selected": false,
"text": "document.querySelector().target = \"_self\""
},
{
"answer_id": 74478060,
"author": "skara9",
"author_id": 17055403,
"author_profile": "https://Stackoverflow.com/users/17055403",
"pm_score": 2,
"selected": true,
"text": "window.open"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8698539/"
] |
74,477,661
|
<p>In Spring-boot you can use the <code>@Profile(!dev)</code> annotation to exclude beans and classes from being provided when certain profiles are active or not active. Is there an equivalent property for this that can be used inside the application.yml?</p>
|
[
{
"answer_id": 74477925,
"author": "Farbod Shabani",
"author_id": 14712252,
"author_profile": "https://Stackoverflow.com/users/14712252",
"pm_score": 0,
"selected": false,
"text": "document.querySelector().target = \"_self\""
},
{
"answer_id": 74478060,
"author": "skara9",
"author_id": 17055403,
"author_profile": "https://Stackoverflow.com/users/17055403",
"pm_score": 2,
"selected": true,
"text": "window.open"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944515/"
] |
74,477,702
|
<p>I have array of objects like this,</p>
<pre><code> let data = [
{ id: 1, name: 'a' },
{ id: 1, name: 'b'},
{ id: 1, name: 'a'},
{ id: 2, name: 'a'},
{ id: 2, name: 'b'},
{ id: 3, name: 'c'},
{ id: 3, name: 'c'}
]
</code></pre>
<p>I am trying to achieve unique combination of id and name, so expected output should be like,</p>
<pre><code>output
[
{ id: 1, name: 'a'},
{ id: 1, name: 'b'},
{ id: 2, name: 'a'},
{ id: 2, name: 'b'},
{ id: 3, name: 'c'}
]
</code></pre>
<p>I have tried Set method but could not do it for key, value pair.
Please could someone help.
Thanks
Edit- 1
Most solutions have array of string, number or object with one key-value pair. I have two key-value pairs in object.</p>
|
[
{
"answer_id": 74477822,
"author": "libik",
"author_id": 2854908,
"author_profile": "https://Stackoverflow.com/users/2854908",
"pm_score": 2,
"selected": true,
"text": "let data = [\n { id: 1, name: 'a' },\n { id: 1, name: 'b'},\n { id: 1, name: 'a'},\n { id: 2, name: 'a'},\n { id: 2, name: 'b'},\n { id: 3, name: 'c'},\n { id: 3, name: 'c'}\n ]\n \nconst nodup = new Set();\ndata.forEach(item => nodup.add(`${item.id}-${item.name}`));\nconsole.log(Array.from(nodup))\nlet uniqueData = Array.from(nodup).map(item => {\n const data = item.split('-')\n return {id: data[0], name: data[1]};\n});\nconsole.log(uniqueData);"
},
{
"answer_id": 74477867,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 1,
"selected": false,
"text": "let data = [\n { id: 1, name: 'a' },\n { id: 1, name: 'b'},\n { id: 1, name: 'a'},\n { id: 2, name: 'a'},\n { id: 2, name: 'b'},\n { id: 3, name: 'c'},\n { id: 3, name: 'c'}\n ]\nconst unique_combos= (arr1) => {\nconst returned_array = []\narr1.map(element => {\n if (!(returned_array.find(e=>e?.id === element?.id && e?.name === element.name)))\n returned_array.push(element);\n})\n\nreturn (returned_array);\n}\n\nconsole.log(unique_combos(data))"
},
{
"answer_id": 74478262,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "reduce"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8449651/"
] |
74,477,713
|
<p>When creating graphs using, for instance, Python. It is possible to save these figures as vector graphics (SVG, EPS, PDF) and the text is rendered separately. This makes it possible to select or search the text when shown in a pdf file. However, I've tried to render a simple graph using math symbols in addition to text (in latex). The math symbol gets encoded as part of the image, rather than as text.</p>
<p>Here is a minimum reproducible example.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt
x_list = np.linspace(-10,10,num=128)
y = list(map(lambda x: (x**2 + x + 1), x_list))
plt.plot(y, label="$\\Psi_{example}$")
plt.legend()
plt.xticks(np.linspace(0, 128, num=8),
map(round, np.linspace(-10, 10, num=8), [0] * 8))
plt.savefig("./example.pdf")
</code></pre>
<p>Which produces the following image.</p>
<p><a href="https://i.stack.imgur.com/xldH3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xldH3.png" alt="Example Graph x^2+x+1" /></a></p>
<p>When saving this image as vector graphics, all the numbers as well as the 'example' word in the legend become selectable/searchable (i.e. rendered as text). However, the Ψ (Psi) character is not selectable/searchable.</p>
<p>Is there any way to make math symbols render as text in vector graphics?</p>
|
[
{
"answer_id": 74477822,
"author": "libik",
"author_id": 2854908,
"author_profile": "https://Stackoverflow.com/users/2854908",
"pm_score": 2,
"selected": true,
"text": "let data = [\n { id: 1, name: 'a' },\n { id: 1, name: 'b'},\n { id: 1, name: 'a'},\n { id: 2, name: 'a'},\n { id: 2, name: 'b'},\n { id: 3, name: 'c'},\n { id: 3, name: 'c'}\n ]\n \nconst nodup = new Set();\ndata.forEach(item => nodup.add(`${item.id}-${item.name}`));\nconsole.log(Array.from(nodup))\nlet uniqueData = Array.from(nodup).map(item => {\n const data = item.split('-')\n return {id: data[0], name: data[1]};\n});\nconsole.log(uniqueData);"
},
{
"answer_id": 74477867,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 1,
"selected": false,
"text": "let data = [\n { id: 1, name: 'a' },\n { id: 1, name: 'b'},\n { id: 1, name: 'a'},\n { id: 2, name: 'a'},\n { id: 2, name: 'b'},\n { id: 3, name: 'c'},\n { id: 3, name: 'c'}\n ]\nconst unique_combos= (arr1) => {\nconst returned_array = []\narr1.map(element => {\n if (!(returned_array.find(e=>e?.id === element?.id && e?.name === element.name)))\n returned_array.push(element);\n})\n\nreturn (returned_array);\n}\n\nconsole.log(unique_combos(data))"
},
{
"answer_id": 74478262,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "reduce"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9302146/"
] |
74,477,716
|
<p>I have setup the PubSub emulator to run a Python script locally pointing to it.<br />
The emulator is run following the tutorial and it seems to be working fine:</p>
<pre><code>➜ gcloud beta emulators pubsub start --project=tokyo-rain-123 --host-port=127.0.0.1:8085
Executing: /Users/pabloruiz/Downloads/google-cloud-sdk/platform/pubsub-emulator/bin/cloud-pubsub-emulator --host=127.0.0.1 --port=8085
[pubsub] This is the Google Pub/Sub fake.
[pubsub] Implementation may be incomplete or differ from the real system.
[pubsub] Nov 17, 2022 3:32:04 PM com.google.cloud.pubsub.testing.v1.Main main
[pubsub] INFO: IAM integration is disabled. IAM policy methods and ACL checks are not supported
[pubsub] SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
[pubsub] SLF4J: Defaulting to no-operation (NOP) logger implementation
[pubsub] SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
[pubsub] Nov 17, 2022 3:32:04 PM com.google.cloud.pubsub.testing.v1.Main main
[pubsub] INFO: Server started, listening on 8085
</code></pre>
<p><strong>It is working fine using curl:</strong></p>
<pre><code>➜ curl -X PUT http://localhost:8085/v1/projects/tokyo-rain-123/topics/topic-data1
{
"name": "projects/tokyo-rain-123/topics/topic-data1"
}
</code></pre>
<p>Although it is displaying this warning on the emulator:</p>
<pre><code>[pubsub] INFO: Server started, listening on 8085
[pubsub] Nov 17, 2022 4:00:57 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
[pubsub] INFO: Detected non-HTTP/2 connection.
[pubsub] Nov 17, 2022 4:00:57 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
[pubsub] INFO: Detected HTTP/2 connection.
</code></pre>
<p><strong>I can't reach it using Postman.</strong> I receive this response:</p>
<pre><code>{
"error": {
"code": 500,
"message": "RST_STREAM closed stream. HTTP/2 error code: PROTOCOL_ERROR",
"status": "INTERNAL"
}
}
</code></pre>
<p>And this is the log from the emulator:</p>
<pre><code>[pubsub] WARNING: Metadata key is 'Connection', which should not be used. That is used by HTTP/1 for connection-specific headers which are not to be forwarded. There is probably an HTTP/1 conversion bug. Simply removing the Connection header is not enough; you should remove all headers it references as well. See RFC 7230 section 6.1
[pubsub] java.lang.RuntimeException: exception to show backtrace
[pubsub] at io.grpc.Metadata$Key.validateName(Metadata.java:740)
[pubsub] at io.grpc.Metadata$Key.<init>(Metadata.java:762)
[pubsub] at io.grpc.Metadata$Key.<init>(Metadata.java:671)
[pubsub] at io.grpc.Metadata$AsciiKey.<init>(Metadata.java:971)
[pubsub] at io.grpc.Metadata$AsciiKey.<init>(Metadata.java:966)
[pubsub] at io.grpc.Metadata$Key.of(Metadata.java:708)
[pubsub] at io.grpc.Metadata$Key.of(Metadata.java:704)
[pubsub] at io.gapi.emulators.grpc.HttpAdapter$StubMethodHandler.handle(HttpAdapter.java:537)
[pubsub] at io.gapi.emulators.grpc.HttpAdapter$UnaryMethodHandler.handle(HttpAdapter.java:572)
[pubsub] at io.gapi.emulators.grpc.HttpAdapter.handleRequest(HttpAdapter.java:195)
[pubsub] at io.gapi.emulators.netty.HttpHandler.channelRead(HttpHandler.java:52)
[pubsub] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
[pubsub] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
[pubsub] at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
[pubsub] at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103)
[pubsub] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
[pubsub] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
[pubsub] at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
[pubsub] at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103)
[pubsub] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
[pubsub] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
[pubsub] at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
[pubsub] at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:324)
[pubsub] at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:296)
[pubsub] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
[pubsub] at io.netty.channel.AbstractChannelHandlerContext.access$600(AbstractChannelHandlerContext.java:61)
[pubsub] at io.netty.channel.AbstractChannelHandlerContext$7.run(AbstractChannelHandlerContext.java:370)
[pubsub] at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)
[pubsub] at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:469)
[pubsub] at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:503)
[pubsub] at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
[pubsub] at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
[pubsub] at java.base/java.lang.Thread.run(Thread.java:1589)
[pubsub]
[pubsub] Nov 17, 2022 4:02:20 PM io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder$FrameReadListener shouldIgnoreHeadersOrDataFrame
[pubsub] INFO: [id: 0xde374c44, L:/127.0.0.1:56005 - R:/127.0.0.1:56628] ignoring DATA frame for stream RST_STREAM sent.
[pubsub] Nov 17, 2022 4:02:20 PM io.gapi.emulators.netty.HttpHandler$1 onError
[pubsub] INFO: Exception when handling request: INTERNAL: RST_STREAM closed stream. HTTP/2 error code: PROTOCOL_ERROR
</code></pre>
<p>If I try it with t<strong>he Python client, it just never reaches the server,</strong> since I can't see anything in the logs. This is the Python scripts:</p>
<pre><code>import logging
import os
from dotenv import load_dotenv
from google.cloud import pubsub_v1
load_dotenv()
logger = logging.getLogger(__name__)
HOST, PROJECT_ID = os.environ.get("PUBSUB_EMULATOR_HOST"), os.environ.get("PUBSUB_PROJECT_ID")
print(f"Host: {HOST}, Project ID: {PROJECT_ID}")
publisher = pubsub_v1.PublisherClient()
def list_topics(project_id):
project_path = f"projects/{project_id}"
all_topics = list(publisher.list_topics(
request={"project": project_path},
timeout=5
))
print(f"Found {len(all_topics)}")
return all_topics
logger.info("Listing topics for project:")
topics = list_topics(project_id=PROJECT_ID)
for topic in topics:
logger.info(topics)
</code></pre>
<p>which is just printing the correct env variables, but the client never gets a response for the rpc call.</p>
<pre><code>Host: [::1]:8085, Project ID: tokyo-rain-123
</code></pre>
<p>Any idea why this is happening ?</p>
<p>Thanks in advance !</p>
|
[
{
"answer_id": 74477822,
"author": "libik",
"author_id": 2854908,
"author_profile": "https://Stackoverflow.com/users/2854908",
"pm_score": 2,
"selected": true,
"text": "let data = [\n { id: 1, name: 'a' },\n { id: 1, name: 'b'},\n { id: 1, name: 'a'},\n { id: 2, name: 'a'},\n { id: 2, name: 'b'},\n { id: 3, name: 'c'},\n { id: 3, name: 'c'}\n ]\n \nconst nodup = new Set();\ndata.forEach(item => nodup.add(`${item.id}-${item.name}`));\nconsole.log(Array.from(nodup))\nlet uniqueData = Array.from(nodup).map(item => {\n const data = item.split('-')\n return {id: data[0], name: data[1]};\n});\nconsole.log(uniqueData);"
},
{
"answer_id": 74477867,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 1,
"selected": false,
"text": "let data = [\n { id: 1, name: 'a' },\n { id: 1, name: 'b'},\n { id: 1, name: 'a'},\n { id: 2, name: 'a'},\n { id: 2, name: 'b'},\n { id: 3, name: 'c'},\n { id: 3, name: 'c'}\n ]\nconst unique_combos= (arr1) => {\nconst returned_array = []\narr1.map(element => {\n if (!(returned_array.find(e=>e?.id === element?.id && e?.name === element.name)))\n returned_array.push(element);\n})\n\nreturn (returned_array);\n}\n\nconsole.log(unique_combos(data))"
},
{
"answer_id": 74478262,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "reduce"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7245020/"
] |
74,477,737
|
<p>I have a query that will return all the results for matching row values between two tables.</p>
<p>The tables are <code>Students</code> and <code>StudentRace</code>. The match in the <code>WHERE</code> statement is <code>STUDENTS.ID = STUDENTRACE.STUDENTID</code>.</p>
<p>I am trying to return the column <code>STUDENTRACE.RACECD</code> where all the matching RACECDs are in a single row in the resulting table. The query does something different, however. IF a STUDENTID has more than 1 RACECD it does not repeat each RACECD in a single row for the STUDENTID. It will return a separate row for each RACECD that matches the STUDENTID.Here is my query:</p>
<pre><code>select
STUDENTS.ID as ID,
STUDENTS.STUDENT_NUMBER as STUDENT_NUMBER,
STUDENTRACE.STUDENTID as STUDENTID,
STUDENTS.FIRST_NAME as FIRST_NAME,
STUDENTS.LAST_NAME as LAST_NAME,
STUDENTRACE.RACECD as RACECD,
STUDENTS.ENROLL_STATUS as ENROLL_STATUS
from
STUDENTRACE STUDENTRACE,
STUDENTS STUDENTS
where
STUDENTS.ID = STUDENTRACE.STUDENTID
and ENROLL_STATUS = 0
</code></pre>
<p>Here is the result for a STUDENT ID = 23:</p>
<pre><code>StudentID Racecd
23 B
23 W
</code></pre>
<p>This is close but not exactly what I would like to see. I would like the result to be:</p>
<pre><code>StudentID Racecd
23 B,W
</code></pre>
<p>or something similar to that. I think I may need the <code>CONCAT</code> function and possibly a nested <code>SELECT</code> statement as well, but I am not sure. I am new to SQL so I am not sure how to move forward.</p>
|
[
{
"answer_id": 74477822,
"author": "libik",
"author_id": 2854908,
"author_profile": "https://Stackoverflow.com/users/2854908",
"pm_score": 2,
"selected": true,
"text": "let data = [\n { id: 1, name: 'a' },\n { id: 1, name: 'b'},\n { id: 1, name: 'a'},\n { id: 2, name: 'a'},\n { id: 2, name: 'b'},\n { id: 3, name: 'c'},\n { id: 3, name: 'c'}\n ]\n \nconst nodup = new Set();\ndata.forEach(item => nodup.add(`${item.id}-${item.name}`));\nconsole.log(Array.from(nodup))\nlet uniqueData = Array.from(nodup).map(item => {\n const data = item.split('-')\n return {id: data[0], name: data[1]};\n});\nconsole.log(uniqueData);"
},
{
"answer_id": 74477867,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 1,
"selected": false,
"text": "let data = [\n { id: 1, name: 'a' },\n { id: 1, name: 'b'},\n { id: 1, name: 'a'},\n { id: 2, name: 'a'},\n { id: 2, name: 'b'},\n { id: 3, name: 'c'},\n { id: 3, name: 'c'}\n ]\nconst unique_combos= (arr1) => {\nconst returned_array = []\narr1.map(element => {\n if (!(returned_array.find(e=>e?.id === element?.id && e?.name === element.name)))\n returned_array.push(element);\n})\n\nreturn (returned_array);\n}\n\nconsole.log(unique_combos(data))"
},
{
"answer_id": 74478262,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "reduce"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531070/"
] |
74,477,751
|
<p>i just did a backup, and when i tried to log in the website (/wp-admin) this error appears:</p>
<p>Warning: require(/htdocs/wp-includes/version.php): Failed to open stream: No such file or directory in /htdocs/wp-settings.php on line 33</p>
<p>Fatal error: Uncaught Error: Failed opening required '/htdocs/wp-includes/version.php' (include_path='.:/usr/share/php') in /htdocs/wp-settings.php:33 Stack trace: #0 /htdocs/wp-config.php(86): require_once() #1 /htdocs/wp-load.php(50): require_once('/htdocs/wp-conf...') #2 /htdocs/wp-admin/admin.php(34): require_once('/htdocs/wp-load...') #3 /htdocs/wp-admin/index.php(10): require_once('/htdocs/wp-admi...') #4 {main} thrown in /htdocs/wp-settings.php on line 33
for more info this is my website: <a href="https://sg-plombier.be/" rel="nofollow noreferrer">https://sg-plombier.be/</a></p>
<p>i don't know what to do now.</p>
|
[
{
"answer_id": 74477822,
"author": "libik",
"author_id": 2854908,
"author_profile": "https://Stackoverflow.com/users/2854908",
"pm_score": 2,
"selected": true,
"text": "let data = [\n { id: 1, name: 'a' },\n { id: 1, name: 'b'},\n { id: 1, name: 'a'},\n { id: 2, name: 'a'},\n { id: 2, name: 'b'},\n { id: 3, name: 'c'},\n { id: 3, name: 'c'}\n ]\n \nconst nodup = new Set();\ndata.forEach(item => nodup.add(`${item.id}-${item.name}`));\nconsole.log(Array.from(nodup))\nlet uniqueData = Array.from(nodup).map(item => {\n const data = item.split('-')\n return {id: data[0], name: data[1]};\n});\nconsole.log(uniqueData);"
},
{
"answer_id": 74477867,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 1,
"selected": false,
"text": "let data = [\n { id: 1, name: 'a' },\n { id: 1, name: 'b'},\n { id: 1, name: 'a'},\n { id: 2, name: 'a'},\n { id: 2, name: 'b'},\n { id: 3, name: 'c'},\n { id: 3, name: 'c'}\n ]\nconst unique_combos= (arr1) => {\nconst returned_array = []\narr1.map(element => {\n if (!(returned_array.find(e=>e?.id === element?.id && e?.name === element.name)))\n returned_array.push(element);\n})\n\nreturn (returned_array);\n}\n\nconsole.log(unique_combos(data))"
},
{
"answer_id": 74478262,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "reduce"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20386311/"
] |
74,477,756
|
<p>I have a table in Postgres with a column that has distinct alphanumeric values in the pattern 1234P001. However, due to some bug, there are duplicate values in the column, like <code>1234P001</code> appearing thrice.</p>
<p>I want to replace duplicate <code>1234P001</code>'s with <code>1234P002</code>, <code>1234P003</code> and <code>1234P004</code>. How can I do this in PostgresSql?</p>
<p>I tried using sequence but it didn't work.</p>
|
[
{
"answer_id": 74477822,
"author": "libik",
"author_id": 2854908,
"author_profile": "https://Stackoverflow.com/users/2854908",
"pm_score": 2,
"selected": true,
"text": "let data = [\n { id: 1, name: 'a' },\n { id: 1, name: 'b'},\n { id: 1, name: 'a'},\n { id: 2, name: 'a'},\n { id: 2, name: 'b'},\n { id: 3, name: 'c'},\n { id: 3, name: 'c'}\n ]\n \nconst nodup = new Set();\ndata.forEach(item => nodup.add(`${item.id}-${item.name}`));\nconsole.log(Array.from(nodup))\nlet uniqueData = Array.from(nodup).map(item => {\n const data = item.split('-')\n return {id: data[0], name: data[1]};\n});\nconsole.log(uniqueData);"
},
{
"answer_id": 74477867,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 1,
"selected": false,
"text": "let data = [\n { id: 1, name: 'a' },\n { id: 1, name: 'b'},\n { id: 1, name: 'a'},\n { id: 2, name: 'a'},\n { id: 2, name: 'b'},\n { id: 3, name: 'c'},\n { id: 3, name: 'c'}\n ]\nconst unique_combos= (arr1) => {\nconst returned_array = []\narr1.map(element => {\n if (!(returned_array.find(e=>e?.id === element?.id && e?.name === element.name)))\n returned_array.push(element);\n})\n\nreturn (returned_array);\n}\n\nconsole.log(unique_combos(data))"
},
{
"answer_id": 74478262,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "reduce"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531357/"
] |
74,477,765
|
<p>Suppose:</p>
<p><code>props.data1 = 'data1'</code> and <code>props.data2 = 'data2'</code></p>
<p>In React, I have the following code:</p>
<pre><code> <div>
{props.data1}&emsp;&emsp;&emsp;&emsp;{props.data2}
</div>
</code></pre>
<p>Which appears like: <code>data1 data2</code>.</p>
<p>What I am trying to do is <em>right justify</em> only data2 so it looks like the following:</p>
<p><code>data1 data2</code></p>
<p>Assuming that is the furthest data2 can be pushed horizontally. Is there any tag/CSS that I can add to enable this? I've tried using span, but it causes <code>data2</code> to be pushed to a newline in React.</p>
|
[
{
"answer_id": 74477900,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "display: flex;"
},
{
"answer_id": 74477908,
"author": "Carlos Silva",
"author_id": 11579317,
"author_profile": "https://Stackoverflow.com/users/11579317",
"pm_score": 0,
"selected": false,
"text": "<div style=\"width: 100%; display: flex; justify-content: space-between\">\n <span>{data1}</span>\n <span>{data2}</span>\n</div>\n"
},
{
"answer_id": 74477915,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 0,
"selected": false,
"text": ".wrapper {\n display: flex;\n justify-content: space-between;\n}"
},
{
"answer_id": 74477923,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 2,
"selected": true,
"text": "<div class=\"container\">\n<span>data1</span>\n<span>data2</span>\n</div>\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11199289/"
] |
74,477,796
|
<p>I have a list of Future, with each Future completing with a List of values OR with a failure. I am trying to combine these futures in a way that all available values are captured and errors are logged. This is my attempt:</p>
<pre><code>val individualFutures: List[Future[Seq[Element]]] = ....
val allElements: Future[List[Element]] = Future.foldLeft(individualFutures)(List[Element]())((acc,
elements) => acc ++ elements)
Try(Await.result(allElements, Duration.Inf)) match {
case Success(elements) => ....
case Failure(error) => ....log
}
</code></pre>
<p>But I don't think this is right way to achieve my objective. I guess as soon as a future completes with an error, this would stop there.</p>
<p>How can I achieve same?</p>
|
[
{
"answer_id": 74478631,
"author": "farmac",
"author_id": 8973587,
"author_profile": "https://Stackoverflow.com/users/8973587",
"pm_score": 3,
"selected": true,
"text": " val allElements: Future[List[Element]] = Future.traverse(individualFutures) {\n _.recover {\n case throwable: Throwable =>\n println(throwable.getMessage)\n Nil\n }\n }.map(_.flatten)\n"
},
{
"answer_id": 74488384,
"author": "Zvi Mints",
"author_id": 10875851,
"author_profile": "https://Stackoverflow.com/users/10875851",
"pm_score": 0,
"selected": false,
"text": "\nobject FutureSupport extends StrictLogging {\n \n def aggregateSuccessSequence[In](futures: List[Future[In]], logOnFailure: Boolean = false)(implicit ec: ExecutionContext): Future[AggregateResult[In]] = {\n val futureTries = futures.map(_.map(Success(_)).recover {\n case NonFatal(ex) =>\n if (logOnFailure) {\n logger.warn(s\"FutureSupport: Failure occurred on aggregateSuccessSequence\", ex)\n }\n Failure(ex)\n })\n Future.sequence(futureTries).map {\n _.foldRight(AggregateResult.empty[In]) {\n case (curr, acc) =>\n curr match {\n case Success(res) => AggregateResult(acc.failureOccurred, res :: acc.outs)\n case Failure(_) => AggregateResult(failureOccurred = true, acc.outs)\n }\n }\n }\n }\n\n def aggregateSuccessTraversal[In, Out](source: List[In])(f: In => Future[Option[Out]])(logOnFailure: Boolean = false)(implicit ec: ExecutionContext): Future[AggregateResult[Out]] = {\n if (source.isEmpty) {\n Future.successful(AggregateResult.empty[In])\n }\n\n Future\n .traverse(source)(in => f(in).map(Success(_)).recover {\n case NonFatal(ex) =>\n if (logOnFailure) {\n logger.warn(s\"FutureSupport: Failure occurred on aggregateSuccessTraversal\", ex)\n }\n Failure(ex)\n })\n .map {\n _.foldRight(AggregateResult.empty[Out]) {\n case (curr, acc) =>\n curr match {\n case Failure(_) => acc.copy(failureOccurred = true)\n case Success(opt) => opt match {\n case Some(success) => acc.copy(outs = success :: acc.outs)\n case None => acc\n }\n }\n }\n }\n }\n\n case class AggregateResult[Out](failureOccurred: Boolean, outs: List[Out])\n object AggregateResult {\n def empty[Out]: AggregateResult[Out] = AggregateResult(failureOccurred = false, Nil)\n }\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2444661/"
] |
74,477,817
|
<p>I have two dfs(500x100 & 1300x2) and want to create a new column in the first one with which categories that occur on each row. To achieve this I need to fetch the category associated with the column name from second df. There might be several categories on same row.</p>
<pre><code>df = pd.DataFrame({'apple': [0, 0, 1, 0],
'strawberries': [0, 1, 1, 0],
'cucumber': [1, 1, 0, 0],
'hawthorn': [0, 1, 0, 1]
})
df2 = pd.DataFrame({'storage': ['apple', 'strawberries', 'cucumber', 'hawthorn'],
'category': ['fruits', 'berries', 'vegetables', 'berries']
})
</code></pre>
<p>I've found two potential solutions which both aims to fetch value from dict when value of row is != 0:</p>
<pre><code>df2_dict = dict(zip(df2['storage'], df2['category']))
df['categories'] = pd.Series(df.columns[np.where(df!=0)[1]]).map(df2_dict)
|
df['categories'] = df.apply(lambda s: ', '.join(s.index[s.eq(1)]), axis = 1).map(df2_dict)
</code></pre>
<p>These works to some extent but for some reason only give me results on about 1/10 of the rows. Desired output would be:</p>
<pre><code>df = pd.DataFrame({'apple': [0, 0, 1, 0],
'strawberries': [0, 1, 1, 0],
'cucumber': [1, 1, 0, 0],
'hawthorn': [0, 1, 0, 1],
'categories': ['vegetables', 'berries, vegetables, berries',
'fruits, berries', 'berries' ]})
</code></pre>
<p>As of now column names are keys in dict. FYI the columns are dummies so only 0|1 in them.</p>
<p>Appreciate any smart solutions to this.
xoxo</p>
|
[
{
"answer_id": 74478631,
"author": "farmac",
"author_id": 8973587,
"author_profile": "https://Stackoverflow.com/users/8973587",
"pm_score": 3,
"selected": true,
"text": " val allElements: Future[List[Element]] = Future.traverse(individualFutures) {\n _.recover {\n case throwable: Throwable =>\n println(throwable.getMessage)\n Nil\n }\n }.map(_.flatten)\n"
},
{
"answer_id": 74488384,
"author": "Zvi Mints",
"author_id": 10875851,
"author_profile": "https://Stackoverflow.com/users/10875851",
"pm_score": 0,
"selected": false,
"text": "\nobject FutureSupport extends StrictLogging {\n \n def aggregateSuccessSequence[In](futures: List[Future[In]], logOnFailure: Boolean = false)(implicit ec: ExecutionContext): Future[AggregateResult[In]] = {\n val futureTries = futures.map(_.map(Success(_)).recover {\n case NonFatal(ex) =>\n if (logOnFailure) {\n logger.warn(s\"FutureSupport: Failure occurred on aggregateSuccessSequence\", ex)\n }\n Failure(ex)\n })\n Future.sequence(futureTries).map {\n _.foldRight(AggregateResult.empty[In]) {\n case (curr, acc) =>\n curr match {\n case Success(res) => AggregateResult(acc.failureOccurred, res :: acc.outs)\n case Failure(_) => AggregateResult(failureOccurred = true, acc.outs)\n }\n }\n }\n }\n\n def aggregateSuccessTraversal[In, Out](source: List[In])(f: In => Future[Option[Out]])(logOnFailure: Boolean = false)(implicit ec: ExecutionContext): Future[AggregateResult[Out]] = {\n if (source.isEmpty) {\n Future.successful(AggregateResult.empty[In])\n }\n\n Future\n .traverse(source)(in => f(in).map(Success(_)).recover {\n case NonFatal(ex) =>\n if (logOnFailure) {\n logger.warn(s\"FutureSupport: Failure occurred on aggregateSuccessTraversal\", ex)\n }\n Failure(ex)\n })\n .map {\n _.foldRight(AggregateResult.empty[Out]) {\n case (curr, acc) =>\n curr match {\n case Failure(_) => acc.copy(failureOccurred = true)\n case Success(opt) => opt match {\n case Some(success) => acc.copy(outs = success :: acc.outs)\n case None => acc\n }\n }\n }\n }\n }\n\n case class AggregateResult[Out](failureOccurred: Boolean, outs: List[Out])\n object AggregateResult {\n def empty[Out]: AggregateResult[Out] = AggregateResult(failureOccurred = false, Nil)\n }\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11481935/"
] |
74,477,827
|
<p>No precise information on the "resourceType" usable with the YAML pipeline security API:</p>
<p><a href="https://learn.microsoft.com/en-us/rest/api/azure/devops/approvalsandchecks/pipeline-permissions/get?view=azure-devops-rest-7.0&tabs=HTTP" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/rest/api/azure/devops/approvalsandchecks/pipeline-permissions/get?view=azure-devops-rest-7.0&tabs=HTTP</a></p>
<p><a href="https://dev.azure.com/%7Borganization%7D/%7Bproject%7D/_apis/pipelines/pipelinepermissions/%7BresourceType%7D/%7BresourceId%7D?api-version=7.0-preview.1" rel="nofollow noreferrer">https://dev.azure.com/{organization}/{project}/_apis/pipelines/pipelinepermissions/{resourceType}/{resourceId}?api-version=7.0-preview.1</a></p>
|
[
{
"answer_id": 74486045,
"author": "Ziyang Liu-MSFT",
"author_id": 16183552,
"author_profile": "https://Stackoverflow.com/users/16183552",
"pm_score": 1,
"selected": false,
"text": "GET https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}/resources?api-version=7.0-preview.1\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11379807/"
] |
74,477,869
|
<p>Normally all things is good but when I want to add setState() it show overflow. I am making an BMI calculator app and i create a custom button and i think there the problem started.</p>
<pre><code>import 'package:flutter/material.dart';
class RoundIconButton extends StatelessWidget {
RoundIconButton({required this.icon, required this.tap});
final IconData icon;
final Function tap;
@override
Widget build(BuildContext context) {
return RawMaterialButton(
onPressed: tap(),
child: Icon(
icon,
color: Color(0xffFF8B00),
),
elevation: 6.0,
constraints: BoxConstraints.tightFor(
width: 40.0,
height: 47.0,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
fillColor: Colors.black,
);
}
}
</code></pre>
<pre><code>import 'package:bmi_calculator/round_icon_button.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'reusable_card.dart';
import 'iconText.dart';
import 'constants.dart';
enum Gender {
male,
female,
}
class InputPage extends StatefulWidget {
const InputPage({Key? key}) : super(key: key);
@override
State<InputPage> createState() => _InputPageState();
}
class _InputPageState extends State<InputPage> {
Gender? selectedGender;
int height = 180;
int weight = 50;
int age = 18;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.black,
title: Text('BMI Calculator'),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Row(
children: [
Expanded(
child: GestureDetector(
onTap: () {
setState(() {
selectedGender = Gender.male;
print('Male tapped');
});
},
child: ReuseableCard(
colour: selectedGender == Gender.male
? kactiveCardColor
: kinactiveCardColor,
cardChild: iconText(
icon: FontAwesomeIcons.mars,
lable: 'Male',
),
),
),
),
Expanded(
child: GestureDetector(
onTap: () {
setState(() {
selectedGender = Gender.female;
print('Female Tapped');
});
},
child: ReuseableCard(
colour: selectedGender == Gender.female
? kactiveCardColor
: kinactiveCardColor,
cardChild: iconText(
icon: FontAwesomeIcons.venus,
lable: 'FeMale',
),
),
),
),
],
),
),
Expanded(
child: ReuseableCard(
colour: Color(0xffFF8B00),
cardChild: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Height'.toUpperCase(),
style: klableTextStylet,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(
height.toString(),
style: kNumberTextStyle,
),
Text('cm'),
],
),
SliderTheme(
data: SliderTheme.of(context).copyWith(
overlayColor: Colors.red,
thumbShape: RoundSliderThumbShape(enabledThumbRadius: 15),
overlayShape: RoundSliderOverlayShape(overlayRadius: 30),
),
child: Slider(
value: height.toDouble(),
max: 220.0,
min: 50.0,
inactiveColor: Colors.yellow,
activeColor: Colors.black,
thumbColor: Colors.red,
onChanged: (double newValue) {
setState(() {
height = newValue.round();
print(newValue);
});
},
),
),
],
),
),
),
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: ReuseableCard(
colour: Color(0xffFF8B00),
cardChild: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Weight'.toUpperCase(),
style: klableTextStylet,
),
Text(
weight.toString(),
style: kNumberTextStyle,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RoundIconButton(
tap: (){
setState(() {
weight++;
});
},
icon: FontAwesomeIcons.plus,
),
SizedBox(
width: 10,
),
RoundIconButton(
tap: (){
setState(() {
weight--;
});
},
icon: FontAwesomeIcons.minus,
),
],
),
],
),
),
),
Expanded(
child: ReuseableCard(
colour: Color(0xffFF8B00),
cardChild: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Age'.toUpperCase(),
style: klableTextStylet,
),
Text(
age.toString(),
style: kNumberTextStyle,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RoundIconButton(
tap: (){
setState(() {
age++;
});
},
icon: FontAwesomeIcons.plus,
),
SizedBox(
width: 10,
),
RoundIconButton(
tap: (){
setState(() {
age--;
});
},
icon: FontAwesomeIcons.minus,
),
],
),
],
),
),
),
],
),
),
Container(
child: Center(
child: Text(
'Your BMI Calculator',
style: TextStyle(
color: Color(0xffFF8B00),
),
)),
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15), topRight: Radius.circular(15)),
),
width: double.infinity,
height: kbottomContainerHeight,
margin: EdgeInsets.only(top: 10),
),
],
),
);
}
}
</code></pre>
<p>In above code i want to add setstate function in RoundIconButton but when i try to add this it show overflow.<a href="https://i.stack.imgur.com/MG7XH.png" rel="nofollow noreferrer">I am expecting this</a> <a href="https://i.stack.imgur.com/DvSnB.png" rel="nofollow noreferrer">But getting this</a></p>
|
[
{
"answer_id": 74486045,
"author": "Ziyang Liu-MSFT",
"author_id": 16183552,
"author_profile": "https://Stackoverflow.com/users/16183552",
"pm_score": 1,
"selected": false,
"text": "GET https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}/resources?api-version=7.0-preview.1\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11425074/"
] |
74,477,916
|
<p>In the following code, I am trying to use a flag to break out of the loop when true (password is correct) but limit the number of incorrect tries to 3.</p>
<pre><code>def secretagent():
flag=False
while flag==False:
for i in range(3):
password=input("Enter password:")
if password=="secret007":
print("Access Granted!")
flag=True
break
else:
print("Impostor...access denied!")
print("Welcome Secret agent...let's get started...")
#print("You have tried 3 times and failed. Goodbye forever!")
secretagent()
</code></pre>
<p>Here, for ease, is the trinket: <a href="https://trinket.io/python/8869529c45" rel="nofollow noreferrer">https://trinket.io/python/8869529c45</a></p>
<p>Can anyone suggest a suitable solution - the most pythonic way and for learning purposes explain the best way to approach this. e.g. should the for loop or while loop be on the outside and why?</p>
<p>Currently, it still allows unlimited number of tries so my for loop has obviously been placed wrong.</p>
|
[
{
"answer_id": 74486045,
"author": "Ziyang Liu-MSFT",
"author_id": 16183552,
"author_profile": "https://Stackoverflow.com/users/16183552",
"pm_score": 1,
"selected": false,
"text": "GET https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}/resources?api-version=7.0-preview.1\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5074035/"
] |
74,477,930
|
<p>Situation: I want a <code>figure</code> that has an <code>img</code> and a <code>figcaption</code> stacked vertically. The <code>figure</code> should be <code>100vh</code> high, the <code>figcaption</code> its natural height (i.e. it could split onto two lines, or the user could change the text size), and the <code>img</code> should flex to take the remaining space.</p>
<p>I’ve got a solution that works if the image is initially smaller than the viewport: <a href="https://codepen.io/robinwhittleton/pen/XWYaqyg" rel="nofollow noreferrer">https://codepen.io/robinwhittleton/pen/XWYaqyg</a>. But if you edit that pen to an image size of 2000x3000 (i.e. bigger than the viewport) it breaks.</p>
<p>Sample HTML:</p>
<pre class="lang-html prettyprint-override"><code><figure>
<img src="https://via.placeholder.com/200x300/eee?text=2:3"/>
<figcaption>Figcaption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption caption</figcaption>
</figure>
</code></pre>
<p>Sample CSS:</p>
<pre class="lang-css prettyprint-override"><code>figure {
margin: 0;
display: flex;
flex-direction: column;
height: 100vh;
}
img {
object-fit: contain;
flex-shrink: 1;
}
</code></pre>
<p>I’ve tried a bunch of stuff now but either I’m fundamentally misunderstanding this, or it’s not really possible to do (which seems unlikely). Any ideas? This is going into an ePub so the ideal solution will work on slightly older WebKits, but at this point I’d just be happy with a solution that’s working in browsers.</p>
|
[
{
"answer_id": 74524323,
"author": "SerzN1",
"author_id": 2236216,
"author_profile": "https://Stackoverflow.com/users/2236216",
"pm_score": 0,
"selected": false,
"text": "figure {\n margin: 0;\n display: grid;\n flex-direction: column;\n height: 100vh;\n grid-auto-rows: 1fr auto;\n}\n\nimg {\n height: 100%;\n}\n\n\nbody { margin: 0}"
},
{
"answer_id": 74533208,
"author": "Huy Phan",
"author_id": 1664655,
"author_profile": "https://Stackoverflow.com/users/1664655",
"pm_score": 3,
"selected": true,
"text": "flex-grow"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453783/"
] |
74,477,932
|
<p>My original syntax:</p>
<pre><code>select count (*) as Total, description
from ADSAccount
group by Description
</code></pre>
<p>Results:</p>
<pre><code>Total Description
--------------------
20 CloudRoom
100 User
200 Cloud
800 AD
</code></pre>
<p>I'm trying to add a count separation of the "AD" accounts.</p>
<p>I need to split count 800 AD accounts with the following where clause: where SAMAccountName like 'DOM%' and description = 'AD'</p>
<p>Tried the following but its not working:</p>
<pre><code>select count (*) as total, description
from ADSAccount
left join
(select count (*) as DOM
from ADSAccount
where SAMAccountName like 'DOM%'
and description = 'AD')
group by Description
</code></pre>
<p>Expected Result
Results:</p>
<pre><code>Total Description
--------------------
20 CloudRoom
100 User
200 Cloud
700 AD
100 AD-DOM
</code></pre>
<p>Thanks for any advice.</p>
|
[
{
"answer_id": 74524323,
"author": "SerzN1",
"author_id": 2236216,
"author_profile": "https://Stackoverflow.com/users/2236216",
"pm_score": 0,
"selected": false,
"text": "figure {\n margin: 0;\n display: grid;\n flex-direction: column;\n height: 100vh;\n grid-auto-rows: 1fr auto;\n}\n\nimg {\n height: 100%;\n}\n\n\nbody { margin: 0}"
},
{
"answer_id": 74533208,
"author": "Huy Phan",
"author_id": 1664655,
"author_profile": "https://Stackoverflow.com/users/1664655",
"pm_score": 3,
"selected": true,
"text": "flex-grow"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531330/"
] |
74,477,950
|
<p>So i'm on this Kata :</p>
<p>`</p>
<pre><code>def first_non_repeating_letter(s)
a = s.chars
a.select! { |char| a.count(char) == 1 }
if a.empty?
("")
else
a.first
end
end
</code></pre>
<p>`</p>
<p>And the only thing i'm missing is :</p>
<p>"As an added challenge, upper- and lowercase letters are considered the same character, but the function should return <strong>the correct case</strong> <strong>for the initial letter</strong>. For example, the input 'sTreSS' should return 'T'."</p>
<p><code>s.downcase.chars</code> doesn't apply here then. I tried with <code>.casecmp</code> but remain unsuccessful. Should i use regex ?</p>
|
[
{
"answer_id": 74479016,
"author": "Konstantin Strukov",
"author_id": 8008340,
"author_profile": "https://Stackoverflow.com/users/8008340",
"pm_score": 0,
"selected": false,
"text": "Array#count"
},
{
"answer_id": 74480973,
"author": "Cary Swoveland",
"author_id": 256970,
"author_profile": "https://Stackoverflow.com/users/256970",
"pm_score": 1,
"selected": false,
"text": "s"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17007566/"
] |
74,477,961
|
<p>I'm writing a React app and I'm struggling with the following problem. I have a table, let's say:</p>
<pre><code><Table>
<Row onClick={() => onRowClick(0)} >
<Cell innerComponent={row.cell[0].Component}/>
<Cell innerComponent={row.cell[1].Component}/>
<Cell innerComponent={row.cell[2].Component}/>
<Cell innerComponent={row.cell[3].Component}/>
</Row>
<Row onClick={() => onRowClick(1)} >
<Cell innerComponent={row.cell[0].Component}/>
<Cell innerComponent={row.cell[1].Component}/>
<Cell innerComponent={row.cell[2].Component}/>
<Cell innerComponent={row.cell[3].Component}/>
</Row>
</Table>
</code></pre>
<p>so it's just a table component with some element inside. I added the <code>onRowClick</code> prop to the table but the issue is raised when the <code>row.cell[_].Component</code>, that is rendered in the Cell, has a button inside. Indeed, in that case the <code>onClick</code> of the button and the onRowClick is invoked that is partially wrong.</p>
<p>I know, I can use <code>e.stopPropagation()</code> on the inner button onClick but this is easily forgettable and not so maintainable in a big team.</p>
<p>Do you have any suggestion how can I invoke the onRowClick only if this is the first onClick handler invoked instead of stop propagation from the inner handler?</p>
|
[
{
"answer_id": 74479016,
"author": "Konstantin Strukov",
"author_id": 8008340,
"author_profile": "https://Stackoverflow.com/users/8008340",
"pm_score": 0,
"selected": false,
"text": "Array#count"
},
{
"answer_id": 74480973,
"author": "Cary Swoveland",
"author_id": 256970,
"author_profile": "https://Stackoverflow.com/users/256970",
"pm_score": 1,
"selected": false,
"text": "s"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3185712/"
] |
74,477,963
|
<pre><code>String s = #Section250342,Main,First/HS/12345/Jack/M,200010 10.00 200011 -2.00,
#Section250322,Main,First/HS/12345/Aaron/N,200010 17.00,
#Section250399,Main,First/HS/12345/Jimmy/N,200010 12.00,
#Section251234,Main,First/HS/12345/Jack/M,200011 11.00
</code></pre>
<p>Wherever there is the word /Jack/M in the3 string, I want to pull the section numbers(250342,251234),dates (200010,200011) and the values(10.00,11.00,-2.00) associated with it using regex each time. Sometines a single line can contain either one value or two so that what makes the regex sort of confusing. So at the end of day, there will be 3 diff groups we want to extract.</p>
<p>I tried</p>
<pre class="lang-none prettyprint-override"><code>#Section(\d+)(?:(?!#Section\d).)*\bJack/M,(\d+)\h+(\d+(?:\.\d+)?)\s(\d+)\h+([-+]?\d+(?:\.\d+)?)\b
</code></pre>
<p>See it in action here - <a href="https://regex101.com/r/JaKeGg/1" rel="nofollow noreferrer">https://regex101.com/r/JaKeGg/1</a>, it brings in 5 groups instead of 3 and when there is only one value here it doesn't seem to match so I need help with this.</p>
|
[
{
"answer_id": 74478857,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": false,
"text": "#Section(\\d+)\\b(?:(?!#Section\\d).)*\\bJack/M,(\\d+\\h+[-+]?\\d+(?:\\.\\d+)?(?:\\s+\\d+\\h+[-+]?\\d+(?:\\.\\d+)?)*)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19112514/"
] |
74,477,990
|
<p>Lets say I have the following code</p>
<pre><code>def top():
counter = 0
for ch in child_1():
print(ch)
counter += 1
if counter > 2:
break
def child_1():
for ch in child_2():
yield ch
print("child_1 logic has finished")
def child_2():
for ch in "123456789":
yield ch
print("child_2 logic has finished")
if __name__ == '__main__':
top()
</code></pre>
<p>Is there a way to have top() method to exit in the middle of the iteration like I have the counter condition, but let the children to finish their logic? (get to the code after the yield statement)</p>
<p>I tried to use while loop and other python tricks but it all went unsuccessful, I don't think there's a way without modifying the nested generators to not be a generators but I'm trying my shot here :D</p>
|
[
{
"answer_id": 74478062,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 3,
"selected": true,
"text": "def top():\n counter = 0\n\n iter_1 = child_1()\n for ch in iter_1:\n print(ch)\n counter += 1\n\n if counter > 2:\n break\n\n for _ in iter_1:\n pass\n"
},
{
"answer_id": 74478433,
"author": "OneMadGypsy",
"author_id": 10292330,
"author_profile": "https://Stackoverflow.com/users/10292330",
"pm_score": 1,
"selected": false,
"text": "top"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74477990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16597971/"
] |
74,478,015
|
<p>I don't like passing multiple repeating arguments, it looks a bit ugly.<br>
how can I refactor the following code?</p>
<pre><code> prev_month_start = Date.today.prev_month.beginning_of_month
prev_month_end = Date.today.prev_month.end_of_month
contacts = contacts.where('
persons.actual_delivery_date >= ? AND persons.actual_delivery_date <= ? OR
persons.expected_shipment_date >= ? AND persons.expected_shipment_date <= ?',
prev_month_start, prev_month_end,
prev_month_start, prev_month_end)
</code></pre>
|
[
{
"answer_id": 74478145,
"author": "Will Wilson",
"author_id": 4027469,
"author_profile": "https://Stackoverflow.com/users/4027469",
"pm_score": 1,
"selected": false,
"text": "contacts.where(actual_delivery_date: prev_month_start..prev_month_end).or(expected_shipment_date: prev_month_start..prev_month_end) \n"
},
{
"answer_id": 74481056,
"author": "spickermann",
"author_id": 2483313,
"author_profile": "https://Stackoverflow.com/users/2483313",
"pm_score": 3,
"selected": true,
"text": "all_month"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1202194/"
] |
74,478,044
|
<p>I have a html button that has an id, and I want to send the id of the button, but not as writing the id on the field, I want to send it as <code>this.id</code> but I cannot perform this.</p>
<pre><code><button (click)="changeEnergy(this.id)" id="flash" [ngClass]="!theme?'btnEnergy1':'btnEnergy2'">
<i id="flashIcon" class="fa-solid fa-bolt iconFlash"></i>
</button>
</code></pre>
<p>I tried by writing the id manually and it worked, but I want to send it like that as <code>this.id</code> because the id of the element changes, it is not the same id, so I need to send the <code>this.id</code> but I am not able to.</p>
|
[
{
"answer_id": 74478145,
"author": "Will Wilson",
"author_id": 4027469,
"author_profile": "https://Stackoverflow.com/users/4027469",
"pm_score": 1,
"selected": false,
"text": "contacts.where(actual_delivery_date: prev_month_start..prev_month_end).or(expected_shipment_date: prev_month_start..prev_month_end) \n"
},
{
"answer_id": 74481056,
"author": "spickermann",
"author_id": 2483313,
"author_profile": "https://Stackoverflow.com/users/2483313",
"pm_score": 3,
"selected": true,
"text": "all_month"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531528/"
] |
74,478,054
|
<p>I have an map projected with OpenLayer 6. I added a button to change to 3d view with ol-cesium.</p>
<p>When the map is in Cesium the fullscreen button of Openlayer is no more visible (which by the way works perfectly in all browsers when I am in standard OL 2d), as it happens with ol-controls. So I added a fullscreen button that appears only when in ol3d.
However, when I have ol3d activated, toggling between fullscreen and normal screen works fine only in Firefox and Chrome.
In Safari I can access the fullscreen, but I cannot exit (I have to use the keyboard esc). I don't understand where's the problem.</p>
<p>Here's my code</p>
<p><strong>HTML</strong></p>
<pre><code><div id="map" class="map">
<div id="cesiumFs">
<button id="cesiumFsButton" type="button" title="Toggle full-screen"></button>
</div>
<div id="CesiumEnable" class="cesium-icon-change-3d" title="Change projection">
<i id="globe" class="fa fa-globe fa-2x" aria-hidden="true"></i>
</div>
</div>
</code></pre>
<p><strong>JS</strong></p>
<pre><code>const ol3d = new olcs.OLCesium({
map: map,
});
//set ol3d to false as normally I want the 2d map view
ol3d.setEnabled(false);
//when clicking on 3D I enable the Cesium view
document.getElementById('enable').onclick = function() {
//get the elements controlling Fullscreen mode
let cesiumFsTrigger = document.getElementById('cesiumFs');
let cesiumFsButton = document.getElementById('cesiumFsButton');
//if ol3d is true
if(!ol3d.getEnabled()){
//when opening up Cesium I change zoom and center
const NewView = new ol.View({
projection: mercatorProjection,
center: ol.proj.transform([-80, 20], 'EPSG:4326', 'EPSG:3857'),
zoom: 3,
maxZoom: 15,
minZoom: 0,
});
map.setView(NewView);
//set ol3d to true
ol3d.setEnabled(true);
//When in 3d add a "Fullscreen" icon in substitution to the OpenLayer interaction (otherwise not working with Cesium)
//shows the new fullscreen button (set as active)
cesiumFsTrigger.classList.add('FsActive');
//add a fontawesome icon
cesiumFsButton.innerHTML = '<i id="toggleFs" class="fa fa-expand-arrows-alt" aria-hidden="true"></i>';
let iconFs = document.getElementById('toggleFs');
let cesiumFsElement = document.getElementById('map');
//set fullscreen mode to the map
cesiumFsTrigger.addEventListener("click", () => {
if (!document.fullscreenElement) {
Cesium.Fullscreen.requestFullscreen(cesiumFsElement);
iconFs.classList.remove('fa-expand-arrows-alt');
iconFs.classList.add('fa-compress-arrows-alt');
} else {
if (Cesium.Fullscreen.exitFullscreen) {
Cesium.Fullscreen.exitFullscreen();
iconFs.classList.remove('fa-compress-arrows-alt');
iconFs.classList.add('fa-expand-arrows-alt');
}
else if (Cesium.Fullscreen.webkitExitFullscreen) {
Cesium.Fullscreen.webkitExitFullscreen();
iconFs.classList.remove('fa-compress-arrows-alt');
iconFs.classList.add('fa-expand-arrows-alt');
}
}
});//close fullscreen conditions for icons
}
else {
//if ol3d is false
ol3d.setEnabled(false)
map.setView(view);
cesiumFsTrigger.classList.remove('FsActive');
}
};
</code></pre>
|
[
{
"answer_id": 74625431,
"author": "Albert Tinon",
"author_id": 10215367,
"author_profile": "https://Stackoverflow.com/users/10215367",
"pm_score": 0,
"selected": false,
"text": " Ion.defaultAccessToken = cesiumConf.token;\n const viewer = new Viewer('cesiumContainer', {\n geocoder: false,\n infoBox: true,\n timeline: false,\n animation: false,\n navigationHelpButton: true,\n sceneModePicker: false,\n baseLayerPicker: this.$auth0.user.value !== undefined,\n terrainProvider: createWorldTerrain(),\n // imageryProvider: new Cesium.OpenStreetMapImageryProvider({\n // url: 'https://a.tile.openstreetmap.org/'\n // }),\n imageryProvider: new ArcGisMapServerImageryProvider({\n url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'\n })\n });\n viewer.scene.primitives.add(createOsmBuildings());\n const fullScreenHandler = () => {\n const canvas = viewer.canvas;\n if ('webkitRequestFullscreen' in canvas) {\n canvas['webkitRequestFullscreen']() // Safari\n } else {\n canvas.requestFullscreen();\n }\n }\n viewer.fullscreenButton.viewModel.command.beforeExecute.addEventListener(fullScreenHandler)\n viewer.fullscreenButton.viewModel.command.afterExecute.addEventListener(fullScreenHandler)\n"
},
{
"answer_id": 74627248,
"author": "Elena Politi",
"author_id": 4275508,
"author_profile": "https://Stackoverflow.com/users/4275508",
"pm_score": 2,
"selected": true,
"text": "<div id=\"map\" class=\"map\">\n <div id=\"cesiumFs\"></div>\n\n <div id=\"CesiumEnable\" class=\"cesium-icon-change-3d\" title=\"Change projection\">\n <i id=\"globe\" class=\"fa fa-globe fa-2x\" aria-hidden=\"true\"></i>\n </div>\n</div>\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4275508/"
] |
74,478,070
|
<p>How do I replace initials with full names (if the initial matches the full name in another column)?</p>
<p>I have data that looks like this:</p>
<pre><code>data <- data.frame(name = c("Acorus americanus", "Nothocalais cuspidata", "Elymus repens", "Elymus hmmmm", "Acorus americanus"),
synonym = c("A. calamus", "Agoseris cuspidata", "Agropyron r.", "Elymus sp.", "S. americanus"))
name synonym
1 Acorus americanus A. calamus
2 Nothocalais cuspidata Agoseris cuspidata
3 Elymus repens Agropyron r.
4 Elymus hmmmm Elymus sp.
5 Acorus americanus S. americanus
</code></pre>
<p>How can I replace the initial with the name, so I get this?</p>
<pre><code> name synonym
1 Acorus americanus Acorus calamus
2 Nothocalais cuspidata Agoseris cuspidata
3 Elymus repens Agropyron repens
4 Elymus hmmmm Elymus sp.
5 Acorus americanus S. americanus
</code></pre>
<p>There are also other abbreviations like <code>sp.</code>, <code>var.</code> and <code>ssp.</code> that I don't want to change into names, but none of them are single letters. Also I would like to leave the initial if it doesn't match the first letter of a name in another column.</p>
|
[
{
"answer_id": 74478343,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "stringr::str_extract()"
},
{
"answer_id": 74479509,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\ndata %>%\n summarise(read.table(text=t(cur_data())))%>%\n mutate(across(everything(), ~if_else(str_detect(lag(., def=\"\"), .), lag(.), .)))%>%\n unite(result, sep = ' ')%>%\n mutate(rep(names(data), nrow(data)))%>%\n unstack()\n \n name synonym\n1 Acorus americanus Acorus calamus\n2 Nothocalais cuspidata Agoseris cuspidata\n3 Elymus repens Agropyron repens\n4 Elymus hmmmm Elymus sp.\n5 Acorus americanus S. americanus\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19803766/"
] |
74,478,094
|
<p>I'm learning asynchronous programming in JS and I couldn't help but noticed both JS and Raku has some construct for asynchronous programming with the same name, however I'm uncertain to what extent the knowledge from one can transfer to the other. I tried reading <a href="https://docs.raku.org/language/js-nutshell" rel="noreferrer">JS to Raku</a> but the section about <a href="https://docs.raku.org/language/js-nutshell#Asynchronous_programming" rel="noreferrer">async programming</a> is mostly barren.</p>
<p>For example, is it possible to do something like this in Raku?</p>
<pre class="lang-js prettyprint-override"><code>fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
</code></pre>
<p>Or something like this if I want to create my own promises?</p>
<pre class="lang-js prettyprint-override"><code>function getLanguages() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() >= 0.5;
if (success) {
const languages = ['js', 'perl', 'python', 'raku'];
resolve(languages);
}
else {
reject(new Error('No languages'));
}
}, 0);
});
}
getLanguages()
.then((languages) => {
console.log(languages);
})
.catch((error) => {
console.log(error);
});
</code></pre>
|
[
{
"answer_id": 74478514,
"author": "Scimon Proctor",
"author_id": 117284,
"author_profile": "https://Stackoverflow.com/users/117284",
"pm_score": 3,
"selected": false,
"text": "start"
},
{
"answer_id": 74479469,
"author": "Jonathan Worthington",
"author_id": 7832584,
"author_profile": "https://Stackoverflow.com/users/7832584",
"pm_score": 4,
"selected": true,
"text": "Promise"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10824322/"
] |
74,478,109
|
<p>I have a pandas DataFrame called data_combined with the following structure:</p>
<pre><code> index corr_year corr_5d
0 (DAL, AAL) 0.873762 0.778594
1 (WEC, ED) 0.851578 0.850549
2 (CMS, LNT) 0.850028 0.776143
3 (SWKS, QRVO) 0.850799 0.830603
4 (ALK, DAL) 0.874162 0.744590
</code></pre>
<p>Now I am trying to divide the column named index into two columns on the (,).
The desired output should look like this:</p>
<pre><code> index1 index2 corr_year corr_5d
0 DAL AAL 0.873762 0.778594
1 WEC ED 0.851578 0.850549
2 CMS LNT 0.850028 0.776143
3 SWKS QRVO 0.850799 0.830603
4 ALK DAL 0.874162 0.744590
</code></pre>
<p>I have tried using pd.explode() with the following code</p>
<pre><code>data_results_test = data_results_combined.explode('index')
data_results_test
</code></pre>
<p>Which leads to the following output:</p>
<pre><code> index corr_year corr_5d
0 DAL 0.873762 0.778594
0 AAL 0.873762 0.778594
1 WEC 0.851578 0.850549
1 ED 0.851578 0.850549
</code></pre>
<p>How can I achieve the split with newly added columns instead of rows. pd.explode does not seem to have any option to choose wether to add new rows or columns</p>
|
[
{
"answer_id": 74478185,
"author": "crashMOGWAI",
"author_id": 5373105,
"author_profile": "https://Stackoverflow.com/users/5373105",
"pm_score": 0,
"selected": false,
"text": "df[['index1','index2']] = df['index'].str.split(',',expand=True)\n"
},
{
"answer_id": 74478190,
"author": "Alex",
"author_id": 15941713,
"author_profile": "https://Stackoverflow.com/users/15941713",
"pm_score": 3,
"selected": true,
"text": "data_results_combined['index1'] = data_results_combined['index'].apply(lambda x: x[0])\ndata_results_combined['index2'] = data_results_combined['index'].apply(lambda x: x[1])\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17217956/"
] |
74,478,118
|
<p>I am trying to send email internally within work using the <code>smtplib</code> package in Python. I am running this script behind a VPN using the same proxy settings for R and Spyder.
I use the following code which was adapted from <a href="https://mkyong.com/python/how-do-send-email-in-python-via-smtplib/" rel="nofollow noreferrer">mkyoung.com</a></p>
<pre><code>import smtplib
to = 'foo@foo-corporate.com'
corp_user = 'foo@foo-corporate.com'
corp_pwd = 'password'
smtpserver = smtplib.SMTP_SSL(local_hostname="smtp://foo-corporate.com", port = 25)
smtpserver.connect()
</code></pre>
<p>Once i try the last line <code>smtpserver.connect()</code>, I get the error message:</p>
<blockquote>
<p>[WinError 10061] No connection could be made because the target machine actively refused it</p>
</blockquote>
<p>This would suggest that the server is not accepting SMTP requests.
However if i execute the same script in R using the <code>Blastula</code> <a href="https://rstudio.github.io/blastula/" rel="nofollow noreferrer">package</a> It works fine.
Can anyone suggest how I can trouble shoot this?</p>
<pre><code>library(blastula)
create_smtp_creds_key(
id = "email_creds",
user = "foo@foo-corporate.com",
host = "smtp://foo-corporate.com",
port = 25,
use_ssl = TRUE
)
email <-
compose_email(
body = md(" Hello,
This is a test email
"))
# Sending email by SMTP using a credentials file
email %>%
smtp_send(
to = "foo@foo-corporate.com",
from = "foo@foo-corporate.com",
subject = "Testing the `smtp_send()` function",
credentials = creds_key("email_creds")
)
</code></pre>
|
[
{
"answer_id": 74478378,
"author": "Ovski",
"author_id": 8610346,
"author_profile": "https://Stackoverflow.com/users/8610346",
"pm_score": 1,
"selected": false,
"text": "import smtplib\n\nsmtp_server = 'mail.example.com'\nport = 587 # For starttls\nsender_email = \"from@mail.com\"\nreceiver_email = 'to@mail.com'\npassword = r'password'\nmessage = f'''\\\nFrom: from-name <from@mail.com>\nTo: to-name <to@mail.com>\nSubject: testmail\n\ntestmail\n\n'''\ntry:\n server = smtplib.SMTP(smtp_server, port)\n server.ehlo()\n server.starttls()\n server.ehlo()\n server.login(sender_email, password)\n server.sendmail(sender_email, receiver_email, message) \nexcept Exception as e:\n # Print any error messages to stdout\n print(e)\nfinally:\n server.quit()\n"
},
{
"answer_id": 74517497,
"author": "John Smith",
"author_id": 1901071,
"author_profile": "https://Stackoverflow.com/users/1901071",
"pm_score": 1,
"selected": true,
"text": "\nimport smtplib\nimport ssl\n\nto = 'foo@foo-corporate.com'\ncorp_user = 'foo@foo-corporate.com'\ncorp_pwd = 'password'\nsmtpserver = smtplib.SMTP_SSL(\"smtp://foo-corporate.com\")\nsmtp_server.ehlo()\nsmtp_server.login(corp_user, corp_pwd)\nmsg_to_send = '''\nhello world!\n'''\n\nsmtp_server.sendmail(user,to,msg_to_send)\nsmtp_server.quit()\n\n\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1901071/"
] |
74,478,132
|
<p>I am trying to deploy an application on Azure App Service. I have created a deployment with <code>Python 3.9.7</code>, but my app needs <code>Python 3.9.12</code>. How do I upgrade python's version?</p>
<p>In Azure App Service > Configuration > General Settings > Python minor version, there is no 3.9.12 available. So I have to upgrade it by SSH. But, I don't understand Linux.</p>
<p>Can anyone tell me a command to upgrade my python version to 3.9.12 using bash?</p>
|
[
{
"answer_id": 74487947,
"author": "Hari Krishna",
"author_id": 16630138,
"author_profile": "https://Stackoverflow.com/users/16630138",
"pm_score": 2,
"selected": true,
"text": "az webapp config set ..."
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15964159/"
] |
74,478,162
|
<p>I'm struggling trying to replicate <a href="https://i.stack.imgur.com/2XaiN.png" rel="nofollow noreferrer">this</a> using Flexbox.
My result looks like <a href="https://i.stack.imgur.com/P1nkW.png" rel="nofollow noreferrer">this</a> for the moment.</p>
<p>Here is the affected code :</p>
<pre><code><div class="box-container">
<div class="box">
<p>this is some subtext under an illustration or image</p>
</div>
<div class="box">
<p>this is some subtext under an illustration or image</p>
</div>
<div class="box">
<p>this is some subtext under an illustration or image</p>
</div>
<div class="box">
<p>this is some subtext under an illustration or image</p>
</div>
</div>
</code></pre>
<pre><code>.box-container {
display: flex;
justify-content: center;
gap: 25px;
}
.box {
height: 160px;
width: 155px;
border: 3px solid #3882f6;
border-radius: 10px;
}
</code></pre>
<p>I just can't seem to figure out how to properly align/position the text under my boxes.</p>
<p>I already tried not nesting the box class with the paragraph but then the text is just hanging next to the box and not under it. I tried to play with margin and width of the container but without success.</p>
|
[
{
"answer_id": 74478266,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 2,
"selected": true,
"text": ".box-container {\n display: flex;\n justify-content: center;\n gap: 25px;\n}\n\n.box {\n height: 160px;\n width: auto;\n border: 3px solid #3882f6;\n border-radius: 10px;\n}\n\n.wrapper {\n display: flex;\n flex-direction: column;\n text-align: center;\n}"
},
{
"answer_id": 74478389,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 0,
"selected": false,
"text": " .box-container {\n display: flex;\n justify-content: center;\n gap: 25px;\n }\n\n .box-holder {\n display: flex;\n flex-direction: column;\n height: auto;\n width: auto;\n text-align: center;\n height: 240px;\n width: 155px;\n }\n\n .box {\n height: 100%;\n width: 100%;\n border: 3px solid #3882f6;\n border-radius: 10px;\n }"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19111213/"
] |
74,478,164
|
<p>I have done a quite a good research and unable to find a good tutorial for flutter. but here is what I am trying to do.</p>
<p>I have an API call which gets me a lot of data and this data should be shown across multiple screens.</p>
<p>What is the best way to do it using futurebuilder. Ideally, I would like to call the API in the splash screen and the save the data and use it across multiple screens, but not able to get a good tutorial to do it.</p>
<p>Editing to Add the code.</p>
<pre><code>Future<ApiCallResponse> makeApiCall({
required String callName,
required String apiUrl,
required ApiCallType callType,
Map<String, dynamic> headers = const {},
Map<String, dynamic> params = const {},
String? body,
BodyType? bodyType,
bool returnBody = true,
bool cache = false,
}) async {
print(apiUrl);
// print(body);
print(params);
final callRecord =
ApiCallRecord(callName, apiUrl, headers, params, body, bodyType);
// Modify for your specific needs if this differs from your API.
if (_accessToken != null) {
headers[HttpHeaders.authorizationHeader] = 'Token $_accessToken';
}
if (!apiUrl.startsWith('http')) {
apiUrl = 'https://$apiUrl';
}
// If we've already made this exact call before and caching is on,
// return the cached result.
if (cache && _apiCache.containsKey(callRecord)) {
return _apiCache[callRecord]!;
}
ApiCallResponse result;
switch (callType) {
case ApiCallType.GET:
case ApiCallType.DELETE:
result =
await urlRequest(callType, apiUrl, headers, params, returnBody);
break;
case ApiCallType.POST:
case ApiCallType.PUT:
case ApiCallType.PATCH:
result = await requestWithBody(
callType, apiUrl, headers, params, body, bodyType, returnBody);
break;
}
// If caching is on, cache the result (if present).
if (cache) {
_apiCache[callRecord] = result;
}
// print(result.jsonBody);
// print(result.jsonBody['abhijit']);
// print(result.jsonBody['gowri']);
// final prefs = await SharedPreferences.getInstance();
// await prefs.setStringList('gowri', result.jsonBody['gowri']);
// await prefs.setStringList('gouri', result.jsonBody['gouri']);
SaveDataResponse(result);
return result;
}
void SaveDataResponse(ApiCallResponse result) async{
String SunriseData = result.jsonBody['sunrise'].toString();
// String gouriVal = result.jsonBody['gouri'].toString();
print(SunriseData);
// print(gouriVal);
final prefs = await SharedPreferences.getInstance();
prefs.setString('sunrise', SunriseData);
// await prefs.setString('sunrise', SunriseData);
}
</code></pre>
<p>When I try to use the following inside the initstate on the page where I want to see the data</p>
<pre><code>sunrise= SharedPref.getString('SunriseData') as String?;
</code></pre>
<p>I get the following message</p>
<pre><code>Unhandled Exception: type 'Future<String>' is not a subtype of type 'String?' in type cast
E/flutter (18953): #0 _HomePageWidgetState._loadlatlon.<anonymous closure> (package:myApp/home_page/home_page_widget.dart:62:50)
E/flutter (18953): #1 State.setState (package:flutter/src/widgets/framework.dart:1114:30)
E/flutter (18953): #2 _HomePageWidgetState._loadlatlon (package:myApp/home_page/home_page_widget.dart:59:5)
E/flutter (18953): <asynchronous suspension>
</code></pre>
|
[
{
"answer_id": 74478394,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 1,
"selected": false,
"text": "class DataClass {\n static List allData = [];\n }\n"
},
{
"answer_id": 74502037,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "initState()"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/821887/"
] |
74,478,167
|
<p>I have a component which has child components, i want to render these child components with different Ids. They are getting their data from store.The problem is they are rendered but with the same item. how can this be solved?</p>
<p><strong>MultiImages Component</strong></p>
<pre><code>const MultiImages: () => JSX.Element = () => {
const values = ['500', '406', '614'];
return (
<div>
{values.map((val, index) => {
return <OneImage key={index} projectID={val} />;
})}
</div>
);
};
export default MultiImages;
</code></pre>
<p><strong>OneImage Component</strong></p>
<pre><code>const OneImage: () => JSX.Element = ({ projectID }) => {
const projectData = useProjectDataStore();
const { getProject } = useAction();
useEffect(() => {
getProject(projectID ?? '');
}, []);
return (
<>
<div>
<img
src={projectData.picture}
}
/>
<div>
<a>
{projectData.projectName}
</a>
</div>
</div>
</>
);
};
export default OneImage;
</code></pre>
|
[
{
"answer_id": 74478440,
"author": "André",
"author_id": 13970434,
"author_profile": "https://Stackoverflow.com/users/13970434",
"pm_score": 0,
"selected": false,
"text": "OneImage"
},
{
"answer_id": 74506463,
"author": "Alex Shtromberg",
"author_id": 4952402,
"author_profile": "https://Stackoverflow.com/users/4952402",
"pm_score": 1,
"selected": false,
"text": "const OneImage: () => JSX.Element = ({ projectID }) => {\n // making your hook depended on **projectID**\n const projectData = useProjectDataStore(projectID);\n const { getProject } = useAction();\n useEffect(() => {\n // No need of usage **projectID** cause it will inherit if from useProjectDataStore\n getProject();\n }, []);\n\n return (\n <>\n <div> \n <img\n src={projectData.picture}\n }\n />\n <div>\n <a>\n {projectData.projectName}\n </a>\n </div>\n </div>\n </>\n );\n};\n\nexport default OneImage;\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18892774/"
] |
74,478,178
|
<p>I have a dataframe like this.</p>
<pre><code> val consecutive
0 0.0001 0.0
1 0.0008 0.0
2 -0.0001 0.0
3 0.0005 0.0
4 0.0008 0.0
5 0.0002 0.0
6 0.0012 0.0
7 0.0012 1.0
8 0.0007 1.0
9 0.0004 1.0
10 0.0002 1.0
11 0.0000 0.0
12 0.0015 0.0
13 -0.0005 0.0
14 -0.0003 0.0
15 0.0001 0.0
16 0.0001 0.0
17 0.0003 0.0
18 -0.0003 0.0
19 -0.0001 0.0
20 0.0000 0.0
21 0.0000 0.0
22 -0.0008 0.0
23 -0.0008 0.0
24 -0.0001 0.0
25 -0.0006 0.0
26 -0.0010 1.0
27 0.0002 0.0
28 -0.0003 0.0
29 -0.0008 0.0
30 -0.0010 0.0
31 -0.0003 0.0
32 -0.0005 1.0
33 -0.0012 1.0
34 -0.0002 1.0
35 0.0000 0.0
36 -0.0018 0.0
37 -0.0009 0.0
38 -0.0007 0.0
39 0.0000 0.0
40 -0.0011 0.0
41 -0.0006 0.0
42 -0.0010 0.0
43 -0.0015 0.0
44 -0.0012 1.0
45 -0.0011 1.0
46 -0.0010 1.0
47 -0.0014 1.0
48 -0.0011 1.0
49 -0.0017 1.0
50 -0.0015 1.0
51 -0.0010 1.0
52 -0.0014 1.0
53 -0.0012 1.0
54 -0.0004 1.0
55 -0.0007 1.0
56 -0.0011 1.0
57 -0.0008 1.0
58 -0.0006 1.0
59 0.0002 0.0
</code></pre>
<p>The column 'consecutive' is what I want to compute. It is '1' when current row has more than 5 consecutive previous values with same sign (either positive or negative, including it self).</p>
<p>What I've tried is:</p>
<pre><code>df['consecutive'] = df['val'].rolling(5).apply(
lambda arr: np.all(arr > 0) or np.all(arr < 0), raw=True
).replace(np.nan, 0)
</code></pre>
<p>But it's too slow for large dataset.</p>
<p>Do you have any idea how to speed up?</p>
|
[
{
"answer_id": 74478933,
"author": "Emma",
"author_id": 2956135,
"author_profile": "https://Stackoverflow.com/users/2956135",
"pm_score": 0,
"selected": false,
"text": "min"
},
{
"answer_id": 74479859,
"author": "Pavloski",
"author_id": 19665312,
"author_profile": "https://Stackoverflow.com/users/19665312",
"pm_score": 1,
"selected": false,
"text": "apply()"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14937012/"
] |
74,478,191
|
<p>I have a file named <code>in.txt</code>.</p>
<p><code>in.txt</code></p>
<pre><code>0000fb435 00000326fab123bc2a 20
00003b4c6 0020346afeff655423 26
0000cb341 be3652a156fffcabd5 26
.
.
</code></pre>
<p>i need to check if number <strong>20</strong> is present in file and if present i need the output to look like this.</p>
<p><strong>Expected output</strong>:</p>
<p><code>out.txt</code></p>
<pre><code>0020fb435 00000326fab123bc2a 20 twenty_number
00003b4c6 0020346afeff655423 26 none
0000cb341 be3652a120fffcabd5 26 none
.
.
</code></pre>
<p>this is my current attempt:</p>
<pre><code>with open("in.txt", "r") as fin:
with open("out.txt", "w") as fout:
for line in fin:
line = line.strip()
if '20' in line:
fout.write(line + f" twenty_number \n")
</code></pre>
<p>this is <strong>current output</strong>:
<code>out.txt</code></p>
<pre><code>0020fb435 00000326fab123bc2a 20 twenty_number
00003b4c6 0020346afeff655423 26 twenty_number
0000cb341 be3652a120fffcabd5 26 twenty_number
.
.
</code></pre>
<p>this is because it is checking "20" in every line but i only need to check the last column.</p>
|
[
{
"answer_id": 74478293,
"author": "amirhm",
"author_id": 4529589,
"author_profile": "https://Stackoverflow.com/users/4529589",
"pm_score": 1,
"selected": false,
"text": "with open(\"in.txt\", \"r\") as fin:\n with open(\"out.txt\", \"w\") as fout:\n for line in fin:\n last_col = line.split()[-1]\n fout.write(f\"{line.strip()} {'twenty_number' if '20' in last_col else 'none'}\" )\n"
},
{
"answer_id": 74478346,
"author": "Chandler Bong",
"author_id": 19576917,
"author_profile": "https://Stackoverflow.com/users/19576917",
"pm_score": 3,
"selected": true,
"text": "endswith"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20273554/"
] |
74,478,195
|
<p>I have a List that consists of a boolean and an int. I want to dynamically change the background color between black and white of a TextView for a certain time of (int) numbers. I have treid this approach so far, however, when running the UI sleeps and the textView will only be updated once at the end.</p>
<pre><code> List<Primitive> codeContainer;
codeContainer.add(new Primitive(3, true));
codeContainer.add(new Primitive(1, false));
codeContainer.add(new Primitive(7, true));
theBlinker = findViewById(R.id.theBlinker);
theBlinker.setBackgroundColor(ContextCompat.getColor(this, R.color.black));
submit = findViewById(R.id.submit);
submit.setOnClickListener(view -> {
for (Primitive item : codeContainer) {
blinking(item.getSignalLengthInDits() * 500);
}
theBlinker.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.black));
});
}
private void blinking(int time) {
final Handler handler = new Handler();
new Thread(() -> handler.post(() -> {
theBlinker = findViewById(R.id.theBlinker);
ColorDrawable buttonColor = (ColorDrawable) txt.getBackground();
if (buttonColor.getColor() == Color.BLACK) {
txt.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.white));
} else {
txt.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.black));
}
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
})).start();
}
</code></pre>
<p>Any Ideas?</p>
|
[
{
"answer_id": 74483886,
"author": "Aorlinn",
"author_id": 5369727,
"author_profile": "https://Stackoverflow.com/users/5369727",
"pm_score": 0,
"selected": false,
"text": "Thread.Sleep"
},
{
"answer_id": 74494326,
"author": "Prem Thakur",
"author_id": 15707830,
"author_profile": "https://Stackoverflow.com/users/15707830",
"pm_score": 2,
"selected": true,
"text": " //define executors and handlers\n static Executor mExecutor = Executors.newSingleThreadExecutor();\n final static Handler handler = new Handler(Looper.getMainLooper());\n\n List<Primitive> codeContainer;\n codeContainer.add(new Primitive(3, true));\n codeContainer.add(new Primitive(1, false));\n codeContainer.add(new Primitive(7, true));\n theBlinker = findViewById(R.id.theBlinker);\n theBlinker.setBackgroundColor(ContextCompat.getColor(this, R.color.black));\n submit = findViewById(R.id.submit);\n\n submit.setOnClickListener(v ->{\n //execute the task\n mExecutor.execute(() ->{\n for (Primitive item : codeContainer) {\n blinking();\n\n //after changing color sleeps the thread\n try {\n Thread.sleep(item.getSignalLengthInDits() * 500);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n theBlinker.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.black));\n });\n });\n}\n private void blinking() {\n\n //change text view color on the main thread\n handler.post(() -> {\n theBlinker = findViewById(R.id.theBlinker);\n ColorDrawable buttonColor = (ColorDrawable) txt.getBackground();\n if (buttonColor.getColor() == Color.BLACK) {\n txt.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.white));\n } else {\n txt.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.black));\n }\n });\n }\n\n\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9090704/"
] |
74,478,208
|
<p>I get an error("myDiv is null"), when I try to use <code>document.getElementById</code> in Cypress. Can anybody give me a hint? This is my setup:</p>
<pre class="lang-js prettyprint-override"><code>
a.html
...
<div id='myid'>
</div>
...
test.cy.js
function foo()
{
let myDiv = document.getElementById('myid');
let myParagraphs = myDiv.getElementsByTagName('p');
...
}
it('MyTest', ()=> {
cy.visit('\fsdgjfs\a.html');
foo();
...
});
</code></pre>
<p>myDiv should be not null.</p>
|
[
{
"answer_id": 74483886,
"author": "Aorlinn",
"author_id": 5369727,
"author_profile": "https://Stackoverflow.com/users/5369727",
"pm_score": 0,
"selected": false,
"text": "Thread.Sleep"
},
{
"answer_id": 74494326,
"author": "Prem Thakur",
"author_id": 15707830,
"author_profile": "https://Stackoverflow.com/users/15707830",
"pm_score": 2,
"selected": true,
"text": " //define executors and handlers\n static Executor mExecutor = Executors.newSingleThreadExecutor();\n final static Handler handler = new Handler(Looper.getMainLooper());\n\n List<Primitive> codeContainer;\n codeContainer.add(new Primitive(3, true));\n codeContainer.add(new Primitive(1, false));\n codeContainer.add(new Primitive(7, true));\n theBlinker = findViewById(R.id.theBlinker);\n theBlinker.setBackgroundColor(ContextCompat.getColor(this, R.color.black));\n submit = findViewById(R.id.submit);\n\n submit.setOnClickListener(v ->{\n //execute the task\n mExecutor.execute(() ->{\n for (Primitive item : codeContainer) {\n blinking();\n\n //after changing color sleeps the thread\n try {\n Thread.sleep(item.getSignalLengthInDits() * 500);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n theBlinker.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.black));\n });\n });\n}\n private void blinking() {\n\n //change text view color on the main thread\n handler.post(() -> {\n theBlinker = findViewById(R.id.theBlinker);\n ColorDrawable buttonColor = (ColorDrawable) txt.getBackground();\n if (buttonColor.getColor() == Color.BLACK) {\n txt.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.white));\n } else {\n txt.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.black));\n }\n });\n }\n\n\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20111643/"
] |
74,478,231
|
<p>I have device with a common register bank that can be accessed through 3 different interfaces, one is the "regular" interface where the register and fields have the normal access restriction (e.g. rw or ro) per the specification, but the other two interfaces are privileged access interfaces where the access restrictions are lifted in different ways for different registers/fields.</p>
<p>How would I implement that in a convenient way in DML?</p>
<p>One could imagine implementing a register bank with no restrictions on register and fields, but how would I then apply the normal access restrictions on top of it for the regular interface?</p>
|
[
{
"answer_id": 74483886,
"author": "Aorlinn",
"author_id": 5369727,
"author_profile": "https://Stackoverflow.com/users/5369727",
"pm_score": 0,
"selected": false,
"text": "Thread.Sleep"
},
{
"answer_id": 74494326,
"author": "Prem Thakur",
"author_id": 15707830,
"author_profile": "https://Stackoverflow.com/users/15707830",
"pm_score": 2,
"selected": true,
"text": " //define executors and handlers\n static Executor mExecutor = Executors.newSingleThreadExecutor();\n final static Handler handler = new Handler(Looper.getMainLooper());\n\n List<Primitive> codeContainer;\n codeContainer.add(new Primitive(3, true));\n codeContainer.add(new Primitive(1, false));\n codeContainer.add(new Primitive(7, true));\n theBlinker = findViewById(R.id.theBlinker);\n theBlinker.setBackgroundColor(ContextCompat.getColor(this, R.color.black));\n submit = findViewById(R.id.submit);\n\n submit.setOnClickListener(v ->{\n //execute the task\n mExecutor.execute(() ->{\n for (Primitive item : codeContainer) {\n blinking();\n\n //after changing color sleeps the thread\n try {\n Thread.sleep(item.getSignalLengthInDits() * 500);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n theBlinker.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.black));\n });\n });\n}\n private void blinking() {\n\n //change text view color on the main thread\n handler.post(() -> {\n theBlinker = findViewById(R.id.theBlinker);\n ColorDrawable buttonColor = (ColorDrawable) txt.getBackground();\n if (buttonColor.getColor() == Color.BLACK) {\n txt.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.white));\n } else {\n txt.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.black));\n }\n });\n }\n\n\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5876823/"
] |
74,478,232
|
<p>Well, I want to do this: <a href="https://grafana.com/docs/grafana/v9.0/basics/timeseries-dimensions/" rel="nofollow noreferrer">https://grafana.com/docs/grafana/v9.0/basics/timeseries-dimensions/</a>, but on Kusto.</p>
<p>The problem is that I don't know where I'm failing, the unique point is that I have the following warning:</p>
<blockquote>
<p>Detected long formatted time series but failed to convert from long
frame: long series must be sorted ascending by time to be converted.</p>
</blockquote>
<p>The point is that my query returns the following:</p>
<p><a href="https://i.stack.imgur.com/nQ0R5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nQ0R5.png" alt="..." /></a></p>
<pre><code>let test = datatable (Timestamp: datetime, Id: string, Value: dynamic)
[
datetime(2022-11-09 11:39:25), "machineA", "True",
datetime(2022-11-09 11:39:30), "machineA", "True",
datetime(2022-11-09 11:39:35), "machineA", "False",
datetime(2022-11-09 11:39:36), "machineA", "False",
datetime(2022-11-09 11:40:03), "machineA", "True",
datetime(2022-11-09 11:40:03), "machineA", "True",
datetime(2022-11-09 11:40:04), "machineA", "True",
datetime(2022-11-09 11:40:05), "machineA", "True",
datetime(2022-11-09 11:40:25), "machineA", "False",
datetime(2022-11-09 11:40:25), "machineA", "False",
datetime(2022-11-09 11:40:26), "machineA", "False",
datetime(2022-11-09 11:40:27), "machineA", "False",
datetime(2022-11-09 11:40:37), "machineA", "True",
datetime(2022-11-09 11:40:47), "machineA", "False",
datetime(2022-11-09 11:40:57), "machineA", "True",
datetime(2022-11-09 11:40:59), "machineA", "True",
datetime(2022-11-09 11:40:25), "machineB", "True",
datetime(2022-11-09 11:40:30), "machineB", "True",
datetime(2022-11-09 11:40:35), "machineB", "False",
datetime(2022-11-09 11:40:36), "machineB", "False",
datetime(2022-11-09 11:41:03), "machineB", "True",
datetime(2022-11-09 11:41:03), "machineB", "True",
datetime(2022-11-09 11:41:04), "machineB", "True",
datetime(2022-11-09 11:41:05), "machineB", "True",
datetime(2022-11-09 11:41:25), "machineB", "False",
datetime(2022-11-09 11:41:25), "machineB", "False",
datetime(2022-11-09 11:41:26), "machineB", "False",
datetime(2022-11-09 11:41:27), "machineB", "False",
datetime(2022-11-09 11:41:37), "machineB", "True",
datetime(2022-11-09 11:41:47), "machineB", "False",
datetime(2022-11-09 11:41:57), "machineB", "True",
datetime(2022-11-09 11:41:59), "machineB", "True",
datetime(2022-11-09 11:42:25), "machineC", "True",
datetime(2022-11-09 11:42:30), "machineC", "True",
datetime(2022-11-09 11:42:35), "machineC", "False",
datetime(2022-11-09 11:42:36), "machineC", "False",
datetime(2022-11-09 11:43:03), "machineC", "True",
datetime(2022-11-09 11:43:03), "machineC", "True",
datetime(2022-11-09 11:43:04), "machineC", "True",
datetime(2022-11-09 11:43:05), "machineC", "True",
datetime(2022-11-09 11:43:25), "machineC", "False",
datetime(2022-11-09 11:43:25), "machineC", "False",
datetime(2022-11-09 11:43:26), "machineC", "False",
datetime(2022-11-09 11:43:27), "machineC", "False",
datetime(2022-11-09 11:43:37), "machineC", "True",
datetime(2022-11-09 11:43:47), "machineC", "False",
datetime(2022-11-09 11:43:57), "machineC", "False",
datetime(2022-11-09 11:43:59), "machineC", "False",
];
let tiemposCicloBruto = test
| where Timestamp > ago(100d)
| partition hint.strategy=native by Id
(
order by Timestamp asc // ordenamos ascendentemente
| extend prev_Timestamp = prev(Timestamp) // extendemos la fecha previa
| extend prev_Value = prev(Value) // extendemos el valor previo
| extend duration =
iif( // Condicion ternaria
prev_Value == "True" and Value == "False" // Si anteriormente estaba en funcion y el valor actual es parado, cuenta como tiempo de ciclo
or prev_Value == "True" and Value == "True", // Si el valor anterior era funcionando y el actual tambien, la maquina sigue funcionando
Timestamp - prev_Timestamp, // Para ese caso restamos la diferencia de tiempo
time(null) // Para el caso contrario, devolvemos nulo
)
| project Id, Timestamp, duration, Value, prev_Value
);
tiemposCicloBruto // La consulta para 1d completo tarda entre 1-1.5s
| where isnotnull(duration)
| partition hint.strategy=native by Id ( // partimos por Id
order by Timestamp asc // debe ser siempre ascendente si no pierde la logica
| scan declare (y:timespan=time(null), x:timespan=time(null)) with ( // declaramos el scan
step s1: true => // declaramos el paso
x=iif(s1.Value == "True" and Value == "True", iif(isnull(s1.x), duration, s1.x)+s1.duration, time(null)), // si tenemos varios True-True consecutivos, sumamos la duracion anterior a la actual, asignandola a X
y=iif(s1.Value=="False" and Value=="False", duration, // si tenemos el caso de que es False-False, partimos de la duracion
iif(s1.Value=="True" and Value=="False", s1.x+duration, time(null))); // si tenemos que la maquina estaba funcionando y para, sumamos las duraciones consecutivas de mientras que estaba funcionando
)
| extend next_Id=next(Id)
| extend tiempoCiclo=iif(isempty(next_Id), duration, iif(isnull(y) and prev_Value == "True" and Value=="False", duration+prev(duration), iif(isnotnull(y), y, time(null)))) / 1s // y para aquellos cambios de maquina o para aquellos donde no hubiera valor por casuistica, asignamos la duracion o la duracion+duracion previa
| where isnotnull(tiempoCiclo) // filtramos
| project-away prev_Value, x, y, duration, Value, next_Id
)
</code></pre>
<p>But I cannot see those machine groupings on my KQL Grafana Time series graph:</p>
<p><a href="https://i.stack.imgur.com/rJLYx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rJLYx.png" alt="..." /></a></p>
<p>At least, it should show as much as machines in my environment:</p>
<p><a href="https://i.stack.imgur.com/LVAm6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LVAm6.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74483242,
"author": "ChrisWue",
"author_id": 220986,
"author_profile": "https://Stackoverflow.com/users/220986",
"pm_score": 1,
"selected": true,
"text": "pivot"
},
{
"answer_id": 74623668,
"author": "greatvovan",
"author_id": 947012,
"author_profile": "https://Stackoverflow.com/users/947012",
"pm_score": 1,
"selected": false,
"text": "...\n| order by Timestamp asc\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3286975/"
] |
74,478,247
|
<p>Sorry but I don't know what is happening when I try to run (python3 manage.py makemigrations).</p>
<p>I really don't know what's going on I'm looking for an answer for a while but I can't figure out where the error is:</p>
<pre><code>(paginas) root@janstar:/home/paginas/proyectodedjango# python3 manage.py makemigrations
Traceback (most recent call last):
File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/home/paginas/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle
loader.check_consistent_history(connection)
File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history
applied = recorder.applied_migrations()
File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations
if self.has_table():
File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table
return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 260, in cursor
return self._cursor()
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 236, in _cursor
self.ensure_connection()
File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection
self.connect()
File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect
self.connection = self.get_new_connection(conn_params)
File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 199, in get_new_connection
conn = Database.connect(**conn_params)
TypeError: argument 1 must be str, not PosixPath
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/paginas/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/paginas/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 341, in run_from_argv
connections.close_all()
File "/home/paginas/lib/python3.6/site-packages/django/db/utils.py", line 230, in close_all
connection.close()
File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 261, in close
if not self.is_in_memory_db():
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'PosixPath' is not iterable
</code></pre>
<p><a href="https://i.stack.imgur.com/hYoHx.png" rel="nofollow noreferrer">Try changing this:</a>
<a href="https://i.stack.imgur.com/lRfg2.png" rel="nofollow noreferrer">For this:</a></p>
<p>Sorry if I added the images wrong I'm new to this page.</p>
<p>This is my settings.py file:
"""</p>
<pre><code> from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-k3d35^_5m3-=t-7&-!4qq78o+h%-ra6atz-a9m1)19a7()$8u2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['31.220.48.123']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ckeditor',
'mainapp',
'pages.apps.PagesConfig',
'blog.apps.BlogConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ProyectoDjango.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'pages.context_processors.get_pages',
'blog.processor.get_categories',
],
},
},
]
WSGI_APPLICATION = 'ProyectoDjango.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
"""
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
"""
"""
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'proyectodjango',
'USER': 'root',
'PASSWORD': '12345',
'HOST': 'localhost',
'PORT': 3306
}
}
"""
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'es-es'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Media
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
</code></pre>
<p>"""</p>
<p>and this is my manage.py file:
<a href="https://i.stack.imgur.com/sgnFr.png" rel="nofollow noreferrer">enter image description here</a></p>
|
[
{
"answer_id": 74483242,
"author": "ChrisWue",
"author_id": 220986,
"author_profile": "https://Stackoverflow.com/users/220986",
"pm_score": 1,
"selected": true,
"text": "pivot"
},
{
"answer_id": 74623668,
"author": "greatvovan",
"author_id": 947012,
"author_profile": "https://Stackoverflow.com/users/947012",
"pm_score": 1,
"selected": false,
"text": "...\n| order by Timestamp asc\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19064485/"
] |
74,478,271
|
<p>I need to construct a majority voting (3/5) based on the (int64) elements in the various columns as new column (Voting)</p>
<pre><code> Column1 Column2 Column3 Column4 Column5
0 0 0 6 1 0
1 4 4 6 4 0
2 4 2 2 2 2
3 4 4 4 4 4
4 0 0 0 2 4
5 6 6 6 6 6
6 3 3 3 3 5
7 0 6 6 0 4
8 3 3 3 3 4
9 2 2 4 2 2
</code></pre>
<p>My expecting result is like:</p>
<pre><code> Column1 Column2 Column3 Column4 Column5 Voting
0 0 0 6 1 0 0
1 4 4 6 4 0 4
2 4 2 2 2 2 2
3 4 4 4 4 4 4
4 0 0 0 2 4 0
5 6 6 6 6 6 6
6 3 3 3 3 5 3
7 0 6 6 0 4 -1
8 3 3 3 3 4 3
9 2 2 4 3 3 -1
</code></pre>
<pre><code>
where -1 is printed when we have pair number of elements.
Thanks a lot.
</code></pre>
|
[
{
"answer_id": 74478443,
"author": "Scott Boston",
"author_id": 6361531,
"author_profile": "https://Stackoverflow.com/users/6361531",
"pm_score": 1,
"selected": false,
"text": "pd.Series.mode"
},
{
"answer_id": 74478516,
"author": "SomeDude",
"author_id": 1410303,
"author_profile": "https://Stackoverflow.com/users/1410303",
"pm_score": 0,
"selected": false,
"text": "DataFrame.mode"
},
{
"answer_id": 74478536,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 2,
"selected": true,
"text": "import numpy as np\ndf['Voting']=np.where(df.mode(axis=1)[1].notnull(),-1,df.mode(axis=1)[0])\nprint(df)\n'''\n Column1 Column2 Column3 Column4 Column5 Voting\n0 0 0 6 1 0 0.0\n1 4 4 6 4 0 4.0\n2 4 2 2 2 2 2.0\n3 4 4 4 4 4 4.0\n4 0 0 0 2 4 0.0\n5 6 6 6 6 6 6.0\n6 3 3 3 3 5 3.0\n7 0 6 6 0 4 -1.0\n8 3 3 3 3 4 3.0\n9 2 2 4 2 2 2.0\n'''\n\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8064373/"
] |
74,478,286
|
<p>In Snowflake, when I create a store proc like so</p>
<pre><code>create procedure stack_overflow_question(select_table varchar)
returns varchar
language sql
as
declare
select_statement varchar;
begin
select_statement := '
SELECT * FROM ' || :select_table || '
';
end;
</code></pre>
<p>Then, later when I use <code>select get_ddl('procedure', 'stack_overflow_question(varchar)');</code> function to make edits to the store proc, the result of this function call has extra single quotes.</p>
<p>Here is the result</p>
<pre><code>CREATE OR REPLACE PROCEDURE "STACK_OVERFLOW_QUESTION"("SELECT_TABLE" VARCHAR(16777216))
RETURNS VARCHAR(16777216)
LANGUAGE SQL
EXECUTE AS OWNER
AS 'declare
select_statement varchar;
begin
select_statement := ''
SELECT * FROM '' || :select_table || ''
'';
end';
</code></pre>
<p>Note the difference between the two! The extra single quotes. Also double quotes in the name of the store proc.</p>
<p>Is there something that I can do to prevent this from happening? I am using Snowsight - but don't think that this actually is the problem. Also, I am using snowflake as the language for store procs.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 74478443,
"author": "Scott Boston",
"author_id": 6361531,
"author_profile": "https://Stackoverflow.com/users/6361531",
"pm_score": 1,
"selected": false,
"text": "pd.Series.mode"
},
{
"answer_id": 74478516,
"author": "SomeDude",
"author_id": 1410303,
"author_profile": "https://Stackoverflow.com/users/1410303",
"pm_score": 0,
"selected": false,
"text": "DataFrame.mode"
},
{
"answer_id": 74478536,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 2,
"selected": true,
"text": "import numpy as np\ndf['Voting']=np.where(df.mode(axis=1)[1].notnull(),-1,df.mode(axis=1)[0])\nprint(df)\n'''\n Column1 Column2 Column3 Column4 Column5 Voting\n0 0 0 6 1 0 0.0\n1 4 4 6 4 0 4.0\n2 4 2 2 2 2 2.0\n3 4 4 4 4 4 4.0\n4 0 0 0 2 4 0.0\n5 6 6 6 6 6 6.0\n6 3 3 3 3 5 3.0\n7 0 6 6 0 4 -1.0\n8 3 3 3 3 4 3.0\n9 2 2 4 2 2 2.0\n'''\n\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11262704/"
] |
74,478,290
|
<p>I am trying to make a responsive navbar where part of the items become scrollable when the screen size is reduced. It is something like this:</p>
<p>Large screens:</p>
<pre><code>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ FIXED ITEM + EMPTY SPACE + SCROLLABLE ITEM + FIXED ITEM +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
</code></pre>
<p>Small screens:</p>
<pre><code>++++++++++++++++++++++++++++++++++++++++++
| FIXED ITEM | SCROLLABL... | FIXED ITEM |
+++++++++++++.<@@@@>--------.+++++++++++++
</code></pre>
<p>So far, I have managed to do everything (see <a href="https://jsfiddle.net/ybfw58s3/" rel="nofollow noreferrer">here</a>) except the scroll part. Any ideas?</p>
|
[
{
"answer_id": 74478430,
"author": "SaroGFX",
"author_id": 10546172,
"author_profile": "https://Stackoverflow.com/users/10546172",
"pm_score": 2,
"selected": true,
"text": "white-space: nowrap"
},
{
"answer_id": 74479687,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "body{ font-family: impact; }\n \n.header {\n background-color: blue;\n color: white;\n display: flex;\n flex: 1;\n justify-content: space-between;\n padding: 10px 30px;\n}\n\n.logo { \n \n font-size: 28px;\n display: flex;\n justify-content: center;\n align-items: center;\n}\n\n.button {\n width: 80px;\n display: flex;\n border-style: solid;\n border-color: cornflowerblue;\n border-width: 4px;\n border-radius: 8px;\n font-size: 18px;\n justify-content: center;\n align-items: center;\n text-decoration: none;\n color: white;\n}\n\n.button:hover{\n\n color: red;\n background-color: white;\n\n}\n\n.at-right{\n \n font-size: 18px;\n width: 380px;\n height:32px;\n background: rgb(0, 191, 255);\n margin: 10px;\n display: flex;\n flex-direction: column;\n cursor: pointer;\n overflow-x: hidden;\n overflow-y: scroll;\n white-space: nowrap;\n border-radius: 4px;\n\n}\n\n.scrollnav{ margin: 0 auto; }\n\n.right-side{ display: flex; }\n\n.at-right::-webkit-scrollbar { display: none; /* for Chrome, Safari, and Opera */}"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15159198/"
] |
74,478,312
|
<p>When would we ever need <code>with</code> in Kotlin if we can already use <code>apply</code>, <code>run</code>, <code>also</code> and <code>let</code>?</p>
<p>Can anyone give me a clear example?</p>
|
[
{
"answer_id": 74478430,
"author": "SaroGFX",
"author_id": 10546172,
"author_profile": "https://Stackoverflow.com/users/10546172",
"pm_score": 2,
"selected": true,
"text": "white-space: nowrap"
},
{
"answer_id": 74479687,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "body{ font-family: impact; }\n \n.header {\n background-color: blue;\n color: white;\n display: flex;\n flex: 1;\n justify-content: space-between;\n padding: 10px 30px;\n}\n\n.logo { \n \n font-size: 28px;\n display: flex;\n justify-content: center;\n align-items: center;\n}\n\n.button {\n width: 80px;\n display: flex;\n border-style: solid;\n border-color: cornflowerblue;\n border-width: 4px;\n border-radius: 8px;\n font-size: 18px;\n justify-content: center;\n align-items: center;\n text-decoration: none;\n color: white;\n}\n\n.button:hover{\n\n color: red;\n background-color: white;\n\n}\n\n.at-right{\n \n font-size: 18px;\n width: 380px;\n height:32px;\n background: rgb(0, 191, 255);\n margin: 10px;\n display: flex;\n flex-direction: column;\n cursor: pointer;\n overflow-x: hidden;\n overflow-y: scroll;\n white-space: nowrap;\n border-radius: 4px;\n\n}\n\n.scrollnav{ margin: 0 auto; }\n\n.right-side{ display: flex; }\n\n.at-right::-webkit-scrollbar { display: none; /* for Chrome, Safari, and Opera */}"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531364/"
] |
74,478,321
|
<p>i have a array and i want to select the last index
how can I select it
check the picture of problem: [https://xip.li/z3cePZ]
I am new at PHP I do not know what to do</p>
|
[
{
"answer_id": 74478429,
"author": "Momen Shaker",
"author_id": 8894315,
"author_profile": "https://Stackoverflow.com/users/8894315",
"pm_score": 1,
"selected": true,
"text": "<?php\n $arr = array('Ram', 'Shita', 'Geeta');\n echo end($arr);\n?>\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531560/"
] |
74,478,325
|
<p>I would like to use this dataframe</p>
<pre><code>df = pd.DataFrame({'Serial' : ['A1', 'A1', 'A1', 'B1','B1', 'B1'],'Day' : ['01.01.2022', '01.01.2022', '01.01.2021', '01.01.2019', '01.01.2019', '01.01.2020'],'Else' : ['a', 'b', 'c', 'd','e', 'f']})
</code></pre>
<p>to groupby Serial and keep only rows with max(Day), ie here is my expected output:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Serial</th>
<th>Day</th>
<th>Else</th>
</tr>
</thead>
<tbody>
<tr>
<td>A1</td>
<td>01.01.2022</td>
<td>a</td>
</tr>
<tr>
<td>A1</td>
<td>01.01.2022</td>
<td>b</td>
</tr>
<tr>
<td>B1</td>
<td>01.01.2020</td>
<td>f</td>
</tr>
</tbody>
</table>
</div>
<p>I success to compute the max but don't know how to use it to filter in order to get the expected output.</p>
<pre><code>df['Day']= pd.to_datetime(df['Day'], format="%d.%m.%Y")
df = df.groupby(['Serial'])['Day'].max()
</code></pre>
|
[
{
"answer_id": 74478531,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 1,
"selected": false,
"text": "# convert the date to the YMD format for finding max\ndf['Day2']=pd.to_datetime(df['Day'], dayfirst=True)\n\n\n# group on Serial, and return the max value against all rows of grouped result\n# compare and filter where max date matches the date in DF\n\nout=df.loc[df['Day2'].eq(df.groupby('Serial')['Day2'].transform(max))].drop(columns='Day2')\n\nout\n"
},
{
"answer_id": 74478733,
"author": "Luke B",
"author_id": 8228122,
"author_profile": "https://Stackoverflow.com/users/8228122",
"pm_score": 1,
"selected": true,
"text": "df = pd.DataFrame({'Serial' : ['A1', 'A1', 'A1', 'B1','B1', 'B1'],'Day' : ['01.01.2022', '01.01.2022', '01.01.2021', '01.01.2019', '01.01.2019', '01.01.2020'],'Else' : ['a', 'b', 'c', 'd','e', 'f']})\ndf['Day'] = pd.to_datetime(df['Day'], format=\"%d.%m.%Y\")\nidx = df.groupby(['Serial'])['Day'].transform(max) == df['Day']\nprint(df[idx])\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20184381/"
] |
74,478,332
|
<p>I am working on SimpleDatFormat on android.
I tried to convert time from US locale to Swedish. It is working fine in emulator but when I tested it on Samsung devices it is not working. On rest of the devices and versions it is working fine.</p>
<pre><code>SimpleDateFormat inputFormat = new SimpleDateFormat("hh:mm a", Locale.US);
SimpleDateFormat outputFormat = new SimpleDateFormat("hh:mm a", new Locale("sv"));
try {
return outputFormat.format(inputFormat.parse(date));
} catch (ParseException e) {e.printStackTrace();}
return null;
</code></pre>
<p><strong>Actual Result</strong></p>
<p>Example input :- 06:45 AM</p>
<p>O/p in emulator :- 06:45 FM</p>
<p>O/p in real device :- 06:45 AM</p>
<p><strong>Expected Result</strong></p>
<p>Example input :- 06:45 AM</p>
<p>O/p in emulator :- 06:45 FM</p>
<p>O/p in real device :- 06:45 FM</p>
<p>Note : This issue only happens for Time locale conversion. The date conversion works fine in both real and emulator devices.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 74481569,
"author": "Arvind Kumar Avinash",
"author_id": 10819573,
"author_profile": "https://Stackoverflow.com/users/10819573",
"pm_score": 2,
"selected": false,
"text": "SimpleDateFormat"
},
{
"answer_id": 74483379,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 1,
"selected": false,
"text": "localTime\n.format(\n DateTimeFormatter\n .ofLocalizedTime( FormatStyle.SHORT )\n .withLocale( new Locale( \"sv\" , \"SE\" ) ) // Swedish language, Sweden culture.\n)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10744522/"
] |
74,478,358
|
<p>I'm using a <code>ComboBox</code> to display a list of many items (don't worry, the differences between the items allow a quick selection by <code>AutoComplete</code> :-).</p>
<p>This list is created during the creation of the form (<code>OnCreate</code> event), but so that the form does not freeze while filling, I added a <code>TThread</code> that performs the filling to <code>TStringList</code> and then assigns it to <code>ComboBox.Items</code>.</p>
<p>It works, but when the form is displayed it is not drawn properly until the thread has finished and the content in the Combo is already displayed. Shouldn't using thread save this?</p>
<p>Here is my code:
(it is not currently written in an IDE, so there may be typos...)</p>
<pre class="lang-pascal prettyprint-override"><code>type
TLoadList = class(TThread)
public
constructor Create;
destructor Destroy; override;
private
SL: TStrings;
procedure UpdateCombo;
procedure Execute; override;
end;
implementation
uses uMain, HebNumFunc; //The main form unit
constructor TLoadList.Create;
begin
FreeOnTerminate := True;
SL := TStringList.Create;
inherited Create(True);
end;
procedure TLoadList.UpdateCombo;
begin
MainFrm.YListCombo.Items := SL;
end;
procedure TLoadList.Execute;
begin
for var I: Integer := 1 to 6000 do SL.Add(HebNumber(I)); //HebNumber This is a function that converts the value of the number to a Hebrew alphabetic value
Synchronize(UpdateCombo);
end;
destructor TLoadList.Destroy;
begin
SL.Free;
inherited;
end;
</code></pre>
<p>The HebNumber function is declared in the HebNumFunc unit in this way:</p>
<pre class="lang-pascal prettyprint-override"><code>function HebNumber(const Number: Integer): string;
const
Letters1: Array of String = ['','א','ב','ג','ד','ה','ו','ז','ח','ט'];
Letters10: Array of String = ['','י','כ','ל','מ','נ','ס','ע','פ','צ'];
Letters100: Array of String = ['','ק','ר','ש','ת','תק','תר','תש','תת','תתק'];
function _ThousandsConv(const Value: Integer): string;
var
Input, Hundreds, Tens, Some: Integer;
begin
if Value <= 0 then Exit('');
if Value = 1 then Exit(Format('%s'' ', [Letters1[Value]]));
if Value in [2..9] then Exit(Format('%s"א ', [Letters1[Value]]));
if Value >= 10 then
begin
Input := Value;
Hundreds := Input div 100;
Input := Input mod 100;
Tens := Input div 10;
Some := Input mod 10;
Result := Format('%s%s%s"א ', [Letters100[Hundreds], Letters10[Tens], Letters1[Some]]);
end;
end;
var
Input, Thousands, Hundreds, Tens, Some: Integer;
begin
Input := Number;
Thousands := Input div 1000;
if Thousands > 999 then Exit('חריגה');
Input := Input mod 1000;
Hundreds := Input div 100;
Input := Input mod 100;
Tens := Input div 10;
Some := Input mod 10;
if (Thousands > 0) and (Hundreds + Tens + Some = 0) then
Exit(Format('%sתתר', [_ThousandsConv(Thousands - 1)]));
Result := Format('%s%s%s%s', [_ThousandsConv(Thousands),
Letters100[Hundreds], Letters10[Tens], Letters1[Some]]);
if Result.Contains('יה') then Exit(Result.Replace('יה', 'טו'));
if Result.Contains('יו') then Result := Result.Replace('יו', 'טז');
end;
</code></pre>
<p>I call it in the OnCreate event simply like this:</p>
<pre class="lang-pascal prettyprint-override"><code>var
LoadList: TLoadList;
begin
LoadList := TLoadList.Create;
LoadList.Start;
{...}
end;
</code></pre>
<p>There is nothing else in the <code>OnCreate</code> event that causes a delay in coloring the form, other than the call to create and run the Thread. There is also nothing extra an additional operation is performed in it.</p>
|
[
{
"answer_id": 74482178,
"author": "Dalija Prasnikar",
"author_id": 4267244,
"author_profile": "https://Stackoverflow.com/users/4267244",
"pm_score": 2,
"selected": true,
"text": "OnCreate"
},
{
"answer_id": 74506769,
"author": "yonni",
"author_id": 18279795,
"author_profile": "https://Stackoverflow.com/users/18279795",
"pm_score": 0,
"selected": false,
"text": "procedure TMyForm.FillYListCombo;\nvar\n SL: TStrings;\nbegin\n SL := TStringList.Create;\n try\n for var I: Integer := 1 to 6000 do\n SL.Add(HebNumber(I));\n\n //Waiting for the form to finish loading...\n WaitForInputIdle(GetCurrentProcess, 1000);\n\n TThread.Synchronize(nil,\n procedure\n begin\n YListCombo.Items.Assign(SL);\n end);\n finally\n SL.Free;\n end;\nend;\n\nprocedure TMyForm.FormCreate(Sender: TObject);\nbegin\n TThread.CreateAnonymousThread(FillYListCombo).Start;\n {...}\nend;\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18279795/"
] |
74,478,395
|
<p>I would like to make a 3D scatterplot with different shape symbols to represent different categories of data. In 2D, this is straightforward using the pch argument in the plot function, and I would like to extend it to the rgl plot3d function</p>
<p>However, as discussed in this thread,</p>
<p><a href="https://stackoverflow.com/questions/71288129/rgl-plot3d-with-extended-plotting-symbols">rgl: plot3d with "extended" plotting symbols</a></p>
<p>rgl::plot3d returns a single symbol regardless of pch argument, while pch3d doesn't embed the symbols in 3d axes. The best option suggested in the thread uses text3d and generates a 3D plot with no axes labels, e.g. for all_symbol a vector of n1 0's, n2 1's, n3 2's etc</p>
<pre><code>library(rgl)
rgl::open3d()
for(i in 1:49){
rgl::text3d(scores.df$PC1[i], scores.df$PC2[i], scores.df$PC3[i], text = intToUtf8(all_symbol[i]), cex = 2, usePlotmath = TRUE)
}
rgl::box3d()
</code></pre>
<p>generates no axes labels or tick marks.</p>
<p>Is there some graphics library that will give me the same basic 3d plotting functionality of rgl while allowing me to do the rather straightforward tasks such as using symbols for classes of data and labeling axes?</p>
|
[
{
"answer_id": 74482178,
"author": "Dalija Prasnikar",
"author_id": 4267244,
"author_profile": "https://Stackoverflow.com/users/4267244",
"pm_score": 2,
"selected": true,
"text": "OnCreate"
},
{
"answer_id": 74506769,
"author": "yonni",
"author_id": 18279795,
"author_profile": "https://Stackoverflow.com/users/18279795",
"pm_score": 0,
"selected": false,
"text": "procedure TMyForm.FillYListCombo;\nvar\n SL: TStrings;\nbegin\n SL := TStringList.Create;\n try\n for var I: Integer := 1 to 6000 do\n SL.Add(HebNumber(I));\n\n //Waiting for the form to finish loading...\n WaitForInputIdle(GetCurrentProcess, 1000);\n\n TThread.Synchronize(nil,\n procedure\n begin\n YListCombo.Items.Assign(SL);\n end);\n finally\n SL.Free;\n end;\nend;\n\nprocedure TMyForm.FormCreate(Sender: TObject);\nbegin\n TThread.CreateAnonymousThread(FillYListCombo).Start;\n {...}\nend;\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5904690/"
] |
74,478,413
|
<p>I have two temporary tables</p>
<pre><code>#tempA
colum1 | colum2 | colum3
-------------+------------+----------+
0001 | NULL |05/10/2022|
0002 | NULL |06/10/2022|
0003 | NULL |07/10/2022|
</code></pre>
<p>#tempB</p>
<pre><code>#tempB
dato1 | dato2 |
-------------+------------+
| |
| |
| |
</code></pre>
<p>I want to insert the values on colum1 and colum3 from #tempA into to #tempB(dato1,dato2)</p>
|
[
{
"answer_id": 74482178,
"author": "Dalija Prasnikar",
"author_id": 4267244,
"author_profile": "https://Stackoverflow.com/users/4267244",
"pm_score": 2,
"selected": true,
"text": "OnCreate"
},
{
"answer_id": 74506769,
"author": "yonni",
"author_id": 18279795,
"author_profile": "https://Stackoverflow.com/users/18279795",
"pm_score": 0,
"selected": false,
"text": "procedure TMyForm.FillYListCombo;\nvar\n SL: TStrings;\nbegin\n SL := TStringList.Create;\n try\n for var I: Integer := 1 to 6000 do\n SL.Add(HebNumber(I));\n\n //Waiting for the form to finish loading...\n WaitForInputIdle(GetCurrentProcess, 1000);\n\n TThread.Synchronize(nil,\n procedure\n begin\n YListCombo.Items.Assign(SL);\n end);\n finally\n SL.Free;\n end;\nend;\n\nprocedure TMyForm.FormCreate(Sender: TObject);\nbegin\n TThread.CreateAnonymousThread(FillYListCombo).Start;\n {...}\nend;\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18293753/"
] |
74,478,439
|
<p>I would like to do a regular expression that does not allow more than 1
consecutive spaces.</p>
<p>For example:</p>
<ul>
<li><code>A Bb 7</code> is valid</li>
<li><code>AA O</code> is not valid</li>
<li><code>00 55 </code> is valid</li>
<li><code>A b </code> is not valid</li>
</ul>
|
[
{
"answer_id": 74482178,
"author": "Dalija Prasnikar",
"author_id": 4267244,
"author_profile": "https://Stackoverflow.com/users/4267244",
"pm_score": 2,
"selected": true,
"text": "OnCreate"
},
{
"answer_id": 74506769,
"author": "yonni",
"author_id": 18279795,
"author_profile": "https://Stackoverflow.com/users/18279795",
"pm_score": 0,
"selected": false,
"text": "procedure TMyForm.FillYListCombo;\nvar\n SL: TStrings;\nbegin\n SL := TStringList.Create;\n try\n for var I: Integer := 1 to 6000 do\n SL.Add(HebNumber(I));\n\n //Waiting for the form to finish loading...\n WaitForInputIdle(GetCurrentProcess, 1000);\n\n TThread.Synchronize(nil,\n procedure\n begin\n YListCombo.Items.Assign(SL);\n end);\n finally\n SL.Free;\n end;\nend;\n\nprocedure TMyForm.FormCreate(Sender: TObject);\nbegin\n TThread.CreateAnonymousThread(FillYListCombo).Start;\n {...}\nend;\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571531/"
] |
74,478,453
|
<p>The problem:
I want to search keywords on Amazon and take screenshots. I am using selenium package. However, when I search on amazon.co.uk, it shows delivery address as Unites States. How can I change the "Deliver to Country"?</p>
<p>Below are sample Python code and a sample screenshot.</p>
<pre><code>import time as t
from datetime import datetime
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
chrome_options = Options()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument('disable-notifications')
chrome_options.add_argument("user-agent=UA")
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--headless")
chrome_options.add_argument('window-size=2160x3840')
urls = ['https://www.amazon.co.uk/s?k=advil', 'https://www.amazon.co.uk/s?k=Whitening toothpaste']
def get_secondly_screenshots(navi_dictionary):
driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
driver.get('https://www.amazon.co.uk')
driver.execute_script("document.body.style.zoom='50%'")
driver.get(url)
try:
test = driver.find_element('xpath', '//*[@id="sp-cc-rejectall-link"]')
test.click()
print('gotcha!')
except:
pass
now = datetime.now()
date_time = now.strftime("%Y_%m_%d_%H_%M_%S")
sh_url = url.split('?k=')[1]
print(sh_url, date_time)
driver.save_screenshot(f'{sh_url}_{date_time}.png')
print('screenshotted ', url)
t.sleep(2)
driver.quit()
for url in urls:
get_secondly_screenshots(url)
</code></pre>
<p><a href="https://i.stack.imgur.com/gcR3B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gcR3B.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74482178,
"author": "Dalija Prasnikar",
"author_id": 4267244,
"author_profile": "https://Stackoverflow.com/users/4267244",
"pm_score": 2,
"selected": true,
"text": "OnCreate"
},
{
"answer_id": 74506769,
"author": "yonni",
"author_id": 18279795,
"author_profile": "https://Stackoverflow.com/users/18279795",
"pm_score": 0,
"selected": false,
"text": "procedure TMyForm.FillYListCombo;\nvar\n SL: TStrings;\nbegin\n SL := TStringList.Create;\n try\n for var I: Integer := 1 to 6000 do\n SL.Add(HebNumber(I));\n\n //Waiting for the form to finish loading...\n WaitForInputIdle(GetCurrentProcess, 1000);\n\n TThread.Synchronize(nil,\n procedure\n begin\n YListCombo.Items.Assign(SL);\n end);\n finally\n SL.Free;\n end;\nend;\n\nprocedure TMyForm.FormCreate(Sender: TObject);\nbegin\n TThread.CreateAnonymousThread(FillYListCombo).Start;\n {...}\nend;\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4794400/"
] |
74,478,456
|
<p>I have a graph in Excel that I'd like to replicate in R if it's even possible. I am new to R, so any guidance will be appreciated.
So my data looks like this</p>
<p><a href="https://i.stack.imgur.com/48kHh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/48kHh.png" alt="Excel data" /></a></p>
<p>I can include the file if anyone wants it.</p>
<p>Then I have this graph:
<a href="https://i.stack.imgur.com/pVrEE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pVrEE.png" alt="Graph Image" /></a></p>
<p>I'd like to plot the same graph as in the Excel file but using R. So, is there a way to have a kind of subset for the x-axis values that belong to the main value?</p>
<p>I looked through the ggplot documentation and <a href="https://stackoverflow.com/questions/70858250/how-to-plot-side-by-side-with-sub-labels-and-without-space-between-subplots">How to plot side-by-side with sub labels and without space between subplots</a>, but to no avail.</p>
|
[
{
"answer_id": 74478653,
"author": "jrcalabrese",
"author_id": 14992857,
"author_profile": "https://Stackoverflow.com/users/14992857",
"pm_score": 2,
"selected": false,
"text": "geom_bar(position = \"dodge\")"
},
{
"answer_id": 74478771,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": true,
"text": "library(tidyr)\nlibrary(ggplot2)\n\n df %>% \n pivot_longer(ACI:SB) %>% \n mutate(across(where(is.character), as.factor)) %>% \n ggplot(aes(x = R, y = value, fill=name))+\n geom_bar(stat=\"identity\", position = \"dodge\", width=0.75)+\n facet_wrap(~A, nrow=1, strip.position=\"bottom\") + \n theme(legend.position = \"bottom\") + \n labs(fill=\"\", y=\"\", x=\"\")\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13349539/"
] |
74,478,461
|
<p>With a DataFrame like,</p>
<pre class="lang-py prettyprint-override"><code>
import pandas as pd
import numpy as np
df = pd.DataFrame({
'id_1': [33,33,33,33,22,22,88,100],
'id_2': [64,64,64,64,12,12,77,100],
'col_1': [np.nan, 'dog', np.nan, 'kangaroo', np.nan, np.nan, np.nan, np.nan],
'col_2': ['bike', 'car', np.nan, np.nan, 'train', np.nan, 'horse', np.nan],
'col_3': [np.nan, np.nan, 'star', 'meteor', np.nan, 'rock', np.nan, np.nan]
})
"""
id_1 id_2 col_1 col_2 col_3
0 33 64 NaN bike NaN
1 33 64 dog car NaN
2 33 64 NaN NaN star
3 33 64 kangaroo NaN meteor
4 22 12 NaN train NaN
5 22 12 NaN NaN rock
6 88 77 NaN horse NaN
7 100 100 NaN NaN NaN
"""
</code></pre>
<p>How can it be transformed into a minimum amount of rows without aggregating or losing data like the following?</p>
<pre><code> id_1 id_2 col_1 col_2 col_3
0 33 64 dog bike star
1 33 64 kangaroo car meteor
3 22 12 NaN train rock
4 88 77 NaN horse NaN
5 100 100 NaN NaN NaN
</code></pre>
<p>Basically, for each group of <code>id_X</code> columns, the <code>col_X</code> columns' <code>NaN</code> values are replaced with other group values if applicable.</p>
|
[
{
"answer_id": 74478653,
"author": "jrcalabrese",
"author_id": 14992857,
"author_profile": "https://Stackoverflow.com/users/14992857",
"pm_score": 2,
"selected": false,
"text": "geom_bar(position = \"dodge\")"
},
{
"answer_id": 74478771,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": true,
"text": "library(tidyr)\nlibrary(ggplot2)\n\n df %>% \n pivot_longer(ACI:SB) %>% \n mutate(across(where(is.character), as.factor)) %>% \n ggplot(aes(x = R, y = value, fill=name))+\n geom_bar(stat=\"identity\", position = \"dodge\", width=0.75)+\n facet_wrap(~A, nrow=1, strip.position=\"bottom\") + \n theme(legend.position = \"bottom\") + \n labs(fill=\"\", y=\"\", x=\"\")\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9576988/"
] |
74,478,463
|
<p>I am developing deployment via DBX to Azure Databricks. In this regard I need a data job written in SQL to happen everyday. The job is located in the file <code>data.sql</code>. I know how to do it with a python file. Here I would do the following:</p>
<pre><code>build:
python: "pip"
environments:
default:
workflows:
- name: "workflow-name"
#schedule:
quartz_cron_expression: "0 0 9 * * ?" # every day at 9.00
timezone_id: "Europe"
format: MULTI_TASK #
job_clusters:
- job_cluster_key: "basic-job-cluster"
<<: *base-job-cluster
tasks:
- task_key: "task-name"
job_cluster_key: "basic-job-cluster"
spark_python_task:
python_file: "file://filename.py"
</code></pre>
<p>But how can I change it so I can run a SQL job instead? I imagine it is the last two lines of code (<code>spark_python_task:</code> and <code>python_file: "file://filename.py"</code>) which needs to be changed.</p>
|
[
{
"answer_id": 74488928,
"author": "renardeinside",
"author_id": 3659303,
"author_profile": "https://Stackoverflow.com/users/3659303",
"pm_score": 2,
"selected": true,
"text": "sql_task"
},
{
"answer_id": 74531024,
"author": "andKaae",
"author_id": 13219123,
"author_profile": "https://Stackoverflow.com/users/13219123",
"pm_score": 0,
"selected": false,
"text": "data.sql"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13219123/"
] |
74,478,521
|
<p>I have a column of strings, example below. Each string is a delimited combinations of texts. Each row has different number of texts. I want to create a single column with one text per row based on this column.</p>
<p>FROM:</p>
<pre><code>a;b
x;y;z
p;q;r;s;t
</code></pre>
<p>TO:</p>
<pre><code>a
b
x
y
z
p
q
r
s
t
</code></pre>
<p><strong>How do I achieve this using a single formula?</strong></p>
<p>I tried <code>TRANSPOSE(TEXTSPLIT(TEXTJOIN(";",TRUE, data),";"))</code>
However, this fails because the TEXTJOIN part results in more than 32767 characters.</p>
<p>I also tried building a 2D array of mxn where m=no. of rows in the original data and n=no. of texts. However, the MAKEARRAY still results in a single column. Had it worked, I would have used TOCOL or something similar to convert to a single column.</p>
<pre><code>=MAKEARRAY(ROWS(data),COLUMNS(MAX(num_of_texts_in_each_row)), LAMBDA(r,c, LET(
drow, INDEX(data,r,1),
splits, TEXTSPLIT(drow,";"),
INDEX(splits,,c)
)))
</code></pre>
|
[
{
"answer_id": 74478661,
"author": "Scott Craner",
"author_id": 4851590,
"author_profile": "https://Stackoverflow.com/users/4851590",
"pm_score": 2,
"selected": false,
"text": "=LET(\n rng,A1:A3,\n clm,MAX(BYROW(rng,LAMBDA(a,COUNTA(TEXTSPLIT(a,\";\"))))),\n TOCOL(MAKEARRAY(ROWS(rng),clm,LAMBDA(a,b,INDEX(TEXTSPLIT(INDEX(A1:A3,a),\";\"),b))),3))\n"
},
{
"answer_id": 74480153,
"author": "P.b",
"author_id": 12634230,
"author_profile": "https://Stackoverflow.com/users/12634230",
"pm_score": 3,
"selected": true,
"text": "=DROP(REDUCE(0,A1:A3,LAMBDA(a,b,VSTACK(a,TEXTSPLIT(b,,\";\")))),1)"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2935885/"
] |
74,478,535
|
<p>To begin with, i have an event Map like this:</p>
<p><code> final Map<DateTime, List<CleanCalendarEvent>>? events;</code></p>
<p>It mapped all my event based on event Date. I want to select some events in certain range of date. I know how to select all the events in one selected date, and put it in a List.</p>
<pre><code>_selectedEventsList = widget.events?[DateTime(_selectedDate.year, _selectedDate.month, _selectedDate.day)] ??[];
</code></pre>
<p>I want to select the all events in a week. How to do this with just Map? Can i just specify it in []?</p>
|
[
{
"answer_id": 74478661,
"author": "Scott Craner",
"author_id": 4851590,
"author_profile": "https://Stackoverflow.com/users/4851590",
"pm_score": 2,
"selected": false,
"text": "=LET(\n rng,A1:A3,\n clm,MAX(BYROW(rng,LAMBDA(a,COUNTA(TEXTSPLIT(a,\";\"))))),\n TOCOL(MAKEARRAY(ROWS(rng),clm,LAMBDA(a,b,INDEX(TEXTSPLIT(INDEX(A1:A3,a),\";\"),b))),3))\n"
},
{
"answer_id": 74480153,
"author": "P.b",
"author_id": 12634230,
"author_profile": "https://Stackoverflow.com/users/12634230",
"pm_score": 3,
"selected": true,
"text": "=DROP(REDUCE(0,A1:A3,LAMBDA(a,b,VSTACK(a,TEXTSPLIT(b,,\";\")))),1)"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15991847/"
] |
74,478,537
|
<p>I need to add device names and device IP addresses to the bottom of a text file each time a new device goes live so I can connect via name instead of IP.</p>
<p>My problem is how to check the device I'm adding doesn't already exist, if it does exist then the logic should be to ignore, otherwise it should be added to the bottom of the specified file.</p>
<p>I have managed to add the required text to the file but on running the code for a second time the text is added again rather than ignoring.</p>
<p>Any text specified in lines that already exists in the file called Device_Names should not be added.</p>
<p>I've seen a lot of examples that look for specific key words in the existing text file which returns true/false parameters and/or prints to screen but this isn't sustainable long term. Can someone point me in the right direction on how to go about it? I've used and if/else functions but not getting very far.</p>
<p>I currently have:</p>
<pre><code>lines = [
'\n\device.1 A 10.10.10.10'
'\n\n'
'device.2 A 11.11.11.11'
'\n\n'
'device.3 A 12.12.12.12']
with open ("Device_Names", "a+") as f:
for line in lines:
f.write(line)
f.close()
</code></pre>
|
[
{
"answer_id": 74478661,
"author": "Scott Craner",
"author_id": 4851590,
"author_profile": "https://Stackoverflow.com/users/4851590",
"pm_score": 2,
"selected": false,
"text": "=LET(\n rng,A1:A3,\n clm,MAX(BYROW(rng,LAMBDA(a,COUNTA(TEXTSPLIT(a,\";\"))))),\n TOCOL(MAKEARRAY(ROWS(rng),clm,LAMBDA(a,b,INDEX(TEXTSPLIT(INDEX(A1:A3,a),\";\"),b))),3))\n"
},
{
"answer_id": 74480153,
"author": "P.b",
"author_id": 12634230,
"author_profile": "https://Stackoverflow.com/users/12634230",
"pm_score": 3,
"selected": true,
"text": "=DROP(REDUCE(0,A1:A3,LAMBDA(a,b,VSTACK(a,TEXTSPLIT(b,,\";\")))),1)"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531399/"
] |
74,478,550
|
<p>Is it possible to determine whether a commit (or md5hash value) is a "merge" from a developer branch to a parent branch? (i.e. master)</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 74478616,
"author": "Tsvetoslav Tsvetkov",
"author_id": 7357959,
"author_profile": "https://Stackoverflow.com/users/7357959",
"pm_score": 0,
"selected": false,
"text": "git log"
},
{
"answer_id": 74478660,
"author": "eftshift0",
"author_id": 2437508,
"author_profile": "https://Stackoverflow.com/users/2437508",
"pm_score": 2,
"selected": false,
"text": "git show --pretty=%ph --quiet some-brach-or-commit\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9531146/"
] |
74,478,572
|
<p>In many languages, a function call consists of a slug followed by any number of arguments surrounded by parentheses, like so:</p>
<pre><code>my_function(); // no arguments
my_function(one_argument);
my_function(first_argument,second_argument);
my_function(first_argument,second_argument,third_argument);
</code></pre>
<p>What regular expression will match exactly the case with two arguments (the <em>third</em> case in the pseudocode above)?</p>
<p>The "obvious answer" would be something like <code>\w+\([^)]+,[^)]+\)</code>. However, the special meaning of the parentheses breaks this expression.</p>
|
[
{
"answer_id": 74478611,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": true,
"text": "\\w+\\([^,)]+,[^,)]+\\);\n"
},
{
"answer_id": 74479507,
"author": "zer00ne",
"author_id": 2813224,
"author_profile": "https://Stackoverflow.com/users/2813224",
"pm_score": 0,
"selected": false,
"text": "/\\w+\\([a-zA-Z_$][\\w$]*, ?[a-zA-Z_$][\\w$]*\\);/g\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1905056/"
] |
74,478,576
|
<pre><code>from typing import NamedTuple, List, Set, Tuple, Dict
class EmbeddingInfoStruct(NamedTuple):
emb_names : list[str] =[]
idx_in_data: list[int] =[]
emb_dim: list[int] =[]
info1 =EmbeddingInfoStruct()
info1.emb_names.append("name1")
info2=EmbeddingInfoStruct()
print("info1 address = ", id(info1), ", info2 address = " ,id(info2))
print (info1)
print (info2)
</code></pre>
<p>output of print :</p>
<pre><code>info1 address = 2547212397920 , info2 address = 2547211152576
EmbeddingInfoStruct(emb_names=['name1'], idx_in_data=[], emb_dim=[])
EmbeddingInfoStruct(emb_names=['name1'], idx_in_data=[], emb_dim=[])
</code></pre>
<p>Surprisingly info1 and info2 both share the same value. I'd expect info2.emb_names to be empty. Why does NamedTuple behaves like it's a "static class"?</p>
|
[
{
"answer_id": 74478611,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": true,
"text": "\\w+\\([^,)]+,[^,)]+\\);\n"
},
{
"answer_id": 74479507,
"author": "zer00ne",
"author_id": 2813224,
"author_profile": "https://Stackoverflow.com/users/2813224",
"pm_score": 0,
"selected": false,
"text": "/\\w+\\([a-zA-Z_$][\\w$]*, ?[a-zA-Z_$][\\w$]*\\);/g\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1281766/"
] |
74,478,685
|
<p>I have a 404 page on my website, but on a nested page (for example test1/test2) static files aren‘t working.</p>
<p>Below is an example for a page with only one part. The css file works normal.</p>
<pre><code>app.get("/:part1", (req, res) => {
res.render("404")
});
</code></pre>
<p>If I go to <em>domain</em>/test i will get a page with the static style.css:
<a href="https://i.stack.imgur.com/UrmLf.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/UrmLf.jpg</a></p>
<p>Below is an example for a page two parts. The css file doesn‘t load.</p>
<pre><code>app.get("/:part1/:part2", (req, res) => {
res.render("404")
});
</code></pre>
<p>Now if I go to <em>domain</em>/test1/test2 I will still get the message, but not the css:
<a href="https://i.stack.imgur.com/70SHn.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/70SHn.jpg</a></p>
|
[
{
"answer_id": 74478611,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": true,
"text": "\\w+\\([^,)]+,[^,)]+\\);\n"
},
{
"answer_id": 74479507,
"author": "zer00ne",
"author_id": 2813224,
"author_profile": "https://Stackoverflow.com/users/2813224",
"pm_score": 0,
"selected": false,
"text": "/\\w+\\([a-zA-Z_$][\\w$]*, ?[a-zA-Z_$][\\w$]*\\);/g\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531413/"
] |
74,478,703
|
<p>If I have the following select:</p>
<pre><code><select id="multi_select" multiple>
<option id="1" value="one">One</option>
<option id="2" value="two">Two</option>
<option id="3" value="three">Three</option>
<option id="4" value="four">Four</option>
<option id="5" value="five">Five</option>
</select>
</code></pre>
<p>How can I get the id of the clicked option element?</p>
<p>If I use this:</p>
<pre><code>$("#multi_select").on('change', function () {
let id = this.options[this.selectedIndex].id;
});
</code></pre>
<p>It doesn't work, because it returns the top most <code>id</code>.</p>
<p>In my example, if I click option One and then I shift-click option Two (select multiple), the <code>id</code> would be <code>1</code> because it's the top most selected option, but I need only the <code>id</code> of the option that was clicked on</p>
<hr />
<p><strong>Edit</strong> Added snippet</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>$("#multi_select").on('change', function() {
let id = this.options[this.selectedIndex].id;
console.log(id);
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="multi_select" multiple>
<option id="1" value="one">One</option>
<option id="2" value="two">Two</option>
<option id="3" value="three">Three</option>
<option id="4" value="four">Four</option>
<option id="5" value="five">Five</option>
</select></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74478820,
"author": "epascarello",
"author_id": 14104,
"author_profile": "https://Stackoverflow.com/users/14104",
"pm_score": 3,
"selected": true,
"text": "document.querySelector(\"#multi_select\").addEventListener(\"change\", (evt) => {\n const selectedIds = [...evt.target.querySelectorAll('option:checked')].map(({\n id\n }) => id);\n console.log(selectedIds);\n});\n\n\n/*\ndocument.querySelector(\"#multi_select\").addEventListener(\"change\", function(evt) {\n const selectedIds = Array.from(evt.target.querySelectorAll('option:checked')).map(function(opt) {\n return opt.id\n });\n console.log(selectedIds);\n});\n*/"
},
{
"answer_id": 74478824,
"author": "CodeCrusher300_",
"author_id": 19635354,
"author_profile": "https://Stackoverflow.com/users/19635354",
"pm_score": 0,
"selected": false,
"text": "$(\"#multi_select\").change(function() {\n var id = $(this).children(\":selected\").attr(\"id\");\n});\n"
},
{
"answer_id": 74478973,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 0,
"selected": false,
"text": "let selectedOpt = [];\n function check(ev) {\n for (let item of ev.target.options) {\n if (item.selected) {\n selectedOpt.push(item);\n }\n }\n\n // here we got finally selected options\n console.log(selectedOpt);\n\n //here array iteration can be done\n for (let opt of selectedOpt) {\n console.log(opt.id, opt.value);\n }\n }"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18178584/"
] |
74,478,758
|
<p>For example, I have a string <code>section 213(d)-456(c)</code></p>
<p>How can I split it to get a list of strings:</p>
<p><code>['section', '213', '(', 'd', ')', '-', '456', '(', 'c', ')']</code>.</p>
<p>Thank you!</p>
|
[
{
"answer_id": 74478858,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 0,
"selected": false,
"text": "re.split(r'([-\\s()])', 'section 213(d)-456(c)')\n"
},
{
"answer_id": 74478876,
"author": "Punit Choudhary",
"author_id": 13527252,
"author_profile": "https://Stackoverflow.com/users/13527252",
"pm_score": 3,
"selected": true,
"text": "import re\ntext = \"section 213(d)-456(c)\"\noutput = re.split(\"(\\W)\", text)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12787553/"
] |
74,478,807
|
<p>I am trying to train a multi-class classifier using XGBoost. Data contains 4 independent variables which are ordinal in nature. I want to use these variables as is because they are encoded. The data looks like below</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column name</th>
<th>Values</th>
</tr>
</thead>
<tbody>
<tr>
<td>target</td>
<td>['high', 'medium', 'low']</td>
</tr>
<tr>
<td>feature_1</td>
<td>Values ranging from 1-5</td>
</tr>
<tr>
<td>feature_2</td>
<td>Values ranging from 1-5</td>
</tr>
<tr>
<td>feature_3</td>
<td>Values ranging from 1-5</td>
</tr>
<tr>
<td>feature_4</td>
<td>Values ranging from 1-5</td>
</tr>
</tbody>
</table>
</div>
<p>My code currently look like below</p>
<pre><code>y = data['target']
X = data.drop(['target'], axis=1)
X = X.fillna(0)
X = X.astype('int').astype('category')
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state=random_state, stratify=y)
# Create instance of model
xgb_model = XGBClassifier()
# Create the random grid
xgb_grid = {'n_estimators': [int(x) for x in np.linspace(start = 100, stop = 500, num = 5)],
'max_depth': [3, 5, 8, 10],
'learning_rate': [0.01, 0.05, 0.1, 0.2, 0.3]}
xgb_model_tuned = RandomizedSearchCV(estimator = xgb_model, param_distributions = xgb_grid, n_iter = 50, cv = 5, scoring='roc_auc', verbose=2, random_state=random_state, n_jobs = -1)
# Pass training data into model
xgb_model_tuned.fit(x_train, y_train)
</code></pre>
<p>I get the following error when i run this</p>
<pre><code>ValueError: DataFrame.dtypes for data must be int, float, bool or categorical. When
categorical type is supplied, DMatrix parameter
`enable_categorical` must be set to `True`.feature_1, feature_2,
feature_3, feature_4
</code></pre>
<p>The dtype is <code>category</code> for all the variables. This worked well with RandomForest Classifier but not with XGBoost. If i cannot use the datatype <code>category</code> how can i pass the ordinal variables as categories?</p>
|
[
{
"answer_id": 74479935,
"author": "wavetitan",
"author_id": 19069334,
"author_profile": "https://Stackoverflow.com/users/19069334",
"pm_score": 0,
"selected": false,
"text": "enable_categorical=True"
},
{
"answer_id": 74482428,
"author": "Ben Reiniger",
"author_id": 10495893,
"author_profile": "https://Stackoverflow.com/users/10495893",
"pm_score": 2,
"selected": true,
"text": "int"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4257964/"
] |
74,478,827
|
<p>I am trying to build a dataframe of KML files. I have 52 different files in my dataset, and I have already uploaded them to R using the following code chunk:</p>
<pre><code>#importing data
library(fs)
file_paths = fs::dir_ls("C:/Users/JoaoArbache/Desktop/Mestrado/carbono/dados")
file_contents = list()
for(i in seq_along(file_paths)) {
file_contents[[i]] = st_read(
dsn = file_paths[[i]]
)
}
#renaming the lists
numeros = list()
for(i in file_paths) {
numeros[[i]] = str_extract(i, "\\d+") %>%
as.numeric()
}
id = do.call(rbind.data.frame, numeros) %>%
filter(!row_number() %in% c(53))
colnames(id)[1] = "id"
file_contents = set_names(file_contents, id$id)
</code></pre>
<p>Ok, so far everything is alright. I have all of the 52 files uploaded in the <code>file_contents</code> list.
<a href="https://i.stack.imgur.com/Gpy7r.png" rel="nofollow noreferrer">This is the file_contents list</a>
Now, I need to get each of the 52 lists in <code>file_contents</code>, that contain one dataframe each, and build a single dataframe. So it should bind 52 different dataframes into a single one. I`ve tried lots of different ways to solve this problem, but I always failed.</p>
<p>Thanks for the support :)</p>
<p>I tried different loops, <code>do.call</code> function, some native R functions, but none of them worked. I`d either get an error message (e.g.</p>
<pre><code>Error in `[[<-`(`*tmp*`, i, value = as.data.frame(i)) :
attempt to select more than one element in vectorIndex
</code></pre>
<p>) or just create a dataframe with the first element of the <code>file_contents</code> list. I was expecting to get a single dataframe with the 52 dataframes binded...</p>
|
[
{
"answer_id": 74479935,
"author": "wavetitan",
"author_id": 19069334,
"author_profile": "https://Stackoverflow.com/users/19069334",
"pm_score": 0,
"selected": false,
"text": "enable_categorical=True"
},
{
"answer_id": 74482428,
"author": "Ben Reiniger",
"author_id": 10495893,
"author_profile": "https://Stackoverflow.com/users/10495893",
"pm_score": 2,
"selected": true,
"text": "int"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9927885/"
] |
74,478,837
|
<pre><code>int f( int i ) {
printf("called f\n");
if (i < 0) return -i;
else
return 3 * i;
}
</code></pre>
<p>I just want to know what int "f" means.</p>
|
[
{
"answer_id": 74479935,
"author": "wavetitan",
"author_id": 19069334,
"author_profile": "https://Stackoverflow.com/users/19069334",
"pm_score": 0,
"selected": false,
"text": "enable_categorical=True"
},
{
"answer_id": 74482428,
"author": "Ben Reiniger",
"author_id": 10495893,
"author_profile": "https://Stackoverflow.com/users/10495893",
"pm_score": 2,
"selected": true,
"text": "int"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20442194/"
] |
74,478,872
|
<p>Suppose I have a ruby function (func) with named arguments (foo and bar) which I can call by providing either or both arguments like this:</p>
<pre><code>func(foo: "whatever")
func(bar: "whatever")
func(foo: "whatever", bar: "whatever")
</code></pre>
<p>What I need is a way to call this function by passing strings for the arguments' names:</p>
<pre><code>name = "foo"
func(name: "whatever")
</code></pre>
<p>I read about to_sym but don't know how to use it. At least this does not work:</p>
<pre><code>name = "foo"
func(name.to_sym: "whatever")
</code></pre>
<p>Is there a way?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 74479252,
"author": "steenslag",
"author_id": 290394,
"author_profile": "https://Stackoverflow.com/users/290394",
"pm_score": 3,
"selected": true,
"text": "func(name.to_sym => \"whatever\")\n"
},
{
"answer_id": 74479267,
"author": "Bedol",
"author_id": 4537366,
"author_profile": "https://Stackoverflow.com/users/4537366",
"pm_score": 1,
"selected": false,
"text": "func(\"#{name}\": \"whatever\")\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/805623/"
] |
74,478,875
|
<pre><code>SELECT tblSign.sigdate,tblSign.sigtime,tblSign.sigact,tblSign.esignature,tblEmpl.fname,tblEmpl.lname,tblEmpl.location, tblEmpl.estatus,tblLocs.unit,tblLocs.descript,TblLocs.addr1,tblLocs.city,tblLocs.state, tblLocs.zip
FROM tblEmpl
LEFT JOIN tblSign
ON tblSign.eight_id = tblEmpl.eight_id
AND tblSign.formid = '9648'
AND tblSign.sigact <> 'O'
AND tblSign.sigdate >= '2022-11-01'
LEFT JOIN tblLocs
ON tblEmpl.location = tblLocs.location
WHERE tblEmpl.estatus = 'A'
AND tblEmpl.location = '013'
ORDER BY
tblSign.sigdate ASC;
</code></pre>
<p>My table Sign has multiple records with the same eight_id so Im just trying to join tables getting the most recent record from tblSign besides multiple records</p>
<p>Data I get</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Sigdate</th>
<th>fname</th>
<th>lname</th>
<th>location</th>
<th>sigact</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-11-01</td>
<td>Bill</td>
<td>Lee</td>
<td>023</td>
<td>A</td>
</tr>
<tr>
<td>2022-10-01</td>
<td>Bill</td>
<td>Lee</td>
<td>023</td>
<td>A</td>
</tr>
<tr>
<td>2022-11-01</td>
<td>Carter</td>
<td>Hill</td>
<td>555</td>
<td>A</td>
</tr>
</tbody>
</table>
</div>
<p>This is what I want :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Sigdate</th>
<th>fname</th>
<th>lname</th>
<th>location</th>
<th>sigact</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-11-01</td>
<td>Bill</td>
<td>Lee</td>
<td>023</td>
<td>A</td>
</tr>
<tr>
<td>2022-11-01</td>
<td>Carter</td>
<td>Hill</td>
<td>555</td>
<td>A</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74479252,
"author": "steenslag",
"author_id": 290394,
"author_profile": "https://Stackoverflow.com/users/290394",
"pm_score": 3,
"selected": true,
"text": "func(name.to_sym => \"whatever\")\n"
},
{
"answer_id": 74479267,
"author": "Bedol",
"author_id": 4537366,
"author_profile": "https://Stackoverflow.com/users/4537366",
"pm_score": 1,
"selected": false,
"text": "func(\"#{name}\": \"whatever\")\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20151702/"
] |
74,478,881
|
<p>I've been working on the project. The main goal is to calculate how many words do not contain letters 'B' nor 'C'. Given file has [0;1000] lines. Every line contains 6 columns.</p>
<p>he first two columns contain string with [1; 20] characters. Characters could be letters, numbers, and whitespaces.</p>
<p>3-5 columns contain integers in the range [-100; 100]. 6th column contain real numbers in range [-9.99; 9.99] with only two digits after decimal point.</p>
<p>Each section I separated by a semicolon ';'.</p>
<p><strong>FILE EXAMPLE:</strong></p>
<pre><code>helloA;lB;lC;lD;lE;lF
A11;bas morning;0;0;5;1.15
B12; Hello WoRlD;-100;11;78;1.33
B11;table;10;0;55;-2.44
C1;OakWood;0;8;17;3.77
</code></pre>
<p><strong>TASK:</strong> calculate how many words (word is one or more symbols without ' '(space)) in the first two columns do not contain letters 'B' or 'C'. And print that integer number.</p>
<p>I have dealt with the most part of the task. I already did File's name reading from command line, reading the file, priting the integer out. But I have stuck on one thing. I don't really get it how to check every word one by one. I almost every time get a wrong answer.</p>
<pre><code>Input: ( a A a a aba aca;BA A C BA a;1;1;1;1.00) - without brackets.
Output: 6
</code></pre>
<p><strong>MY CODE SO FAR</strong></p>
<pre><code>org 100h
%include 'yasmmac.inc'
section .text
startas:
macPutString 'Write outpu file name', crlf, '$'
; Reading file from command line
.commandLine:
mov bx, 82h
mov si, 0h
jmp .checkInputFile
; Turns it into ASCIIZ
.checkInputFile:
mov cl, [bx+si]
cmp cl, 20h
jl .addZero
inc si
jmp .checkInputFile
.addZero:
mov byte [bx+si], 0h
xor si, si
; Saving writing file
mov al, 128
mov dx, writingFile
call procGetStr
macNewLine
; Open reading file
mov dx, bx
call procFOpenForReading
jnc .writingFileIsOpened
macPutString 'Error while opening reading file', '$'
exit
; Atidarome rasymo faila
.writingFileIsOpened:
mov [readingDescriptor], bx
mov dx, writingFile
call procFCreateOrTruncate
jnc .openWritingFile
macPutString 'Error while opening writing file', '$'
jmp .writingError
; Save writing descriptor
.openWritingFile:
mov [writingDescriptor], bx
; Reads first line
call procReadLine
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Main loop
.whileNotEndOfFile:
xor di, di
xor si, si
call procReadLine
; Check first two columns
;mov al, ';'
mov di, line
mov al, [di]
cmp al, ' '
je .nextWord
cmp al, ';'
je .nextWord
; Checking words
.checkWord:
mov al, [di]
inc di
cmp al, byte 'B'
je .nextWord
cmp al, byte 'b'
je .nextWord
cmp al, byte 'C'
je .nextWord
cmp al, byte 'c'
je .nextWord
cmp al, byte ' '
je .addNumber
cmp al, byte ';'
je .semicolon
jmp .checkWord
.nextWord:
call procNextWord
jmp .checkWord
.semicolon:
call procAddNumber
inc si
cmp si, 0x2
je .skipLine
jmp .nextWord
.addNumber:
call procAddNumber
jmp .nextWord
; If this is not the end of file, repeat loop
.skipLine:
cmp [readLastLine], byte 0
je .whileNotEndOfFile
; Hexadecimal convertion to decimal
mov dx, lineCount
mov ax, [lineCount]
call procUInt16ToStr
call procPutStr
macNewLine
mov si, dx
.writingToFile:
lodsb
cmp al, 0
jne .writingToFile
sub si, dx
lea cx, [si-1]
mov bx, [writingDescriptor]
mov ah, 40h
int 21h
; Closing Files
.end:
mov bx, [writingDescriptor]
call procFClose
.writingError:
mov bx, [readingDescriptor]
call procFClose
macPutString 'Program ends', crlf, '$'
exit
%include 'yasmlib.asm'
; void procReadLine()
; Read line to buffer ‘eilute’
procReadLine:
push ax
push bx
push cx
push si
mov bx, [readingDescriptor]
mov si, 0
.loop:
call procFGetChar
; End if the end of file or error
cmp ax, 0
je .endOfFile
jc .endOfFile
; Putting symbol to buffer
mov [line+si], cl
inc si
; Check if there is \n?
cmp cl, 0x0A
je .endOfLine
jmp .loop
.endOfFile:
mov [readLastLine], byte 1
.endOfLine:
mov [line+si], byte '$'
mov [lineLenght], si
pop si
pop cx
pop bx
pop ax
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
procAddNumber:
push si
push ax
push bx
push cx
push dx
;lineCount++
mov ax, word [lineCount]
inc ax
mov [lineCount], ax
pop dx
pop cx
pop bx
pop ax
pop si
ret
procNextWord:
.loop:
inc di
mov al, [di]
cmp al, byte ' '
je .loop
jmp .t
.t:
cmp al, byte ';'
je .t2
jmp .return
.t2:
inc di
mov al, [di]
cmp al, byte ' '
je .t2
jmp .return
.return:
ret
section .data
readingDescriptor:
dw 0000
writingFile:
times 128 db 00
writingDescriptor:
dw 0000
readLastLine:
db 00
line:
db 64
times 66 db '$'
lineLenght:
dw 0000
lineCount:
times 128 db 00
</code></pre>
<p><a href="https://github.com/Kurbamit/Vilnius_University_Software_Engineer/tree/main/Year%201/Computer%20architecture/LAB2" rel="nofollow noreferrer">GITHUB: yasmmac.inc/yasmlib.asm</a></p>
<p>Any help will be appreaciated.</p>
|
[
{
"answer_id": 74480234,
"author": "Sep Roland",
"author_id": 3144770,
"author_profile": "https://Stackoverflow.com/users/3144770",
"pm_score": 1,
"selected": false,
"text": " mov al, [di]\n cmp al, ' ' *\n je .nextWord *\n cmp al, ';' *\n je .nextWord *\n.checkWord:\n mov al, [di]\n inc di\n"
},
{
"answer_id": 74482695,
"author": "Sep Roland",
"author_id": 3144770,
"author_profile": "https://Stackoverflow.com/users/3144770",
"pm_score": 3,
"selected": true,
"text": "; Main loop\n.whileNotEndOfFile:\n call procReadLine\n mov si, 2 ; Do 2 columns\n mov di, line\n.skipSpaces:\n mov al, [di]\n inc di\n cmp al, ' '\n je .skipSpaces\n cmp al, ';'\n je .q3 ; It's trailing whitespace\n dec di\n.checkWord:\n mov bx, 1 ; Assuming it will be a 'good' word\n.q1:\n mov al, [di]\n inc di\n cmp al, ' '\n je .q2\n cmp al, ';'\n je .q2\n or al, 32 ; LCase\n cmp al, 'b'\n jb .q1\n cmp al, 'c'\n ja .q1\n xor bx, bx ; One or more invalid chars in current word\n jmp .q1\n \n.q2:\n add [lineCount], bx ; BX=[0,1] Counting the 'good' words\n cmp al, ';'\n jne .skipSpaces\n.q3:\n dec si ; Next column ?\n jnz .skipSpaces\n.skipLine:\n cmp [readLastLine], byte 0\n je .whileNotEndOfFile\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12652243/"
] |
74,478,884
|
<p>I have the following bar chart. here is the javascript options for it:</p>
<pre><code> public chartOptions = {
responsive: true,
maintainAspectRatio: false,
legend: {
display: true,
labels: {
fontColor: "black",
fontSize: 12,
},
},
scales: {
yAxes: [
{
display: true,
stacked: false,
scaleLabel: {
display: true,
labelString: "Number of Students",
},
ticks: {
stepSize: 5,
min: 0,
max: 30,
fontSize: 12,
fontColor: "black",
},
},
],
xAxes: [
{
display: true,
stacked: false,
ticks: {
fontSize: 12,
fontColor: "black",
precision: 0,
},
},
],
},
};
</code></pre>
<p>Here is the html:</p>
<pre><code> <canvas
baseChart
[datasets]="chartData"
[labels]="chartLabels"
[options]="chartOptions"
[colors]="chartColors"
[plugins]="[]"
[legend]="true"
[chartType]="'bar'"
height="300px"
>
</canvas>
</code></pre>
<p>Sometimes the data labels appear on the bars (see picture), but i can't figure out how to change the colour to make them white. Does anyone know?</p>
<p><a href="https://i.stack.imgur.com/sTlUD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sTlUD.png" alt="chart image" /></a></p>
<p>UPDATE:</p>
<p>Here is the chart with new chartOptions, but still doesn't change the colour of the data labels:</p>
<pre><code> chartOptions = {
responsive: true,
maintainAspectRatio: false,
legend: {
display: true,
},
scales: {
yAxes: [
{
display: true,
stacked: false,
scaleLabel: {
display: true,
labelString: "Number of Students",
},
ticks: {
stepSize: 5,
min: 0,
max: 30,
fontSize: 12,
fontColor: "black",
},
},
],
xAxes: [
{
display: true,
stacked: false,
ticks: {
fontSize: 12,
fontColor: "black",
precision: 0,
},
},
],
},
plugins: {
labels: {
fontColor: "white",
fontSize: 12,
},
},
};
</code></pre>
|
[
{
"answer_id": 74479228,
"author": "user2057925",
"author_id": 2057925,
"author_profile": "https://Stackoverflow.com/users/2057925",
"pm_score": 1,
"selected": false,
"text": " options: {\n ...\n plugins: {\n labels: {\n fontColor: \"black\",\n fontSize: 12,\n },\n }\n ...\n }\n"
},
{
"answer_id": 74483874,
"author": "TestUser",
"author_id": 19238266,
"author_profile": "https://Stackoverflow.com/users/19238266",
"pm_score": 1,
"selected": true,
"text": " dataLabels: {\n colors: [\"white\"],\n },\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19238266/"
] |
74,478,922
|
<p>I am trying to fill <code>NA</code> values of my dataframe. However, I would like to fill them based on the first value of each group.</p>
<pre><code>#> df = data.frame(
group = c(rep("A", 4), rep("B", 4)),
val = c(1, 2, NA, NA, 4, 3, NA, NA)
)
#> df
group val
1 A 1
2 A 2
3 A NA
4 A NA
5 B 4
6 B 3
7 B NA
8 B NA
#> fill(df, val, .direction = "down")
group val
1 A 1
2 A 2
3 A 2 # -> should be 1
4 A 2 # -> should be 1
5 B 4
6 B 3
7 B 3 # -> should be 4
8 B 3 # -> should be 4
</code></pre>
<p>Can I do this with <code>tidyr::fill()</code>? Or is there another (more or less elegant) way how to do this? I need to use this in a longer chain (<code>%>%</code>) operation.</p>
<p>Thank you very much!</p>
|
[
{
"answer_id": 74478974,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "tidyr::replace_na()"
},
{
"answer_id": 74478991,
"author": "jpsmith",
"author_id": 12109788,
"author_profile": "https://Stackoverflow.com/users/12109788",
"pm_score": 2,
"selected": false,
"text": "dplyr"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5013084/"
] |
74,478,934
|
<p>I'm attempting to recreate the following plot styling in R:</p>
<p><a href="https://i.stack.imgur.com/aNWg5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aNWg5.png" alt="enter image description here" /></a></p>
<p>The data doesn't need to map onto the gradient in any meaningful way (though I guess technically it somewhat maps on to the categorical steps of the x-axis, with the colour gradually changing as the date/month changes).</p>
<p>I've tried scale_colour_gradient() and scale_fill_gradient(), but I'm not having any luck. Any guidance on how I could achieve something similar would be appreciated!</p>
<p>Sample data:</p>
<pre><code> views <- tribble(
~month, ~views,
"Jan", 374,
"Feb", 500,
"Mar", 416,
"Apr", 603,
"May", 389,
"Jun", 510) %>%
transform(month = factor(month, levels=c("Jan","Feb","Mar","Apr","May","Jun")))
views %>%
ggplot(., aes(x = month, y = views, group=1)) +
geom_line(color="red") +
scale_y_continuous(breaks=seq(0, 1000, by = 200),
limits = c(0, 1000))
</code></pre>
|
[
{
"answer_id": 74479601,
"author": "tjebo",
"author_id": 7941188,
"author_profile": "https://Stackoverflow.com/users/7941188",
"pm_score": 2,
"selected": false,
"text": "approx"
},
{
"answer_id": 74479717,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 1,
"selected": false,
"text": "geom_line"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11983479/"
] |
74,478,947
|
<p>I need help figuring out what is going wrong. I wrote a long code to basically reformat a workbook by separating and combining information on separate sheets and then save every sheet separately as a CSV. Here is the beginning of my code:</p>
<pre><code>Sub All()
Dim Bottom As Long
Dim Header As Long
> 'A. CHECK DATE
If ThisWorkbook.Sheets("ACH PULL").Range("C1") <> Date Then
MsgBox "ERROR" & Chr(10) & "Date on file is different than today's date" & Chr(13) & "Ask client for corrected file"
Exit Sub
Else
> '1. OUTGOING CHECKS
Sheets("OUTGOING CHECKS").Select
Bottom = WorksheetFunction.Match((Cells(Rows.Count, 1).End(xlUp)), Range("A:A"), 0)
Header = WorksheetFunction.Match("Account*", Range("A:A"), 0)
If Bottom <> Header Then
MsgBox "ERROR" & Chr(10) & "The batch contains outgoing checks" & Chr(13) & "Ask client for corrected file"
Exit Sub
</code></pre>
<p>Bottom and Header are used to find the header of the range and the last row respectively. I use this so many times in my code on separate sheets.</p>
<p>The code works great when I run it from the file that I need to modify. But I need to assign it to a button to another spreadsheet to open the to-be-modified file through VBA and then apply the code. So I added this:</p>
<blockquote>
<pre><code>Sub All()
Dim FileToOpen As Variant
Dim NewBatch As Workbook
Dim Bottom As Integer
Dim Header As Integer
FileToOpen = Application.GetOpenFilename(Title:="Find batch file")
If FileToOpen <> False Then
Set NewBatch = Application.Workbooks.Open(FileToOpen)
End If
'A. CHECK DATE
If Sheets("ACH PULL").Range("C1") <> Date Then
MsgBox "ERROR" & Chr(10) & "Date on file is different than today's date" & Chr(13) & "Ask client for corrected file"
Exit Sub
Else
'1. OUTGOING CHECKS
Sheets("OUTGOING CHECKS").Select
Bottom = WorksheetFunction.Match((Cells(Rows.Count, 1).End(xlUp)), Range("A:A"), 0)
Header = WorksheetFunction.Match("Account*", Range("A:A"), 0)
End If
If Bottom <> Header Then
MsgBox "ERROR" & Chr(10) & "The batch contains outgoing checks" & Chr(13) & "Ask client for corrected file"
Exit Sub
.. The rest of the code
</code></pre>
</blockquote>
<p>Now, when I try to run this, it goes well until the line:</p>
<blockquote>
<p>Bottom = WorksheetFunction.Match((Cells(Rows.Count, 1).End(xlUp)), Range("A:A"), 0)</p>
</blockquote>
<p>I either get 1004 or 400 error. I Dim'd the two integers that I need to use, I tried to make multiple changes including Activating the workbook but still not sure what is causing the problem in this part in the code.</p>
<p>I have the two pieces (VBA opening a workbook, and the reformatting code) working separately, but I can't combine them!</p>
<p>I Dim'd the two integers that I need to use before using them.
I tried making multiple changes including</p>
<blockquote>
<p>NewBatch.Activate</p>
</blockquote>
<p>But it didn't actually made a difference as the opened workbook is already activated. I tried to set the values for Bottom and Header but that didn't work too.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 74479601,
"author": "tjebo",
"author_id": 7941188,
"author_profile": "https://Stackoverflow.com/users/7941188",
"pm_score": 2,
"selected": false,
"text": "approx"
},
{
"answer_id": 74479717,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 1,
"selected": false,
"text": "geom_line"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531339/"
] |
74,478,948
|
<p>I want to deploy an Ubuntu VM on Azure and <strong>automatically</strong> execute a few lines of Bash code right after the VM is deployed. The Bash code is supposed to install PowerShell on the VM. To do this, I use this <a href="https://github.com/fabioklr/pwsh_project/blob/main/main.bicep" rel="nofollow noreferrer">Bicep file</a>. Below you can see an extract of that Bicep file where I specify what Bash code I want to be executed post deployment.</p>
<pre><code>resource deploymentscript 'Microsoft.Compute/virtualMachines/runCommands@2022-08-01' = {
parent: virtualMachine
name: 'postDeploymentPSInstall'
location: location
properties: {
source: {
script: '''sudo apt-get update &&\
sudo apt-get install -y wget apt-transport-https software-properties-common &&\
wget -q "https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb" &&\
sudo dpkg -i packages-microsoft-prod.deb &&\
sudo apt-get update &&\
sudo apt-get install -y powershell &&\
pwsh'''
}
}
}
</code></pre>
<p>I searched for solutions on the web but only found conflicting explanations. I made the code above with the help of this <a href="https://www.errush.org/blogposts/deploymentscripts-in-bicep/" rel="nofollow noreferrer">tutorial</a>. The only difference I see is that I'm using Bash and not PowerShell like the blog post author. Thanks for your help.</p>
|
[
{
"answer_id": 74531629,
"author": "Jahnavi",
"author_id": 19785512,
"author_profile": "https://Stackoverflow.com/users/19785512",
"pm_score": 1,
"selected": false,
"text": "Linux"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15611217/"
] |
74,478,954
|
<p>I'm Trying to fetch values between two timestamps, however the conversion timestamp failing with formatting error.</p>
<pre><code>SELECT
*
FROM
PKV
WHERE
extended_timestamp BETWEEN TO_TIMESTAMP('28-OCT-22 01.10.37.153016000 PM ASIA/CALCUTTA,DD-MON-YY HH24:MI:SS') AND TO_TIMESTAMP(
'28-OCT-22 10.10.37.153016000 PM ASIA/CALCUTTA,DD-MON-YY HH24:MI:SS')
</code></pre>
|
[
{
"answer_id": 74479708,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 2,
"selected": true,
"text": "TO_TIMESTAMP_TZ('28-OCT-22 01.10.37.153016000 PM ASIA/CALCUTTA','DD-MON-YY HH12:MI:SS.FF9 PM TZR', 'NLS_DATE_LANGUAGE = American') \n"
},
{
"answer_id": 74483176,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 0,
"selected": false,
"text": "TIMESTAMP"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5393402/"
] |
74,478,959
|
<p>Is it possible to have graphviz/dot render a node as a circle that is split in the middle horizontally, with a top and bottom text content? Something like a record, but the final shape should be a circle. Currently I'm using <a href="https://graphviz.org/doc/info/shapes.html#record" rel="nofollow noreferrer">Mrecord</a>, but that's only a rounded rectangle, not a circle shape.</p>
<p>I searched for ways to increase the border radius of Mrecord (to make it a quasi-circle) but that did not work. I also tried <a href="https://graphviz.org/doc/info/shapes.html#d:Mcircle" rel="nofollow noreferrer">Mcircle</a>, which is not what I was looking for.</p>
|
[
{
"answer_id": 74479708,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 2,
"selected": true,
"text": "TO_TIMESTAMP_TZ('28-OCT-22 01.10.37.153016000 PM ASIA/CALCUTTA','DD-MON-YY HH12:MI:SS.FF9 PM TZR', 'NLS_DATE_LANGUAGE = American') \n"
},
{
"answer_id": 74483176,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 0,
"selected": false,
"text": "TIMESTAMP"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12681220/"
] |
74,478,967
|
<p>I'm looking for some help please with some VBA.</p>
<p>I have the next table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>header1</th>
</tr>
</thead>
<tbody>
<tr>
<td>000Model Test0Model Val00User0</td>
</tr>
<tr>
<td>Perman000User0Model Name000000</td>
</tr>
<tr>
<td>000Perman00000000000000000000Name</td>
</tr>
</tbody>
</table>
</div>
<p>So I need to replace all Ceros with only one "," like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>header1</th>
</tr>
</thead>
<tbody>
<tr>
<td>,Model Test,Model Val,User,</td>
</tr>
<tr>
<td>Perman,User,Model Name,</td>
</tr>
<tr>
<td>,Perman,Name</td>
</tr>
</tbody>
</table>
</div>
<p>Is there a combination of formulas to do this? or with code in VBA?</p>
|
[
{
"answer_id": 74479408,
"author": "FaneDuru",
"author_id": 2233308,
"author_profile": "https://Stackoverflow.com/users/2233308",
"pm_score": 3,
"selected": true,
"text": "Function replace0(x As String) As String\n Dim matches As Object, mch As Object, arr, k As Long\n ReDim arr(Len(x))\n With CreateObject(\"VbScript.regexp\")\n Pattern = \"[0]{1,30}\"\n .Global = True\n If .test(x) Then\n replace0 = .replace(x, \",\")\n End If\n End With\nEnd Function\n"
},
{
"answer_id": 74480547,
"author": "Ron Rosenfeld",
"author_id": 2872922,
"author_profile": "https://Stackoverflow.com/users/2872922",
"pm_score": 2,
"selected": false,
"text": "=IF(LEFT(A1)=\"0\",\",\",\"\")&TEXTJOIN(\",\",TRUE,TEXTSPLIT(A1,\"0\"))&IF(RIGHT(A1)=\"0\",\",\",\"\")\n"
},
{
"answer_id": 74481501,
"author": "T.M.",
"author_id": 6460297,
"author_profile": "https://Stackoverflow.com/users/6460297",
"pm_score": 1,
"selected": false,
"text": "tmp"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17786412/"
] |
74,478,971
|
<p>I am reading all files from a directory and storing the file paths of those in that directory in a list using</p>
<pre><code>files = [os.path.abspath(x) for x in os.listdir(r"my directory")]
</code></pre>
<p>Each file in a unique template so the resulting list is something like</p>
<pre><code>[C:\Users\....\Template_Coversheet.xlsx
C:\Users\....\Template_Blanks.xlsx,
C:\Users\....\Template_Stocks.xlsx,
C:\Users\....\Template_May.xlsx]
</code></pre>
<p>*Note files aren't necessarily always in the same order</p>
<p>I want to reach each of these files and assign them to a variable that corresponds to the type of template.</p>
<p>I can do this by doing a a for loop and a long series of if statements</p>
<pre><code>for f in files:
if "Blanks" in f:
blank=f
if "Stocks" in f:
stock=f
if "May" in f:
may=f
if "Coversheet" in f:
coversheet=f
</code></pre>
<p>But is there an easier or more pythonic way to achieve this?</p>
|
[
{
"answer_id": 74479032,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 1,
"selected": true,
"text": "TEMPLATE_TYPES = \"Blanks\", \"Stocks\", \"May\", \"Coversheet\"\n\nfiles_by_template = {t: [] for t in TEMPLATE_TYPES}\nfor f in files:\n for t in TEMPLATE_TYPES:\n if t in f:\n files_by_template[t].append(f)\n"
},
{
"answer_id": 74479082,
"author": "Farooq Karimi Zadeh",
"author_id": 13159343,
"author_profile": "https://Stackoverflow.com/users/13159343",
"pm_score": 2,
"selected": false,
"text": "Template_TEMPLATENAME.xlsx"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11956484/"
] |
74,478,978
|
<p>I have two CSV files data1.csv and data2.csv the content is something like this (with headers) :</p>
<p>DATA1.csv</p>
<pre><code>Client Name;strnu;addr;fav
MAD01;HDGF;11;V PO
CVOJF01;HHD-;635;V T
LINKO10;DH--JDH;98;V ZZ
</code></pre>
<p>DATA2.csv</p>
<pre><code>USER;BINin;TYPE
XXMAD01XXXHDGFXX;11;N
KJDGD;635;M
CVOJF01XXHHD;635;N
</code></pre>
<p>Issues :</p>
<ul>
<li>The value of the 1st and 2nd column of DATA1.csv exist randomly in the first column of DATA2.csv.
For example <code>MAD01;HDGF</code> exist in the first column of DATA2 <code>***MAD01***HDGF**</code> (<code>*</code> can be alphanum and/or symbols charachter) and <code>MAD01;HDGF</code> might not be in the same order in the column <code>USER</code> of DATA2.</li>
<li>The value of strnum in DATA1 is equal to the value of the column BINin in DATA2</li>
<li>The column fav DATA1 is the same as TYPE in DATA2 because <code>V T = M</code> and <code>V PO = N</code> (some other valuses may exist but we won't need them for example line 3 of DATA1 it should be ignored)</li>
</ul>
<p>N.B: some data may exist in a file but not the other.</p>
<p>my bash script needs to generate a new CSV file that should contain:</p>
<ul>
<li>The column <code>USER</code> from DATA2</li>
<li><code>Client Name</code> and <code>strnu</code> from DATA1</li>
<li><code>BINin</code> from DATA2 only if it's equal to the corespondent line and value of <code>strnu</code> DATA1</li>
<li><code>TYPE</code> using <code>M</code> <code>N</code> Format and making sure to respect the condition that <code>V T = M</code> and <code>V PO = N</code></li>
</ul>
<p>The first thing i tried was usuing grep to search for lines that exist in both files</p>
<pre><code>#!/bin/sh
DATA1="${1}"
DATA2="${2}"
for i in $(cat $DATA1 | awk -F";" '{print $1".*"$2}' | sed 1d) ; do
grep "$i" $DATA2
done
</code></pre>
<p>Result :</p>
<pre><code>$ ./script.sh DATA1.csv DATA2.csv
MAD01;HDGF;11;V PO
XXMAD01XXXHDGFXX;11;N
CVOJF01;HHD-;635;V T
LINKO10;DH--JDH;98;V PO
</code></pre>
<p>Using grep and awk i could find lines that are present in DATA1 and DATA2 files but it doesn't work for all the lines and i guess it's because of the <code>-</code> and other special characters present in column 2 of DATA1 but they can be ignored.</p>
<p>I don't know how i can generate a new csv that would mix the lines present in both files but the expected generated CSV should look like this</p>
<pre><code>USER;Client Name;strnu;BINin;TYPE
XXMAD01XXXHDGFXX;MAD01;HDGF;11;N
CVOJF01XXHHD;CVOJF01;HHD-;635;M
</code></pre>
|
[
{
"answer_id": 74479032,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 1,
"selected": true,
"text": "TEMPLATE_TYPES = \"Blanks\", \"Stocks\", \"May\", \"Coversheet\"\n\nfiles_by_template = {t: [] for t in TEMPLATE_TYPES}\nfor f in files:\n for t in TEMPLATE_TYPES:\n if t in f:\n files_by_template[t].append(f)\n"
},
{
"answer_id": 74479082,
"author": "Farooq Karimi Zadeh",
"author_id": 13159343,
"author_profile": "https://Stackoverflow.com/users/13159343",
"pm_score": 2,
"selected": false,
"text": "Template_TEMPLATENAME.xlsx"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11363473/"
] |
74,478,984
|
<p>I'm parsing an XML document, and I need the book title & number value under Score and place them on a 2d list. My current code, can retrieve that data and place it on a list, but the problem is there's some sections in the XML file where the score is not present, and I need to be able to leave an indicator (ex. N/A) on the list to indicate that value is empty for that particular book title.</p>
<p>This is a sample, simplified version of the xml file. Please note, that this problem repeats throughout the much longer version of the xml file. So no code can use, 1 as an index to get past this problem.</p>
<pre><code><bookstore>
<book>[A-23] Everyday Italian</book>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
<field></field>
<key id="6408">[A-23]Everyday Italian</key>
<brief>Everyday Italian</brief>
<success></success>
<province> id="256" key=".com.place.fieldtypes:float">
<name>Post</name>
<numbers>
<number></number>
</numbers>
</province>
<province> id="490" key=".com.ave.fieldtypes:float">
<name>Score</name>
<numbers>
<number>4.0</number>
</numbers>
</province>
<province> id="531" key=".com.spot.fieldtypes:float">
<name>Doc</name>
<numbers>
<number></number>
</numbers>
</province>
</bookstore>
<bookstore>
<book>[A-42] Pottery</book>
<author>Leo Di Plos</author>
<year>2012</year>
<price>25.00</price>
<field></field>
<key id="4502">[A-42] Pottery</key>
<brief>Pottery</brief>
<success></success>
<province> id="627" key=".com.tri.fieldtypes:float">
<name>Post</name>
<numbers>
<number></number>
</numbers>
</province>
<province> id="124" key=".com.doct.fieldtypes:float">
<name>Doc</name>
<numbers>
<number></number>
</numbers>
</province>
</bookstore>
<bookstore>
<book>[A-12] Skipping the Line</book>
<author>Gloria Gasol</author>
<year>1999</year>
<price>22.00</price>
<field></field>
<key id="1468">[A-23]Skipping the Line</key>
<brief>Skipping the Line</brief>
<success></success>
<province> id="754" key=".com.cit.fieldtypes:float">
<name>Post</name>
<numbers>
<number></number>
</numbers>
</province>
<province> id="211" key=".com.soct.fieldtypes:float">
<name>Score</name>
<numbers>
<number>12.0</number>
</numbers>
</province>
<province> id="458" key=".com.lot.fieldtypes:float">
<name>Doc</name>
<numbers>
<number></number>
</numbers>
</province>
</bookstore>
</code></pre>
<p>This is my current code:</p>
<pre><code>book = []
for book in root.iter('book'):
item1 = book.text
title.append(item1)
score = []
for province in root.iter('province'):
for child in province:
for grandchild in child:
if re.match('^[+-]?\d*?\.\d+$', grandchild.text) != None:
item2 = float(grandchild.text)
score.append(item2)
print(book, score)
</code></pre>
<p>The expected output is:</p>
<pre><code>([A-23] Everyday Italian, 4.0), ([A-42] Pottery, N/A), ([A-12] Skipping the Line, 12.0)
</code></pre>
<p>But the actual output is:</p>
<pre><code>([A-23] Everyday Italian, 4.0), ([A-42] Pottery, 12.0), ([A-12] Skipping the Line)
</code></pre>
|
[
{
"answer_id": 74479200,
"author": "Paweł Pietraszko",
"author_id": 19391219,
"author_profile": "https://Stackoverflow.com/users/19391219",
"pm_score": 2,
"selected": false,
"text": "<bookstore>\n <book>[A-23] Everyday Italian</book>**\n\n <author>Giada De Laurentiis</author>\n <year>2005</year>\n <price>30.00</price>\n <field></field>\n <key id=\"6408\">[A-23]Everyday Italian</key>\n <brief>Everyday Italian</brief>\n <success></success>\n <province> id=\"256\" key=\".com.place.fieldtypes:float\">\n <name>Post</name>\n <numbers>\n <number></number>\n </numbers>\n </province>\n <province> id=\"490\" key=\".com.ave.fieldtypes:float\">\n **\n <name>Score</name>**\n \n <numbers>\n **\n <number>4.0</number>**\n \n </numbers>\n </province>\n <province> id=\"531\" key=\".com.spot.fieldtypes:float\">\n <name>Doc</name>\n <numbers>\n <number></number>\n </numbers>\n </province>\n</bookstore>\n"
},
{
"answer_id": 74480952,
"author": "balderman",
"author_id": 415016,
"author_profile": "https://Stackoverflow.com/users/415016",
"pm_score": 2,
"selected": true,
"text": "import xml.etree.ElementTree as ET\n\nxml = '''<r>\n <bookstore>\n <book>[A-23] Everyday Italian</book>\n <author>Giada De Laurentiis</author>\n <year>2005</year>\n <price>30.00</price>\n <field></field>\n <key id=\"6408\">[A-23]Everyday Italian</key>\n <brief>Everyday Italian</brief>\n <success></success>\n <province> id=\"256\" key=\".com.place.fieldtypes:float\">\n <name>Post</name>\n <numbers>\n <number></number>\n </numbers>\n </province>\n <province> id=\"490\" key=\".com.ave.fieldtypes:float\">\n <name>Score</name>\n <numbers>\n <number>4.0</number>\n </numbers>\n </province>\n <province> id=\"531\" key=\".com.spot.fieldtypes:float\">\n <name>Doc</name>\n <numbers>\n <number></number>\n </numbers>\n </province>\n </bookstore>\n <bookstore>\n <book>[A-42] Pottery</book>\n <author>Leo Di Plos</author>\n <year>2012</year>\n <price>25.00</price>\n <field></field>\n <key id=\"4502\">[A-42] Pottery</key>\n <brief>Pottery</brief>\n <success></success>\n <province> id=\"627\" key=\".com.tri.fieldtypes:float\">\n <name>Post</name>\n <numbers>\n <number></number>\n </numbers>\n </province>\n <province> id=\"124\" key=\".com.doct.fieldtypes:float\">\n <name>Doc</name>\n <numbers>\n <number></number>\n </numbers>\n </province>\n </bookstore>\n <bookstore>\n <book>[A-12] Skipping the Line</book>\n <author>Gloria Gasol</author>\n <year>1999</year>\n <price>22.00</price>\n <field></field>\n <key id=\"1468\">[A-23]Skipping the Line</key>\n <brief>Skipping the Line</brief>\n <success></success>\n <province> id=\"754\" key=\".com.cit.fieldtypes:float\">\n <name>Post</name>\n <numbers>\n <number></number>\n </numbers>\n </province>\n <province> id=\"211\" key=\".com.soct.fieldtypes:float\">\n <name>Score</name>\n <numbers>\n <number>12.0</number>\n </numbers>\n </province>\n <province> id=\"458\" key=\".com.lot.fieldtypes:float\">\n <name>Doc</name>\n <numbers>\n <number></number>\n </numbers>\n </province>\n </bookstore>\n</r>\n'''\nroot = ET.fromstring(xml)\ndata = []\nfor bs in root.findall('.//bookstore'):\n book = bs.find('book').text\n scores = [s.text for s in bs.findall('.//number') if s.text]\n score = 'N/A' if not scores else scores[0]\n data.append((book, score))\nprint(data)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74478984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20511050/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.