qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,546,149
|
<p>I am trying to find a way to check the AD roles attached to a user. After a lot of reading, it seems like there is no cli call that can provide this information. The workaround I am thinking is to list out all the users who have "Global Administrator" permission in the AD role. Is there an azure CLI call that can help with getting this information? I tried the calls in <code>az ad user</code> but none of them have the information I am looking for.</p>
|
[
{
"answer_id": 74548125,
"author": "Sridevi",
"author_id": 18043665,
"author_profile": "https://Stackoverflow.com/users/18043665",
"pm_score": 2,
"selected": true,
"text": "GET https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments?$filter=roleDefinitionId eq '62e90394-69f5-4237-9190-012177145e10'\n az rest az rest --method get --url \"https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments?$filter=roleDefinitionId eq '62e90394-69f5-4237-9190-012177145e10'\"\n az rest --method get --url \"https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments?$filter=roleDefinitionId eq '62e90394-69f5-4237-9190-012177145e10'\"\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/881150/"
] |
74,546,189
|
<p>Please help me to find a <em>more</em> elegant way to rewrite this snippet using <code>std::transform</code> or similar algorithm:</p>
<pre><code>for (auto& warning : warnings)
{
NormalizePath(warning.path, GetParsedPathLength(warning.path), longestPathLength);
};
</code></pre>
<p>Where <code>warning</code> is a <code>struct</code>.</p>
<p>This is what I came up with:</p>
<pre><code>std::transform(begin(warnings), end(warnings), begin(warnings),
[longestPathLength](auto& warning)
{
NormalizePath(warning.path, GetParsedPathLength(warning.path), longestPathLength);
return warning;
});
</code></pre>
<p>But it requires a copy of full data-structure. Is there a way to create a modifiable view of a original sequence that contains only <code>path</code> member? So transform could be rewritten only accepting and returning modified <code>path</code>. And in the end all the changes should affect original <code>warnings</code> sequence.</p>
|
[
{
"answer_id": 74548125,
"author": "Sridevi",
"author_id": 18043665,
"author_profile": "https://Stackoverflow.com/users/18043665",
"pm_score": 2,
"selected": true,
"text": "GET https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments?$filter=roleDefinitionId eq '62e90394-69f5-4237-9190-012177145e10'\n az rest az rest --method get --url \"https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments?$filter=roleDefinitionId eq '62e90394-69f5-4237-9190-012177145e10'\"\n az rest --method get --url \"https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments?$filter=roleDefinitionId eq '62e90394-69f5-4237-9190-012177145e10'\"\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2170898/"
] |
74,546,201
|
<p>I have a script that is adding or substracting a value (picked up in M2 cell) in each cell of a selected range (I mean a range that I can select with the mouse) :</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-html lang-html prettyprint-override"><code>function moreLess() {
var ss = SpreadsheetApp.getActive();
var sel = ss.getSelection().getActiveRangeList().getRanges();
for (var i=0; i<sel.length; i++) {
var range = sel[i];
var values = range.getValues();
var number = SpreadsheetApp.getActive().getSheetByName("sommaire_redac").getRange('M2').getValue();
for (var j=0; j<values.length; j++) {
for (var k=0; k<values[0].length; k++) {
values[j][k] += number;
}
}
range.setValues(values);
}
}</code></pre>
</div>
</div>
</p>
<p>This works. But instead of selecting all the cells in which I want add or substract a value, I would like to select only one cell, and have a script that would select a range from this selected cell to the last non-empty cell of the column.</p>
<p>For example, instead of selecting cells T30:T36 like this…</p>
<p><a href="https://i.stack.imgur.com/EA17u.png" rel="nofollow noreferrer">with the code I have today</a></p>
<p>… I would like to select only T30, like this…</p>
<p><a href="https://i.stack.imgur.com/WXBk4.png" rel="nofollow noreferrer">with the code I'd like to have</a></p>
<p>… and then I would like the script to get the last non-empty cell of the column (T36) and select the range T30:T36.</p>
<p>I mean I would like to get exactly the same result by selecting only T30 cell, that I today obtain by selecting T30:T36.</p>
<p>Thanks !</p>
|
[
{
"answer_id": 74546846,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 0,
"selected": false,
"text": " var ss = SpreadsheetApp.getActive();\n ss.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate()\n var sel = ss.getSelection().getActiveRangeList().getRanges();\n"
},
{
"answer_id": 74546864,
"author": "Ping",
"author_id": 20288037,
"author_profile": "https://Stackoverflow.com/users/20288037",
"pm_score": -1,
"selected": false,
"text": "function lastEmpty(col) {\n const sss = SpreadsheetApp.getActiveSpreadsheet();\n const ss = sss.getActiveSheet();\n \n const getlastEmptyRow = (colValues) => {\n return colValues.length - colValues.reverse().findIndex(row => !!row[0]);\n }\n const colValues = ss.getRange(col+\":\"+col).getValues();\n const lastEmptyRow = getlastEmptyRow(colValues);\n\n return lastEmptyRow;\n}\n\nconsole.log(`last empty row in column T is ${lastEmpty('T')}`)"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15086384/"
] |
74,546,203
|
<p>How can I get the id of a task in my todo app without using ActivatedRoute method for updating functionality in angular ?</p>
<p><code>this.route.paramMap.subscribe(params => {this.id = params.get('id');})</code></p>
<p>this is the way which I'm using now</p>
|
[
{
"answer_id": 74546362,
"author": "XRaycat",
"author_id": 7744154,
"author_profile": "https://Stackoverflow.com/users/7744154",
"pm_score": 0,
"selected": false,
"text": "@output @input"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16953799/"
] |
74,546,214
|
<p>i have two df and i wanna check for the id if the value differs in both df if so i need to print those.</p>
<p>example:</p>
<pre><code>df1 = |id |check_column1|
|1|abc|
|1|bcd|
|2|xyz|
|2|mno|
|2|mmm|
</code></pre>
<pre><code>df2 =
|id |check_column2|
|1|bcd|
|1|abc|
|2|xyz|
|2|mno|
|2|kkk|
</code></pre>
<p>here the output should be just |2|mmm|kkk| but i am getting whole table as output since index are different</p>
<p>This is what i did</p>
<pre><code>output = pd.merge(df1,df2, on= ['id'], how='inner')
event4 = output[output.apply(lambda x: x['check_column1'] != x['check_column2'], axis=1)]
</code></pre>
|
[
{
"answer_id": 74546283,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "id GroupBy.cumcount df1 = df1.sort_values(['id','check_column1'])\ndf2 = df2.sort_values(['id','check_column2'])\n \ndf = pd.merge(df1,df2, left_on= ['id',df1.groupby('id').cumcount()], \n right_on= ['id',df2.groupby('id').cumcount()])\n\noutput = df[df['check_column1'] != df['check_column2']]\nprint (output)\n id key_1 check_column1 check_column2\n2 2 0 mmm kkk\n"
},
{
"answer_id": 74546359,
"author": "Ouroboroski",
"author_id": 8303090,
"author_profile": "https://Stackoverflow.com/users/8303090",
"pm_score": 0,
"selected": false,
"text": "mask = np.where((df1['id'] != df2['id']) | (df1['check_column1'] != df2['check_column2']), True, False)\n\noutput = df2[mask]\n"
},
{
"answer_id": 74546654,
"author": "htrcode",
"author_id": 20581579,
"author_profile": "https://Stackoverflow.com/users/20581579",
"pm_score": 0,
"selected": false,
"text": "df1 = pd.DataFrame({'id':[1,1,2,2,2],'check_column1':['abc','bcd','xyz','mno','mmm']})\ndf2 = pd.DataFrame({'id':[1,1,2,2,2],'check_column2':['bcd','abc','xyz','mno','kkk']})\n\noutput = pd.merge(df1,df2, on= ['id'], how='inner')\nevent4 = np.where(output['check_column1']!=output['check_column2'],output[['id','check_column1']],output[['id','check_column2']])\n array([[2, 'mmm'],\n [2, 'kkk']], dtype=object)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19189066/"
] |
74,546,242
|
<p>I was trying to update my whole project dependencies, and managed to do it, but when I try to run the tests with <code>ng test --no-watch</code> they don't work, giving me the following error.</p>
<pre><code>23 11 2022 12:33:58.268:INFO [Chrome Headless 107.0.5304.107 (Windows 10)]: Connected on socket JpJqOsJswlYxFGjeAAAB with id 12720855
Chrome Headless 107.0.5304.107 (Windows 10) ERROR
An error was thrown in afterAll
Uncaught TypeError: __webpack_require__(...).context is not a function
TypeError: __webpack_require__(...).context is not a function
at Object.4289 (http://localhost:9876/_karma_webpack_/webpack:/src/test.ts:18:25)
at __webpack_require__ (http://localhost:9876/_karma_webpack_/webpack:/webpack/bootstrap:19:1)
at __webpack_exec__ (http://localhost:9876/_karma_webpack_/main.js:10483:48)
at http://localhost:9876/_karma_webpack_/main.js:10484:54
at Function.__webpack_require__.O (http://localhost:9876/_karma_webpack_/webpack:/webpack/runtime/chunk loaded:23:1)
at http://localhost:9876/_karma_webpack_/main.js:10485:56
at webpackJsonpCallback (http://localhost:9876/_karma_webpack_/webpack:/webpack/runtime/jsonp chunk loading:71:1)
at http://localhost:9876/_karma_webpack_/main.js:1:87
Chrome Headless 107.0.5304.107 (Windows 10): Executed 0 of 0 ERROR (0.106 secs / 0 secs)
</code></pre>
<p>It's interesting how it worked perfectly before doing the update, and suddenly it seems like webpack is unable to find the context? Why?</p>
<p>The dependencies I changed were:</p>
<p>Old dependencies:</p>
<pre><code>"dependencies": {
"@angular/animations": "13.3.6",
"@angular/cdk": "13.3.6",
"@angular/common": "13.3.6",
"@angular/compiler": "13.3.6",
"@angular/core": "13.3.6",
"@angular/forms": "13.3.6",
"@angular/localize": "13.3.6",
"@angular/platform-browser": "13.3.6",
"@angular/platform-browser-dynamic": "13.3.6",
"@angular/router": "13.3.6",
"@auth0/angular-jwt": "5.0.2",
"@fortawesome/angular-fontawesome": "0.10.2",
"@fortawesome/fontawesome-svg-core": "6.1.1",
"@fortawesome/free-regular-svg-icons": "6.1.1",
"@fortawesome/free-solid-svg-icons": "6.1.1",
"@ngrx/effects": "13.2.0",
"@ngrx/router-store": "13.2.0",
"@ngrx/store": "13.2.0",
"@ngrx/store-devtools": "13.2.0",
"@ngx-translate/core": "14.0.0",
"bootstrap": "5.1.3",
"core-js": "3.22.4",
"ngx-bootstrap": "8.0.0",
"@popperjs/core": "2.11.5",
"primeng": "13.3.3",
"rxjs": "7.5.5",
"svg-to-pdfkit": "0.1.8",
"tslib": "2.4.0",
"ws-blueprint-api": "file:./build/stubs/domain-a-api",
"zone.js": "0.11.5"
},
"devDependencies": {
"@angular-devkit/build-angular": "13.3.5",
"@angular-eslint/builder": "13.2.1",
"@angular-eslint/eslint-plugin": "13.2.1",
"@angular-eslint/eslint-plugin-template": "13.2.1",
"@angular-eslint/schematics": "13.2.1",
"@angular-eslint/template-parser": "13.2.1",
"@angular/cli": "13.3.5",
"@angular/compiler-cli": "13.3.6",
"@angular/language-service": "13.3.6",
"@ngrx/schematics": "13.2.0",
"@types/jasmine": "4.0.3",
"@types/jasminewd2": "2.0.10",
"@types/node": "17.0.31",
"@typescript-eslint/eslint-plugin": "5.22.0",
"@typescript-eslint/parser": "5.22.0",
"cypress": "9.6.0",
"cypress-multi-reporters": "1.6.0",
"cypress-sonarqube-reporter": "1.10.0",
"eslint": "8.15.0",
"eslint-formatter-gitlab": "3.0.0",
"eslint-plugin-import": "2.25.4",
"eslint-plugin-jsdoc": "38.0.6",
"eslint-plugin-prefer-arrow": "1.2.3",
"jasmine-core": "4.1.0",
"jasmine-spec-reporter": "7.0.0",
"karma": "6.3.19",
"karma-chrome-launcher": "3.1.1",
"karma-coverage": "2.2.0",
"karma-jasmine": "5.0.0",
"karma-junit-reporter": "2.0.1",
"karma-sonarqube-unit-reporter": "0.0.23",
"mocha-junit-reporter": "2.0.2",
"ngrx-store-freeze": "0.2.4",
"ngx-translate-testing": "6.0.1",
"prettier": "2.6.2",
"start-server-and-test": "1.14.0",
"ts-node": "10.7.0",
"typescript": "4.6.4",
"webpack-bundle-analyzer": "4.5.0"
},
</code></pre>
<p>New dependencies:</p>
<pre><code>"dependencies": {
"@angular/animations": "15.0.0",
"@angular/cdk": "15.0.0",
"@angular/common": "15.0.0",
"@angular/compiler": "15.0.0",
"@angular/core": "15.0.0",
"@angular/forms": "15.0.0",
"@angular/localize": "15.0.0",
"@angular/platform-browser": "15.0.0",
"@angular/platform-browser-dynamic": "15.0.0",
"@angular/router": "15.0.0",
"@auth0/angular-jwt": "5.1.0",
"@fortawesome/angular-fontawesome": "0.12.0",
"@fortawesome/fontawesome-svg-core": "6.2.1",
"@fortawesome/free-regular-svg-icons": "6.2.1",
"@fortawesome/free-solid-svg-icons": "6.2.1",
"@ngrx/effects": "14.3.2",
"@ngrx/router-store": "14.3.2",
"@ngrx/store": "14.3.2",
"@ngrx/store-devtools": "14.3.2",
"@ngx-translate/core": "14.0.0",
"bootstrap": "5.2.2",
"core-js": "3.26.1",
"ngx-bootstrap": "9.0.0",
"@popperjs/core": "2.11.6",
"primeng": "14.2.2",
"rxjs": "7.5.7",
"svg-to-pdfkit": "0.1.8",
"tslib": "2.4.1",
"ws-blueprint-api": "file:./build/stubs/domain-a-api",
"zone.js": "0.12.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "15.0.0",
"@angular-eslint/builder": "15.0.0",
"@angular-eslint/eslint-plugin": "15.0.0",
"@angular-eslint/eslint-plugin-template": "15.0.0",
"@angular-eslint/schematics": "15.0.0",
"@angular-eslint/template-parser": "15.0.0",
"@angular/cli": "15.0.0",
"@angular/compiler-cli": "15.0.0",
"@angular/language-service": "15.0.0",
"@ngrx/schematics": "14.3.2",
"@types/jasmine": "4.3.0",
"@types/jasminewd2": "2.0.10",
"@types/node": "18.11.9",
"@typescript-eslint/eslint-plugin": "5.43.0",
"@typescript-eslint/parser": "5.43.0",
"cypress": "11.1.0",
"cypress-multi-reporters": "1.6.1",
"cypress-sonarqube-reporter": "1.11.0",
"eslint": "8.28.0",
"eslint-formatter-gitlab": "4.0.0",
"eslint-plugin-import": "2.26.0",
"eslint-plugin-jsdoc": "39.6.2",
"eslint-plugin-prefer-arrow": "1.2.3",
"jasmine-core": "4.5.0",
"jasmine-spec-reporter": "7.0.0",
"karma": "6.4.1",
"karma-chrome-launcher": "3.1.1",
"karma-coverage": "2.2.0",
"karma-jasmine": "5.1.0",
"karma-junit-reporter": "2.0.1",
"karma-sonarqube-unit-reporter": "0.0.23",
"mocha-junit-reporter": "2.2.0",
"ngrx-store-freeze": "0.2.4",
"ngx-translate-testing": "6.1.0",
"prettier": "2.7.1",
"start-server-and-test": "1.14.0",
"ts-node": "10.9.1",
"typescript": "4.8.4",
"webpack-bundle-analyzer": "4.7.0"
},
</code></pre>
<p>Basically changed most of them to the latest. I even tried to revert and try to update one by one, but as soon as I update angular it breaks, why is so?</p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 74572172,
"author": "donkeyjot",
"author_id": 14701008,
"author_profile": "https://Stackoverflow.com/users/14701008",
"pm_score": 1,
"selected": false,
"text": " const context = require.context('./', true, /\\.spec\\.ts$/);\n context.keys().forEach(context);\n"
},
{
"answer_id": 74644245,
"author": "Tobias Teichner",
"author_id": 9781753,
"author_profile": "https://Stackoverflow.com/users/9781753",
"pm_score": 0,
"selected": false,
"text": "{\n \"builder\": \"@angular-devkit/build-angular:karma\",\n \"options\": {\n \"main\": \"projects/components/src/test.ts\",\n \"tsConfig\": \"projects/components/tsconfig.spec.json\",\n \"karmaConfig\": \"projects/components/karma.conf.js\"\n }\n}\n {\n \"builder\": \"@angular-devkit/build-angular:karma\",\n \"options\": {\n \"polyfills\": [\n \"zone.js\",\n \"zone.js/testing\"\n ],\n \"tsConfig\": \"projects/components/tsconfig.spec.json\",\n \"karmaConfig\": \"projects/components/karma.conf.js\"\n }\n}\n {\n \"files\": [\n \"src/test.ts\"\n ],\n \"include\": [\n \"**/*.spec.ts\",\n \"**/*.d.ts\"\n ]\n}\n {\n \"files\": [\n ],\n \"include\": [\n \"**/*.spec.ts\",\n \"**/*.d.ts\",\n \"**/*.ts\"\n ]\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9244199/"
] |
74,546,243
|
<p>This is my code</p>
<pre><code>public class StringTest {
public static void main(String []args) {
String str= "8650";
StringBuilder build = new StringBuilder(str);
char index = str.charAt(0);
System.out.println(index+"");
int indexStr= build.indexOf(index+"");
System.out.println(indexStr);
for( int i = 0; i < str.length(); i++) {
if(indexStr == 0)
build.deleteCharAt(indexStr);
}
System.out.println(build);
}
}
</code></pre>
<p>I want to delete thé first number if it’s 0</p>
<p>So if I have 8650 it will print 8650, instead if I have 0650 it will print 650.</p>
|
[
{
"answer_id": 74546289,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 1,
"selected": false,
"text": "String.startsWith() public class StringTest {\n\n public static void main(String[] args) {\n String str = \"8650\";\n str = \"0650\";\n if (str.startsWith(\"0\")) {\n str = str.substring(1);\n }\n System.out.println(str);\n }\n}\n"
},
{
"answer_id": 74546393,
"author": "Abirami Balasubramaniyan",
"author_id": 5755531,
"author_profile": "https://Stackoverflow.com/users/5755531",
"pm_score": 1,
"selected": false,
"text": " public static void main(String[] args) {\n\n String val = \"10456\";\n val = (val.charAt(0) == '0') ? val.substring(1, val.length()) : val;\n System.out.println(val);\n}\n"
},
{
"answer_id": 74547250,
"author": "Bhushan",
"author_id": 12965752,
"author_profile": "https://Stackoverflow.com/users/12965752",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n String str = \"000650\";\n str = str.replaceFirst(\"^0*\", \"\");\n System.out.println(str); // output 650 it will remove all leading zero\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581459/"
] |
74,546,251
|
<p>Always been struggeling with RegEx, help is much appreciated!
I want to match parts of a URL with Regex but cannot get my head around it.</p>
<p>Domains are:</p>
<p>https://<strong>name</strong>.secondpart.thirdpart.com</p>
<p>I want my regex to match</p>
<p><strong>name</strong> How would I achieve this?</p>
<p>Started with <code>(?<=^|\.)</code> and <code>(?<=^|\.)secondpart\.thirdpart\.com$</code> but it didn't work.</p>
|
[
{
"answer_id": 74546377,
"author": "Jay",
"author_id": 4068476,
"author_profile": "https://Stackoverflow.com/users/4068476",
"pm_score": 2,
"selected": true,
"text": "/ \\/ ^[^.:\\/]+:\\/\\/([^.]+)\n ^[^.:\\/]+:\\/\\/([^.]+)\\.secondpart\\.thirdpart\\.com$\n ^[^.:\\/]+:\\/\\/([^.]+)(?:\\.[^.]+){3}$\n"
},
{
"answer_id": 74546556,
"author": "Newbie Swift Coder",
"author_id": 16874055,
"author_profile": "https://Stackoverflow.com/users/16874055",
"pm_score": 0,
"selected": false,
"text": "(?:http[s]*\\:\\/\\/)*(.*?)\\.(?=[^\\/]*\\..{2,5})\n"
},
{
"answer_id": 74548926,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 1,
"selected": false,
"text": "^https?://\\K[^\\s./]+\n ^ https?:// \\K [^\\s./]+ . /"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581055/"
] |
74,546,255
|
<p>Hi we have two blog types defined within our shop and they both use the same template right now.</p>
<p>Specifically I want to make changes to just one of the two blogs listing pages (the page where a summary and thumbnail of each blog article is shown).</p>
<p>How can I achieve this? Will this automatically happen if I name the templates to something specific a bit like how wordpress handles templating ?</p>
|
[
{
"answer_id": 74546377,
"author": "Jay",
"author_id": 4068476,
"author_profile": "https://Stackoverflow.com/users/4068476",
"pm_score": 2,
"selected": true,
"text": "/ \\/ ^[^.:\\/]+:\\/\\/([^.]+)\n ^[^.:\\/]+:\\/\\/([^.]+)\\.secondpart\\.thirdpart\\.com$\n ^[^.:\\/]+:\\/\\/([^.]+)(?:\\.[^.]+){3}$\n"
},
{
"answer_id": 74546556,
"author": "Newbie Swift Coder",
"author_id": 16874055,
"author_profile": "https://Stackoverflow.com/users/16874055",
"pm_score": 0,
"selected": false,
"text": "(?:http[s]*\\:\\/\\/)*(.*?)\\.(?=[^\\/]*\\..{2,5})\n"
},
{
"answer_id": 74548926,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 1,
"selected": false,
"text": "^https?://\\K[^\\s./]+\n ^ https?:// \\K [^\\s./]+ . /"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1022861/"
] |
74,546,272
|
<p>My problem with my is to be able to retrieve the returned value (the name of the fund chosen by the user) by the post method in order to use it in my get method. this value will be the name of my ConnectionName</p>
<p>ConnectionName :</p>
<pre class="lang-json prettyprint-override"><code>{
"ConnectionStrings": {
"DefaultConnection": "Server=.\\SQLEXPRESS; Database=Ctisn; Trusted_Connection=True; MultipleActiveResultSets=True;",
"MECLESINE": "Server=myserver; Database=aicha_meclesine; User ID=***; Password=***;",
"FONEES": "Server=myserver; Database=aicha_fonees; User ID=***; Password=***;",
"MECFP": "Server=myserver; Database=aaicha_mecfp; User ID=***; Password=***;",
"MECCT": "Server=myserver; Database=aicha_ct; User ID=***; Password=***;",
"JSR": "Server=myserver; Database=aicha_jsr; User ID=***; Password=***;",
}
</code></pre>
<p>Post and Get Methods :</p>
<pre class="lang-cs prettyprint-override"><code>[Authorize]
[Route("api/[controller]")]
[ApiController]
public class TopClientsController : ControllerBase
{
private readonly IConfiguration \_configuration;
public TopClientsController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpPost("{AdminValue}")]
public JsonResult Post(string AdminValue)
{
return new JsonResult(new { data = AdminValue });
}
[HttpGet]
public JsonResult Get()
{
string query = @"
-------------------My sql requet-----------------
";
var iden;
if (User.IsInRole("Administrator"))
{
// iden = The result of the post methode ;
}
else
{
iden=((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("caisse").Value;
}
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString($"{iden}");
MySqlDataReader myReader;
using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
{
mycon.Open();
using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
{
myReader = myCommand.ExecuteReader();
table.Load(myReader);
myReader.Close();
mycon.Close();
}
}
return new JsonResult(table);
}
}
</code></pre>
<p>I don't know will you understand my idea, but the connection to the database depends on the fund the user belongs to and if it's the admin, he chooses the fund he wants to point to 'send to the API and I get this name I pass it to my get method.</p>
|
[
{
"answer_id": 74546554,
"author": "CthenB",
"author_id": 1885199,
"author_profile": "https://Stackoverflow.com/users/1885199",
"pm_score": 1,
"selected": false,
"text": "[HttpGet]\npublic JsonResult Get([FromUri] string admin)\n{\n}\n"
},
{
"answer_id": 74546649,
"author": "vernou",
"author_id": 2703673,
"author_profile": "https://Stackoverflow.com/users/2703673",
"pm_score": 0,
"selected": false,
"text": "[HttpGet]\npublic JsonResult Get()\n{\n ...\n var postResult = Post(\"foo\");\n ...\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20378743/"
] |
74,546,287
|
<p>In my project, I extracted frames from a video and in another folder I have ground truth for each frame.
I want to map the ground truth image of each frame of a video (in my case, it is saliency prediction ground truth) on its related frame image. As an example I have the following frame:</p>
<p><a href="https://i.stack.imgur.com/QLMDE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QLMDE.png" alt="" /></a></p>
<p>And the following is ground truth mask:</p>
<p><a href="https://i.stack.imgur.com/9BFbI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9BFbI.png" alt="" /></a></p>
<p>and the following is the mapping of ground truth on the frame.</p>
<p><a href="https://i.stack.imgur.com/FcB2m.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FcB2m.jpg" alt="" /></a></p>
<p>How can I do that. Also, I have two folders that inside each of them, there are several folders that inside each of them the there are stored frames. How can I do this operation with these batch data?</p>
<p>This is the hierarchy of my folders:</p>
<p>frame_folder: folder_1, folder_2, ......</p>
<pre><code>├── frames
│ ├── 601 (601 and 602 and etc are folders that in the inside there are image frames that their name is like 0001.png,0002.png, ...)
│ ├── 602
.
.
.
│ └── 700
├── ground truth
│ ├── 601 (601 and 602 and etc are folders that in the inside there are ground truth masks that their name is like 0001.png,0002.png, ...)
│ ├── 602
.
.
.
│ └── 700
</code></pre>
<blockquote>
<p>Update:
Using the answer proposed by @hkchengrex , I faced with an error. When there is only one folder in the paths, it works well but when I put several folders (frames of different videos) based on the question I face with the following error. the details are in below:</p>
</blockquote>
<pre><code> multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "/home/user/miniconda3/envs/vtn/lib/python3.10/multiprocessing/pool.py", line 125, in worker
result = (True, func(*args, **kwds))
TypeError: process_video() takes 1 positional argument but 6 were given
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/user/Video_processing/Saliency_mapping.py", line 69, in <module>
pool.apply(process_video, videos)
File "/home/user/miniconda3/envs/vtn/lib/python3.10/multiprocessing/pool.py", line 357, in apply
return self.apply_async(func, args, kwds).get()
File "/home/user/miniconda3/envs/vtn/lib/python3.10/multiprocessing/pool.py", line 771, in get
raise self._value
TypeError: process_video() takes 1 positional argument but 6 were given
</code></pre>
|
[
{
"answer_id": 74580040,
"author": "hkchengrex",
"author_id": 3237438,
"author_profile": "https://Stackoverflow.com/users/3237438",
"pm_score": 4,
"selected": true,
"text": "multiprocessing.Pool .png import os\nfrom os import path\nimport cv2\nimport numpy as np\n\nfrom argparse import ArgumentParser\nfrom multiprocessing import Pool\n\n\ndef create_overlay(image, mask):\n \"\"\"\n image: H*W*3 numpy array\n mask: H*W numpy array\n If dimensions do not match, the mask is upsampled to match that of the image\n\n Returns a H*W*3 numpy array\n \"\"\"\n h, w = image.shape[:2]\n mask = cv2.resize(mask, dsize=(w,h), interpolation=cv2.INTER_CUBIC)\n\n # color options: https://docs.opencv.org/4.x/d3/d50/group__imgproc__colormap.html\n mask_color = cv2.applyColorMap(mask, cv2.COLORMAP_HOT).astype(np.float32)\n mask = mask[:, :, None] # create trailing dimension for broadcasting\n mask = mask.astype(np.float32)/255\n\n # different other options that you can use to merge image/mask\n overlay = (image*(1-mask)+mask_color*mask).astype(np.uint8)\n # overlay = (image*0.5 + mask_color*0.5).astype(np.uint8)\n # overlay = (image + mask_color).clip(0,255).astype(np.uint8)\n\n return overlay\n\ndef process_video(video_name):\n \"\"\"\n Processing frames in a single video\n \"\"\"\n vid_image_path = path.join(image_path, video_name)\n vid_mask_path = path.join(mask_path, video_name)\n vid_output_path = path.join(output_path, video_name)\n os.makedirs(vid_output_path, exist_ok=True)\n\n frames = sorted(os.listdir(vid_image_path))\n for f in frames:\n image = cv2.imread(path.join(vid_image_path, f))\n mask = cv2.imread(path.join(vid_mask_path, f.replace('.jpg','.png')), cv2.IMREAD_GRAYSCALE)\n overlay = create_overlay(image, mask)\n cv2.imwrite(path.join(vid_output_path, f), overlay)\n\n\nparser = ArgumentParser()\nparser.add_argument('--image_path')\nparser.add_argument('--mask_path')\nparser.add_argument('--output_path')\nargs = parser.parse_args()\n\nimage_path = args.image_path\nmask_path = args.mask_path\noutput_path = args.output_path\n\nif __name__ == '__main__':\n videos = sorted(\n list(set(os.listdir(image_path)).intersection(\n set(os.listdir(mask_path))))\n )\n\n print(f'Processing {len(videos)} videos.')\n\n pool = Pool()\n pool.map(process_video, videos)\n\n print('Done.')\n\n pool.apply pool.map"
},
{
"answer_id": 74584993,
"author": "fmw42",
"author_id": 7355741,
"author_profile": "https://Stackoverflow.com/users/7355741",
"pm_score": 2,
"selected": false,
"text": "import cv2\nimport numpy as np\n\n# read image\nimg = cv2.imread('bullfight.png')\nhh, ww = img.shape[:2]\n\n# read ground truth overlay\noverlay = cv2.imread('truth.png')\n\n# resize the overlay to match the size of the image\nover_resize = cv2.resize(overlay, (ww,hh), fx=0, fy=0, interpolation=cv2.INTER_CUBIC)\n\n# colorize the over_resized image\nover_color = cv2.applyColorMap(over_resize, cv2.COLORMAP_HOT)\n\n# blend over_color and image (adjust weights for different effects)\nresult = cv2.addWeighted(img, 1, over_color, 1, 0)\n\n# save output image\ncv2.imwrite('bullfight_overlay.png', result) \n\n# display images\ncv2.imshow('overcolor', over_color)\ncv2.imshow('result', result)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11140344/"
] |
74,546,288
|
<p>I am checking whether a list in python contains only numeric data. For simple ints and floats I can use the following code:</p>
<p><code>if all(isinstance(x, (int, float)) for x in lstA):</code></p>
<p>If there any easy way to check whether another list is embedded in the first list also containing numeric data?</p>
|
[
{
"answer_id": 74546353,
"author": "oskros",
"author_id": 9490769,
"author_profile": "https://Stackoverflow.com/users/9490769",
"pm_score": 3,
"selected": true,
"text": "def is_all_numeric(lst):\n for elem in lst:\n if isinstance(elem, list):\n if not is_all_numeric(elem):\n return False\n elif not isinstance(elem, (int, float)):\n return False\n return True\n print(is_all_numeric([1,2,3]))\n>>> True\n\nprint(is_all_numeric([1,2,'a']))\n>>> False\n\nprint(is_all_numeric([1,2,[1,2,3]]))\n>>> True\n\nprint(is_all_numeric([1,2,[1,2,'a']]))\n>>> False\n"
},
{
"answer_id": 74546370,
"author": "lemmgua",
"author_id": 20281146,
"author_profile": "https://Stackoverflow.com/users/20281146",
"pm_score": -1,
"selected": false,
"text": "numbers = [1,2,3,4,5,6,7,8]\n\nallListIsNumber = True\n\nfor i in numbers:\n if i.isnumeric() == False:\n allListIsNumber = False\n isnumeric() isinstance()"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11436967/"
] |
74,546,297
|
<p>This query works fine:
<code>$query = "SELECT * from hired WHERE username = 'kaas' and dvd = 'dvd 2'";</code></p>
<p>But then I change it to this query:
<code>$query = "SELECT * from hired WHERE username = " . $_SESSION['name'] . " AND dvd = " . $_POST['dvd'];</code></p>
<p>and it doesn't work, even though the values should be the same as the top query. It goes straight to my error message, <em>You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '2' at line 1</em></p>
<p>The dvd's are having names like 'dvd 1' 'dvd 2' 'dvd 3'. Why is it not working? Is there anything wrong in my query?</p>
<p>I tried to use the query with the data written down instead of using the session and post. It worked as I expected, and showed me an echo.</p>
|
[
{
"answer_id": 74546333,
"author": "Fal",
"author_id": 20581548,
"author_profile": "https://Stackoverflow.com/users/20581548",
"pm_score": -1,
"selected": false,
"text": "$query = \"SELECT * from hired WHERE username = '\" . $_SESSION['name'] . \"'\" . \"AND dvd = '\" . $_POST['dvd'] . \"'\";\n"
},
{
"answer_id": 74546442,
"author": "Hafiz Ameer Hamza",
"author_id": 5938236,
"author_profile": "https://Stackoverflow.com/users/5938236",
"pm_score": -1,
"selected": false,
"text": "$query = \"SELECT * from hired WHERE username = '\" . $_SESSION['name'] . \"' AND dvd = '\".$_POST['dvd'].\"'\";\n"
},
{
"answer_id": 74546510,
"author": "Justinas",
"author_id": 1346234,
"author_profile": "https://Stackoverflow.com/users/1346234",
"pm_score": 1,
"selected": false,
"text": "$query = \"SELECT * from hired WHERE username = :name AND dvd = :dvd\";\n\n$statement = $pdo->prepare($query);\n\n$statement->execute([':name' => $_SESSION['name'], ':dvd' => $_POST['dvd']]);\n$result = $statement->fetchAll();\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581548/"
] |
74,546,355
|
<p>I am beginner to dart. I have tried using regular expression to validate the length of string. But its not working as expected. The {} curly braces indicate a length range in regex. Using {12} means a length of exactly 12, {12,15} means a length of 12 to 15 characters, and {12,} means a length of at least 12 with no upper limit. Because {12,} follows the . character, allowing 12 or more of any character. I have done based on this.</p>
<pre><code> const password = r"dsjRK@#RDsk34$SwedfQWDF";
if (!password.contains(RegExp(r'[a-z]'))) {
print('password should contain atleast lower case character');
} else if (!RegExp(r'[A-Z]').hasMatch(password)) {
print('password should contain atleast lower case character');
} else if (!RegExp(r'[0-9]').hasMatch(password)) {
print('password should contain atleast one digits');
} else if (!RegExp(r'[$@#%&*^!]').hasMatch(password)) {
print('password should contain atleast one special charatcer');
} else if (!RegExp(r'.{12,15}').hasMatch(password)) {
print('password atleast 12 max 15 digits');
} else {
print("Perfect Password");
}
</code></pre>
<p>OutPUT:
<strong>Perfect Password</strong></p>
<p>We can use some other solutions also . But my doubt is min length validation is working , why maximum validation is not working ?Please help me to understand the issue.</p>
|
[
{
"answer_id": 74546577,
"author": "Robert Sandberg",
"author_id": 13263384,
"author_profile": "https://Stackoverflow.com/users/13263384",
"pm_score": 0,
"selected": false,
"text": "{12, 15} const password = r\"dsjRK@#RDsk34$SwedfQWDF\";\n if (!RegExp(r'[a-z]').hasMatch(password)) {\n print('password should contain at least one lower case character');\n } else if (!RegExp(r'[A-Z]').hasMatch(password)) {\n print('password should contain at least lower case character');\n } else if (!RegExp(r'[0-9]').hasMatch(password)) {\n print('password should contain at least one digits');\n } else if (!RegExp(r'[$@#%&*^!]').hasMatch(password)) {\n print('password should contain at least one special charatcer');\n } else if (password.length < 12) {\n print('password at least 12 characters');\n } else if (password.length > 15) {\n print('password should have max 15 characters');\n } else {\n print(\"Perfect Password\");\n }\n"
},
{
"answer_id": 74560259,
"author": "Gicu Aftene",
"author_id": 18811731,
"author_profile": "https://Stackoverflow.com/users/18811731",
"pm_score": 2,
"selected": true,
"text": "r'^.{12,15}$' else if (!RegExp(r'^.{12,15}$').hasMatch(password){\n print('password atleast 12 max 15 digits');\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8609394/"
] |
74,546,372
|
<p>Trying to make a free food finder but get unknown error</p>
<p>I'm trying to make this code to get every free product in this food delivery restaurant
I expect it to iterate through this 'hbaEIe.sc-5674cfe4-2' elements, that look like this:
<a href="https://i.stack.imgur.com/wMoZb.png" rel="nofollow noreferrer">Restaurant div</a></p>
<pre><code>url = 'https://www.rappi.com.ar/restaurantes'
for restaurant in all_restaurant:
link = restaurant.get_attribute("href")
full_link = base_url + link
name = restaurant.get_attribute("aria-label")
# open tab
driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.CONTROL + 't')
# Load a page
driver.get(full_link)
getFreeStuff(name, full_link)
# close the tab
driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.CONTROL + 'w')
print(name)
</code></pre>
<p>Then, for each restaurant i want to iterate through all the product list and get the price, comparing it to 0.</p>
<pre><code>def getFreeStuff(restaurant, link):
time.sleep(1)
prices = driver.find_elements(By.CLASS_NAME, "css-kowr8")
names = driver.find_elements(By.CLASS_NAME, "css-puxjan")
for i in range(0, len(prices)):
price = prices[i]
if price == "$ 0,00":
restaurants.append(restaurant)
links.append(link)
products.append(names[i])
return 0
</code></pre>
<p>But when i run it it gives me the following error:</p>
<pre><code>BOULEVARD HONORIO
Traceback (most recent call last):
File "C:\Users\Usuario\Desktop\Web Scraping\practica2\main.py", line 39, in <module>
link = restaurant.get_attribute("href")
File "C:\Users\Usuario\Desktop\Web Scraping\practica1\venv\lib\site-packages\selenium\webdriver\remote\webelement.py", line 155, in get_attribute
attribute_value = self.parent.execute_script(...
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=107.0.5304.107)
Stacktrace:
Backtrace:
Ordinal0 [0x00A3ACD3+2075859]
Ordinal0 [0x009CEE61+1633889]
...
RtlGetAppContainerNamedObjectPath [0x771A7B8E+238]
Process finished with exit code 1
</code></pre>
<p>I've tried many things, but i don't know how to proceed</p>
|
[
{
"answer_id": 74546577,
"author": "Robert Sandberg",
"author_id": 13263384,
"author_profile": "https://Stackoverflow.com/users/13263384",
"pm_score": 0,
"selected": false,
"text": "{12, 15} const password = r\"dsjRK@#RDsk34$SwedfQWDF\";\n if (!RegExp(r'[a-z]').hasMatch(password)) {\n print('password should contain at least one lower case character');\n } else if (!RegExp(r'[A-Z]').hasMatch(password)) {\n print('password should contain at least lower case character');\n } else if (!RegExp(r'[0-9]').hasMatch(password)) {\n print('password should contain at least one digits');\n } else if (!RegExp(r'[$@#%&*^!]').hasMatch(password)) {\n print('password should contain at least one special charatcer');\n } else if (password.length < 12) {\n print('password at least 12 characters');\n } else if (password.length > 15) {\n print('password should have max 15 characters');\n } else {\n print(\"Perfect Password\");\n }\n"
},
{
"answer_id": 74560259,
"author": "Gicu Aftene",
"author_id": 18811731,
"author_profile": "https://Stackoverflow.com/users/18811731",
"pm_score": 2,
"selected": true,
"text": "r'^.{12,15}$' else if (!RegExp(r'^.{12,15}$').hasMatch(password){\n print('password atleast 12 max 15 digits');\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17411396/"
] |
74,546,438
|
<p>I have a file with following lines:</p>
<pre><code>2022-Nov-23
2021-Jul-14
</code></pre>
<p>I want to replace the month with its number, my script should accept the date as an argument, and I added these variables to it:</p>
<pre><code>Jan=01
Feb=02
Mar=03
Apr=04
May=05
Jun=06
Jul=07
Aug=08
Sep=09
Oct=10
Nov=11
Dec=12
</code></pre>
<p>How can I match the month name in the string with regex and substitute it based on the variables? here is what I have for now:</p>
<p>echo "$1" | sed 's/(\w{3})/${\1}/'</p>
<p>But it doesn't work.</p>
|
[
{
"answer_id": 74546577,
"author": "Robert Sandberg",
"author_id": 13263384,
"author_profile": "https://Stackoverflow.com/users/13263384",
"pm_score": 0,
"selected": false,
"text": "{12, 15} const password = r\"dsjRK@#RDsk34$SwedfQWDF\";\n if (!RegExp(r'[a-z]').hasMatch(password)) {\n print('password should contain at least one lower case character');\n } else if (!RegExp(r'[A-Z]').hasMatch(password)) {\n print('password should contain at least lower case character');\n } else if (!RegExp(r'[0-9]').hasMatch(password)) {\n print('password should contain at least one digits');\n } else if (!RegExp(r'[$@#%&*^!]').hasMatch(password)) {\n print('password should contain at least one special charatcer');\n } else if (password.length < 12) {\n print('password at least 12 characters');\n } else if (password.length > 15) {\n print('password should have max 15 characters');\n } else {\n print(\"Perfect Password\");\n }\n"
},
{
"answer_id": 74560259,
"author": "Gicu Aftene",
"author_id": 18811731,
"author_profile": "https://Stackoverflow.com/users/18811731",
"pm_score": 2,
"selected": true,
"text": "r'^.{12,15}$' else if (!RegExp(r'^.{12,15}$').hasMatch(password){\n print('password atleast 12 max 15 digits');\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11586574/"
] |
74,546,453
|
<p>I have inputs like 999,9999,10999. I want to replace first digits except last two by XXX in angular template.
That is 999 should become X99,9999 should XX99 and 10999 should XXX99.</p>
<p>How to do that is there any pipe?</p>
|
[
{
"answer_id": 74546536,
"author": "Chaitanya Karmarkar",
"author_id": 12182265,
"author_profile": "https://Stackoverflow.com/users/12182265",
"pm_score": 0,
"selected": false,
"text": "import { Pipe, PipeTransform } from '@angular/core';\n\n@Pipe({\n name: 'xMask'\n})\nexport class XMaskPipe implements PipeTransform {\n\n transform(value: number): any {\n\nif ((!isNaN(value)) && (value != 0)) {\n var currencySymbol = '₹';\n //var output = Number(input).toLocaleString('en-IN'); <-- This method is not working fine in all browsers! \n var result = value.toString().split('.');\n\n var lastThree = result[0].substring(result[0].length - 3);\n var otherNumbers = result[0].substring(0, result[0].length - 3);\n if (otherNumbers != '')\n lastThree = ',' + lastThree;\n var output = otherNumbers.replace(/\\B(?=(\\d{2})+(?!\\d))/g, \",\") + lastThree;\n\n if (result.length > 1) {\n output += \".\" + result[1];\n }\n\n const visibleDigits = 2;\n let maskedSection = output.slice(0, -visibleDigits);\n let visibleSection = output.slice(-visibleDigits);\n return currencySymbol + maskedSection.replace(/./g, 'X') + visibleSection;\n }\n\n }\n\n\n\n}\n"
},
{
"answer_id": 74546580,
"author": "Sajeetharan",
"author_id": 1749403,
"author_profile": "https://Stackoverflow.com/users/1749403",
"pm_score": 1,
"selected": false,
"text": "import { Pipe, PipeTransform } from '@angular/core';\n@Pipe({\n name: 'specialPipe'\n})\nexport class specialPipe implements PipeTransform {\n\n transform(value: string): string {\n let newVal = value.replace(/\\d{2}$/, 'XX');\n return newVal;\n }\n \n}\n <hello name=\"{{ name1 |specialPipe }}\"></hello>\n"
},
{
"answer_id": 74546946,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 2,
"selected": true,
"text": "@Pipe({\n pure: true,\n name: 'xMask'\n})\nexport class XMaskPipe implements PipeTransform {\n transform(value: string): string {\n return `${'X'.repeat(value.length - 2)}${value.slice(-2)}`;\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12182265/"
] |
74,546,455
|
<p>When looking for a secure random password generator in Python I came across this script:</p>
<pre><code># necessary imports
import secrets
import string
# define the alphabet
letters = string.ascii_letters
digits = string.digits
special_chars = string.punctuation
alphabet = letters + digits + special_chars
# fix password length
pwd_length = 12
# generate a password string
pwd = ''
for i in range(pwd_length):
pwd += ''.join(secrets.choice(alphabet))
print(pwd)
# generate password meeting constraints
while True:
pwd = ''
for i in range(pwd_length):
pwd += ''.join(secrets.choice(alphabet))
if (any(char in special_chars for char in pwd) and
sum(char in digits for char in pwd)>=2):
break
print(pwd)
</code></pre>
<p>Source: <a href="https://geekflare.com/password-generator-python-code/" rel="nofollow noreferrer">How to Create a Random Password Generator in Python - Geekflare</a>
There is one thing that is unclear to me in the final "if" statement, which checks if the generated password meets certain constraints.</p>
<p>The expression is:</p>
<pre><code>char in special_chars for char in pwd
</code></pre>
<p>I understand, that "in" can either check if something is part of an iterable or be part of the "for in" statement that generates a loop from an iterable.</p>
<p>But what I do not understand is how these both are interacting here. To me it looks as if "char in special_chars" checks if the second "char", defined in "for char in pwd", is part of special_chars.</p>
<p>But: how does the first "char" gets defined before the "char" in "for in" gets defined? I always thought that a variable could not be accessed before it gets defined. This example looks to me as if Python behaves differently. Could anybody explain this to me?</p>
|
[
{
"answer_id": 74546536,
"author": "Chaitanya Karmarkar",
"author_id": 12182265,
"author_profile": "https://Stackoverflow.com/users/12182265",
"pm_score": 0,
"selected": false,
"text": "import { Pipe, PipeTransform } from '@angular/core';\n\n@Pipe({\n name: 'xMask'\n})\nexport class XMaskPipe implements PipeTransform {\n\n transform(value: number): any {\n\nif ((!isNaN(value)) && (value != 0)) {\n var currencySymbol = '₹';\n //var output = Number(input).toLocaleString('en-IN'); <-- This method is not working fine in all browsers! \n var result = value.toString().split('.');\n\n var lastThree = result[0].substring(result[0].length - 3);\n var otherNumbers = result[0].substring(0, result[0].length - 3);\n if (otherNumbers != '')\n lastThree = ',' + lastThree;\n var output = otherNumbers.replace(/\\B(?=(\\d{2})+(?!\\d))/g, \",\") + lastThree;\n\n if (result.length > 1) {\n output += \".\" + result[1];\n }\n\n const visibleDigits = 2;\n let maskedSection = output.slice(0, -visibleDigits);\n let visibleSection = output.slice(-visibleDigits);\n return currencySymbol + maskedSection.replace(/./g, 'X') + visibleSection;\n }\n\n }\n\n\n\n}\n"
},
{
"answer_id": 74546580,
"author": "Sajeetharan",
"author_id": 1749403,
"author_profile": "https://Stackoverflow.com/users/1749403",
"pm_score": 1,
"selected": false,
"text": "import { Pipe, PipeTransform } from '@angular/core';\n@Pipe({\n name: 'specialPipe'\n})\nexport class specialPipe implements PipeTransform {\n\n transform(value: string): string {\n let newVal = value.replace(/\\d{2}$/, 'XX');\n return newVal;\n }\n \n}\n <hello name=\"{{ name1 |specialPipe }}\"></hello>\n"
},
{
"answer_id": 74546946,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 2,
"selected": true,
"text": "@Pipe({\n pure: true,\n name: 'xMask'\n})\nexport class XMaskPipe implements PipeTransform {\n transform(value: string): string {\n return `${'X'.repeat(value.length - 2)}${value.slice(-2)}`;\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10006567/"
] |
74,546,461
|
<p>So i have this inside a text file :</p>
<p><code>"00:00:25,58 --> 00:00:27,91 (DRAMATIC MUSIC PLAYING)"</code></p>
<p>I want to remove characters inside and including the braces itself so :</p>
<p><code>"00:00:25,58 --> 00:00:27,91 "</code></p>
<pre><code>
eng_sub = open(text).read()
eng_sub2 = re.sub("\(", "", eng_sub)
new_eng_sub = re.sub("\)", "", eng_sub2)
open(text, "w").write(new_eng_sub)
</code></pre>
<p>I've tried using sub() and it removes a character but what i really want to do is manipulate characters between those 2 (i.e. "(" , ")") characters.</p>
<p>I don't know how to do it. thank you for your help.</p>
|
[
{
"answer_id": 74546536,
"author": "Chaitanya Karmarkar",
"author_id": 12182265,
"author_profile": "https://Stackoverflow.com/users/12182265",
"pm_score": 0,
"selected": false,
"text": "import { Pipe, PipeTransform } from '@angular/core';\n\n@Pipe({\n name: 'xMask'\n})\nexport class XMaskPipe implements PipeTransform {\n\n transform(value: number): any {\n\nif ((!isNaN(value)) && (value != 0)) {\n var currencySymbol = '₹';\n //var output = Number(input).toLocaleString('en-IN'); <-- This method is not working fine in all browsers! \n var result = value.toString().split('.');\n\n var lastThree = result[0].substring(result[0].length - 3);\n var otherNumbers = result[0].substring(0, result[0].length - 3);\n if (otherNumbers != '')\n lastThree = ',' + lastThree;\n var output = otherNumbers.replace(/\\B(?=(\\d{2})+(?!\\d))/g, \",\") + lastThree;\n\n if (result.length > 1) {\n output += \".\" + result[1];\n }\n\n const visibleDigits = 2;\n let maskedSection = output.slice(0, -visibleDigits);\n let visibleSection = output.slice(-visibleDigits);\n return currencySymbol + maskedSection.replace(/./g, 'X') + visibleSection;\n }\n\n }\n\n\n\n}\n"
},
{
"answer_id": 74546580,
"author": "Sajeetharan",
"author_id": 1749403,
"author_profile": "https://Stackoverflow.com/users/1749403",
"pm_score": 1,
"selected": false,
"text": "import { Pipe, PipeTransform } from '@angular/core';\n@Pipe({\n name: 'specialPipe'\n})\nexport class specialPipe implements PipeTransform {\n\n transform(value: string): string {\n let newVal = value.replace(/\\d{2}$/, 'XX');\n return newVal;\n }\n \n}\n <hello name=\"{{ name1 |specialPipe }}\"></hello>\n"
},
{
"answer_id": 74546946,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 2,
"selected": true,
"text": "@Pipe({\n pure: true,\n name: 'xMask'\n})\nexport class XMaskPipe implements PipeTransform {\n transform(value: string): string {\n return `${'X'.repeat(value.length - 2)}${value.slice(-2)}`;\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581562/"
] |
74,546,474
|
<p>I need to flat arrays but i can't to use flat().</p>
<p>First check example of my arrays</p>
<pre><code>let arr = [
['test1' , 'test1'],
['test2' , 'test2'],
['test3', true],
['test4' , false]
];
</code></pre>
<p>What is problem here?</p>
<p>I need to get only first item 'test1' , 'test2', 'test3', 'test4' and push to one array</p>
<p>After that I want to my array be;</p>
<p>['test1' , 'test2' , 'test3' , 'test4' ];</p>
<p>What I'm try:</p>
<pre><code>let arr = [
['test1' , 'test1'],
['test2' , 'test2'],
['test3', true],
['test4' , false]
];
</code></pre>
<p>let newArr = arr.flat();</p>
<p>but I got all items not first index in each array</p>
|
[
{
"answer_id": 74546489,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 0,
"selected": false,
"text": "Array.map() Array.flat() let arr = [\n ['test1' , 'test1'],\n ['test2' , 'test2'],\n ['test3', true],\n ['test4' , false]\n];\n\nlet result = arr.map(i => i[0]).flat()\nconsole.log(result)"
},
{
"answer_id": 74546490,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 2,
"selected": false,
"text": "Array#map const arr = [ ['test1' , 'test1'], ['test2' , 'test2'], ['test3', true], ['test4' , false] ];\n\nconst res = arr.map(([ e ]) => e);\n\nconsole.log(res);"
},
{
"answer_id": 74547430,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 0,
"selected": false,
"text": "let arr = [\n ['test1' , 'test1'],\n ['test2' , 'test2'],\n ['test3', true],\n ['test4' , false]\n];\n\nconsole.log(arr.map(innerArr => innerArr[0]));"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20448930/"
] |
74,546,493
|
<p>I am managing around 12 TYPO3 backends with almost similar content. Is it possible to copy and paste a created site between independent backends? Right now I'm creating by hand 12 sites with the same content. There has to be an easier way.</p>
<p>Well, there is not much I could try. Within TYPO3 I don't see any option to export/import sites from other backends.</p>
|
[
{
"answer_id": 74546871,
"author": "Bernd Wilke πφ",
"author_id": 6796354,
"author_profile": "https://Stackoverflow.com/users/6796354",
"pm_score": 0,
"selected": false,
"text": "fileadmin/ uploads/ typo3conf/ typo3conf/LocalConfiguration.php typo3conf/AdditionalConfiguration.php"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581665/"
] |
74,546,501
|
<p>I'm trying to replace an array in a JSON file using C# .net 6.0</p>
<p>There is such a JSON file:</p>
<pre><code>{
...
"exchange":{
...
"pair_whitelist": [
"EOS3S/USDT",
"ACH/USDT",
"SOC/USDT"]
...
}
...
}
</code></pre>
<p>I want to replace this "pair_whitelist" array with another array</p>
<pre><code>"pair_whitelist": [
"SKM/USDT",
"NEW/USDT",
"XEC/USDT"]
</code></pre>
<p>How should I do it?</p>
<p>My attempt was as follows</p>
<pre><code>public static dynamic GetJSONFromFile_dynamic(string path)
{
var data = File.ReadAllText(path);
return JsonSerializer.Deserialize<ExpandoObject>(data);
}
...
var config = GetJSONFromFile_dynamic(path_to_JSON_file);
dynamic a = config.exchange.pair_whitelist;
</code></pre>
<p>But I got the following error: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.Text.Json.JsonElement' does not contain a definition for 'pair_whitelist''</p>
<p>How to change the value of the pair_whitelist array?</p>
|
[
{
"answer_id": 74546571,
"author": "Prasad Telkikar",
"author_id": 6299857,
"author_profile": "https://Stackoverflow.com/users/6299857",
"pm_score": 3,
"selected": true,
"text": "JObject.Parse() JObject jObject = JObject.Parse(File.ReadAllText(path_to_JSON_file));\n\nif(jObject[\"exchange\"]?[\"pair_whitelist\"] != null) //Check key exists before update\n jObject[\"exchange\"][\"pair_whitelist\"] = [\"Stack\", \"Overflow\"];\n"
},
{
"answer_id": 74546646,
"author": "Magnus",
"author_id": 468973,
"author_profile": "https://Stackoverflow.com/users/468973",
"pm_score": 2,
"selected": false,
"text": "JsonNode System.Text.Json var json = @\"{\n\"\"exchange\"\":{\n \"\"pair_whitelist\"\": [\n \"\"EOS3S/USDT\"\",\n \"\"ACH/USDT\"\",\n \"\"SOC/USDT\"\"]\n }\n}\";\nvar node = JsonNode.Parse(json);\nnode[\"exchange\"][\"pair_whitelist\"] = new JsonArray(\"SKM/USDT\", \"NEW/USDT\", \"XEC/USDT\");\n\nvar newJson = node.ToJsonString();\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7479675/"
] |
74,546,505
|
<p>In the main component I want to pass the title and price via props, why doesn't it work?</p>
<p>What did I miss?</p>
<p><a href="https://i.stack.imgur.com/pTjDm.png" rel="nofollow noreferrer">enter image description here</a></p>
<p><a href="https://i.stack.imgur.com/JwxaG.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////</p>
<pre><code>const Categories = () => {
return (
<div className="content__items">
<PizzaBlock title="Мексиканская" price="500"/>
<PizzaBlock title="Мексиканская" price="500"/>
<PizzaBlock/>
</div>
)
}
</code></pre>
<pre><code>const PizzaBlock = (props) => {
const [pizzaItem, setpizzaItem] = useState([{
title: 'Вегатарианская',
price: '499р',
id: '1'
}]);
return (
<div className="pizza-block">
<img
className="pizza-block__image"
src="https://dodopizza-a.akamaihd.net/static/Img/Products/Pizza/ru-RU/b750f576-4a83-48e6-a283-5a8efb68c35d.jpg"
alt="Pizza"
/>
{pizzaItem.map((item) => (
<PizzaItemBlock key={item.id} {...item}/>
))}
</div>
)
}
</code></pre>
<pre><code>const PizzaItemBlock = ({title,price}) => {
return (
<>
<h4 className="pizza-block__title">{title}</h4>
<div className="pizza-block__selector">
<ul>
<li className="active">тонкое</li>
<li>традиционное</li>
</ul>
<ul>
<li className="active">26 см.</li>
<li>30 см.</li>
<li>40 см.</li>
</ul>
</div>
<div className="pizza-block__bottom">
<div className="pizza-block__price">{price}</div>
<div className="button button--outline button--add">
<svg
width="12"
height="12"
viewBox="0 0 12 12"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M10.8 4.8H7.2V1.2C7.2 0.5373 6.6627 0 6 0C5.3373 0 4.8 0.5373 4.8 1.2V4.8H1.2C0.5373 4.8 0 5.3373 0 6C0 6.6627 0.5373 7.2 1.2 7.2H4.8V10.8C4.8 11.4627 5.3373 12 6 12C6.6627 12 7.2 11.4627 7.2 10.8V7.2H10.8C11.4627 7.2 12 6.6627 12 6C12 5.3373 11.4627 4.8 10.8 4.8Z"
fill="white"
/>
</svg>
<span>Добавить</span>
<i>2</i>
</div>
</div>
</>
)
}
</code></pre>
|
[
{
"answer_id": 74546571,
"author": "Prasad Telkikar",
"author_id": 6299857,
"author_profile": "https://Stackoverflow.com/users/6299857",
"pm_score": 3,
"selected": true,
"text": "JObject.Parse() JObject jObject = JObject.Parse(File.ReadAllText(path_to_JSON_file));\n\nif(jObject[\"exchange\"]?[\"pair_whitelist\"] != null) //Check key exists before update\n jObject[\"exchange\"][\"pair_whitelist\"] = [\"Stack\", \"Overflow\"];\n"
},
{
"answer_id": 74546646,
"author": "Magnus",
"author_id": 468973,
"author_profile": "https://Stackoverflow.com/users/468973",
"pm_score": 2,
"selected": false,
"text": "JsonNode System.Text.Json var json = @\"{\n\"\"exchange\"\":{\n \"\"pair_whitelist\"\": [\n \"\"EOS3S/USDT\"\",\n \"\"ACH/USDT\"\",\n \"\"SOC/USDT\"\"]\n }\n}\";\nvar node = JsonNode.Parse(json);\nnode[\"exchange\"][\"pair_whitelist\"] = new JsonArray(\"SKM/USDT\", \"NEW/USDT\", \"XEC/USDT\");\n\nvar newJson = node.ToJsonString();\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20419637/"
] |
74,546,524
|
<p>I'm working through a task where I need to bind a few survey datasets, but unfortunately the survey questions are inconsistently numbered (wording is consistent). To solve this, I want to drop the question number from the start of each question.</p>
<p>Currently I am doing this manually with <code>rename()</code>, but it is time consuming to repeat for every question across each dataset. Any tips to do this in a quicker, more efficient way?</p>
<p>Here's an example dataset and my current process:</p>
<pre class="lang-r prettyprint-override"><code>df1 <- data.frame(ID = c(1, 2, 3, 4, 5),
`1. First Question` = c('a', 'b', 'c', 'd', 'e'),
`2. Second Question` = c(1, 1, 3, 0, 1),
`3. Third Question` = c(1, 2, 0, 2, 1),
Year = 2021) %>%
rename(`First Question` = `1. First Question`,
`Second Question` = `2. Second Question`,
`Third Question` = `3. Third Question`)
df2 <- data.frame(ID = c(1, 2, 3, 4, 5),
`1. First Question` = c('a', 'b', 'c', 'd', 'e'),
`2. Third Question` = c(2, 1, 3, 1, 2),
`3. Second Question` = c(2, 2, 1, 3, 2),
Year = 2022) %>%
rename(`First Question` = `1. First Question`,
`Second Question` = `3. Second Question`,
`Third Question` = `2. Third Question`)
end_df <- rbind(df1, df2)
</code></pre>
|
[
{
"answer_id": 74546691,
"author": "Chris Ruehlemann",
"author_id": 8039978,
"author_profile": "https://Stackoverflow.com/users/8039978",
"pm_score": 2,
"selected": false,
"text": "rename_with sub df1 %>%\n rename_with(~ sub(\"^X\\\\d\\\\.\\\\.\", \"\", .))\n ID First.Question Second.Question Third.Question Year\n1 1 a 1 1 2021\n2 2 b 1 2 2021\n3 3 c 3 0 2021\n4 4 d 0 2 2021\n5 5 e 1 1 2021\n list list(df1, df2) %>%\n map(rename_with, ~ sub(\"^X\\\\d\\\\.\\\\.\", \"\", .))\n df1 <- data.frame(ID = c(1, 2, 3, 4, 5),\n `1. First Question` = c('a', 'b', 'c', 'd', 'e'),\n `2. Second Question` = c(1, 1, 3, 0, 1),\n `3. Third Question` = c(1, 2, 0, 2, 1),\n Year = 2021)\n\ndf2 <- data.frame(ID = c(1, 2, 3, 4, 5),\n `1. First Question` = c('a', 'b', 'c', 'd', 'e'),\n `2. Third Question` = c(2, 1, 3, 1, 2),\n `3. Second Question` = c(2, 2, 1, 3, 2),\n Year = 2022)\n"
},
{
"answer_id": 74546709,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "stringr::str_remove() dplyr::rename_with() library(purrr)\nlibrary(dplyr)\nlibrary(stringr)\n\nlist(df1, df2) %>%\n map(rename_with, ~ str_remove(.x, \"^\\\\d\\\\.\\\\s\")) %>%\n bind_rows()\n # A tibble: 10 × 5\n ID `First Question` `Second Question` `Third Question` Year\n <dbl> <chr> <dbl> <dbl> <dbl>\n 1 1 a 1 1 2021\n 2 2 b 1 2 2021\n 3 3 c 3 0 2021\n 4 4 d 0 2 2021\n 5 5 e 1 1 2021\n 6 1 a 2 2 2022\n 7 2 b 2 1 2022\n 8 3 c 1 3 2022\n 9 4 d 3 1 2022\n10 5 e 2 2 2022\n"
},
{
"answer_id": 74547079,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 2,
"selected": false,
"text": "colnames(df1)[2:4] <- sub(\"^[0-9]\\\\. \", \"\", colnames(df1)[2:4])\ncolnames(df2)[2:4] <- sub(\"^[0-9]\\\\. \", \"\", colnames(df2)[2:4])\n\nrbind(df1, df2)\n ID First Question Second Question Third Question Year\n1 1 a 1 1 2021\n2 2 b 1 2 2021\n3 3 c 3 0 2021\n4 4 d 0 2 2021\n5 5 e 1 1 2021\n6 1 a 2 2 2022\n7 2 b 2 1 2022\n8 3 c 1 3 2022\n9 4 d 3 1 2022\n10 5 e 2 2 2022\n check.names = F X1..First.Question df1 <- data.frame(ID = c(1, 2, 3, 4, 5),\n `1. First Question` = c('a', 'b', 'c', 'd', 'e'),\n `2. Second Question` = c(1, 1, 3, 0, 1),\n `3. Third Question` = c(1, 2, 0, 2, 1),\n Year = 2021, check.names = F)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18878494/"
] |
74,546,534
|
<p>I have a bigger app named X and I have another smaller one named Y.
they are right now separate from each other and they are working fine.
I want to integrate app Y in X. I want to put codes of Y in X project but they should have a different Main so I can set different themes and routes.
Is there anyway to do that?</p>
<p>////update////</p>
<p>I upvoted all answers because they are all correct.</p>
<p>but if you know this one please answer.
I am using GetMaterialApp from GetX instead of MaterialApp.
and it returns error</p>
<blockquote>
<p>'package:flutter/src/widgets/framework.dart': Failed assertion: line 5334 pos 14: '_dependents.isEmpty': is not true.</p>
</blockquote>
<p>how can I fix this?</p>
|
[
{
"answer_id": 74546684,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 3,
"selected": true,
"text": "MaterialApp() InheritedWidget Theme Navigator MediaQuery /*...*/\n MaterialApp(\n /*...*/\n home: AppXHome(),\n ),\n /*...*/\n\nclass AppXHome extends StatelessWidegt { \n @override\n Widget build(BuildContext context) {\n return Column(\n children: <Widget>[\n Container(),\n Container(),\n MaterialApp(\n home: AppYHome(),\n ),\n ],\n ),}}\n"
},
{
"answer_id": 74546779,
"author": "blackkara",
"author_id": 1281180,
"author_profile": "https://Stackoverflow.com/users/1281180",
"pm_score": 1,
"selected": false,
"text": "main"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14729488/"
] |
74,546,557
|
<p>I would like to copy all files from a folder in my docker build context. The files in the folder are mixed with different owners and groups (e.g. UID=400 GUID=800 etc.), which I need to preserve (I also need to preserve timestamps, etc.)</p>
<p>So basically I need a 1:1 copy of the files to my docker image.</p>
<p>When I use ADD/COPY, it doesn't preserve any the owner/group IDs which is also stated in the documentation. (defaults to 0)</p>
<p>I have made a workaround which uses rsync (-a) with localhost, but it's not an ideal solution.
I could also use the docker cp command and commit the image but I would like to use this in my dockerfile.</p>
<p>Is there any way to do this?
(Docker Version 20.10.16-r2)</p>
<p>Edit:
I have also tried</p>
<pre><code>RUN --mount=type=bind,source=myfiles,target=/myfiles cp -ar /myfiles/* /container_target/
</code></pre>
<p>but this doesn't preserve owner, etc. neither</p>
<p>EDIT:
I am using <code>DOCKER_BUILDKIT=1</code></p>
|
[
{
"answer_id": 74546684,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 3,
"selected": true,
"text": "MaterialApp() InheritedWidget Theme Navigator MediaQuery /*...*/\n MaterialApp(\n /*...*/\n home: AppXHome(),\n ),\n /*...*/\n\nclass AppXHome extends StatelessWidegt { \n @override\n Widget build(BuildContext context) {\n return Column(\n children: <Widget>[\n Container(),\n Container(),\n MaterialApp(\n home: AppYHome(),\n ),\n ],\n ),}}\n"
},
{
"answer_id": 74546779,
"author": "blackkara",
"author_id": 1281180,
"author_profile": "https://Stackoverflow.com/users/1281180",
"pm_score": 1,
"selected": false,
"text": "main"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1176008/"
] |
74,546,563
|
<p>So, i am running a java project which have many library that are available in the current working directory but VS code seems to not recognize these library and giving out error "The import ###### cannot be resolved" ex: The import org.apache.pdfbox.pdmodel.PDDocument cannot be resolved"</p>
<p>here is the image that might help you to know more about it
<a href="https://i.stack.imgur.com/ki9O3.png" rel="nofollow noreferrer">This is the package that i am working on :</a>
Here the org/apache is the library contain the class file that are need to be imported and FileArrangement.java is the file having the import statements</p>
<p><a href="https://i.stack.imgur.com/TSkTX.png" rel="nofollow noreferrer">Error i have been receiving</a>
this is what VS code is been showing</p>
<p>i really need your help because i really don't have any idea how to correct this</p>
<p>I have checked other projects and they are also showing the same result although the import statements for java classes like . java.util.ArrayList doesn't show any kind of error and i have tried to clean java in VS code it also didn't work</p>
<p>i just need to correct this error of VS code to import the classes that i need
<a href="https://i.stack.imgur.com/0FgMA.png" rel="nofollow noreferrer">No error on java.util package</a></p>
|
[
{
"answer_id": 74556153,
"author": "JialeDu",
"author_id": 19133920,
"author_profile": "https://Stackoverflow.com/users/19133920",
"pm_score": 0,
"selected": false,
"text": "java.project.referencedLibraries \"java.project.referencedLibraries\": [\n \"library/**/*.jar\",\n \"/home/username/lib/foo.jar\"\n]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16325891/"
] |
74,546,581
|
<p>I'm trying to send a message to my group at defined time intervals, but I get a warning in the output the first time I try to send the message. Next times no warning, but nothing is posted in the group. I'm the owner of the group so in theory there shouldn't be any permissions issues.</p>
<p><strong>Code</strong></p>
<pre class="lang-py prettyprint-override"><code>from telethon import TelegramClient
import schedule
def sendImage():
apiId = 1111111
apiHash = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
phone = "+111111111111"
client = TelegramClient(phone, apiId, apiHash)
toChat = 1641242898
client.start()
print("Sending...")
client.send_file(toChat, "./image.jpg", caption="Write text here")
client.disconnect()
return
def main():
schedule.every(10).seconds.do(sendImage)
while True:
schedule.run_pending()
if __name__ == "__main__":
main()
</code></pre>
<p><strong>Output</strong></p>
<pre><code>Sending...
RuntimeWarning: coroutine 'UploadMethods.send_file' was never awaited
client.send_file(toChat, "./image.jpg", caption="Write text here")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Sending...
Sending...
Sending...
</code></pre>
|
[
{
"answer_id": 74546733,
"author": "Dan Nagle",
"author_id": 2202018,
"author_profile": "https://Stackoverflow.com/users/2202018",
"pm_score": -1,
"selected": false,
"text": "try:\n client = TelegramClient(...)\n client.start()\nexcept Exception as e:\n print(f\"Exception while starting the client - {e}\")\nelse:\n try:\n ret_value = await client.send_file(...)\n except Exception as e:\n print(f\"Exception while sending the message - {e}\")\n else:\n print(f\"Message sent. Return Value {ret_value}\")\n"
},
{
"answer_id": 74551206,
"author": "Lonami",
"author_id": 4759433,
"author_profile": "https://Stackoverflow.com/users/4759433",
"pm_score": 0,
"selected": false,
"text": "asyncio schedule asyncio asyncio schedule asyncio import asyncio\nfrom telethon import TelegramClient\n\ndef send_image():\n ...\n client = TelegramClient(phone, apiId, apiHash)\n\n await client.start()\n await client.send_file(toChat, \"./image.jpg\", caption=\"Write text here\")\n await client.disconnect()\n\nasync def main():\n while True: # forever\n await send_image() # send image, then\n await asyncio.sleep(10) # sleep 10 seconds\n\n # this is essentially \"every 10 seconds call send_image\"\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n start() main"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13846064/"
] |
74,546,696
|
<p>So, i have been trying to build a python number guessing game. I am new, and i can't figure out how i add +1 to my chance variable. I have tried +=1 like here but it always shows 1 as the output no matter what. And i know that there is a lot of things wrong with this code but, keep in mind that i am new to coding.</p>
<pre class="lang-py prettyprint-override"><code>import random
numbers = 1,2,3,4,5,6,7,8,9,10
user = None
hidden = random.choice(numbers)
print("Welcome to volty's's number guessing game!")
def game():
chance = 0
user = int(input("choose a number from 1 to 10: "))
if user > hidden:
print ("ur number is more than the hidden number")
game()
chance += 1
elif user < hidden:
print ("ur number is less than the hidden number")
game()
chance = +1
elif user == hidden:
print (" u guessed the hidden number!")
print ("the hidden number was:",hidden)
print (f"u guessed it in {chance +1} step {'s' if chance > 1 else ' '}")
game()
</code></pre>
<p>So this is the code.</p>
|
[
{
"answer_id": 74546780,
"author": "Noah",
"author_id": 14028308,
"author_profile": "https://Stackoverflow.com/users/14028308",
"pm_score": 0,
"selected": false,
"text": "import random\n\nnumbers = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10\nuser = None\nhidden = random.choice(numbers)\n\nprint(\"Welcome to volty's's number guessing game!\")\n\n\ndef game(chance):\n user = int(input(\"choose a number from 1 to 10: \"))\n if user > hidden:\n print(\"ur number is more than the hidden number\")\n chance += 1\n game(chance)\n elif user < hidden:\n print(\"ur number is less than the hudden number\")\n chance += 1\n game(chance)\n elif user == hidden:\n print(\" u guessed the hidden number!\")\n print(\"the hidden number was:\", hidden)\n print(f\"u guessed it in {chance + 1} step {'s' if chance > 1 else ' '}\")\n\n\ngame(0)\n"
},
{
"answer_id": 74546833,
"author": "Julia F.",
"author_id": 17565391,
"author_profile": "https://Stackoverflow.com/users/17565391",
"pm_score": 1,
"selected": false,
"text": "chance chance import random\n\nnumbers = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10\nuser = None\nhidden = random.choice(numbers)\n\nprint(\"Welcome to volty's's number guessing game!\")\n\nchance = 0\n\ndef game(chance):\n user = int(input(\"choose a number from 1 to 10: \"))\n if user > hidden:\n print(\"ur number is more than the hidden number\")\n game(chance + 1)\n # chance += 1\n elif user < hidden:\n print(\"ur number is less than the hudden number\")\n game(chance + 1)\n # chance += 1\n elif user == hidden:\n print(\" u guessed the hidden number!\")\n print(\"the hidden number was:\", hidden)\n print(f\"u guessed it in {chance + 1} step{'s' if chance > 1 else ' '}\")\n\n\ngame(chance)\n"
},
{
"answer_id": 74546850,
"author": "TheBidouilleur",
"author_id": 20570666,
"author_profile": "https://Stackoverflow.com/users/20570666",
"pm_score": 0,
"selected": false,
"text": "import random\n\nprint(\"Welcome to volty's's number guessing game!\")\ndef game():\n numbers = 1,2,3,4,5,6,7,8,9,10 \n user = None\n hidden = random.choice(numbers) # maybe use random.randint(0, 10)\n\n is_hidden_found = False\n chance = 0\n while is_hidden_found == False:\n\n user = int(input(\"choose a number from 1 to 10: \"))\n if user > hidden:\n print (\"ur number is more than the hidden number\")\n chance += 1\n elif user < hidden: \n print (\"ur number is less than the hudden number\")\n chance += 1\n elif user == hidden:\n is_hidden_found = True\n print (\" u guessed the hidden number!\")\n print (\"the hidden number was:\",hidden)\n print (f\"u guessed it in {chance +1} step {'s' if chance > 1 else ' '}\")\n\ngame()\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581655/"
] |
74,546,712
|
<p>I have a recurring problem in SQL queries, that I haven't been able to solve elegantly, neither in raw SQL or the Django ORM, and now I'm faced with it in EntityFramework as well. It is probably common enough to have its own name, but I don't know it.</p>
<p>Say, I have a simple foreign key relationship between two tables, e.g.</p>
<pre><code>Book 1 <- * Tag
</code></pre>
<p>A book has many tags and a tag has one book, i.e. the Tag table has a foreign key to the book table.</p>
<p>Now, I want to find all books that have "Tag1" and "Tag2".</p>
<h3>Raw SQL</h3>
<p>I can make multiple joins</p>
<pre><code>SELECT * FROM books
JOIN tags t1 on tags.book_id = books.id
JOIN tags t2 on tags.book_id = books.id
WHERE t1.tag = 'Tag1' AND t2.tag = 'Tag2'
</code></pre>
<p>Cool, that works, but doesn't really seem performant</p>
<h3>Django</h3>
<p>In django, I could do something similar</p>
<pre><code>Book.objects.filter(tags__tag="Tag1").filter(tags__tag="Tag1")
</code></pre>
<p>Changing filters like that will cause the extra joins, like in the raw SQL version</p>
<h3>EntityFramework LINQ</h3>
<p>I tried chaining <code>.Where()</code> similar to changing Django's <code>.filter()</code>, but that does not have the same result. It will build a query resembling the following, which will of course return nothing, because there is no row where the tag are two different strings</p>
<pre><code>SELECT * FROM books
JOIN tags t1 on tags.book_id = books.id
WHERE t1.tag = 'Tag1' AND t1.tag = 'Tag2'
</code></pre>
<h3>Wrapping it up</h3>
<p>I suppose I could do an array aggregate to aggregate tags into and array and compare to that, but that seems expensive too, and aggregates and grouping also have impact on the ordering of things, which forces me to do subqueries to get the order I want.</p>
<p>I am by no means an expert in SQL, as you can plainly see, but I guess what I am hoping for is either</p>
<ol>
<li>A way to mimic the stupid nonsense above in LINQ</li>
<li>An alternative, more elegant approach that will let me do what I need and which works well with any ORM</li>
</ol>
<h3>Extra ramblings</h3>
<p>This case where I need to find books that have "all of" a list of tags is the tricky bit... If it was "any of" or "this particular one", then it would be simple.</p>
<p>EDIT: The solution using arrays and overlap</p>
<p>In Postgres, we can do <code>array_agg</code> to aggregate all related tags into an array, like this:</p>
<pre><code>SELECT * FROM books
JOIN tags t1 on tags.book_id = books.id
;
+--------+-------+------+
| BookId | Name | Tag |
+--------+-------+------+
| 1 | BookA | Tag1 |
| 1 | BookA | Tag2 |
| 1 | BookA | Tag3 |
| 2 | BookB | Tag1 |
| 2 | BookB | Tag3 |
+--------+-------+------+
SELECT books.BookId, Name, array_agg(t1.tags) as tags
FROM books
JOIN tags t1 on tags.book_id = books.id
GROUP BY BookId
ORDER BY BookId
;
+--------+-------+--------------------+
| BookId | Name | tags |
+--------+-------+--------------------+
| 1 | BookA | [Tag1, Tag2, Tag3} |
| 2 | BookB | {Tag1, Tag3} |
+--------+-------+--------------------+
</code></pre>
<p>With that, I can then use the array "contains" operator to find the row where <code>tag</code> overlaps with the expected set: <code>WHERE tags @> ('Tag1', 'Tag2')</code>.</p>
<p>This is also a viable option. It does aggregation instead of excessive joining. Not sure what that would look like with LINQ query though</p>
|
[
{
"answer_id": 74553824,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 2,
"selected": false,
"text": "group by having Tag 1 Tag 2 with cte_tags as (\nselect book_id\n from tags\n where tag in ('Tag 1', 'Tag 2')\n group by book_id\n having count(*)=2)\nselect b.id as book_id,\n b.name\n from books b\n join cte_tags t\n on b.id = t.book_id;\n tag tags book_id with cte_tags as (\nselect book_id\n from tags\n where tag in ('Tag 1', 'Tag 2')\n group by book_id\n having count(distinct tag)=2)\nselect b.id as book_id,\n b.name\n from books b\n join cte_tags t\n on b.id = t.book_id;\n tag1 tag2 tag1 tag2 with cte_tags as (\nselect book_id\n from tags\n where tag in ('Tag 1', 'Tag 2')\n group by book_id\n having count(distinct tag) between 1 and 2)\nselect b.id as book_id,\n b.name\n from books b\n join cte_tags t\n on b.id = t.book_id;\n"
},
{
"answer_id": 74616084,
"author": "Gert Arnold",
"author_id": 861716,
"author_profile": "https://Stackoverflow.com/users/861716",
"pm_score": 0,
"selected": false,
"text": "var tags = new[] { \"Tag1\", \"Tag2\" };\nvar books = context.Books\n .Where(b => b.Tags.All(t => tags.Contains(t.Tag))\n && b.Tags.Select(t => t.Tag).Distinct().Count() == tags.Count());\n var books = context.Books\n .Where(b => b.Tags.All(t => tags.Contains(t.Tag))\n && b.Tags.Count() > 0);\n All SELECT [b].[Id]\n FROM [Books] AS [b]\n WHERE NOT EXISTS (\n SELECT 1\n FROM [Tags] AS [t]\n WHERE ([b].[Id] = [t].[BookId]) AND [t].[Tag] NOT IN (N'Tag1', N'Tag2'))\n AND ((\n SELECT COUNT(*)\n FROM [Tags] AS [t0]\n WHERE [b].[Id] = [t0].[BookId]) > 0)\n"
},
{
"answer_id": 74674367,
"author": "Vladimir Baranov",
"author_id": 4116017,
"author_profile": "https://Stackoverflow.com/users/4116017",
"pm_score": 0,
"selected": false,
"text": "select book_id\nfrom tags\nwhere tag in ('Tag1', 'Tag2')\n select book_id\nfrom tags\nwhere tag = 'Tag 1' OR tag = 'Tag2'\n tags tag select book_id\nfrom tags\nwhere tag = 'Tag1'\n OR WITH\nCTE_BookIDs\nAS\n(\n select book_id\n from tags\n where tag = 'Tag1'\n\n INTERSECT\n\n select book_id\n from tags\n where tag = 'Tag2'\n)\nSELECT\n books.*\nFROM\n books\n INNER JOIN CTE_BookIDs ON CTE_BookIDs.book_id = books.id\n;\n CREATE TABLE #Tags\n (ID int IDENTITY NOT NULL PRIMARY KEY\n ,BookID int NOT NULL\n ,Tag varchar(50) NOT NULL);\n\nINSERT INTO #Tags VALUES\n(1, 'Tag1'),\n(1, 'Tag2'),\n(1, 'Tag3'),\n(1, 'Tag4'),\n(2, 'Tag1'),\n(3, 'Tag2'),\n(4, 'Tag1'),\n(4, 'Tag2'),\n(4, 'Tag3'),\n(5, 'Tag3'),\n(5, 'Tag4'),\n(5, 'Tag5'),\n(6, 'Tag1'),\n(6, 'Tag3'),\n(6, 'Tag5'),\n(7, 'Tag2'),\n(7, 'Tag3'),\n(8, 'Tag1'),\n(8, 'Tag2');\n\nCREATE INDEX IX_Tag ON #Tags\n(\n Tag, BookID\n);\n\nWITH\nCTE_BookIDs\nAS\n(\n select BookID\n from #Tags\n where tag = 'Tag1'\n\n INTERSECT\n\n select BookID\n from #Tags\n where tag = 'Tag2'\n)\nSELECT *\nFROM CTE_BookIDs\n;\n\nDROP TABLE #Tags;\n +--------+\n| BookID |\n+--------+\n| 1 |\n| 4 |\n| 8 |\n+--------+\n"
},
{
"answer_id": 74674781,
"author": "Ryabchenko Alexander",
"author_id": 6515755,
"author_profile": "https://Stackoverflow.com/users/6515755",
"pm_score": 0,
"selected": false,
"text": "create index on tags (tag, book_id);\n SELECT * FROM books\nJOIN tags t1 on t1.tag = 'Tag1' AND t2.book_id = books.id\nJOIN tags t2 on t2.tag = 'Tag2' AND t2.book_id = books.id;\n SELECT \n books.id,\n count(distinct tags.id) as tags_count\nFROM books\nJOIN tags on tags.tag = ANY(['Tag1', 'Tag2', ...]) AND tags.book_id = books.id\nGROUP BY books.id\nHAVING \n count(distinct tags.id) = <number of tags>\n create index on tags (book_id, tag);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1600533/"
] |
74,546,731
|
<p>So I'm trying to lexicographically sort this collection but with no success. The same unsorted collection is in the input and the output of the sort method.</p>
<pre><code>class Person {
private String privateName;
private String lastName;
public Person(String privateName, String lastName) {
this.privateName = privateName;
this.lastName = lastName;
}
public String toString() {
return privateName + " " + lastName;
}
}
class Main {
public static void main(String[] args) {
Collection<Person> people = new ArrayList<>();
people.add(new Person("aaa", "hhh"));
people.add(new Person("aaa", "aaa"));
people.add(new Person("aaa", "uuu"));
Arrays.sort(people.toArray(), Comparator.comparing(Object::toString));
}
}
</code></pre>
<p>The order of the elements in the output collection:
"aaa hhh" -> "aaa aaa" -> "aaa uuu"</p>
<p>While I want it to be:
"aaa aaa" -> "aaa hhh" -> "aaa uuu"</p>
<p>Can somebody tell me why?</p>
|
[
{
"answer_id": 74546794,
"author": "OH GOD SPIDERS",
"author_id": 6073886,
"author_profile": "https://Stackoverflow.com/users/6073886",
"pm_score": 3,
"selected": true,
"text": "public static void main(final String[] args) {\n final List<Person> people = new ArrayList<>();\n \n people.add(new Person(\"aaa\", \"hhh\"));\n people.add(new Person(\"aaa\", \"aaa\"));\n people.add(new Person(\"aaa\", \"uuu\"));\n\n Collections.sort(people, Comparator.comparing(Person::toString));\n \n System.out.println(people);\n \n}\n"
},
{
"answer_id": 74550443,
"author": "Panagiotis Bougioukos",
"author_id": 7237884,
"author_profile": "https://Stackoverflow.com/users/7237884",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n\n Person[] peopleArray = {\n new Person(\"aaa\", \"hhh\"),\n new Person(\"aaa\", \"aaa\"),\n new Person(\"aaa\", \"uuu\")\n };\n\n Collection<Person> people = Arrays.asList(peopleArray);\n\n Arrays.sort(peopleArray, Comparator.comparing(Object::toString));\n\n System.out.println(people);\n }\n [aaa aaa, aaa hhh, aaa uuu] Arrays.sort(peopleArray, Comparator.comparing(Object::toString)); [aaa hhh, aaa aaa, aaa uuu] Arrays.asList() java.util.ArrayList() ArrayList"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16076953/"
] |
74,546,763
|
<p>I get a String of the format
<code><num-num-num><num-num-num><num-num-num></code>. I want to turn this into a nested Array of Ints with each Array being the content between the <code><></code>.</p>
<p>This is what I got so far:</p>
<pre class="lang-java prettyprint-override"><code>String parameter = args[1];
// split the string into an array of strings at >
String[] splitString = parameter.split(">");
int[][] square = new int[splitString.length][splitString.length];
// remove <, > and - characters and push the numbers into the square
for (int i = 0; i < splitString.length; i++) {
splitString[i] = splitString[i].replaceAll("[<>-]", "");
for (int j = 0; j < splitString.length; j++) {
square[i][j] = Integer.parseInt(splitString[i].substring(j, j + 1));
}
}
</code></pre>
<p>I don't feel like this is very clean, but it works. Does anyone have an idea on how to improve readability?</p>
|
[
{
"answer_id": 74546913,
"author": "Thomas",
"author_id": 637853,
"author_profile": "https://Stackoverflow.com/users/637853",
"pm_score": 3,
"selected": true,
"text": "\"<num-num-num><num-num-num><num-num-num>\" \"num-num-num\" \"><\" \"-\" String input = \"<11-12-13><21-22-23><31-32-33>\";\n \n//remove leading < and trailing > then split at >< \nString[] inputRows = input.substring(1,input.length()-1).split(\"><\");\n \nint[][] grid = new int[inputRows.length][];\n \nfor( int r = 0; r < inputRows.length; r++) {\n //split the row at -\n String[] cells = inputRows[r].split(\"-\");\n \n //convert the array of strings to an array of int by parsing each cell\n grid[r] = Arrays.stream(cells).mapToInt(Integer::parseInt).toArray();\n}\n"
},
{
"answer_id": 74547085,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 1,
"selected": false,
"text": "Matcher.results() - public static final Pattern ANGLE_BRACKETS = Pattern.compile(\"<([\\\\d-]*)>\");\n Matcher.results() MatchResult MatchResult.group() 1 Pattern.splitAsStream() Arrays.split() \"-\" Pattern.splitAsStream() splitAsStream() \"-\" String parameter = \"<1-2-3><4-5-6><7-8-9>\";\n \nint[][] matrix = ANGLE_BRACKETS1.matcher(parameter).results()\n .map(matchResult -> matchResult.group(1))\n .map(str -> Arrays.stream(str.split(\"-\")).mapToInt(Integer::parseInt).toArray())\n .toArray(int[][]::new);\n \nSystem.out.println(Arrays.deepToString(matrix));\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12299738/"
] |
74,546,776
|
<p>I have pairs of images of the same 2D object with very minor diferences. The two images of a pair have two reference points (a star [x_s,y_s] and an arrow-head [x_a,y_a]) as shown below:</p>
<p><img src="https://i.stack.imgur.com/GjEDx.png" alt="The Image Pair" /></p>
<p>I have written a Python script to align one image with reference to the second image of the pair with the reference points/coordinates. Please go through the code below for a clear understanding:</p>
<pre class="lang-py prettyprint-override"><code>
import numpy as np
import cv2
import pandas as pd
# Function to align image2 with respect to image1:
def alignFromReferenceImage(image1, imgname1, image2, imgname2):
# Using Panda dataframe to read the coordinate values ((x_s,y_s) and (x_a,y_a)) from a csv file
#
# The .csv file looks like this:-
#
# id;x_s;y_s;x_a;y_a
# img11;113;433;45;56
# img12;54;245;55;77
# img21;33;76;16;88
# img22;62;88;111;312
# ... ;..;..;...;
df = pd.read_csv("./image_metadata.csv", delimiter= ';')
# Eliminate .jpg from the image name and fetch the row
filter_data=df[df.isin([imgname1.split('.')[0]]).any(1)]
x1_s=filter_data['x_s'].values[0]
y1_s=filter_data['y_s'].values[0]
x1_a=filter_data['x_a'].values[0]
y1_a=filter_data['y_a'].values[0]
filter_data2=df[df.isin([imgname2.split('.')[0]]).any(1)]
x2_s=filter_data2['x_s'].values[0]
y2_s=filter_data2['y_s'].values[0]
x2_a=filter_data2['x_a'].values[0]
y2_a=filter_data2['y_a'].values[0]
tx=x2_s-x1_s
ty=y2_s-y1_s
rows,cols = image1.shape
M = np.float32([[1,0,-tx],[0,1,-ty]])
image_after_translation = cv2.warpAffine(image2,M,(cols,rows))
d1 = math.sqrt((x1_a - x1_s)**2 + (y1_a - y1_s)**2)
d2 = math.sqrt((x2_a - x2_s)**2 + (y2_a - y2_s)**2)
dx1 = x1_a - x1_s
dy1 = -(y1_a - y1_s)
alpha1 = math.degrees(math.atan2(dy1, dx1))
alpha1=(360+alpha1) if (alpha1<0) else alpha1
dx2 = x2_a - x2_s
dy2 = -(y2_a - y2_s)
alpha2 = math.degrees(math.atan2(dy2, dx2))
alpha2=(360+alpha2) if (alpha2<0) else alpha2
ang=alpha1-alpha2
scale = d1 / d2
centre = (filter_data['x_s'].values[0], filter_data['y_s'].values[0])
M = cv2.getRotationMatrix2D((centre),ang,scale)
aligned_image = cv2.warpAffine(image_after_translation, M, (cols,rows))
return aligned_image
</code></pre>
<p>After alignment, the image looks as shown below:</p>
<p><img src="https://i.stack.imgur.com/xXvhE.png" alt="Image After Alignment" /></p>
<p><strong>Important:</strong> Now, after aligning the first image with respect to the second image, I want to crop the aligned image in such a way that the image will no longer have the black background after cropping. The picture below will clearly explain what I want to do:</p>
<p><img src="https://i.stack.imgur.com/kPXIL.png" alt="Image After Cropping" /></p>
<p>I have researched on it and found some useful links:</p>
<ol>
<li><a href="http://roffle-largest-rectangle.blogspot.com/2011/09/find-largest-rectangle-in-rotated-image.html" rel="nofollow noreferrer">http://roffle-largest-rectangle.blogspot.com/2011/09/find-largest-rectangle-in-rotated-image.html</a></li>
<li><a href="https://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders">Rotate image and crop out black borders</a></li>
<li><a href="https://stackoverflow.com/questions/5789239/calculate-largest-inscribed-rectangle-in-a-rotated-rectangle">Calculate largest inscribed rectangle in a rotated rectangle</a></li>
</ol>
<p>But these posts only discuss about rotation and I have no clue how the maths work for translation and scaling. Any help in this problem would be highly appreciated.</p>
|
[
{
"answer_id": 74546913,
"author": "Thomas",
"author_id": 637853,
"author_profile": "https://Stackoverflow.com/users/637853",
"pm_score": 3,
"selected": true,
"text": "\"<num-num-num><num-num-num><num-num-num>\" \"num-num-num\" \"><\" \"-\" String input = \"<11-12-13><21-22-23><31-32-33>\";\n \n//remove leading < and trailing > then split at >< \nString[] inputRows = input.substring(1,input.length()-1).split(\"><\");\n \nint[][] grid = new int[inputRows.length][];\n \nfor( int r = 0; r < inputRows.length; r++) {\n //split the row at -\n String[] cells = inputRows[r].split(\"-\");\n \n //convert the array of strings to an array of int by parsing each cell\n grid[r] = Arrays.stream(cells).mapToInt(Integer::parseInt).toArray();\n}\n"
},
{
"answer_id": 74547085,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 1,
"selected": false,
"text": "Matcher.results() - public static final Pattern ANGLE_BRACKETS = Pattern.compile(\"<([\\\\d-]*)>\");\n Matcher.results() MatchResult MatchResult.group() 1 Pattern.splitAsStream() Arrays.split() \"-\" Pattern.splitAsStream() splitAsStream() \"-\" String parameter = \"<1-2-3><4-5-6><7-8-9>\";\n \nint[][] matrix = ANGLE_BRACKETS1.matcher(parameter).results()\n .map(matchResult -> matchResult.group(1))\n .map(str -> Arrays.stream(str.split(\"-\")).mapToInt(Integer::parseInt).toArray())\n .toArray(int[][]::new);\n \nSystem.out.println(Arrays.deepToString(matrix));\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5509436/"
] |
74,546,782
|
<p>I have a treeview with the following columns:</p>
<pre><code>self.columns = ("Name", "Status", "Activity")
</code></pre>
<p>This treeview is updated depending on the socket message and client name it receives. If the program receives "NAME:", it will insert a new row in the treeview with the client name placed under the "Name" column. Else if it's "CLOSED:", the "Status" and "Activity" columns where client name given is located will be updated.</p>
<pre><code>import tkinter as tk
from tkinter import ttk as tick
import socket
from threading import Thread
class GUI2(cust.CTk): #second window, not the root
def __init__(self, a, b, c, d, e):
self.PORT = a
self.SERVER = b
self.ADDRESS = c
self.FORMAT = d
self.host = e
self.master2 = cust.CTkToplevel()
self.columns = ("name", "status", "activity")
self.clientlist = tick.Treeview(self.clientframe, columns = self.columns, show = "tree")
self.clientlist.grid(row = 0, column = 0, sticky = "nswe")
self.clientlist.column("#0", minwidth = 0, width = 10, stretch = False)
self.clientlist.column("name", minwidth = 0, width = 140, stretch = False)
self.clientlist.column("status", minwidth = 0, width = 140, stretch = False)
self.clientlist.column("activity", minwidth = 0, width = 140, stretch = False)
self.thread = Thread(target = self.initreceiver)
self.thread.start()
def initreceiver(self):
try:
while True:
self.message = self.host.recv(1024).decode(self.FORMAT)
if "NAME:" in self.message:
x = self.message.replace("NAME:", "") #removes "NAME:" to get the clientname
self.clientlist.insert("", cust.END, iid = x, values = x) #inserts new row and display only client name;
#also sets iid the same as the client name for reference
elif "CLOSED:" in self.message:
x = self.message.replace("CLOSED", "") #remove "CLOSED:" to get clientname
self.clientlist.set(x, "Status", "Eyes are closed") #set "Status" column with the new value
self.clientlist.set(x, "Activity", "Eyes are closed") #set "Activity" column with the new value
except Exception:
print (traceback.format_exc())
</code></pre>
<p>Error is as follows:</p>
<pre><code>Traceback (most recent call last):
File "F:\Personal Programs\Python\Lobby + Tracking\mainmenu.py", line 438, in initreceiver
self.clientlist.set(x, "status", "Eyes are closed")
File "F:\Program Files (x86)\Python\lib\tkinter\ttk.py", line 1459, in set
res = self.tk.call(self._w, "set", item, column, value)
_tkinter.TclError: Item :Maikz not found #Maikz is the example client name sent
</code></pre>
<p>It looks like <code>.set()</code> method needs item value for the first argument, but I don't know what to put; I'm learning Treeview for the first time.</p>
<p>I need to be able to set the "Status" and "Activity" cells' values where their "Name" value matches the client name. Any advice or alternative solution is appreciated.</p>
|
[
{
"answer_id": 74546913,
"author": "Thomas",
"author_id": 637853,
"author_profile": "https://Stackoverflow.com/users/637853",
"pm_score": 3,
"selected": true,
"text": "\"<num-num-num><num-num-num><num-num-num>\" \"num-num-num\" \"><\" \"-\" String input = \"<11-12-13><21-22-23><31-32-33>\";\n \n//remove leading < and trailing > then split at >< \nString[] inputRows = input.substring(1,input.length()-1).split(\"><\");\n \nint[][] grid = new int[inputRows.length][];\n \nfor( int r = 0; r < inputRows.length; r++) {\n //split the row at -\n String[] cells = inputRows[r].split(\"-\");\n \n //convert the array of strings to an array of int by parsing each cell\n grid[r] = Arrays.stream(cells).mapToInt(Integer::parseInt).toArray();\n}\n"
},
{
"answer_id": 74547085,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 1,
"selected": false,
"text": "Matcher.results() - public static final Pattern ANGLE_BRACKETS = Pattern.compile(\"<([\\\\d-]*)>\");\n Matcher.results() MatchResult MatchResult.group() 1 Pattern.splitAsStream() Arrays.split() \"-\" Pattern.splitAsStream() splitAsStream() \"-\" String parameter = \"<1-2-3><4-5-6><7-8-9>\";\n \nint[][] matrix = ANGLE_BRACKETS1.matcher(parameter).results()\n .map(matchResult -> matchResult.group(1))\n .map(str -> Arrays.stream(str.split(\"-\")).mapToInt(Integer::parseInt).toArray())\n .toArray(int[][]::new);\n \nSystem.out.println(Arrays.deepToString(matrix));\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6541346/"
] |
74,546,793
|
<p>I'm trying three js with OBJ files, but it does not get rendered on the screen, can someone please help me with this issue? is there something obvious I'm missing?</p>
<p>On the other hand, a geometric cube renders perfectly.</p>
<p><em><strong>OBJ file can be downloaded here</strong></em>: <a href="https://free3d.com/pt/3d-model/tote-bag-womens-v1--846558.html" rel="nofollow noreferrer">https://free3d.com/pt/3d-model/tote-bag-womens-v1--846558.html</a></p>
<p><em><strong>index.js:</strong></em></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>import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'
import sacola from './sacola.obj';
const renderer = new THREE.WebGLRenderer();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const controls = new OrbitControls( camera, renderer.domElement );
const loader = new OBJLoader();
const scene = new THREE.Scene();
const axesHelper = new THREE.AxesHelper(5)
scene.add(axesHelper)
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor('#000', 0)
camera.position.set(0,0,8);
controls.enableDamping = true
document.body.appendChild( renderer.domElement );
// const geometry = new THREE.BoxGeometry( 1, 1, 1 );
// const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
// const cube = new THREE.Mesh( geometry, material );
// scene.add( cube );
loader.load(sacola, (model) => {
model.position.set(0, 0, -53);
scene.add( model )
},
);
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
controls.update();
}
animate()</code></pre>
</div>
</div>
</p>
<p><em><strong>index.html:</strong></em></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-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Apresentação 3D</title>
</head>
<body>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><em><strong>webpack.config.js:</strong></em></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>const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
module.exports = {
mode: 'development',
entry: path.resolve(__dirname, 'src/index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
assetModuleFilename: 'assets/[hash][ext][query]',
},
devServer: {
port: 3001,
open: true,
allowedHosts: 'all'
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx']
},
module: {
rules: [
{
test: /\.(png|svg|jpg|jpeg|gif|obj)$/i,
type: 'asset/resource'
},
{
test: /\.obj$/,
loader: 'webpack-obj-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({ template: './src/public/index.html', inject: true })
],
}</code></pre>
</div>
</div>
</p>
<p><em><strong>Code structure:</strong></em></p>
<p><a href="https://i.stack.imgur.com/pykem.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pykem.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74546913,
"author": "Thomas",
"author_id": 637853,
"author_profile": "https://Stackoverflow.com/users/637853",
"pm_score": 3,
"selected": true,
"text": "\"<num-num-num><num-num-num><num-num-num>\" \"num-num-num\" \"><\" \"-\" String input = \"<11-12-13><21-22-23><31-32-33>\";\n \n//remove leading < and trailing > then split at >< \nString[] inputRows = input.substring(1,input.length()-1).split(\"><\");\n \nint[][] grid = new int[inputRows.length][];\n \nfor( int r = 0; r < inputRows.length; r++) {\n //split the row at -\n String[] cells = inputRows[r].split(\"-\");\n \n //convert the array of strings to an array of int by parsing each cell\n grid[r] = Arrays.stream(cells).mapToInt(Integer::parseInt).toArray();\n}\n"
},
{
"answer_id": 74547085,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 1,
"selected": false,
"text": "Matcher.results() - public static final Pattern ANGLE_BRACKETS = Pattern.compile(\"<([\\\\d-]*)>\");\n Matcher.results() MatchResult MatchResult.group() 1 Pattern.splitAsStream() Arrays.split() \"-\" Pattern.splitAsStream() splitAsStream() \"-\" String parameter = \"<1-2-3><4-5-6><7-8-9>\";\n \nint[][] matrix = ANGLE_BRACKETS1.matcher(parameter).results()\n .map(matchResult -> matchResult.group(1))\n .map(str -> Arrays.stream(str.split(\"-\")).mapToInt(Integer::parseInt).toArray())\n .toArray(int[][]::new);\n \nSystem.out.println(Arrays.deepToString(matrix));\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15026611/"
] |
74,546,818
|
<p>My application is a VueJS frontend and a Laravel Backend API. I want to subscribe to Binance API WebSocket but I'm unsure how to do it.</p>
<p>Any ideas?
I'm talking about the high level design of it. I was not able to find a way to listen to a WebSocket from the backend in Laravel.</p>
<ul>
<li>FYI, I've already setup a websocket server and I'm sending events through it so my Vue JS Front end knows when the specific event happens, now I need to actually take the event from Binance WebSocket. It's important for me to listen to the websocket from the backend since that's where the action should happen.</li>
</ul>
<p>For sure this has to run somewhere at the back in some kind of isolated env or ?</p>
|
[
{
"answer_id": 74546913,
"author": "Thomas",
"author_id": 637853,
"author_profile": "https://Stackoverflow.com/users/637853",
"pm_score": 3,
"selected": true,
"text": "\"<num-num-num><num-num-num><num-num-num>\" \"num-num-num\" \"><\" \"-\" String input = \"<11-12-13><21-22-23><31-32-33>\";\n \n//remove leading < and trailing > then split at >< \nString[] inputRows = input.substring(1,input.length()-1).split(\"><\");\n \nint[][] grid = new int[inputRows.length][];\n \nfor( int r = 0; r < inputRows.length; r++) {\n //split the row at -\n String[] cells = inputRows[r].split(\"-\");\n \n //convert the array of strings to an array of int by parsing each cell\n grid[r] = Arrays.stream(cells).mapToInt(Integer::parseInt).toArray();\n}\n"
},
{
"answer_id": 74547085,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 1,
"selected": false,
"text": "Matcher.results() - public static final Pattern ANGLE_BRACKETS = Pattern.compile(\"<([\\\\d-]*)>\");\n Matcher.results() MatchResult MatchResult.group() 1 Pattern.splitAsStream() Arrays.split() \"-\" Pattern.splitAsStream() splitAsStream() \"-\" String parameter = \"<1-2-3><4-5-6><7-8-9>\";\n \nint[][] matrix = ANGLE_BRACKETS1.matcher(parameter).results()\n .map(matchResult -> matchResult.group(1))\n .map(str -> Arrays.stream(str.split(\"-\")).mapToInt(Integer::parseInt).toArray())\n .toArray(int[][]::new);\n \nSystem.out.println(Arrays.deepToString(matrix));\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14156743/"
] |
74,546,844
|
<p>I have a child component that gets a year list from parent, and needs to style an element if that list contains the current year.</p>
<p><strong>The child ts</strong>:</p>
<pre><code>export class ChildComponent implements OnInit {
@Input() listYears: Array<number> = [];
year = 2022;
constructor() { }
ngOnInit(): void {
}
existInList() {
return this.listYears.find(x => x === this.year);
}
}
</code></pre>
<p><strong>the child html:</strong></p>
<pre><code><div [style.background-color]="existInList() ? 'red' : 'blue' ">
</div>
</code></pre>
<p><strong>and the parent html:</strong></p>
<pre><code><app-child [listYears]="[2022]"></app-child>
</code></pre>
<p>Because the condition for the style uses a method, and the recommendation is to prevent using function calls in Angular template expressions (<a href="https://medium.com/showpad-engineering/why-you-should-never-use-function-calls-in-angular-template-expressions-e1a50f9c0496" rel="nofollow noreferrer">never use function calls in Angular template</a>)
so how can I achive this without a function call?</p>
<p>I assume that inserting the condition within the template instead of in ts, like this:</p>
<pre><code>
<div [style.background-color]="listYears.find(x => x === year) ? 'red' : 'blue' ">
</div>
</code></pre>
<p>does not matter for performance.
Am I wrong? If not - what's the write way?</p>
<p>Thanks</p>
|
[
{
"answer_id": 74547006,
"author": "Avraham Weinstein",
"author_id": 8938503,
"author_profile": "https://Stackoverflow.com/users/8938503",
"pm_score": 2,
"selected": true,
"text": "Pipe pipe @Pipe({\n name: 'existInList'\n})\nexport class ExistInListPipe implements PipeTransform {\n transform(listYears: number[], year: number): string {\n return listYears.find((x) => x === year) ? 'red' : 'blue';\n }\n}\n <div [style.background-color]=\"listYears | existInList : year\">\n </div>\n"
},
{
"answer_id": 74547178,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 0,
"selected": false,
"text": "@Component({\n selector: 'hello',\n template: `<h1>Hello!</h1>`,\n styles: [`h1 { font-family: Lato; }`],\n})\nexport class HelloComponent {\n private _listYears: number[];\n yearToStyle: number = 2022;\n\n @HostBinding('style.color')\n background: string;\n\n @Input()\n set listYears(value: number[]) {\n this._listYears = value;\n\n this.background = value.includes(this.yearToStyle) ? 'red' : 'blue';\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3345721/"
] |
74,546,848
|
<p>I'm trying to use LINQ in a C# (Polyglot Notebook).</p>
<pre class="lang-cs prettyprint-override"><code>using System.Linq;
Environment.GetEnvironmentVariables().Values.Select(x => x)
</code></pre>
<p>But I'm getting the error:</p>
<blockquote>
<p>Error: (3,46): error CS1061: 'ICollection' does not contain a definition for 'Select' and no accessible extension method 'Select' accepting a first argument of type 'ICollection' could be found (are you missing a using directive or an assembly reference?)</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/zQo4u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zQo4u.png" alt="Screenshot VSCodoe" /></a></p>
|
[
{
"answer_id": 74547006,
"author": "Avraham Weinstein",
"author_id": 8938503,
"author_profile": "https://Stackoverflow.com/users/8938503",
"pm_score": 2,
"selected": true,
"text": "Pipe pipe @Pipe({\n name: 'existInList'\n})\nexport class ExistInListPipe implements PipeTransform {\n transform(listYears: number[], year: number): string {\n return listYears.find((x) => x === year) ? 'red' : 'blue';\n }\n}\n <div [style.background-color]=\"listYears | existInList : year\">\n </div>\n"
},
{
"answer_id": 74547178,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 0,
"selected": false,
"text": "@Component({\n selector: 'hello',\n template: `<h1>Hello!</h1>`,\n styles: [`h1 { font-family: Lato; }`],\n})\nexport class HelloComponent {\n private _listYears: number[];\n yearToStyle: number = 2022;\n\n @HostBinding('style.color')\n background: string;\n\n @Input()\n set listYears(value: number[]) {\n this._listYears = value;\n\n this.background = value.includes(this.yearToStyle) ? 'red' : 'blue';\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201482/"
] |
74,546,853
|
<p>I am fitting an example model in SAS:</p>
<pre><code>proc mixed data = pat_ehp30 method = reml;
class trt_group AssNo stage_endo_cat opinofsurg age_cat larc_selection larc_decision recruitcent;
model infertile = trt_group AssNo AssNo * trt_group infertile0 stage_endo_cat opinofsurg age_cat larc_selection larc_decision / s cl;
repeated AssNo / type = cs sub = Pat_TNO r rcorr;
random recruitcent;
lsmeans trt_group * AssNo / slice = AssNo diff cl e;
run;
</code></pre>
<p>I am fitting the same model 11 times, with the only difference being the output is different and I'm adjusting for baseline (in this case the variable <code>infertile0</code>). I have written a macro:</p>
<pre><code>%macro rm (domain = ,);
proc mixed data = pat_ehp30 method = reml;
class trt_group AssNo stage_endo_cat opinofsurg age_cat larc_selection larc_decision recruitcent;
model &domain = trt_group AssNo AssNo * trt_group &domain0 stage_endo_cat opinofsurg age_cat larc_selection larc_decision / s cl;
repeated AssNo / type = cs sub = Pat_TNO r rcorr;
random recruitcent;
lsmeans trt_group * AssNo / slice = AssNo diff cl e;
run;
%mend rm;
</code></pre>
<p>However the variable <code>&domain0</code> will not work. I want it to append a <code>0</code> to the end of whatever name I put into <code>domain</code>, eg <code>pain</code> becomes <code>pain0</code>.</p>
|
[
{
"answer_id": 74547006,
"author": "Avraham Weinstein",
"author_id": 8938503,
"author_profile": "https://Stackoverflow.com/users/8938503",
"pm_score": 2,
"selected": true,
"text": "Pipe pipe @Pipe({\n name: 'existInList'\n})\nexport class ExistInListPipe implements PipeTransform {\n transform(listYears: number[], year: number): string {\n return listYears.find((x) => x === year) ? 'red' : 'blue';\n }\n}\n <div [style.background-color]=\"listYears | existInList : year\">\n </div>\n"
},
{
"answer_id": 74547178,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 0,
"selected": false,
"text": "@Component({\n selector: 'hello',\n template: `<h1>Hello!</h1>`,\n styles: [`h1 { font-family: Lato; }`],\n})\nexport class HelloComponent {\n private _listYears: number[];\n yearToStyle: number = 2022;\n\n @HostBinding('style.color')\n background: string;\n\n @Input()\n set listYears(value: number[]) {\n this._listYears = value;\n\n this.background = value.includes(this.yearToStyle) ? 'red' : 'blue';\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19414769/"
] |
74,546,862
|
<p>I have this query
`</p>
<pre><code>CREATE TABLE Commitment_fees
(user_id INT PRIMARY KEY AUTO_INCREMENT,
amount INT,
success INT,
date DATE);
ALTER TABLE Commitment_fees AUTO_INCREMENT=1000;
INSERT INTO Commitment_fees (amount, success, date)
VALUES
(1000, 1, '2021-01-01'),
(1010, 0, '2021-01-01'),
(200, 1, '2021-01-01'),
(201, 0, '2021-01-02'),
(100, 0, '2021-01-02'),
(101, 1, '2021-01-02');
SELECT
date,
SUM(amount) AS Attempt_amount,
(SELECT
SUM(amount)
FROM
Commitment_fees
WHERE
success = 1) AS Success_amount
FROM
Commitment_fees
GROUP BY
date;
</code></pre>
<p>`
But my result is
<a href="https://i.stack.imgur.com/cno6e.jpg" rel="nofollow noreferrer">enter image description here</a>
You can see what a second day Success_amount is not correct</p>
<p>I try to
`</p>
<pre><code>SELECT
date,
SUM(amount) AS Attempt_amount,
(SELECT
SUM(amount)
FROM
Commitment_fees
WHERE
success = 1
**GROUP BY
date**) AS Success_amount
FROM
Commitment_fees
GROUP BY
date;
</code></pre>
<p>`
But its return more than 1 row.
What structure of this query i need?</p>
|
[
{
"answer_id": 74547006,
"author": "Avraham Weinstein",
"author_id": 8938503,
"author_profile": "https://Stackoverflow.com/users/8938503",
"pm_score": 2,
"selected": true,
"text": "Pipe pipe @Pipe({\n name: 'existInList'\n})\nexport class ExistInListPipe implements PipeTransform {\n transform(listYears: number[], year: number): string {\n return listYears.find((x) => x === year) ? 'red' : 'blue';\n }\n}\n <div [style.background-color]=\"listYears | existInList : year\">\n </div>\n"
},
{
"answer_id": 74547178,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 0,
"selected": false,
"text": "@Component({\n selector: 'hello',\n template: `<h1>Hello!</h1>`,\n styles: [`h1 { font-family: Lato; }`],\n})\nexport class HelloComponent {\n private _listYears: number[];\n yearToStyle: number = 2022;\n\n @HostBinding('style.color')\n background: string;\n\n @Input()\n set listYears(value: number[]) {\n this._listYears = value;\n\n this.background = value.includes(this.yearToStyle) ? 'red' : 'blue';\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14354411/"
] |
74,546,863
|
<p>I want to display some images with matplotlib with <code>fig.add_subplot</code> but for some attempts I faced some errors like below:</p>
<pre><code>Traceback (most recent call last):
File "/home/---/Documents/---/---/dataset.py", line 134, in <module>
display_dicom(dicom,target["mask"])
File "/home/---/Documents/---/---/dataset.py", line 123, in display_dicom
fig.add_subplot(rows,cols,i+2)
File "/home/---/.pyenv/versions/3.8.13/envs/---/lib/python3.8/site-packages/matplotlib/figure.py", line 745, in add_subplot
ax = subplot_class_factory(projection_class)(self, *args, **pkw)
File "/home/---/.pyenv/versions/3.8.13/envs/---/lib/python3.8/site-packages/matplotlib/axes/_subplots.py", line 36, in __init__
self.set_subplotspec(SubplotSpec._from_subplot_args(fig, args))
File "/home/---/.pyenv/versions/3.8.13/envs/---/lib/python3.8/site-packages/matplotlib/gridspec.py", line 612, in _from_subplot_args
raise ValueError(
ValueError: num must be 1 <= num <= 2, not 3
</code></pre>
<pre><code>Traceback (most recent call last):
File "/home/---/Documents/---/---/dataset.py", line 133, in <module>
display_dicom(dicom,target["mask"])
File "/home/---/Documents/---/---/dataset.py", line 123, in display_dicom
plt.imshow(mask[i],cmap=plt.cm.bone)
IndexError: index 69 is out of bounds for dimension 0 with size 69
</code></pre>
<p>I want to compute row and col in <code>plt.figure</code> automatically. What is the formula that doesn't crash the code?</p>
<p>I tried the following func to display it.
<code>dicom</code> and <code>mask</code> are <code>torch.tensors</code>. When I select the row and col by hand, it works well.</p>
<pre><code>def display_dicom(dicom,mask):
count,width,height = mask.shape
if count == 0:
count = 1
fig = plt.figure(figsize=(10,10))
rows= int(math.sqrt(count)+1)
cols = int(math.sqrt(count)+1)
fig.add_subplot(rows,cols, 1)
plt.imshow(dicom, cmap=plt.cm.bone) # set the color map to bone
plt.title("dicom")
for i in range(2,count+2):
fig.add_subplot(rows,cols,i)
plt.imshow(mask[i],cmap=plt.cm.bone)
plt.title(f"mask {i+1}")
plt.show()
</code></pre>
<p>Sample plots are how I want to get the plot:
<a href="https://i.stack.imgur.com/7nIMv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7nIMv.png" alt="83 image" /></a>
<a href="https://i.stack.imgur.com/fhHAz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fhHAz.png" alt="10 image" /></a>
<a href="https://i.stack.imgur.com/RZtq3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RZtq3.png" alt="2 image" /></a></p>
|
[
{
"answer_id": 74547544,
"author": "ImotVoksim",
"author_id": 17580723,
"author_profile": "https://Stackoverflow.com/users/17580723",
"pm_score": -1,
"selected": false,
"text": "fig, axes = plt.subplots(nrows = rows, ncols = cols, figsize = (10, 10)) axes .imshow axes nrows x ncols"
},
{
"answer_id": 74582443,
"author": "Alican Kartal",
"author_id": 19970856,
"author_profile": "https://Stackoverflow.com/users/19970856",
"pm_score": 0,
"selected": false,
"text": "display_dicom def display_dicom(dicom,mask):\n\n count,width,height = mask.shape\n if count == 0:\n count = 1 # np.zeros empty mask\n \n number_of_images = count + 1 # masks + dicom\n\n fig = plt.figure(figsize=(10,10))\n rows= math.ceil(math.sqrt(number_of_images))\n cols = rows\n \n fig.add_subplot(rows,cols, 1)\n plt.imshow(dicom, cmap=plt.cm.bone) # set the color map to bone\n plt.title(\"dicom\")\n\n for i in range(count):\n fig.add_subplot(rows,cols,i+2)\n plt.imshow(mask[i],cmap=plt.cm.bone)\n plt.title(f\"mask {i+1}\")\n\n plt.show()\n\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19970856/"
] |
74,546,866
|
<p>I have a utility class:</p>
<p>utils.ts</p>
<pre><code>import axios, { AxiosResponse } from 'axios';
import { throwError } from 'rxjs';
axios.defaults.withCredentials = true;
axios.defaults.responseType = 'json';
export class UserUtils {
public updateUserData(data) {
return axios.post('http://mock.rest.server.com:1234/rest/update/user/', data,
{
withCredentials: true,
responseType: 'json' as 'json
})
.then(resp => {
return resp;
})
.catch(error => {
return throwError('error updating user data');
});
}
}
</code></pre>
<p>And my component classes call the above as per:</p>
<p>userComponent.ts</p>
<pre><code>export class UserComponent {
import { UserUtils } from './utils';
public userUtils: UserUtils = new UserUtils();
// Btn click method
public update(content) {
this.userUtils.updateUserData(content) // <-- call made here
.then((data) => {
this.showSuccessModal(); // <- trying to test this
}, (err) => {
this.showErrorModal(error); // <- trying to test this
});
}
}
</code></pre>
<p>I am trying to test the positive (showSuccessModal) / negative (showErrorModal) scenarios on userComponent.ts</p>
<p>userComponent.spec.ts</p>
<pre><code>import { UserComponent } from '../../../user/userComponent';
import { UserUtils } from '../../../user/utils';
describe('User Comp test', () => {
beforeAll(done => (async () => {
Testbed.configureTestingModule({
declarations: [
UserComponent
]
});
await TestBed.compileComponents();
})().then(done).catch(done.fail);
describe('User Comp (with beforeEach)', () => {
let component: UserComponent;
let fixture: ComponentFixture<UserComponent>;
beforeEach(() => {
fixture = await TestBed.createComponent(UserComponent);
component = fixture.componentInstance;
});
it('should show error modal', () => {
let errorModal = spyOn(component, 'showErrorModal');
spyOn(component.userUtils, 'updateUserData').and.returnValue(Promise.reject('error updating'));
component.update({test: 'test');
expect(errorModal).toHaveBeenCalled();
});
});
}
</code></pre>
<p>However when running tests, i see:</p>
<pre><code>Error: Expected spy showErrorModal to have been called
at <Jasmine>
</code></pre>
<p>It looks like in the test, the 'successful' route it always called.</p>
|
[
{
"answer_id": 74547544,
"author": "ImotVoksim",
"author_id": 17580723,
"author_profile": "https://Stackoverflow.com/users/17580723",
"pm_score": -1,
"selected": false,
"text": "fig, axes = plt.subplots(nrows = rows, ncols = cols, figsize = (10, 10)) axes .imshow axes nrows x ncols"
},
{
"answer_id": 74582443,
"author": "Alican Kartal",
"author_id": 19970856,
"author_profile": "https://Stackoverflow.com/users/19970856",
"pm_score": 0,
"selected": false,
"text": "display_dicom def display_dicom(dicom,mask):\n\n count,width,height = mask.shape\n if count == 0:\n count = 1 # np.zeros empty mask\n \n number_of_images = count + 1 # masks + dicom\n\n fig = plt.figure(figsize=(10,10))\n rows= math.ceil(math.sqrt(number_of_images))\n cols = rows\n \n fig.add_subplot(rows,cols, 1)\n plt.imshow(dicom, cmap=plt.cm.bone) # set the color map to bone\n plt.title(\"dicom\")\n\n for i in range(count):\n fig.add_subplot(rows,cols,i+2)\n plt.imshow(mask[i],cmap=plt.cm.bone)\n plt.title(f\"mask {i+1}\")\n\n plt.show()\n\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2244072/"
] |
74,546,885
|
<p>I have a dataframe like this:</p>
<p><code>Name= letters[1:5]</code></p>
<p><code>Amount <- c(1, 4, 9, 2, 0)</code></p>
<p><code>df <- data.frame(Name, Amount)</code></p>
<p>The problem is I have to print a pair of consecutive <strong>Name</strong> that the <strong>Amount</strong> of the name after is the most larger than the name previous. For example, in my data frame <strong>df</strong>:</p>
<p>(a,b) is 1&4 -> 4-1=3</p>
<p>(b,c) is 4&9 -> 9-4=5 (Correct answer)</p>
<p>(c,d) is 9&2 -> 9-2=-7</p>
<p>(d,e) is 2&0 -> 2-0=2</p>
<p>So the answer would be : <strong>b c</strong></p>
<p>I have tried something like <code>as.data.frame(table(df))</code> and <code>count()</code> to extract the desired value but it didn't work.</p>
|
[
{
"answer_id": 74547544,
"author": "ImotVoksim",
"author_id": 17580723,
"author_profile": "https://Stackoverflow.com/users/17580723",
"pm_score": -1,
"selected": false,
"text": "fig, axes = plt.subplots(nrows = rows, ncols = cols, figsize = (10, 10)) axes .imshow axes nrows x ncols"
},
{
"answer_id": 74582443,
"author": "Alican Kartal",
"author_id": 19970856,
"author_profile": "https://Stackoverflow.com/users/19970856",
"pm_score": 0,
"selected": false,
"text": "display_dicom def display_dicom(dicom,mask):\n\n count,width,height = mask.shape\n if count == 0:\n count = 1 # np.zeros empty mask\n \n number_of_images = count + 1 # masks + dicom\n\n fig = plt.figure(figsize=(10,10))\n rows= math.ceil(math.sqrt(number_of_images))\n cols = rows\n \n fig.add_subplot(rows,cols, 1)\n plt.imshow(dicom, cmap=plt.cm.bone) # set the color map to bone\n plt.title(\"dicom\")\n\n for i in range(count):\n fig.add_subplot(rows,cols,i+2)\n plt.imshow(mask[i],cmap=plt.cm.bone)\n plt.title(f\"mask {i+1}\")\n\n plt.show()\n\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20552762/"
] |
74,546,896
|
<p>df1:</p>
<pre><code>**Tarif von bis GK**
FedEx 0.0 1.0 G001
FedEx 1.0 2.0 G002
...
DHL. 0.0 0.5 G001
DHL. 0.5 1.0 G002
...
DPD 0.0 5.0 G001
DPD 5.0 10.0 G002
</code></pre>
<p>df2:</p>
<pre><code>**Tarif Weight GK**
FedEx 0.6
DHL 0.6
FedEx 0.5
DPD 7.5
</code></pre>
<p>My attempt:</p>
<pre><code>for i in range(len(df2)):
df2.loc[[i]['GK'] = df1['GK'].loc[(df1['Tarif'] == df2.loc[[i]]['Tarif'])
& (df1['von'] < df2[[i]]['Weight'])
& (df1['bis'] >= df2[[i]]['Weight'])]
</code></pre>
<pre><code>ValueError: Can only compare identically-labeled Series objects*
</code></pre>
<p>Result should be</p>
<p>df2:</p>
<pre><code>**Tarif Weight GK****
FedEx 0.6. G001
DHL 0.6. G002
FedEx 0.5. G001
DPD 3.5. G002
</code></pre>
|
[
{
"answer_id": 74546955,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "merge_asof (pd.merge_asof(df2.reset_index().drop(columns='GK', errors='ignore')\n .sort_values(by='Weight'),\n df1.sort_values(by='von'),\n left_on='Weight', right_on='von', by='Tarif'\n )\n .set_index('index')\n # the line below is only necessary if the bins are disjoint\n # or if there is a risk that the Weight is greater than the max \"bis\"\n .assign(GK=lambda d: d['GK'].mask(d['Weight'].gt(d['bis'])))\n .sort_index()\n #.drop(columns=['von', 'bis']) # uncomment to remove von/bis\n)\n Tarif Weight von bis GK\nindex \n0 FedEx 0.6 0.0 1.0 G001\n1 DHL 0.6 0.5 1.0 G002\n2 FedEx 0.5 0.0 1.0 G001\n3 DPD 7.5 5.0 10.0 G002\n"
},
{
"answer_id": 74547264,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "pandas.DataFrame.merge out = df2.iloc[:,:2].merge(df1, on='Tarif')\nout = out.loc[out['von'].lt(out['Weight']) & out['bis'].ge(out['Weight'])]\nout = out.reset_index(drop=True)\n Tarif Weight von bis GK\n0 FedEx 0.6 0.0 1.0 G001\n1 FedEx 0.5 0.0 1.0 G001\n2 DHL 0.6 0.5 1.0 G002\n3 DPD 7.5 5.0 10.0 G002\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581767/"
] |
74,546,910
|
<p>I have an enumerable <code>t</code> of items that expose a property <code>X</code> which is an integer.<br />
I would like to count the number of elements with <code>X < 0</code>, <code>X == 0</code> and <code>X > 0</code>.<br />
Sure I can fire three statements like this:</p>
<pre class="lang-csharp prettyprint-override"><code>var p = t.Count(a => a.X < 0);
var q = t.Count(b => b.X == 0);
var r = t.Count(c => c.X > 0);
</code></pre>
<p>But this trigger <a href="https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1851" rel="nofollow noreferrer">CA1851</a> (Possible multiple enumerations of <code>IEnumerable</code> collection).<br />
What is a better way to get the three numbers via a single enumeration using Linq ?</p>
|
[
{
"answer_id": 74547073,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 2,
"selected": false,
"text": "ToLookup GroupBy ToDictionary var xLookup = t.ToLookup(x => Math.Sign(x.X)); // Sign returns -1, 0 or 1\nint negativeCount = xLookup[-1].Count();\nint zeroCount = xLookup[0].Count();\nint positiveCount = xLookup[1].Count();\n Math.Sign var countDict = users.GroupBy(x => Math.Sign(x.X)).ToDictionary(g => g.Key, g => g.Count());\nint countNegative = countDict.TryGetValue(-1, out int cNeg) ? cNeg : 0;\nint countZero = countDict.TryGetValue(0, out int cZero) ? cZero : 0;\nint countPositive = countDict.TryGetValue(1, out int cPos) ? cPos : 0;\n Dictionary<int, int>"
},
{
"answer_id": 74547183,
"author": "Drag and Drop",
"author_id": 6560478,
"author_profile": "https://Stackoverflow.com/users/6560478",
"pm_score": 0,
"selected": false,
"text": "var baseInput = new []{1,-1,1,0,-1,1,0,-1,0};\nvar inputs = Enumerable.Range(0, 100).Select(x=> baseInput[x%baseInput.Count()]);\nvar result = inputs.Aggregate(\n (CountPositive: 0, CountNegative: 0, CountZero: 0, SumPossitive:0),\n (a, x) =>\n {\n var pos = (x>0) ? a.CountPositive + 1 : a.CountPositive;\n var neg = (x<0) ? a.CountNegative + 1 : a.CountNegative;\n var zer = (x==0) ? a.CountZero + 1 : a.CountZero;\n var sumPos = a.SumPossitive+x;\n return (pos, neg, zer, sumPos);\n });\n\nConsole.WriteLine(result);\n\n> (34, 33, 33, 1)\n"
},
{
"answer_id": 74547360,
"author": "Orace",
"author_id": 361177,
"author_profile": "https://Stackoverflow.com/users/361177",
"pm_score": 2,
"selected": false,
"text": "O(n) var (p,q,r) = t.GetCount(v => v < 0)\n .AndCount(v => v == 0)\n .AndCount(v => v > 0);\n Aggregate Aggregate var (p, q, r) = t.Aggregate(0, (pAcc, v) => pAcc + (v < 0 ? 1 : 0),\n 0, (qAcc, v) => qAcc + (v == 0 ? 1 : 0),\n 0, (rAcc, v) => rAcc + (v > 0 ? 1 : 0),\n (pAcc, qAcc, rAcc) => (pAcc, qAcc, rAcc));\n foreach var p = 0;\nvar q = 0;\nvar r = 0;\nforeach (var value in t)\n{\n switch (value)\n {\n case < 0:\n p++;\n break;\n case 0:\n q++;\n break;\n case > 0:\n r++;\n break;\n }\n}\n"
},
{
"answer_id": 74547759,
"author": "SomeBody",
"author_id": 8248570,
"author_profile": "https://Stackoverflow.com/users/8248570",
"pm_score": 1,
"selected": false,
"text": "public static int[] MultiCount<T>(this IEnumerable<T> input, params Func<T,bool> functions[])\n{\n int[] result = new int[functions.Length];\n foreach(var entry in input)\n {\n for(int i = 0; i < functions.Length; i++)\n {\n if(functions[i].Invoke(entry))\n {\n result[i]++;\n }\n }\n }\n return result;\n} \n int[] counts = t.MultiCount(\n a => a.X < 0,\n b => b.X == 0,\n c => c.X > 0);\n\nint p = counts[0];\nint q = counts[1];\nint r = counts[2];\n"
},
{
"answer_id": 74549719,
"author": "mrtig",
"author_id": 2638872,
"author_profile": "https://Stackoverflow.com/users/2638872",
"pm_score": 2,
"selected": true,
"text": "GroupBy var x = input\n .GroupBy(k=> (\n k < 0 ? 1 : 0,\n k == 0 ? 1 : 0,\n k > 0 ? 1 : 0)\n )\n .OrderByDescending(g=>g.Key)\n .Select(k=>k.Count())\n .ToArray();\n\n(int ltz, int zzz, int gtz) val = (x[0], x[1], x[2]); \n\n Math.Sign var x = t.\n .Select(i=>i.X)\n .Concat(new[] { -1, 0, 1})\n .GroupBy(Math.Sign)\n .OrderBy(k=>k.Key)\n .Select(k=>k.Count())\n .ToArray();\n\n if(x != null && x.Any())\n (int ltz, int zzz, int gtz) val = (x[0]-1, x[1]-1, x[2]-1);\n \n\n"
},
{
"answer_id": 74561588,
"author": "displayname",
"author_id": 17376447,
"author_profile": "https://Stackoverflow.com/users/17376447",
"pm_score": 0,
"selected": false,
"text": "public enum GroupEnum\n{\n EqualToZero,\n LessThanZero,\n GreaterThanZero\n}\n\nvar groups = (await t\n .GroupBy(item => item.X < 0\n ? GroupEnum.LessThanZero\n : (item.X == 0\n ? GroupEnum.EqualToZero\n : GroupEnum.GreaterThanZero\n )\n ).Select(group => new { group.Key, Count = group.Count() })\n .ToListAsync())\n .Select(o => (Case: o.Key, Count: o.Count))\n .ToArray();\n \nvar equalToZero = groups.ToArray().FirstOrDefault(x => x.Case == GroupEnum.EqualToZero).Count;\nvar greaterThanZero = groups.ToArray().FirstOrDefault(x => x.Case == GroupEnum.GreaterThanZero).Count;\nvar lessThanZero = groups.ToArray().FirstOrDefault(x => x.Case == GroupEnum.LessThanZero).Count;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17376447/"
] |
74,546,938
|
<pre><code> <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div>
<ul id="freelancer">
<li class="item active">Name</li>
<li class="item">Skills</li>
<li class="item">Cost</li>
<li class="item active">Projects</li>
</ul>
</div>
</body>
</html>
</code></pre>
<p>so here there are 2 li where the active class is available.
i want to find the active class in the list and remove the classname from there.
i tried the below example to check whether i will get the value. but it is only checking for the first li that appears. its not looping on the li's and checking.</p>
<pre><code>const div = document.querySelector('li');
console.log(div.classList.contains('active'));
</code></pre>
<p>what is the other way to do it?</p>
|
[
{
"answer_id": 74547002,
"author": "Butch",
"author_id": 7680976,
"author_profile": "https://Stackoverflow.com/users/7680976",
"pm_score": 0,
"selected": false,
"text": "querySelector() querySelectorAll() const activeLi = querySelectorAll('li.active')\n"
},
{
"answer_id": 74547140,
"author": "Maniraj Murugan",
"author_id": 7785337,
"author_profile": "https://Stackoverflow.com/users/7785337",
"pm_score": 3,
"selected": true,
"text": "querySelector querySelectorAll() querySelectorAll(li.active) item.classList.remove('active') const activeClasses = document.querySelectorAll('li.active');\n\nactiveClasses.forEach(item => item.classList.remove('active')); <!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width\">\n <title>JS Bin</title>\n</head>\n<body>\n <div>\n <ul id=\"freelancer\">\n <li class=\"item active\">Name</li>\n <li class=\"item\">Skills</li>\n <li class=\"item\">Cost</li>\n <li class=\"item active\">Projects</li>\n </ul>\n </div>\n</body>\n</html>"
},
{
"answer_id": 74547312,
"author": "Coskun Ozogul",
"author_id": 1829048,
"author_profile": "https://Stackoverflow.com/users/1829048",
"pm_score": 0,
"selected": false,
"text": "function removeActive(){\n\n var activeItems = document.querySelectorAll('li.active');\n \n Array.prototype.forEach.call(activeItems, function(item) {\n \n item.classList.remove(\"active\");\n \n });\n \n} .active{\ncolor:red;\n} <!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width\">\n <title>JS Bin</title>\n</head>\n<body>\n <div>\n <ul id=\"freelancer\">\n <li class=\"item active\">Name</li>\n <li class=\"item\">Skills</li>\n <li class=\"item\">Cost</li>\n <li class=\"item active\">Projects</li>\n </ul>\n \n <button onclick=\"removeActive();\">Remove active class</button>\n </div>\n</body>\n</html>"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10894717/"
] |
74,546,944
|
<p>I am working on a project and I have to fetch '6596626' from the source code of url= "https://www.screener.in/company/ITC/consolidated/".
The value is not visible on web page making it difficult to extract using xpath.
The below code is a part of page's source code which has the value which I want to extract.</p>
<pre><code> <div
data-company-id="1552"
data-warehouse-id="6596626"
data-user-is-registered="true"
data-consolidated="true"
id="company-info">
</div>
</code></pre>
<p>This was the code I tried on, I was expecting to extract the value straight from the source code but with no result.</p>
<pre class="lang-py prettyprint-override"><code> from urllib import request
from bs4 import BeautifulSoup
from lxml import etree
symbol=input("Enter symbol of the company\n")
response = request.urlopen("https://www.screener.in/company/"+symbol+"/consolidated/")
page_source = response.read().decode('utf-8')
soup=BeautifulSoup(page_source,'html.parser')
id=soup.get_text('data-warehouse-id')
print(id)
</code></pre>
|
[
{
"answer_id": 74547605,
"author": "baduker",
"author_id": 6106791,
"author_profile": "https://Stackoverflow.com/users/6106791",
"pm_score": 1,
"selected": true,
"text": "data-warehouse-id HTML import re\n\nimport requests\n\ndata_id = (\n re.search(\n r'data-warehouse-id=\\\"(\\d+)\\\"',\n requests.get(\"https://www.screener.in/company/ITC/consolidated/\").text,\n ).group(1)\n)\nprint(data_id)\n 6596626\n"
},
{
"answer_id": 74548854,
"author": "αԋɱҽԃ αмєяιcαη",
"author_id": 7658985,
"author_profile": "https://Stackoverflow.com/users/7658985",
"pm_score": 1,
"selected": false,
"text": "from bs4 import BeautifulSoup\nimport requests\n\n\ndef main(url):\n r = requests.get(url)\n soup = BeautifulSoup(r.text, 'lxml')\n print(soup.select_one('#company-info')['data-warehouse-id'])\n\n\nmain('https://www.screener.in/company/ITC/consolidated/')\n 6596626\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20575915/"
] |
74,546,960
|
<p>I need to create an dynamic link to to hyperlink a string so that anybody clicks on that string it opens the lin related to that day. For example if someone clicks today it will open this link. <a href="https://sobbanglay.com/sob/history-today-november-23/" rel="nofollow noreferrer">https://sobbanglay.com/sob/history-today-november-23/</a></p>
<p>Can you please help me to to create a simple script to create the above URL pattern dynamically?</p>
<p>I tried something like below, taking help from this forum but I am not able to print the month in string. Can you please help me to achive this is with simple html script like below?</p>
<pre><code><a href="https://sobbanglay.com/sob/history-today-january-01/" id="link">As it happened on today</a>
<script>
var d = new Date();
var month = d.getMonth() +1;
var day = d.getDate();
document.getElementById("link").href = "https://sobbanglay.com/sob/history-today-" + month + "-" + day + "/";
</script>
</code></pre>
|
[
{
"answer_id": 74547240,
"author": "Brok3r",
"author_id": 19534834,
"author_profile": "https://Stackoverflow.com/users/19534834",
"pm_score": 2,
"selected": true,
"text": "<a href=\"https://sobbanglay.com/sob/history-today-january-01/\" id=\"link\">As it happened on today</a><script>\nvar monthNames = [\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December\"];\n\n\n\nvar d = new Date();\nlet month = monthNames[d.getMonth()];\nvar day = d.getDate();\n\n\n\ndocument.getElementById(\"link\").href = \"https://sobbanglay.com/sob/history-today-\" + month + \"-\" + day + \"/\";\n</script>\n"
},
{
"answer_id": 74547412,
"author": "Tat",
"author_id": 19269506,
"author_profile": "https://Stackoverflow.com/users/19269506",
"pm_score": 0,
"selected": false,
"text": "<script> \nconst months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\",\"August\", \"September\", \"October\", \"November\", \"December\"];\nconst days= [\"Sun\",\"Mon\", \"Tue\",\"Wed\",\"Thurs\",\"Fri\",\"Sat\"];\nvar d = new Date();\nvar month = d.getMonth();\nvar day = d.getDay();\nvar year=d.getFullYear();\ndocument.getElementById(\"link\").href=`https://sobbanglay.com/sob/history-${days[month]}-${months[month]}-${year}`;\n</script>\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581871/"
] |
74,546,962
|
<p>I have a class and a nested class in C++ and they are both generic classes.</p>
<pre><code>#define GENERIC template<typename T>
GENERIC
class Class1 final{
private:
GENERIC
class Class2 final{
private:
T class2Field{};
};
T class1Field{};
};
</code></pre>
<p>I want to pass the type parameter <code>T</code> that is passed to <code>Class1</code> when instantiating it, all the way to the <code>Class 2</code>. How can I achieve that?</p>
|
[
{
"answer_id": 74547037,
"author": "Stack Danny",
"author_id": 6039995,
"author_profile": "https://Stackoverflow.com/users/6039995",
"pm_score": 3,
"selected": true,
"text": "Class2 Class1 Class1 T template<typename T>\nclass Class1 final {\nprivate:\n class Class2 final {\n private:\n T class2Field{};\n };\n\n T class1Field{};\n};\n Class1<int>::Class2::class2Field int Class2"
},
{
"answer_id": 74547125,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 2,
"selected": false,
"text": "template<typename T>\nclass Class1 {\nprivate:\n//-----------vvvvvvvvvvvvvv---->use default argument\n template<typename U = T>\n class Class2 {\n private:\n U class2Field{};\n };\n\n T class1Field{};\n};\n\n Class1<int>::Class2::class2Field int"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19345796/"
] |
74,546,973
|
<p>I have a problem where I want to pass a parameter in the url, in this case "id". But when I click on the url it returns a 404 error. The route exists and this
is the code.</p>
<p><em>Web.php</em></p>
<pre><code>Route::get('/chat/{id}', [App\Http\Controllers\AppController::class, 'chat'])->name('chat');
</code></pre>
<p><em>home.blade.php</em></p>
<pre><code><a href="/chat/{{$chat['id']}}">test</a>
</code></pre>
<p><em>AppController</em></p>
<pre><code>return view('chat')
</code></pre>
<p>I did not put anything in the controller yet as i first wanted to test if it even links to the blade file.</p>
<p>I tried clearing the cache of the routes and renaming anything but still no positive result.</p>
|
[
{
"answer_id": 74547103,
"author": "Erhan URGUN",
"author_id": 9476192,
"author_profile": "https://Stackoverflow.com/users/9476192",
"pm_score": 0,
"selected": false,
"text": "<?php\n\n// Path: routes/web.php\nuse App\\Http\\Controllers\\AppController;\n\nRoute::get('/chat/{id}', [AppController::class, 'chat'])->name('chat');\n\n// Path: AppController.php\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Models\\Chat;\n\nclass AppController extends Controller\n{\n public function chat($id)\n {\n $chat = Chat::find($id);\n return view('chat', compact('chat'));\n }\n}\n\n// Path: home.blade.php\n@foreach ($chats as $chat)\n <a href=\"{{ route('chat', $chat->id) }}\">{{ $chat->name }}</a>\n@endforeach\n"
},
{
"answer_id": 74548732,
"author": "Muhammad Sajidul Islam",
"author_id": 13139162,
"author_profile": "https://Stackoverflow.com/users/13139162",
"pm_score": 1,
"selected": false,
"text": "<a href=\"{{ route('chat', $chat->id) }}\">test</a>\n php artisan route:clear\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581972/"
] |
74,546,974
|
<p>I am analysing a "classic" Hibernate error :</p>
<p><code>org.hibernate.LazyInitializationException : could not initialize proxy – no Session.</code></p>
<p>I am wondering how it could happen whereas the Spring Open In View mode is enabled?</p>
<p>If you have any documentation or knowledge on a possible reason, please share.
Thanks</p>
|
[
{
"answer_id": 74550057,
"author": "Panagiotis Bougioukos",
"author_id": 7237884,
"author_profile": "https://Stackoverflow.com/users/7237884",
"pm_score": 0,
"selected": false,
"text": "@Transactional controller jackson entity json"
},
{
"answer_id": 74558076,
"author": "Guillaume Delafosse",
"author_id": 5035345,
"author_profile": "https://Stackoverflow.com/users/5035345",
"pm_score": 1,
"selected": false,
"text": "LazyInitializationException @Transactional Entitymanager LazyInitializationException LazyInitializationException org.hibernate.proxy.AbstractLazyInitializer#initialize session session EntityManager.clear EntityManager.clear EntityManager EntityManager.clear LazyInitializationException"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5035345/"
] |
74,546,978
|
<p>i am trying to get the value of the selected option but i couldn't, any help:</p>
<p>i am pretty new to JavaScript</p>
<p>help is very appreciated.</p>
<p>here is my code</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>btn = document.getElementById('submitbtn')
btn.addEventListener('click', checkOverallRating);
let overall = document.querySelector('select');
let overallValue = overall.options[overall.selectedIndex].text
function checkOverallRating(e){
if (overall == 0) {
alert(overallValue);
e.preventDefault();
}
else {
alert(overallValue);
e.preventDefault();
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><select method="POST" name="OverallRating" id="OverallRating" class="form-select form-select-lg mb-3" aria-label=".form-select-lg example">
<option value= 0 selected>Select the desired Overall Rating</option>
<option value="5">Outstanding Performance</option>
<option value="4">Excceds Target</option>
<option value="3">Meets Target</option>
<option value="2">Partially Meets Target</option>
<option value="1">Needs Improvement</option>
</select>
<button type="submit" id="submitbtn">Submit</button></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74547052,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 0,
"selected": false,
"text": "checkOverallRating() let overall = document.querySelector('select');\n let overallValue = overall.options[overall.selectedIndex].text\n checkOverallRating() <form>\n<select method=\"POST\" name=\"OverallRating\" id=\"OverallRating\" class=\"form-select form-select-lg mb-3\" aria-label=\".form-select-lg example\">\n <option value= 0 selected>Select the desired Overall Rating</option>\n <option value=\"5\">Outstanding Performance</option>\n <option value=\"4\">Excceds Target</option>\n <option value=\"3\">Meets Target</option>\n <option value=\"2\">Partially Meets Target</option>\n <option value=\"1\">Needs Improvement</option>\n </select>\n \n <button type=\"submit\" id=\"submitbtn\">Submit</button>\n\n</form>\n\n<script>\n btn = document.getElementById('submitbtn')\n btn.addEventListener('click', checkOverallRating);\n function checkOverallRating(e){\n let overall = document.querySelector('select');\n let overallValue = overall.options[overall.selectedIndex].text\n if (overall == 0) {\n alert(overallValue);\n e.preventDefault();\n }\n else {\n alert(overallValue);\n e.preventDefault();\n }\n \n }\n</script>"
},
{
"answer_id": 74547057,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 0,
"selected": false,
"text": "btn = document.getElementById('submitbtn')\nbtn.addEventListener('click', checkOverallRating);\nfunction checkOverallRating(e){\n // move these two lines into the function...\n let overall = document.querySelector('select');\n let overallValue = overall.options[overall.selectedIndex].text\n\n if (overall == 0) {\n alert(overallValue);\n e.preventDefault();\n } else {\n alert(overallValue);\n e.preventDefault();\n }\n} <select method=\"POST\" name=\"OverallRating\" id=\"OverallRating\" class=\"form-select form-select-lg mb-3\" aria-label=\".form-select-lg example\">\n <option value= 0 selected>Select the desired Overall Rating</option>\n <option value=\"5\">Outstanding Performance</option>\n <option value=\"4\">Excceds Target</option>\n <option value=\"3\">Meets Target</option>\n <option value=\"2\">Partially Meets Target</option>\n <option value=\"1\">Needs Improvement</option>\n</select>\n<button type=\"submit\" id=\"submitbtn\">Submit</button> if 0 if btn = document.getElementById('submitbtn')\nbtn.addEventListener('click', checkOverallRating);\nfunction checkOverallRating(e){\n // move these two lines into the function...\n let overall = document.querySelector('select');\n let overallValue = overall.options[overall.selectedIndex].text\n\n alert(overallValue);\n e.preventDefault();\n} <select method=\"POST\" name=\"OverallRating\" id=\"OverallRating\" class=\"form-select form-select-lg mb-3\" aria-label=\".form-select-lg example\">\n <option value= 0 selected>Select the desired Overall Rating</option>\n <option value=\"5\">Outstanding Performance</option>\n <option value=\"4\">Excceds Target</option>\n <option value=\"3\">Meets Target</option>\n <option value=\"2\">Partially Meets Target</option>\n <option value=\"1\">Needs Improvement</option>\n</select>\n<button type=\"submit\" id=\"submitbtn\">Submit</button>"
},
{
"answer_id": 74547082,
"author": "Tat",
"author_id": 19269506,
"author_profile": "https://Stackoverflow.com/users/19269506",
"pm_score": 0,
"selected": false,
"text": "document.getElementById(OverallRating).value;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16994887/"
] |
74,546,982
|
<p>I need to get the largest and the smallest number out of three using two functions. I assigned the inputted numbers to the function parameters and wrote the functions but I don't seem to be getting the value returned from the function. Code compiles and prints correctly but instead of the smallest and largest number, I am getting a bunch of zeroes.</p>
<p><strong>Edit:
When assigning the value to a variable, the variable needs to be written first. For example first = number is not the same as number = first.</strong></p>
<p><strong>Also, my way of checking which number is the largest/smallest is not done correctly here :D</strong></p>
<pre><code>#include <stdio.h>
int smallest(int first, int second, int third);
int largest(int first, int second, int third);
int main()
{
int first_number, second_number, third_number, largest_number, smallest_number;
printf("Enter the 1. number:");
scanf("%d", &first_number);
printf("Enter the 2. number:");
scanf("%d", &second_number);
printf("Enter the 3. number:");
scanf("%d", &third_number);
largest_number = largest(first_number, second_number, third_number);
smallest_number = smallest(first_number, second_number, third_number);
printf("Among the numbers you entered,\nthe largest was %d and the smallest was %d.", largest_number, smallest_number);
return 0;
}
int largest(int first, int second, int third)
{
int number;
if (first>second && second>third)
first = number;
else if (second>third && third>first)
second = number;
else
third = number;
return number;
}
int smallest(int first, int second, int third)
{
int number;
if (first<second && second<third)
first = number;
else if (second<third && third<first)
second = number;
else
third = number;
return number;
}
</code></pre>
|
[
{
"answer_id": 74547052,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 0,
"selected": false,
"text": "checkOverallRating() let overall = document.querySelector('select');\n let overallValue = overall.options[overall.selectedIndex].text\n checkOverallRating() <form>\n<select method=\"POST\" name=\"OverallRating\" id=\"OverallRating\" class=\"form-select form-select-lg mb-3\" aria-label=\".form-select-lg example\">\n <option value= 0 selected>Select the desired Overall Rating</option>\n <option value=\"5\">Outstanding Performance</option>\n <option value=\"4\">Excceds Target</option>\n <option value=\"3\">Meets Target</option>\n <option value=\"2\">Partially Meets Target</option>\n <option value=\"1\">Needs Improvement</option>\n </select>\n \n <button type=\"submit\" id=\"submitbtn\">Submit</button>\n\n</form>\n\n<script>\n btn = document.getElementById('submitbtn')\n btn.addEventListener('click', checkOverallRating);\n function checkOverallRating(e){\n let overall = document.querySelector('select');\n let overallValue = overall.options[overall.selectedIndex].text\n if (overall == 0) {\n alert(overallValue);\n e.preventDefault();\n }\n else {\n alert(overallValue);\n e.preventDefault();\n }\n \n }\n</script>"
},
{
"answer_id": 74547057,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 0,
"selected": false,
"text": "btn = document.getElementById('submitbtn')\nbtn.addEventListener('click', checkOverallRating);\nfunction checkOverallRating(e){\n // move these two lines into the function...\n let overall = document.querySelector('select');\n let overallValue = overall.options[overall.selectedIndex].text\n\n if (overall == 0) {\n alert(overallValue);\n e.preventDefault();\n } else {\n alert(overallValue);\n e.preventDefault();\n }\n} <select method=\"POST\" name=\"OverallRating\" id=\"OverallRating\" class=\"form-select form-select-lg mb-3\" aria-label=\".form-select-lg example\">\n <option value= 0 selected>Select the desired Overall Rating</option>\n <option value=\"5\">Outstanding Performance</option>\n <option value=\"4\">Excceds Target</option>\n <option value=\"3\">Meets Target</option>\n <option value=\"2\">Partially Meets Target</option>\n <option value=\"1\">Needs Improvement</option>\n</select>\n<button type=\"submit\" id=\"submitbtn\">Submit</button> if 0 if btn = document.getElementById('submitbtn')\nbtn.addEventListener('click', checkOverallRating);\nfunction checkOverallRating(e){\n // move these two lines into the function...\n let overall = document.querySelector('select');\n let overallValue = overall.options[overall.selectedIndex].text\n\n alert(overallValue);\n e.preventDefault();\n} <select method=\"POST\" name=\"OverallRating\" id=\"OverallRating\" class=\"form-select form-select-lg mb-3\" aria-label=\".form-select-lg example\">\n <option value= 0 selected>Select the desired Overall Rating</option>\n <option value=\"5\">Outstanding Performance</option>\n <option value=\"4\">Excceds Target</option>\n <option value=\"3\">Meets Target</option>\n <option value=\"2\">Partially Meets Target</option>\n <option value=\"1\">Needs Improvement</option>\n</select>\n<button type=\"submit\" id=\"submitbtn\">Submit</button>"
},
{
"answer_id": 74547082,
"author": "Tat",
"author_id": 19269506,
"author_profile": "https://Stackoverflow.com/users/19269506",
"pm_score": 0,
"selected": false,
"text": "document.getElementById(OverallRating).value;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581931/"
] |
74,546,991
|
<p>I'm trying to get the length of many nested objects with dynamic keys in an array as the below:</p>
<p>Input:</p>
<pre><code>{
"a": {
"deptAS": [
{...}
],
"deptDr": [
{...},
{...},
{...},
{...},
{...},
{...}
],
"deptES": [
{...},
{...}
],
"deptGW": [
{...
}
]
},
"b": {
"deptDr": [
{...},
{...},
{...},
{...},
{...}
],
"deptES": [
{...},
{...},
{...},
{...}
],
"deptLU": [
{...},
{...}
],
"deptSR": [
{...},
{...}
]
},
}
</code></pre>
<p>Which would return:</p>
<pre><code>"a": {
"deptAS": 1,
"deptDr": 6
"deptES": 2,
"deptGW": 1
}
"b": {
"deptDr":5,
"deptES":4,
"deptLU":2,
"deptSR":2,
}
</code></pre>
<p>I've tried various .map and lodash functions but can't get the data out in the format required, but I suspect the solution is very simple.</p>
<p>There is access to Lodash in the project already so that can be used</p>
|
[
{
"answer_id": 74547120,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 2,
"selected": false,
"text": "const\n data = { a: { deptAS: [{}], deptDr: [{}, {}, {}, {}, {}, {}], deptES: [{}, {}], deptGW: [{}] }, b: { deptDr: [{}, {}, {}, {}, {}], deptES: [{}, {}, {}, {}], deptLU: [{}, {}], deptSR: [{}, {}] } },\n getLength = object => Object.fromEntries(Object\n .entries(object)\n .map(([k, v]) => [k, v.length ?? getLength(v)])\n ),\n result = getLength(data);\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74547129,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 0,
"selected": false,
"text": "Object#entries Array#reduce const obj = {\n \"a\": {\n \"deptAS\": [ {} ],\n \"deptDr\": [ {}, {}, {}, {}, {}, {} ],\n \"deptES\": [ {}, {} ],\n \"deptGW\": [ {} ]\n },\n \"b\": {\n \"deptDr\": [ {}, {}, {}, {}, {} ],\n \"deptES\": [ {}, {}, {}, {} ],\n \"deptLU\": [ {}, {} ],\n \"deptSR\": [ {}, {} ]\n }\n};\n\nconst res = Object.entries(obj).reduce((acc, [key, value]) => {\n acc[key] = {};\n Object.entries(value).forEach(([prop, arr]) => { acc[key][prop] = arr.length });\n return acc;\n}, {});\n\nconsole.log(res);"
},
{
"answer_id": 74547485,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": true,
"text": "result = _.mapValues(yourObject, v => _.mapValues(v, 'length'))\n _.mapValues"
},
{
"answer_id": 74547488,
"author": "Erique Bomfim",
"author_id": 2088394,
"author_profile": "https://Stackoverflow.com/users/2088394",
"pm_score": 0,
"selected": false,
"text": "p = {\n \"a\": {\n \"deptAS\": [\n {}\n ],\n \"deptDr\": [\n {},\n {},\n {},\n {},\n {},\n {}\n ],\n \"deptES\": [\n {},\n {}\n ],\n \"deptGW\": [\n {\n }\n ]\n },\n \"b\": {\n \"deptDr\": [\n {},\n {},\n {},\n {},\n {}\n ],\n \"deptES\": [\n {},\n {},\n {},\n {}\n ],\n \"deptLU\": [\n {},\n {}\n ],\n \"deptSR\": [\n {},\n {}\n ]\n }\n}\n\ncalcProp = function(obj){\n \n const _props = Object.keys(obj);\n var _output = {};\n\n _props.forEach(_p=>{\n /* this way we avoid string calculation*/\n if (obj[_p].constructor.name == \"Array\"){\n _output[_p] = obj[_p].length\n }\n /* this way we go thought any level*/\n if (obj[_p].constructor.name == \"Object\"){\n _output[_p] = calcProp(obj[_p])\n }\n })\n\n return _output;\n}\n \nd = calcProp(p);\n \nconsole.log(d); "
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581768/"
] |
74,547,020
|
<p><strong>TLDR;</strong></p>
<p>I have a react-native mobile application which needs to receive a file shared by ther other application.</p>
<p><strong>Details:</strong></p>
<p>I am trying to receive this file inside my own application. And since I am new to React/React-native/Expo/Android development I am not sure how it's coded in react native.</p>
<ol start="0">
<li>connect the mobile device to phone and allow development and tethering. or have emulator ready</li>
</ol>
<p><strong>Mobile App:</strong></p>
<p>run following commands in the terminal:</p>
<pre><code>git clone https://github.com/dimaportenko/react-native-receive-share-file-tutorial
run yarn install
run yarn android
</code></pre>
<p><strong>Browser:</strong></p>
<ol start="4">
<li><p>In broswer of the mobile phone navigate to <a href="https://w3c.github.io/web-share/demos/share-files.html" rel="nofollow noreferrer">https://w3c.github.io/web-share/demos/share-files.html</a></p>
</li>
<li><p>Fill Data.</p>
</li>
<li><p>Attach a file.</p>
</li>
<li><p>click 'Share'</p>
</li>
<li><p>Select the 'rnrecievesharetutorial'</p>
</li>
<li><p>This should show something like following</p>
<p>Received Files Array [
Object {
"contentUri": null,
"extension": null,
"fileName": null,
"filePath": null,
"subject": "Credential Offer",
"text": "Choose a wallet to process this offer.",
"weblink": null,
},
]</p>
</li>
</ol>
<p><strong>Question:</strong></p>
<p>Can you please share some code which allows me to get the file data ?</p>
<p>The website has indeed shared the file data. As a proof: if you select the email/gmail application on your phone it should add the file as an attachement.</p>
|
[
{
"answer_id": 74547120,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 2,
"selected": false,
"text": "const\n data = { a: { deptAS: [{}], deptDr: [{}, {}, {}, {}, {}, {}], deptES: [{}, {}], deptGW: [{}] }, b: { deptDr: [{}, {}, {}, {}, {}], deptES: [{}, {}, {}, {}], deptLU: [{}, {}], deptSR: [{}, {}] } },\n getLength = object => Object.fromEntries(Object\n .entries(object)\n .map(([k, v]) => [k, v.length ?? getLength(v)])\n ),\n result = getLength(data);\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74547129,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 0,
"selected": false,
"text": "Object#entries Array#reduce const obj = {\n \"a\": {\n \"deptAS\": [ {} ],\n \"deptDr\": [ {}, {}, {}, {}, {}, {} ],\n \"deptES\": [ {}, {} ],\n \"deptGW\": [ {} ]\n },\n \"b\": {\n \"deptDr\": [ {}, {}, {}, {}, {} ],\n \"deptES\": [ {}, {}, {}, {} ],\n \"deptLU\": [ {}, {} ],\n \"deptSR\": [ {}, {} ]\n }\n};\n\nconst res = Object.entries(obj).reduce((acc, [key, value]) => {\n acc[key] = {};\n Object.entries(value).forEach(([prop, arr]) => { acc[key][prop] = arr.length });\n return acc;\n}, {});\n\nconsole.log(res);"
},
{
"answer_id": 74547485,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": true,
"text": "result = _.mapValues(yourObject, v => _.mapValues(v, 'length'))\n _.mapValues"
},
{
"answer_id": 74547488,
"author": "Erique Bomfim",
"author_id": 2088394,
"author_profile": "https://Stackoverflow.com/users/2088394",
"pm_score": 0,
"selected": false,
"text": "p = {\n \"a\": {\n \"deptAS\": [\n {}\n ],\n \"deptDr\": [\n {},\n {},\n {},\n {},\n {},\n {}\n ],\n \"deptES\": [\n {},\n {}\n ],\n \"deptGW\": [\n {\n }\n ]\n },\n \"b\": {\n \"deptDr\": [\n {},\n {},\n {},\n {},\n {}\n ],\n \"deptES\": [\n {},\n {},\n {},\n {}\n ],\n \"deptLU\": [\n {},\n {}\n ],\n \"deptSR\": [\n {},\n {}\n ]\n }\n}\n\ncalcProp = function(obj){\n \n const _props = Object.keys(obj);\n var _output = {};\n\n _props.forEach(_p=>{\n /* this way we avoid string calculation*/\n if (obj[_p].constructor.name == \"Array\"){\n _output[_p] = obj[_p].length\n }\n /* this way we go thought any level*/\n if (obj[_p].constructor.name == \"Object\"){\n _output[_p] = calcProp(obj[_p])\n }\n })\n\n return _output;\n}\n \nd = calcProp(p);\n \nconsole.log(d); "
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5462398/"
] |
74,547,036
|
<p>I like to create scenarios in my code where I declare a static global struct inside a .c file that everyone will share, it contains configuration stuff. Right underneath the declaration, I'll create a constant pointer to this struct and put this in the .h file so that everyone can get access to it.</p>
<p>Sometimes, within a .c file, I like to have a global pointer to the specific configuration that that .c file cares about, that way I don't have constantly keep referencing the global struct, because sometimes I'll get this configuration from a different source on different projects.</p>
<p>The issue that I have is that I can't define this "local global" pointer because the initializer element is not constant. Here is an example.</p>
<pre><code>typedef struct
{
int Value;
} mystruct_t, *pmystruct_t;
static const mystruct_t GlobalStruct;
const pmystruct_t pGlobalStruct = &GlobalStruct;
const int *ValuePtr = &pGlobalStruct->Value;
int main()
{
*ValuePtr = 10;
return 0;
}
</code></pre>
<p>I tried reading on the const keywords for pointer in C, and I thought I understood it, but apparently it's still a mystery to me. The line of code that I tried, and may gotten me closer to that piece of code to compile is</p>
<pre><code>const mystruct_t const *pGlobalStruct = &GlobalStruct;
</code></pre>
<p>However, it still doesn't compile because ValuePtr initializer element is not constant (the error I get).</p>
<p>The end goal here is to have ValuePtr be a constant, where no one can change where it is pointing to, but allow change the elements of the struct that it is pointing to.</p>
<p>EDIT: I want ValuePtr to use pGlobalStruct</p>
|
[
{
"answer_id": 74547120,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 2,
"selected": false,
"text": "const\n data = { a: { deptAS: [{}], deptDr: [{}, {}, {}, {}, {}, {}], deptES: [{}, {}], deptGW: [{}] }, b: { deptDr: [{}, {}, {}, {}, {}], deptES: [{}, {}, {}, {}], deptLU: [{}, {}], deptSR: [{}, {}] } },\n getLength = object => Object.fromEntries(Object\n .entries(object)\n .map(([k, v]) => [k, v.length ?? getLength(v)])\n ),\n result = getLength(data);\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74547129,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 0,
"selected": false,
"text": "Object#entries Array#reduce const obj = {\n \"a\": {\n \"deptAS\": [ {} ],\n \"deptDr\": [ {}, {}, {}, {}, {}, {} ],\n \"deptES\": [ {}, {} ],\n \"deptGW\": [ {} ]\n },\n \"b\": {\n \"deptDr\": [ {}, {}, {}, {}, {} ],\n \"deptES\": [ {}, {}, {}, {} ],\n \"deptLU\": [ {}, {} ],\n \"deptSR\": [ {}, {} ]\n }\n};\n\nconst res = Object.entries(obj).reduce((acc, [key, value]) => {\n acc[key] = {};\n Object.entries(value).forEach(([prop, arr]) => { acc[key][prop] = arr.length });\n return acc;\n}, {});\n\nconsole.log(res);"
},
{
"answer_id": 74547485,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": true,
"text": "result = _.mapValues(yourObject, v => _.mapValues(v, 'length'))\n _.mapValues"
},
{
"answer_id": 74547488,
"author": "Erique Bomfim",
"author_id": 2088394,
"author_profile": "https://Stackoverflow.com/users/2088394",
"pm_score": 0,
"selected": false,
"text": "p = {\n \"a\": {\n \"deptAS\": [\n {}\n ],\n \"deptDr\": [\n {},\n {},\n {},\n {},\n {},\n {}\n ],\n \"deptES\": [\n {},\n {}\n ],\n \"deptGW\": [\n {\n }\n ]\n },\n \"b\": {\n \"deptDr\": [\n {},\n {},\n {},\n {},\n {}\n ],\n \"deptES\": [\n {},\n {},\n {},\n {}\n ],\n \"deptLU\": [\n {},\n {}\n ],\n \"deptSR\": [\n {},\n {}\n ]\n }\n}\n\ncalcProp = function(obj){\n \n const _props = Object.keys(obj);\n var _output = {};\n\n _props.forEach(_p=>{\n /* this way we avoid string calculation*/\n if (obj[_p].constructor.name == \"Array\"){\n _output[_p] = obj[_p].length\n }\n /* this way we go thought any level*/\n if (obj[_p].constructor.name == \"Object\"){\n _output[_p] = calcProp(obj[_p])\n }\n })\n\n return _output;\n}\n \nd = calcProp(p);\n \nconsole.log(d); "
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11019890/"
] |
74,547,044
|
<p>I have nested arrays which contain a data string value and number value for a period of time. I want to be able to loop through these to find out which month has highest amount sales by comparing one month another e.g jan > feb, feb - march, march to april etc... and produce output which states JAN 500 or something similar, i am not able to figure how these needs to be done, i am just starting out in javscript</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>const sales = [
['jan-2010', 200000],
['feb-2010', 400000],
['mar-2010', 100000]
];
for (let i = 0; i < sales.length; i++) {
for (let j = 0; j < sales[i].length; j++)
if (typeof sales[i][j] === "number") {
};
}</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74547120,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 2,
"selected": false,
"text": "const\n data = { a: { deptAS: [{}], deptDr: [{}, {}, {}, {}, {}, {}], deptES: [{}, {}], deptGW: [{}] }, b: { deptDr: [{}, {}, {}, {}, {}], deptES: [{}, {}, {}, {}], deptLU: [{}, {}], deptSR: [{}, {}] } },\n getLength = object => Object.fromEntries(Object\n .entries(object)\n .map(([k, v]) => [k, v.length ?? getLength(v)])\n ),\n result = getLength(data);\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74547129,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 0,
"selected": false,
"text": "Object#entries Array#reduce const obj = {\n \"a\": {\n \"deptAS\": [ {} ],\n \"deptDr\": [ {}, {}, {}, {}, {}, {} ],\n \"deptES\": [ {}, {} ],\n \"deptGW\": [ {} ]\n },\n \"b\": {\n \"deptDr\": [ {}, {}, {}, {}, {} ],\n \"deptES\": [ {}, {}, {}, {} ],\n \"deptLU\": [ {}, {} ],\n \"deptSR\": [ {}, {} ]\n }\n};\n\nconst res = Object.entries(obj).reduce((acc, [key, value]) => {\n acc[key] = {};\n Object.entries(value).forEach(([prop, arr]) => { acc[key][prop] = arr.length });\n return acc;\n}, {});\n\nconsole.log(res);"
},
{
"answer_id": 74547485,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": true,
"text": "result = _.mapValues(yourObject, v => _.mapValues(v, 'length'))\n _.mapValues"
},
{
"answer_id": 74547488,
"author": "Erique Bomfim",
"author_id": 2088394,
"author_profile": "https://Stackoverflow.com/users/2088394",
"pm_score": 0,
"selected": false,
"text": "p = {\n \"a\": {\n \"deptAS\": [\n {}\n ],\n \"deptDr\": [\n {},\n {},\n {},\n {},\n {},\n {}\n ],\n \"deptES\": [\n {},\n {}\n ],\n \"deptGW\": [\n {\n }\n ]\n },\n \"b\": {\n \"deptDr\": [\n {},\n {},\n {},\n {},\n {}\n ],\n \"deptES\": [\n {},\n {},\n {},\n {}\n ],\n \"deptLU\": [\n {},\n {}\n ],\n \"deptSR\": [\n {},\n {}\n ]\n }\n}\n\ncalcProp = function(obj){\n \n const _props = Object.keys(obj);\n var _output = {};\n\n _props.forEach(_p=>{\n /* this way we avoid string calculation*/\n if (obj[_p].constructor.name == \"Array\"){\n _output[_p] = obj[_p].length\n }\n /* this way we go thought any level*/\n if (obj[_p].constructor.name == \"Object\"){\n _output[_p] = calcProp(obj[_p])\n }\n })\n\n return _output;\n}\n \nd = calcProp(p);\n \nconsole.log(d); "
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581800/"
] |
74,547,050
|
<p>I'm newbie in Java and wanna ask you question. Let's imagine the situation. I generate account for testing purposes using API and in response I get line e.g. such as:</p>
<pre><code>{
"accountId": "42515896"
}
</code></pre>
<p>How could I write method that will take this "42515896" from the response and insert it into some int variable that I declared before?</p>
<pre><code>public class failedAuthorization {
// created reference variable for WebDriver
WebDriver driver;
@BeforeMethod
public void setup() {
System.setProperty("webdriver.chrome.driver","C:\\Users\\imagineName.imagineSurname\\chromedriver\\chromedriver.exe");
// initializing driver variable using Chrome Driver
driver=new ChromeDriver();
driver.manage().deleteAllCookies();
// launching google.com on the browser
driver.get("https://login.live.com/");
// maximized the browser window
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
}
</code></pre>
<p>e.g. I have some API request that generate me account and in response I get data that I will need further to login. How to use generated data?</p>
|
[
{
"answer_id": 74547191,
"author": "Pekinek",
"author_id": 5198144,
"author_profile": "https://Stackoverflow.com/users/5198144",
"pm_score": 1,
"selected": false,
"text": "String jsonString = \"{'accountId': '42515896'}\";\nObjectMapper mapper = new ObjectMapper();\nJsonNode actualObj = mapper.readTree(jsonString);\nactualObj.get(\"accountId\").textValue(); //returns 42515896\n"
},
{
"answer_id": 74548592,
"author": "Alex Karamfilov",
"author_id": 7031148,
"author_profile": "https://Stackoverflow.com/users/7031148",
"pm_score": 0,
"selected": false,
"text": " public static void main(String[] args) {\n String myJson = \"{\\\"accountId\\\": \\\"42515896\\\"}\";\n String accountId = JsonPath.read(myJson, \"$.accountId\");\n System.out.println(accountId);\n }\n <!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->\n<dependency>\n <groupId>com.jayway.jsonpath</groupId>\n <artifactId>json-path</artifactId>\n <version>2.7.0</version>\n</dependency>\n\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16042806/"
] |
74,547,069
|
<p>I want to define a complete SQL statement condition after <code>where</code> through the linking implementation of string, because I am not sure how many conditions after <code>where</code> there are.</p>
<pre><code>for (int i = 0; i < listView2.Items.Count; i++)
{
if (!is_first)
{
para += "maccount" +" "+ "=" + listView2.Items[i].Text;
is_first = true;
}
else
{
para += " or " + "maccount"+"="+ listView2.Items[i].Text;
}
}
MessageBox.Show(para);
string sql3 = "select maccount,msum from pharmaceutical_stocks where @para";
SqlParameter[] parameters3 = new SqlParameter[]
{
new SqlParameter("@para",para)
};
DataTable dt = sqlcontent.dt(sql3, parameters3);
</code></pre>
<p>I want to find data in the database by the information saved in each item in listview2。</p>
<p>But I get this exception:</p>
<blockquote>
<p>System.Data.SqlClient.SqlException: An expression of non-Boolean type is specified in the context in which the condition should be used (near '@para').</p>
</blockquote>
|
[
{
"answer_id": 74547332,
"author": "Steve",
"author_id": 1197518,
"author_profile": "https://Stackoverflow.com/users/1197518",
"pm_score": 3,
"selected": true,
"text": "StringBuilder inText = new StringBuilder();\nList<SqlParameter> prms = new List<SqlParameter>();\nfor(int i = 0; i < listView2.Items.Count; i++)\n{\n SqlParameter p = new SqlParameter(\"@p\" + i, SqlDbType.NVarChar);\n p.Value = listView2.Items[i].Text;\n prms.Add(p);\n inText.Append($\"@p{i},\");\n}\nif(inText.Length > 0) inText.Length--;\nstring sql3 = $@\"select maccount,msum \n from pharmaceutical_stocks \n where maccount in({inText.ToString()})\";\nDataTable dt = sqlcontent.dt(sql3, prms.ToArray());\n"
},
{
"answer_id": 74547470,
"author": "vadim",
"author_id": 816227,
"author_profile": "https://Stackoverflow.com/users/816227",
"pm_score": -1,
"selected": false,
"text": "const string sql = \"select maccount, msum from pharmaceutical_stocks where maccount in ({0})\";\nstring sqlCommand = string.Format(sql, string.Join(\",\", parameters.Select(p => p.ParameterName)));\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20485257/"
] |
74,547,096
|
<p>I want to start my app.jar (Spring Boot) using other properties by providing some yaml files e.g. in folders</p>
<pre><code>/opt/app/app1/application1.yaml
/opt/app/app2/application2.yaml
/opt/app/app3/application3.yaml
</code></pre>
<p>Each yaml is for one app configuration.</p>
<p>Is there any way to give the new application.yaml as a parameter after the jar sth. like:</p>
<pre><code>java -jar /opt/app/app.jar /opt/app/app3/application1.yaml
java -jar /opt/app/app.jar /opt/app/app3/application2.yaml
java -jar /opt/app/app.jar /opt/app/app3/application3.yaml
</code></pre>
<p>We start our application by using the PropertiesLauncher with -cp</p>
<pre><code>java -Xmx4096M -cp /opt/app/app.jar -Dloader.path=additional-libs/ -Dloader.main=app.SpringBootApplication org.springframework.boot.loader.PropertiesLauncher
</code></pre>
|
[
{
"answer_id": 74547332,
"author": "Steve",
"author_id": 1197518,
"author_profile": "https://Stackoverflow.com/users/1197518",
"pm_score": 3,
"selected": true,
"text": "StringBuilder inText = new StringBuilder();\nList<SqlParameter> prms = new List<SqlParameter>();\nfor(int i = 0; i < listView2.Items.Count; i++)\n{\n SqlParameter p = new SqlParameter(\"@p\" + i, SqlDbType.NVarChar);\n p.Value = listView2.Items[i].Text;\n prms.Add(p);\n inText.Append($\"@p{i},\");\n}\nif(inText.Length > 0) inText.Length--;\nstring sql3 = $@\"select maccount,msum \n from pharmaceutical_stocks \n where maccount in({inText.ToString()})\";\nDataTable dt = sqlcontent.dt(sql3, prms.ToArray());\n"
},
{
"answer_id": 74547470,
"author": "vadim",
"author_id": 816227,
"author_profile": "https://Stackoverflow.com/users/816227",
"pm_score": -1,
"selected": false,
"text": "const string sql = \"select maccount, msum from pharmaceutical_stocks where maccount in ({0})\";\nstring sqlCommand = string.Format(sql, string.Join(\",\", parameters.Select(p => p.ParameterName)));\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7762344/"
] |
74,547,128
|
<p>I need to create a AWS container with ECS. However, I don't have programatic access for push the image in the ECR repository and I don't found other way to create a container.</p>
<p>My question is: Is there another way to create a container without programatic access?</p>
<p>I found a way to upload the image in Amazon S3 (compress the image into a .zip), but I don't know how to use the image after the upload.</p>
|
[
{
"answer_id": 74547332,
"author": "Steve",
"author_id": 1197518,
"author_profile": "https://Stackoverflow.com/users/1197518",
"pm_score": 3,
"selected": true,
"text": "StringBuilder inText = new StringBuilder();\nList<SqlParameter> prms = new List<SqlParameter>();\nfor(int i = 0; i < listView2.Items.Count; i++)\n{\n SqlParameter p = new SqlParameter(\"@p\" + i, SqlDbType.NVarChar);\n p.Value = listView2.Items[i].Text;\n prms.Add(p);\n inText.Append($\"@p{i},\");\n}\nif(inText.Length > 0) inText.Length--;\nstring sql3 = $@\"select maccount,msum \n from pharmaceutical_stocks \n where maccount in({inText.ToString()})\";\nDataTable dt = sqlcontent.dt(sql3, prms.ToArray());\n"
},
{
"answer_id": 74547470,
"author": "vadim",
"author_id": 816227,
"author_profile": "https://Stackoverflow.com/users/816227",
"pm_score": -1,
"selected": false,
"text": "const string sql = \"select maccount, msum from pharmaceutical_stocks where maccount in ({0})\";\nstring sqlCommand = string.Format(sql, string.Join(\",\", parameters.Select(p => p.ParameterName)));\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19362097/"
] |
74,547,141
|
<p>Lets say I have function that triggers when table is being updated. Then it tries to send this data as json into remote database via dblink:</p>
<pre><code>statement := 'INSERT INTO mytable(my_data) VALUES (''' || my_json || ''')';
PERFORM dblink('my connection data', statement);
</code></pre>
<p><code>my_json </code> is formed by <code>json_build_object</code> method with some dynamic data. When some of this json fields values contains single quote, this function starts throw syntax errors.</p>
<p>I know that I need to use double single quotes, but I can't because data is dynamic.</p>
<p>For example if my json is like this:</p>
<pre><code>{ "a": "It's a test" }
</code></pre>
<p>It throws:</p>
<p>Syntax error at s</p>
|
[
{
"answer_id": 74547332,
"author": "Steve",
"author_id": 1197518,
"author_profile": "https://Stackoverflow.com/users/1197518",
"pm_score": 3,
"selected": true,
"text": "StringBuilder inText = new StringBuilder();\nList<SqlParameter> prms = new List<SqlParameter>();\nfor(int i = 0; i < listView2.Items.Count; i++)\n{\n SqlParameter p = new SqlParameter(\"@p\" + i, SqlDbType.NVarChar);\n p.Value = listView2.Items[i].Text;\n prms.Add(p);\n inText.Append($\"@p{i},\");\n}\nif(inText.Length > 0) inText.Length--;\nstring sql3 = $@\"select maccount,msum \n from pharmaceutical_stocks \n where maccount in({inText.ToString()})\";\nDataTable dt = sqlcontent.dt(sql3, prms.ToArray());\n"
},
{
"answer_id": 74547470,
"author": "vadim",
"author_id": 816227,
"author_profile": "https://Stackoverflow.com/users/816227",
"pm_score": -1,
"selected": false,
"text": "const string sql = \"select maccount, msum from pharmaceutical_stocks where maccount in ({0})\";\nstring sqlCommand = string.Format(sql, string.Join(\",\", parameters.Select(p => p.ParameterName)));\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3003432/"
] |
74,547,190
|
<p>jdk 11 was fine on my mac os Mojave. On upgrading to Mac OS Ventura, I started seeing this popup error:</p>
<p><a href="https://i.stack.imgur.com/yoPkq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yoPkq.png" alt="enter image description here" /></a></p>
<p>openjdk-11.0.2 is damaged and can't be opened.I uninstalled and reinstalled openjdk11 using brew but still get the same error:</p>
<pre><code>$ brew uninstall openjdk@11
Uninstalling /usr/local/Cellar/openjdk@11/11.0.16.1_1... (678 files, 298.8MB)
$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
1.8.261.12 (x86_64) "Oracle Corporation" - "Java" /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
1.8.0_191 (x86_64) "Oracle Corporation" - "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home
/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
$ brew install openjdk@11
==> Downloading https://ghcr.io/v2/homebrew/core/openjdk/11/manifests/11.0.16.1_1
Already downloaded: /Users/user/Library/Caches/Homebrew/downloads/66d77b9adc57a7f85fca1b4c90e6187f64aa336a0777d7dc1014151d925df3d8--openjdk@11-11.0.16.1_1.bottle_manifest.json
==> Downloading https://ghcr.io/v2/homebrew/core/openjdk/11/blobs/sha256:4157114f6dd128b93d0732559787f191678d2d496476e19855a03d0f226aa50c
Already downloaded: /Users/user/Library/Caches/Homebrew/downloads/853c10b19f8f8cd779b49261c60a74abf52e9fea1067d934c45549bea2b8ed3e--openjdk@11--11.0.16.1_1.ventura.bottle.tar.gz
==> Pouring openjdk@11--11.0.16.1_1.ventura.bottle.tar.gz
==> Caveats
For the system Java wrappers to find this JDK, symlink it with
sudo ln -sfn /usr/local/opt/openjdk@11/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-11.jdk
openjdk@11 is keg-only, which means it was not symlinked into /usr/local,
because this is an alternate version of another formula.
If you need to have openjdk@11 first in your PATH, run:
echo 'export PATH="/usr/local/opt/openjdk@11/bin:$PATH"' >> /Users/user/.bash_profile
For compilers to find openjdk@11 you may need to set:
export CPPFLAGS="-I/usr/local/opt/openjdk@11/include"
==> Summary
� /usr/local/Cellar/openjdk@11/11.0.16.1_1: 678 files, 298.8MB
==> Running `brew cleanup openjdk@11`...
Disable this behaviour by setting HOMEBREW_NO_INSTALL_CLEANUP.
Hide these hints with HOMEBREW_NO_ENV_HINTS (see `man brew`).
</code></pre>
|
[
{
"answer_id": 74563141,
"author": "user674669",
"author_id": 674669,
"author_profile": "https://Stackoverflow.com/users/674669",
"pm_score": 0,
"selected": false,
"text": "/Library/Java/JavaVirtualMachines/\n /usr/local/Cellar/\n brew install openjdk@11\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/674669/"
] |
74,547,236
|
<p>Given a <code>std::chrono::sys_seconds time</code>, one might expect to reassign <code>time</code> from its clock with something like:</p>
<pre class="lang-cpp prettyprint-override"><code>time = decltype(time)::clock::now();
</code></pre>
<p>However, this would likely fail, because <code>decltype(time)::clock::duration</code> has nothing to do with <code>decltype(time)</code>. Instead it is a predefined unit(likely finer than <code>seconds</code>), so you would have to manually cast it to a coarser unit.</p>
<p>Which means you would need to write something like:</p>
<pre class="lang-cpp prettyprint-override"><code>time = std::chrono::time_point_cast<decltype(time)::duration>(decltype(time)::clock::now());
</code></pre>
<hr />
<p>So my question is if there is a shorter syntax to do this?</p>
|
[
{
"answer_id": 74563141,
"author": "user674669",
"author_id": 674669,
"author_profile": "https://Stackoverflow.com/users/674669",
"pm_score": 0,
"selected": false,
"text": "/Library/Java/JavaVirtualMachines/\n /usr/local/Cellar/\n brew install openjdk@11\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12861639/"
] |
74,547,254
|
<pre><code>DATA = data.frame(STUDENT = c(1,1,1,1,1,1,2,2,2,2,2, 3,3,3),
YEAR = c(2000, 2000, 2000, 2001, 2001, 2001, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001),
TRIMESTER= c(1,2,3,1,2,3,2,3,1,2,3,1,2,3),
SCORE = c(5,7,8,9,10,3,4,6,3,1,2,3,6, 9),
WANT = c(NA,NA,NA,4,3,-5,NA,NA,NA,-3,-4,NA,NA,NA))
</code></pre>
<p>I have DATA and wish to create 'WANT' which is calculate by:</p>
<p>For each STUDENT, find the SCORE where (YEAR = YEAR +1, TRIMESTER = TRIMESTER) and get the difference.</p>
<pre><code>EX: SCORE(STUDENT = 1, TRIMESTER = 1, YEAR = 2001) - SCORE(STUDENT = 1, TRIMESTER = 1, YEAR = 2000)
</code></pre>
|
[
{
"answer_id": 74547298,
"author": "nd37255",
"author_id": 12710567,
"author_profile": "https://Stackoverflow.com/users/12710567",
"pm_score": 3,
"selected": true,
"text": "library(tidyverse)\n\nDATA = data.frame(STUDENT = c(1,1,1,1,1,1,2,2,2,2,2, 3,3,3),\n YEAR = c(2000, 2000, 2000, 2001, 2001, 2001, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001),\n TRIMESTER= c(1,2,3,1,2,3,2,3,1,2,3,1,2,3),\n SCORE = c(5,7,8,9,10,3,4,6,3,1,2,3,6, 9),\n WANT = c(NA,NA,NA,4,3,-5,NA,NA,NA,-3,-4,NA,NA,NA))\n\nDATA <- as_tibble(DATA)\n\nDATA %>% \n group_by(STUDENT, TRIMESTER) %>% \n mutate(LAST = lag(SCORE),\n DIFF = SCORE - LAST)\n#> # A tibble: 14 x 7\n#> # Groups: STUDENT, TRIMESTER [9]\n#> STUDENT YEAR TRIMESTER SCORE WANT LAST DIFF\n#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n#> 1 1 2000 1 5 NA NA NA\n#> 2 1 2000 2 7 NA NA NA\n#> 3 1 2000 3 8 NA NA NA\n#> 4 1 2001 1 9 4 5 4\n#> 5 1 2001 2 10 3 7 3\n#> 6 1 2001 3 3 -5 8 -5\n#> 7 2 2000 2 4 NA NA NA\n#> 8 2 2000 3 6 NA NA NA\n#> 9 2 2001 1 3 NA NA NA\n#> 10 2 2001 2 1 -3 4 -3\n#> 11 2 2001 3 2 -4 6 -4\n#> 12 3 2001 1 3 NA NA NA\n#> 13 3 2001 2 6 NA NA NA\n#> 14 3 2001 3 9 NA NA NA\n"
},
{
"answer_id": 74547511,
"author": "user2974951",
"author_id": 2974951,
"author_profile": "https://Stackoverflow.com/users/2974951",
"pm_score": 1,
"selected": false,
"text": "DATA = data.frame(STUDENT = c(1,1,1,1,1,1,2,2,2,2,2, 3,3,3),\n YEAR = c(2000, 2000, 2000, 2001, 2001, 2001, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001),\n TRIMESTER= c(1,2,3,1,2,3,2,3,1,2,3,1,2,3),\n SCORE = c(5,7,8,9,10,3,4,6,3,1,2,3,6, 9))\n DATA=merge(\n DATA,\n cbind(\n DATA[,c(\"STUDENT\",\"TRIMESTER\")],\n DATA[,\"YEAR\",drop=F]+1,\n \"MATCH\"=DATA[,\"SCORE\"]\n ),\n by=c(\"STUDENT\",\"YEAR\",\"TRIMESTER\"),\n all.x=T\n)\nDATA$WANT=DATA$SCORE-DATA$MATCH\n STUDENT YEAR TRIMESTER SCORE MATCH WANT\n1 1 2000 1 5 NA NA\n2 1 2000 2 7 NA NA\n3 1 2000 3 8 NA NA\n4 1 2001 1 9 5 4\n5 1 2001 2 10 7 3\n6 1 2001 3 3 8 -5\n7 2 2000 2 4 NA NA\n8 2 2000 3 6 NA NA\n9 2 2001 1 3 NA NA\n10 2 2001 2 1 4 -3\n11 2 2001 3 2 6 -4\n12 3 2001 1 3 NA NA\n13 3 2001 2 6 NA NA\n14 3 2001 3 9 NA NA\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619171/"
] |
74,547,307
|
<p>The objective:
I have a package with submodules that I would like to be accessible in the most straightforward way possible. <strong>The submodules contain classes</strong> to take advantage of the class structure, but don't need to be initialized (as they contain static and class methods). So, ideally, I would like to access them as follows:</p>
<pre><code>from myPackage.subModule import someMethod
print (someMethod)
from myPackage import subModule
print (subModule.someMethod)
import myPackage
print(myPackage.subModule.someMethod)
</code></pre>
<p>Here is the package structure:</p>
<pre><code>myPackage ─┐
__init__.py
subModule
subModule2
etc.
</code></pre>
<p>Example of a typical submodule:</p>
<pre><code># submodule.py
class SomeClass():
someAttr = list(range(10))
@classmethod
def someMethod(cls):
pass
@staticmethod
def someMethod2():
pass
</code></pre>
<p>Here is the code I have in my '__init __.py': In order to achieve the above; it attempts to set attributes for each class at the package level, and the same for it's methods at the sub-module level.</p>
<pre><code># __init__.py
def import_submodules(package, filetypes=('py', 'pyc', 'pyd'), ignoreStartingWith='_'):
'''Import submodules to the given package, expose any classes at the package level
and their respective class methods at submodule level.
:Parameters:
package (str)(obj) = A python package.
filetypes (str)(tuple) = Filetype extension(s) to include.
ignoreStartingWith (str)(tuple) = Ignore submodules starting with given chars.
'''
if isinstance(package, str):
package = sys.modules[package]
if not package:
return
pkg_dir = os.path.dirname(os.path.abspath(package.__file__))
sys.path.append(pkg_dir) #append this dir to the system path.
for mod_name in os.listdir(pkg_dir):
if mod_name.startswith(ignoreStartingWith):
continue
elif os.path.isfile(os.path.join(pkg_dir, mod_name)):
mod_name, *mod_ext = mod_name.rsplit('.', 1)
if filetypes:
if not mod_ext or mod_ext[0] not in filetypes:
continue
mod = importlib.import_module(mod_name)
vars(package)[mod_name] = mod
classes = inspect.getmembers(mod, inspect.isclass)
for cls_name, clss in classes:
vars(package)[cls_name] = clss
methods = inspect.getmembers(clss, inspect.isfunction)
for method_name, method in methods:
vars(mod)[method_name] = method
del mod_name
import_submodules(__name__)
</code></pre>
<p>At issue is this line:</p>
<pre><code>vars(mod)[method_name] = method
</code></pre>
<p>Which ultimately results in: (indicating that the attribute was not set)</p>
<pre><code>from myPackage.subModule import someMethod
ImportError: cannot import name 'someMethod' from 'myPackage.subModule'
</code></pre>
<p>I am able to set the methods as attributes to the module within that module, but setting them from outside (ie. in the package __init __), isn't working as written. I understand this isn't ideal to begin with, but my current logic is; that the ease of use, outweighs any perceived issues with namespace pollution. I am, of course, always open to counter-arguments.</p>
|
[
{
"answer_id": 74547298,
"author": "nd37255",
"author_id": 12710567,
"author_profile": "https://Stackoverflow.com/users/12710567",
"pm_score": 3,
"selected": true,
"text": "library(tidyverse)\n\nDATA = data.frame(STUDENT = c(1,1,1,1,1,1,2,2,2,2,2, 3,3,3),\n YEAR = c(2000, 2000, 2000, 2001, 2001, 2001, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001),\n TRIMESTER= c(1,2,3,1,2,3,2,3,1,2,3,1,2,3),\n SCORE = c(5,7,8,9,10,3,4,6,3,1,2,3,6, 9),\n WANT = c(NA,NA,NA,4,3,-5,NA,NA,NA,-3,-4,NA,NA,NA))\n\nDATA <- as_tibble(DATA)\n\nDATA %>% \n group_by(STUDENT, TRIMESTER) %>% \n mutate(LAST = lag(SCORE),\n DIFF = SCORE - LAST)\n#> # A tibble: 14 x 7\n#> # Groups: STUDENT, TRIMESTER [9]\n#> STUDENT YEAR TRIMESTER SCORE WANT LAST DIFF\n#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n#> 1 1 2000 1 5 NA NA NA\n#> 2 1 2000 2 7 NA NA NA\n#> 3 1 2000 3 8 NA NA NA\n#> 4 1 2001 1 9 4 5 4\n#> 5 1 2001 2 10 3 7 3\n#> 6 1 2001 3 3 -5 8 -5\n#> 7 2 2000 2 4 NA NA NA\n#> 8 2 2000 3 6 NA NA NA\n#> 9 2 2001 1 3 NA NA NA\n#> 10 2 2001 2 1 -3 4 -3\n#> 11 2 2001 3 2 -4 6 -4\n#> 12 3 2001 1 3 NA NA NA\n#> 13 3 2001 2 6 NA NA NA\n#> 14 3 2001 3 9 NA NA NA\n"
},
{
"answer_id": 74547511,
"author": "user2974951",
"author_id": 2974951,
"author_profile": "https://Stackoverflow.com/users/2974951",
"pm_score": 1,
"selected": false,
"text": "DATA = data.frame(STUDENT = c(1,1,1,1,1,1,2,2,2,2,2, 3,3,3),\n YEAR = c(2000, 2000, 2000, 2001, 2001, 2001, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001),\n TRIMESTER= c(1,2,3,1,2,3,2,3,1,2,3,1,2,3),\n SCORE = c(5,7,8,9,10,3,4,6,3,1,2,3,6, 9))\n DATA=merge(\n DATA,\n cbind(\n DATA[,c(\"STUDENT\",\"TRIMESTER\")],\n DATA[,\"YEAR\",drop=F]+1,\n \"MATCH\"=DATA[,\"SCORE\"]\n ),\n by=c(\"STUDENT\",\"YEAR\",\"TRIMESTER\"),\n all.x=T\n)\nDATA$WANT=DATA$SCORE-DATA$MATCH\n STUDENT YEAR TRIMESTER SCORE MATCH WANT\n1 1 2000 1 5 NA NA\n2 1 2000 2 7 NA NA\n3 1 2000 3 8 NA NA\n4 1 2001 1 9 5 4\n5 1 2001 2 10 7 3\n6 1 2001 3 3 8 -5\n7 2 2000 2 4 NA NA\n8 2 2000 3 6 NA NA\n9 2 2001 1 3 NA NA\n10 2 2001 2 1 4 -3\n11 2 2001 3 2 6 -4\n12 3 2001 1 3 NA NA\n13 3 2001 2 6 NA NA\n14 3 2001 3 9 NA NA\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6759015/"
] |
74,547,365
|
<p>I am faced with a challenge.</p>
<p>I have an Python method implemented and the SonarLint plugin of my PyCharm warns me with the message: "Refactor this function to reduce its Cognitive Complexity from 19 to the 15 allowed." but I can't see how to reduce the complexity.</p>
<p>My Python method is:</p>
<pre><code>def position(key):
if key == 'a':
return 0
elif key == 'b':
return 1
elif key == 'c':
return 2
elif key == 'd':
return 3
elif key == 'e':
return 4
elif key == 'f':
return 5
elif key == 'g':
return 6
elif key == 'h':
return 7
elif key == 'i':
return 8
elif key == 'j':
return 9
elif key == 'k':
return 10
elif key == 'l':
return 11
elif key == 'm':
return 12
elif key == 'n':
return 13
elif key == 'ñ':
return 14
elif key == 'o':
return 15
elif key == 'p':
return 16
elif key == 'q':
return 17
else:
logger.info('error')
</code></pre>
<p>And the warning of SonarLint is:</p>
<p><a href="https://i.stack.imgur.com/BuSfu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BuSfu.png" alt="enter image description here" /></a></p>
<p>And if I click on show issue locations it gives me the explanation of how the Cognitive Complexity is calculated:
<a href="https://i.stack.imgur.com/YSlDg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YSlDg.png" alt="enter image description here" /></a></p>
<p>I can't see how to reduce the complex of this function. I know that I can implement another method with the same behaviour using things like the ascii code, but it's not the point of this question.</p>
<p>The summary of the question is how can I follow the suggestion of SonarLint, I mean, how can I reduce the Cognitive Complexity from 19 to the 15 of this particular method.</p>
<p>Something I've noticed is that if I remove elif statements until I have only 14 characters cases, the warning magically disappears.</p>
|
[
{
"answer_id": 74547546,
"author": "Manuel González Costa",
"author_id": 15476816,
"author_profile": "https://Stackoverflow.com/users/15476816",
"pm_score": 2,
"selected": true,
"text": " def position(key: str) -> (int, None):\n char_map = {\n 'a': 0,\n 'b': 1,\n 'c': 2,\n 'd': 3,\n 'e': 4,\n 'f': 5,\n 'g': 6,\n 'h': 7,\n 'i': 8,\n 'j': 9,\n 'k': 10,\n 'l': 11,\n 'm': 12,\n 'n': 13,\n 'ñ': 14,\n 'o': 15,\n 'p': 16,\n 'q': 17,\n 'r': 18,\n 's': 19,\n 't': 20,\n 'u': 21,\n 'v': 22,\n 'w': 23,\n 'x': 24,\n 'y': 25,\n 'z': 26\n }\n\n try:\n output = char_map[key]\n except KeyError:\n logger.error('KeyError in position() with the key: ' + str(key))\n return None\n\n return output\n"
},
{
"answer_id": 74548094,
"author": "Bendik Knapstad",
"author_id": 6547224,
"author_profile": "https://Stackoverflow.com/users/6547224",
"pm_score": 2,
"selected": false,
"text": "def position(key):\n values =\"abcdefghijklmnñopq\"\n try:\n return values.index(key)\n except Exception as e:\n print(e) #you can use logger here if you want\n >>> position(\"a\")\n0\n>>> position(\"z\")\nsubstring not found\n"
},
{
"answer_id": 74548197,
"author": "Guimoute",
"author_id": 9282844,
"author_profile": "https://Stackoverflow.com/users/9282844",
"pm_score": 0,
"selected": false,
"text": "\"ñ\" ord \"abcdefghijklmnop\" \ndef position(key:str) -> int:\n value = ord(key) - ord(\"a\")\n if 0 <= value <= ord(\"p\") - ord(\"a\"):\n return value\n else:\n logger.info('error')\n \"a\" \"p\" def position(key:str; min_key=\"a\", max_key=\"p\") -> int:\n value = ord(key) - ord(min_key)\n if 0 <= value <= ord(max_key) - ord(min_key):\n return value\n else:\n logger.info('error')\n"
},
{
"answer_id": 74548327,
"author": "kindall",
"author_id": 416467,
"author_profile": "https://Stackoverflow.com/users/416467",
"pm_score": 1,
"selected": false,
"text": "if a def position(key, offset=ord(\"a\")):\n pos = ord(key) - offset\n if 0 <= pos <= 17:\n return pos\n logger.info(\"error\")\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15476816/"
] |
74,547,370
|
<p>I have an array of objects but I only want to loop through the first 5 objects and break, whats the best way to do that.</p>
<pre><code>[
{"visibility": 10000,},
{"visibility": 10000,},
{"visibility": 30000,},
{"visibility": 40000,},
{"visibility": 10000,}, -----> exit here
{"visibility": 20000,},
{"visibility": 90000,},
{"visibility": 230000,},
{"visibility": 10000,},
{"visibility": 70000,},
]
</code></pre>
|
[
{
"answer_id": 74547546,
"author": "Manuel González Costa",
"author_id": 15476816,
"author_profile": "https://Stackoverflow.com/users/15476816",
"pm_score": 2,
"selected": true,
"text": " def position(key: str) -> (int, None):\n char_map = {\n 'a': 0,\n 'b': 1,\n 'c': 2,\n 'd': 3,\n 'e': 4,\n 'f': 5,\n 'g': 6,\n 'h': 7,\n 'i': 8,\n 'j': 9,\n 'k': 10,\n 'l': 11,\n 'm': 12,\n 'n': 13,\n 'ñ': 14,\n 'o': 15,\n 'p': 16,\n 'q': 17,\n 'r': 18,\n 's': 19,\n 't': 20,\n 'u': 21,\n 'v': 22,\n 'w': 23,\n 'x': 24,\n 'y': 25,\n 'z': 26\n }\n\n try:\n output = char_map[key]\n except KeyError:\n logger.error('KeyError in position() with the key: ' + str(key))\n return None\n\n return output\n"
},
{
"answer_id": 74548094,
"author": "Bendik Knapstad",
"author_id": 6547224,
"author_profile": "https://Stackoverflow.com/users/6547224",
"pm_score": 2,
"selected": false,
"text": "def position(key):\n values =\"abcdefghijklmnñopq\"\n try:\n return values.index(key)\n except Exception as e:\n print(e) #you can use logger here if you want\n >>> position(\"a\")\n0\n>>> position(\"z\")\nsubstring not found\n"
},
{
"answer_id": 74548197,
"author": "Guimoute",
"author_id": 9282844,
"author_profile": "https://Stackoverflow.com/users/9282844",
"pm_score": 0,
"selected": false,
"text": "\"ñ\" ord \"abcdefghijklmnop\" \ndef position(key:str) -> int:\n value = ord(key) - ord(\"a\")\n if 0 <= value <= ord(\"p\") - ord(\"a\"):\n return value\n else:\n logger.info('error')\n \"a\" \"p\" def position(key:str; min_key=\"a\", max_key=\"p\") -> int:\n value = ord(key) - ord(min_key)\n if 0 <= value <= ord(max_key) - ord(min_key):\n return value\n else:\n logger.info('error')\n"
},
{
"answer_id": 74548327,
"author": "kindall",
"author_id": 416467,
"author_profile": "https://Stackoverflow.com/users/416467",
"pm_score": 1,
"selected": false,
"text": "if a def position(key, offset=ord(\"a\")):\n pos = ord(key) - offset\n if 0 <= pos <= 17:\n return pos\n logger.info(\"error\")\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15018590/"
] |
74,547,393
|
<p>I have an array</p>
<pre><code>errorPriority: string[] = ['shippingError', 'paymentInfoError', 'generalError'];
</code></pre>
<p>I need a function call to be looped on every element of array, but somehow after executing function for first element 'shippingError', the loop stops. Below is the function call</p>
<pre><code>this.errorPriority.every(this.getErrorData);
</code></pre>
<p>And the function that is executed</p>
<pre><code>getErrorData = (value: string): void => {
if (eval(this.objectPath[value as keyof ObjectPath]) && eval(this.objectPath[value as keyof ObjectPath]).length)
this.checkoutState.errors[value] = eval(this.objectPath[value as keyof ObjectPath]);
}
</code></pre>
<p>It sometimes, works on array element, but mostly stops after first element, Am I missing something, please help</p>
<p>I expect function should be looped on every array element</p>
|
[
{
"answer_id": 74547492,
"author": "Paul-Marie",
"author_id": 9603417,
"author_profile": "https://Stackoverflow.com/users/9603417",
"pm_score": 0,
"selected": false,
"text": "void getErrorData = (value) => {\n if (eval(this.objectPath[value]) && eval(this.objectPath[value]).length) {\n this.checkoutState.errors[value] = eval(this.objectPath[value]);\n return true;\n }\n }\n"
},
{
"answer_id": 74547526,
"author": "jigfox",
"author_id": 262980,
"author_profile": "https://Stackoverflow.com/users/262980",
"pm_score": 2,
"selected": false,
"text": "every() Array#every() void undefined false every every forEach"
},
{
"answer_id": 74547534,
"author": "laian",
"author_id": 14374655,
"author_profile": "https://Stackoverflow.com/users/14374655",
"pm_score": -1,
"selected": true,
"text": "array.every() array.every getErrorData = (value) => {\n if (eval(this.objectPath[value]) && eval(this.objectPath[value]).length) {\n this.checkoutState.errors[value] = eval(this.objectPath[value]);\n return true;\n }\n return false\n }"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17134599/"
] |
74,547,400
|
<p>I tried to call a function for every attribute (column) that I want to read from 4 .txt files and then write into a .csv file. One column has flawed output and the code should have a few logic flaws as I haven't learned batch cleanly from scratch. Do you know a fix?</p>
<p>Link to previous solved question: <a href="https://stackoverflow.com/questions/74258020/read-information-from-multiple-txt-files-and-sort-it-into-csv-file">Read information from multiple .txt files and sort it into .csv file</a></p>
<p>@Magoo</p>
<p><a href="https://i.stack.imgur.com/Ve3vN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ve3vN.png" alt="The result I got" /></a></p>
<pre><code>echo Name;Prename;Sign;Roomnumber;Phonenumber > sorted.csv
for /f "tokens=1,2 delims= " %%a in (TestEmployees.txt) do (
call :findSign %%a %%b
)
:findSign
set prename=%1
set name=%2
for /f "tokens=1,2 delims= " %%a in (TestSign.txt) do (
if "%name%"=="%%a" (
call :findRoomNumber
)
)
:End
:findRoomNumber
set sign=%1
for /f "tokens=1,2 delims=|" %%q in (TestRoomNumber.txt) do (
if "%sign%"=="%%q" (
call :findPhoneNumber
)
)
:End
:findPhoneNumber
for /f "tokens=1,2 delims=;" %%u in (TestPhoneNumber.txt) do (
if "%%b"=="%%u" (
echo %name%;%prename%;%%b;%%r;%%v >> sorted.csv
)
)
:End
</code></pre>
|
[
{
"answer_id": 74547492,
"author": "Paul-Marie",
"author_id": 9603417,
"author_profile": "https://Stackoverflow.com/users/9603417",
"pm_score": 0,
"selected": false,
"text": "void getErrorData = (value) => {\n if (eval(this.objectPath[value]) && eval(this.objectPath[value]).length) {\n this.checkoutState.errors[value] = eval(this.objectPath[value]);\n return true;\n }\n }\n"
},
{
"answer_id": 74547526,
"author": "jigfox",
"author_id": 262980,
"author_profile": "https://Stackoverflow.com/users/262980",
"pm_score": 2,
"selected": false,
"text": "every() Array#every() void undefined false every every forEach"
},
{
"answer_id": 74547534,
"author": "laian",
"author_id": 14374655,
"author_profile": "https://Stackoverflow.com/users/14374655",
"pm_score": -1,
"selected": true,
"text": "array.every() array.every getErrorData = (value) => {\n if (eval(this.objectPath[value]) && eval(this.objectPath[value]).length) {\n this.checkoutState.errors[value] = eval(this.objectPath[value]);\n return true;\n }\n return false\n }"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374919/"
] |
74,547,414
|
<p>So my json data is coming as string like following:</p>
<pre><code> { "name":"aaa", "sub": "{"x":"sss", "y":"eee"}" }
</code></pre>
<p>Sub field is a raw json string here.</p>
<p>My model is like following.</p>
<pre><code> class Main
{
public string Name { get;set;}
public Sub Sub { get;set;}
}
class Sub
{
public string X { get;set;}
public string Y { get;set;}
}
</code></pre>
<p>I want to deserialize it like following:</p>
<pre><code>var response = Encoding.UTF8.GetString(bytes); // getting data.
var jsonString = JsonConvert.Deseialize(response).ToString(); // to string.
var model = JsonConvert.Deserialize<Main>(jsonString); // error
</code></pre>
<p>The last step throws exception, like "string can not cast to Main" class.</p>
|
[
{
"answer_id": 74547560,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 0,
"selected": false,
"text": "sub Sub Sub class Main\n{\n public string Name { get;set; }\n public string Sub { get;set; }\n}\n var mainObj = JsonConvert.DeserializeObject<Main>(response);\n mainObj.Sub class Sub\n{\n public string X { get;set; }\n public string Y { get;set; }\n}\n var subObj = JsonConvert.DeserializeObject<Sub>(mainObj.Sub);\n"
},
{
"answer_id": 74547656,
"author": "DavidG",
"author_id": 1663001,
"author_profile": "https://Stackoverflow.com/users/1663001",
"pm_score": 3,
"selected": true,
"text": "{ \"name\":\"aaa\", \"sub\": \"{\\\"x\\\":\\\"sss\\\", \\\"y\\\":\\\"eee\\\"}\" }\n public class NestedJsonConverter : JsonConverter\n{\n public override bool CanConvert(Type objectType) => true;\n\n public override object? ReadJson(JsonReader reader, Type objectType, \n object? existingValue, JsonSerializer serializer)\n {\n // Get the raw string\n var s = serializer.Deserialize<string>(reader);\n\n // Deserialise into the correct type\n return JsonConvert.DeserializeObject(s, objectType);\n }\n\n public override void WriteJson(JsonWriter writer, object? value, \n JsonSerializer serializer)\n => throw new NotImplementedException();\n}\n class Main\n{\n public string Name { get; set; }\n \n [JsonConverter(typeof(NestedJsonConverter))]\n public Sub Sub { get; set; }\n}\n var result = JsonConvert.DeserializeObject<Main>(jsonString);\n"
},
{
"answer_id": 74554626,
"author": "Anu Viswan",
"author_id": 7299782,
"author_profile": "https://Stackoverflow.com/users/7299782",
"pm_score": 1,
"selected": false,
"text": "class Main\n{\n public string Name { get;set;}\n\n private string _subString;\n [JsonProperty(\"Sub\")]\n public string SubString {\n get => _subString;\n set\n {\n _subString = value;\n Sub = JsonConvert.DeserializeObject<Sub>(_subString);\n }\n }\n \n [JsonIgnore]\n public Sub Sub { get;set;}\n}\n\nclass Sub\n{\n public string X { get;set;}\n public string Y { get;set;}\n}\n Sub SubString Sub"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/694716/"
] |
74,547,457
|
<p>I want to centre all of the content of my cards but it's all going to the right side</p>
<p>my card code:</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-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap demo</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<h1>Hello, world!</h1>
<div class="container mt-5 p-5">
<div class="row g-4">
<div class="col-12 col-md-6 col-lg-3">
<div class="card align-items-center bg-light">
<img src="img/oranvour.png" alt="dfg juice" class="card-img-top">
<div class="card-body">
<h5 class="card-title">Juice</h5>
<p class="card-text">Price: $199.00</p>
<div class="form-outline">
<label class="form-label" for="typeNumber">amount</label>
<input type="number" id="typeNumber" class="form-control" />
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I am expecting all of the content to be in the centre of the card not to align-right</p>
|
[
{
"answer_id": 74547697,
"author": "MarioG8",
"author_id": 13705979,
"author_profile": "https://Stackoverflow.com/users/13705979",
"pm_score": 2,
"selected": true,
"text": "text-center card <div class=\"card text-center bg-light\" style=\"width: 18rem;\">\n <!doctype html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>Bootstrap demo</title>\n <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65\" crossorigin=\"anonymous\">\n</head>\n\n<body>\n <h1>Hello, world!</h1>\n\n <div class=\"container mt-5 p-5\">\n\n <div class=\"row g-4\">\n\n <div class=\"col-12 col-md-6 col-lg-3\">\n <div class=\"card text-center bg-light\" style=\"width: 18rem;\">\n <img src=\"https://images.unsplash.com/photo-1669111957903-36e4da270ef1?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80\" alt=\"\" class=\"card-img-top\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">Juice</h5>\n <p class=\"card-text\">Price: $199.00</p>\n\n <div class=\"form-outline\">\n <label class=\"form-label\" for=\"typeNumber\">amount</label>\n <input type=\"number\" id=\"typeNumber\" class=\"form-control\" />\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n\n <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4\" crossorigin=\"anonymous\"></script>\n</body>\n\n</html>"
},
{
"answer_id": 74547764,
"author": "Syaifal Illahi",
"author_id": 16611350,
"author_profile": "https://Stackoverflow.com/users/16611350",
"pm_score": 0,
"selected": false,
"text": "<div class=\"container mt-5 p-5\">\n <div class=\"row g-4\">\n <div class=\"col-12 col-md-6 col-lg-3 mx-auto\">\n <div class=\"card align-items-center bg-light\">\n <img src=\"img/oranvour.png\" alt=\"dfg juice\" class=\"card-img-top\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">Juice</h5>\n <p class=\"card-text\">Price: $199.00</p>\n\n <div class=\"form-outline\">\n <label class=\"form-label\" for=\"typeNumber\">amount</label>\n <input type=\"number\" id=\"typeNumber\" class=\"form-control\" />\n </div> \n </div>\n </div>\n </div>\n </div>\n<div/>\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20387575/"
] |
74,547,471
|
<p>I have typed out the following code.</p>
<pre><code>la = [1,[2,[3,[4]]]]
lb = [la[1], la[1][1]]
print(la)
lb[0][1]=9
print(la)
</code></pre>
<p>I was expecting la to remain as in the original first line, but it changed as shown below.</p>
<pre><code>[1, [2, [3, [4]]]]
[1, [2, 9]]
</code></pre>
<p>Does this have to do with shallow and deep copy? I can't seem to wrap my head around what's going on. Apologies for the formatting, I'm trying to fix it.</p>
|
[
{
"answer_id": 74547545,
"author": "Aymen",
"author_id": 5165980,
"author_profile": "https://Stackoverflow.com/users/5165980",
"pm_score": 0,
"selected": false,
"text": "copy() lb = [la[1].copy(), la[1][1].copy()]\n"
},
{
"answer_id": 74547655,
"author": "Fra93",
"author_id": 4952549,
"author_profile": "https://Stackoverflow.com/users/4952549",
"pm_score": 3,
"selected": true,
"text": "ptr(X) X la = [1,[2,[3,[4]]]]\n\n# la = [ 1 , ptr(X) ]\n# X = [ 2 , ptr(Y) ]\n# Y = [ 3 , ptr(Z) ]\n# Z = [ 4 ]\nprint(la)\n\n\nlb = [la[1], la[1][1]]\n\n# lb = [ ptr(X) , ptr(Y) ]\n\nlb[0][1]=9\n\n# lb[0] is ptr(X)\n# lb[0][1] is X[1] is ptr(Y)\n# lb[0][1] = 9 --> X = [2,9]\n\n# now if we look at how la is defined\n# la = [ 1 , ptr(X) ]\n# X = [ 2 , ptr(Y) ]\n\n# meaning that now X is [2,9] and ptr(X) points to [2,9], \n# so la is\n\n# la = [ 1 , ptr(X) ]\n# X = [ 2 , 9 ]\n\n# so if we print la we get\n# [1,[2,9]]\n\n# et voila\nprint(la)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19728078/"
] |
74,547,478
|
<p>I am dealing with the dataframe where some of the rows have no value inside just like a below dataframe (look at the third row). The picture below shows only one row which does not have any value but total I have lot of rows in which one or two of their column does not have any value. I want to delete such kind of rows which has no value in atleast one column.</p>
<pre><code>df
Thick Max Mean
19 0.7889 8172.58 2197.091
20 1.0603 9366.3 2781.3216
21 '- '- '-
22 1.0577 9347.46 2774.4086
23 0.8125 8243.45 2241.2326
24 0.924 8461.7 2484.9097
</code></pre>
<p>How can I delete these columns?</p>
|
[
{
"answer_id": 74547545,
"author": "Aymen",
"author_id": 5165980,
"author_profile": "https://Stackoverflow.com/users/5165980",
"pm_score": 0,
"selected": false,
"text": "copy() lb = [la[1].copy(), la[1][1].copy()]\n"
},
{
"answer_id": 74547655,
"author": "Fra93",
"author_id": 4952549,
"author_profile": "https://Stackoverflow.com/users/4952549",
"pm_score": 3,
"selected": true,
"text": "ptr(X) X la = [1,[2,[3,[4]]]]\n\n# la = [ 1 , ptr(X) ]\n# X = [ 2 , ptr(Y) ]\n# Y = [ 3 , ptr(Z) ]\n# Z = [ 4 ]\nprint(la)\n\n\nlb = [la[1], la[1][1]]\n\n# lb = [ ptr(X) , ptr(Y) ]\n\nlb[0][1]=9\n\n# lb[0] is ptr(X)\n# lb[0][1] is X[1] is ptr(Y)\n# lb[0][1] = 9 --> X = [2,9]\n\n# now if we look at how la is defined\n# la = [ 1 , ptr(X) ]\n# X = [ 2 , ptr(Y) ]\n\n# meaning that now X is [2,9] and ptr(X) points to [2,9], \n# so la is\n\n# la = [ 1 , ptr(X) ]\n# X = [ 2 , 9 ]\n\n# so if we print la we get\n# [1,[2,9]]\n\n# et voila\nprint(la)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17289097/"
] |
74,547,489
|
<p>I want to pass a class to a function and infer the keys of the class but it doesn't work:</p>
<pre><code>class Foo {
bar: string;
}
function foo<C>(comp: C, key: keyof C) {
}
foo(Foo, '') // expecting to get bar here, but I'm getting the prototype key
</code></pre>
<p>When I use it as a type, it works:</p>
<pre><code>type Keys = keyof Foo;
</code></pre>
<p>What's the issue?</p>
|
[
{
"answer_id": 74547557,
"author": "captain-yossarian from Ukraine",
"author_id": 8495254,
"author_profile": "https://Stackoverflow.com/users/8495254",
"pm_score": 3,
"selected": true,
"text": "bar bar bar Foo bar InstanceType class Foo {\n bar: string = ''\n}\ntype AnyClass = new (...args: any[]) => any\n\nfunction foo<C extends AnyClass>(comp: C, key: keyof InstanceType<C>) {\n\n}\n\nfoo(Foo, 'bar') // ok\n"
},
{
"answer_id": 74547578,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 0,
"selected": false,
"text": "var Foo = class Foo { ... }\nfoo(/* new () => Foo */ Foo, /* 'prototype' */ ...)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7330592/"
] |
74,547,506
|
<p>I need to set a Field with a decimal? value, if doesn't have value it should show the "-".</p>
<p>I tried use this code:</p>
<p><code>Field="@(nameof(this.DataDTO.EventDefaultValue > 0 ? this.DataDTO.EventDefaultValue.ToString("F2") : "-"))"/></code></p>
<p>But doesn't is possible convert, the Visual Studio show the error</p>
<p><a href="https://i.stack.imgur.com/S8K3c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S8K3c.png" alt="enter image description here" /></a></p>
<p>I'm using the Blazor, together with DevExpress DxDataGridColumn component.</p>
<p>How can I to resolve this point? Someone can help me?</p>
|
[
{
"answer_id": 74547557,
"author": "captain-yossarian from Ukraine",
"author_id": 8495254,
"author_profile": "https://Stackoverflow.com/users/8495254",
"pm_score": 3,
"selected": true,
"text": "bar bar bar Foo bar InstanceType class Foo {\n bar: string = ''\n}\ntype AnyClass = new (...args: any[]) => any\n\nfunction foo<C extends AnyClass>(comp: C, key: keyof InstanceType<C>) {\n\n}\n\nfoo(Foo, 'bar') // ok\n"
},
{
"answer_id": 74547578,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 0,
"selected": false,
"text": "var Foo = class Foo { ... }\nfoo(/* new () => Foo */ Foo, /* 'prototype' */ ...)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18727756/"
] |
74,547,507
|
<p>I started using .NET MAUI recently and I found a problem with Styling.
I started with the basic project to make sure the problem is not something I made during the process.
The project starts with a button that will change text and size each time the user press it.
<a href="https://i.stack.imgur.com/xYVle.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xYVle.png" alt="enter image description here" /></a></p>
<p>The problem is any time I use LinearGradientBrush directly or through the global styling, the button size doesn't change to fit the text, and even worse it moves to the left.
<a href="https://i.stack.imgur.com/S2NYb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S2NYb.png" alt="enter image description here" /></a></p>
<p>I looked everywhere but I didn't find any similar problem or solution.</p>
<p>It works well with Windows but not with Android</p>
<p>Code</p>
<pre><code><Button
x:Name="CounterBtn"
Text="Click me"
SemanticProperties.Hint="Counts the number of times you click"
Clicked="OnCounterClicked"
HorizontalOptions="Center">
<Button.Background>
<LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#8A26ED"/>
<GradientStop Color="#381061" Offset="1"/>
</LinearGradientBrush>
</Button.Background>
</Button>
</code></pre>
|
[
{
"answer_id": 74556271,
"author": "Liqun Shen-MSFT",
"author_id": 20118901,
"author_profile": "https://Stackoverflow.com/users/20118901",
"pm_score": 1,
"selected": false,
"text": "private void OnCounterClicked(object sender, EventArgs e)\n{\n LinearGradientBrush ll = new LinearGradientBrush();\n ll.EndPoint = new Point(0, 1);\n GradientStop a = new GradientStop(Color.FromHex(\"#8A26ED\"), 0);\n GradientStop b = new GradientStop(Color.FromHex(\"#381061\"), 1);\n ll.GradientStops = new GradientStopCollection()\n {\n a,b\n };\n CounterBtn.Background = ll; \n ...\n}\n"
},
{
"answer_id": 74557990,
"author": "Abanoub Zak",
"author_id": 18204376,
"author_profile": "https://Stackoverflow.com/users/18204376",
"pm_score": 1,
"selected": true,
"text": " private void CounterBtn_SizeChanged(object sender, EventArgs e)\n {\n LinearGradientBrush ll = new LinearGradientBrush();\n ll.EndPoint = new Point(0, 1);\n GradientStop a = new GradientStop(Color.FromHex(\"#8A26ED\"), 0);\n GradientStop b = new GradientStop(Color.FromHex(\"#381061\"), 1);\n ll.GradientStops = new GradientStopCollection()\n {\n a,b\n };\n CounterBtn.Background = ll;\n }\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18204376/"
] |
74,547,518
|
<p>I'm using the tidyr <code>complete()</code> and <code>fill()</code> functions to extend (copy down) a dataframe so all ID elements have the same number of rows. The code posted at the bottom correctly extends all fields, with the exception of the "Bal2" column of the dataframe where a series of NA's should be extended. Any recommendations for how to correct this?</p>
<p>The NA values do serve a calculation purpose in the fuller code this is deployed in. Also please note that I have another code snippet for correctly extending the "Period_2" column so I don't need help with "Period_2". It's been omitted for code brevity.</p>
<p>The below illustrates the issue when generating the <code>testDF</code> and <code>testDF1</code> dataframes:</p>
<p><a href="https://i.stack.imgur.com/mduxL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mduxL.png" alt="enter image description here" /></a></p>
<p>Code:</p>
<pre><code>library(dplyr)
library(tidyr)
testDF <-
data.frame(
ID = c(rep(1,5),rep(50,3),rep(60,3)),
Period_1 = c(1:5,1:3,1:3),
Period_2 = c("2012-06","2012-07","2012-08","2012-09","2012-10","2013-06","2013-07","2013-08","2012-10","2012-11","2012-12"),
Bal1 = c(rep(10,5),21:23,36:34),
Bal2 = c(rep(12,8),rep(NA,3))
)
testDF1 <- testDF %>%
tidyr::complete(ID, nesting(Period_1)) %>%
tidyr::fill(Bal1, Bal2, .direction = "down")
testDF1 <- as.data.frame(testDF1)
</code></pre>
|
[
{
"answer_id": 74547622,
"author": "Captain Hat",
"author_id": 4676560,
"author_profile": "https://Stackoverflow.com/users/4676560",
"pm_score": 0,
"selected": false,
"text": "dplry::group_by() fill() require(dplyr)\n#> Loading required package: dplyr\nrequire(tidyr)\n#> Loading required package: tidyr\n\ntest <- tribble(\n ~id, ~value,\n \"A\", 80,\n \"A\", NA,\n \"A\", NA,\n \"B\", NA,\n \"B\", NA\n)\n\nfill(test, value)\n#> # A tibble: 5 × 2\n#> id value\n#> <chr> <dbl>\n#> 1 A 80\n#> 2 A 80\n#> 3 A 80\n#> 4 B 80\n#> 5 B 80\n\ntest <- group_by(test, id)\nfill(test, value)\n#> # A tibble: 5 × 2\n#> # Groups: id [2]\n#> id value\n#> <chr> <dbl>\n#> 1 A 80\n#> 2 A 80\n#> 3 A 80\n#> 4 B NA\n#> 5 B NA\n"
},
{
"answer_id": 74548256,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 2,
"selected": true,
"text": "ID library(dplyr)\n# library(tidyr)\ntestDF %>%\n tidyr::complete(ID, tidyr::nesting(Period_1)) %>%\n group_by(ID) %>%\n tidyr::fill(Bal1, Bal2, .direction = \"down\") %>%\n ungroup()\n# # A tibble: 15 x 5\n# ID Period_1 Period_2 Bal1 Bal2\n# <dbl> <int> <chr> <dbl> <dbl>\n# 1 1 1 2012-06 10 12\n# 2 1 2 2012-07 10 12\n# 3 1 3 2012-08 10 12\n# 4 1 4 2012-09 10 12\n# 5 1 5 2012-10 10 12\n# 6 50 1 2013-06 21 12\n# 7 50 2 2013-07 22 12\n# 8 50 3 2013-08 23 12\n# 9 50 4 NA 23 12\n# 10 50 5 NA 23 12\n# 11 60 1 2012-10 36 NA\n# 12 60 2 2012-11 35 NA\n# 13 60 3 2012-12 34 NA\n# 14 60 4 NA 34 NA\n# 15 60 5 NA 34 NA\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19657749/"
] |
74,547,566
|
<p><strong>Repreduce:</strong></p>
<p>In file <code>config/app.php</code> I changed following code</p>
<pre class="lang-php prettyprint-override"><code>'debug' => true,
</code></pre>
<p>After run <code>php artisan config:cache</code> command, I executed <code>dd(Config::get('app.debug'))</code></p>
<p><strong>Expected:</strong></p>
<p>Get <code>true</code></p>
<p><strong>Actual:</strong></p>
<p>Get <code>false</code></p>
<hr />
<p>You should to know when I changed other config, I got that except <code>debug</code></p>
|
[
{
"answer_id": 74548028,
"author": "Haris",
"author_id": 15335938,
"author_profile": "https://Stackoverflow.com/users/15335938",
"pm_score": 1,
"selected": false,
"text": "use Illuminate\\Support\\Facades\\Config;\n dd(config('app.debug'));\n"
},
{
"answer_id": 74550913,
"author": "MohaMed HaMdy",
"author_id": 11636002,
"author_profile": "https://Stackoverflow.com/users/11636002",
"pm_score": 0,
"selected": false,
"text": "debug"
},
{
"answer_id": 74557507,
"author": "Atefeh 1999",
"author_id": 19577810,
"author_profile": "https://Stackoverflow.com/users/19577810",
"pm_score": 3,
"selected": true,
"text": "APP_ENV development testing .env php artisan config:cache APP_ENV=development\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6569224/"
] |
74,547,573
|
<p>Is there a way in using firestore that will print a message using flutter if an array contains a string.</p>
<p>I want to check if the array inside a specific document has the user email inside it. If the array contains the user email, it will show a message.</p>
<p>here's my current code but it is not working.</p>
<pre><code>(FirebaseFirestore.instance.collection('users').where(
'requests',
arrayContains: user.email) == true)
? Text("true")
: Text("false");
</code></pre>
|
[
{
"answer_id": 74548028,
"author": "Haris",
"author_id": 15335938,
"author_profile": "https://Stackoverflow.com/users/15335938",
"pm_score": 1,
"selected": false,
"text": "use Illuminate\\Support\\Facades\\Config;\n dd(config('app.debug'));\n"
},
{
"answer_id": 74550913,
"author": "MohaMed HaMdy",
"author_id": 11636002,
"author_profile": "https://Stackoverflow.com/users/11636002",
"pm_score": 0,
"selected": false,
"text": "debug"
},
{
"answer_id": 74557507,
"author": "Atefeh 1999",
"author_id": 19577810,
"author_profile": "https://Stackoverflow.com/users/19577810",
"pm_score": 3,
"selected": true,
"text": "APP_ENV development testing .env php artisan config:cache APP_ENV=development\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20132700/"
] |
74,547,575
|
<p>I'm having trouble trying to find a substring within a string. This isn't a simple substring match using <code>indexOf</code> or <code>match()</code> or <code>test()</code> or <code>includes()</code>. I've tried using these but to no avail. I have a bunch of strings inside an array, and then either need to use <code>filter()</code> method or the <code>some()</code> method to find a substring match.</p>
<p>I need to match a string in the array with the command;</p>
<p>I tried the following but it doesn't work:</p>
<pre><code>let matchedObject;
const command = "show vacuum bed_temperature_1";
const array = [ "show vacuum", "show system", "set system", "set vacuum" ];
if (array.some((a) => command.includes(a))) {
// This matches an element in the array partially correctly, only that it also matches with one of the unacceptable strings below.
}
</code></pre>
<p><strong>Acceptable strings</strong></p>
<p>The element "show vacuum" is an exact match with the command.</p>
<pre><code>const example1 = "show vacuum";
const example2 = "show vacuum bed_temperature_1";
const example3 = "show vacuum bed_temp_2";
const example4 = "show vacuum bed_temp3";
</code></pre>
<p><strong>Unacceptable strings</strong></p>
<pre><code>const example 1 = "show vacuums bed_temperature_1";
const example 2 = "shows vacuum bed_temperature_1";
const example 3 = "show vauum bed_temp3";
</code></pre>
|
[
{
"answer_id": 74547652,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": false,
"text": "\\b const array = [ \"show vacuum\", \"show system\", \"set system\", \"set vacuum\" ];\n\nconst re = RegExp('\\\\b(' + array.join('|') + ')\\\\b')\n\ntest = `\nshow vacuum bed_temperature_1\nshow vacuum bed_temp_2\nshow vacuum bed_temp3\nshow vacuums bed_temperature_1\nshows vacuum bed_temperature_1\nshow vauum bed_temp3\n`\n\nconsole.log(test.trim().split('\\n').map(s => s + ' = ' + re.test(s))) array"
},
{
"answer_id": 74547799,
"author": "Nuh Ylmz",
"author_id": 6677999,
"author_profile": "https://Stackoverflow.com/users/6677999",
"pm_score": -1,
"selected": true,
"text": "const array = [\"show vacuum\", \"show system\", \"set system\", \"set vacuum\"];\nconst outputString = \"show vacuum bed_temperature_1\";\n\narray.forEach((key) => {\n const regex = new RegExp(`${key}`);\n if (regex.test(outputString)) {\n console.log(key, \"matched\");\n } else {\n console.log(key, \"not matched\");\n }\n})\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581974/"
] |
74,547,579
|
<p>I want to implement Kahn's algorithm for a directed acyclic graph.</p>
<p>I understand why in rust it's not possible to borrow mutable variables more than once and that I cannot borrow mutable var if it was already borrowed immutable, but I don't want to use a ref counting pointer because it allocates memory on a heap.</p>
<pre class="lang-rust prettyprint-override"><code>struct Node {
ref_count: u32,
id: usize,
text: String
}
impl Node {
fn new(text: String) -> Self {
Node {
ref_count: 0,
id: 0,
text: text
}
}
fn get_ref_count(&self) -> u32 {
self.ref_count
}
fn get_id(&self) -> usize {
self.id
}
fn execute(&self) {
println!("{}", self.text);
}
}
struct Edge {
from: usize,
to: usize
}
impl Edge {
fn new(from: &Node, to: &Node) -> Self {
Edge {
from: from.get_id(),
to: to.get_id()
}
}
}
struct Dag {
nodes: Vec<Node>,
edges: Vec<Edge>
}
impl Dag {
fn new() -> Self {
Dag {
nodes: vec![],
edges: vec![]
}
}
fn add_node(&mut self, node: Node) {
let id = self.nodes.len();
self.nodes.push(node);
self.nodes[id].id = id;
}
fn add_edge(&mut self, edge: Edge) {
self.edges.push(edge);
}
fn sort_and_execute(&mut self) {
for edge in &self.edges {
let node = &mut self.nodes[edge.to];
node.ref_count+=1;
}
let mut stack: Vec<&Node> = vec![];
for node in &self.nodes {
if node.get_ref_count() == 0 {
stack.push(node);
}
}
while !stack.is_empty() {
let node = stack.pop();
if let Some(node) = node {
node.execute();
let edges: Vec<&Edge> = self.edges
.iter()
.filter(|edge| edge.from == node.get_id() )
.collect();
for edge in edges {
//linked node must be mutable, because the ref count has to be decremented
let linkedNode = &mut self.nodes[edge.to];
linkedNode.ref_count -= 1;
if linkedNode.get_ref_count() == 0 {
stack.push(linkedNode);
}
}
}
}
}
}
fn main() {
let a = Node::new("0".to_owned());
let b = Node::new("1".to_owned());
let c = Node::new("2".to_owned());
let d = Node::new("3".to_owned());
let a_c = Edge::new(&a, &c);
let b_c = Edge::new(&b, &c);
let c_d = Edge::new(&c, &d);
let mut dag = Dag::new();
dag.add_node(a);
dag.add_node(b);
dag.add_node(c);
dag.add_node(d);
dag.add_edge(a_c);
dag.add_edge(b_c);
dag.add_edge(c_d);
dag.sort_and_execute();
}
</code></pre>
<p>The problem is that in line <code>73</code> the for loop borrows <code>self.nodes</code> to find nodes with <code>ref_count = 0</code> and in line <code>89</code> <code>self.nodes</code> also has to be borrowed (mutably) to decrement the ref count</p>
<p>is there any way I can do it?</p>
|
[
{
"answer_id": 74547652,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": false,
"text": "\\b const array = [ \"show vacuum\", \"show system\", \"set system\", \"set vacuum\" ];\n\nconst re = RegExp('\\\\b(' + array.join('|') + ')\\\\b')\n\ntest = `\nshow vacuum bed_temperature_1\nshow vacuum bed_temp_2\nshow vacuum bed_temp3\nshow vacuums bed_temperature_1\nshows vacuum bed_temperature_1\nshow vauum bed_temp3\n`\n\nconsole.log(test.trim().split('\\n').map(s => s + ' = ' + re.test(s))) array"
},
{
"answer_id": 74547799,
"author": "Nuh Ylmz",
"author_id": 6677999,
"author_profile": "https://Stackoverflow.com/users/6677999",
"pm_score": -1,
"selected": true,
"text": "const array = [\"show vacuum\", \"show system\", \"set system\", \"set vacuum\"];\nconst outputString = \"show vacuum bed_temperature_1\";\n\narray.forEach((key) => {\n const regex = new RegExp(`${key}`);\n if (regex.test(outputString)) {\n console.log(key, \"matched\");\n } else {\n console.log(key, \"not matched\");\n }\n})\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20266935/"
] |
74,547,591
|
<p>How to correctly encode an <strong>extended</strong> Le field of an APDU</p>
<pre><code>+------+------+------+------+------+-------------+------+
| CLA | INS | P1 | P2 | Lc | DATA | Le |
+------+------+------+------+------+-------------+------+
</code></pre>
<p>Specifically regarding following sentence from the <strong>ISO_IEC_7816-4-2020</strong> Standard page 9 section 5.2 Syntax:</p>
<blockquote>
<p>An extended Le field consists of either three bytes (one byte set to '00'
followed by two bytes with any value) if the Lc field is absent, or
two bytes (with any value) if an extended Lc field is present.</p>
</blockquote>
<p><strong>Question1:</strong>
If I want to encode a 2 byte Le field, does this mean, that the Lc field also has to be <em>extended</em>? Means, 2 byte Lc?</p>
<p><strong>Question2:</strong>
If I want to encode a 3 byte Le field, does tths mean, that the Lc field must be absent? Or only, when the Lc field is absent, I have to encode a 3 byte Le field?</p>
<p><a href="https://i.stack.imgur.com/l7rHN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l7rHN.png" alt="enter image description here" /></a>
[Table 1 of ISO_IEC_7816-4-2020 Standard page9]</p>
|
[
{
"answer_id": 74547652,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": false,
"text": "\\b const array = [ \"show vacuum\", \"show system\", \"set system\", \"set vacuum\" ];\n\nconst re = RegExp('\\\\b(' + array.join('|') + ')\\\\b')\n\ntest = `\nshow vacuum bed_temperature_1\nshow vacuum bed_temp_2\nshow vacuum bed_temp3\nshow vacuums bed_temperature_1\nshows vacuum bed_temperature_1\nshow vauum bed_temp3\n`\n\nconsole.log(test.trim().split('\\n').map(s => s + ' = ' + re.test(s))) array"
},
{
"answer_id": 74547799,
"author": "Nuh Ylmz",
"author_id": 6677999,
"author_profile": "https://Stackoverflow.com/users/6677999",
"pm_score": -1,
"selected": true,
"text": "const array = [\"show vacuum\", \"show system\", \"set system\", \"set vacuum\"];\nconst outputString = \"show vacuum bed_temperature_1\";\n\narray.forEach((key) => {\n const regex = new RegExp(`${key}`);\n if (regex.test(outputString)) {\n console.log(key, \"matched\");\n } else {\n console.log(key, \"not matched\");\n }\n})\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1650038/"
] |
74,547,612
|
<p>The sub-directories have different depth and have videos scattered. I am using find command to locate videos of multiple extensions like mp4, mkv, m4v, webm, ts, mov, etc. and then trying to process them with ffmpeg.</p>
<p>So far, I have come up with this command:</p>
<pre><code>find . -type f \( -name "*.mp4" -o -name "*.mkv" -o -name "*.m4v" -o -name "*.webm" -o -name "*.ts" -o -name "*.mov" \) -execdir ffmpeg -i {} -vcodec libx264 -crf 32 -vf scale=1280:720 -r 16 -map_metadata -1 {}.mp4 \;
</code></pre>
<p>If I try adding a prefix to ffmpeg output as <code>... out{}.mp4 \;</code>, it is not possible. It says:</p>
<blockquote>
<p>out./<FILE_NAME>.mp4: No such file or directory</p>
</blockquote>
<p>I want the final output to have <code>"out${original_name}".mp4</code> as the name. Is there anyway to add prefix to output?</p>
|
[
{
"answer_id": 74547652,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": false,
"text": "\\b const array = [ \"show vacuum\", \"show system\", \"set system\", \"set vacuum\" ];\n\nconst re = RegExp('\\\\b(' + array.join('|') + ')\\\\b')\n\ntest = `\nshow vacuum bed_temperature_1\nshow vacuum bed_temp_2\nshow vacuum bed_temp3\nshow vacuums bed_temperature_1\nshows vacuum bed_temperature_1\nshow vauum bed_temp3\n`\n\nconsole.log(test.trim().split('\\n').map(s => s + ' = ' + re.test(s))) array"
},
{
"answer_id": 74547799,
"author": "Nuh Ylmz",
"author_id": 6677999,
"author_profile": "https://Stackoverflow.com/users/6677999",
"pm_score": -1,
"selected": true,
"text": "const array = [\"show vacuum\", \"show system\", \"set system\", \"set vacuum\"];\nconst outputString = \"show vacuum bed_temperature_1\";\n\narray.forEach((key) => {\n const regex = new RegExp(`${key}`);\n if (regex.test(outputString)) {\n console.log(key, \"matched\");\n } else {\n console.log(key, \"not matched\");\n }\n})\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20582261/"
] |
74,547,620
|
<p>I have just created a screen that has three build methods and each method showing data based on provider data...here I have to declare provider object in each method,
is there any other way..</p>
<p>and can't declare at state level as showing error of context..</p>
<p>createing in main build method and passing to all child method..is it good way of code?</p>
<p>here is my code</p>
<pre><code>
class _TempFileState extends State<TempFile> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
Expanded(child: headerSection()),
Expanded(child: categorySection()),
Expanded(child: showTransaction()),
],),
);
}
headerSection() {
final provider = Provider.of<TransactionProvider>(context);
return Row(children: [
Text('Total Expense:' + provider.get_total_expense.toString())
],);
}
categorySection() {
final provider = Provider.of<TransactionProvider>(context);
return Row(children: [
Text('Available Categories' + provider.number_of_entries.toString())
],);
}
showTransaction() {
final provider = Provider.of<TransactionProvider>(context);
var transaction = provider.showtransactions;
if(transaction.length>0)
{
return ListView.builder(
itemCount: transaction.length,
itemBuilder: (context, index) {
return Text(transaction[index].amount.toString());
});
}
else
{
return Text('No Data Found');
}
}
}
</code></pre>
|
[
{
"answer_id": 74547891,
"author": "Mohamed Mohsin",
"author_id": 12999567,
"author_profile": "https://Stackoverflow.com/users/12999567",
"pm_score": 1,
"selected": false,
"text": "context provider initState class _TempFileState extends State<TempFile> {\n late final TransactionProvider provider;\n @override\n void initState() {\n super.initState();\n provider = Provider.of<TransactionProvider>(context);\n }\n ...\n}\n"
},
{
"answer_id": 74548814,
"author": "Ivo",
"author_id": 1514861,
"author_profile": "https://Stackoverflow.com/users/1514861",
"pm_score": 0,
"selected": false,
"text": "late class _TempFileState extends State<TempFile> {\n\n late final provider = Provider.of<TransactionProvider>(context);\n\n ...\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18817235/"
] |
74,547,662
|
<p>I have a List of links that I have collected from google search results and I'm downloading these (PDF) files using selenium.</p>
<p>I want to rename each file so that its filename contains the URL.</p>
<p>What can I do?</p>
<p>I have not tried any code so please help me. I'm showing the code of selenium that I used to download the files.</p>
<pre><code>folderName=input(("Enter The FolderName:\t")).upper() #Geting Input for the name of folder
newDir="C:\\Users\\sulta\\Data Science CV\\" + folderName
print(newDir)
if not os.path.exists(newDir):
os.makedirs(newDir) #creating folder
options = webdriver.ChromeOptions()
options.add_experimental_option('prefs', {
"download.default_directory":"C:\\Users\\sulta\\Data Science CV\\" + folderName, #Downloading the files to thi path
"download.prompt_for_download": False, #To auto download the file
"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True #It will not show PDF directly in chrome
})
driver = webdriver.Chrome(options=options)
for z in range(len(link)): #My All links are stored in the list named link
try:
driver.get(link[z])
driver.set_page_load_timeout(10)
except:
continue
</code></pre>
|
[
{
"answer_id": 74547891,
"author": "Mohamed Mohsin",
"author_id": 12999567,
"author_profile": "https://Stackoverflow.com/users/12999567",
"pm_score": 1,
"selected": false,
"text": "context provider initState class _TempFileState extends State<TempFile> {\n late final TransactionProvider provider;\n @override\n void initState() {\n super.initState();\n provider = Provider.of<TransactionProvider>(context);\n }\n ...\n}\n"
},
{
"answer_id": 74548814,
"author": "Ivo",
"author_id": 1514861,
"author_profile": "https://Stackoverflow.com/users/1514861",
"pm_score": 0,
"selected": false,
"text": "late class _TempFileState extends State<TempFile> {\n\n late final provider = Provider.of<TransactionProvider>(context);\n\n ...\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14094853/"
] |
74,547,673
|
<pre><code>import React, { useState, useEffect } from 'react';
import './style.css';
export default function App() {
const [state, setState] = useState([]);
const [inputData, setInputData] = useState();
const [fetchdata, setFetchData] = useState([])
const addHandler = () => {
setState((data) => {
return [...data, inputData];
});
localStorage.setItem('state', JSON.stringify(state));
setInputData('');
};
setFetchData(localStorage.getItem('state'))
return (
<div>
<input
onChange={(e) => setInputData(e.target.value)}
value={inputData || ''}
placeholder="add items"
/>
<button onClick={addHandler}>Add</button>
{fetchdata?.map((item) => {
return (
<div style={{ color: `#+${color}` }}>
<li key={item}>{item}</li>
</div>
);
}) || []}
</div>
);
}
</code></pre>
<p><strong>This is the code I have tried also need dynamic colors for lists. Any help is appreciated with big thanks</strong></p>
<p>even the key I have given unique but it says unique key required</p>
|
[
{
"answer_id": 74547891,
"author": "Mohamed Mohsin",
"author_id": 12999567,
"author_profile": "https://Stackoverflow.com/users/12999567",
"pm_score": 1,
"selected": false,
"text": "context provider initState class _TempFileState extends State<TempFile> {\n late final TransactionProvider provider;\n @override\n void initState() {\n super.initState();\n provider = Provider.of<TransactionProvider>(context);\n }\n ...\n}\n"
},
{
"answer_id": 74548814,
"author": "Ivo",
"author_id": 1514861,
"author_profile": "https://Stackoverflow.com/users/1514861",
"pm_score": 0,
"selected": false,
"text": "late class _TempFileState extends State<TempFile> {\n\n late final provider = Provider.of<TransactionProvider>(context);\n\n ...\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20347723/"
] |
74,547,681
|
<p>I want to take user input for a 2D array using pointer name</p>
<p>Let's say I have a 2D array named arr1[3][3] and the pointer variable name is ptr1. Is it possible use scanf with the pointer variable name?
Check the code below. I am using ptr1+row+column in a nested loop</p>
<pre><code>`#include <stdio.h>
int main(void)
{
int arr1[3][3];
int *ptr1 = &arr1[3][3];
for (int row = 0; row < 3; row++)
{
for (int column = 0; column < 3; column++)
{
scanf("%d", (ptr1 + row) + column);
}
}
}`
</code></pre>
<p>I know I could have taken input using scanf("%d", (*(arr1 + i) + j));
Thank you!</p>
|
[
{
"answer_id": 74547891,
"author": "Mohamed Mohsin",
"author_id": 12999567,
"author_profile": "https://Stackoverflow.com/users/12999567",
"pm_score": 1,
"selected": false,
"text": "context provider initState class _TempFileState extends State<TempFile> {\n late final TransactionProvider provider;\n @override\n void initState() {\n super.initState();\n provider = Provider.of<TransactionProvider>(context);\n }\n ...\n}\n"
},
{
"answer_id": 74548814,
"author": "Ivo",
"author_id": 1514861,
"author_profile": "https://Stackoverflow.com/users/1514861",
"pm_score": 0,
"selected": false,
"text": "late class _TempFileState extends State<TempFile> {\n\n late final provider = Provider.of<TransactionProvider>(context);\n\n ...\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16721382/"
] |
74,547,684
|
<p>Let's say <code>test_t</code> is defined as follows:</p>
<pre><code>typedef struct test_t {
void *unused;
} *(test_t)
</code></pre>
<p>Is it possible define a variable to be a pointer to const without modifying the definition of <code>test_t</code>?</p>
<p><code>const test_t var</code> would be a const pointer to <code>struct test_t</code>, right?</p>
<p>I have this problem since sonarqube recommends to "Make the type of this variable a pointer-to-const" but I can't change the definition since it is used in many other places where the variable should be a pointer to <code>struct test_t</code>.</p>
|
[
{
"answer_id": 74547758,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 3,
"selected": false,
"text": "typedef struct test_t { \n void *unused; \n} test_t;\n\nconst test_t *var;\n"
},
{
"answer_id": 74547884,
"author": "Antti Haapala -- Слава Україні",
"author_id": 918959,
"author_profile": "https://Stackoverflow.com/users/918959",
"pm_score": 0,
"selected": false,
"text": "typedef typedef const struct { \n void *unused; \n} *const_test_t;\n test_t struct test_t {...} test_t const test_t var:\n const struct test_t *ptr;\n typedef const struct { } *test_t;"
},
{
"answer_id": 74547932,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "typedef struct test_t { \n void *unused; \n} *(test_t);\n test_t struct test_t * const test_t var;\n test_t const var;\n struct test_t * const var;\n var struct test_t var const struct test_t *var;\n const struct test_t * const var;\n typedef struct test_t { \n void *unused; \n} test_t;\n const test_t *var;\n test_t struct test_t const const struct test_t"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3744927/"
] |
74,547,696
|
<p>I have about 50 tables in DynamoDB and I'm looking for a way to find size of all tables.</p>
<pre><code>aws dynamodb describe-table --table-name [table name]
</code></pre>
<p>I know above command returns TableSizeBytes, but is this the only way to get size of table?
Do I have to run this command for all tables in picture?
Also, what is the cost of running this command?</p>
|
[
{
"answer_id": 74547758,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 3,
"selected": false,
"text": "typedef struct test_t { \n void *unused; \n} test_t;\n\nconst test_t *var;\n"
},
{
"answer_id": 74547884,
"author": "Antti Haapala -- Слава Україні",
"author_id": 918959,
"author_profile": "https://Stackoverflow.com/users/918959",
"pm_score": 0,
"selected": false,
"text": "typedef typedef const struct { \n void *unused; \n} *const_test_t;\n test_t struct test_t {...} test_t const test_t var:\n const struct test_t *ptr;\n typedef const struct { } *test_t;"
},
{
"answer_id": 74547932,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "typedef struct test_t { \n void *unused; \n} *(test_t);\n test_t struct test_t * const test_t var;\n test_t const var;\n struct test_t * const var;\n var struct test_t var const struct test_t *var;\n const struct test_t * const var;\n typedef struct test_t { \n void *unused; \n} test_t;\n const test_t *var;\n test_t struct test_t const const struct test_t"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10763104/"
] |
74,547,714
|
<p>I'm trying to understand the options for hosting an asp.net core website on the internet today. I understand that HTTP.SYS based hosting is possible without having IIS on the webserver but I've not found clear information as to why you would do it (pros/cons) and what is today the most security way to host on the internet an asp.net core website. IIS was time back considered somehow an unsecure webserver and I don't know to what extent this is still true today. I'm leaving out of the discussion kestrel which I perceive more as a development-only option but not secure enough for direct internet hosting.</p>
|
[
{
"answer_id": 74547758,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 3,
"selected": false,
"text": "typedef struct test_t { \n void *unused; \n} test_t;\n\nconst test_t *var;\n"
},
{
"answer_id": 74547884,
"author": "Antti Haapala -- Слава Україні",
"author_id": 918959,
"author_profile": "https://Stackoverflow.com/users/918959",
"pm_score": 0,
"selected": false,
"text": "typedef typedef const struct { \n void *unused; \n} *const_test_t;\n test_t struct test_t {...} test_t const test_t var:\n const struct test_t *ptr;\n typedef const struct { } *test_t;"
},
{
"answer_id": 74547932,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "typedef struct test_t { \n void *unused; \n} *(test_t);\n test_t struct test_t * const test_t var;\n test_t const var;\n struct test_t * const var;\n var struct test_t var const struct test_t *var;\n const struct test_t * const var;\n typedef struct test_t { \n void *unused; \n} test_t;\n const test_t *var;\n test_t struct test_t const const struct test_t"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5014665/"
] |
74,547,753
|
<p>I have a dataframe column which looks like this:</p>
<pre><code>df_cost['region.localCurrency']:
0 [{'content': 'Dirham', 'languageCode': 'EN'}]
1 [{'content': 'Dirham', 'languageCode': 'EN'}]
2 [{'content': 'Dirham', 'languageCode': 'EN'}]
3 [{'content': 'Euro', 'languageCode': 'DE'}]
4 [{'content': 'Euro', 'languageCode': 'DE'}]
5 [{'content': 'Euro', 'languageCode': 'DE'}]
6 [{'content': 'Euro', 'languageCode': 'DE'}]
7 [{'content': 'Euro', 'languageCode': 'DE'}]
8 [{'content': 'Euro', 'languageCode': 'DE'}]
9 [{'content': 'Euro', 'languageCode': 'DE'}]
10 [{'content': 'Euro', 'languageCode': 'DE'}]
11 [{'content': 'Euro', 'languageCode': 'DE'}]
12 [{'content': 'Euro', 'languageCode': 'DE'}]
13 [{'content': 'Dirham', 'languageCode': 'EN'}]
14 [{'content': 'Dirham', 'languageCode': 'EN'}]
15 [{'content': 'Dirham', 'languageCode': 'EN'}]
16 [{'content': 'Euro', 'languageCode': 'DE'}]
17 [{'content': 'Euro', 'languageCode': 'DE'}]
18 [{'content': 'Euro', 'languageCode': 'DE'}]
19 [{'content': 'Euro', 'languageCode': 'DE'}]
Name: region.localCurrency, dtype: object
</code></pre>
<p>and I want to convert it, to separate the dictionary keys and values into columns. I want to add two separate columns to the initial df_cost dataframe, like 'localCurrencyContent' and 'localCurrencyCode', based on the dictionary contents of region.localCurrency.
I tried to split the region.localCurrency column like:</p>
<pre><code>df_split=pd.DataFrame(df_cost['region.localCurrency'].apply(pd.Series), columns=['localCurrencyContent', 'localCurrencyCode'])
print(df_split)
</code></pre>
<p>but this gives me NaN values for the localCurrencyContent and localCurrencyCode, instead of 'Euro' and 'DE' for example. How could I split the column "region.localCurrency" and add the two created columns to the cost_df, initial dataframe?</p>
|
[
{
"answer_id": 74547758,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 3,
"selected": false,
"text": "typedef struct test_t { \n void *unused; \n} test_t;\n\nconst test_t *var;\n"
},
{
"answer_id": 74547884,
"author": "Antti Haapala -- Слава Україні",
"author_id": 918959,
"author_profile": "https://Stackoverflow.com/users/918959",
"pm_score": 0,
"selected": false,
"text": "typedef typedef const struct { \n void *unused; \n} *const_test_t;\n test_t struct test_t {...} test_t const test_t var:\n const struct test_t *ptr;\n typedef const struct { } *test_t;"
},
{
"answer_id": 74547932,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "typedef struct test_t { \n void *unused; \n} *(test_t);\n test_t struct test_t * const test_t var;\n test_t const var;\n struct test_t * const var;\n var struct test_t var const struct test_t *var;\n const struct test_t * const var;\n typedef struct test_t { \n void *unused; \n} test_t;\n const test_t *var;\n test_t struct test_t const const struct test_t"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18890565/"
] |
74,547,763
|
<p>I've got an icon that shows a popup div when the user hovers over it or focuses on it and then disappears when the users mouse moves out or blur.
Currently I have this:</p>
<pre><code><div
className="iconWrapper"
onFocus={() => this.showToolTip(true)}
onBlur={() => this.showToolTip(false)}
onMouseOver={() => this.showToolTip(true)}
onMouseOut={() => this.showToolTip(false)}
tabIndex="0"
role="button">
<Icon width="12" height="12" fillColor="#000" />
</div>
</code></pre>
<p>This works but its pretty messy, is there another way to accomplish this goal?</p>
|
[
{
"answer_id": 74547758,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 3,
"selected": false,
"text": "typedef struct test_t { \n void *unused; \n} test_t;\n\nconst test_t *var;\n"
},
{
"answer_id": 74547884,
"author": "Antti Haapala -- Слава Україні",
"author_id": 918959,
"author_profile": "https://Stackoverflow.com/users/918959",
"pm_score": 0,
"selected": false,
"text": "typedef typedef const struct { \n void *unused; \n} *const_test_t;\n test_t struct test_t {...} test_t const test_t var:\n const struct test_t *ptr;\n typedef const struct { } *test_t;"
},
{
"answer_id": 74547932,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "typedef struct test_t { \n void *unused; \n} *(test_t);\n test_t struct test_t * const test_t var;\n test_t const var;\n struct test_t * const var;\n var struct test_t var const struct test_t *var;\n const struct test_t * const var;\n typedef struct test_t { \n void *unused; \n} test_t;\n const test_t *var;\n test_t struct test_t const const struct test_t"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15123639/"
] |
74,547,765
|
<blockquote>
<p>Ask for a string from the user and make each alternative word lower and upper case (e.g. the string “I am learning to code” would
become “i AM learning TO code”). Using the split and join functions will help you here.</p>
</blockquote>
<p>I did a similar thing for characters in the string, but as I found out it doesn't work with full words.</p>
<pre><code>new_string = input("Please enter a string: ")
char_storage = "" #blank string to store all the string's characters
char = 1
for i in new_string:
if char % 2 == 0:
char_storage += i.lower()
else:
char_storage += i.upper()
char += 1
print(char_storage)
</code></pre>
<p>I am still quite confused about how python connects char with new_string value, if anyone has a good website where it is explained I would be very grateful.</p>
|
[
{
"answer_id": 74547876,
"author": "OneCricketeer",
"author_id": 2308683,
"author_profile": "https://Stackoverflow.com/users/2308683",
"pm_score": 0,
"selected": false,
"text": "new_string = input(\"Please enter a string: \").split()\n def change_case(x, upper):\n return x.upper() if upper else x.lower()\nchar_storage = ' '.join(change_case(x, i%2!=0) for i, x in enumerate(new_string)) \n"
},
{
"answer_id": 74547918,
"author": "P-A",
"author_id": 9720524,
"author_profile": "https://Stackoverflow.com/users/9720524",
"pm_score": 2,
"selected": true,
"text": "new_string = input(\"Please enter a string: \")\nchar_storage = \"\" #blank string to store all the string's characters\nchar = 1\n\nfor i in new_string.split(): \n if char != 1:\n char_storage += \" \"\n if char % 2 == 0:\n char_storage += i.lower()\n else: \n char_storage += i.upper()\n char += 1\n"
},
{
"answer_id": 74548001,
"author": "Martin",
"author_id": 5621651,
"author_profile": "https://Stackoverflow.com/users/5621651",
"pm_score": 0,
"selected": false,
"text": "new_string = input(\"Please enter a string: \").split()\nchar_storage = \" \".join([x.upper() if i % 2 else x.lower() for i, x in enumerate(new_string)])\nprint(char_storage)\n \" \".join()"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20148679/"
] |
74,547,768
|
<p>I have an existing Google Cloud Function that I am trying to call. I want to pass into it an Id and with that Id, the cloud function can run its operation in the background. I am new to cloud functions and would appreciate the help. When I call the function, I get the error "POST....500" and the error message says "INTERNAL". Here is the code I use to call the cloud function, I have declared a function that I call in an onClick event in a button:</p>
<pre><code>import { httpsCallable } from "firebase/functions";
import { functions } from "../../../firebase/firebase";
/* Below is how I call the cloud function */
// handle payment confirmation
const handlePayment = async () => {
const confirmPayment = httpsCallable(
functions,
"loanV2Group-onManualRepay"
);
confirmPayment(loanId)
.then((response) => {
if (response.status === "success") {
setIsConfirmed(true);
setOpenSnackbar(true);
handleClose();
} else {
setOpenSnackbar(true);
}
})
.catch((error) => {
console.log("Payment Confirmation Error: ", error);
});
};
</code></pre>
<p>Kindly help!! Thanks.</p>
|
[
{
"answer_id": 74547876,
"author": "OneCricketeer",
"author_id": 2308683,
"author_profile": "https://Stackoverflow.com/users/2308683",
"pm_score": 0,
"selected": false,
"text": "new_string = input(\"Please enter a string: \").split()\n def change_case(x, upper):\n return x.upper() if upper else x.lower()\nchar_storage = ' '.join(change_case(x, i%2!=0) for i, x in enumerate(new_string)) \n"
},
{
"answer_id": 74547918,
"author": "P-A",
"author_id": 9720524,
"author_profile": "https://Stackoverflow.com/users/9720524",
"pm_score": 2,
"selected": true,
"text": "new_string = input(\"Please enter a string: \")\nchar_storage = \"\" #blank string to store all the string's characters\nchar = 1\n\nfor i in new_string.split(): \n if char != 1:\n char_storage += \" \"\n if char % 2 == 0:\n char_storage += i.lower()\n else: \n char_storage += i.upper()\n char += 1\n"
},
{
"answer_id": 74548001,
"author": "Martin",
"author_id": 5621651,
"author_profile": "https://Stackoverflow.com/users/5621651",
"pm_score": 0,
"selected": false,
"text": "new_string = input(\"Please enter a string: \").split()\nchar_storage = \" \".join([x.upper() if i % 2 else x.lower() for i, x in enumerate(new_string)])\nprint(char_storage)\n \" \".join()"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13441266/"
] |
74,547,779
|
<p>I have a dataframe like this:</p>
<pre><code>DURATION CLUSTER COEFF
3 0 0.34
3 1 -0.005
3 2 1
3 3 0.33
4 0 -0.02
4 1 -0.28
4 2 0.22
4 3 0.48
5 0 0.65
5 1 -0.26
5 2 0.1
5 3 0.15
</code></pre>
<p>I want to create a RESULT categorical column according to the "COEFF" coefficients for each "DURATION". The one with the greatest "COEFF" value will be "First" and so on.</p>
<p>Desired output like this:</p>
<pre><code>DURATION CLUSTER COEFF RESULT
3 0 0.34 Second
3 1 -0.005 Fourth
3 2 1 First
3 3 0.33 Third
4 0 -0.02 Third
4 1 -0.28 Fourth
4 2 0.22 Second
4 3 0.48 First
5 0 0.65 First
5 1 -0.26 Fourth
5 2 0.1 Third
5 3 0.15 Second
</code></pre>
<p>Could you please help me about this?</p>
|
[
{
"answer_id": 74547858,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "groupby.rank map labels = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\ndf['RESULT'] = (df.groupby('DURATION')['COEFF']\n .rank('dense', ascending=False).sub(1)\n .map(dict(enumerate(labels)))\n )\n DURATION CLUSTER COEFF RESULT\n0 3 0 0.340 Second\n1 3 1 -0.005 Fourth\n2 3 2 1.000 First\n3 3 3 0.330 Third\n4 4 0 -0.020 Third\n5 4 1 -0.280 Fourth\n6 4 2 0.220 Second\n7 4 3 0.480 First\n8 5 0 0.650 First\n9 5 1 -0.260 Fourth\n10 5 2 0.100 Third\n11 5 3 0.150 Second\n"
},
{
"answer_id": 74548215,
"author": "LoneWanderer",
"author_id": 7237062,
"author_profile": "https://Stackoverflow.com/users/7237062",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\n# see answer https://stackoverflow.com/a/20007730/7237062, others exist\n# code golfed version of an \"ordinal\" function (int -> ordinal string in english)\nordinal = lambda n: \"%d%s\" % (n,\"tsnrhtdd\"[(n//10%10!=1)*(n%10<4)*n%10::4])\n# copy pasta of OP input data\ndf = pd.read_clipboard() # let pandas read the clipboard\ndf[\"RESULT\"] = (df.groupby('DURATION')['COEFF']\n .rank('dense', ascending=False)\n .sub(1) # mozway's answer so far !\n .astype(int)\n + 1 # +1 so ordinals start at 1 (instead of 0)\n ).apply(ordinal) \n DURATION CLUSTER COEFF RESULT\n0 3 0 0.340 2nd\n1 3 1 -0.005 4th\n2 3 2 1.000 1st\n3 3 3 0.330 3rd\n4 4 0 -0.020 3rd\n5 4 1 -0.280 4th\n6 4 2 0.220 2nd\n7 4 3 0.480 1st\n8 5 0 0.650 1st\n9 5 1 -0.260 4th\n10 5 2 0.100 3rd\n11 5 3 0.150 2nd\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12231431/"
] |
74,547,781
|
<p>I've been mostly using private variables when writing a class and using methods to set the variable's value.</p>
<p>Especially when it comes array, indexing them would be just using the operator[]. But what if I were to put them inside a method like <code>getIndex(int x)</code>, and calling that method. Would that have any impact to the performance like slowing it down a little bit?</p>
|
[
{
"answer_id": 74547904,
"author": "Quimby",
"author_id": 7691729,
"author_profile": "https://Stackoverflow.com/users/7691729",
"pm_score": 2,
"selected": true,
"text": "inline object.array[idx]"
},
{
"answer_id": 74547952,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 2,
"selected": false,
"text": "getItem(int idx) getItems()"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15690088/"
] |
74,547,796
|
<p>I have the dataframe.
`</p>
<pre><code>data = pd.DataFrame([['Benz', 'MinSpeed', 0, np.nan, 'USA', '2022-08-12'],
['Benz', 'TopSpeed', 200, np.nan, 'USA', '2022-08-12'],
['Benz', 'ChasisNum', 654121, np.nan, 'USA', '2022-08-12'],
['Benz', 'Seats', 5, np.nan, 'USA', '2022-08-12'],
['Benz', 'AirBags', 5, np.nan, 'USA', '2022-08-12'],
['Benz', 'VehicleType', np.nan, 'Sedan', 'USA', '2022-08-12'],
['Benz', 'Color', np.nan, 'Black','USA', '2022-08-12'],
['Benz', 'InternetInside', np.nan, 'Yes','USA', '2022-08-12'],
['Ferrari', 'MinSpeed', 0, np.nan, 'France', '2022-12-25'],
['Ferrari', 'TopSpeed', 250, np.nan, 'France', '2022-12-25'],
['Ferrari', 'ChasisNum', 781121, np.nan, 'France', '2022-12-25'],
['Ferrari', 'Seats', 4, np.nan, 'France', '2022-12-25'],
['Ferrari', 'AirBags', 2, np.nan, 'France', '2022-12-25'],
['Ferrari', 'VehicleType', np.nan, 'SUV', 'France', '2022-12-25'],
['Ferrari', 'Color', np.nan, 'Red','France', '2022-12-25'],
['Ferrari', 'InternetInside', np.nan, 'No','France', '2022-12-25'],
],
columns= ['CarModel', 'Features', 'NumericalValues', 'CategoricalValues','Country', 'DeliveryDate'])
</code></pre>
<p>`</p>
<p>I am trying the pivot the data using the pivot function but getting repeated columns for "NumericalValues" and "CategoricalValues" values</p>
<p>Code:
`</p>
<pre><code>data.pivot(index='CarModel', columns='Features', values=['NumericalValues','CategoricalValues' ]).reset_index()
</code></pre>
<p>`</p>
<p>I need the expected output as:
`</p>
<pre><code>output_data = pd.DataFrame([['Benz', 0, 200, 654121, 5, 5, 'Sedan', 'Black', 'Yes', 'USA', '2022-08-12'],
['Ferrari', 0, 250, 781121, 4, 2, 'SUV', 'Red', 'No', 'France', '2022-12-25']
],
columns=['CarModel', 'MinSpeed', 'TopSpeed', 'ChasisNum','Seats', 'AirBags', 'VehicleType', 'Color', 'InternetInside', 'Country', 'DeliveryDate'])
</code></pre>
<p>`
I tried with Pivot table as well but unable to get this output.</p>
|
[
{
"answer_id": 74548032,
"author": "Ben.T",
"author_id": 9274732,
"author_profile": "https://Stackoverflow.com/users/9274732",
"pm_score": 2,
"selected": true,
"text": "fillna pivot res = (\n data.assign(Values=lambda x: x['NumericalValues'].fillna(x['CategoricalValues']))\n .pivot(index='CarModel', columns='Features', values='Values')\n .reset_index().rename_axis(columns=None)\n)\nprint(res)\n# CarModel AirBags ChasisNum Color InternetInside MinSpeed Seats TopSpeed \\\n# 0 Benz 5.0 654121.0 Black Yes 0.0 5.0 200.0 \n# 1 Ferrari 2.0 781121.0 Red No 0.0 4.0 250.0 \n\n# VehicleType \n# 0 Sedan \n# 1 SUV \n"
},
{
"answer_id": 74548044,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "pivot groupby.first out = (data\n .pivot(index=['CarModel', 'Country', 'DeliveryDate'],\n columns='Features'\n )\n .groupby(level='Features', axis=1).first()\n .reset_index()\n)\n Features CarModel Country DeliveryDate AirBags ChasisNum Color InternetInside MinSpeed Seats TopSpeed VehicleType\n0 Benz USA 2022-08-12 5.0 654121.0 Black Yes 0.0 5.0 200.0 Sedan\n1 Ferrari France 2022-12-25 2.0 781121.0 Red No 0.0 4.0 250.0 SUV\n Features\nCarModel object\nCountry object\nDeliveryDate object\nAirBags float64\nChasisNum float64\nColor object\nInternetInside object\nMinSpeed float64\nSeats float64\nTopSpeed float64\nVehicleType object\ndtype: object\n"
},
{
"answer_id": 74550824,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "pandas.pivot_table out = (data.pivot_table(\n index=['CarModel', 'Country', 'DeliveryDate'], \n columns='Features', values=['NumericalValues', 'CategoricalValues'],\n aggfunc=max)\n .droplevel(0, axis=1)\n .rename_axis(None, axis=1)\n .reset_index())\n CarModel Country DeliveryDate Color InternetInside VehicleType AirBags \\\n0 Benz USA 2022-08-12 Black Yes Sedan 5.0 \n1 Ferrari France 2022-12-25 Red No SUV 2.0 \n\n ChasisNum MinSpeed Seats TopSpeed \n0 654121.0 0.0 5.0 200.0 \n1 781121.0 0.0 4.0 250.0 \n CarModel object\nCountry object\nDeliveryDate object\nColor object\nInternetInside object\nVehicleType object\nAirBags float64\nChasisNum float64\nMinSpeed float64\nSeats float64\nTopSpeed float64\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19836382/"
] |
74,547,814
|
<p>I'm trying to implement (into Java SE) a standalone embedded web server, exposing REST application with CDI support.</p>
<p>I followed up a simple tutorial at this link <a href="https://techunity.de/blog/integrate-a-rest-service-into-a-standalone-java-application/" rel="nofollow noreferrer">https://techunity.de/blog/integrate-a-rest-service-into-a-standalone-java-application/</a>, but I don't want to use OpenAPI, just simple JAX-RS resource classes.</p>
<p>I set up Gradle as follow, with all required dependencies:</p>
<pre><code>plugins {
id 'application'
id 'java'
id 'eclipse'
}
repositories {
mavenCentral()
}
dependencies {
// Use JUnit Jupiter for testing.
testImplementation 'org.junit.jupiter:junit-jupiter:5.7.2'
// This dependency is used by the application.
implementation 'org.slf4j:slf4j-api:2.0.4'
implementation 'ch.qos.logback:logback-classic:1.4.5'
implementation 'jakarta.enterprise:jakarta.enterprise.cdi-api:3.0.1'
implementation 'jakarta.ws.rs:jakarta.ws.rs-api:3.0.1'
implementation 'org.jboss.weld.se:weld-se-core:5.1.0.Final'
implementation 'org.jboss.weld.servlet:weld-servlet-core:5.1.0.Final'
implementation 'org.eclipse.jetty:jetty-server:11.0.12'
implementation 'org.eclipse.jetty:jetty-servlet:11.0.12'
implementation 'org.glassfish.jersey.core:jersey-server:3.1.0'
implementation 'org.glassfish.jersey.containers:jersey-container-servlet-core:3.1.0'
implementation 'org.glassfish.jersey.ext.cdi:jersey-cdi1x:3.1.0'
implementation 'org.glassfish.jersey.ext.cdi:jersey-cdi1x-servlet:3.1.0'
implementation 'org.glassfish.jersey.ext.cdi:jersey-weld2-se:3.1.0'
implementation 'org.glassfish.jersey.inject:jersey-hk2:3.1.0'
implementation 'org.glassfish.jersey.media:jersey-media-json-jackson:3.1.0'
implementation 'com.fasterxml.jackson.core:jackson-core:2.12.7'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.7'
}
application {
// Define the main class for the application.
mainClass = 'it.gym.StartApp'
}
tasks.named('test') {
// Use JUnit Platform for unit tests.
useJUnitPlatform()
}
</code></pre>
<p>Then I created the main class:</p>
<pre><code>package it.gym;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.servlet.ServletContainer;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.jboss.weld.environment.servlet.Listener;
import org.jboss.weld.environment.servlet.WeldServletLifecycle;
public class StartApp {
public static void main(String[] args) {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
final Server server = new Server(9000);
final ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.addEventListener(Listener.using(weld));
context.setAttribute(
WeldServletLifecycle.BEAN_MANAGER_ATTRIBUTE_NAME,
container.getBeanManager());
final ServletHolder servletHolder = new ServletHolder(
ServletContainer.class);
servletHolder.setInitOrder(1);
servletHolder.setInitParameter(
"jersey.config.server.provider.packages",
"it.gym");
context.addServlet(servletHolder, "/rest/*");
server.setHandler(context);
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>And then I created a resource class and a bean class:</p>
<pre><code>package it.gym.rest;
import java.util.List;
import it.gym.dao.GymDAO;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
@Path("/")
@RequestScoped
public class GymEndpoint {
@Inject
private GymDAO gymDAO;
@GET
@Path("/test")
public Response test() {
List<String> entity = gymDAO.getDevices();
return Response.status(Status.OK).entity(entity).build();
}
}
</code></pre>
<pre><code>package it.gym.dao;
import java.util.ArrayList;
import java.util.List;
import jakarta.enterprise.context.RequestScoped;
@RequestScoped
public class GymDAO {
public GymDAO() {
}
public List<String> getDevices() {
return new ArrayList<>();
}
}
</code></pre>
<p>When I start the server I get the following error. It seems not to find the GymDAO class as a CDI class, ignoring the @RequestScoped annotation. Can anyone figure out what I'm missing?</p>
<pre><code>jakarta.servlet.ServletException: org.glassfish.jersey.servlet.ServletContainer-15eebbff==org.glassfish.jersey.servlet.ServletContainer@60d52d52{jsp=null,order=1,inst=true,async=true,src=EMBEDDED:null,STARTED}
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:651)
at org.eclipse.jetty.servlet.ServletHolder.initialize(ServletHolder.java:415)
at org.eclipse.jetty.servlet.ServletHandler.lambda$initialize$2(ServletHandler.java:725)
at java.base/java.util.stream.SortedOps$SizedRefSortingSink.end(SortedOps.java:357)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:510)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:749)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:392)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:901)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:306)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:93)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:171)
at org.eclipse.jetty.server.Server.start(Server.java:470)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:89)
at org.eclipse.jetty.server.Server.doStart(Server.java:415)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:93)
at it.gym.StartApp.main(StartApp.java:40)
Caused by: org.jboss.weld.exceptions.IllegalArgumentException: WELD-001408: Unsatisfied dependencies for type GymDAO with qualifiers @Default
at injection point [BackedAnnotatedField] @Inject private it.gym.rest.GymEndpoint.gymDAO
at it.gym.rest.GymEndpoint.gymDAO(GymEndpoint.java:0)
at org.jboss.weld.manager.InjectionTargetFactoryImpl.createInjectionTarget(InjectionTargetFactoryImpl.java:83)
at org.jboss.weld.manager.InjectionTargetFactoryImpl.createInjectionTarget(InjectionTargetFactoryImpl.java:70)
at org.jboss.weld.manager.InjectionTargetFactoryImpl.createInjectionTarget(InjectionTargetFactoryImpl.java:51)
at org.glassfish.jersey.ext.cdi1x.internal.AbstractCdiBeanSupplier$2.<init>(AbstractCdiBeanSupplier.java:83)
at org.glassfish.jersey.ext.cdi1x.internal.AbstractCdiBeanSupplier.<init>(AbstractCdiBeanSupplier.java:79)
at org.glassfish.jersey.ext.cdi1x.internal.GenericCdiBeanSupplier.<init>(GenericCdiBeanSupplier.java:37)
at org.glassfish.jersey.ext.cdi1x.internal.CdiComponentProvider.bind(CdiComponentProvider.java:225)
at org.glassfish.jersey.ext.cdi1x.internal.CdiComponentProvider.bind(CdiComponentProvider.java:182)
at org.glassfish.jersey.ext.cdi1x.internal.CdiServerComponentProvider.bind(CdiServerComponentProvider.java:50)
at org.glassfish.jersey.server.ResourceModelConfigurator.bindWithComponentProvider(ResourceModelConfigurator.java:193)
at org.glassfish.jersey.server.ResourceModelConfigurator.bindProvidersAndResources(ResourceModelConfigurator.java:150)
at org.glassfish.jersey.server.ResourceModelConfigurator.init(ResourceModelConfigurator.java:63)
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:359)
at org.glassfish.jersey.server.ApplicationHandler.lambda$initialize$1(ApplicationHandler.java:310)
at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
at org.glassfish.jersey.internal.Errors.process(Errors.java:274)
at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:232)
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:309)
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:274)
at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:311)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:154)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:338)
at jakarta.servlet.GenericServlet.init(GenericServlet.java:178)
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:633)
... 20 more
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type GymDAO with qualifiers @Default
at injection point [BackedAnnotatedField] @Inject private it.gym.rest.GymEndpoint.gymDAO
at it.gym.rest.GymEndpoint.gymDAO(GymEndpoint.java:0)
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:367)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:285)
at org.jboss.weld.bootstrap.Validator.validateProducer(Validator.java:414)
at org.jboss.weld.injection.producer.InjectionTargetService.validateProducer(InjectionTargetService.java:36)
at org.jboss.weld.manager.InjectionTargetFactoryImpl.validate(InjectionTargetFactoryImpl.java:153)
at org.jboss.weld.manager.InjectionTargetFactoryImpl.createInjectionTarget(InjectionTargetFactoryImpl.java:81)
... 43 more
14:27:02.984 [Thread-0] INFO org.jboss.weld.Bootstrap - WELD-ENV-002001: Weld SE container 944b54c2-e094-44a2-ba2b-0ae8d247d9aa shut down
Weld SE container 944b54c2-e094-44a2-ba2b-0ae8d247d9aa shut down by shutdown hook
</code></pre>
|
[
{
"answer_id": 74548839,
"author": "Francesco Rosso",
"author_id": 9630238,
"author_profile": "https://Stackoverflow.com/users/9630238",
"pm_score": 0,
"selected": false,
"text": "plugins {\n id 'application'\n id 'java'\n id 'eclipse'\n}\n\nrepositories {\n mavenCentral()\n}\n\ndependencies {\n // Use JUnit Jupiter for testing.\n testImplementation 'org.junit.jupiter:junit-jupiter:5.7.2'\n\n // This dependency is used by the application.\n implementation 'org.slf4j:slf4j-api:2.0.4'\n implementation 'ch.qos.logback:logback-classic:1.4.5'\n\n implementation 'jakarta.enterprise:jakarta.enterprise.cdi-api:3.0.1'\n implementation 'jakarta.ws.rs:jakarta.ws.rs-api:3.0.1'\n\n implementation 'org.jboss.weld.se:weld-se-core:5.1.0.Final'\n implementation 'org.jboss.weld.servlet:weld-servlet-core:5.1.0.Final'\n\n implementation 'org.glassfish.grizzly:grizzly-http-server:4.0.0'\n\n implementation 'org.glassfish.jersey.core:jersey-server:3.1.0'\n implementation 'org.glassfish.jersey.containers:jersey-container-grizzly2-http:3.1.0'\n implementation 'org.glassfish.jersey.ext.cdi:jersey-weld2-se:3.1.0'\n implementation 'org.glassfish.jersey.inject:jersey-hk2:3.1.0'\n implementation 'org.glassfish.jersey.media:jersey-media-json-jackson:3.1.0'\n\n implementation 'com.fasterxml.jackson.core:jackson-core:2.12.7'\n implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.7'\n}\n\napplication {\n // Define the main class for the application.\n mainClass = 'it.gym.StartApp'\n}\n\ntasks.named('test') {\n // Use JUnit Platform for unit tests.\n useJUnitPlatform()\n}\n package it.gym;\n\nimport java.net.URI;\n\nimport org.glassfish.grizzly.http.server.HttpServer;\nimport org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;\nimport org.glassfish.jersey.server.ResourceConfig;\nimport org.jboss.weld.environment.se.Weld;\n\npublic class StartApp {\n\n public static void main(String[] args) {\n Weld weld = new Weld();\n weld.initialize();\n\n ResourceConfig resourceConfig = new ResourceConfig();\n resourceConfig.packages(\"it.gym\");\n\n final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create(\"http://localhost:9000/\"),\n resourceConfig);\n\n try {\n Thread.sleep(1000 * 1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n\n server.shutdownNow();\n weld.shutdown();\n }\n}\n"
},
{
"answer_id": 74554923,
"author": "Joakim Erdfelt",
"author_id": 775715,
"author_profile": "https://Stackoverflow.com/users/775715",
"pm_score": 1,
"selected": false,
"text": "jetty-11.0.x implementation 'org.slf4j:slf4j-api:2.0.4'\n implementation 'ch.qos.logback:logback-classic:1.4.5'\n\n implementation 'org.eclipse.jetty:jetty-servlet:11.0.12'\n implementation 'org.eclipse.jetty:jetty-cdi:11.0.12'\n \n implementation 'org.jboss.weld.servlet:weld-servlet-core:4.0.3.Final'\n\n implementation 'org.glassfish.jersey.containers:jersey-container-servlet-core:3.0.4'\n implementation 'org.glassfish.jersey.media:jersey-cdi2-se:3.0.4'\n implementation 'org.glassfish.jersey.media:jersey-media-json-jackson:3.0.4'\n jetty-cdi context.addEventListener(Listener.using(weld));\ncontext.setAttribute(\n WeldServletLifecycle.BEAN_MANAGER_ATTRIBUTE_NAME,\n container.getBeanManager());\n import org.eclipse.jetty.cdi.CdiServletContainerInitializer;\nimport org.eclipse.jetty.cdi.CdiDecoratingListener;\nimport org.jboss.weld.environment.servlet.EnhancedListener;\n\ncontext.setInitParameter(\n CdiServletContainerInitializer.CDI_INTEGRATION_ATTRIBUTE, \n CdiDecoratingListener.MODE);\ncontext.addServletContainerInitializer(new CdiServletContainerInitializer());\ncontext.addServletContainerInitializer(new EnhancedListener());\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9630238/"
] |
74,547,909
|
<p>So far my modal works fine, and does what it's supposed to be.
But when i try to implement a way to let the modal close when i click outside the modal I run into some bugs.</p>
<p>e.g. i tried to add onClick={() => setShowModal(false) in the top div, but then the button to open the modal no longer works, bcs this button is inside the top div with the setShowModal(false) function.</p>
<pre><code>const [showModal, setShowModal] = useState(false);
<div className='flex justify-center md:justify-end md:mt-4 mt-12'>
<button
onClick={() => setShowModal(!showModal)}
className='bg-red-500 hover:bg-red-400 text-white font-bold py-2 px-4 border-red-700 rounded'
>
Delete account button
</button>
{showModal && (
<>
<div className='justify-center items-center flex overflow-x-hidden overflow-y-auto fixed inset-0 z-50 outline-none focus:outline-none'>
<div className='relative w-auto my-6 mx-auto max-w-3xl'>
<div className=' bg-gray-600 rounded-lg shadow-2xl relative flex flex-col w-full bg-white outline-none focus:outline-none'>
<div className='flex items-start justify-between p-5 border-b border-solid border-slate-200 rounded-t'>
<h3 className='text-3xl font-semibold text-red-500'>
Delete account
</h3>
</div>
<div className='relative p-6 flex-auto'>
<p className='my-4 text-white text-lg leading-relaxed'>
Are you sure...
</p>
</div>
<div className='flex items-center justify-end p-6 border-t border-solid border-slate-200 rounded-b'>
<button
className='text-red-500 background-transparent font-bold uppercase px-6 py-2 text-sm outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150'
type='button'
onClick={() => setShowModal(!showModal)}
>
Cancel
</button>
<button
className='bg-red-500 text-white active:bg-red-600 font-bold uppercase text-sm px-6 py-3 rounded shadow hover:shadow-lg outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150'
type='button'
onClick={() => handleSelfDelete(user._id)}
>
Confirm
</button>
</div>
</div>
</div>
</div>
<div
className='w-full h-screen opacity-25 fixed inset-0 z-10 bg-black'
onClick={() => setShowModal(false)}
/>
</>
)}
</div>
</code></pre>
|
[
{
"answer_id": 74548839,
"author": "Francesco Rosso",
"author_id": 9630238,
"author_profile": "https://Stackoverflow.com/users/9630238",
"pm_score": 0,
"selected": false,
"text": "plugins {\n id 'application'\n id 'java'\n id 'eclipse'\n}\n\nrepositories {\n mavenCentral()\n}\n\ndependencies {\n // Use JUnit Jupiter for testing.\n testImplementation 'org.junit.jupiter:junit-jupiter:5.7.2'\n\n // This dependency is used by the application.\n implementation 'org.slf4j:slf4j-api:2.0.4'\n implementation 'ch.qos.logback:logback-classic:1.4.5'\n\n implementation 'jakarta.enterprise:jakarta.enterprise.cdi-api:3.0.1'\n implementation 'jakarta.ws.rs:jakarta.ws.rs-api:3.0.1'\n\n implementation 'org.jboss.weld.se:weld-se-core:5.1.0.Final'\n implementation 'org.jboss.weld.servlet:weld-servlet-core:5.1.0.Final'\n\n implementation 'org.glassfish.grizzly:grizzly-http-server:4.0.0'\n\n implementation 'org.glassfish.jersey.core:jersey-server:3.1.0'\n implementation 'org.glassfish.jersey.containers:jersey-container-grizzly2-http:3.1.0'\n implementation 'org.glassfish.jersey.ext.cdi:jersey-weld2-se:3.1.0'\n implementation 'org.glassfish.jersey.inject:jersey-hk2:3.1.0'\n implementation 'org.glassfish.jersey.media:jersey-media-json-jackson:3.1.0'\n\n implementation 'com.fasterxml.jackson.core:jackson-core:2.12.7'\n implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.7'\n}\n\napplication {\n // Define the main class for the application.\n mainClass = 'it.gym.StartApp'\n}\n\ntasks.named('test') {\n // Use JUnit Platform for unit tests.\n useJUnitPlatform()\n}\n package it.gym;\n\nimport java.net.URI;\n\nimport org.glassfish.grizzly.http.server.HttpServer;\nimport org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;\nimport org.glassfish.jersey.server.ResourceConfig;\nimport org.jboss.weld.environment.se.Weld;\n\npublic class StartApp {\n\n public static void main(String[] args) {\n Weld weld = new Weld();\n weld.initialize();\n\n ResourceConfig resourceConfig = new ResourceConfig();\n resourceConfig.packages(\"it.gym\");\n\n final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create(\"http://localhost:9000/\"),\n resourceConfig);\n\n try {\n Thread.sleep(1000 * 1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n\n server.shutdownNow();\n weld.shutdown();\n }\n}\n"
},
{
"answer_id": 74554923,
"author": "Joakim Erdfelt",
"author_id": 775715,
"author_profile": "https://Stackoverflow.com/users/775715",
"pm_score": 1,
"selected": false,
"text": "jetty-11.0.x implementation 'org.slf4j:slf4j-api:2.0.4'\n implementation 'ch.qos.logback:logback-classic:1.4.5'\n\n implementation 'org.eclipse.jetty:jetty-servlet:11.0.12'\n implementation 'org.eclipse.jetty:jetty-cdi:11.0.12'\n \n implementation 'org.jboss.weld.servlet:weld-servlet-core:4.0.3.Final'\n\n implementation 'org.glassfish.jersey.containers:jersey-container-servlet-core:3.0.4'\n implementation 'org.glassfish.jersey.media:jersey-cdi2-se:3.0.4'\n implementation 'org.glassfish.jersey.media:jersey-media-json-jackson:3.0.4'\n jetty-cdi context.addEventListener(Listener.using(weld));\ncontext.setAttribute(\n WeldServletLifecycle.BEAN_MANAGER_ATTRIBUTE_NAME,\n container.getBeanManager());\n import org.eclipse.jetty.cdi.CdiServletContainerInitializer;\nimport org.eclipse.jetty.cdi.CdiDecoratingListener;\nimport org.jboss.weld.environment.servlet.EnhancedListener;\n\ncontext.setInitParameter(\n CdiServletContainerInitializer.CDI_INTEGRATION_ATTRIBUTE, \n CdiDecoratingListener.MODE);\ncontext.addServletContainerInitializer(new CdiServletContainerInitializer());\ncontext.addServletContainerInitializer(new EnhancedListener());\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74547909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20199710/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.