qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,488,705
|
<p>I have the following funciton telling us that a <code>series</code> has at least one negative value:</p>
<pre><code>def has_negative(series):
v=False
for i in range(len(series)):
if series[i]<0:
v=True
break
return v
</code></pre>
<p>When we use this function on an example we get :</p>
<pre><code>y=[1,2,3,4,5,6,7,8,9]
z=[1,-2,3,4,5,6,7,8,9]
print(has_negative(y))
print(has_negative(y))
</code></pre>
<p>Output:</p>
<pre><code>>>> False
>>> True
</code></pre>
<p>The function seems to work well, although I want to make it shorter, any suggestion from your side will be appreciated</p>
|
[
{
"answer_id": 74488796,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 1,
"selected": false,
"text": "def has_negative(series):\n for i in series:\n if i < 0:\n return True\n return False\n print(bool([i for i in z if i<0]))\n"
},
{
"answer_id": 74488804,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 3,
"selected": true,
"text": "def has_negative(lst):\n return any(e < 0 for e in lst)\n\nprint(has_negative([1,2,3,4,5,6,7,8,9]))\nprint(has_negative([1,-2,3,4,5,6,7,8,9]))\n False\nTrue\n"
},
{
"answer_id": 74488841,
"author": "iurii_n",
"author_id": 1227828,
"author_profile": "https://Stackoverflow.com/users/1227828",
"pm_score": 2,
"selected": false,
"text": "sorted(series)[0] < 0\n"
},
{
"answer_id": 74489419,
"author": "Marble_gold",
"author_id": 15423701,
"author_profile": "https://Stackoverflow.com/users/15423701",
"pm_score": 1,
"selected": false,
"text": "has_negative = lambda series: True if [series for x in series if x < 0] else False\n z = [1,-2,3,4,5,6,7,8,9]\n\nhas_negative(z)\n >>> True\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15852600/"
] |
74,488,737
|
<p>This works on my local machine</p>
<pre><code>git ls-remote --tags | grep -o 'refs/tags/[0-9]*\.[0-9]*' | sort -r | head -1 | grep -o '[^\/]*$
</code></pre>
<p>but not in my jenkins build server which is running from docker, it doesn't have the rights and I can't seem to fix that.</p>
<p>Is there an alternative for <code>ls-remote</code> which would give me exactly the same output, but then for my local git repository?</p>
<p>Or, is there a silver bullet solution for getting the LATEST tag from my local repo, looking from the tip of the branch and then backwards? I have been struggling with <code>git tag | head -1</code> and all kinds of alternatives but nothing gives me the latest tag searching back from the tip of the branch....</p>
|
[
{
"answer_id": 74488913,
"author": "LeGEC",
"author_id": 86072,
"author_profile": "https://Stackoverflow.com/users/86072",
"pm_score": 0,
"selected": false,
"text": "git tag --sort=v:refname | tail -1\n git tag --sort=v:refname --list \"v[0-9]*\" | tail -1\n v[0-9]* v [0-9] * git fetch --tags git tag --sort=v:refname --merged=HEAD | tail -1\n git describe --tags --abbrev=0\n"
},
{
"answer_id": 74489420,
"author": "Lazy Badger",
"author_id": 960558,
"author_profile": "https://Stackoverflow.com/users/960558",
"pm_score": 2,
"selected": true,
"text": "git describe --abbrev"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1470327/"
] |
74,488,763
|
<p>I am doing php parser using cURL (simple_html_dom.php).
I have to parse news posts here: <a href="https://www.sport-express.ru/football/reviews/page2/" rel="nofollow noreferrer">https://www.sport-express.ru/football/reviews/page2/</a>
It is second page. I need to get programatically last number of page (it will be 50).
There is no pagination - only lazy loading button.
How can I get last page number using cURL?
Thanks!</p>
<p>PS: It will be great if You show also how can I get last page number when there will pagination.</p>
|
[
{
"answer_id": 74488913,
"author": "LeGEC",
"author_id": 86072,
"author_profile": "https://Stackoverflow.com/users/86072",
"pm_score": 0,
"selected": false,
"text": "git tag --sort=v:refname | tail -1\n git tag --sort=v:refname --list \"v[0-9]*\" | tail -1\n v[0-9]* v [0-9] * git fetch --tags git tag --sort=v:refname --merged=HEAD | tail -1\n git describe --tags --abbrev=0\n"
},
{
"answer_id": 74489420,
"author": "Lazy Badger",
"author_id": 960558,
"author_profile": "https://Stackoverflow.com/users/960558",
"pm_score": 2,
"selected": true,
"text": "git describe --abbrev"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20146550/"
] |
74,488,766
|
<p>I am using <code>react-router</code> where I have following code</p>
<pre><code> <Router basename={config.historyBasename}>
<Routes>
<Route path={routes.landingPage} element={<LandingPage />} />
<Route
path={routes.activateAccount}
element={
!document.referrer.length ? (
redirectTo(appUrls.home)
) : (
<Parent/>
)
}
/>
</Routes>
</Router>
</code></pre>
<p>Here, I am using <code>redirectTo</code> which I created custom method. Now here, I am trying to create a custom route which will do</p>
<pre><code> <Route
path={routes.activateAccount}
element={
!document.referrer.length ? (
redirectTo(appUrls.home)
) : (
<Parent/>
)
}
/>
</code></pre>
<p>this. How can I create a custom route which will handle this ?</p>
|
[
{
"answer_id": 74488913,
"author": "LeGEC",
"author_id": 86072,
"author_profile": "https://Stackoverflow.com/users/86072",
"pm_score": 0,
"selected": false,
"text": "git tag --sort=v:refname | tail -1\n git tag --sort=v:refname --list \"v[0-9]*\" | tail -1\n v[0-9]* v [0-9] * git fetch --tags git tag --sort=v:refname --merged=HEAD | tail -1\n git describe --tags --abbrev=0\n"
},
{
"answer_id": 74489420,
"author": "Lazy Badger",
"author_id": 960558,
"author_profile": "https://Stackoverflow.com/users/960558",
"pm_score": 2,
"selected": true,
"text": "git describe --abbrev"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9372639/"
] |
74,488,803
|
<p>I ask the user to enter it's name and I print the pattern
eg:
W
WO
WOR
WORL
WORLD</p>
<pre><code>s=input("Enter your name")
l=s.split()
i=len(l)
for m in range(0,i):
for s in range(0,m):
print(s)
print()
</code></pre>
<p>I have written this program where am I wrong please help. A beginner here</p>
|
[
{
"answer_id": 74488886,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "name = input(\"Enter your name: \")\nfor i in range(len(name)):\n print(name[:i+1])\n"
},
{
"answer_id": 74488890,
"author": "Bharat Adhikari",
"author_id": 17731030,
"author_profile": "https://Stackoverflow.com/users/17731030",
"pm_score": 1,
"selected": true,
"text": "s = input(\"Enter your name\")\n\nfor i in range(len(s)+1):\n print(s[:i])\n\n#Output:\nW\nWO\nWOR\nWORL\nWORLD\n"
},
{
"answer_id": 74489110,
"author": "Hampus Larsson",
"author_id": 8805293,
"author_profile": "https://Stackoverflow.com/users/8805293",
"pm_score": 1,
"selected": false,
"text": "#s=input(\"Enter your name\")\n# Let's pretend that the given word from the user was 'WORLD' as in your example.\ns = \"WORLD\"\nl=s.split()\n s.split() str.split() split(self, /, sep=None, maxsplit=-1)\n Return a list of the words in the string, using sep as the delimiter string.\n\n sep\n The delimiter according which to split the string.\n None (the default value) means split according to any whitespace,\n and discard empty strings from the result.\n \"WORLD\".split() ['WORLD'] i=len(l)\n s.split() # This is essentially: for m in range(0, 1) which will only loop once, because range is non-inclusive\nfor m in range(0,i): \n # This is range-command will not execute, because the first value of m will be 0\n # Because range is non-inclusive, running range(0, 0) will not return a value.\n # That means that nothing inside of the for-loop will execute.\n for s in range(0,m):\n print(s)\n print()\n print() range"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20210759/"
] |
74,488,847
|
<p>I have two objects inst1, inst2 which are both instances of the same class. If I use</p>
<pre><code>inst2 = JSON.parse(JSON.stringify(inst1));
</code></pre>
<p>now if I change values of properties of inst2, values in inst1 do not change. That is great.
But sadly methods of inst2 have disappeared. So if I do</p>
<pre><code>inst2.method1();
</code></pre>
<p>I get the error
"inst2.method1 is not a function"</p>
<p><strong>Is there some way I can copy the values in an instance without destroying methods?</strong>
(obviously I could laboriously copy each value. I am trying to avoid that because I am lazy.)</p>
<p>I have tried to follow <a href="https://stackoverflow.com/questions/28150967/typescript-cloning-object">typescript - cloning object</a> but I cannot make it work-</p>
|
[
{
"answer_id": 74488886,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "name = input(\"Enter your name: \")\nfor i in range(len(name)):\n print(name[:i+1])\n"
},
{
"answer_id": 74488890,
"author": "Bharat Adhikari",
"author_id": 17731030,
"author_profile": "https://Stackoverflow.com/users/17731030",
"pm_score": 1,
"selected": true,
"text": "s = input(\"Enter your name\")\n\nfor i in range(len(s)+1):\n print(s[:i])\n\n#Output:\nW\nWO\nWOR\nWORL\nWORLD\n"
},
{
"answer_id": 74489110,
"author": "Hampus Larsson",
"author_id": 8805293,
"author_profile": "https://Stackoverflow.com/users/8805293",
"pm_score": 1,
"selected": false,
"text": "#s=input(\"Enter your name\")\n# Let's pretend that the given word from the user was 'WORLD' as in your example.\ns = \"WORLD\"\nl=s.split()\n s.split() str.split() split(self, /, sep=None, maxsplit=-1)\n Return a list of the words in the string, using sep as the delimiter string.\n\n sep\n The delimiter according which to split the string.\n None (the default value) means split according to any whitespace,\n and discard empty strings from the result.\n \"WORLD\".split() ['WORLD'] i=len(l)\n s.split() # This is essentially: for m in range(0, 1) which will only loop once, because range is non-inclusive\nfor m in range(0,i): \n # This is range-command will not execute, because the first value of m will be 0\n # Because range is non-inclusive, running range(0, 0) will not return a value.\n # That means that nothing inside of the for-loop will execute.\n for s in range(0,m):\n print(s)\n print()\n print() range"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12220927/"
] |
74,488,850
|
<p>I have a few repos on GitHub. Up until now, I've used a single machine (a Mac) to host the local version of of these repos; i.e. they are located in the folder <code>/Users/seamus/Documents/GitHub</code> on the <code>Macintosh HD</code> for this Mac. Eeach repo has a sub-folder. Straightforward and simple to maintain for one user and one machine.</p>
<p>But I'm "branching out" a bit... I now have 3 Macs, an Ubuntu desktop, a few Raspberry Pis and I work on projects that are tied closely to a particular machine. For example, I have set up the IDE for my RPi Pico ucontroller on the Ubuntu box, whereas my Mac-related projects are on one of my Macs - which one depends upon whether the project is "vintage" or "current". And this may be important: I am the only "local person" working on these repos - there is no "team".</p>
<p>In summary, it has become awkward to have the local repo located on the <code>Mac HD</code> of one of my Macs. A potential solution would be to move my local Mac HD-based repo to my NAS drive - a Synology unit. I can mount a share on the Synology from all of my machines, and (it seems to me) this would solve my immediate problem by allowing me to work on any of my repos from any of my machines.</p>
<p>AFAICT the NAS-hosted local repo should work fine for my current situation (1 user, several repos). But I'm not proficient with <code>git</code>, so I wanted to ask if there are any obvious problems with this setup - or if there's a better way to accomplish my objective?</p>
|
[
{
"answer_id": 74488886,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "name = input(\"Enter your name: \")\nfor i in range(len(name)):\n print(name[:i+1])\n"
},
{
"answer_id": 74488890,
"author": "Bharat Adhikari",
"author_id": 17731030,
"author_profile": "https://Stackoverflow.com/users/17731030",
"pm_score": 1,
"selected": true,
"text": "s = input(\"Enter your name\")\n\nfor i in range(len(s)+1):\n print(s[:i])\n\n#Output:\nW\nWO\nWOR\nWORL\nWORLD\n"
},
{
"answer_id": 74489110,
"author": "Hampus Larsson",
"author_id": 8805293,
"author_profile": "https://Stackoverflow.com/users/8805293",
"pm_score": 1,
"selected": false,
"text": "#s=input(\"Enter your name\")\n# Let's pretend that the given word from the user was 'WORLD' as in your example.\ns = \"WORLD\"\nl=s.split()\n s.split() str.split() split(self, /, sep=None, maxsplit=-1)\n Return a list of the words in the string, using sep as the delimiter string.\n\n sep\n The delimiter according which to split the string.\n None (the default value) means split according to any whitespace,\n and discard empty strings from the result.\n \"WORLD\".split() ['WORLD'] i=len(l)\n s.split() # This is essentially: for m in range(0, 1) which will only loop once, because range is non-inclusive\nfor m in range(0,i): \n # This is range-command will not execute, because the first value of m will be 0\n # Because range is non-inclusive, running range(0, 0) will not return a value.\n # That means that nothing inside of the for-loop will execute.\n for s in range(0,m):\n print(s)\n print()\n print() range"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5395338/"
] |
74,488,869
|
<p>I implement this target by below code</p>
<p>open file:</p>
<pre><code>/* 打开文件
* @param file
*/
public static void openFile(Activity context, File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//设置intent的Action属性
intent.setAction(Intent.ACTION_VIEW);
//intent.addCategory(Intent.CATEGORY_DEFAULT);
//获取文件file的Uri
Uri uri = UriUtils.file2Uri(file);
//获取文件file的MIME类型
String type = getMimeType(context, uri);
//设置intent的data和Type属性。
intent.setDataAndType(/*uri*/uri, type);
try {
//跳转
context.startActivity(intent); //这里最好try一下,有可能会报错。 //比如说你的MIME类型是打开邮箱,但是你手机里面没装邮箱客户端,就会报错。
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getMimeType(Context context, Uri uri) {
ContentResolver cR = context.getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
//String type = mime.getExtensionFromMimeType(cR.getType(uri));
String type = cR.getType(uri);
return type;
}
</code></pre>
<p>file to uri</p>
<pre><code> /**
* File to uri.
*
* @param file The file.
* @return uri
*/
public static Uri file2Uri(@NonNull final File file) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
String authority = Utils.getApp().getPackageName() + ".utilcode.provider";
return FileProvider.getUriForFile(Utils.getApp(), authority, file);
} else {
return Uri.fromFile(file);
}
}
</code></pre>
<p>provider declare</p>
<pre><code> <provider
android:name="com.blankj.utilcode.util.UtilsFileProvider"
android:authorities="${applicationId}.utilcode.provider"
android:exported="false"
android:grantUriPermissions="true" >
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/util_code_provider_paths" />
</provider>
</code></pre>
<p>provider resource</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<paths>
<root-path
name="root_path"
path="" />
<files-path
name="files_path"
path="." />
<cache-path
name="cache_path"
path="." />
<external-path
name="external_path"
path="." />
<external-files-path
name="external_files_path"
path="." />
<external-cache-path
name="external_cache_path"
path="." />
<external-media-path
name="external_media_path"
path="." />
</paths>
</code></pre>
<p>Now I have a question: I can open zip or rar files by choosing qq browser, but not by choosing quark or uc browser</p>
<p>How I can do to open zip or rar files by choosing quark or uc browser.
Thanks for your time first.</p>
<p>By the way, I can open normal format file such as jpeg or txt by choosing any browser.</p>
|
[
{
"answer_id": 74488886,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "name = input(\"Enter your name: \")\nfor i in range(len(name)):\n print(name[:i+1])\n"
},
{
"answer_id": 74488890,
"author": "Bharat Adhikari",
"author_id": 17731030,
"author_profile": "https://Stackoverflow.com/users/17731030",
"pm_score": 1,
"selected": true,
"text": "s = input(\"Enter your name\")\n\nfor i in range(len(s)+1):\n print(s[:i])\n\n#Output:\nW\nWO\nWOR\nWORL\nWORLD\n"
},
{
"answer_id": 74489110,
"author": "Hampus Larsson",
"author_id": 8805293,
"author_profile": "https://Stackoverflow.com/users/8805293",
"pm_score": 1,
"selected": false,
"text": "#s=input(\"Enter your name\")\n# Let's pretend that the given word from the user was 'WORLD' as in your example.\ns = \"WORLD\"\nl=s.split()\n s.split() str.split() split(self, /, sep=None, maxsplit=-1)\n Return a list of the words in the string, using sep as the delimiter string.\n\n sep\n The delimiter according which to split the string.\n None (the default value) means split according to any whitespace,\n and discard empty strings from the result.\n \"WORLD\".split() ['WORLD'] i=len(l)\n s.split() # This is essentially: for m in range(0, 1) which will only loop once, because range is non-inclusive\nfor m in range(0,i): \n # This is range-command will not execute, because the first value of m will be 0\n # Because range is non-inclusive, running range(0, 0) will not return a value.\n # That means that nothing inside of the for-loop will execute.\n for s in range(0,m):\n print(s)\n print()\n print() range"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538746/"
] |
74,488,889
|
<p>I hope to get the name with the initial from the client's full name using the SQL server.
The format should be the First letter of the first name and middle names except last name + Last name</p>
<p>Eg:
If the full name is John Cena, then the output should be J Cena</p>
<p>if the full name is Wathsala Malshani Perera, then the output should be W M Perera.</p>
<p>please help me to build a query.
Thank you</p>
|
[
{
"answer_id": 74488886,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "name = input(\"Enter your name: \")\nfor i in range(len(name)):\n print(name[:i+1])\n"
},
{
"answer_id": 74488890,
"author": "Bharat Adhikari",
"author_id": 17731030,
"author_profile": "https://Stackoverflow.com/users/17731030",
"pm_score": 1,
"selected": true,
"text": "s = input(\"Enter your name\")\n\nfor i in range(len(s)+1):\n print(s[:i])\n\n#Output:\nW\nWO\nWOR\nWORL\nWORLD\n"
},
{
"answer_id": 74489110,
"author": "Hampus Larsson",
"author_id": 8805293,
"author_profile": "https://Stackoverflow.com/users/8805293",
"pm_score": 1,
"selected": false,
"text": "#s=input(\"Enter your name\")\n# Let's pretend that the given word from the user was 'WORLD' as in your example.\ns = \"WORLD\"\nl=s.split()\n s.split() str.split() split(self, /, sep=None, maxsplit=-1)\n Return a list of the words in the string, using sep as the delimiter string.\n\n sep\n The delimiter according which to split the string.\n None (the default value) means split according to any whitespace,\n and discard empty strings from the result.\n \"WORLD\".split() ['WORLD'] i=len(l)\n s.split() # This is essentially: for m in range(0, 1) which will only loop once, because range is non-inclusive\nfor m in range(0,i): \n # This is range-command will not execute, because the first value of m will be 0\n # Because range is non-inclusive, running range(0, 0) will not return a value.\n # That means that nothing inside of the for-loop will execute.\n for s in range(0,m):\n print(s)\n print()\n print() range"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20385505/"
] |
74,488,899
|
<p>I would like to convert strings such as <strong>"Tue, 15 May 2012 17:26:44 EST"</strong> into UTC dates, so that I can then convert them into UNIX timestamps.</p>
<p>I tried the following but can't see a parameter for timezones in the MySQL <a href="https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_str-to-date" rel="nofollow noreferrer">documentation</a></p>
<pre><code>SELECT STR_TO_DATE("Tue, 15 May 2012 17:26:44 EST", "%a, %d-%b-%Y %T");
</code></pre>
<p>I think I can also use COVERT_TZ() but the records could be any timezone so I'm not sure how to to determine the parameters.</p>
|
[
{
"answer_id": 74488886,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "name = input(\"Enter your name: \")\nfor i in range(len(name)):\n print(name[:i+1])\n"
},
{
"answer_id": 74488890,
"author": "Bharat Adhikari",
"author_id": 17731030,
"author_profile": "https://Stackoverflow.com/users/17731030",
"pm_score": 1,
"selected": true,
"text": "s = input(\"Enter your name\")\n\nfor i in range(len(s)+1):\n print(s[:i])\n\n#Output:\nW\nWO\nWOR\nWORL\nWORLD\n"
},
{
"answer_id": 74489110,
"author": "Hampus Larsson",
"author_id": 8805293,
"author_profile": "https://Stackoverflow.com/users/8805293",
"pm_score": 1,
"selected": false,
"text": "#s=input(\"Enter your name\")\n# Let's pretend that the given word from the user was 'WORLD' as in your example.\ns = \"WORLD\"\nl=s.split()\n s.split() str.split() split(self, /, sep=None, maxsplit=-1)\n Return a list of the words in the string, using sep as the delimiter string.\n\n sep\n The delimiter according which to split the string.\n None (the default value) means split according to any whitespace,\n and discard empty strings from the result.\n \"WORLD\".split() ['WORLD'] i=len(l)\n s.split() # This is essentially: for m in range(0, 1) which will only loop once, because range is non-inclusive\nfor m in range(0,i): \n # This is range-command will not execute, because the first value of m will be 0\n # Because range is non-inclusive, running range(0, 0) will not return a value.\n # That means that nothing inside of the for-loop will execute.\n for s in range(0,m):\n print(s)\n print()\n print() range"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5770166/"
] |
74,488,975
|
<p>How to write this SQL query in a better way. Can I avoid using a CTE?</p>
<p>For a subset of table_1 I need to get only the data with the latest integration_date. For data not in the subset (variable_A != 'X') I want all data from table_1.</p>
<pre><code>Latest_dates AS ( SELECT MAX(INTEGRATION_DATE) AS MAX_INTEGRATION_DATE, ID FROM table_1 GROUP BY ID)
SELECT S.* FROM Table_1 AS S
LEFT JOIN Latest_dates ON S.INTEGRATION_DATE = Latest_dates.MAX_INTEGRATION_DATE AND S.ID= Latest_dates.ID
WHERE Latest_dates.MAX_INTEGRATION_DATE is not NULL
OR S.variable_A != 'X'
</code></pre>
<p>Code works fine, but looks ugly.</p>
|
[
{
"answer_id": 74489048,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 2,
"selected": false,
"text": "CTE WITH CTE AS\n(\n SELECT ID, INTEGRATION_DATE, \n IdDateRank = RANK() OVER (PARTITION BY ID ORDER BY INTEGRATION_DATE DESC)\n -- other columns\n WHERE S.variable_A != 'X'\n)\nSELECT ID, INTEGRATION_DATE -- other columns\nFROM CTE WHERE IdDateRank = 1\n"
},
{
"answer_id": 74490233,
"author": "George Menoutis",
"author_id": 5825963,
"author_profile": "https://Stackoverflow.com/users/5825963",
"pm_score": 0,
"selected": false,
"text": "select top 1 * with ties \nfrom Table_1 \norder by row_number() over (partition by id order by case when variable_A = 'X' then null else INTEGRATION_DATE end desc) asc\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10711681/"
] |
74,488,978
|
<p>I have a table with sticky header and sticky tds which have rowspan.
When it's scrolled td with rowspan appears on top of it's header (according to this example it is the first column).
Specifying z-index puts header on top of the td but overlaps its text.
How can I prevent this?
My first version was without rowspan, contained empty cells and behaved correctly.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
/*
.wrapper {
overflow: auto;
height: 20rem;
}
*/
table {
display: block;
overflow: auto;
height: 20rem;
border-collapse: separate;
border-spacing: 0;
}
thead {
position: sticky;
top: 0;
background-color: #333;
color: #fff;
/* z-index: 100; */
}
thead th {
border: 0.1rem solid #ddd;
}
tbody tr:nth-child(even) {
background-color: #ddd;
}
tbody td {
padding: 0 0.5rem;
}
tbody td[rowspan] {
border-top: 0.1rem solid #999;
vertical-align: top;
position: sticky;
top: 1.4rem;
background-color: #fff;
/* z-index: 10; */
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- <div class="wrapper"> -->
<table>
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
<th>col5</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="10">cell_text_1</td>
<td rowspan="4">cell_text</td>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="4">cell_text</td>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="2">cell_text</td>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="10">cell_text_2</td>
<td rowspan="5">cell_text</td>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="5">cell_text</td>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="18">cell_text_3</td>
<td rowspan="6">cell_text</td>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="7">cell_text</td>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="5">cell_text</td>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="12">cell_text_4</td>
<td rowspan="6">cell_text</td>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="6">cell_text</td>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
<tr>
<td rowspan="">cell_text</td>
<td>cell_text</td>
<td>cell_text</td>
</tr>
</tbody>
</table>
<!-- </div> --></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74489048,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 2,
"selected": false,
"text": "CTE WITH CTE AS\n(\n SELECT ID, INTEGRATION_DATE, \n IdDateRank = RANK() OVER (PARTITION BY ID ORDER BY INTEGRATION_DATE DESC)\n -- other columns\n WHERE S.variable_A != 'X'\n)\nSELECT ID, INTEGRATION_DATE -- other columns\nFROM CTE WHERE IdDateRank = 1\n"
},
{
"answer_id": 74490233,
"author": "George Menoutis",
"author_id": 5825963,
"author_profile": "https://Stackoverflow.com/users/5825963",
"pm_score": 0,
"selected": false,
"text": "select top 1 * with ties \nfrom Table_1 \norder by row_number() over (partition by id order by case when variable_A = 'X' then null else INTEGRATION_DATE end desc) asc\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538236/"
] |
74,488,989
|
<p>I'm quite new in C and wanted to write code for a Binary-Tree with methods for inserting, deleting and wahtever.
In the code, I use value = 0 in order to show that the struct is undefined yet. (I don't know any better way). Problem: We shouldn't insert the value 0.
The main problem I have: Why does <code>printf("%d\n", root.pLeft->value);</code> print the number 6422476 instead of 3??
Here is the whole code:
`</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node {
int value;
struct Node *pLeft;
struct Node *pRight;
};
void insert(struct Node *root, int value) {
struct Node *current = root;
while (current->value != 0) {
if (value < current->value) {
current = current->pLeft;
} else {
current = current->pRight;
}
}
current->value = value;
struct Node newLeft;
newLeft.value = 0;
struct Node newRight;
newRight.value = 0;
current->pLeft = &newLeft;
current->pRight = &newRight;
}
int main() {
struct Node root;
root.value = 0;
insert(&root, 4);
insert(&root, 3);
printf("%d\n", root.value);
printf("%d\n", root.pLeft->value);
return 0;
}
</code></pre>
<p>`</p>
<hr />
|
[
{
"answer_id": 74489048,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 2,
"selected": false,
"text": "CTE WITH CTE AS\n(\n SELECT ID, INTEGRATION_DATE, \n IdDateRank = RANK() OVER (PARTITION BY ID ORDER BY INTEGRATION_DATE DESC)\n -- other columns\n WHERE S.variable_A != 'X'\n)\nSELECT ID, INTEGRATION_DATE -- other columns\nFROM CTE WHERE IdDateRank = 1\n"
},
{
"answer_id": 74490233,
"author": "George Menoutis",
"author_id": 5825963,
"author_profile": "https://Stackoverflow.com/users/5825963",
"pm_score": 0,
"selected": false,
"text": "select top 1 * with ties \nfrom Table_1 \norder by row_number() over (partition by id order by case when variable_A = 'X' then null else INTEGRATION_DATE end desc) asc\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20028059/"
] |
74,488,994
|
<p>I want to access an element using React.createRef() (which is inside a function). Below is the example of how I want to access it.</p>
<p><strong>react:</strong></p>
<pre><code>someFunction = () => {
let element = this.myRef.current;
console.log(element)
}
</code></pre>
<pre><code>render(){
return(
<FlexView>
<div ref={this.myRef}>
some text here
</div>
{this.someFunction()}
</FlexView>
)
}
</code></pre>
<p>Here, I want to access the div element through <strong>someFunction()</strong>. But for some reason <strong>this.myRef.current</strong> is returning a null value in console - I guess the issue is related to react life cycle, but I just can't figure out why. However by using the button, I can able to access the div element without having any problem, but only when I try to use the above method to trigger a function it's returning null.</p>
<pre><code>render(){
return(
<FlexView>
<div ref={this.myRef}>
some text here
</div>
<button onClick={this.someFunction()}>click-here</button>
</FlexView>
)
}
</code></pre>
<p>Can someone please let me know how do it.</p>
<p>p.s. I'm new to React and Js</p>
|
[
{
"answer_id": 74489178,
"author": "Fahad Ali",
"author_id": 15844433,
"author_profile": "https://Stackoverflow.com/users/15844433",
"pm_score": 1,
"selected": false,
"text": " class Component extends React.Component{\n constructor(...args){\n super(args);\n this.ref = React.createRef();\n }\n state = {\n isLoaded = false;\n }\n componentDidMount(){\n this.setState({isLoaded:true}) \n }\n someFunction = () => {\n let element = this.myRef.current;\n console.log(element)\n }\n render(){\n <FlexView>\n <div ref={this.ref}>\n some text here \n </div>\n <button onClick={this.someFunction}>click-here</button>\n </FlexView>\n }\n \n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74488994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18445570/"
] |
74,489,006
|
<p>Raku sigils denote the nature of the underlying variable (e.g., $scalar, @positional, %associative, &code).</p>
<p>It's possible to declare a variable as sigil-less with a backslash (e.g., \some-variable) and then later refer to it without a sigil (i.e., some-variable).</p>
<p>Just wondering in what circumstance it's preferred to use a sigil-less variable?</p>
|
[
{
"answer_id": 74493069,
"author": "Jonathan Worthington",
"author_id": 7832584,
"author_profile": "https://Stackoverflow.com/users/7832584",
"pm_score": 5,
"selected": true,
"text": "my \\a = expr a expr my $fh = open 'somefile';\nmy \\no-comments = $fh.lines.grep({ not /^\\s*'#'/ });\nfor no-comments -> $sig-line {\n ...\n}\n grep Seq @ my $fh = open 'somefile';\nmy @no-comments = $fh.lines.grep({ not /^\\s*'#'/ });\nfor @no-comments -> $sig-line {\n ...\n}\n @no-comments $ my $fh = open 'somefile';\nmy $no-comments = $fh.lines.grep({ not /^\\s*'#'/ });\nfor $no-comments -> $sig-line {\n ...\n}\n Seq $sig-line my $fh = open 'somefile';\nmy $no-comments = $fh.lines.grep({ not /^\\s*'#'/ });\nfor $no-comments<> -> $sig-line {\n ...\n}\n sub log-and-call(&foo, \\value) {\n note(value.raku);\n foo(value)\n}\n $ foo"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2145475/"
] |
74,489,011
|
<p>I have a list of objects which needs to be filtered with another list of functional interfaces.</p>
<p>For example:</p>
<pre><code>List<SomeClass> originalList = .....
List<SomeClass> filteredList = originalList.stream().filter(filterList).toList();
^^^^^^^^^^^^^^^^
</code></pre>
<p>How do I use a list of functional interfaces here such that
the final list contains objects filtered by all the filters in the list. Where</p>
<pre><code>List<FilterClass> filterList = Arrays.asList(
new ClassWhichImplementsFilterClass1(),
new ClassWhichImplementsFilterClass2()
);
</code></pre>
<p>FilterClass.java</p>
<pre><code>@FunctionalInterface
public interface FilterClass{
boolean isValid(SomeClass someClass);
}
</code></pre>
<p>How do I achieve this? I think I can do this by streaming the list of objects and then passing that object through each filter class in the <code>filterList</code>, but is there a way to do it some other way.</p>
|
[
{
"answer_id": 74489465,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 2,
"selected": true,
"text": "Class Predicate<SomeClass> class Student {\n @Getter public LocalDate birthDate;\n}\n\nPredicate<Student> isAdult = s -> ChronoUnit.YEARS.between(\n LocalDate.now(), s.getBirthDate()) >= 18;\n List<Predicate<Student>> filterList = ...;\nPredicate<Student> allMatch = s -> {\n for (var pred : filterList) if (!pred.test(s)) return false;\n return true;\n}\n\nfoo.stream().filter(allMatch).collect(....);\n Predicate and List<Predicate<Student>> filterList = ...;\nPredicate<Student> allMatch = s -> true;\nfor (var pred : filterList) allMatch = allMatch.and(pred);\n List<Predicate<Student>> filterList = ...;\nPredicate<Student> allMatch = filterList.stream()\n .collect(Collectors.reducing(s -> true, Predicate::and));\n FilterClass java.util.function.Predicate and"
},
{
"answer_id": 74489696,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 0,
"selected": false,
"text": "filter Predicate filter Predicate Predicate Predicate abstract Predicate abstract abstract isValid() List<Filter> filters = List.of();\n \nList<SomeClass> originalList = List.of();\n \nList<SomeClass> filteredList = originalList.stream()\n .filter(foo -> filters.stream().anyMatch(filter -> filter.isValid(foo))) // or `.allMatch` depending of how validation should be performed\n .toList(); // for Java 16+ or collect(Collectors.toList())\n Predicate @FunctionalInterface\npublic interface Filter extends Predicate<SomeClass> {\n \n default boolean isValid(SomeClass someClass) {\n return test(someClass);\n }\n}\n Predicate.and() Predicate.or() List<Filter> filters = List.of();\n \nPredicate<SomeClass> allMatch = filters.stream().map(Predicate.class::cast).reduce(t -> true, Predicate::and);\nPredicate<SomeClass> anyMatch = filters.stream().map(Predicate.class::cast).reduce(t -> false, Predicate::or);\n\nList<SomeClass> originalList = List.of();\n \nList<SomeClass> filteredList = originalList.stream()\n .filter(anyMatch)\n .toList(); // for Java 16+ or collect(Collectors.toList())\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4242499/"
] |
74,489,031
|
<p>What are the reasons for C++ to not define some behavior (something like better error checking)? Why don't throw some error and stop?</p>
<p>Some pseudocodes for example:</p>
<pre><code>if (p == NULL && op == deref){
return "Invalid operation"
}
</code></pre>
<p>For Integer Overflows:</p>
<pre><code>if(size > capacity){
return "Overflow"
}
</code></pre>
<p>I know these are very simple examples. But I'm pretty sure most UBs can be caught by the compiler. So why not implement them? Because it is really time expensive and not doing error checking is faster? Some UBs can be caught with a single if statement. So maybe speed is not the only concern?</p>
|
[
{
"answer_id": 74489078,
"author": "user253751",
"author_id": 106104,
"author_profile": "https://Stackoverflow.com/users/106104",
"pm_score": 4,
"selected": true,
"text": "-fwrapv int array[N];\n// ...\nfor(int i = 0; i < N+1; i++) {\n fprintf(file, \"%d \", array[i]);\n}\n array[N] i < N+1 int getFoo(struct X *px) {return (px == NULL ? -1 : px->foo);}\n\nint blah(struct X *px) {\n bar(px->f1);\n printf(\"%s\", px->name);\n frobnicate(&px->theFrob);\n count += getFoo(px);\n}\n px px == NULL getFoo(px) px->foo"
},
{
"answer_id": 74489443,
"author": "HolyBlackCat",
"author_id": 2752075,
"author_profile": "https://Stackoverflow.com/users/2752075",
"pm_score": 3,
"selected": false,
"text": "-fsanitize=address -fsanitize=undefined"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19076879/"
] |
74,489,047
|
<p>I have the dataframe '<strong>rankedvariableslist</strong>', with the index 'Sleepvariables' being the sleep variable of interest, and the two columns being the R-squared and P-value of that model and variable respectively.</p>
<p>I am trying to sort the data in ascending order by 'P-value', then by 'R-squared value', but I keep getting the error: '<strong>'values' is not ordered, please explicitly specify the categories order by passing in a categories argument</strong>' and am not sure why.</p>
<p>I would be so grateful for a helping hand!</p>
<pre><code>correspondantsleepvariable = []
correspondantpvalue = []
correspondantpvalue = []
newerresults = resultmodeldistancevariation2sleepsummary.tables[0]
newerdata = pd.DataFrame(newerresults)
rsquaredvalue = newerdata.iloc[0,3]
rsquaredvalues.append(rsquaredvalue)
modelpvalues = resultmodeldistancevariation2sleepsummary.tables[1]
newerdatavalues = pd.DataFrame(modelpvalues)
pvalue = newerdatavalues.iloc[12,4]
correspondantpvalue.append(pvalue)
correspondantsleepvariable.append(sleepvariable[i])
rankedvariableslist.sort_values(['P-value','R-squared value'],ascending = [True, False])
print(rankedvariableslist.head(3)
Sleepvariables R-squared value P-value
0 hours_of_sleep 0.026 0.491
1 frequency_of_alarm_usage 0.026 0.681
2 sleepiness_bed 0.026 0.413
</code></pre>
<pre><code>As an example of the dataframe 'newerresults':
OLS Regression Results
==============================================================================
Dep. Variable: distance R-squared: 0.028
Model: OLS Adj. R-squared: 0.016
Method: Least Squares F-statistic: 2.338
Date: Fri, 18 Nov 2022 Prob (F-statistic): 0.00773
Time: 12:39:29 Log-Likelihood: -1274.1
No. Observations: 907 AIC: 2572.
Df Residuals: 895 BIC: 2630.
Df Model: 11
Covariance Type: nonrobust
==============================================================================
</code></pre>
|
[
{
"answer_id": 74489078,
"author": "user253751",
"author_id": 106104,
"author_profile": "https://Stackoverflow.com/users/106104",
"pm_score": 4,
"selected": true,
"text": "-fwrapv int array[N];\n// ...\nfor(int i = 0; i < N+1; i++) {\n fprintf(file, \"%d \", array[i]);\n}\n array[N] i < N+1 int getFoo(struct X *px) {return (px == NULL ? -1 : px->foo);}\n\nint blah(struct X *px) {\n bar(px->f1);\n printf(\"%s\", px->name);\n frobnicate(&px->theFrob);\n count += getFoo(px);\n}\n px px == NULL getFoo(px) px->foo"
},
{
"answer_id": 74489443,
"author": "HolyBlackCat",
"author_id": 2752075,
"author_profile": "https://Stackoverflow.com/users/2752075",
"pm_score": 3,
"selected": false,
"text": "-fsanitize=address -fsanitize=undefined"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12985497/"
] |
74,489,058
|
<p>When I get an automated 400 from Asp.Net Core, there are often some implementation details that I do not want to expose, nor are they relevant really, e.g.:</p>
<pre class="lang-json prettyprint-override"><code>{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-71b3ed06990f759c440ed484475b437c-23db588b254e8013-00",
"errors": {
"$": [
"JSON deserialization for type 'MyExampleNamespace.MyRequest' was missing required properties, including the following: messageId"
],
"request": [
"The request field is required."
]
}
}
</code></pre>
<pre><code>public record MyRequest
{
public required MessageId { get; init; }
}
</code></pre>
<p>Example request:
json</p>
<pre><code>{
"notMessageId": "hello"
}
</code></pre>
<p>So what I expect to get is a more "non C# dependent response" that does not include fully qualified C# names in response.</p>
|
[
{
"answer_id": 74489078,
"author": "user253751",
"author_id": 106104,
"author_profile": "https://Stackoverflow.com/users/106104",
"pm_score": 4,
"selected": true,
"text": "-fwrapv int array[N];\n// ...\nfor(int i = 0; i < N+1; i++) {\n fprintf(file, \"%d \", array[i]);\n}\n array[N] i < N+1 int getFoo(struct X *px) {return (px == NULL ? -1 : px->foo);}\n\nint blah(struct X *px) {\n bar(px->f1);\n printf(\"%s\", px->name);\n frobnicate(&px->theFrob);\n count += getFoo(px);\n}\n px px == NULL getFoo(px) px->foo"
},
{
"answer_id": 74489443,
"author": "HolyBlackCat",
"author_id": 2752075,
"author_profile": "https://Stackoverflow.com/users/2752075",
"pm_score": 3,
"selected": false,
"text": "-fsanitize=address -fsanitize=undefined"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1671558/"
] |
74,489,084
|
<p>In wix 3 you could specify a condition inside the <a href="https://wixtoolset.org/docs/v3/xsd/wix/custom/" rel="nofollow noreferrer">custom element</a>.</p>
<p>In wix 4 the same element does not seem to accept inner text anymore. If you try to set a condition the compiler throws a <code>The Custom element contains illegal inner text: 'NOT Installed AND NOT UPGRADINGPRODUCTCODE'</code> error. How would one go ahead and only run the custom action during the installation now?</p>
|
[
{
"answer_id": 74489305,
"author": "gthvmt",
"author_id": 20013195,
"author_profile": "https://Stackoverflow.com/users/20013195",
"pm_score": 0,
"selected": false,
"text": "REMOVE var isUninstall = session[\"REMOVE\"] == \"ALL\";\n"
},
{
"answer_id": 74491604,
"author": "Bob Arnson",
"author_id": 104149,
"author_profile": "https://Stackoverflow.com/users/104149",
"pm_score": 2,
"selected": true,
"text": "Condition Custom"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20013195/"
] |
74,489,089
|
<p>I am working in Reactjs and using Nextjs,I am trying to add class(active) on
"first id"/array first record (fetching from db) but right now working with statically "where id=1" instead of First record,How can i do this ? in other words i want to add active on "first record(in array)" not "where id=1",
I tried with following code</p>
<pre><code>{this.state.trending.map((post, index) => {
return (
<>
<div className={`carousel-item ${post.id == 1 ? 'active' : ''}`}>
)
})}
</code></pre>
|
[
{
"answer_id": 74489305,
"author": "gthvmt",
"author_id": 20013195,
"author_profile": "https://Stackoverflow.com/users/20013195",
"pm_score": 0,
"selected": false,
"text": "REMOVE var isUninstall = session[\"REMOVE\"] == \"ALL\";\n"
},
{
"answer_id": 74491604,
"author": "Bob Arnson",
"author_id": 104149,
"author_profile": "https://Stackoverflow.com/users/104149",
"pm_score": 2,
"selected": true,
"text": "Condition Custom"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5308126/"
] |
74,489,132
|
<p>I have strings like:</p>
<pre><code>string <- "1, 2, \"something, else\""
</code></pre>
<p>I want to use <code>tidyr::separate_rows()</code> with <code>sep==","</code>, but the comma inside the quoted portion of the string is tripping me up. I'd like to remove the comma between something and else (but only this comma).</p>
<p>Here's a more complex toy example:</p>
<pre><code>string <- c("1, 2, \"something, else\"", "3, 5, \"more, more, more\"", "6, \"commas, are fun\", \"no, they are not\"")
string
#[1] "1, 2, \"something, else\""
#[2] "3, 5, \"more, more, more\""
#[3] "6, \"commas, are fun\", \"no, they are not\""
</code></pre>
<p>I want to get rid of all commas inside the embedded quotations. Desired output:</p>
<pre><code>[1] "1, 2, \"something else\""
[2] "3, 5, \"more more more\""
[3] "6, \"commas are fun\", \"no they are not\""
</code></pre>
|
[
{
"answer_id": 74489796,
"author": "Paul Stafford Allen",
"author_id": 16730940,
"author_profile": "https://Stackoverflow.com/users/16730940",
"pm_score": 2,
"selected": false,
"text": "stringr::str_replace_all(string,\"(?<=\\\\\\\".{1,15})(,)(?=.+?\\\\\\\")\",\"\")\n (?<= ) \\\\\\\" \\ \" .{1,15} (,) (?= ) .+? \\\\\\\" \\ \" .+?"
},
{
"answer_id": 74489920,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 4,
"selected": true,
"text": "library(stringr)\n\nrmcom <- function(x) gsub(\",\", \"\", x)\n\nstr_replace_all(string, \"(\\\"[[:alnum:]]+,[ [:alnum:],]*\\\")\", rmcom)\n[1] \"1, 2, \\\"something else\\\"\"\n[2] \"3, 5, \\\"more more more\\\"\"\n[3] \"6, \\\"commas are fun\\\", \\\"no they are not\\\"\"\n"
},
{
"answer_id": 74490208,
"author": "harre",
"author_id": 4786466,
"author_profile": "https://Stackoverflow.com/users/4786466",
"pm_score": 2,
"selected": false,
"text": "separate_rows library(tidyr)\n\ndf |>\n separate_rows(stringcol, sep = '(?!\\\\B\"[^\\\"]*), (?![^\"]*\\\"\\\\B)')\n # A tibble: 9 × 1\n stringcol \n <chr> \n1 \"1\" \n2 \"2\" \n3 \"\\\"something, else\\\"\" \n4 \"3\" \n5 \"5\" \n6 \"\\\"more, more, more\\\"\"\n7 \"6\" \n8 \"\\\"commas, are fun\\\"\" \n9 \"\\\"no, they are not\\\"\"\n library(tibble)\n\ndf <- tibble(stringcol = string)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841405/"
] |
74,489,137
|
<p>I have a requirement for an object type to not duplicate keys across nested objects. For example, if <code>foo.bar</code> contains the key <code>hello</code> then <code>foo.baz</code> cannot contain that key. Is there any way to enforce this at the type level?</p>
<p>One simplified formulation might be something like the following:</p>
<pre class="lang-js prettyprint-override"><code>type NestedUniqueKeys<T extends Object> = any // <- what goes here?
interface Something {
one: string
two: string
three: string
four: string
}
const good: NestedUniqueKeys<Something> = {
foo: {
three: 'hi',
one: 'hi',
},
bar: {
two: 'hiya',
},
}
// @ts-expect-error
const bad: NestedUniqueKeys<Something> = {
foo: {
two: 'hi', // duplicated
one: 'hi',
},
bar: {
two: 'hiya', // duplicated
},
}
</code></pre>
<p>So a simpler step might be, how could <code>NestedUniqueKeys</code> be formulated for a single level of nesting?</p>
<p>Then, how to extend it to arbitrary nestings?</p>
<pre class="lang-js prettyprint-override"><code>const good: NestedUniqueKeys<Something> = {
foo: {
three: 'hi',
baz: {
one: 'oh',
bill: {
four: 'uh',
},
},
},
bar: {
two: 'hiya',
},
}
// @ts-expect-error
const bad: NestedUniqueKeys<Something> = {
foo: {
three: 'hi',
baz: {
one: 'oh',
bill: {
four: 'uh', // duplicated
},
},
},
bar: {
two: 'hiya',
foobar: {
four: 'hey', // duplicated
},
},
}
</code></pre>
<p>And in the final formulation, could it be made to infer the full set of keys so no type parameter needs to be passed in?</p>
<h3>Edit</h3>
<p>I tried an initial sketch of something approaching the solution, but this results in <em>all</em> nested keys being forbidden. I guess this is because <code>K</code> is inferred to be <code>string</code> when it's passed into the recursive <code>NestedUniqueKeys</code>? I'm not sure why...</p>
<pre class="lang-js prettyprint-override"><code>type NestedUniqueKeys<Keys extends string = never> = {
[K in string]: K extends Keys
? never
: string | NestedUniqueKeys<K|Keys>
}
</code></pre>
<p><a href="https://www.typescriptlang.org/play?ssl=5&ssc=2&pln=1&pc=1#code/C4TwDgpgBAchDOwIBMCqA7AlgRwK4QGkIR4AeIkqCADyXWXikQCdN0BzKAXinQgDcIzAHzcoAbwBQUKAG0CUNk2CsOAXQBcUBTToNtxeNJlQA-LwFDjMrSzacAPrARI0WPIUPkHFeMMkAvpKSAMYA9uiIUOxhYchacIgoGDj4vmJSMgBmsVqZJsAAFswQEFoA5IWY5QA01lARZVCV1XUyAW1QAEYAhsx59cAA7mEVVSA9tcYdgcEA9HNQAALA8AC0NJAhwBvMzGHMoRFRvfHOSW6pnpQ8+TmjEoMjY631jS9T7Z29-Y8mUMMHi0JrUoAsoABrYhQAAGgJhikYJUgPVcUB6IX28EY8FwXTWYS6ACsINsjF9AkA" rel="nofollow noreferrer">Playground</a></p>
<h3>Edit 2</h3>
<p><a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAchDOwIBMCqA7AlgRwK4QGkIR4AeIkqCADyXWXikQCdN0BzKAXinQgDcIzAHzcAUFCgBvKAG0CUNk2CsOAXQBcUBTToNtxRgH5eAoVC0s2nAL5VaEeozYAzcwBUAFpngAZMwA2ElAmANbEAPYuUF4+-oIB9nqMVhzBJrF+gVAAZNLBkrIwiujKquyasEmO+hTGpoLMFrAISGhYeISGpOEgUTHeWQkAPnXCwTbBWnyNUw1CYmIAxhHoiFDsERHIWnCIKBg4+HXc+ZIuW1pSBVDAnswQEFoA5N7PADQ3q09Qr5gfE0+kgARgBDZhXG7AADuERe3hAoIBkhsn0mYgA9BioAABYDwAC0NEgS2AROYzAizGWq3WYJ2LX27SOXUoPGu50uZ0kt1h8P+QJ5335yKgqOCYIh3MkMLhvwRSPeUCxUF6UAABrL1YpGA9IKC2lBQUtKfAUrhgQSIsCAFYQUnwQFiGxAA" rel="nofollow noreferrer">Another attempt</a>, I'm not sure why this isn't allowing any keys in the nested objects...</p>
<pre class="lang-js prettyprint-override"><code>type NestedUniqueKeys<Keys extends string = never> =
{ [K in string]: K extends Keys ? never : string } extends infer ThisLevel
? keyof ThisLevel extends string
? ThisLevel & {
[N in string]: N extends Keys ? never : NestedUniqueKeys<keyof ThisLevel|Keys>
}
: never
: never
</code></pre>
|
[
{
"answer_id": 74489796,
"author": "Paul Stafford Allen",
"author_id": 16730940,
"author_profile": "https://Stackoverflow.com/users/16730940",
"pm_score": 2,
"selected": false,
"text": "stringr::str_replace_all(string,\"(?<=\\\\\\\".{1,15})(,)(?=.+?\\\\\\\")\",\"\")\n (?<= ) \\\\\\\" \\ \" .{1,15} (,) (?= ) .+? \\\\\\\" \\ \" .+?"
},
{
"answer_id": 74489920,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 4,
"selected": true,
"text": "library(stringr)\n\nrmcom <- function(x) gsub(\",\", \"\", x)\n\nstr_replace_all(string, \"(\\\"[[:alnum:]]+,[ [:alnum:],]*\\\")\", rmcom)\n[1] \"1, 2, \\\"something else\\\"\"\n[2] \"3, 5, \\\"more more more\\\"\"\n[3] \"6, \\\"commas are fun\\\", \\\"no they are not\\\"\"\n"
},
{
"answer_id": 74490208,
"author": "harre",
"author_id": 4786466,
"author_profile": "https://Stackoverflow.com/users/4786466",
"pm_score": 2,
"selected": false,
"text": "separate_rows library(tidyr)\n\ndf |>\n separate_rows(stringcol, sep = '(?!\\\\B\"[^\\\"]*), (?![^\"]*\\\"\\\\B)')\n # A tibble: 9 × 1\n stringcol \n <chr> \n1 \"1\" \n2 \"2\" \n3 \"\\\"something, else\\\"\" \n4 \"3\" \n5 \"5\" \n6 \"\\\"more, more, more\\\"\"\n7 \"6\" \n8 \"\\\"commas, are fun\\\"\" \n9 \"\\\"no, they are not\\\"\"\n library(tibble)\n\ndf <- tibble(stringcol = string)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9241395/"
] |
74,489,158
|
<p>What is the issue with <code>str</code> below on line <code>15</code>? I would have imagined the Typescript compiler can see that <code>str</code> will always be <code>'foo'</code> or <code>'bar'</code></p>
<pre class="lang-js prettyprint-override"><code>import { useEffect } from 'react'
type Type = {
name: 'foo' | 'bar'
}
const Demo = () => {
const update = ({ name }: Type) => console.log('logging: ', name)
useEffect(() => {
const arr = ['foo', 'bar']
arr.forEach((str) => {
update({
name: str,
})
})
}, [])
return null
}
export default Demo
</code></pre>
<p>But the Typescript compiler says...</p>
<pre><code>(property) name: "foo" | "bar"
Type 'string' is not assignable to type '"foo" | "bar"'.ts(2322)
file.tsx(4, 3): The expected type comes from property 'name' which is declared here on type 'Type'
</code></pre>
|
[
{
"answer_id": 74489227,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 0,
"selected": false,
"text": "arr string[] const arr: Type['name'][] = ['foo', 'bar']\n"
},
{
"answer_id": 74489250,
"author": "Tushar Shahi",
"author_id": 10140124,
"author_profile": "https://Stackoverflow.com/users/10140124",
"pm_score": 2,
"selected": false,
"text": "const arr = ['foo', 'bar'] string[] const arr : ['foo','bar']= ['foo', 'bar'];\n const arr = ['foo', 'bar'] as const;\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2102042/"
] |
74,489,160
|
<p>I'm trying in Python to "clean up" a string and remove some characters that were added like :</p>
<pre><code>"1. bla bla" => i want "bla bla"
"#. bla bla" => same
"3) bla bla" => same
"I. bla bla" => same
</code></pre>
<p>I tried to use (\W)(\w.*) but doesn't work.</p>
<p>Thanks !</p>
|
[
{
"answer_id": 74489220,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 0,
"selected": false,
"text": "(\\\")[^ ]* ([^\\\"]*\\\")\n"
},
{
"answer_id": 74489233,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "^.[.)]\\s+(.*)\n import re\n\ntext = \"\"\"\\\n1. bla bla\n#. bla bla\n3) bla bla\nI. bla bla\"\"\"\n\npat = re.compile(r\"^.[.)]\\s+(.*)\", flags=re.M)\n\nfor cleaned in pat.findall(text):\n print(cleaned)\n bla bla\nbla bla\nbla bla\nbla bla\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4078511/"
] |
74,489,186
|
<p>Hell All,</p>
<p>I have been trying to print tabular data from two dimensional list
numerical are right aligned, strings are left aligned and width of a column is dynamically decided based on max string length in each column</p>
<p>Example-A:</p>
<pre><code>table = [['Name', 'Marks', 'Division', 'ID'], ['Raj', 7, 'A', 21], ['Shivam', 9, 'A', 52], ['Shreeya', 8, 'C', 27], ['Kartik', 5, 'B', 38]]
Name Marks Division ID
---- ----- -------- --
Raj 7 A 21
Shivam 9 A 52
Shreeya 8 C 27
Kartik 5 B 38
</code></pre>
<p>Example-B:</p>
<pre><code>table = [['Name', 'Marks', 'Div', 'Role Number'], ['Raj', 7, 'A', 21], ['Shivam', 9, 'A', 52], ['Shreeya', 8, 'C', 27], ['Kartik', 5, 'B', 38]]
Name Marks Div Role Number
---- ----- --- -----------
Raj 7 A 21
Shivam 9 A 52
Shreeya 8 C 27
Kartik 5 B 38
</code></pre>
<p>I could get up to determining max length of each column, but not sure how to print each row with different alignment width and that to numerical are right aligned and strings are left aligned</p>
<pre><code>rlen = []
for row in table:
clen = []
for col in row:
clen.append(len(str(col)))
rlen.append(clen)
width = [max(idx) for idx in zip(*rlen)]
print(width) #[7, 5, 8, 2]
</code></pre>
<p>Can someone guide please, as number of columns in input data may vary.</p>
|
[
{
"answer_id": 74489554,
"author": "Alex",
"author_id": 2595183,
"author_profile": "https://Stackoverflow.com/users/2595183",
"pm_score": 0,
"selected": false,
"text": "f-string for i in table:\n print(f'{i[0]:<10} {i[1]:>10} {i[2]:<10} {i[3]:>10}')\n Name Marks Div Role Number\nRaj 7 A 21\nShivam 9 A 52\nShreeya 8 C 27\nKartik 5 B 38\n"
},
{
"answer_id": 74490589,
"author": "Timus",
"author_id": 14311263,
"author_profile": "https://Stackoverflow.com/users/14311263",
"pm_score": 2,
"selected": true,
"text": "cols = []\nfor col in zip(*table):\n just = str.ljust if isinstance(col[1], str) else str.rjust\n strings = [str(item) for item in col]\n width = max(map(len, strings))\n cols.append(\n [strings[0].ljust(width), (len(strings[0]) * \"-\").ljust(width)]\n + [just(string, width) for string in strings[1:]]\n )\n\nprint(\"\\n\".join(\" \".join(line) for line in zip(*cols)))\n table = [['Name', 'Marks', 'Div', 'Role Number'], ['Raj', 7, 'A', 21], ['Shivam', 9, 'A', 52], ['Shreeya', 8, 'C', 27], ['Kartik', 5, 'B', 38]]\n Name Marks Div Role Number\n---- ----- --- -----------\nRaj 7 A 21\nShivam 9 A 52\nShreeya 8 C 27\nKartik 5 B 38\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4306541/"
] |
74,489,190
|
<p>I am trying to create a table for bookings and want there to be a check constraint where the customer can only insert the D.O.B from a certain year to another certain year but keep getting the same error message</p>
<p>Any help would be very appreciated</p>
<p>`</p>
<pre><code>create table guest
( Guest_ID varchar2(8) primary key,
Family_Name varchar2(20) not null,
Given_Name varchar2(20) not null,
Date_of_Birth date check (Date_of_Birth between date '01/01/1904' and
date '01/01/2004' ) not null,
Address varchar2(80) not null
);
</code></pre>
<p>`</p>
|
[
{
"answer_id": 74489481,
"author": "Epitay",
"author_id": 20500640,
"author_profile": "https://Stackoverflow.com/users/20500640",
"pm_score": 0,
"selected": false,
"text": "create table guest\n(Guest_ID varchar2(8) primary key, \n Family_Name varchar2(20) not null,\n Given_Name varchar2(20) not null,\n Date_of_Birth date check (Date_of_Birth between date '1904- \n 01- 01' and date '2004-01-01' ) not null,\n Address varchar2(80) not null\n ); \n\ninsert into guest values ('t','t','t','18-NOV-03','t')\n"
},
{
"answer_id": 74489514,
"author": "Griffin",
"author_id": 18280576,
"author_profile": "https://Stackoverflow.com/users/18280576",
"pm_score": 2,
"selected": true,
"text": "create table guest\n( Guest_ID varchar2(8) primary key, \n Family_Name varchar2(20) not null,\n Given_Name varchar2(20) not null,\n Date_of_Birth date check (Date_of_Birth between to_date('01/01/1904','DD/MM/YYYY') and \n to_date('01/01/2004','DD/MM/YYYY')) not null,\n Address varchar2(80) not null\n); \n"
},
{
"answer_id": 74489578,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 0,
"selected": false,
"text": "EXTRACT ...CHECK (EXTRACT(YEAR FROM Date_of_Birth) BETWEEN 1904 and 2003 )...\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17810001/"
] |
74,489,212
|
<p>So I have two lists I want to compare, listA and listB. If an item from listA appears in listB, I want to remove it from listB. I can do this with:</p>
<pre><code>listA = ["config", "\n", "config checkpoint"]
listB = ["config exclusive", "config checkpoint test", "config", "config", "config", "\n", "hello"]
listB = [line for line in listB if not any(line in item for item in listA)]
</code></pre>
<p>But where things now become more complex, is that I have some lines I want to remove only if the list item matches exactly (as it currently does), but also lines that I want to remove if the item from listB contains the item from listA, i.e. a partial match.</p>
<p>I'm not sure whether it can be done succinctly within the same function. I've explored using .startswith, rawstrings to add ^ and $ on the end of the complete lines, importing re.match (I couldn't iterate within the given code).</p>
<p>I think it might just be a beautiful dream, but can anyone think of an elegant way of doing this within the same pass?</p>
|
[
{
"answer_id": 74489614,
"author": "Ingwersen_erik",
"author_id": 17587002,
"author_profile": "https://Stackoverflow.com/users/17587002",
"pm_score": 0,
"selected": false,
"text": "difflib.get_close_matches \nimport difflib\n\nlistA = [\"config\", \"\\n\", \"config checkpoint\"]\nlistB = [\"config exclusive\", \"config checkpoint test\", \"config\", \"config\", \"config\", \"\\n\", \"hello\"]\n\nnew_listB = [line for line in listB if len(difflib.get_close_matches(line, listA, n=len(listA), cutoff=0.4)) == 0]\nprint(new_listB)\n# Prints:\n#\n# ['hello']\n difflib.get_close_matches cutoff cutoff listA line \ndifflib.get_close_matches('John', ['John', 'Joe', 'Jane', 'Janet'], cutoff=0.2, n=100)\n# Returns:\n#\n# ['John', 'Joe', 'Jane', 'Janet']\n\ndifflib.get_close_matches('John', ['John', 'Joe', 'Jane', 'Janet'], cutoff=0.6, n=100)\n# Returns:\n#\n# ['John']\n\n"
},
{
"answer_id": 74489667,
"author": "Dani Mesejo",
"author_id": 4001592,
"author_profile": "https://Stackoverflow.com/users/4001592",
"pm_score": 2,
"selected": true,
"text": "listA import re\n\nlistA = [\"^config$\", \"^\\n$\", \"^config checkpoint\"]\nlistB = [\"config exclusive\", \"config checkpoint test\", \"config\", \"config\", \"config\", \"\\n\", \"hello\"]\n\nlistB = [line for line in listB if not any(re.match(item, line) for item in listA)]\nprint(listB)\n ['config exclusive', 'hello']\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198974/"
] |
74,489,215
|
<p>I need a div where a background image will be set but there should be a button on bottom of image (content of same div).</p>
<p>When this button will be click then background image should be rotate <strong>not Button</strong>.</p>
<p><strong>Is this possible using JavaScript Only?</strong></p>
<p>this is code sample</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>function rotate() {
document.getElementById("img_container").style.transform = "rotate(45deg)";
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
position: relative;
height: 400px;
max-width: 400px;
background: url("https://www.w3schools.com/howto/img_snow.jpg");
}
.container .btn {
position: absolute;
top: 90%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
background-color: #555;
color: white;
font-size: 16px;
padding: 12px 24px;
border: none;
cursor: pointer;
border-radius: 5px;
text-align: center;
}
.container .btn:hover {
background-color: black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container" id="img_container">
<button class="btn" onClick="rotate()">Button</button>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74489360,
"author": "JohnySilver1423",
"author_id": 17830387,
"author_profile": "https://Stackoverflow.com/users/17830387",
"pm_score": 3,
"selected": true,
"text": "function rotate() {\n document.getElementById(\"img_container\").style.transform = \"rotate(45deg)\";\n} .container {\n position: relative;\n height: 400px;\n max-width: 400px;\n \n}\n\n#img_container {\n background: url(\"https://www.w3schools.com/howto/img_snow.jpg\");\n width: 100%;\n height:100%;\n}\n\n.container .btn {\n position: absolute;\n top: 90%;\n left: 50%;\n transform: translate(-50%, -50%);\n -ms-transform: translate(-50%, -50%);\n background-color: #555;\n color: white;\n font-size: 16px;\n padding: 12px 24px;\n border: none;\n cursor: pointer;\n border-radius: 5px;\n text-align: center;\n}\n\n.container .btn:hover {\n background-color: black;\n} \n<div class=\"container\">\n <div id=\"img_container\"></div>\n <button class=\"btn\" onClick=\"rotate()\">Button</button>\n</div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10662727/"
] |
74,489,219
|
<p>When setting <code>innerHTML = '\r\n'</code>, it seems like browsers may end up writing <code>'\n'</code>.<br />
This introduces a gap between the actual plain text content of the element and what I have been keeping track of.</p>
<ul>
<li>Is this a rather isolated problem or are there many more potential changes I should be aware of?</li>
<li>How to ensure that the content of the text nodes matches exactly what I'm trying to write?</li>
</ul>
<p>I guess it's possible just not to use innerHTML, build the nodes and the text nodes and insert them, but it's much less convenient.</p>
|
[
{
"answer_id": 74489360,
"author": "JohnySilver1423",
"author_id": 17830387,
"author_profile": "https://Stackoverflow.com/users/17830387",
"pm_score": 3,
"selected": true,
"text": "function rotate() {\n document.getElementById(\"img_container\").style.transform = \"rotate(45deg)\";\n} .container {\n position: relative;\n height: 400px;\n max-width: 400px;\n \n}\n\n#img_container {\n background: url(\"https://www.w3schools.com/howto/img_snow.jpg\");\n width: 100%;\n height:100%;\n}\n\n.container .btn {\n position: absolute;\n top: 90%;\n left: 50%;\n transform: translate(-50%, -50%);\n -ms-transform: translate(-50%, -50%);\n background-color: #555;\n color: white;\n font-size: 16px;\n padding: 12px 24px;\n border: none;\n cursor: pointer;\n border-radius: 5px;\n text-align: center;\n}\n\n.container .btn:hover {\n background-color: black;\n} \n<div class=\"container\">\n <div id=\"img_container\"></div>\n <button class=\"btn\" onClick=\"rotate()\">Button</button>\n</div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19965362/"
] |
74,489,245
|
<p>So, I'm trying to create a zig-zag edge on an element with an inner bevel on the edges, <a href="https://i.stack.imgur.com/YNAxP.png" rel="nofollow noreferrer">as in this image here.</a>
currently i am managing it by using a border image, but i'd like to know if it's possible with pure css, because the person i am making this site for wants to be able to easily change the color of the element in question, and having a border image makes it not so easy.</p>
<p>i found this tool to create a zig-zag edge using masks (<a href="https://css-generators.com/custom-borders/" rel="nofollow noreferrer">https://css-generators.com/custom-borders/</a>) and that works great, but because it's a mask, i cant add any inset box-shadows to it, which is how i would normally do a bevel. i tried wrapping the element in a parent div and applying a drop-shadow filter to the parent, but unfortunately it seems that the drop shadow filter doesnt allow for inset shadows the way box shadow does.</p>
<p>is there any way to achieve this with pure css, or should i stick to the border-image, and just teach them how to change the color of the png?</p>
|
[
{
"answer_id": 74489360,
"author": "JohnySilver1423",
"author_id": 17830387,
"author_profile": "https://Stackoverflow.com/users/17830387",
"pm_score": 3,
"selected": true,
"text": "function rotate() {\n document.getElementById(\"img_container\").style.transform = \"rotate(45deg)\";\n} .container {\n position: relative;\n height: 400px;\n max-width: 400px;\n \n}\n\n#img_container {\n background: url(\"https://www.w3schools.com/howto/img_snow.jpg\");\n width: 100%;\n height:100%;\n}\n\n.container .btn {\n position: absolute;\n top: 90%;\n left: 50%;\n transform: translate(-50%, -50%);\n -ms-transform: translate(-50%, -50%);\n background-color: #555;\n color: white;\n font-size: 16px;\n padding: 12px 24px;\n border: none;\n cursor: pointer;\n border-radius: 5px;\n text-align: center;\n}\n\n.container .btn:hover {\n background-color: black;\n} \n<div class=\"container\">\n <div id=\"img_container\"></div>\n <button class=\"btn\" onClick=\"rotate()\">Button</button>\n</div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20539077/"
] |
74,489,269
|
<p>Heello! My turtle is not moving and I don't really know why... May anyone help?</p>
<pre><code>import turtle
chocolate = turtle.Turtle()
def move_forward():
chocolate.forward(10)
screen = turtle.Screen()
screen.exitonclick()
screen.listen()
screen.onkey(fun=move_forward, key="space")
screen.mainloop()
</code></pre>
<p>I expect my turtle moving with 10 pace when I press "space".</p>
|
[
{
"answer_id": 74489360,
"author": "JohnySilver1423",
"author_id": 17830387,
"author_profile": "https://Stackoverflow.com/users/17830387",
"pm_score": 3,
"selected": true,
"text": "function rotate() {\n document.getElementById(\"img_container\").style.transform = \"rotate(45deg)\";\n} .container {\n position: relative;\n height: 400px;\n max-width: 400px;\n \n}\n\n#img_container {\n background: url(\"https://www.w3schools.com/howto/img_snow.jpg\");\n width: 100%;\n height:100%;\n}\n\n.container .btn {\n position: absolute;\n top: 90%;\n left: 50%;\n transform: translate(-50%, -50%);\n -ms-transform: translate(-50%, -50%);\n background-color: #555;\n color: white;\n font-size: 16px;\n padding: 12px 24px;\n border: none;\n cursor: pointer;\n border-radius: 5px;\n text-align: center;\n}\n\n.container .btn:hover {\n background-color: black;\n} \n<div class=\"container\">\n <div id=\"img_container\"></div>\n <button class=\"btn\" onClick=\"rotate()\">Button</button>\n</div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20017175/"
] |
74,489,299
|
<blockquote>
<p>I am unable to stop the Video Playback when the viewpager is scrolled.</p>
</blockquote>
<blockquote>
<p>This is my MainActivity's Viewpager scrollListener code :</p>
</blockquote>
<pre><code> viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
simpleExoPlayer1.stop(); //error is here
Log.e("onPageScrolled", "onPageScrolled");
}
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
Log.e("onPageSelected", "onPageSelected");
}
@Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
Log.e("onPageScrolStateChang", "onPageScrollStateChanged");
}
});
myAdapter = new VideoSliderAdapter(getApplicationContext(), videoPaths,
MainActivity2.this, this);
viewPager.setAdapter(myAdapter);
}
@Override
public void clicktoupdate(ImageView playPause, int position,
PlayerView playerView,
SimpleExoPlayer simpleExoPlayer1) {
// get data
Toast.makeText(this, "Playing..", Toast.LENGTH_SHORT).show();
Uri videoUri = Uri.parse(videoPaths.get(position));
playPause.setVisibility(View.GONE);
playerView.setVisibility(View.VISIBLE);
simpleExoPlayer1 = new SimpleExoPlayer.Builder(getApplicationContext())
.setSeekBackIncrementMs(5000)
.setSeekForwardIncrementMs(5000)
.build();
playerView.setPlayer(simpleExoPlayer1);
playerView.setKeepScreenOn(true);
simpleExoPlayer1.addListener(new Player.Listener() {
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == Player.STATE_BUFFERING) {
// progressBar.setVisibility(View.VISIBLE);
} else if (playbackState == Player.STATE_READY) {
// progressBar.setVisibility(View.GONE);
}
}
});
MediaItem mediaItem = MediaItem.fromUri(videoUri);
simpleExoPlayer1.setMediaItem(mediaItem);
simpleExoPlayer1.prepare();
simpleExoPlayer1.play();
}
</code></pre>
<blockquote>
<p>This is my Adapter's Viewholder code :</p>
</blockquote>
<pre><code> public class ViewHolder extends RecyclerView.ViewHolder {
PlayerView playerView;
ImageView thumbnailImage;
ImageView playPauseBtn;
ImageView bt_fullscreen, bt_lockscreen;
SimpleExoPlayer simpleExoPlayer;
ProgressBar progressBar;
LinearLayout sec_mid, sec_bottom;
public ViewHolder(@NonNull View view) {
super(view);
playerView = view.findViewById(R.id.statusSliderVideo);
thumbnailImage = view.findViewById(R.id.statusSliderThumbnailImage);
playPauseBtn = view.findViewById(R.id.playPauseBtn);
progressBar = view.findViewById(R.id.progress_bar);
bt_fullscreen = view.findViewById(R.id.bt_fullscreen);
bt_lockscreen = view.findViewById(R.id.exo_lock);
sec_mid = view.findViewById(R.id.sec_controlvid1);
sec_bottom = view.findViewById(R.id.sec_controlvid2);
playPauseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
onitemclicklisteners.clicktoupdate(playPauseBtn, position, playerView, simpleExoPlayer);
}
}
});
}
}
public interface Onitemclicklisteners {
void clicktoupdate(ImageView playPause, int position, PlayerView playerView, SimpleExoPlayer simpleExoPlayer);
}
</code></pre>
<blockquote>
<p>As soon as the App starts, this is the Error I am getting :</p>
</blockquote>
<pre><code>java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.exoplayer2.SimpleExoPlayer.stop()' on a null object reference
</code></pre>
<blockquote>
<p>I think I have to make the <code>simpleExoPlayer1 global</code> in MainActivity , please help me fix this issue. Thanks in advance</p>
</blockquote>
|
[
{
"answer_id": 74489360,
"author": "JohnySilver1423",
"author_id": 17830387,
"author_profile": "https://Stackoverflow.com/users/17830387",
"pm_score": 3,
"selected": true,
"text": "function rotate() {\n document.getElementById(\"img_container\").style.transform = \"rotate(45deg)\";\n} .container {\n position: relative;\n height: 400px;\n max-width: 400px;\n \n}\n\n#img_container {\n background: url(\"https://www.w3schools.com/howto/img_snow.jpg\");\n width: 100%;\n height:100%;\n}\n\n.container .btn {\n position: absolute;\n top: 90%;\n left: 50%;\n transform: translate(-50%, -50%);\n -ms-transform: translate(-50%, -50%);\n background-color: #555;\n color: white;\n font-size: 16px;\n padding: 12px 24px;\n border: none;\n cursor: pointer;\n border-radius: 5px;\n text-align: center;\n}\n\n.container .btn:hover {\n background-color: black;\n} \n<div class=\"container\">\n <div id=\"img_container\"></div>\n <button class=\"btn\" onClick=\"rotate()\">Button</button>\n</div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10805570/"
] |
74,489,310
|
<p>I am new at C# entity framework. I am trying to build an API, but stuck in retrieving data from relational table.
I have a Game table in MS SQL database, where GameId is the primary key. I have another table called GameCharacter, where GameCharacterId is the primary key.
In Game table GameCharacterId is foreign key. How i can get all GameCharacters on Get Games.</p>
<pre><code> public class Game
{
public Game()
{
GameCharacters = new List<GameCharacter>();
}
public int GameID { get; set; }
public string Title { get; set; }
public string Platform { get; set; }
public string imgpath { get; set; }
public int ReleaseYear { get; set; }
public virtual ICollection< GameCharacter> GameCharacters { get; set; }
}
</code></pre>
<pre><code> public class GameCharacter
{
[Key]
public Guid CharID { get; set; }
public string CharName { get; set; }
public string CharGame { get; set; }
public string charimgpath { get; set; }
[ForeignKey("Game")]
public int GameID { get; set; }
public virtual Game Game { get; set; }
}
</code></pre>
<pre><code> public class GameController : Controller
{
private readonly GameApiDbconnect dbContext;
public GameController(GameApiDbconnect dbContext)
{
this.dbContext = dbContext;
}
[HttpGet]
public async Task<IActionResult> GetGames()
{
return Ok(await dbContext.Games.ToListAsync());
}
[HttpGet]
[Route("{GameID=guid}")]
public async Task<IActionResult> GetGame([FromRoute] Guid GameID)
{
var game = await dbContext.Games.FindAsync(GameID);
if (game == null)
{
return NotFound();
}
return Ok(game);
}
</code></pre>
<p><strong>OutPut</strong>
Response body</p>
<p>{
"gameID": 1,
"title": "string",
"platform": "string",
"imgpath": "string",
"releaseYear": 0,
"gameCharacters": []
}</p>
|
[
{
"answer_id": 74491614,
"author": "Basit",
"author_id": 15013178,
"author_profile": "https://Stackoverflow.com/users/15013178",
"pm_score": -1,
"selected": true,
"text": " [HttpGet]\n public async Task<IActionResult> GetGames()\n {\n return Ok(from g in dbContext.Games\n join c in dbContext.GameCharacters on g.GameID \n equals c.GameID into Gcharacters\n select new\n {\n GameID = g.GameID,\n Title = g.Title,\n Platform = g.Platform,\n imgpath = g.imgpath,\n ReleaseYear = g.ReleaseYear,\n\n GameCharacters = Gcharacters.Select(gc => new { \n CharID = gc.CharID, CharName = gc.CharName, CharGame = \n gc.CharGame, charimgpath = gc.charimgpath }) }\n ) ;\n }\n \n"
},
{
"answer_id": 74502489,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 0,
"selected": false,
"text": " [HttpGet]\n public async Task<IActionResult> GetGames()\n {\n var games = await dbContext.Games\n .Include( g=> g.GameCharacters)\n .ToListAsync();\n return Ok(games);\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15013178/"
] |
74,489,313
|
<p>I am new to learning <code>React</code>.
I wanted to make it: when entering data into the <code>input</code>, this data automatically appear in <code>H1</code>in another component.</p>
<p><strong>Screen.js</strong></p>
<pre><code> class Screen extends React.Component {
render() {
return (
<div className="screen">
<h1>Text from input</h1>
</div>
);
}
}
export default Screen;
</code></pre>
<p><strong>Inputs.js</strong></p>
<pre><code>class Inputs extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('Value: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Enter" />
</form>
);
}
}
export default Inputs;
</code></pre>
<p><strong>App.js</strong></p>
<pre><code>export default function App() {
return (
<div>
<h1>Hello StackBlitz!</h1>
<p>Start editing to see some magic happen :)</p>
<Inputs />
<Screen />
</div>
);
}
</code></pre>
|
[
{
"answer_id": 74491614,
"author": "Basit",
"author_id": 15013178,
"author_profile": "https://Stackoverflow.com/users/15013178",
"pm_score": -1,
"selected": true,
"text": " [HttpGet]\n public async Task<IActionResult> GetGames()\n {\n return Ok(from g in dbContext.Games\n join c in dbContext.GameCharacters on g.GameID \n equals c.GameID into Gcharacters\n select new\n {\n GameID = g.GameID,\n Title = g.Title,\n Platform = g.Platform,\n imgpath = g.imgpath,\n ReleaseYear = g.ReleaseYear,\n\n GameCharacters = Gcharacters.Select(gc => new { \n CharID = gc.CharID, CharName = gc.CharName, CharGame = \n gc.CharGame, charimgpath = gc.charimgpath }) }\n ) ;\n }\n \n"
},
{
"answer_id": 74502489,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 0,
"selected": false,
"text": " [HttpGet]\n public async Task<IActionResult> GetGames()\n {\n var games = await dbContext.Games\n .Include( g=> g.GameCharacters)\n .ToListAsync();\n return Ok(games);\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19053788/"
] |
74,489,352
|
<p>There are a way how to set TTL for existing raws in table without re-inserting all data?</p>
<p>All documentation talks about examples when inserting record using custom/default TTL.
<a href="https://docs.aws.amazon.com/keyspaces/latest/devguide/TTL-how-to.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/keyspaces/latest/devguide/TTL-how-to.html</a></p>
<pre><code>ALTER TABLE "my_keyspace"."my_table" WITH default_time_to_live = 31536000 ;
</code></pre>
<p>Sets default TTL for new records.</p>
|
[
{
"answer_id": 74491402,
"author": "Paul",
"author_id": 10914049,
"author_profile": "https://Stackoverflow.com/users/10914049",
"pm_score": 2,
"selected": false,
"text": "INSERT INTO keyspace.table (col1, col2, col3) VALUES ('coltext1', 'coltext2', 'coltext3') USING TTL 864000;\n"
},
{
"answer_id": 74568994,
"author": "Erick Ramirez",
"author_id": 4269535,
"author_profile": "https://Stackoverflow.com/users/4269535",
"pm_score": 1,
"selected": false,
"text": "WRITETIME() WRITETIME() Murmur3Partitioner RandomPartitioner com.amazonaws.cassandra.DefaultPartitioner"
},
{
"answer_id": 74608278,
"author": "MikeJPR",
"author_id": 3120345,
"author_profile": "https://Stackoverflow.com/users/3120345",
"pm_score": 0,
"selected": false,
"text": "val myTable = sparkSession.read\n .format(\"org.apache.spark.sql.cassandra\")\n .options(Map( \"table\" -> tableName, \"keyspace\" -> keyspaceName))\n .load()\n\n //Try first without shuffling step. If you see WriteThottleEvents then reading by partition and writing by partition maybe causing hotkeys. Can happen with wider partitions. \n //Randomize data will avoid WriteThottleEvents\n //The following command will randomize the data.\n \n //val shuffledData = myTable.orderBy(rand())\n\n myTable.write.format(\"org.apache.spark.sql.cassandra\").mode(\"append\").option(\"keyspace\", keyspaceName).option(\"table\", tableName).option(\"ttl\",999999).save()\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4512086/"
] |
74,489,355
|
<p>The code is shown here:</p>
<pre><code>class Basket{
public:
/*other contents*/
private:
// function to compare shared_ptrs needed by the multiset member
static bool compare(const std::shared_ptr<Quote> &lhs,
const std::shared_ptr<Quote> &rhs)
{ return lhs->isbn() < rhs->isbn(); }
// multiset to hold multiple quotes, ordered by the compare member
std::multiset<std::shared_ptr<Quote>, decltype(compare)*>
items{compare};
};
</code></pre>
<p>We initialize our multiset through an in-class initializer. Commonly we put a same class object in the curly bracket. <strong>Why a function can be put here?</strong> I can't understand;</p>
<p>It's explained in the book C++ primer like it: The multiset will use a function with the same type as our compare member to order the elements. The multiset member is named items, and we’re initializing items to use our compare function.</p>
<p>I can understand the logic, but what is the syntax used here?</p>
|
[
{
"answer_id": 74491402,
"author": "Paul",
"author_id": 10914049,
"author_profile": "https://Stackoverflow.com/users/10914049",
"pm_score": 2,
"selected": false,
"text": "INSERT INTO keyspace.table (col1, col2, col3) VALUES ('coltext1', 'coltext2', 'coltext3') USING TTL 864000;\n"
},
{
"answer_id": 74568994,
"author": "Erick Ramirez",
"author_id": 4269535,
"author_profile": "https://Stackoverflow.com/users/4269535",
"pm_score": 1,
"selected": false,
"text": "WRITETIME() WRITETIME() Murmur3Partitioner RandomPartitioner com.amazonaws.cassandra.DefaultPartitioner"
},
{
"answer_id": 74608278,
"author": "MikeJPR",
"author_id": 3120345,
"author_profile": "https://Stackoverflow.com/users/3120345",
"pm_score": 0,
"selected": false,
"text": "val myTable = sparkSession.read\n .format(\"org.apache.spark.sql.cassandra\")\n .options(Map( \"table\" -> tableName, \"keyspace\" -> keyspaceName))\n .load()\n\n //Try first without shuffling step. If you see WriteThottleEvents then reading by partition and writing by partition maybe causing hotkeys. Can happen with wider partitions. \n //Randomize data will avoid WriteThottleEvents\n //The following command will randomize the data.\n \n //val shuffledData = myTable.orderBy(rand())\n\n myTable.write.format(\"org.apache.spark.sql.cassandra\").mode(\"append\").option(\"keyspace\", keyspaceName).option(\"table\", tableName).option(\"ttl\",999999).save()\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20538902/"
] |
74,489,407
|
<p><a href="https://i.stack.imgur.com/YJ7tF.png" rel="nofollow noreferrer">error message screenshot</a>I'm quite new to Python and I need to create a nested loop for excel parsing. I have a spreadsheet with 4 columns <strong>ID, Model, Part Number, Part Description, Year</strong> and I need a parser to go through each line and to return in format:
Part Number, Toyota > Model > Year | Toyota > Model > Year etc...
so that part number is returned only once listing all of the multiple fitting models and years.
I was able to achieve the same through the code below but it is not switching to the second part Part Number</p>
<pre><code>import pandas as pd
import xlrd
workbook = pd.read_excel('Query1.xls')
workbook.head()
i = 0
l = int(len(workbook))
a = workbook['Part Number'].iloc[i]
while i < l:
b = 0
c = workbook['Part Number'].iloc[b]
print(a)
while c == a:
#print(c)
print(b, 'TOYOTA >', workbook['Model'].iloc[b], ' > ', workbook['Year'].iloc[b], ' | ', end = ' ')
b = b + 1
print()
i = i + b
</code></pre>
|
[
{
"answer_id": 74490185,
"author": "Stuart",
"author_id": 567595,
"author_profile": "https://Stackoverflow.com/users/567595",
"pm_score": 2,
"selected": true,
"text": "c part_number_group = None\nfor i in range(len(df)): # or `for i, row in df.iterrows():`\n part_number = df.loc[i, \"Part Number\"]\n if part_number != part_number_group:\n if part_number_group is not None:\n print()\n print(part_number)\n part_number_group = part_number\n print(i, 'TOYOTA >', df.loc[i, 'Model'], ' > ', df.loc[i, 'Year'], ' | ', end = ' ')\n groupby df[\"Model-Year\"] = df.index.astype(str) + \" TOYOTA > \" + df[\"Model\"] + \" > \" + df[\"Year\"].astype(str)\nfor part_number, group in df.groupby(\"Part Number\"):\n print(part_number)\n print(*group[\"Model-Year\"], sep=\" | \")\n \n"
},
{
"answer_id": 74490424,
"author": "Nyps",
"author_id": 7890561,
"author_profile": "https://Stackoverflow.com/users/7890561",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\nimport xlrd\nworkbook = pd.read_excel('Query1.xls')\n\nfor num in pd.unique(workbook[\"Part Number\"]):\n print('\\n', num)\n part_df = workbook.query(\"`Part Number` == @num\")\n for i in range(len(part_df)):\n print(i, 'TOYOTA >', part_df['Model'].iloc[i], ' > ', part_df['Year'].iloc[i], ' | ', end=' ')\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20539218/"
] |
74,489,410
|
<p>I was playing around with <code>sum</code> function and observed the following behaviour.</p>
<p><em>case 1:</em></p>
<pre><code>source = """
class A:
def __init__(self, a):
self.a = a
def __add__(self, other):
return self.a + other;
sum([*range(10000)], start=A(10))
"""
import timeit
print(timeit.timeit(stmt=source))
</code></pre>
<p>As you can see I am using an instance of custom class as <code>start</code> argument to the <code>sum</code> function. Benchmarking above code takes around <code>192.60747704200003</code> seconds in my system.</p>
<p><em>case 2:</em></p>
<pre><code>source = """
class A:
def __init__(self, a):
self.a = a
def __add__(self, other):
return self.a + other;
sum([*range(10000)], start=10). <- Here
"""
import timeit
print(timeit.timeit(stmt=source))
</code></pre>
<p>But if I remove the custom class instance and use <code>int</code> object directly it tooks only <code>111.48285191600007</code> seconds. I am curious to understand the reason for this speed difference?</p>
<p><strong>My system info:</strong></p>
<pre><code>>>> import platform
>>> platform.platform()
'macOS-12.5-arm64-arm-64bit'
>>> import sys
>>> sys.version
'3.11.0 (v3.11.0:deaf509e8f, Oct 24 2022, 14:43:23) [Clang 13.0.0 (clang-1300.0.29.30)]'
</code></pre>
|
[
{
"answer_id": 74490086,
"author": "payloc91",
"author_id": 8524301,
"author_profile": "https://Stackoverflow.com/users/8524301",
"pm_score": -1,
"selected": false,
"text": "import dis\n\ndef test_range():\n class A:\n def __init__(self, a):\n self.a = a\n\n def __add__(self, other):\n return self.a + other\n\n sum([*range(10000)], start=10)\n\ndis.dis(test_range)\n start=A(10) 2 LOAD_CONST 1 (<code object A at 0x7ff0bfa25c90, file \"/.../main.py\", line 5>)\n...\n26 LOAD_CONST 4 (10)\n28 LOAD_CONST 5 (('start',))\n30 CALL_FUNCTION_KW 2\n32 POP_TOP\n34 LOAD_CONST 0 (None)\n36 RETURN_VALUE\n 2 LOAD_CONST 1 (<code object A at 0x7ff0bfa25c90, file \"/.../main.py\", line 5>)\n...\n26 LOAD_FAST 0 (A) <--- here\n28 LOAD_CONST 4 (10)\n30 CALL_FUNCTION 1 <--- and here\n32 LOAD_CONST 5 (('start',))\n34 CALL_FUNCTION_KW 2\n36 POP_TOP\n38 LOAD_CONST 0 (None)\n40 RETURN_VALUE\n start=A(10) A"
},
{
"answer_id": 74494793,
"author": "Ahmed AEK",
"author_id": 15649230,
"author_profile": "https://Stackoverflow.com/users/15649230",
"pm_score": 4,
"selected": true,
"text": "start start __add__"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6699447/"
] |
74,489,411
|
<p>I am trying to use the Database Migration Service to migrate an existing database into CloudSQL.</p>
<p>When I start the migration, I receive the following error:</p>
<pre><code>finished setup replication with errors: [api_production]: error importing schema: failed to restore schema: stderr=pg_restore: while PROCESSING TOC: pg_restore: from TOC entry 3997; 0 0 DATABASE PROPERTIES api_production postgres pg_restore: error: could not execute query: ERROR: permission denied to set parameter "log_min_duration_statement" Command was: ALTER DATABASE api_production SET log_min_duration_statement TO '500ms'; pg_restore: warning: errors ignored on restore: 1 , stdout=
</code></pre>
<p>How can I continue the migration, ignoring the <code>SET PARAMETER</code> statement?</p>
|
[
{
"answer_id": 74658152,
"author": "Hayden Ball",
"author_id": 1322410,
"author_profile": "https://Stackoverflow.com/users/1322410",
"pm_score": 1,
"selected": true,
"text": "reset log_min_duration_statement;\nALTER DATABASE <database_name> RESET log_min_duration_statement;\nALTER DATABASE postgres RESET log_min_duration_statement;\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1322410/"
] |
74,489,447
|
<pre><code>Id condition2 score
A pass 0
A fail 0
B pass 0
B level_1 0
B fail 0
C fail 0
D fail 0
</code></pre>
<p>Expected Dataframe :</p>
<pre><code>Id condition2 score
A pass 1
A fail 1
B pass 1
B level_1 1
B fail 1
C fail 0
D fail 0
</code></pre>
<p>looking to tag score as 1 for each row of unique Id , if the condition 2 has either pass or level_1 in any of the row.</p>
<pre><code>df['score'] = df.groupby('Id')['condition2'].transform(lambda x: x.eq('pass').any().astype(int))
</code></pre>
<p>what modifications to be done on above code</p>
|
[
{
"answer_id": 74658152,
"author": "Hayden Ball",
"author_id": 1322410,
"author_profile": "https://Stackoverflow.com/users/1322410",
"pm_score": 1,
"selected": true,
"text": "reset log_min_duration_statement;\nALTER DATABASE <database_name> RESET log_min_duration_statement;\nALTER DATABASE postgres RESET log_min_duration_statement;\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19303365/"
] |
74,489,469
|
<p>I want select records that have GUID and not exists into parentGUID</p>
<p><a href="https://i.stack.imgur.com/pIuUm.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>i tried this code</p>
<pre><code>select code, GUID, ParentGUID
from ac00
where NOT EXISTS (select ParentGUID from ac00 where GUID <> ParentGUID)
order by Code asc
</code></pre>
|
[
{
"answer_id": 74489506,
"author": "Cetin Basoz",
"author_id": 894977,
"author_profile": "https://Stackoverflow.com/users/894977",
"pm_score": 3,
"selected": true,
"text": "select code,GUID,ParentGUID \nfrom ac00 t1 \nwhere NOT EXISTS (select * from ac00 t2 \n where t2.GUID = t1.ParentGUID) \norder by Code asc;\n"
},
{
"answer_id": 74489570,
"author": "MD Zand",
"author_id": 5118861,
"author_profile": "https://Stackoverflow.com/users/5118861",
"pm_score": -1,
"selected": false,
"text": "select ac1.Code,ac1.GUID,ac1.ParentGUID \nfrom ac00 ac1 LEFT OUTER JOIN dbo.ac00 ac2\nON ac2.Guid = ac1.ParentGuid\nWHERE ac2.Code IS NULL\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20539283/"
] |
74,489,476
|
<p>Do you know how to assign these in a loop so it's less exhaustive?</p>
<pre><code>number1 <- as.data.frame(do.call(cbind, my_list[1]))
number2 <- as.data.frame(do.call(cbind, my_list[2]))
number3 <- as.data.frame(do.call(cbind, my_list[3]))
number4 <- as.data.frame(do.call(cbind, my_list[4]))
number5 <- as.data.frame(do.call(cbind, my_list[5]))
</code></pre>
<p>I have tried:</p>
<pre><code>for (i in 1:5) {
(number(i) <- as.data.frame(do.call(cbind, my_list[(i)])))
}
</code></pre>
<p>which doesn't work.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 74489642,
"author": "Afshin",
"author_id": 6582929,
"author_profile": "https://Stackoverflow.com/users/6582929",
"pm_score": 1,
"selected": false,
"text": "assign() for (i in 1:5) {\n m <- data.frame(x=rnorm(10), y=rnorm(10))\n assign(paste0('number',i), m)\n}\nnumber1\nnumber2\nnumber3\nnumber4\nnumber5 \n"
},
{
"answer_id": 74489865,
"author": "jpsmith",
"author_id": 12109788,
"author_profile": "https://Stackoverflow.com/users/12109788",
"pm_score": 1,
"selected": true,
"text": "assign # Example list with 5 elements\nmy_list <- list(1:5, 1:5, 1:5, 1:5, 1:5)\n\nfor(xx in seq_along(my_list)){\n assign(paste0(\"number\", xx), as.data.frame(do.call(cbind, my_list[xx])))\n}\n number1 number2 number5"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20322342/"
] |
74,489,479
|
<ol>
<li><p>Radian to degree:
var Degrees = Radian * (180 / Math.PI)</p>
</li>
<li><p>Degree to transform
var bval=Math.sin(45*Math.PI / 180);</p>
</li>
<li><p>Transform to angle
var angle = Math.round(Math.asin(bval) * (180/Math.PI));</p>
</li>
<li><p>Degree to radian:
var Radians = Degree * Math.PI/180</p>
</li>
</ol>
<p>The above steps tried with the below code with values "-3.17934" & "-0.9998"</p>
<ol>
<li>"-3.17934" --> This value properly converted not closed to First Radian & Last radian</li>
<li>"-0.9998" --> This value properly converted & closed to First Radian & Last radian</li>
</ol>
<pre><code>`<script>
console.log("--------------------------------");
//var rad2="-3.17934";//-3.17934
var rad2="-0.9998";//-0.9998
console.log("First radian: "+rad2);
var rad2angle = rad2 * (180/Math.PI);
console.log("2 rad2angle: "+rad2angle);
var tt = Math.sin(rad2angle*Math.PI / 180);
console.log("3 To Transform: "+tt);
var t2angle = Math.round(Math.asin(tt) * (180/Math.PI));
console.log("2 t2angle: "+t2angle);
var angle2radian = t2angle * Math.PI/180;
console.log("Last radian: "+angle2radian);
</script>`
</code></pre>
<p>Thanks in Advance.</p>
<p>I tried with above code given in detail area.</p>
|
[
{
"answer_id": 74489642,
"author": "Afshin",
"author_id": 6582929,
"author_profile": "https://Stackoverflow.com/users/6582929",
"pm_score": 1,
"selected": false,
"text": "assign() for (i in 1:5) {\n m <- data.frame(x=rnorm(10), y=rnorm(10))\n assign(paste0('number',i), m)\n}\nnumber1\nnumber2\nnumber3\nnumber4\nnumber5 \n"
},
{
"answer_id": 74489865,
"author": "jpsmith",
"author_id": 12109788,
"author_profile": "https://Stackoverflow.com/users/12109788",
"pm_score": 1,
"selected": true,
"text": "assign # Example list with 5 elements\nmy_list <- list(1:5, 1:5, 1:5, 1:5, 1:5)\n\nfor(xx in seq_along(my_list)){\n assign(paste0(\"number\", xx), as.data.frame(do.call(cbind, my_list[xx])))\n}\n number1 number2 number5"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19851199/"
] |
74,489,519
|
<p>I'm trying to get something like this:</p>
<p><a href="https://i.stack.imgur.com/YID5im.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YID5im.png" alt="enter image description here" /></a></p>
<p>with this code</p>
<pre class="lang-py prettyprint-override"><code>x = np.arange(l, r, s)
y = np.arange(b, t, s)
X, Y = np.meshgrid(x, y)
Z = f(X,Y)
plt.axis('equal')
plt.pcolormesh(X, Y, Z)
plt.savefig("image.png",dpi=300)
</code></pre>
<p>But I get this:</p>
<p><a href="https://i.stack.imgur.com/kmiAGm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kmiAGm.png" alt="enter image description here" /></a></p>
<p>How could I remove the white regions?
I really appreciate any kind of help.</p>
|
[
{
"answer_id": 74489758,
"author": "Double_LA",
"author_id": 5801964,
"author_profile": "https://Stackoverflow.com/users/5801964",
"pm_score": -1,
"selected": false,
"text": "plt.margins(x=0)\n"
},
{
"answer_id": 74490131,
"author": "AlexWach",
"author_id": 14569281,
"author_profile": "https://Stackoverflow.com/users/14569281",
"pm_score": 2,
"selected": true,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\ndef f(x,y):\n return x + y\n\nx = np.arange(1, 10, .1)\ny = np.arange(1, 10, .1)\nX, Y = np.meshgrid(x, y)\nZ = f(X,Y)\n\n\nf, ax = plt.subplots(figsize=(4, 4))\nplt.pcolormesh(X, Y, Z)\nplt.show()\n plt.pcolormesh(X, Y, Z)\nplt.axis('scaled')\nplt.show()\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8173933/"
] |
74,489,537
|
<p>I don't know what have bellow error:
<code>TypeError: res.json is not a function</code></p>
<p>I readed express documentation, and don't see any wrong syntax or other errrors.</p>
<p>Code:</p>
<ul>
<li>index.js</li>
</ul>
<pre><code>import express from "express";
import postRoutes from "./routes/posts.js";
const app = express();
app.use(express.json());
app.use("/api/posts", postRoutes);
app.listen(8800, () => {
console.log("Server is running on port 8800");
});
</code></pre>
<ul>
<li>./routes/posts.js</li>
</ul>
<pre><code>import express from "express";
const router = express.Router();
router.get("/", (res, req) => {
res.json("This works!");
});
export default router;
</code></pre>
|
[
{
"answer_id": 74489576,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 1,
"selected": false,
"text": "json() res req router.get(\"/\", (req, res) => {\n res.json(\"This works!\");\n});\n"
},
{
"answer_id": 74489590,
"author": "Delano van londen",
"author_id": 19923550,
"author_profile": "https://Stackoverflow.com/users/19923550",
"pm_score": 1,
"selected": false,
"text": "router.get(\"/\", (res, req) => {\n res.json(\"This works!\");\n});\n \nrouter.get(\"/\", (req, res) => {\n res.json(\"This works!\");\n});\n\n"
},
{
"answer_id": 74489602,
"author": "Nuro007",
"author_id": 19669556,
"author_profile": "https://Stackoverflow.com/users/19669556",
"pm_score": 1,
"selected": false,
"text": "(req, res) (res, req) router.get(\"/\", (req, res) => {\n res.json(\"This works!\");\n});\n"
},
{
"answer_id": 74489727,
"author": "Hadi Mir",
"author_id": 9920947,
"author_profile": "https://Stackoverflow.com/users/9920947",
"pm_score": 0,
"selected": false,
"text": "Handler request response req res router.get(\"/\", (req, res) => {\n res.json(\"This works!\");\n}); res.json() req.json()"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19964129/"
] |
74,489,538
|
<p>I'm working with spark java application with spark version 2.7. I'm trying to load a multiline JSON file that might have corrupted records according to my schema. I'm passing a schema while loading it, but the issue is that it rejects the entire file as one corrupted record even if there's one JSON object which is not satisfying the schema I'm providing.</p>
<p>My Json file looks something like-</p>
<pre><code>[
{Json_object},
{Json_object},
{Json_object}
]
</code></pre>
<p>I manually created schema(of StructType) for it and loading it like -</p>
<pre><code>Dataset<Row> df = spark.read().option("multiline", "true").option("mode","PERMISSIVE").option("columnNameOfCorruptRecord","_corrupt_record").schema(schema).json("filepath");
</code></pre>
<p>The issue is that even if one JSON object doesn't follow the schema, for instance if attribute1 in my schema has integer type and it is in form of string for one of the json object then json object should get inside corrupted_record, insted I'm getting something like-</p>
<pre><code>+------------+---------------+---------------+
| attribute1 | attribute2 |_corrupt_record|
+------------+---------------+---------------+
| null | null | [{|
| | | all_json_obj |
| | | ... |
| | | }] |
+------------+---------------+---------------+
</code></pre>
<p>And it works absolutely fine with typical single line json objects where newline character '\n' is used as a delimiter, no issues facing in that and ideal results. Can somebody tell me what am I missing here?</p>
<p>PS: The question is not limited to spark java, the behavior is same in scala and python as well.</p>
|
[
{
"answer_id": 74511352,
"author": "Koedlt",
"author_id": 15405732,
"author_profile": "https://Stackoverflow.com/users/15405732",
"pm_score": 0,
"selected": false,
"text": "+------------+---------------+---------------+\n| attribute1 | attribute2 |_corrupt_record|\n+------------+---------------+---------------+\n| null | null | [{|\n| | | all_json_obj |\n| | | ... |\n| | | }] |\n+------------+---------------+---------------+\n [{ }] { } [{\n{Json_object},\n{Json_object},\n{Json_object}\n}]\n {} [] [\n {\n \"id\": 1,\n \"object\": {\n \"val1\": \"thisValue\",\n \"val2\": \"otherValue\"\n }\n },\n {\n \"id\": 2,\n \"object\": {\n \"val1\": \"hehe\",\n \"val2\": \"test\"\n }\n },\n {\n \"id\": 3,\n \"object\": {\n \"val1\": \"yes\",\n \"val2\": \"no\"\n }\n }\n]\n val df = spark.read.option(\"multiline\", \"true\").json(\"test.json\") scala> df.show(false)\n+---+-----------------------+\n|id |object |\n+---+-----------------------+\n|1 |[thisValue, otherValue]|\n|2 |[hehe, test] |\n|3 |[yes, no] |\n+---+-----------------------+\n\n\nscala> df.printSchema\nroot\n |-- id: long (nullable = true)\n |-- object: struct (nullable = true)\n | |-- val1: string (nullable = true)\n | |-- val2: string (nullable = true)\n [{ }]"
},
{
"answer_id": 74511806,
"author": "M_S",
"author_id": 19915660,
"author_profile": "https://Stackoverflow.com/users/19915660",
"pm_score": 3,
"selected": true,
"text": "override def readFile(\n conf: Configuration,\n file: PartitionedFile,\n parser: JacksonParser,\n schema: StructType): Iterator[InternalRow] = {\n val linesReader = new HadoopFileLinesReader(file, parser.options.lineSeparatorInRead, conf)\n Option(TaskContext.get()).foreach(_.addTaskCompletionListener[Unit](_ => linesReader.close()))\n val textParser = parser.options.encoding\n .map(enc => CreateJacksonParser.text(enc, _: JsonFactory, _: Text))\n .getOrElse(CreateJacksonParser.text(_: JsonFactory, _: Text))\n\n val safeParser = new FailureSafeParser[Text](\n input => parser.parse(input, textParser, textToUTF8String),\n parser.options.parseMode,\n schema,\n parser.options.columnNameOfCorruptRecord)\n linesReader.flatMap(safeParser.parse)\n}\n override def readFile(\n conf: Configuration,\n file: PartitionedFile,\n parser: JacksonParser,\n schema: StructType): Iterator[InternalRow] = {\n def partitionedFileString(ignored: Any): UTF8String = {\n Utils.tryWithResource {\n CodecStreams.createInputStreamWithCloseResource(conf, new Path(new URI(file.filePath)))\n } { inputStream =>\n UTF8String.fromBytes(ByteStreams.toByteArray(inputStream))\n }\n }\n val streamParser = parser.options.encoding\n .map(enc => CreateJacksonParser.inputStream(enc, _: JsonFactory, _: InputStream))\n .getOrElse(CreateJacksonParser.inputStream(_: JsonFactory, _: InputStream))\n\n val safeParser = new FailureSafeParser[InputStream](\n input => parser.parse[InputStream](input, streamParser, partitionedFileString),\n parser.options.parseMode,\n schema,\n parser.options.columnNameOfCorruptRecord)\n\n safeParser.parse(\n CodecStreams.createInputStreamWithCloseResource(conf, new Path(new URI(file.filePath))))\n }\n def parse[T](\n record: T,\n createParser: (JsonFactory, T) => JsonParser,\n recordLiteral: T => UTF8String): Iterable[InternalRow] = {\n try {\n Utils.tryWithResource(createParser(factory, record)) { parser =>\n // a null first token is equivalent to testing for input.trim.isEmpty\n // but it works on any token stream and not just strings\n parser.nextToken() match {\n case null => None\n case _ => rootConverter.apply(parser) match {\n case null => throw QueryExecutionErrors.rootConverterReturnNullError()\n case rows => rows.toSeq\n }\n }\n }\n } catch {\n case e: SparkUpgradeException => throw e\n case e @ (_: RuntimeException | _: JsonProcessingException | _: MalformedInputException) =>\n // JSON parser currently doesnt support partial results for corrupted records.\n // For such records, all fields other than the field configured by\n // `columnNameOfCorruptRecord` are set to `null`\n throw BadRecordException(() => recordLiteral(record), () => None, e)\n case e: CharConversionException if options.encoding.isEmpty =>\n val msg =\n \"\"\"JSON parser cannot handle a character in its input.\n |Specifying encoding as an input option explicitly might help to resolve the issue.\n |\"\"\".stripMargin + e.getMessage\n val wrappedCharException = new CharConversionException(msg)\n wrappedCharException.initCause(e)\n throw BadRecordException(() => recordLiteral(record), () => None, wrappedCharException)\n case PartialResultException(row, cause) =>\n throw BadRecordException(\n record = () => recordLiteral(record),\n partialResult = () => Some(row),\n cause)\n }\n }\n [SPARK-18352][SQL] Support parsing multiline json files\n\n## What changes were proposed in this pull request?\n\nIf a new option `wholeFile` is set to `true` the JSON reader will parse each file (instead of a single line) as a value. This is done with Jackson streaming and it should be capable of parsing very large documents, assuming the row will fit in memory.\n\nBecause the file is not buffered in memory the corrupt record handling is also slightly different when `wholeFile` is enabled: the corrupt column will contain the filename instead of the literal JSON if there is a parsing failure. It would be easy to extend this to add the parser location (line, column and byte offsets) to the output if desired.\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11321873/"
] |
74,489,551
|
<p>I want to split a character string is part of the comma but the orca I try my code below it only returns me the index of the first comma and not the different strings fraction of the sentence</p>
<pre><code>DELIMITER $$
create procedure separertext()
BEGIN
DECLARE text varchar (128);
DECLARE i varchar (10);
DECLARE j varchar(10);
DECLARE ind varchar(100);
DECLARE nom varchar (128);
set text = 'bonjour,daryle,manuella';
select LOCATE(',', text) as c;
SELECT SUBSTRING(text, 1, c) AS ExtractString;
END$$
DELIMITER ;
</code></pre>
<p>and here is the result I got</p>
<pre><code>+------+
| c |
+------+
| 8 |
+------+`
`1 row in set (0.001 sec)
</code></pre>
|
[
{
"answer_id": 74511352,
"author": "Koedlt",
"author_id": 15405732,
"author_profile": "https://Stackoverflow.com/users/15405732",
"pm_score": 0,
"selected": false,
"text": "+------------+---------------+---------------+\n| attribute1 | attribute2 |_corrupt_record|\n+------------+---------------+---------------+\n| null | null | [{|\n| | | all_json_obj |\n| | | ... |\n| | | }] |\n+------------+---------------+---------------+\n [{ }] { } [{\n{Json_object},\n{Json_object},\n{Json_object}\n}]\n {} [] [\n {\n \"id\": 1,\n \"object\": {\n \"val1\": \"thisValue\",\n \"val2\": \"otherValue\"\n }\n },\n {\n \"id\": 2,\n \"object\": {\n \"val1\": \"hehe\",\n \"val2\": \"test\"\n }\n },\n {\n \"id\": 3,\n \"object\": {\n \"val1\": \"yes\",\n \"val2\": \"no\"\n }\n }\n]\n val df = spark.read.option(\"multiline\", \"true\").json(\"test.json\") scala> df.show(false)\n+---+-----------------------+\n|id |object |\n+---+-----------------------+\n|1 |[thisValue, otherValue]|\n|2 |[hehe, test] |\n|3 |[yes, no] |\n+---+-----------------------+\n\n\nscala> df.printSchema\nroot\n |-- id: long (nullable = true)\n |-- object: struct (nullable = true)\n | |-- val1: string (nullable = true)\n | |-- val2: string (nullable = true)\n [{ }]"
},
{
"answer_id": 74511806,
"author": "M_S",
"author_id": 19915660,
"author_profile": "https://Stackoverflow.com/users/19915660",
"pm_score": 3,
"selected": true,
"text": "override def readFile(\n conf: Configuration,\n file: PartitionedFile,\n parser: JacksonParser,\n schema: StructType): Iterator[InternalRow] = {\n val linesReader = new HadoopFileLinesReader(file, parser.options.lineSeparatorInRead, conf)\n Option(TaskContext.get()).foreach(_.addTaskCompletionListener[Unit](_ => linesReader.close()))\n val textParser = parser.options.encoding\n .map(enc => CreateJacksonParser.text(enc, _: JsonFactory, _: Text))\n .getOrElse(CreateJacksonParser.text(_: JsonFactory, _: Text))\n\n val safeParser = new FailureSafeParser[Text](\n input => parser.parse(input, textParser, textToUTF8String),\n parser.options.parseMode,\n schema,\n parser.options.columnNameOfCorruptRecord)\n linesReader.flatMap(safeParser.parse)\n}\n override def readFile(\n conf: Configuration,\n file: PartitionedFile,\n parser: JacksonParser,\n schema: StructType): Iterator[InternalRow] = {\n def partitionedFileString(ignored: Any): UTF8String = {\n Utils.tryWithResource {\n CodecStreams.createInputStreamWithCloseResource(conf, new Path(new URI(file.filePath)))\n } { inputStream =>\n UTF8String.fromBytes(ByteStreams.toByteArray(inputStream))\n }\n }\n val streamParser = parser.options.encoding\n .map(enc => CreateJacksonParser.inputStream(enc, _: JsonFactory, _: InputStream))\n .getOrElse(CreateJacksonParser.inputStream(_: JsonFactory, _: InputStream))\n\n val safeParser = new FailureSafeParser[InputStream](\n input => parser.parse[InputStream](input, streamParser, partitionedFileString),\n parser.options.parseMode,\n schema,\n parser.options.columnNameOfCorruptRecord)\n\n safeParser.parse(\n CodecStreams.createInputStreamWithCloseResource(conf, new Path(new URI(file.filePath))))\n }\n def parse[T](\n record: T,\n createParser: (JsonFactory, T) => JsonParser,\n recordLiteral: T => UTF8String): Iterable[InternalRow] = {\n try {\n Utils.tryWithResource(createParser(factory, record)) { parser =>\n // a null first token is equivalent to testing for input.trim.isEmpty\n // but it works on any token stream and not just strings\n parser.nextToken() match {\n case null => None\n case _ => rootConverter.apply(parser) match {\n case null => throw QueryExecutionErrors.rootConverterReturnNullError()\n case rows => rows.toSeq\n }\n }\n }\n } catch {\n case e: SparkUpgradeException => throw e\n case e @ (_: RuntimeException | _: JsonProcessingException | _: MalformedInputException) =>\n // JSON parser currently doesnt support partial results for corrupted records.\n // For such records, all fields other than the field configured by\n // `columnNameOfCorruptRecord` are set to `null`\n throw BadRecordException(() => recordLiteral(record), () => None, e)\n case e: CharConversionException if options.encoding.isEmpty =>\n val msg =\n \"\"\"JSON parser cannot handle a character in its input.\n |Specifying encoding as an input option explicitly might help to resolve the issue.\n |\"\"\".stripMargin + e.getMessage\n val wrappedCharException = new CharConversionException(msg)\n wrappedCharException.initCause(e)\n throw BadRecordException(() => recordLiteral(record), () => None, wrappedCharException)\n case PartialResultException(row, cause) =>\n throw BadRecordException(\n record = () => recordLiteral(record),\n partialResult = () => Some(row),\n cause)\n }\n }\n [SPARK-18352][SQL] Support parsing multiline json files\n\n## What changes were proposed in this pull request?\n\nIf a new option `wholeFile` is set to `true` the JSON reader will parse each file (instead of a single line) as a value. This is done with Jackson streaming and it should be capable of parsing very large documents, assuming the row will fit in memory.\n\nBecause the file is not buffered in memory the corrupt record handling is also slightly different when `wholeFile` is enabled: the corrupt column will contain the filename instead of the literal JSON if there is a parsing failure. It would be easy to extend this to add the parser location (line, column and byte offsets) to the output if desired.\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20002167/"
] |
74,489,567
|
<p>I'm quite new to Power Bi and DAX in general and I have some problems calculating how much of each month was of the whole year.</p>
<pre><code>Example:
Year 2021:
Month Value Percentage
Jan. 100 10
Feb. 50 5
Mar. 250 25
Apr. 30 3
Etc...
Total 1000 100
</code></pre>
<p>I have calculated the percentage column in dax as:</p>
<pre><code> =
[Value] /
CALCULATE(
[Value],
ALLEXCEPT(Calendar, Calendar[Year])
)
</code></pre>
<p>This gives me the correct result for the chosen year, the problem I have is when trying to compare it to last year's result.</p>
<p>I've tried to add
"SAMEPERIODLASTYEAR(Calendar[Key_Calendar])" and "PARALLELLPERIOD(CALENDAR[Key_Calendar],-12,Month)"</p>
<p>but neither of them gives me the result I am looking for.</p>
<p>I'd appreciate any help that I can get on the issue.</p>
|
[
{
"answer_id": 74511352,
"author": "Koedlt",
"author_id": 15405732,
"author_profile": "https://Stackoverflow.com/users/15405732",
"pm_score": 0,
"selected": false,
"text": "+------------+---------------+---------------+\n| attribute1 | attribute2 |_corrupt_record|\n+------------+---------------+---------------+\n| null | null | [{|\n| | | all_json_obj |\n| | | ... |\n| | | }] |\n+------------+---------------+---------------+\n [{ }] { } [{\n{Json_object},\n{Json_object},\n{Json_object}\n}]\n {} [] [\n {\n \"id\": 1,\n \"object\": {\n \"val1\": \"thisValue\",\n \"val2\": \"otherValue\"\n }\n },\n {\n \"id\": 2,\n \"object\": {\n \"val1\": \"hehe\",\n \"val2\": \"test\"\n }\n },\n {\n \"id\": 3,\n \"object\": {\n \"val1\": \"yes\",\n \"val2\": \"no\"\n }\n }\n]\n val df = spark.read.option(\"multiline\", \"true\").json(\"test.json\") scala> df.show(false)\n+---+-----------------------+\n|id |object |\n+---+-----------------------+\n|1 |[thisValue, otherValue]|\n|2 |[hehe, test] |\n|3 |[yes, no] |\n+---+-----------------------+\n\n\nscala> df.printSchema\nroot\n |-- id: long (nullable = true)\n |-- object: struct (nullable = true)\n | |-- val1: string (nullable = true)\n | |-- val2: string (nullable = true)\n [{ }]"
},
{
"answer_id": 74511806,
"author": "M_S",
"author_id": 19915660,
"author_profile": "https://Stackoverflow.com/users/19915660",
"pm_score": 3,
"selected": true,
"text": "override def readFile(\n conf: Configuration,\n file: PartitionedFile,\n parser: JacksonParser,\n schema: StructType): Iterator[InternalRow] = {\n val linesReader = new HadoopFileLinesReader(file, parser.options.lineSeparatorInRead, conf)\n Option(TaskContext.get()).foreach(_.addTaskCompletionListener[Unit](_ => linesReader.close()))\n val textParser = parser.options.encoding\n .map(enc => CreateJacksonParser.text(enc, _: JsonFactory, _: Text))\n .getOrElse(CreateJacksonParser.text(_: JsonFactory, _: Text))\n\n val safeParser = new FailureSafeParser[Text](\n input => parser.parse(input, textParser, textToUTF8String),\n parser.options.parseMode,\n schema,\n parser.options.columnNameOfCorruptRecord)\n linesReader.flatMap(safeParser.parse)\n}\n override def readFile(\n conf: Configuration,\n file: PartitionedFile,\n parser: JacksonParser,\n schema: StructType): Iterator[InternalRow] = {\n def partitionedFileString(ignored: Any): UTF8String = {\n Utils.tryWithResource {\n CodecStreams.createInputStreamWithCloseResource(conf, new Path(new URI(file.filePath)))\n } { inputStream =>\n UTF8String.fromBytes(ByteStreams.toByteArray(inputStream))\n }\n }\n val streamParser = parser.options.encoding\n .map(enc => CreateJacksonParser.inputStream(enc, _: JsonFactory, _: InputStream))\n .getOrElse(CreateJacksonParser.inputStream(_: JsonFactory, _: InputStream))\n\n val safeParser = new FailureSafeParser[InputStream](\n input => parser.parse[InputStream](input, streamParser, partitionedFileString),\n parser.options.parseMode,\n schema,\n parser.options.columnNameOfCorruptRecord)\n\n safeParser.parse(\n CodecStreams.createInputStreamWithCloseResource(conf, new Path(new URI(file.filePath))))\n }\n def parse[T](\n record: T,\n createParser: (JsonFactory, T) => JsonParser,\n recordLiteral: T => UTF8String): Iterable[InternalRow] = {\n try {\n Utils.tryWithResource(createParser(factory, record)) { parser =>\n // a null first token is equivalent to testing for input.trim.isEmpty\n // but it works on any token stream and not just strings\n parser.nextToken() match {\n case null => None\n case _ => rootConverter.apply(parser) match {\n case null => throw QueryExecutionErrors.rootConverterReturnNullError()\n case rows => rows.toSeq\n }\n }\n }\n } catch {\n case e: SparkUpgradeException => throw e\n case e @ (_: RuntimeException | _: JsonProcessingException | _: MalformedInputException) =>\n // JSON parser currently doesnt support partial results for corrupted records.\n // For such records, all fields other than the field configured by\n // `columnNameOfCorruptRecord` are set to `null`\n throw BadRecordException(() => recordLiteral(record), () => None, e)\n case e: CharConversionException if options.encoding.isEmpty =>\n val msg =\n \"\"\"JSON parser cannot handle a character in its input.\n |Specifying encoding as an input option explicitly might help to resolve the issue.\n |\"\"\".stripMargin + e.getMessage\n val wrappedCharException = new CharConversionException(msg)\n wrappedCharException.initCause(e)\n throw BadRecordException(() => recordLiteral(record), () => None, wrappedCharException)\n case PartialResultException(row, cause) =>\n throw BadRecordException(\n record = () => recordLiteral(record),\n partialResult = () => Some(row),\n cause)\n }\n }\n [SPARK-18352][SQL] Support parsing multiline json files\n\n## What changes were proposed in this pull request?\n\nIf a new option `wholeFile` is set to `true` the JSON reader will parse each file (instead of a single line) as a value. This is done with Jackson streaming and it should be capable of parsing very large documents, assuming the row will fit in memory.\n\nBecause the file is not buffered in memory the corrupt record handling is also slightly different when `wholeFile` is enabled: the corrupt column will contain the filename instead of the literal JSON if there is a parsing failure. It would be easy to extend this to add the parser location (line, column and byte offsets) to the output if desired.\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12857834/"
] |
74,489,636
|
<pre><code>let products = [
{
name: "A",
color: "Blue",
size: {
size1: 1,
size2: 2,
size3: 3,
},
},
{
name: "B",
color: "Blue",
size: {
size1: 5,
size2: 19,
size3: 22,
},
},
{ name: "C", color: "Black", size: 70 },
{ name: "D", color: "Green", size: 50 },
];
</code></pre>
<pre><code>filters = ['Blue','2'];
</code></pre>
<p>the result must be the object that checks all strings in the array for example</p>
<pre><code> {
name: "A",
color: "Blue",
size: {
size1: 1,
size2: 2,
size3: 3,
},
},
</code></pre>
<p>the research must be accepted whatever the value in the</p>
|
[
{
"answer_id": 74489719,
"author": "Nuro007",
"author_id": 19669556,
"author_profile": "https://Stackoverflow.com/users/19669556",
"pm_score": 0,
"selected": false,
"text": "Array.every const products = [\n { name: \"A\", color: \"Blue\", size: { size1:1, size2:2, size3:3 } },\n { name: \"B\", color: \"Blue\", size: { size1:5, size2:19, size3:22 } },\n { name: \"C\", color: \"Black\", size: 70 },\n { name: \"D\", color: \"Green\", size: 50 },\n];\n\nconst filters = ['Blue','2'];\n\nconst filtered = products.filter(product => {\n return Object.values(product).every(value => {\n return filters.includes(value);\n });\n});\n\nconsole.log(filtered);"
},
{
"answer_id": 74490154,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 1,
"selected": false,
"text": "function getFiltered(obj, filters, found = null) {\n let outermostCall = (found === null);\n if (outermostCall) { //outermost call\n found = [];\n for (let index = 0; index < filters.length; index++) {\n found[index] = false;\n }\n }\n for (let key in obj) {\n if (typeof obj[key] === 'object') {\n let tempFound = getFiltered(obj[key], filters, found);\n for (let index = 0; index < found.length; index++) {\n if (tempFound[index]) found[index] = true;\n }\n } else {\n let foundIndex = -1;\n for (let index = 0; index < filters.length; index++) {\n if (filters[index] == obj[key]) {\n foundIndex = index;\n index = filters.length;\n }\n }\n if (foundIndex >= 0) {\n found[foundIndex] = true;\n }\n }\n }\n if (outermostCall) {\n return !found.filter(item => !item).length;\n }\n return found;\n}\n\nfunction getAllFiltered(array, filters) {\n let output = [];\n for (let obj of array) {\n if (getFiltered(obj, filters)) output.push(obj);\n }\n return output;\n}\n\nlet products = [\n {\n name: \"A\",\n color: \"Blue\",\n size: {\n size1: 1,\n size2: 2,\n size3: 3,\n },\n },\n {\n name: \"B\",\n color: \"Blue\",\n size: {\n size1: 5,\n size2: 19,\n size3: 22,\n },\n },\n { name: \"C\", color: \"Black\", size: 70 },\n { name: \"D\", color: \"Green\", size: 50 },\n];\n\nlet filters = ['Blue','2']; \n\nconsole.log(getAllFiltered(products, filters));"
},
{
"answer_id": 74490514,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 1,
"selected": false,
"text": "const\n has = f => {\n const check = o => o && typeof o === 'object'\n ? Object.values(o).some(check)\n : f === o;\n\n return check;\n },\n products = [{ name: \"A\", color: \"Blue\", size: { size1: 1, size2: 2, size3: 3 } }, { name: \"B\", color: \"Blue\", size: { size1: 5, size2: 19, size3: 22 } }, { name: \"C\", color: \"Black\", size: 70 }, { name: \"D\", color: \"Green\", size: 50 }],\n search = ['Blue', 2],\n result = products.filter(o => search.every(f => has(f)(o)));\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74490867,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 0,
"selected": false,
"text": "strings const products = [{\"name\":\"A\",\"color\":\"Blue\",\"size\":{\"size1\":1,\"size2\":2,\"size3\":3}},{\"name\":\"B\",\"color\":\"Blue\",\"size\":{\"size1\":5,\"size2\":19,\"size3\":22}},{\"name\":\"C\",\"color\":\"Black\",\"size\":70},{\"name\":\"D\",\"color\":\"Green\",\"size\":50}];\nconst filters = ['Blue','2'];\nconst subsetMatch=(a,s)=>s.every(i=>a.includes(i));\nconst strings=i=>typeof i==='object'?Object.values(i).flatMap(strings):i+'';\nconsole.log(products.filter(i=>subsetMatch(strings(i),filters)));"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16120549/"
] |
74,489,659
|
<p>Yes I'm a newbie to VueJs and Typescript but even though it is bad practice there has been a reason that typescript offers this line of code <code>//@ignore-ts</code>. Now in my VueJs App everything works as expected. Only thing annoying me is a typescript error in my template block in my code editor. Is there any option I could not find yet similar to what I would do in my script block?</p>
<pre class="lang-bash prettyprint-override"><code><script setup lang="ts">
//@ignore-ts
this line will be ignored of typescript errors
</script>
<template>
<!-- @ignore-ts -->
this does not work and this line still has a typescript error
</template>
</code></pre>
<p>A more comprehensive question to my problem is asked <a href="https://stackoverflow.com/questions/74490975/vuejs-typescript-v-model-type-number-is-not-assignable-to-type-nullablestrin">here</a></p>
|
[
{
"answer_id": 74489719,
"author": "Nuro007",
"author_id": 19669556,
"author_profile": "https://Stackoverflow.com/users/19669556",
"pm_score": 0,
"selected": false,
"text": "Array.every const products = [\n { name: \"A\", color: \"Blue\", size: { size1:1, size2:2, size3:3 } },\n { name: \"B\", color: \"Blue\", size: { size1:5, size2:19, size3:22 } },\n { name: \"C\", color: \"Black\", size: 70 },\n { name: \"D\", color: \"Green\", size: 50 },\n];\n\nconst filters = ['Blue','2'];\n\nconst filtered = products.filter(product => {\n return Object.values(product).every(value => {\n return filters.includes(value);\n });\n});\n\nconsole.log(filtered);"
},
{
"answer_id": 74490154,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 1,
"selected": false,
"text": "function getFiltered(obj, filters, found = null) {\n let outermostCall = (found === null);\n if (outermostCall) { //outermost call\n found = [];\n for (let index = 0; index < filters.length; index++) {\n found[index] = false;\n }\n }\n for (let key in obj) {\n if (typeof obj[key] === 'object') {\n let tempFound = getFiltered(obj[key], filters, found);\n for (let index = 0; index < found.length; index++) {\n if (tempFound[index]) found[index] = true;\n }\n } else {\n let foundIndex = -1;\n for (let index = 0; index < filters.length; index++) {\n if (filters[index] == obj[key]) {\n foundIndex = index;\n index = filters.length;\n }\n }\n if (foundIndex >= 0) {\n found[foundIndex] = true;\n }\n }\n }\n if (outermostCall) {\n return !found.filter(item => !item).length;\n }\n return found;\n}\n\nfunction getAllFiltered(array, filters) {\n let output = [];\n for (let obj of array) {\n if (getFiltered(obj, filters)) output.push(obj);\n }\n return output;\n}\n\nlet products = [\n {\n name: \"A\",\n color: \"Blue\",\n size: {\n size1: 1,\n size2: 2,\n size3: 3,\n },\n },\n {\n name: \"B\",\n color: \"Blue\",\n size: {\n size1: 5,\n size2: 19,\n size3: 22,\n },\n },\n { name: \"C\", color: \"Black\", size: 70 },\n { name: \"D\", color: \"Green\", size: 50 },\n];\n\nlet filters = ['Blue','2']; \n\nconsole.log(getAllFiltered(products, filters));"
},
{
"answer_id": 74490514,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 1,
"selected": false,
"text": "const\n has = f => {\n const check = o => o && typeof o === 'object'\n ? Object.values(o).some(check)\n : f === o;\n\n return check;\n },\n products = [{ name: \"A\", color: \"Blue\", size: { size1: 1, size2: 2, size3: 3 } }, { name: \"B\", color: \"Blue\", size: { size1: 5, size2: 19, size3: 22 } }, { name: \"C\", color: \"Black\", size: 70 }, { name: \"D\", color: \"Green\", size: 50 }],\n search = ['Blue', 2],\n result = products.filter(o => search.every(f => has(f)(o)));\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74490867,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 0,
"selected": false,
"text": "strings const products = [{\"name\":\"A\",\"color\":\"Blue\",\"size\":{\"size1\":1,\"size2\":2,\"size3\":3}},{\"name\":\"B\",\"color\":\"Blue\",\"size\":{\"size1\":5,\"size2\":19,\"size3\":22}},{\"name\":\"C\",\"color\":\"Black\",\"size\":70},{\"name\":\"D\",\"color\":\"Green\",\"size\":50}];\nconst filters = ['Blue','2'];\nconst subsetMatch=(a,s)=>s.every(i=>a.includes(i));\nconst strings=i=>typeof i==='object'?Object.values(i).flatMap(strings):i+'';\nconsole.log(products.filter(i=>subsetMatch(strings(i),filters)));"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19932351/"
] |
74,489,666
|
<p>I have uploaded my project on github and cloned to another computer. It compiles fine but it hasnt got access to Firbase/firestore and therefore i cant use this cloned project properly with authentication and so on.
Do I have to change something when I clone a flutter app with firebase to another computer to make it work and gain access to the database and the authentication?</p>
<p><strong>Errormessage:</strong></p>
<pre><code>D/EGL_emulation(10634): app_time_stats: avg=6275.84ms min=9.86ms max=106419.61ms count=17
D/EGL_emulation(10634): app_time_stats: avg=11.48ms min=5.31ms max=40.71ms count=60
D/EGL_emulation(10634): app_time_stats: avg=9.29ms min=4.92ms max=16.29ms count=56
D/EGL_emulation(10634): app_time_stats: avg=8.66ms min=5.06ms max=15.26ms count=61
D/EGL_emulation(10634): app_time_stats: avg=9.94ms min=4.58ms max=24.23ms count=61
D/EGL_emulation(10634): app_time_stats: avg=10.22ms min=5.13ms max=20.02ms count=60
D/EGL_emulation(10634): app_time_stats: avg=8.59ms min=4.91ms max=15.28ms count=60
D/EGL_emulation(10634): app_time_stats: avg=8.31ms min=5.03ms max=16.29ms count=61
D/EGL_emulation(10634): app_time_stats: avg=8.91ms min=4.52ms max=14.01ms count=61
D/EGL_emulation(10634): app_time_stats: avg=9.90ms min=4.90ms max=17.99ms count=60
I/flutter (10634): 2 false
D/EGL_emulation(10634): app_time_stats: avg=9.15ms min=5.06ms max=22.87ms count=60
D/EGL_emulation(10634): app_time_stats: avg=83.28ms min=12.88ms max=1016.12ms count=15
W/Firestore(10634): (24.4.0) [WatchStream]: (24ebbad) Stream closed with status: Status{code=UNAVAILABLE, description=Channel shutdownNow invoked, cause=null}.
W/DynamiteModule(10634): Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found.
I/DynamiteModule(10634): Considering local module com.google.android.gms.providerinstaller.dynamite:0 and remote module com.google.android.gms.providerinstaller.dynamite:0
W/ProviderInstaller(10634): Failed to load providerinstaller module: No acceptable module com.google.android.gms.providerinstaller.dynamite found. Local version is 0 and remote version is 0.
</code></pre>
|
[
{
"answer_id": 74489719,
"author": "Nuro007",
"author_id": 19669556,
"author_profile": "https://Stackoverflow.com/users/19669556",
"pm_score": 0,
"selected": false,
"text": "Array.every const products = [\n { name: \"A\", color: \"Blue\", size: { size1:1, size2:2, size3:3 } },\n { name: \"B\", color: \"Blue\", size: { size1:5, size2:19, size3:22 } },\n { name: \"C\", color: \"Black\", size: 70 },\n { name: \"D\", color: \"Green\", size: 50 },\n];\n\nconst filters = ['Blue','2'];\n\nconst filtered = products.filter(product => {\n return Object.values(product).every(value => {\n return filters.includes(value);\n });\n});\n\nconsole.log(filtered);"
},
{
"answer_id": 74490154,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 1,
"selected": false,
"text": "function getFiltered(obj, filters, found = null) {\n let outermostCall = (found === null);\n if (outermostCall) { //outermost call\n found = [];\n for (let index = 0; index < filters.length; index++) {\n found[index] = false;\n }\n }\n for (let key in obj) {\n if (typeof obj[key] === 'object') {\n let tempFound = getFiltered(obj[key], filters, found);\n for (let index = 0; index < found.length; index++) {\n if (tempFound[index]) found[index] = true;\n }\n } else {\n let foundIndex = -1;\n for (let index = 0; index < filters.length; index++) {\n if (filters[index] == obj[key]) {\n foundIndex = index;\n index = filters.length;\n }\n }\n if (foundIndex >= 0) {\n found[foundIndex] = true;\n }\n }\n }\n if (outermostCall) {\n return !found.filter(item => !item).length;\n }\n return found;\n}\n\nfunction getAllFiltered(array, filters) {\n let output = [];\n for (let obj of array) {\n if (getFiltered(obj, filters)) output.push(obj);\n }\n return output;\n}\n\nlet products = [\n {\n name: \"A\",\n color: \"Blue\",\n size: {\n size1: 1,\n size2: 2,\n size3: 3,\n },\n },\n {\n name: \"B\",\n color: \"Blue\",\n size: {\n size1: 5,\n size2: 19,\n size3: 22,\n },\n },\n { name: \"C\", color: \"Black\", size: 70 },\n { name: \"D\", color: \"Green\", size: 50 },\n];\n\nlet filters = ['Blue','2']; \n\nconsole.log(getAllFiltered(products, filters));"
},
{
"answer_id": 74490514,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 1,
"selected": false,
"text": "const\n has = f => {\n const check = o => o && typeof o === 'object'\n ? Object.values(o).some(check)\n : f === o;\n\n return check;\n },\n products = [{ name: \"A\", color: \"Blue\", size: { size1: 1, size2: 2, size3: 3 } }, { name: \"B\", color: \"Blue\", size: { size1: 5, size2: 19, size3: 22 } }, { name: \"C\", color: \"Black\", size: 70 }, { name: \"D\", color: \"Green\", size: 50 }],\n search = ['Blue', 2],\n result = products.filter(o => search.every(f => has(f)(o)));\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74490867,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 0,
"selected": false,
"text": "strings const products = [{\"name\":\"A\",\"color\":\"Blue\",\"size\":{\"size1\":1,\"size2\":2,\"size3\":3}},{\"name\":\"B\",\"color\":\"Blue\",\"size\":{\"size1\":5,\"size2\":19,\"size3\":22}},{\"name\":\"C\",\"color\":\"Black\",\"size\":70},{\"name\":\"D\",\"color\":\"Green\",\"size\":50}];\nconst filters = ['Blue','2'];\nconst subsetMatch=(a,s)=>s.every(i=>a.includes(i));\nconst strings=i=>typeof i==='object'?Object.values(i).flatMap(strings):i+'';\nconsole.log(products.filter(i=>subsetMatch(strings(i),filters)));"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17500827/"
] |
74,489,725
|
<p>Let's say I have the following program to export an object to JSON:</p>
<pre class="lang-cpp prettyprint-override"><code>struct MyChronoObject {
std::string name;
std::chrono::system_clock::time_point birthday;
MyChronoObject(const std::string name_) : name(name_) {
birthday = std::chrono::system_clock::now();
}
std::string toJSON1() {
std::string s = "{ \"name\": \"" + name + "\", \"birthday\": ";
s += std::to_string((birthday.time_since_epoch().count() / 1000000));
s += " }";
return s;
}
std::string toJSON2() {
std::string s = "{ \"name\": \"" + name + "\", \"birthday\": ";
s += std::to_string((birthday.time_since_epoch().count()));
s += " }";
return s;
}
void setBirthday(int birthday_in_seconds) {
// how do I properly cast this?
}
};
</code></pre>
<p>Which, for <code>toJSON1()</code>, has the output <code>{ "name": "Steve", "birthday": 16687719115 }</code></p>
<p>There are several problems with this code (which I will mention but will probably address them in separate threads), but first and foremost...</p>
<ul>
<li>The number <code>16687747280</code> is not correct. It should be one digit shorter for <code>seconds</code> or 2 digits longer for <code>milliseconds</code> if I go by this: <a href="https://www.epochconverter.com/" rel="nofollow noreferrer">EpochConverter</a></li>
<li>Not dividing the the birthday by one million, <code>toJSON2()</code>, leads to a number that is one digit too long for <code>microseconds</code> and 2 digits too short for <code>nanoseconds</code>: <code>16687747280849928</code>.</li>
</ul>
<p>So which way would be correct (and most efficient) to store and convert the stored epoch time so that I can export it to something that can be used by Javascript?</p>
<p>Thank you in advance!
</p>
<hr />
<p>P.S.: Other questions that I have are:</p>
<ul>
<li>How do I cast back a number that the <code>C++</code> program receives from the frontend (like in <code>setBirthday</code>)?</li>
<li>Should I even store the date as <code>chrono</code> object if seconds are sufficient?</li>
<li>How do I add exactly one year so that I land on the same date (e.g. 25.1.20<strong>19</strong> to 25.1.20<strong>20</strong>), considering things like leap years, etc.).</li>
<li>What about dates before 1970?</li>
</ul>
|
[
{
"answer_id": 74489988,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": false,
"text": "duration.count() std::chrono::duration_cast<std::chrono::seconds>(birthday.time_since_epoch()).count()\n// Instead of birthday.time_since_epoch().count()\n"
},
{
"answer_id": 74489991,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 3,
"selected": false,
"text": "std::chrono::system_clock birthday.time_since_epoch().count() / 1000000 std::chrono::duration_cast<std::chrono::seconds>(birthday.time_since_epoch())\n .count()\n std::chrono::ceil<seconds> std::chrono::floor<seconds> std::chrono::round<seconds> time_point std::chrono::sys_time{std::chrono::seconds{birthday_in_second}};\n std::chrono::sys_time{std::chrono::milliseconds{birthday_in_millisecond}};\n auto now = std::chrono::system_clock::now();\nauto today = std::chrono::year_month_day{std::chrono::floor<std::chrono::days>(now)};\nauto today_10_years_ago = today - std::chrono::years{10};\n using namespace std::chrono::literals 10y years{10} today today_10_years_ago year_month_day time_point auto today_as_time_point = std::chrono::sys_days{today_10_years_ago};\n\nauto time_only = today - now;\nauto today_with_time_info = today_as_time_point + time_only;\n <chrono> chrono::hours chrono::days chrono::years now - years{1000} now <chrono> year std::format auto now = std::chrono::system_clock::now();\nstd::cout << std::format(\"{:%Y}\", now); // This will print only the year\n {fmt} std::format"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547768/"
] |
74,489,729
|
<p>sorry if this is a easy question, I am just having a hard time trying to figure out how I would tackle this problem.</p>
<p>For example, I have 2 Objects as below:</p>
<pre><code>cont oldCar = {
model: 'Honda',
notes: {
id: 1,
timestamp: 2000,
text: 'is old'
}
}
cont oldCar = {
model: 'Toyota',
notes: {
id: 1,
timestamp: 4000,
text: 'is new'
}
}
</code></pre>
<p>I want to try and combine the above two objects. I know they have same key's so I wanted to merge the values of each key if they are the same. Such as:</p>
<pre><code>mode: 'Honda / Toyota'
</code></pre>
<p>I tried the following:</p>
<pre><code>let merged = {...obj1, ...obj2};
</code></pre>
<p>But this will merge both objects but it only retains the values from the right object. I was trying to do a for loop and add check if the key is same in both objects then combine the values together but I keep getting lost and it is hard to visualise. If someone could help me understand how i can create an for loop to start the comparison that would help me in completing the rest.</p>
|
[
{
"answer_id": 74489988,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 2,
"selected": false,
"text": "duration.count() std::chrono::duration_cast<std::chrono::seconds>(birthday.time_since_epoch()).count()\n// Instead of birthday.time_since_epoch().count()\n"
},
{
"answer_id": 74489991,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 3,
"selected": false,
"text": "std::chrono::system_clock birthday.time_since_epoch().count() / 1000000 std::chrono::duration_cast<std::chrono::seconds>(birthday.time_since_epoch())\n .count()\n std::chrono::ceil<seconds> std::chrono::floor<seconds> std::chrono::round<seconds> time_point std::chrono::sys_time{std::chrono::seconds{birthday_in_second}};\n std::chrono::sys_time{std::chrono::milliseconds{birthday_in_millisecond}};\n auto now = std::chrono::system_clock::now();\nauto today = std::chrono::year_month_day{std::chrono::floor<std::chrono::days>(now)};\nauto today_10_years_ago = today - std::chrono::years{10};\n using namespace std::chrono::literals 10y years{10} today today_10_years_ago year_month_day time_point auto today_as_time_point = std::chrono::sys_days{today_10_years_ago};\n\nauto time_only = today - now;\nauto today_with_time_info = today_as_time_point + time_only;\n <chrono> chrono::hours chrono::days chrono::years now - years{1000} now <chrono> year std::format auto now = std::chrono::system_clock::now();\nstd::cout << std::format(\"{:%Y}\", now); // This will print only the year\n {fmt} std::format"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20539428/"
] |
74,489,742
|
<p>I have 4 flexbox items placed in a parent div flexbox. When I shrink the screen width this is what I get.</p>
<p><img src="https://i.stack.imgur.com/UDwpZ.png" alt="Problem example" /></p>
<p>What I want to see instead is:</p>
<p><img src="https://i.stack.imgur.com/aDuzh.png" alt="Desired result" /></p>
<p>I tried to add some CSS rules with different alignment settings, but none of them helped.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.footer__main__div {
display: flex;
margin-left: auto;
margin-right: auto;
max-width: 1280px;
flex-wrap: wrap;
justify-content: space-between;
padding-top: 2.5rem;
padding-bottom: 2.5rem;
padding-left: 1.25rem;
padding-right: 1.25rem;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="footer__main__div">
<div class="footer__left__div">
</div>
<section class="footer__list__section">
</section>
<section class="footer__list__section">
</section>
<section class="footer__list__section">
</section>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74489932,
"author": "IAmSammy",
"author_id": 20539572,
"author_profile": "https://Stackoverflow.com/users/20539572",
"pm_score": 1,
"selected": false,
"text": "<section> <div class=\"footer__main__div\">\n <div class=\"footer__left__div\">\n </div>\n\n <div class=\"footer__right__div\">\n <section class=\"footer__list__section\">\n </section>\n\n <section class=\"footer__list__section\">\n </section>\n\n <section class=\"footer__list__section\">\n </section>\n </div>\n </div>\n"
},
{
"answer_id": 74490123,
"author": "tacoshy",
"author_id": 14072420,
"author_profile": "https://Stackoverflow.com/users/14072420",
"pm_score": 0,
"selected": false,
"text": "width: 100% .footer__main__div {\n display: flex;\n margin-left: auto;\n margin-right: auto;\n max-width: 1280px;\n flex-wrap: wrap;\n justify-content: space-between;\n padding-top: 2.5rem;\n padding-bottom: 2.5rem;\n padding-left: 1.25rem;\n padding-right: 1.25rem;\n}\n\n.footer__left__div {\n box-sizing: border-box;\n border: 2px dashed blue;\n width: 100%;\n}\n\nsection {\n box-sizing: border-box;\n width: 25%;\n border: 2px dashed green;\n} <div class=\"footer__main__div\">\n <div class=\"footer__left__div\">\n text\n </div>\n\n <section class=\"footer__list__section\">\n services\n </section>\n\n <section class=\"footer__list__section\">\n social\n </section>\n\n <section class=\"footer__list__section\">\n support\n </section>\n</div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20539455/"
] |
74,489,833
|
<p>I have the code below</p>
<pre><code>class Sample {
var variable1: SomeClass? = null
var variable2: SomeClass? = null
var variable3: SomeClass? = null
fun checkVariable() {
when {
variable1 != null -> variable1!!.doSomething()
variable2 != null -> variable2!!.doSomething()
variable3 != null -> variable3!!.doSomething()
}
}
}
</code></pre>
<p>I'm hoping I can make <code>variableX</code> after the <code>-></code> non-nullable, so I don't need to <code>!!</code>.
I can avoid <code>!!</code> with</p>
<pre><code>variable1 !== null -> variable1?.doSomething()
</code></pre>
<p>But is there away to do this more elegantly that I can have a non-nullable variable to access the <code>doSomething()</code>?</p>
|
[
{
"answer_id": 74489957,
"author": "Ivo",
"author_id": 1514861,
"author_profile": "https://Stackoverflow.com/users/1514861",
"pm_score": 1,
"selected": false,
"text": "fun getStrLength() = (variable1 ?: variable2 ?: variable3)?.doSomething()
\n !! fun getStrLengths() {
\n val variable1 = variable1\n val variable2 = variable2
\n val variable3 = variable3
\n when {
\n variable1 != null -> variable1.doSomething()
\n variable2 != null -> variable2.doSomething()
\n variable3 != null -> variable3.doSomething()
\n }\n}\n"
},
{
"answer_id": 74490048,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 2,
"selected": false,
"text": "when var (variable1 ?: variable2 ?: variable3)?.doSomething()\n doSomething variable1?.also {\n it.doSomething()\n} ?: variable2?.also {\n it.doSomethingElse()\n} ?: variable3?.also {\n it.doAnotherThing()\n}\n"
},
{
"answer_id": 74490162,
"author": "aSemy",
"author_id": 4161471,
"author_profile": "https://Stackoverflow.com/users/4161471",
"pm_score": 0,
"selected": false,
"text": "lateinit var isInitialized class Sample {\n lateinit var variable1: SomeClass\n lateinit var variable2: SomeClass\n lateinit var variable3: SomeClass\n\n fun checkVariable() {\n when {\n // so long as a value is initialised, there is no need for null checks\n ::variable1.isInitialized -> variable1.printName()\n ::variable2.isInitialized -> variable2.printName()\n ::variable3.isInitialized -> variable3.printName()\n }\n }\n}\n\nclass SomeClass(val name: String) {\n fun printName() {\n println(name)\n }\n}\n null val sample = Sample()\n\nsample.variable1 = SomeClass(\"foo\")\n\nsample.variable1 = null // ERROR: Null can not be a value of a non-null type SomeClass\n fun main() {\n\n val sample = Sample()\n\n println(\"first check:\")\n sample.checkVariable()\n println(\"---\")\n\n sample.variable3 = SomeClass(\"Jamie\")\n\n println(\"second check:\")\n sample.checkVariable()\n println(\"---\")\n\n sample.variable2 = SomeClass(\"Maddie\")\n\n println(\"third check:\")\n sample.checkVariable()\n println(\"---\")\n\n sample.variable1 = SomeClass(\"Lisa\")\n\n println(\"fourth check:\")\n sample.checkVariable()\n println(\"---\")\n}\n when first check:\n---\nsecond check:\nJamie\n---\nthird check:\nMaddie\n---\nfourth check:\nLisa\n---\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3286489/"
] |
74,489,851
|
<p>I am giving app name, icon, package name, hour, mint, sec to an array my major problem is I want to sort this array according to most used app</p>
<pre><code> appInfoList.add(AppInfo(appName, appIcon, packageName, hour, mint, sec))
appInfoList.sortBy { it.mint }
</code></pre>
<p>it didn't sort an array</p>
|
[
{
"answer_id": 74489957,
"author": "Ivo",
"author_id": 1514861,
"author_profile": "https://Stackoverflow.com/users/1514861",
"pm_score": 1,
"selected": false,
"text": "fun getStrLength() = (variable1 ?: variable2 ?: variable3)?.doSomething()
\n !! fun getStrLengths() {
\n val variable1 = variable1\n val variable2 = variable2
\n val variable3 = variable3
\n when {
\n variable1 != null -> variable1.doSomething()
\n variable2 != null -> variable2.doSomething()
\n variable3 != null -> variable3.doSomething()
\n }\n}\n"
},
{
"answer_id": 74490048,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 2,
"selected": false,
"text": "when var (variable1 ?: variable2 ?: variable3)?.doSomething()\n doSomething variable1?.also {\n it.doSomething()\n} ?: variable2?.also {\n it.doSomethingElse()\n} ?: variable3?.also {\n it.doAnotherThing()\n}\n"
},
{
"answer_id": 74490162,
"author": "aSemy",
"author_id": 4161471,
"author_profile": "https://Stackoverflow.com/users/4161471",
"pm_score": 0,
"selected": false,
"text": "lateinit var isInitialized class Sample {\n lateinit var variable1: SomeClass\n lateinit var variable2: SomeClass\n lateinit var variable3: SomeClass\n\n fun checkVariable() {\n when {\n // so long as a value is initialised, there is no need for null checks\n ::variable1.isInitialized -> variable1.printName()\n ::variable2.isInitialized -> variable2.printName()\n ::variable3.isInitialized -> variable3.printName()\n }\n }\n}\n\nclass SomeClass(val name: String) {\n fun printName() {\n println(name)\n }\n}\n null val sample = Sample()\n\nsample.variable1 = SomeClass(\"foo\")\n\nsample.variable1 = null // ERROR: Null can not be a value of a non-null type SomeClass\n fun main() {\n\n val sample = Sample()\n\n println(\"first check:\")\n sample.checkVariable()\n println(\"---\")\n\n sample.variable3 = SomeClass(\"Jamie\")\n\n println(\"second check:\")\n sample.checkVariable()\n println(\"---\")\n\n sample.variable2 = SomeClass(\"Maddie\")\n\n println(\"third check:\")\n sample.checkVariable()\n println(\"---\")\n\n sample.variable1 = SomeClass(\"Lisa\")\n\n println(\"fourth check:\")\n sample.checkVariable()\n println(\"---\")\n}\n when first check:\n---\nsecond check:\nJamie\n---\nthird check:\nMaddie\n---\nfourth check:\nLisa\n---\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16633017/"
] |
74,489,852
|
<p>I want this type container with curve border, please check attach images<a href="https://i.stack.imgur.com/xrfIv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xrfIv.png" alt="flutter continer" /></a></p>
<p>best solution of answer</p>
|
[
{
"answer_id": 74490237,
"author": "Sabahat Hussain Qureshi",
"author_id": 17901132,
"author_profile": "https://Stackoverflow.com/users/17901132",
"pm_score": 0,
"selected": false,
"text": "Clip Container border import 'package:flutter/material.dart';\n\nvoid main() => runApp(const MyApp());\n\nclass MyApp extends StatelessWidget {\n const MyApp({super.key});\n\n static const String _title = 'Flutter Code Sample';\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: _title,\n home: Scaffold(\n appBar: AppBar(title: const Text(_title)),\n body: const MyStatefulWidget(),\n ),\n );\n }\n}\n\nclass MyStatefulWidget extends StatefulWidget {\n const MyStatefulWidget({super.key});\n\n @override\n State<MyStatefulWidget> createState() => _MyStatefulWidgetState();\n}\n\nclass _MyStatefulWidgetState extends State<MyStatefulWidget> {\n @override\n Widget build(BuildContext context) {\n return Center(\n child: CustomPaint(\n painter: BorderPainter(),\n child: Container(\n height: 200,\n width: 400,\n child: Center(\n child: Padding(\n padding: EdgeInsets.symmetric(horizontal: 20),\n child: Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Text('Pakistan'),\n Spacer(),\n Text('VS'),\n Spacer(),\n Text('India'),\n ],\n ),\n )\n )\n ),\n ),\n );\n }\n}\n class BorderPainter extends CustomPainter {\n @override\n void paint(Canvas canvas, Size size) {\n Paint paint = Paint()\n ..style = PaintingStyle.stroke\n ..strokeWidth = 2\n ..color = Colors.pink;\n Path path0 = Path();\n path0.moveTo(size.width*0.4995083,size.height*0.2401000);\n path0.quadraticBezierTo(size.width*0.5840167,size.height*0.2406000,size.width*0.6666667,size.height*0.1420143);\n path0.lineTo(size.width*0.9996583,size.height*0.1441000);\n path0.lineTo(size.width,size.height);\n path0.lineTo(0,size.height);\n path0.lineTo(0,size.height*0.1422571);\n path0.lineTo(size.width*0.3358333,size.height*0.1442857);\n path0.quadraticBezierTo(size.width*0.4136083,size.height*0.2398857,size.width*0.4995083,size.height*0.2401000);\n path0.close();\n canvas.drawPath(path0, paint);\n }\n\n @override\n bool shouldRepaint(CustomPainter oldDelegate) => true;\n}\n"
},
{
"answer_id": 74490292,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": "paint class CustomShape extends ShapeBorder {\n @override\n EdgeInsetsGeometry get dimensions => EdgeInsets.zero;\n\n @override\n Path getInnerPath(Rect rect, {TextDirection? textDirection}) {\n return getInnerPath(rect);\n }\n\n @override\n Path getOuterPath(Rect rect, {TextDirection? textDirection}) {\n final double curveX = rect.width / 10;\n Path rectPath = Path()\n ..addRRect(RRect.fromRectAndRadius(rect, const Radius.circular(24)));\n\n Path curvePath = Path()\n ..moveTo(rect.center.dx - curveX, rect.top)\n ..quadraticBezierTo(\n rect.center.dx,\n rect.center.dy - curveX, //middle curve control\n rect.center.dx + curveX,\n rect.top,\n );\n\n return Path.combine(PathOperation.xor, rectPath, curvePath);\n }\n\n @override\n void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {\n canvas.drawPath(\n getOuterPath(rect),\n Paint()\n ..color = Colors.red\n ..style = PaintingStyle.stroke);\n }\n\n @override\n ShapeBorder scale(double t) => this;\n}\n child: Container(\n height: 200,\n width: 500,\n decoration: ShapeDecoration(\n shape: CustomShape(),\n ),\n),\n quadraticBezierTo"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20202688/"
] |
74,489,866
|
<p>I'm using a <code>@Composable</code> where I need to pass via parameter an <code>ImageBitmap</code>, the problem is that I get the images from the server given an url so I need to load these images, convert them into a <code>Bitmap</code> and then to a <code>ImageBitmap</code> but I'm quite stuck because I don't know how to convert this to an <code>ImageBitmap</code>, this is my <code>@Composable</code></p>
<pre><code>@ExperimentalComposeUiApi
@Composable
fun MyCanvas(
myImage: ImageBitmap,
modifier: Modifier = Modifier,
) {
Canvas(modifier = modifier
.size(220.dp)
.clipToBounds()
.clip(RoundedCornerShape(size = 16.dp)) {
...
val canvasWidth = size.width.toInt()
val canvasHeight = size.height.toInt()
val imageSize = IntSize(width = canvasWidth, height = canvasHeight)
drawImage(
image = myImage, dstSize = imageSize
)
...
}
}
</code></pre>
<p>So, when I call this <code>@Composable</code> I need to load the image but not sure how to start with and I need to know what's better either using Glide or Coil.</p>
|
[
{
"answer_id": 74491533,
"author": "Thracian",
"author_id": 5457853,
"author_profile": "https://Stackoverflow.com/users/5457853",
"pm_score": 4,
"selected": true,
"text": "androidx.compose.foundation.Canvas Modifier.drawBehind @Composable\nfun Canvas(modifier: Modifier, onDraw: DrawScope.() -> Unit) =\n Spacer(modifier.drawBehind(onDraw))\n @Composable\nprivate fun MyComposable() {\n val sizeModifier = Modifier\n .fillMaxWidth()\n\n val url =\n \"https://avatars3.githubusercontent.com/u/35650605?s=400&u=058086fd5c263f50f2fbe98ed24b5fbb7d437a4e&v=4\"\n\n Column(\n modifier =Modifier.fillMaxSize()\n ) {\n\n val painter = rememberAsyncImagePainter(\n model = url\n )\n\n Canvas(modifier = Modifier\n .clip(RoundedCornerShape(size = 16.dp))\n .size(220.dp)\n ) {\n with(painter) {\n draw(size = size)\n }\n }\n\n }\n}\n /**\n * Clip the content to the bounds of a layer defined at this modifier.\n */\n@Stable\nfun Modifier.clipToBounds() = graphicsLayer(clip = true)\n\n/**\n * Clip the content to [shape].\n *\n * @param shape the content will be clipped to this [Shape].\n */\n@Stable\nfun Modifier.clip(shape: Shape) = graphicsLayer(shape = shape, clip = true)\n"
},
{
"answer_id": 74492019,
"author": "Richard Onslow Roper",
"author_id": 15880865,
"author_profile": "https://Stackoverflow.com/users/15880865",
"pm_score": 2,
"selected": false,
"text": "Bitmap ImageBitmap asImageBitmap() rememberCoilPainter()"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4329781/"
] |
74,489,882
|
<p>For a school project I have to determine a function u(t) of time. I have derived an expression of the following form:</p>
<p><a href="https://i.stack.imgur.com/dVlz9.png" rel="nofollow noreferrer">(https://i.stack.imgur.com/vNrYb.png)</a></p>
<p>with a,b,c,d constants (not necessarily integers). I have figured out that this problem is only solvable with numerical integration with initial condition u(0)=u_0, yet I don't know how to do this particular problem.</p>
<p>I have looked at all the numerical integration methods I have learnt so far, but they all seem to apply for polynomials or for functions where you know the function evaluations at specific points.</p>
|
[
{
"answer_id": 74491533,
"author": "Thracian",
"author_id": 5457853,
"author_profile": "https://Stackoverflow.com/users/5457853",
"pm_score": 4,
"selected": true,
"text": "androidx.compose.foundation.Canvas Modifier.drawBehind @Composable\nfun Canvas(modifier: Modifier, onDraw: DrawScope.() -> Unit) =\n Spacer(modifier.drawBehind(onDraw))\n @Composable\nprivate fun MyComposable() {\n val sizeModifier = Modifier\n .fillMaxWidth()\n\n val url =\n \"https://avatars3.githubusercontent.com/u/35650605?s=400&u=058086fd5c263f50f2fbe98ed24b5fbb7d437a4e&v=4\"\n\n Column(\n modifier =Modifier.fillMaxSize()\n ) {\n\n val painter = rememberAsyncImagePainter(\n model = url\n )\n\n Canvas(modifier = Modifier\n .clip(RoundedCornerShape(size = 16.dp))\n .size(220.dp)\n ) {\n with(painter) {\n draw(size = size)\n }\n }\n\n }\n}\n /**\n * Clip the content to the bounds of a layer defined at this modifier.\n */\n@Stable\nfun Modifier.clipToBounds() = graphicsLayer(clip = true)\n\n/**\n * Clip the content to [shape].\n *\n * @param shape the content will be clipped to this [Shape].\n */\n@Stable\nfun Modifier.clip(shape: Shape) = graphicsLayer(shape = shape, clip = true)\n"
},
{
"answer_id": 74492019,
"author": "Richard Onslow Roper",
"author_id": 15880865,
"author_profile": "https://Stackoverflow.com/users/15880865",
"pm_score": 2,
"selected": false,
"text": "Bitmap ImageBitmap asImageBitmap() rememberCoilPainter()"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7827743/"
] |
74,489,906
|
<p>Let's take the following <code>pd.DataFrame</code></p>
<pre class="lang-py prettyprint-override"><code>>>> df = pd.DataFrame({
'M' : ['1', '1' , '3', '6', '6', '6'],
'col1': [None, 0.1, None, 0.2, 0.3, 0.4],
'col2': [0.01, 0.1, 1.3, None, None, 0.5]})
</code></pre>
<p>which creates</p>
<pre><code> M col1 col2
0 1 NaN 0.01
1 1 0.1 0.10
2 3 NaN 1.30
3 6 0.2 NaN
4 6 0.3 NaN
5 6 0.4 0.50
</code></pre>
<p>I would now like to have the missing rate percentage <strong>per month per column</strong>. The resulting table should look like this</p>
<pre><code>M col1 col2
1 50.0 0.0
3 100.0 0.0
6 0.0 66.6
</code></pre>
<p>where the values in the cells in <code>col1</code> and <code>col2</code> state the missing rates per month for the column.</p>
<p>How can I do this?</p>
|
[
{
"answer_id": 74489939,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "groupby.mean out = (df.drop(columns='M').isna() # check if the value is missing\n .groupby(df['M']) # for each M\n .mean().mul(100).round(2) # get the proportion x 100\n .reset_index() # index as column\n )\n M col1 col2\n0 1 50.0 0.00\n1 3 100.0 0.00\n2 6 0.0 66.67\n"
},
{
"answer_id": 74490200,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 1,
"selected": false,
"text": "df.set_index('M').isna().mean(level=0).mul(100).reset_index()\n M col1 col2\n0 1 50.0 0.0\n1 3 100.0 0.0\n2 6 0.0 66.7\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12052180/"
] |
74,489,915
|
<p>I would like to make an identity service with IdServer4 that outsources the 'authentication' part to Auth0 - Auth0 deals with Single Sign On and other stuff and does a great job - so no need to reinvent the wheel. But I would like to embed this in an identity server (pref. IdentityServer4), that handles authentication via Auth0 and handles authorization itself (claims and scopes) for users & machines.</p>
<p>Machines would acquire their token through the tokenClient via so-called Client Credentials (<a href="https://docs.identityserver.io/en/latest/quickstarts/1_client_credentials.html" rel="nofollow noreferrer">https://docs.identityserver.io/en/latest/quickstarts/1_client_credentials.html</a>).</p>
<pre><code>public static IEnumerable<Client> Clients =>
new List<Client>
{
new Client
{
ClientId = "client",
// no interactive user, use the clientid/secret for authentication
AllowedGrantTypes = GrantTypes.ClientCredentials,
// secret for authentication
ClientSecrets =
{
new Secret("secret".Sha256())
},
// scopes that client has access to
AllowedScopes = { "api1" }
}
};
</code></pre>
<p>The machine 2 machine auth works. But how can the identity server make sure that 'users' log in via Auth0 (SSO) and then get an access token from IdentityServer4 itself (just like the machines), instead of getting the token from Auth0 itself. I have implemented Auth0 as a external ID Provider:</p>
<pre><code> services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect("Auth0", options => {
options.Authority = "auth0domain";
options.ClientId = "clientId";
options.ClientSecret = "secret";
...
});
</code></pre>
<p>For the rest, see : <a href="https://auth0.com/blog/using-csharp-extension-methods-for-auth0-authentication/" rel="nofollow noreferrer">https://auth0.com/blog/using-csharp-extension-methods-for-auth0-authentication/</a></p>
<p>When triggering the Authentication via await HttpContext.ChallengeAsync(); the user can login. And afterwards he or she can logout. This works fine. But the user acquires an access token from Auth0 itself and I would like to replace it by a token generated by IdSrv4. Is this possible?</p>
|
[
{
"answer_id": 74489939,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "groupby.mean out = (df.drop(columns='M').isna() # check if the value is missing\n .groupby(df['M']) # for each M\n .mean().mul(100).round(2) # get the proportion x 100\n .reset_index() # index as column\n )\n M col1 col2\n0 1 50.0 0.00\n1 3 100.0 0.00\n2 6 0.0 66.67\n"
},
{
"answer_id": 74490200,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 1,
"selected": false,
"text": "df.set_index('M').isna().mean(level=0).mul(100).reset_index()\n M col1 col2\n0 1 50.0 0.0\n1 3 100.0 0.0\n2 6 0.0 66.7\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9084993/"
] |
74,489,927
|
<pre><code>function DatTable() {
return (
<DataTable
theme="dark"
columns={columns}
selectableRows
data={FakeData}
/>
);
};
</code></pre>
<p>I've called this component from another file in a dashboard</p>
<pre><code></Box>
<DatTable></DatTable>
</Box>
</code></pre>
<p>Everything works properly if I change the properties in the original function. What I'm trying to achieve is set a useTheme hook for the component and for that I want to edit the theme inside of the dashboard like so :</p>
<pre><code></Box>
<DatTable
theme="dark"
></DatTable>
</Box>
</code></pre>
<p>I've tried changing the properties inside of the dashboard component but it has no effects. I'm also unsure how to turn regular components into React components since the webpage goes white and breaks if I try it that way.</p>
|
[
{
"answer_id": 74489976,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": 1,
"selected": false,
"text": "// default data\nlet columns={};\nlet data={}\n\nfunction DatTable(theme=\"dark\", columns=columns, selectableRows='somedefaultdata',data=FakeData) {\n return (\n <DataTable\n theme=theme\n columns={columns}\n selectableRows\n data={FakeData}\n />\n );\n};\n\n <DatTable \n theme=\"white\"\n/>\n"
},
{
"answer_id": 74490114,
"author": "Marios",
"author_id": 20229075,
"author_profile": "https://Stackoverflow.com/users/20229075",
"pm_score": 1,
"selected": true,
"text": "<DatTable> <DataTable> function DatTable({theme}) {\n return (\n <DataTable\n theme={theme} \n columns={columns}\n selectableRows\n data={FakeData}\n />\n );\n};\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14902688/"
] |
74,489,958
|
<p>I want to use the rolling window function with "stride".<br />
That means, the step is still 1.<br />
But we can resample the index with a certain interval not only 1.<br />
Do you have any idea of this? Thanks a lot.</p>
<p>For example:</p>
<pre><code>df:
row0: 0
row1: 1
row2: 2
row3: 3
row4: 4
row5: 5
row6: 6
row7: 7
row8: 8
row9: 9
...
df1 = df.rolling(window=3, stride=3).sum() (where stride is not exist in pd.rolling)
df1:
row0: nan
row1: nan
row2: nan
row3: nan
row4: nan
row5: nan
row6: 9 (row6+row3+row0)
row7: 12 (row7+row4+row1)
row8: 15 (row8+row5+row2)
row9: 18 (row9+row6+row3)
...
</code></pre>
|
[
{
"answer_id": 74489976,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": 1,
"selected": false,
"text": "// default data\nlet columns={};\nlet data={}\n\nfunction DatTable(theme=\"dark\", columns=columns, selectableRows='somedefaultdata',data=FakeData) {\n return (\n <DataTable\n theme=theme\n columns={columns}\n selectableRows\n data={FakeData}\n />\n );\n};\n\n <DatTable \n theme=\"white\"\n/>\n"
},
{
"answer_id": 74490114,
"author": "Marios",
"author_id": 20229075,
"author_profile": "https://Stackoverflow.com/users/20229075",
"pm_score": 1,
"selected": true,
"text": "<DatTable> <DataTable> function DatTable({theme}) {\n return (\n <DataTable\n theme={theme} \n columns={columns}\n selectableRows\n data={FakeData}\n />\n );\n};\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19331465/"
] |
74,489,972
|
<p>I have a dataset that I've copy pasted into Excel and some numbers have spaces between them. This is subset of a column in the spreadsheet:</p>
<p><a href="https://i.stack.imgur.com/lzs0i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lzs0i.png" alt="enter image description here" /></a></p>
<p>As you can see in the 3rd, 4th, 5th, 9th and 10th rows there's some space between the characters that I want to delete.</p>
<p>Are there any good formulas here for this? I've tried the TRIM-function a couple times but it's only useable for strings. And a complementary note is that they are all treated as generals.</p>
|
[
{
"answer_id": 74490126,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 1,
"selected": false,
"text": "Replace() Substitute() Replace() Substitute() =SUBSTITUTE(C2,\" \",\"\")\n"
},
{
"answer_id": 74490134,
"author": "Ike",
"author_id": 16578424,
"author_profile": "https://Stackoverflow.com/users/16578424",
"pm_score": 1,
"selected": false,
"text": "=NUMBERVALUE(SUBSTITUTE(A1:A10,\" \",\"\"))"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13948427/"
] |
74,489,975
|
<p>I have Django apps, which include users and posts models. The apps work perfectly at local following making migrations and migrating. I tried two different ways to deploy the apps to Heroku. First, using Heroku Git, the apps works on Heroku the same as at local.</p>
<p>When using GitHub, however, all data were not brought to Heroku. I tried to run "python manage.py makemigrations" and "python manage.py migrate" on Heroku, but the data from local was not brought still.</p>
<p>I would really appreciate it if you could please explain and help with the issue using GitHub.</p>
|
[
{
"answer_id": 74490126,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 1,
"selected": false,
"text": "Replace() Substitute() Replace() Substitute() =SUBSTITUTE(C2,\" \",\"\")\n"
},
{
"answer_id": 74490134,
"author": "Ike",
"author_id": 16578424,
"author_profile": "https://Stackoverflow.com/users/16578424",
"pm_score": 1,
"selected": false,
"text": "=NUMBERVALUE(SUBSTITUTE(A1:A10,\" \",\"\"))"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13877145/"
] |
74,489,978
|
<p>Did anyone of You had the same problem as described below? If so, do you have any tip or solution for this?</p>
<p>I have a problem with my local environment. Every time I try to build the solution, a lot of its projects are being skipped and I receive many CS0006 errors: "Metadata file (...) could not be found".</p>
<p>Another thing I noticed is ribbon with message "Current solution contains incorrect configurations mappings. It may cause projects to not work correctly. Open the Configuration Manager to fix them." When I open Configuration Manager, all projects of solution are checked, and everything seems to be correct there.</p>
<p>I use Visual Studio 2022 (64-bit), version 17.4.1 and .NET Framework version 4.8.04084.</p>
<p>I tried almost all recommendations from the Internet, including uninstalling and installing again Visual Studio or reuploading of repository, but there is no update about this problem.</p>
<p>Thank You in advance.</p>
|
[
{
"answer_id": 74490126,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 1,
"selected": false,
"text": "Replace() Substitute() Replace() Substitute() =SUBSTITUTE(C2,\" \",\"\")\n"
},
{
"answer_id": 74490134,
"author": "Ike",
"author_id": 16578424,
"author_profile": "https://Stackoverflow.com/users/16578424",
"pm_score": 1,
"selected": false,
"text": "=NUMBERVALUE(SUBSTITUTE(A1:A10,\" \",\"\"))"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19667273/"
] |
74,489,979
|
<p>I want to fetch text from a div, but there are allot of duplicated classes. The only way to filter my search is by checking for a specific text within a sibling. Right now this is what I got:</p>
<pre><code>accountmanager = ()
def send_keys_in_loop_dropaccountmanager(locator):
for i in range(5):
try:
global accountmanager
test = wait.until(EC.element_to_be_clickable(locator)).text
print(test)
accountmanager = test
break
except:
pass
send_keys_in_loop_dropaccountmanager((By.XPATH, "//div[contains(@class,'ahoy-value')] and following-sibling::div[contains(text(),'Accountmanager')]"))
print("accountmanager:", accountmanager)
</code></pre>
<p>I get no response at all.</p>
<p>Google inspector code(text that I want selected in blue):```</p>
<p><a href="https://i.stack.imgur.com/4hRQm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4hRQm.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74490126,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 1,
"selected": false,
"text": "Replace() Substitute() Replace() Substitute() =SUBSTITUTE(C2,\" \",\"\")\n"
},
{
"answer_id": 74490134,
"author": "Ike",
"author_id": 16578424,
"author_profile": "https://Stackoverflow.com/users/16578424",
"pm_score": 1,
"selected": false,
"text": "=NUMBERVALUE(SUBSTITUTE(A1:A10,\" \",\"\"))"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74489979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15308268/"
] |
74,490,029
|
<p>I am currently trying to implement a tab feature using Angular Material. I can for the life of me not get the button to click that is in the header. I have tried moving the click event around the tabs and it doesn't seem to get triggered anywhere.</p>
<p>I am trying to add the functionality that you can close a tab by clicking on the close icon. I have tried putting it in a div. I've tried using a div instead of a button.</p>
<p>Here is the UI:</p>
<pre><code> <mat-tab-group animationDuration="0ms">
<div *ngIf="tabs">
<mat-tab *ngFor="let tab of tabs; let index = index" [ngSwitch]="tab.type">
<ng-template mat-tab-label>
<div style="display: flex; flex-direction: row; align-items: center;">
{{tab["title"]}}
<div>
<button style="color:black" mat-icon-button (click)="closeTab($event, index)">
<mat-icon>close</mat-icon>
</button>
</div>
</div>
</ng-template>
<div *ngSwitchCase="'Work'">
<p>Work</p>
</div>
<div *ngSwitchCase="'Case'">
<p>Case</p>
</div>
<div *ngSwitchCase="'Document'">
<app-base></app-base>
</div>
</mat-tab>
</div>
</mat-tab-group>
</div>
</code></pre>
<p>And the backend:</p>
<pre><code>import {MatTab, MatTabGroup} from '@angular/material/tabs';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent {
@ViewChild(MatTabGroup, {read: MatTabGroup})
public tabGroup: MatTabGroup;
@ViewChildren(MatTab, {read: MatTab})
public tabNodes: QueryList<MatTab>;
tabs: Tab[] = [];
workCounter: number = 0;
caseCounter: number = 0;
documentCounter: number = 0;
closedTabs: number[] = [];
ngOnInit(): void {
}
addNewTab(type: string): void {
let tab = new Tab();
switch (type) {
case 'Work':
this.workCounter++;
tab.type = type;
tab.title = `${type} # ${this.workCounter}`
break;
case 'Document':
this.documentCounter++;
tab.type = type;
tab.title = `${type} # ${this.documentCounter}`
break;
case 'Case':
this.caseCounter++;
tab.type = type;
tab.title = `${type} # ${this.caseCounter}`
break;
}
this.tabs.push(tab);
}
closeTab(event: Event, index: number) {
console.log(index);
event.stopPropagation();
this.closedTabs.push(index);
this.tabGroup.selectedIndex = this.tabNodes.length - 1;
console.log(index);
}
}
class Tab {
type: string;
title: string;
index: number;
}
</code></pre>
|
[
{
"answer_id": 74494813,
"author": "Mr. Stash",
"author_id": 13625800,
"author_profile": "https://Stackoverflow.com/users/13625800",
"pm_score": 3,
"selected": true,
"text": "<mat-tab-group animationDuration=\"0ms\" class=\"allow-tab-events\">\n</mat-tab-group>\n .allow-tab-events ::ng-deep .mdc-tab .mdc-tab__content{\n pointer-events: all;\n}\n"
},
{
"answer_id": 74556735,
"author": "Minute Illimitée",
"author_id": 10221789,
"author_profile": "https://Stackoverflow.com/users/10221789",
"pm_score": 0,
"selected": false,
"text": " .mdc-tab__content{\n pointer-events: all!important;\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8125309/"
] |
74,490,072
|
<p>I have a long-running bash script (like a daemon), which may emit output to both stdout and stderr.</p>
<p>I have these requirements:</p>
<ul>
<li>prepend every output line with a string (e.g. date, time of the log entry and other info)</li>
<li>redirect all output into a log file</li>
<li>output redirection must be real-time (i.e. log file must be filled while process is running)</li>
<li>the process needs to run in background</li>
</ul>
<p>This is what I've achieved so far:</p>
<pre><code>myscript="script_name"
log_file="/tmp/blabla"
prepend_info() {
xargs -d '\n' printf "$(date +'%b %d %T') $HOSTNAME $myscript: %s\n"
}
script -q -c "$myscript" /dev/null 2>&1 | prepend_info > "$log_file" 2>&1 &
</code></pre>
<p>The problem is that <strong>the log file gets filled only after my script has terminated</strong>, but I want to see output while it's running instead.</p>
<p>If I remove <code>|& prepend_info</code> it works as expected, but I need that additional info into the log file as well.</p>
<p>It seems like the pipe only gets executed after the first command terminates.</p>
<p>Is there some way to modify the output of a background script and redirect it into a file while it's running?</p>
<p>I need to be as compatible as possible, and I can only use simple bash commands. For example, I cannot use <code>ts</code> because it's not always available and also I don't need only the timestamp but other info as well.</p>
<p><strong>UPDATE</strong>: The only solution I found so far (it solves everything, also the issue with date) is the following.</p>
<pre><code>myscript="script_name"
log_file="/tmp/blabla"
exec_script() {
rm -f "$log_file"
local out_log=<($myscript 2>&1)
while read -r line; do
echo "$(date +'%b %d %T') $HOSTNAME $myscript: $line" >> $log_file
done < "$out_log"
}
exec_script &
</code></pre>
<p>If anyone has a better solution, I'm all ears.</p>
|
[
{
"answer_id": 74494813,
"author": "Mr. Stash",
"author_id": 13625800,
"author_profile": "https://Stackoverflow.com/users/13625800",
"pm_score": 3,
"selected": true,
"text": "<mat-tab-group animationDuration=\"0ms\" class=\"allow-tab-events\">\n</mat-tab-group>\n .allow-tab-events ::ng-deep .mdc-tab .mdc-tab__content{\n pointer-events: all;\n}\n"
},
{
"answer_id": 74556735,
"author": "Minute Illimitée",
"author_id": 10221789,
"author_profile": "https://Stackoverflow.com/users/10221789",
"pm_score": 0,
"selected": false,
"text": " .mdc-tab__content{\n pointer-events: all!important;\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2043589/"
] |
74,490,088
|
<p>Basically, I'm creating a really low tier cipher. I've set up a bit of code to randomize each character, but I can't figure out how to replace a string with these. This is the code I attempted</p>
<pre><code>characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", ".", ",", " ", "!", "?"]
characters2 = ['h', 'i', '.', 'u', 'o', 'x', 'q', 'b', 'y', 'z', 's', 'd', 'm', 'w', 'k', 'n', 'j', '?', 'a', 'v', 't', 'r', 'e', 'f', 'c', ' ', '!', 'l', 'g', 'p', ',']
string = string.replace(characters[],characters2[])
</code></pre>
<p>In this example I was basically expecting being able to input a string, such as "string" and get back the encrypted string, which in this case would come back as "av?ywq". The only other way I could think of working this out would basically be to write</p>
<pre><code>string = string.replace(characters[0],characters2[0]).replace(characters[1],characters2[1]).replace...
</code></pre>
<p>for the entire length of the list, which I could do, but it would be extremely tedious and take up way too much space.</p>
<p>Doing a loop would of course mean that if, for example, the "i" in "string" were replaced with an "s", and then the "s" in string were replaced with an "h", it would come out "htrhng", replacing both the "i" and "s" with the "h".</p>
<p>How would I go about solving this?</p>
|
[
{
"answer_id": 74490193,
"author": "StonedTensor",
"author_id": 6023918,
"author_profile": "https://Stackoverflow.com/users/6023918",
"pm_score": 1,
"selected": false,
"text": "old_character new_character character_mapping = {\"a\": \"h\", \"b\": \"i\" , ...} \n\nold_string = \"my old string\"\n\nnew_string = \"\"\n\nfor char in old_string:\n new_string += character_mapping[char]\n string"
},
{
"answer_id": 74490272,
"author": "Bharat Adhikari",
"author_id": 17731030,
"author_profile": "https://Stackoverflow.com/users/17731030",
"pm_score": 0,
"selected": false,
"text": "string = \"string\"\n\ncharacters = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \".\", \",\", \" \", \"!\", \"?\"]\ncharacters2 = ['h', 'i', '.', 'u', 'o', 'x', 'q', 'b', 'y', 'z', 's', 'd', 'm', 'w', 'k', 'n', 'j', '?', 'a', 'v', 't', 'r', 'e', 'f', 'c', ' ', '!', 'l', 'g', 'p', ',']\n \ndic = {} \nfor l1,l2 in zip(characters,characters2):\n dic[l1]=l2\n \nresult = \"\"\nfor letter in string:\n result = result + dic[letter]\nprint(result)\n\n#Output = av?ywq\n"
},
{
"answer_id": 74490303,
"author": "Johnny Mopp",
"author_id": 669576,
"author_profile": "https://Stackoverflow.com/users/669576",
"pm_score": 0,
"selected": false,
"text": "translate() import string\n\ncharacters = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \".\", \",\", \" \", \"!\", \"?\"]\ncharacters2 = ['h', 'i', '.', 'u', 'o', 'x', 'q', 'b', 'y', 'z', 's', 'd', 'm', 'w', 'k', 'n', 'j', '?', 'a', 'v', 't', 'r', 'e', 'f', 'c', ' ', '!', 'l', 'g', 'p', ',']\n\ntext = \"string\"\ntable = text.maketrans(dict(zip(characters, characters2)))\nprint(text.translate(table))\n av?ywq\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20539599/"
] |
74,490,096
|
<p>I am trying to produce a new column (Yrgroup) that puts individual years into 2year groups so:</p>
<pre><code>Yrs TS Yrgroup
2011 2 11/12
2011 2 11/12
2012 4 11/12
2012 8 11/12
2013 2 13/14
2013 1 13/14
2014 3 13/14
2014 7 13/14
</code></pre>
<pre><code>Yr = c(2011,2011,2012,2012,2013,2013,2014,2014)
Yr
Tranship = c(2,5,8,2,2,2,7,8)
df = data.frame(Yr, Tranship)
df
df$Yrgroup = NA
#library(dplyr)
df %>%
group_by(Yr+1)
</code></pre>
<p>This is what I have tried so far but I cannot fill in the year group column</p>
|
[
{
"answer_id": 74490180,
"author": "VvdL",
"author_id": 15589010,
"author_profile": "https://Stackoverflow.com/users/15589010",
"pm_score": 0,
"selected": false,
"text": "modulo 2 Yr = c(2011,2011,2012,2012,2013,2013,2014,2014)\nTranship = c(2,5,8,2,2,2,7,8)\ndf = data.frame(Yr, Tranship)\ndf$Yrgroup <- ifelse(df$Yr %%2 == 1, \n yes = paste(substr(df$Yr, 3, 4), \n as.numeric(substr(df$Yr, 3, 4)) + 1, \n sep = \"/\"), \n no = paste(as.numeric(substr(df$Yr, 3, 4)) - 1, \n substr(df$Yr, 3, 4), \n sep = \"/\"))\n\ndf\n#> Yr Tranship Yrgroup\n#> 1 2011 2 11/12\n#> 2 2011 5 11/12\n#> 3 2012 8 11/12\n#> 4 2012 2 11/12\n#> 5 2013 2 13/14\n#> 6 2013 2 13/14\n#> 7 2014 7 13/14\n#> 8 2014 8 13/14\n lubridate Yr = c(1999, 2000, 2011,2011,2012,2012,2013,2013,2014,2014)\nTranship = c(8,5,2,5,8,2,2,2,7,8)\ndf = data.frame(Yr, Tranship)\n\nlibrary(lubridate)\n\ndf$Yrgroup <- ifelse(df$Yr%%1000%%2 == 1, \n paste(substr(df$Yr, 3, 4),\n format(ymd(df$Yr*10000+101) + years(1), \"%y\"), \n sep = \"/\"), \n paste(format(ymd(df$Yr*10000+101) - years(1), \"%y\"),\n substr(df$Yr, 3, 4), \n sep = \"/\"))\ndf\n#> Yr Tranship Yrgroup\n#> 1 1999 8 99/00\n#> 2 2000 5 99/00\n#> 3 2011 2 11/12\n#> 4 2011 5 11/12\n#> 5 2012 8 11/12\n#> 6 2012 2 11/12\n#> 7 2013 2 13/14\n#> 8 2013 2 13/14\n#> 9 2014 7 13/14\n#> 10 2014 8 13/14\n"
},
{
"answer_id": 74490370,
"author": "langtang",
"author_id": 4447540,
"author_profile": "https://Stackoverflow.com/users/4447540",
"pm_score": 1,
"selected": false,
"text": "f <- function(y) if_else(y%%2==0, paste0(y-1,\"/\",y),paste0(y,\"/\",y+1))\n\nmutate(df, Yrsgroup = f(Yrs%%1000))\n Yrs TS Yrsgroup\n1: 2011 2 11/12\n2: 2011 2 11/12\n3: 2012 4 11/12\n4: 2012 8 11/12\n5: 2013 2 13/14\n6: 2013 1 13/14\n7: 2014 3 13/14\n8: 2014 7 13/14\n Yrs%%1000 mutate(df, Yrsgroup = f(as.numeric(substr(Yrs,3,4))))\n f() f <- function(y) {\n substr(if_else(y%%2==0, paste0(y-1,\"/\",substr(y,3,4)),paste0(y,\"/\",substr(y+1,3,4))),3,7)\n} \n\nmutate(df, Yrsgroup = f(Yrs)\n Yrs TS Yrsgroup\n1: 2000 2 99/00\n2: 2011 2 11/12\n3: 2012 4 11/12\n4: 2012 8 11/12\n5: 2013 2 13/14\n6: 2013 1 13/14\n7: 2014 3 13/14\n8: 2014 7 13/14\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13199109/"
] |
74,490,108
|
<p><strong>Scenario</strong>
I'm developing an API, the request header of the API will contain a Username and Password. We need to validate the username and password. We are using Keycloak IAM, but it's not configured with our wso2 EI setup.</p>
<p><strong>Question</strong>
My exact question is what's the best practice in wso2 EI to validate a username and password against IAM in the In-Sequence flow? Should we use DBLookup mediator or use send mediator for calling the authentication API of IAM?</p>
|
[
{
"answer_id": 74490656,
"author": "ycr",
"author_id": 2627018,
"author_profile": "https://Stackoverflow.com/users/2627018",
"pm_score": 2,
"selected": false,
"text": "Call Mediator Sequence"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7454536/"
] |
74,490,109
|
<p>How can I have the margin between two <code>td</code> elements?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
border: none;
}
table tr {
height: 40px;
}
table tr td:nth-child(2) {
margin-left: 30px;
width: 400px;
}
table tr td {
border-top: 1px solid #000;
color: #000;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tr>
<td>Gebäudetyp</td>
<td>Mall</td>
</tr>
<tr>
<td>Anzahl von Leuchten</td>
<td>450</td>
</tr>
<tr>
<td>Wattage alt</td>
<td>70 W</td>
</tr>
<tr>
<td>Betriebsstunden</td>
<td>6.500</td>
</tr>
<tr>
<td>Stromverbrauch/Jahr</td>
<td>290.000 KWh</td>
</tr>
<tr>
<td>Strompreis</td>
<td>55 Cent/KWh</td>
</tr>
<tr>
<td>Investition</td>
<td>155.203 Euro</td>
</tr>
</table></code></pre>
</div>
</div>
</p>
<p>if I add <code>padding-left: 30px</code> to the second element of <code>td</code> it gives padding, but I want to have gap between elements.</p>
<p>Desired output should be:</p>
<p><a href="https://i.stack.imgur.com/2iyAM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2iyAM.png" alt="output" /></a></p>
|
[
{
"answer_id": 74490156,
"author": "Lakruwan Pathirage",
"author_id": 12383492,
"author_profile": "https://Stackoverflow.com/users/12383492",
"pm_score": 1,
"selected": false,
"text": "table border-spacing table border-spacing table {\n border-spacing: 30px;\n}\n border-spacing table {\n border-spacing:Xvalue yValue;\n }\n Xvalue yValue"
},
{
"answer_id": 74490314,
"author": "Madan Bhandari",
"author_id": 3040180,
"author_profile": "https://Stackoverflow.com/users/3040180",
"pm_score": 1,
"selected": false,
"text": "border-spacing table table {\n border-spacing: 15px 0;\n margin: 0 -15px;\n overflow: hidden;\n}\n\n"
},
{
"answer_id": 74490331,
"author": "Johannes",
"author_id": 5641669,
"author_profile": "https://Stackoverflow.com/users/5641669",
"pm_score": 2,
"selected": false,
"text": "td:nth-child(2) {\n position: relative;\n left: 30px;\n}\n table {\n border: none;\n}\n\ntable tr {\n height: 40px;\n}\n\ntable tr td:nth-child(2) {\n width: 400px;\n}\n\ntable tr td {\n border-top: 1px solid #000;\n color: #000;\n}\ntd:nth-child(2) {\n position: relative;\n left: 30px;\n} <table>\n <tr>\n <td>Gebäudetyp</td>\n <td>Mall</td>\n </tr>\n <tr>\n <td>Anzahl von Leuchten</td>\n <td>450</td>\n </tr>\n <tr>\n <td>Wattage alt</td>\n <td>70 W</td>\n </tr>\n <tr>\n <td>Betriebsstunden</td>\n <td>6.500</td>\n </tr>\n <tr>\n <td>Stromverbrauch/Jahr</td>\n <td>290.000 KWh</td>\n </tr>\n <tr>\n <td>Strompreis</td>\n <td>55 Cent/KWh</td>\n </tr>\n <tr>\n <td>Investition</td>\n <td>155.203 Euro</td>\n </tr>\n</table>"
},
{
"answer_id": 74491700,
"author": "Nijat Mursali",
"author_id": 10489887,
"author_profile": "https://Stackoverflow.com/users/10489887",
"pm_score": 1,
"selected": true,
"text": "table div flex .content {\n display: flex;\n}\n\n.content .left .element,\n.content .right .element {\n border-top: 1px solid #000000;\n}\n\n.content .left .element:last-child,\n.content .right .element:last-child {\n border-bottom: 1px solid #000;\n}\n.content .left {\n margin-right: 15px;\n}\n\n.content .right {\n width: 400px;\n}\n\n.content .left p,\n.content .right p {\n font-size: 19px;\n} <div class=\"content\">\n <div class=\"left\">\n <div class=\"element\">\n <p>Gebäudetyp</p>\n </div>\n <div class=\"element\">\n <p>Anzahl von Leuchten</p>\n </div>\n <div class=\"element\">\n <p>Wattage alt</p>\n </div>\n <div class=\"element\">\n <p>Betriebsstunden</p>\n </div>\n <div class=\"element\">\n <p>Stromverbrauch/Jahr</p>\n </div>\n <div class=\"element\">\n <p>Strompreis</p>\n </div>\n <div class=\"element\">\n <p>Investition</p>\n </div>\n </div>\n <div class=\"right\">\n <div class=\"element\">\n <p>Mall</p>\n </div>\n <div class=\"element\">\n <p>450</p>\n </div>\n <div class=\"element\">\n <p>70 W</p>\n </div>\n <div class=\"element\">\n <p>6.500</p>\n </div>\n <div class=\"element\">\n <p>290.000 KWh</p>\n </div>\n <div class=\"element\">\n <p>55 Cent/KWh</p>\n </div>\n <div class=\"element\">\n <p>155.203 Euro</p>\n </div>\n </div>\n </div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15488181/"
] |
74,490,139
|
<p>I tried writing an algorithm that prints the k largest elemtns of a max heap but I cannot do it in the right complexity.</p>
<p>This is the Pseudo-code I wrote-</p>
<pre><code>Print_k_largest(A[1,…,n],k):
If k>Heapsize(A):Error
i=1
insert[B,A[i])
print(B[1])
k-=1
While k>0:
if 2*i< Heapsize(A):
Insert(B,A[2*i])
Insert(B,A[2*i+1])
elif 2*i= Heapsize(A):
Insert(B,A[2*i])
B[1]=B[Heapsize(B)]
Heapsize(B)-=1
Max-Heapify(B,1)
print(B[1])
i=Binary_search(A[1,…,n],B[1])
k-=1
</code></pre>
<p><a href="https://i.stack.imgur.com/eOFgQ.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>In this solution I create a new max heap based on the original one, so that its size is always smaller than K hence the complexity of max-heapify and other such functions is O(klogk) and not O(klogN) as I was requested to do.
This Pseudocode is based on the solution suggested <a href="https://stackoverflow.com/a/32558705/20539707">here</a>.</p>
<p>The idea is like this- because it's a max heap the largest element is the root, the second largest element is one of the root's son, the third one is either the other son or the sons of the current largest one and so on. In each iteration I insert the sons of the former largest (the one I printed before), remove the former largest, Max-heapify (to make the heap a max heap again, hence the root is the newest largest) and print the newest largest (newest root).
The principle in this brilliant solution (unfortuantely not mine haha) is to do all the changes on a second heap whose size is always smaller than K (because in each of the k iterations we add maximum 2 new elements and remove one) so that the runtime for actions like max-heapify is O(logk) and not O(logn).
The thing is that to add the sons of the current largest I need an acess to its location (index) on the original tree! I don't know how to do it without it costing logn and runing everything.</p>
<p>I would appreaciate any help.</p>
|
[
{
"answer_id": 74492229,
"author": "Edward Peters",
"author_id": 6016064,
"author_profile": "https://Stackoverflow.com/users/6016064",
"pm_score": 1,
"selected": false,
"text": "A B A B B A A Node(value : int, left : Option[Node], right : Option[Node])\n value B MetaNode(value : Node, left : Option[MetaNode], right : Option[MetaNode])\n value.value MetaNode(A.head) for i in range 0..k-1:\n current = B.pop.value\n B.push (current.left) //might be None, should be coded so this is a no-op\n B.push (current.right) //see above\n results.add(current.value)\n"
},
{
"answer_id": 74492277,
"author": "btilly",
"author_id": 585411,
"author_profile": "https://Stackoverflow.com/users/585411",
"pm_score": 1,
"selected": false,
"text": "Append Swap SiftDown Swap HeapInsert Append SiftDown SiftUp SiftDown HeapPop Swap SiftUp Print_k_largest(A[1,…,n],k):\n\nIf k>Heapsize(A):Error\ni=1\nHeapInsert[B,pointer to A[i]])\n\nWhile k>0:\n if 2*i< Heapsize(A):\n HeapInsert(B,pointer to A[2*i])\n HeapInsert(B,pointer to A[2*i+1])\n\n elif 2*i= Heapsize(A):\n HeapInsert(B,pointer to A[2*i])\n\n PtrToElement = HeapPop(B) \n print(PtrToElement.value) \n k-=1\n & * A i j A[i] A[j] A (A[i], i)"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20539707/"
] |
74,490,151
|
<p>Hi I'm wondering what is the fastest, most easy way to AddOrUpdate data in a Pandas DataFrame</p>
<pre><code>import pandas as pd
# Original DataFrame
pd.DataFrame([
{'A':'a1','B':'b1','C':'c1'},
{'A':'a3','B':'b2','C':'c2'},
{'A':'a3','B':'b3','C':'c3'},
])
Original DataFrame :
A B C
0 a1 b1 c1
1 a3 b2 c2
2 a3 b3 c3
# A List of changes
changes = [
{'id':0, 'A':'aNEW','C':'cNEW'},
{'id':2, 'B':'bNEW'},
{'id':3, 'A':'aNEW','C':'cNEW'}},
]
# HOW TO ?
df.UpdateOrAdd(changes)
Resulting DataFrame :
A B C
0 aNEW b1 cNEW
1 a3 b2 c2
2 a3 bNEW c3
3 aNEW None cNEW
</code></pre>
<p>AddOrUpdate a Pandas DataFrame with a list of changes</p>
|
[
{
"answer_id": 74490190,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "DataFrame reindex combine_first df2 = pd.DataFrame(changes).set_index('id')\n\nout = (df2.reindex(df.index.union(df2.index))\n .combine_first(df)\n )\n A B C\n0 aNEW b1 cNEW\n1 a3 b2 c2\n2 a3 bNEW c3\n3 aNEW NaN cNEW\n def AddOrUpdate(self, other):\n if not isinstance(other, pd.DataFrame):\n other = pd.DataFrame(other)\n other = other.set_index('id')\n return (other.reindex(self.index.union(other.index))\n .combine_first(df)\n )\n\npd.DataFrame.AddOrUpdate = AddOrUpdate\n\nout = df.AddOrUpdate(changes)\n"
},
{
"answer_id": 74490256,
"author": "ThePyGuy",
"author_id": 9136348,
"author_profile": "https://Stackoverflow.com/users/9136348",
"pm_score": 0,
"selected": false,
"text": ".loc df.loc[df.shape[0]] = ['aNEW', None, 'cNEW']\n\n#df\nA B C\n0 a1 b1 c1\n1 a3 b2 c2\n2 a3 b3 c3\n3 aNEW None cNEW\n None None NaN df.loc[df.shape[0]] = {'A': 'aNew+', 'C': 'cNew+'}\n\n#df\nA B C\n0 a1 b1 c1\n1 a3 b2 c2\n2 a3 b3 c3\n3 aNew+ NaN cNew+\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7649785/"
] |
74,490,171
|
<p>I've been reading alot and to be honest haven't seen any meaningful solution.
So i have a component which contains a button and a dropdown to display some content (another buttons in this scenario).</p>
<p>Kebab button component:</p>
<pre><code><button>some button displaying dropdown<button>
<app-dropdown-component>
<ul>
<ng-content></ng-content>
</ul>
</app-dropdown-component>
</code></pre>
<p>It looks like this. As ng-content i'm providing a list items in a different components.
The thing is that i want to hide this button when no list items are provided.
Have tried using #ref on a item and then</p>
<pre><code>@ViewChild('ref') items: ElementRef;
</code></pre>
<p>and then check in ngAfterViewInit</p>
<pre><code>this.showButton = this.items.nativeElement && this.items.nativeElement.children.length > 0
</code></pre>
<p>also with .detectChanges();</p>
<p>but it usually says 'cannot read property 'nativeElement' of undefined.
Is there any simple way to hide my button when there are no elements provided by ng-content?
Also i can't use *ngIf on my button so looking for a different way.
I could also accept an solution from a children perspective:</p>
<pre><code><app-kebab-button-component>
<li *ngIf="something">Something</li>
</app-kebab-button-component>
</code></pre>
<p>So i show kebab-button-component only if there is any <code><li></code> provided due to a *ngIf statement.</p>
<p>Im running angular 12</p>
|
[
{
"answer_id": 74490190,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "DataFrame reindex combine_first df2 = pd.DataFrame(changes).set_index('id')\n\nout = (df2.reindex(df.index.union(df2.index))\n .combine_first(df)\n )\n A B C\n0 aNEW b1 cNEW\n1 a3 b2 c2\n2 a3 bNEW c3\n3 aNEW NaN cNEW\n def AddOrUpdate(self, other):\n if not isinstance(other, pd.DataFrame):\n other = pd.DataFrame(other)\n other = other.set_index('id')\n return (other.reindex(self.index.union(other.index))\n .combine_first(df)\n )\n\npd.DataFrame.AddOrUpdate = AddOrUpdate\n\nout = df.AddOrUpdate(changes)\n"
},
{
"answer_id": 74490256,
"author": "ThePyGuy",
"author_id": 9136348,
"author_profile": "https://Stackoverflow.com/users/9136348",
"pm_score": 0,
"selected": false,
"text": ".loc df.loc[df.shape[0]] = ['aNEW', None, 'cNEW']\n\n#df\nA B C\n0 a1 b1 c1\n1 a3 b2 c2\n2 a3 b3 c3\n3 aNEW None cNEW\n None None NaN df.loc[df.shape[0]] = {'A': 'aNew+', 'C': 'cNew+'}\n\n#df\nA B C\n0 a1 b1 c1\n1 a3 b2 c2\n2 a3 b3 c3\n3 aNew+ NaN cNew+\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17947665/"
] |
74,490,177
|
<p>The following code causes CS0266 in Visual Studio:</p>
<pre><code>double x = 1.23;
int y = x;
</code></pre>
<p>But the following code compiles in Visual Studio, and causes an implicit cast double to int:</p>
<pre><code>double x = 0;
ReadOnlyCollection<double> y = new ReadOnlyCollection<double>(new double[3] { 1.23, 2.34, 3.45 });
foreach (int z in y)
{
x += z;
}
</code></pre>
<p>Why is this treated differently? Can I cause compilation to fail?</p>
<p>I expect that an implicit cast to int when looping over an IEnumerable, would cause the same error as when casting a double to an int.</p>
|
[
{
"answer_id": 74490220,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 3,
"selected": false,
"text": "foreach object[] things = ...\n\nforeach(string s in things)\n{\n // ...\n}\n foreach (V v in x) embedded-statement\n E e = ((C)(x)).GetEnumerator();\ntry {\n V v;\n while (e.MoveNext()) {\n v = (V)(T)e.Current;\n embedded-statement\n }\n}\nfinally {\n … // Dispose e\n}\n double d = 123.45;\nint i = (int) d;\n"
},
{
"answer_id": 74490323,
"author": "Diego",
"author_id": 20478349,
"author_profile": "https://Stackoverflow.com/users/20478349",
"pm_score": -1,
"selected": false,
"text": "//here you need a cast\ndouble x = 1.23;\nint y = (int)x; //explicit cast\n int x = 0;\nReadOnlyCollection<double> y = new ReadOnlyCollection<double>(new double[3] {1.23, 2.34, 3.45 });\n// the z variable is to get the int in the y list, like a hidden cast\nforeach (int z in y)\n{\n x += z;\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14502272/"
] |
74,490,235
|
<p>Question: I am trying to validate email endings in an array</p>
<pre class="lang-js prettyprint-override"><code>let input = 'test@gmail.com' // This is grabbed dynamically but for sake of explanation this works the same
let validEndings = ['@gmail.com', '@mail.com', '@aol.com'] //and so on
if(input.endsWith(validEndings)){
console.log('valid')
}else{
console.log('invalid')
}
</code></pre>
<p>I can get this to work when validEndings is just a singular string e.g <code>let validEndings = '@gmail.com'</code>
but not when its in an array comparing multiple things</p>
|
[
{
"answer_id": 74490321,
"author": "birim",
"author_id": 18724350,
"author_profile": "https://Stackoverflow.com/users/18724350",
"pm_score": 2,
"selected": true,
"text": "const input = 'test@gmail.com';\nconst validEndingsRegex = /@gmail.com$|@mail.com$|@aol.com$/g;\nconst found = input.match(validEndingsRegex);\n\nif (found !== null) {\n console.log('valid')\n} else {\n console.log('invalid')\n}"
},
{
"answer_id": 74491160,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 0,
"selected": false,
"text": "Array.some() let input = 'test@gmail.com';\n\nlet validEndings = ['@gmail.com', '@mail.com', '@aol.com'];\n\nconst res = validEndings.some(endingStr => input.endsWith(endingStr));\n\nconsole.log(res);"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19317879/"
] |
74,490,264
|
<p>Week # 1 2 3 4 5</p>
<p>Ratio 0.9 0.9 0.8 0.8 0.6</p>
<p>Select week from Drop Down List ____ (we have 1,2,3,4,5 inside)</p>
<p>So how can we use index,match,product or other excel formulas for performing the following task:</p>
<p>If 3 is selected from the dropdown list, then we multiply 0.9<em>0.9</em>0.8</p>
<p>If 2 is selected from dropdown list, then we multiply 0.9*0.9</p>
<p>Can you please help?</p>
<p>I could not find how to use index match or this</p>
|
[
{
"answer_id": 74490321,
"author": "birim",
"author_id": 18724350,
"author_profile": "https://Stackoverflow.com/users/18724350",
"pm_score": 2,
"selected": true,
"text": "const input = 'test@gmail.com';\nconst validEndingsRegex = /@gmail.com$|@mail.com$|@aol.com$/g;\nconst found = input.match(validEndingsRegex);\n\nif (found !== null) {\n console.log('valid')\n} else {\n console.log('invalid')\n}"
},
{
"answer_id": 74491160,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 0,
"selected": false,
"text": "Array.some() let input = 'test@gmail.com';\n\nlet validEndings = ['@gmail.com', '@mail.com', '@aol.com'];\n\nconst res = validEndings.some(endingStr => input.endsWith(endingStr));\n\nconsole.log(res);"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14806128/"
] |
74,490,315
|
<p>Add added audio to my simple website and when i first click the button the audio does not play. After the second click it will play. If I wait a while then the problem will return.</p>
<p>There are no errors in the console and I even see chromes speaker icon on the tab but hear nothing.</p>
<pre><code></code></pre>
<p>Play</p>
<pre><code><script src="index.js"></script>
<script type="text/javascript">
// play audio on button click
document.getElementById('play').addEventListener('click', function () {
var audio = new Audio()
audio.src = '1.ogg'
// listen for can play event
audio.addEventListener('canplay', function () {
audio.play()
})
});
</script>
</code></pre>
<pre><code></code></pre>
<p>I also tried howler.js but the same problem happened.</p>
|
[
{
"answer_id": 74490321,
"author": "birim",
"author_id": 18724350,
"author_profile": "https://Stackoverflow.com/users/18724350",
"pm_score": 2,
"selected": true,
"text": "const input = 'test@gmail.com';\nconst validEndingsRegex = /@gmail.com$|@mail.com$|@aol.com$/g;\nconst found = input.match(validEndingsRegex);\n\nif (found !== null) {\n console.log('valid')\n} else {\n console.log('invalid')\n}"
},
{
"answer_id": 74491160,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 0,
"selected": false,
"text": "Array.some() let input = 'test@gmail.com';\n\nlet validEndings = ['@gmail.com', '@mail.com', '@aol.com'];\n\nconst res = validEndings.some(endingStr => input.endsWith(endingStr));\n\nconsole.log(res);"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15377471/"
] |
74,490,342
|
<p>Given the following JSON snippet</p>
<pre><code>{
"count": 4,
"checks":
[ {
"id": "8299393",
"name": "NEW_CUSTOMER",
"statusCode": "495"
},
{
"id": "4949449",
"name": "EXISTING_CUSTOMER",
"statusCode": "497"
}
//Further values here
]
}
</code></pre>
<p>...how can I used Javascript to retrieve the <code>id</code> value <code>4949449</code> when I need to be sure it corresponds to the <code>"name":"EXISTING_CUSTOMER"</code> k/v pair as they are not ordered so I cannot use <code>res.id[0]</code> ?</p>
<pre><code>//retrieve data via api call and read response into a const
const res = await response.json();
//get the id value 4949449 which corresponds to the sibling name whos value is 'EXISTING_CUSTOMER'
const existingCustId = res.checks.name["EXISTING_CUSTOMER"].id; //doesn't work
</code></pre>
|
[
{
"answer_id": 74490408,
"author": "Harun Yilmaz",
"author_id": 1331040,
"author_profile": "https://Stackoverflow.com/users/1331040",
"pm_score": 2,
"selected": true,
"text": "EXISTING_CUSTOMER Array.find() const data = {\n \"count\": 4,\n \"checks\": \n [ {\n \"id\": \"8299393\",\n \"name\": \"NEW_CUSTOMER\",\n \"statusCode\": \"495\"\n },\n\n {\n \"id\": \"4949449\",\n \"name\": \"EXISTING_CUSTOMER\",\n \"statusCode\": \"497\"\n }\n //Further values here\n ]\n}\n\nconst existingUserID = data.checks.find(i => i.name === \"EXISTING_CUSTOMER\").id\n\nconsole.log(existingUserID) Array.filter() const data = {\n \"count\": 4,\n \"checks\": \n [ {\n \"id\": \"8299393\",\n \"name\": \"NEW_CUSTOMER\",\n \"statusCode\": \"495\"\n },\n\n {\n \"id\": \"4949449\",\n \"name\": \"EXISTING_CUSTOMER\",\n \"statusCode\": \"497\"\n },\n {\n \"id\": \"5656565656\",\n \"name\": \"EXISTING_CUSTOMER\",\n \"statusCode\": \"497\"\n }\n //Further values here\n ]\n}\n\nconst existingUsers = data.checks.filter(i => i.name === \"EXISTING_CUSTOMER\")\n\nconsole.log(existingUsers.map(i => i.id))"
},
{
"answer_id": 74490431,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 0,
"selected": false,
"text": "const obj={\n\"count\": 4,\n\"checks\": \n[ {\n \"id\": \"8299393\",\n \"name\": \"NEW_CUSTOMER\",\n \"statusCode\": \"495\"\n },\n\n {\n \"id\": \"4949449\",\n \"name\": \"EXISTING_CUSTOMER\",\n \"statusCode\": \"497\"\n }\n //Further values here\n]\n}\n\n\nconsole.log(obj.checks.find(e=>e.name==\"EXISTING_CUSTOMER\").id)"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1461517/"
] |
74,490,376
|
<p>I'm facing an issue with my ec2 instance. Until now, I had an ec2 instance working with an IP like this: ec2-xx-xxx-xxx-xxx.compute-1.amazonaws.com.</p>
<p>Now I configured an elastic IP to make that instead of use the default domain uses one of my own.</p>
<p>Something goes wrong because now a receive a 403 if I make a request pointing to my new domain.</p>
<p>I'm check that I'm still able to connect to my Ubuntu server 20.04 LTS through SSH. Only have to change the host name to my new domain.(I'm using PuTTy)</p>
<p>Searching on internet if found that the problem can be that my machine still have the old domain in some config files. I don't have experience with Ubuntu servers. I try to find the http.conf file or the apache2 directory in etc., but no one is present.....
I don't know what to do next.</p>
<p>I have to change some configuration file? In that case, which one?</p>
<p>I leave you some images from my machine:</p>
<ul>
<li>Root
<a href="https://i.stack.imgur.com/KYfnj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KYfnj.png" alt="enter image description here" /></a></li>
<li>etc folder
<a href="https://i.stack.imgur.com/YouSw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YouSw.png" alt="enter image description here" /></a></li>
</ul>
<p>For further information, the security group of my ec2 instance have these rules:</p>
<p><a href="https://i.stack.imgur.com/rbAtT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rbAtT.png" alt="enter image description here" /></a></p>
<p>Any help will be appreciated. Thanks</p>
<p>-EDIT
I'm trying to access the server, making a request, with Postman like this.<a href="https://i.stack.imgur.com/V2kr8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V2kr8.png" alt="enter image description here" /></a></p>
<p>And that is the error:
<a href="https://i.stack.imgur.com/RqJ5B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RqJ5B.png" alt="enter image description here" /></a></p>
<p>For more information. I implemented my ec2 using this video:<a href="https://www.youtube.com/watch?v=XwAKI3UkfWk&list=PL4bT56Uw3S4w8jmW88-F_bgTQommKsHte&index=3&ab_channel=LuigiCode" rel="nofollow noreferrer">ec2 video</a>
And I changed the domain with that video:<a href="https://www.youtube.com/watch?v=VedY6EjOBWM&ab_channel=Javapocalypse" rel="nofollow noreferrer">link ec2 with namecheap domain</a></p>
|
[
{
"answer_id": 74495184,
"author": "John Rotenstein",
"author_id": 174777,
"author_profile": "https://Stackoverflow.com/users/174777",
"pm_score": 0,
"selected": false,
"text": "bochogame.com A-Record"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12479599/"
] |
74,490,425
|
<p>why can't i change innerHTML</p>
<pre><code><html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>document</title>
<style>
</style>
</head>
<body>
<div class="sa"></div>
<script>
var a = document.getElementsByClassName("sa").innerHTML;
a = "hi";
console.log(a);
</script>
</body>
</html>
</code></pre>
<p>output :
<a href="https://i.stack.imgur.com/eyHLG.png" rel="nofollow noreferrer">output</a></p>
<p>i can't even see the code snippets:
<a href="https://i.stack.imgur.com/xZcFC.png" rel="nofollow noreferrer">code snippets-1</a>,
<a href="https://i.stack.imgur.com/SiWdg.png" rel="nofollow noreferrer">code snippets-2</a></p>
<p>where is wrong in this code?,I searched but couldn't find the result I wanted, I'm not even sure I'm asking the right question, it happens every time I see an example but not when I do,i scare of stop myself in the start.</p>
<p>I'm trying to write hi to the div and check the hi in the console as a result I can't see what I'm typing on the page but I see it in the console</p>
|
[
{
"answer_id": 74495184,
"author": "John Rotenstein",
"author_id": 174777,
"author_profile": "https://Stackoverflow.com/users/174777",
"pm_score": 0,
"selected": false,
"text": "bochogame.com A-Record"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20539168/"
] |
74,490,444
|
<p>I have HTML file:</p>
<p>1.html</p>
<pre><code>!DOCTYPE html>
<html>
<head>
<title>Password Reminder</title>
</head>
<body>
<p>
Dear user, your password expires in: <strong>$($days)</strong> days.
</p>
</body>
</html>
</code></pre>
<p>I created function which reads file content and replace <code>$days</code> variable with actual variable value.</p>
<pre><code>function ReadTemplate($days) {
$template_content = Get-Content "C:\PasswordReminder\1.html" -Encoding UTF8 -Raw
#$template_content = [IO.File]::ReadAllText($template)
$template_content = $template_content -replace "{}",$days
return $template_content
}
</code></pre>
<p>But when calling it</p>
<pre><code>$content = ReadTemplate -days 2
</code></pre>
<p>Instead of Dear user, your password expires in: 2 days.</p>
<p>I'm getting</p>
<p>Dear user, your password expires in: <strong>$($days)</strong> days.</p>
<p>Instead of <code>$($days)</code> specified <code>{0}</code> but nothing</p>
|
[
{
"answer_id": 74490732,
"author": "frankM_DN",
"author_id": 20034020,
"author_profile": "https://Stackoverflow.com/users/20034020",
"pm_score": 3,
"selected": true,
"text": "$template_content = $template_content.replace('$($days)',$days)"
},
{
"answer_id": 74490824,
"author": "Sirwan Afifi",
"author_id": 1646540,
"author_profile": "https://Stackoverflow.com/users/1646540",
"pm_score": 1,
"selected": false,
"text": "Escape $template_content -replace ([regex]::Escape('$($days)')), $days\n"
},
{
"answer_id": 74491505,
"author": "iRon",
"author_id": 1701026,
"author_profile": "https://Stackoverflow.com/users/1701026",
"pm_score": 1,
"selected": false,
"text": "$($days) $Days = 17\n$ExecutionContext.InvokeCommand.ExpandString($template_content)\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11255078/"
] |
74,490,465
|
<p>My previous deployments with same github workflow file were successful.
Suddenly today, I get this error in Github Actions while trying to deploy.</p>
<p>May I know how to fix this?</p>
<pre><code>Run google-github-actions/setup-gcloud@v0
24
/usr/bin/tar xz --warning=no-unknown-keyword --overwrite -C /home/runner/work/_temp/fa0cd935-fe7e-4593-8662-69259b4b00a0 -f /home/runner/work/_temp/52901a76-e32d-4cdf-92e4-83836f8c5362
25
Warning: "service_account_key" has been deprecated. Please switch to using google-github-actions/auth which supports both Workload Identity Federation and Service Account Key JSON authentication. For more details, see https://github.com/google-github-actions/setup-gcloud#authorization
26
Error: google-github-actions/setup-gcloud failed with: failed to execute command `gcloud --quiet auth activate-service-account *** --key-file -`: /opt/hostedtoolcache/gcloud/270.0.0/x64/lib/googlecloudsdk/core/console/console_io.py:544: SyntaxWarning: "is" with a literal. Did you mean "=="?
27
if answer is None or (answer is '' and default is not None):
28
/opt/hostedtoolcache/gcloud/270.0.0/x64/lib/third_party/ipaddress/__init__.py:1106: SyntaxWarning: 'str' object is not callable; perhaps you missed a comma?
29
raise TypeError("%s and %s are not of the same version" (a, b))
30
ERROR: gcloud failed to load: module 'collections' has no attribute 'MutableMapping'
31
gcloud_main = _import_gcloud_main()
32
import googlecloudsdk.gcloud_main
33
from googlecloudsdk.calliope import base
34
from googlecloudsdk.calliope import display
35
from googlecloudsdk.calliope import display_taps
36
from googlecloudsdk.core.resource import resource_printer_base
37
from googlecloudsdk.core.resource import resource_projector
38
from google.protobuf import json_format as protobuf_encoding
39
from google.protobuf import symbol_database
40
from google.protobuf import message_factory
41
from google.protobuf import reflection
42
from google.protobuf.internal import python_message as message_impl
43
from google.protobuf.internal import containers
44
MutableMapping = collections.MutableMapping
45
46
This usually indicates corruption in your gcloud installation or problems with your Python interpreter.
47
48
Please verify that the following is the path to a working Python 2.7 executable:
49
/usr/bin/python
50
51
If it is not, please set the CLOUDSDK_PYTHON environment variable to point to a working Python 2.7 executable.
52
53
If you are still experiencing problems, please reinstall the Cloud SDK using the instructions here:
54
https://cloud.google.com/sdk/
</code></pre>
|
[
{
"answer_id": 74491684,
"author": "user3665224",
"author_id": 3665224,
"author_profile": "https://Stackoverflow.com/users/3665224",
"pm_score": 3,
"selected": true,
"text": "uses: google-github-actions/setup-gcloud@v0 - run: |\n sudo apt-get install python2.7\n export CLOUDSDK_PYTHON=\"/usr/bin/python2\"\n"
},
{
"answer_id": 74562526,
"author": "strada",
"author_id": 808516,
"author_profile": "https://Stackoverflow.com/users/808516",
"pm_score": 1,
"selected": false,
"text": "name: Set up gcloud\n uses: google-github-actions/setup-gcloud@v0\n with:\n version: '318.0.0'\n service_account_email: ${{ secrets.GCP_SA_EMAIL }}\n service_account_key: ${{ secrets.GCP_SA_KEY }}\n"
},
{
"answer_id": 74562740,
"author": "mit4dev",
"author_id": 4698361,
"author_profile": "https://Stackoverflow.com/users/4698361",
"pm_score": 1,
"selected": false,
"text": "- name: Setup python\n uses: actions/setup-python@v4\n with:\n python-version: '3.9'\n\n- name: Export gcloud related env variable\n run: export CLOUDSDK_PYTHON=\"/usr/bin/python3\"\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3665224/"
] |
74,490,476
|
<p>By mistake I encoded hex data with Windows-1253 (Java eclipse option) but the data should be encoded with ISO-8859-1. Is there a way to re encode the data to get the right conversion?</p>
|
[
{
"answer_id": 74492565,
"author": "Thomas Behr",
"author_id": 9535950,
"author_profile": "https://Stackoverflow.com/users/9535950",
"pm_score": 0,
"selected": false,
"text": "Windows-1253 void encode( File src, File tgt ) throws IOException {\n if (Charset.isSupported(\"Windows-1253\")) {\n try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src), \"Windows-1253\"))) {\n try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tgt), \"ISO-8859-1\"))) {\n String del = \"\";\n for (String line = br.readLine(); line != null; line = br.readLine()) {\n bw.write(del);\n bw.write(line);\n del = \"\\r\\n\";\n }\n\n bw.flush();\n }\n }\n } else {\n throw new IOException(\"Unsupported character encoding: Windows-1253\");\n }\n}\n"
},
{
"answer_id": 74655314,
"author": "javac31",
"author_id": 5650290,
"author_profile": "https://Stackoverflow.com/users/5650290",
"pm_score": -1,
"selected": false,
"text": "try (BufferedReader br = new BufferedReader(new FileReader(file))) {\n String line;\n while ((line = br.readLine()) != null) {\n System.out.println(line); \n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5650290/"
] |
74,490,492
|
<p>I have such setup of K8S:</p>
<p>Cloudflare -> Digital Ocean Load Balancer -> Nginx Ingress -> Nginx Container</p>
<p>Based on my answer on this <a href="https://stackoverflow.com/a/72140360/1102574">question</a> all works fine up to <code>Nginx Ingress</code> here I get the correct IP of the user.</p>
<p>But inside Nginx Contaier the IP is set to the service IP.</p>
<p>I restored it by using:</p>
<pre><code>set_real_ip_from 0.0.0.0/0;
real_ip_header X-Forwarded-For;
</code></pre>
<p>But I don't trust this line: <code>set_real_ip_from 0.0.0.0/0;</code> becuase is from any IP, I can't get CIDR of ingress service.</p>
<p>My question is there is a better way to restore client IP inside nginx container when request are coming from Ingress Service?</p>
|
[
{
"answer_id": 74492565,
"author": "Thomas Behr",
"author_id": 9535950,
"author_profile": "https://Stackoverflow.com/users/9535950",
"pm_score": 0,
"selected": false,
"text": "Windows-1253 void encode( File src, File tgt ) throws IOException {\n if (Charset.isSupported(\"Windows-1253\")) {\n try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src), \"Windows-1253\"))) {\n try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tgt), \"ISO-8859-1\"))) {\n String del = \"\";\n for (String line = br.readLine(); line != null; line = br.readLine()) {\n bw.write(del);\n bw.write(line);\n del = \"\\r\\n\";\n }\n\n bw.flush();\n }\n }\n } else {\n throw new IOException(\"Unsupported character encoding: Windows-1253\");\n }\n}\n"
},
{
"answer_id": 74655314,
"author": "javac31",
"author_id": 5650290,
"author_profile": "https://Stackoverflow.com/users/5650290",
"pm_score": -1,
"selected": false,
"text": "try (BufferedReader br = new BufferedReader(new FileReader(file))) {\n String line;\n while ((line = br.readLine()) != null) {\n System.out.println(line); \n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1102574/"
] |
74,490,494
|
<p>I am using gcc compiler through the terminal of linux run a program. The University that i in, gave us a file with tests. We should run these tests on our programs and the tests should pass. I compile my program with gcc through terminal and it doesnt come back with any errors.I run the tests, the test results are correct but it says that i failed because there is No newline at end of file</p>
<p>For example. The test gibes out the result:
Secret
The result is Secret but it says that i failed because of the error mentioned.
How can i fix it?</p>
<pre><code>#include <string.h>
#include <ctype.h>
int main(void)
{
int i,j;
char k='a', arr[5][5];
for (i=0; i<=4; i++)
{
for (j=0; j<=4; j++)
{
arr[i][j]= k;
k= ++ k;
if(k=='j')
k= ++k;
}
}
char str[74],str2[74], *p;
fgets(str,75,stdin);
for(i=0; i<75; i++)
str2[i]=str[i];
p=strtok(str,"-");
while(p!=NULL)
{
if(atoi(p)/10>4||atoi(p)%10>4)
{
printf("Out of bounds\n");
return 0;
}
else if (isalpha(*p))
{
printf("Unable to decode\n");
return 0;
}
p=strtok(NULL,"-");
}
p=strtok(str2,"-");
printf("< ");
while(p!=NULL)
{
printf("%c", arr[atoi(p)/10][atoi(p)%10]);
p=strtok(NULL, "-");
}
printf("\n");
return 0
}
</code></pre>
<p><a href="https://i.stack.imgur.com/awAbw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/awAbw.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74492565,
"author": "Thomas Behr",
"author_id": 9535950,
"author_profile": "https://Stackoverflow.com/users/9535950",
"pm_score": 0,
"selected": false,
"text": "Windows-1253 void encode( File src, File tgt ) throws IOException {\n if (Charset.isSupported(\"Windows-1253\")) {\n try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src), \"Windows-1253\"))) {\n try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tgt), \"ISO-8859-1\"))) {\n String del = \"\";\n for (String line = br.readLine(); line != null; line = br.readLine()) {\n bw.write(del);\n bw.write(line);\n del = \"\\r\\n\";\n }\n\n bw.flush();\n }\n }\n } else {\n throw new IOException(\"Unsupported character encoding: Windows-1253\");\n }\n}\n"
},
{
"answer_id": 74655314,
"author": "javac31",
"author_id": 5650290,
"author_profile": "https://Stackoverflow.com/users/5650290",
"pm_score": -1,
"selected": false,
"text": "try (BufferedReader br = new BufferedReader(new FileReader(file))) {\n String line;\n while ((line = br.readLine()) != null) {\n System.out.println(line); \n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20530985/"
] |
74,490,521
|
<p>I wanna make strings like <code>A1</code>, <code>A2</code>...
here is my code:</p>
<pre><code>def random_room(self):
return chr(random.randint(65, 90)) + chr(random.randint(1, len(self.rooms)))
</code></pre>
<p>but it doesn't work</p>
|
[
{
"answer_id": 74490591,
"author": "Claude Shannon",
"author_id": 20102259,
"author_profile": "https://Stackoverflow.com/users/20102259",
"pm_score": 0,
"selected": false,
"text": "def random_room(self):\n return \"{}{}\".format(chr(random.randint(65, 90)), random.randint(1, len(self.rooms)+1))\n\n len(self.rooms)"
},
{
"answer_id": 74490628,
"author": "Jenia",
"author_id": 12641442,
"author_profile": "https://Stackoverflow.com/users/12641442",
"pm_score": 0,
"selected": false,
"text": "str chr return str(random.randint(65, 90)) + str(random.randint(1, len(self.rooms)))\n letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nid = 0 # Your number here\nnumber = letters[id] + str(random.randint(1, ...))\n"
},
{
"answer_id": 74490806,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": true,
"text": "chr import string\nfrom random import choice, randint\n\nletter = choice(string.ascii_uppercase)\n number = randint(1, len(self.rooms))\n room = f'{letter}{number}'\n import string\nfrom random import choice, randint\n\n\ndef random_room(self):\n letter = choice(string.ascii_uppercase)\n number = randint(1, len(self.rooms))\n return f'{letter}{number}'\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/313421/"
] |
74,490,529
|
<p>I'm trying to compare one list and one set using two for loops, what I find weird is that sometimes 'O' is in the output and sometimes 'L' is but never both. Does it have to do with set being unsorted? Also is there a better way of getting the duplicates of a list? Preferably the unique duplicates. Any help is appreciated!</p>
<pre><code>def duplicate_count(text):
charList = [*text]
charSet = set(charList)
for s in charSet:
for f in charList:
if s == f: charList.remove(s)
return charList
print(duplicate_count("HELOLO"))
</code></pre>
|
[
{
"answer_id": 74490599,
"author": "Cory Kramer",
"author_id": 2296458,
"author_profile": "https://Stackoverflow.com/users/2296458",
"pm_score": 3,
"selected": true,
"text": "charList collections.Counter >>> from collections import Counter\n>>> s = 'HELOLO'\n>>> c = Counter(s)\n>>> c\nCounter({'L': 2, 'O': 2, 'H': 1, 'E': 1})\n>>> sum(1 for i in c if c[i] > 1)\n2\n >>> [k for k,v in c.items() if v > 1]\n['L', 'O']\n"
},
{
"answer_id": 74490912,
"author": "Gábor Fekete",
"author_id": 6464041,
"author_profile": "https://Stackoverflow.com/users/6464041",
"pm_score": 0,
"selected": false,
"text": "def duplicates(text):\n text = text.lower()\n return [c for c in dict.fromkeys(text) if text.count(c) > 1]\n\nprint(duplicates('HELOLO'))\nprint(duplicates('heoLLo'))\n ['l', 'o']\n['o', 'l']\n set text dict.fromkeys text"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18714330/"
] |
74,490,560
|
<p>I am trying to make a 16x16 grid in which the grid background appears green when you hover your mouse over it, and then the green fades out after awhile.</p>
<p>For now, I just removed the html class <code>hover</code> after 2 seconds by using <code>setTimeout</code>, but I can't seem to figure out how to make the grid background fade out instead of disappearing instantly. Can anyone give me some tips on how to do a <strong>fading-out</strong> effect for the grid background?</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>//16x16 = 257
for (let i = 1; i != 257; i++) {
const div = document.createElement("div")
div.textContent = i;
div.addEventListener("mouseover", (e) => {
div.classList.add("hover")
setTimeout(() => {
div.classList.remove("hover")
}, 2000)
})
document.querySelector(".gridContainer").append(div);
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.gridContainer {
background-color: rgb(234, 241, 241);
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.gridContainer>div {
height: 25px;
flex: 0 1 5.8%;
border: 1px solid green;
text-align: center;
}
.hover {
background-color: aquamarine;
transition: 2s;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="gridContainer"> </div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74490614,
"author": "Nuro007",
"author_id": 19669556,
"author_profile": "https://Stackoverflow.com/users/19669556",
"pm_score": 0,
"selected": false,
"text": "transition-duration: 100ms;"
},
{
"answer_id": 74490640,
"author": "isherwood",
"author_id": 1264804,
"author_profile": "https://Stackoverflow.com/users/1264804",
"pm_score": 2,
"selected": true,
"text": "//16x16 = 257\nfor (let i = 1; i != 257; i++) {\n const div = document.createElement(\"div\");\n div.textContent = i;\n\n div.addEventListener(\"mouseover\", e => {\n div.classList.add(\"hover\")\n });\n\n div.addEventListener('mouseout', e => {\n setTimeout(() => {\n div.classList.remove(\"hover\")\n }, 2000)\n });\n\n document.querySelector(\".gridContainer\").append(div);\n} .gridContainer {\n background-color: rgb(234, 241, 241);\n display: flex;\n flex-wrap: wrap;\n justify-content: center;\n}\n\n.gridContainer>div {\n height: 25px;\n flex: 0 1 5.8%;\n border: 1px solid green;\n text-align: center;\n transition: all 2s; /* mouseout transition */\n}\n\n.gridContainer>div.hover {\n background-color: aquamarine;\n transition: all 0.3s; /* mouseover transition */\n} <div class=\"gridContainer\"> </div>"
},
{
"answer_id": 74490687,
"author": "epascarello",
"author_id": 14104,
"author_profile": "https://Stackoverflow.com/users/14104",
"pm_score": 0,
"selected": false,
"text": ":hover transition-delay //16x16 = 257\nfor (let i = 1; i != 257; i++) {\n const div = document.createElement(\"div\")\n div.textContent = i;\n document.querySelector(\".gridContainer\").append(div);\n} .gridContainer {\n background-color: rgb(234, 241, 241);\n display: flex;\n flex-wrap: wrap;\n justify-content: center;\n}\n\n.gridContainer > div {\n height: 25px;\n flex: 0 1 5.8%;\n border: 1px solid green;\n text-align: center;\n transition-delay: 500ms;\n transition: 1s;\n}\n\n.gridContainer > div:hover {\n background-color: aquamarine;\n transition: 2s;\n} <div class=\"gridContainer\"> </div>"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18558349/"
] |
74,490,577
|
<p>I was able to download the data ( json response) from the below URL for a while via curl on Windows.</p>
<p>curl.exe <a href="https://www.theocc.com/mdapi/series-search?symbol_type=U&symbol=AA" rel="nofollow noreferrer">https://www.theocc.com/mdapi/series-search?symbol_type=U&symbol=AA</a></p>
<p>or</p>
<p>curl.exe <a href="https://www.theocc.com/mdapi/series-search?symbol_type=U&symbol=AA&exchange=" rel="nofollow noreferrer">https://www.theocc.com/mdapi/series-search?symbol_type=U&symbol=AA&exchange=</a></p>
<p>But recently it stopped working and instead getting an error html that says</p>
<p>"Enable JavaScript and cookies to continue"</p>
<p>Is there a way I can make this work again?</p>
<p>thanks in advance.</p>
|
[
{
"answer_id": 74490629,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 0,
"selected": false,
"text": "curl -b cookies -c cookies <URL>\n"
},
{
"answer_id": 74497472,
"author": "Misunderstood",
"author_id": 3813605,
"author_profile": "https://Stackoverflow.com/users/3813605",
"pm_score": 1,
"selected": false,
"text": "HTTP/2 200 OK\ndate: Sat, 19 Nov 2022 01:18:10 GMT\ncontent-type: text/plain; charset=utf-8\ncontent-encoding: gzip\nvary: Accept-Encoding\nrequest-context: appId=cid-v1:30c6c72c-1099-4721-b73f-c69b90d8ae95\nstrict-transport-security: max-age=2592000; includeSubDomains; preload\ncf-cache-status: DYNAMIC\nset-cookie: __cf_bm=4i3UCcOc3ABOk_qatlAieY0OkXfECjDOJG_G_Nm.ex0-1668820690-0-Acph3yaZ3B2kSsPbygIqBJubZSuDb+OUkgmIMDycJ4JyRBJq8gv4QCJEirVC9o6WedMi/p6xrc0z+xdBS5J4s4c=; path=/; expires=Sat, 19-Nov-22 01:48:10 GMT; domain=.theocc.com; HttpOnly; Secure; SameSite=None\nserver: cloudflare\ncf-ray: 76c51c3f3a952209-MIA\nX-Firefox-Spdy: h2\n {\"Content\":[{\"Date\":\"2022-11-18T00:00:00Z\",\"Results\":[{\"ProdSymbolId\":\"AA \",\"ExprDate\":1668751200000000,\"StrikePriceIntg\":17,\"StrikePriceFrac\":500,\"CallTickSymbolId\":\"C\",\"PutTickSymbolId\":\"P\",\"CallOpenInt\":0,\"PutOpenInt\":5950,\"PosLimit\":25000000,\"SecuId\":\"AA \",\"CusiId\":null,\"Name\":\"Alcoa Corporation \",\"OnnGrp\":\"EU\",\"StrPriceFrac\":null,\"StrikePriceFracStr\":\"500\"},{\"ProdSymbolId\":\"AA \",\"ExprDate\":1668751200000000,\"StrikePriceIntg\":20,\"StrikePriceFrac\":0,\"CallTickSymbolId\":\"C\",\"PutTickSymbolId\":\"P\",\"CallOpenInt\":0,\"PutOpenInt\":1553,\"PosLimit\":25000000,\"SecuId\":\"AA \",\"CusiId\":null,\"Name\":\"Alcoa Corporation \",\"OnnGrp\":\"EU\",\"StrPriceFrac\":null,\"StrikePriceFracStr\":\"000\"},{\"ProdSymbolId\":\"AA \",\"ExprDate\":1668751200000000,\"StrikePriceIntg\":22,\"StrikePriceFrac\":500,\"CallTickSymbolId\":\"C\",\"PutTickSymbolId\":\"P\",\"CallOpenInt\":25,\"PutOpenInt\":3145,\"PosLimit\":25000000,\"SecuId\":\"AA \",\"CusiId\":null,\"Name\":\"Alcoa Corporation \",\"OnnGrp\":\"EU\",\"StrPriceFrac\":null,\"StrikePriceFracStr\":\"500\"},{\"ProdSymbolId\":\"AA \",\"ExprDate\":1668751200000000,\"StrikePriceIntg\":25,\"StrikePriceFrac\":0,\"CallTickSymbolId\":\"C\",\"PutTickSymbolId\":\"P\",\"CallOpenInt\":115,\"PutOpenInt\":2714,\"PosLimit\":25000000,\"SecuId\":\"AA \",\"CusiId\":null,\"Name\":\"Alcoa Corporation \",\"OnnGrp\":\"EU\",\"StrPriceFrac\":null,\"StrikePriceFracStr\":\"000\"},{\"ProdSymbolId\":\"AA \",\"ExprDate\":1668751200000000,\"StrikePriceIntg\":30,\"StrikePriceFrac\":0,\"CallTickSymbolId\":\"C\",\"PutTickSymbolId\":\"P\",\"CallOpenInt\":263,\"PutOpenInt\":4645,\"PosLimit\":25000000,\"SecuId\":\"AA \",\"CusiId\":null,\"Name\":\"Alcoa Corporation \",\"OnnGrp\":\"EU\",\"StrPriceFrac\":null,\"StrikePriceFracStr\":\"000\"},{\"ProdSymbolId\":\"AA \",\"ExprDate\":1668751200000000,\"StrikePriceIntg\":32,\"StrikePriceFrac\":0,\"CallTickSymbolId\":\"C\",\"PutTickSymbolId\":\"P\",\"CallOpenInt\":21,\"PutOpenInt\":396,\"PosLimit\":25000000,\"SecuId\":\"AA \",\"CusiId\":null,\"Name\":\"Alcoa Corporation \",\"OnnGrp\":\"EU\",\"StrPriceFrac\":null,\"StrikePriceFracStr\":\"000\"},{\"ProdSymbolId\":\"AA \",\"ExprDate\":1668751200000000,\"StrikePriceIntg\":33,\"StrikePriceFrac\":0,\"CallTickSymbolId\":\"C\",\"PutTickSymbolId\":\"P\",\"CallOpenInt\":44,\"PutOpenInt\":409,\"PosLimit\":25000000,\"SecuId\":\"AA \",\"CusiId\":null,\"Name\":\"Alcoa Corporation \",\"OnnGrp\":\"EU\",\"StrPriceFrac\":null,\"StrikePriceFracStr\":\"000\"},{\"ProdSymbolId\":\"AA \",\"ExprDate\":1668751200000000,\"StrikePriceIntg\":34,\"StrikePriceFrac\":0,\"CallTickSymbolId\":\"C\",\"PutTickSymbolId\":\"P\",\"CallOpenInt\":28,\"PutOpenInt\":145,\"PosLimit\":25000000,\"SecuId\":\"AA \",\"CusiId\":null,\"Name\":\"Alcoa Corporation \",\"OnnGrp\":\"EU\",\"StrPriceFrac\":null,\"StrikePriceFracStr\":\"000\"},{\"ProdSymbolId\":\"AA \",\"ExprDate\":1668751200000000,\"StrikePriceIntg\":35,\"StrikePriceFrac\":0,\"CallTickSymbolId\":\"C\",\"PutTickSymbolId\":\"P\",\"CallOpenInt\":271,\"PutOpenInt\":3760,\"PosLimit\":25000000,\"SecuId\":\"AA \",\"CusiId\":null,\"Name\":\"Alcoa Corporation \",\"OnnGrp\":\"EU\",\"StrPriceFrac\":null,\"StrikePriceFracStr\":\"000\"},{\"ProdSymbolId\":\"AA \",\"ExprDate\":1668751200000000,\"StrikePriceIntg\":35,\"StrikePriceFrac\":500,\"CallTickSymbolId\":\"C\",\"PutTickSymbolId\":\"P\",\"CallOpenInt\":30,\"PutOpenInt\":101,\"PosLimit\":25000000,\"SecuId\":\"AA \",\"CusiId\":null,\"Name\":\"Alcoa Corporation \",\"OnnGrp\":\"EU\",\"StrPriceFrac\":null,\"StrikePriceFracStr\":\"500\"},{\"ProdSymbolId\":\"AA \n & \\& \\& curl \"https://www.theocc.com/mdapi/series-search?symbol_type=U\\&symbol=AA\" \n\ncurl \"https://www.theocc.com/mdapi/series-search?symbol_type=U\\&symbol=AA\" -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8' -H 'Accept-Language: en-US,en;q=0.5' -H 'DNT: 1' -H 'Connection: keep-alive' -H 'Cookie: ARRAffinity=50cf07c4923930f3ead4232e638b6657fb662613b8f01df70fb38ac353b8e3d6; ARRAffinitySameSite=50cf07c4923930f3ead4232e638b6657fb662613b8f01df70fb38ac353b8e3d6' -H 'Upgrade-Insecure-Requests: 1' -H 'Sec-Fetch-Dest: document' -H 'Sec-Fetch-Mode: navigate' -H 'Sec-Fetch-Site: none' -H 'Sec-Fetch-User: ?1'\n\ncurl \"https://www.theocc.com/mdapi/series-search?symbol_type=U&symbol=AA\" ^\n -H \"authority: www.theocc.com\" ^\n -H \"accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\" ^\n -H \"accept-language: en-US,en;q=0.9\" ^\n -H \"cache-control: max-age=0\" ^\n -H \"cookie: ARRAffinity=50cf07c4923930f3ead4232e638b6657fb662613b8f01df70fb38ac353b8e3d6; ARRAffinitySameSite=50cf07c4923930f3ead4232e638b6657fb662613b8f01df70fb38ac353b8e3d6; __cf_bm=FS_Oi_E3bPH7QBQUW.XzcyQDP6PFkL8RHPbA0qbdj8I-1668824712-0-AfSfUDI6XgJiQRrzEHCihbO2DP1VUL1Y9fkmzArjKYqZ356bWDu0eSuUlxkJoAc+N7nVyOBw4itGMsGRSuYf6oc=\" ^\n -H \"sec-fetch-dest: document\" ^\n -H \"sec-fetch-mode: navigate\" ^\n -H \"sec-fetch-site: none\" ^\n -H \"sec-fetch-user: ?1\" ^\n -H \"upgrade-insecure-requests: 1\" ^\n -H \"user-agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920) UCBrowser/10.1.0.563 Mobile\" ^\n --compressed\n ^cr/lf theocc.com HTTP/1.1 403 Forbidden\nDate: Sat, 19 Nov 2022 04:17:29 GMT\nContent-Type: text/html; charset=UTF-8\nTransfer-Encoding: chunked\nConnection: close\nCF-Chl-Bypass: 1\nReferrer-Policy: same-origin\nPermissions-Policy: accelerometer=(),autoplay=(),camera=(),clipboard-read=(),clipboard-write=(),fullscreen=(),geolocation=(),gyroscope=(),hid=(),interest-cohort=(),magnetometer=(),microphone=(),payment=(),publickey-credentials-get=(),screen-wake-lock=(),serial=(),sync-xhr=(),usb=()\nCache-Control: private, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0\nExpires: Thu, 01 Jan 1970 00:00:01 GMT\nX-Frame-Options: SAMEORIGIN\nSet-Cookie: __cf_bm=jNH8U9rGVke8A3M9NVoGyM_54P4yqbD6GUdBex2U9as-1668831449-0-Aajlm5as+JsCCdzuStWeD6FNiZE6Q7BqSSGV+axg1GOcbz3CREOYW+gy0pq0iJpVVZ5HRo2RQA3AQaaFBjNnIsk=; path=/; expires=Sat, 19-Nov-22 04:47:29 GMT; domain=.theocc.com; HttpOnly; Secure; SameSite=None\nServer: cloudflare\nCF-RAY: 76c622f05c20d9d1-MIA\n <!DOCTYPE html>\n<html lang=\"en-US\">\n<head>\n <title>Just a moment...</title>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=Edge\">\n <meta name=\"robots\" content=\"noindex,nofollow\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <link href=\"/cdn-cgi/styles/challenges.css\" rel=\"stylesheet\">\n\n\n</head>\n<body class=\"no-js\">\n <div class=\"main-wrapper\" role=\"main\">\n <div class=\"main-content\">\n <h1 class=\"zone-name-title h1\">\n <img class=\"heading-favicon\" src=\"/favicon.ico\"\n onerror=\"this.onerror=null;this.parentNode.removeChild(this)\">\n www.theocc.com\n </h1>\n <h2 class=\"h2\" id=\"challenge-running\">\n Checking if the site connection is secure\n </h2>\n <noscript>\n <div id=\"challenge-error-title\">\n <div class=\"h2\">\n <span class=\"icon-wrapper\">\n <div class=\"heading-icon warning-icon\"></div>\n </span>\n <span id=\"challenge-error-text\">\n Enable JavaScript and cookies to continue\n </span>\n </div>\n </div>\n </noscript>\n <div id=\"trk_jschal_js\" style=\"display:none;background-image:url('/cdn-cgi/images/trace/managed/nojs/transparent.gif?ray=76c5e617baf0221a')\"></div>\n <div id=\"challenge-body-text\" class=\"core-msg spacer\">\n www.theocc.com needs to review the security of your connection before proceeding.\n </div>\n <form id=\"challenge-form\" action=\"/mdapi/series-search?symbol_type=U\\&symbol=AA&__cf_chl_f_tk=kUJFHohnkrGLP_aT8f5l1edyZE38Iuvbqeguf9EaPyM-1668828957-0-gaNycGzNCH0\" method=\"POST\" enctype=\"application/x-www-form-urlencoded\">\n <input type=\"hidden\" name=\"md\" value=\"C_LKeu2P5NrY0aR4BxvKBGqNiMKJ1potyy02pUTruns-1668828957-0-ASvIMrC-30PITC58EAtdhq56Jx7fME4EOUOUE-FMk5FBMP_d7Pfr7XFI_Qr6SAVlPAQCGA9_b9beL_agWaV1I44NJRLSb5IkRQ3E6icwIe8Eq7QVMQWYJ-KlvST_JI7znFj_MeqOMA50UlrgSYomFz8TuMTnjbbiiYo9FziI0gyhbYedZ0BtSiUakd9eMeV54maAR1UqybWW52Lj1qpMUZtAes6YaVvVNcjVLtBtjt5Dbspqa8XsoRwpk11VO5GnlLoz4uSqh-laMjyd6zOas7YCD7Qzs05AGIBGKLuPZ3xeyq43ZS0zcGLkxsxwgbF1IWdBz8br6tVuO6YFvY5qSsEeXvymMXbCltsj8tqKDb-XoCbfyFF_Gb33LwFmxYudOqrvZ-2miy-BbZAGrSRGe7_nNDfKf94f_ZRrpSu25VvNhvni46u1AUa4v4wy7O6ujeT9JHpwem_0Y2RUw5QJywl8ZXSFf9yGkYq9us8Dwbvkhcis7ovToZv3eP2Gf0MKjgSIj0twbMVIguUCrluO5vVhdzWu1HJfaZI0htq0Rn8ZWD9g0XF5amnaWs80iXocIIsJKPEhHDuh5jpNOH0suaXfZm7waukxfDxRUURM6Kg4BEEaJrNH0ZAsLLvaDfaQ-XCgr_s2VFRdLEQHMEScQ76P271i_MfhA23Xv0uSlLwPRjcnrrYhhfAOoYXMxUqMBjntLp52kLxAgBlV7fD4l8xe-JNpKYWaqi5IXQKLn87mG3XV4SCeeysfvhT26n4CHWXlgroGtv6AwcGtIR6Hkvg\">\n <input type=\"hidden\" name=\"r\" value=\"NEE5A4XvbVzMlgGmfv94hrNQy8HlFwlN9MvsAnrBqEc-1668828957-0-AU6LelP5fDUpZVzOa9xe8l/70P6WeCebWpPrNZ5DR1Chl+2RZwXwTYc2PhlpBrSEc527YLgU+biTV2VNZunN7E3l1/kL6wiimvLxzx46KIUC5IXDcXgDJ3uXX5P3eO/x5OE2RSxI4N07jV1pfmsKwsYf0hJtJzCraW+rZt7/bVZVBmvFrYOSBTqI5jmZ+Lsf4gF+kLRBLKoheLKgvvblO8GLixR6SYt56sv8Hp9yS/DWmDoPC3yx8Z7DwvRFkpuvLdOCgqcTGNHGDfKjWQOwNFA1yB0Sc/6+8qD4mQgSPTMlPYdwiMgfERL9aHQy2A8/GQztGizyp+nAceOiUhFripvog+p3MWYdVNzMD4odVVakRdp/wva0LVzt8rtj1G5FBh6wVA94kCxlDRO6M7pYKQjz0c7ejdYUnFtQYFn4pR9B7H3eZNc2vIIJdTQpyxHNcIbjBWSTn5Bv9aZX/JrXZQE8bxK1PKD9wQtSy2k60cuotYOGmrwjNS4Jgk4bt3SaytN0t02mdvOZ6ZuLK9soRGqIN9iJvZUcU3TCvC+pZdcm9x7DXTC9LCSjzkQWQygXwOAfqrf6floZcdmlJIzr6S2XgPN3OAy6Mz9hkc08Vu6qtAYjI2j1igUjLFZw07MIeluznsZCyLipxf/2LWpqMlotab3q8yT9W9WY8480IBsErIOmJ3c+q2aptTpJM+Cuayb9896SOl9niJP5m9UuwYdiyExE+DieDGR2SIuAuzFxU2XuEgC1mgJmvcpkh+jTlcvE/6rHbQBtZdY5xyMUSJI0u0G187QdjEYlGkTX7nL7t+EKnK/bJCz0qFI/JWEBwY/j3OVAL/0DzI9H3d+r6GnxqZZCUEwfBsl/3kLf6PdKzrtP+otybkpG+RvBd3lfuNx06hRVxmtfVAR3R3WfOCo9o8XOMORG1uvGPggT0DBBVJE8TKv0tbIyE3drvyRjJ4KqLxpPwYB2D/7rwDssEVlZhXf0AAu26R8ajqKWcjy/17tyX4tK8ERknmutokwP/hB4b2VEarMK4XgEapf7alPJvY7KB4NQ694DepNXMnhUncUTynw1T1H+T7LTGaSFn9gcZFcNOPBWzIMElyUjfrB6xJEwG+PcgitK9IWKZkHanvSeTTbPdkaCt6tEhk0LlR0IVPUCLhxUOKeo/1hLWah6oZU6LtF+lHVJ0CF/pNK+YnhREmbUaESoeiRs4Ill2CjS+69hl5CAuLtbCXdAoyZUHyBh3wrJBA+u8EiqSZdKlXfxR85Y8jOO7td2XqS1tVDCLc4VODyXsjQ2CP2GKTThzlySl4s4aYlefAYb5/DDaFBnM1AKHM2TX/Sl90Pyzs7wAfx/UG9V1PW+qNBbhizXJDyxYFBdRjK/dR0Mm4Diau5bv+fbyfa1uWW6wywvl6+HwrCbMi7T2fdWzGUwhmyDZzqTlUBHB4ZR8eU0puljriB3uEeH9w11JK/2qQCviYRkvqfCm32lDPel4PIIAJlUb4qdFPyg0b7Faazh/UjyyS+hK23EM1HVUCVX+QY/aYj9dnzSIBxcy0UQDwmK8TpfcIPXD9iyYzrCQVCaa+e5OtSP5ZJwrEX53f5vn/zFJWo0q4xUTMR5+mmrG+QTVbfpRlRcbz3tI5qIQGUpSlg/MKSUNqernPf9b49FsHQM2NvssW/pA3XiJZQrVL2L8Xq/Ed0VbCIufQdOSvf1nQntUnGzKMbwordtTmsGA8z4Pogv5C7AoQcpPPbSNgiQL5D1Nvlz6Y1IlnG5ovU51a69ptkyX/CY7bFugJ66djMp9vFF2xrIVp0r1arEPvYzpS1DcVj2WQTdaWtXvj8OEAykHuBu1tD3UgtmAdEPE1aftX36eOhfveVgOUXhc47ObpQS54Vbl5vXPbIfdi3pnSEKyZY3CUtd8pNb7OhqqRw5UeRTN47JDhJITP5J4iLz+GiPK7t2ORqDsTnm6T5s3/tksp/pa8/v+ooA9hjSmkEssBgIShffOAUEwyIXJesXUoNx83pJyoHYcXoZI0ZfHsNNRoFn+9F+TckR0U//xKdeNbkCbyXjJrB7yTOvKGolqx0LuAkx/SKW1isTCAdhs3CvbQNxb/GxlWi8D1PzUwVJeQ==\">\n </form>\n </div>\n</div>\n<script>\n (function(){\n window._cf_chl_opt={\n cvId: '2',\n cType: 'managed',\n cNounce: '32555',\n cRay: '76c5e617baf0221a',\n cHash: '7592d66e2323e80',\n cUPMDTk: \"\\/mdapi\\/series-search?symbol_type=U\\\\&symbol=AA&__cf_chl_tk=kUJFHohnkrGLP_aT8f5l1edyZE38Iuvbqeguf9EaPyM-1668828957-0-gaNycGzNCH0\",\n cFPWv: 'b',\n cTTimeMs: '1000',\n cTplV: 4,\n cTplB: 'cf',\n cRq: {\n ru: 'aHR0cHM6Ly93d3cudGhlb2NjLmNvbS9tZGFwaS9zZXJpZXMtc2VhcmNoP3N5bWJvbF90eXBlPVVcJnN5bWJvbD1BQQ==',\n ra: 'TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzEwNy4wLjAuMCBTYWZhcmkvNTM3LjM2IEVkZy8xMDcuMC4xNDE4LjQy',\n rm: 'R0VU',\n d: 'HOWi54+55wh9FM6AuZDX9ANcT34bxF2qiuKEraFDkFFxVWfBHI0H0RQrt4iKgIqp/rTy8AJZBTvoHTeHVUHEU8cHb4I9k9KfbQsqkWEYZbs82TTZ7KS7RE4eFUiXiDSp7Y0QjRU9BL8II412SDZ45C5FFFg8HXvVVScSCJoDt+ARF1Ew3Jaw7unS6jp/2QqADMAF7HjZDag23KMOyCqhfXHrFkopkGie3S8ReM8KDMpt/WINtw/ZIztXsz/1gZvG9JYWW+V8qsmBzlVrIHcoD70dm38ABF5ki4OZ34mXVsMrah0cRovMSqbMnbHDiOGr3lRnmAhcALHm8fzgAekQ1s95t7GfNd9mz+Yextk5Ifx/XiwdGfksP67UBE+svAbNUF/XtVzhCNqQjt6T025f+DXfYNRCVK5i6ZpkHcZzndk+x2uQO6lpzqa5w2yrPr7SMlbD+b5vE5XZvNkHTchXBd74S0N68QjUIdxdrS679dCxfrv06qsk57teE5USCsYaxQNhj5n53vDx2FRTWlIJfo2vqHlzyXK2zFAry5MIEjmfYq9FYdciS5ngRM3AxTWA36so3+7syHH4uk3SZb5JQ579YnsmXEiA1ZGzN1h8Vpb9b0g2utYK6QYeRdyN7QZphZZ1Vzt/mMYIA96uakzHfNn3357jDIrZ3kQQDX7NXNo=',\n t: 'MTY2ODgyODk1Ny40MDQwMDA=',\n m: '/aGrMgSdZO6ogXdUQEEOQsDgNn+UAxlig04+B+a9YQY=',\n i1: 'wffO0nID3av5tavW3mXdtA==',\n i2: 'eIr4tQZjzWSBg3EFfM1UhA==',\n zh: 'rjV/vZpjqak/inbeUs7nHF3bR1cMk2CD6n2tHAx8WJg=',\n uh: 'p19SMC98WhDwvsQz+Kqkj/EMDYzdbqDnaATK9trmhK0=',\n hh: 'rTcMqa1eOqviz82idTtNQqeGJGdhBGQmQRzkYbDEzA4=',\n }\n };\n var trkjs = document.createElement('img');\n trkjs.setAttribute('src', '/cdn-cgi/images/trace/managed/js/transparent.gif?ray=76c5e617baf0221a');\n trkjs.setAttribute('style', 'display: none');\n document.body.appendChild(trkjs);\n var cpo = document.createElement('script');\n cpo.src = '/cdn-cgi/challenge-platform/h/b/orchestrate/managed/v1?ray=76c5e617baf0221a';\n window._cf_chl_opt.cOgUHash = location.hash === '' && location.href.indexOf('#') !== -1 ? '#' : location.hash;\n window._cf_chl_opt.cOgUQuery = location.search === '' && location.href.slice(0, -window._cf_chl_opt.cOgUHash.length).indexOf('?') !== -1 ? '?' : location.search;\n if (window.history && window.history.replaceState) {\n var ogU = location.pathname + window._cf_chl_opt.cOgUQuery + window._cf_chl_opt.cOgUHash;\n history.replaceState(null, null, \"\\/mdapi\\/series-search?symbol_type=U\\\\&symbol=AA&__cf_chl_rt_tk=kUJFHohnkrGLP_aT8f5l1edyZE38Iuvbqeguf9EaPyM-1668828957-0-gaNycGzNCH0\" + window._cf_chl_opt.cOgUHash);\n cpo.onload = function() {\n history.replaceState(null, null, ogU);\n };\n }\n document.getElementsByTagName('head')[0].appendChild(cpo);\n }());\n</script>\n\n\n <div class=\"footer\" role=\"contentinfo\">\n <div class=\"footer-inner\">\n <div class=\"clearfix diagnostic-wrapper\">\n <div class=\"ray-id\">Ray ID: <code>76c5e617baf0221a</code></div>\n </div>\n <div class=\"text-center\">Performance & security by <a rel=\"noopener noreferrer\" href=\"https://www.cloudflare.com?utm_source=challenge&utm_campaign=m\" target=\"_blank\">Cloudflare</a></div>\n </div>\n </div>\n</body>\n</html>\n $headers = array();\n//$headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0';\n$headers[] = 'User-Agent: MOT-V9mm/00.62 UP.Browser/6.2.3.4.c.1.123 (GUI) MMP/2.0';\n$headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8';\n$headers[] = 'Accept-Language: en-US,en;q=0.5';\n$headers[] = 'Accept-Encoding: gzip, deflate, br';\n$headers[] = 'DNT: 1';\n$headers[] = 'Connection: keep-alive';\n$headers[] = 'Upgrade-Insecure-Requests: 1';\n$headers[] = 'Sec-Fetch-Dest: document';\n$headers[] = 'Sec-Fetch-Mode: navigate';\n$headers[] = 'Sec-Fetch-Site: none';\n$headers[] = 'Sec-Fetch-User: ?1';\n\n$ch = curl_init();\ncurl_setopt($ch, CURLOPT_URL, 'https://www.theocc.com/mdapi/series-search?symbol_type=U&symbol=AA');\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');\ncurl_setopt($ch, CURLOPT_HTTPHEADER, $headers);\ncurl_setopt($ch, CURLOPT_ENCODING,\"\");\ncurl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);\ncurl_setopt($ch, CURLOPT_TIMEOUT,2);\ncurl_setopt($ch, CURLOPT_FAILONERROR,true);\ncurl_setopt($ch, CURLOPT_ENCODING,\"\");\ncurl_setopt($ch, CURLINFO_HEADER_OUT, true);\ncurl_setopt($ch, CURLOPT_HEADER, true);\ncurl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);\ncurl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);\ncurl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);\n$response = curl_exec($ch);\necho \"Response: $response\\n\";\necho \"\\nheader out: \\n\" . curl_getinfo($ch,CURLINFO_HEADER_OUT);\necho \"curl Error: \\n\" . curl_error($ch);\necho \"\\n\\ncurl_get_info:\\n\";\nvar_export(curl_getinfo($ch));\n Response: \n\nheader out: \nGET /mdapi/series-search?symbol_type=U&symbol=AA HTTP/2\nHost: www.theocc.com\nuser-agent: MOT-V9mm/00.62 UP.Browser/6.2.3.4.c.1.123 (GUI) MMP/2.0\naccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\naccept-language: en-US,en;q=0.5\naccept-encoding: gzip, deflate, br\ndnt: 1\nconnection: keep-alive\nupgrade-insecure-requests: 1\nsec-fetch-dest: document\nsec-fetch-mode: navigate\nsec-fetch-site: none\nsec-fetch-user: ?1\n\ncurl Error: \nThe requested URL returned error: 403\n\ncurl_get_info:\narray (\n 'url' => 'https://www.theocc.com/mdapi/series-search?symbol_type=U&symbol=AA',\n 'content_type' => 'text/html; charset=UTF-8',\n 'http_code' => 403,\n 'header_size' => 954,\n 'request_size' => 470,\n 'filetime' => -1,\n 'ssl_verify_result' => 20,\n 'redirect_count' => 0,\n 'total_time' => 0.082475,\n 'namelookup_time' => 0.000513,\n 'connect_time' => 0.016717,\n 'pretransfer_time' => 0.039101,\n 'size_upload' => 0.0,\n 'size_download' => 0.0,\n 'speed_download' => 0.0,\n 'speed_upload' => 0.0,\n 'download_content_length' => -1.0,\n 'upload_content_length' => 0.0,\n 'starttransfer_time' => 0.0824,\n 'redirect_time' => 0.0,\n 'redirect_url' => '',\n 'primary_ip' => '2606:4700:90:0:3d7d:1d0b:b681:7270',\n 'certinfo' => \n array (\n ),\n 'primary_port' => 443,\n 'local_ip' => '2604:4500:0:8d:ec4:7aff:fe76:281a',\n 'local_port' => 46564,\n 'request_header' => 'GET /mdapi/series-search?symbol_type=U&symbol=AA HTTP/2\nHost: www.theocc.com\nuser-agent: MOT-V9mm/00.62 UP.Browser/6.2.3.4.c.1.123 (GUI) MMP/2.0\naccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\naccept-language: en-US,en;q=0.5\naccept-encoding: gzip, deflate, br\ndnt: 1\nconnection: keep-alive\nupgrade-insecure-requests: 1\nsec-fetch-dest: document\nsec-fetch-mode: navigate\nsec-fetch-site: none\nsec-fetch-user: ?1\n\n',\n)\n \\& >curl \"https://marketdata.theocc.com/series-search?symbolType=U&symbol=AA\"\n Series/contract Strike Open Interest\nProductSymbol year Month Day Integer Dec C/P Call Put Position Limit\nAA 2022 11 18 17 500 C P 0 5950 25000000\nAA 2022 11 18 20 000 C P 0 1553 25000000\nAA 2022 11 18 22 500 C P 0 3145 25000000\nAA 2022 11 18 25 000 C P 0 2714 25000000\nAA 2022 11 18 30 000 C P 0 4645 25000000\nAA 2022 11 18 32 000 C P 0 396 25000000\nAA 2022 11 18 33 000 C P 0 409 25000000\nAA 2022 11 18 34 000 C P 0 145 25000000\nAA 2022 11 18 35 000 C P 0 3760 25000000\nAA 2022 11 18 35 500 C P 0 101 25000000\nAA 2022 11 18 36 000 C P 0 211 25000000\nAA 2022 11 18 36 500 C P 0 163 25000000\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13696925/"
] |
74,490,667
|
<p>What is replace of the <code>CGContextAddLineToPoint</code> this is what I'm trying to do</p>
<pre><code> for i in aerr {
//0.5f offset lines up line with pixel boundary
CGContextMoveToPoint(context, self.bounds.origin.x, self.font!.lineHeight * CGFloat(x) + baselineOffset)
CGContextAddLineToPoint(context, CGFloat(self.bounds.size.width), self.font!.lineHeight * CGFloat(x) + baselineOffset)
}
</code></pre>
<p>and I'm getting the following error. I know they clearly mention using <code>move(to:)</code> but how to use that?</p>
<blockquote>
<p>'CGContextMoveToPoint' is unavailable: Use move(to:) instead</p>
</blockquote>
|
[
{
"answer_id": 74490789,
"author": "Abdulrahman",
"author_id": 12858507,
"author_profile": "https://Stackoverflow.com/users/12858507",
"pm_score": 0,
"selected": false,
"text": "context.move(to: .init(x: self.bounds.origin.x, y: self.font!.lineHeight * CGFloat(x) + baselineOffset))\n"
},
{
"answer_id": 74490828,
"author": "Thang Phi",
"author_id": 10650407,
"author_profile": "https://Stackoverflow.com/users/10650407",
"pm_score": 2,
"selected": true,
"text": "context CGContextMoveToPoint(context, x, y) context.move(to:CGPoint(x, y)) CGContextAddLineToPoint(context, x, y) context.addLine(to: CGPoint(x, y)) guard let context = UIGraphicsGetCurrentContext() else { return }\n\nfor i in aerr {\n //0.5f offset lines up line with pixel boundary\n context.move(to: CGPoint(x: self.bounds.origin.x, y: self.font!.lineHeight * CGFloat(x) + baselineOffset))\n \n context.addLine(to: CGPoint(x: CGFloat(self.bounds.size.width), y: self.font!.lineHeight * CGFloat(x) + baselineOffset))\n }\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10284355/"
] |
74,490,673
|
<p>I am trying to get all transport headers used when calling a specific API and log that for debugging, since we do not know what the name of the headers will be I want to log them all.</p>
<p>I know this can be done via a class mediator as well as by enabling wire logs but I am looking for an option to achieve this without having to do either of those.</p>
<p>I have tried using script mediator and then using:<code> mc.getProperty("org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS")</code> to fetch them from message context but it just returns null.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 74493857,
"author": "ycr",
"author_id": 2627018,
"author_profile": "https://Stackoverflow.com/users/2627018",
"pm_score": 0,
"selected": false,
"text": "\"org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS\" TRANSPORT_HEADERS Axis2Context ScriptMediator"
},
{
"answer_id": 74515597,
"author": "Flaviano O. Silva",
"author_id": 7237982,
"author_profile": "https://Stackoverflow.com/users/7237982",
"pm_score": -1,
"selected": false,
"text": "<log level=\"headers\" category=\"INFO\">\n <property name=\"inicio\" value=\"------ begin -------\"/>\n <property name=\"X_Teste_FOS\" expression=\"get-property('transport','X-Test-FOS')\"/>\n <property name=\"inicio\" value=\"------ end -------\"/>\n</log>\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13981080/"
] |
74,490,698
|
<p>I am trying to deserialize an object with .net builtin functions.<br />
lets see the array "attributes" which I am trying to deserialize:</p>
<pre><code>"attributes": [
{
"trait_type": "Subseries",
"value": "Templar Order"
},
{
"trait_type": "Colorfulness",
"value": 2,
"min_value": 1,
"max_value": 5
},
{
"trait_type": "Style",
"value": "CGI"
},
{
"trait_type": "Material",
"value": "Steel"
},
{
"trait_type": "Special Effects",
"value": "Rare"
},
{
"trait_type": "Background",
"value": "Rare"
}],
</code></pre>
<p>As you can see, an attribute always has a trait_type and a value.<br />
value can be of type string or int.<br />
min and max value are optional and always of type int.</p>
<p>What I am struggling with is the field "value". I tried to make a class from it, but the json deserializer wont just cast an int into a string (which I would be fine with)</p>
<pre><code>public class MetadataAttribute
{
public MetadataAttribute(string Trait_Type, string Value)
{
trait_type = Trait_Type;
value = Value;
}
public MetadataAttribute(string Trait_Type, int Value, int? Min_Value = null, int? Max_Value = null)
{
trait_type = Trait_Type;
value = Value.ToString();
min_value = Min_Value;
max_value = Max_Value;
}
public MetadataAttribute() { }
/// <summary>
/// the attribute name, eg sharpness
/// </summary>
public string trait_type { get; set; }
/// <summary>
/// the value of the attribute, eg 10
/// </summary>
public string value { get; set; }
/// <summary>
/// optional: the minimum value atribute to provide a possible range
/// </summary>
public int? min_value{get;set;}
/// <summary>
/// optional: the maximum value attribute to provide a possible range
/// </summary>
public int? max_value { get; set; }
}
</code></pre>
<p>current deserialize function (works when there is no int in value)</p>
<pre><code>public static Metadata Load(string path)
{
FileInfo testFile = new FileInfo(path);
string text = File.ReadAllText(testFile.FullName);
Metadata json = JsonSerializer.Deserialize<Metadata>(text);
return json;
}
</code></pre>
<p>Hiw do I resolve this ambiguity?</p>
|
[
{
"answer_id": 74491496,
"author": "Peter Csala",
"author_id": 13268855,
"author_profile": "https://Stackoverflow.com/users/13268855",
"pm_score": 1,
"selected": false,
"text": "abstract class TraitInfo\n{\n [JsonProperty(\"trait_type\")]\n public string TraitType { get; set; }\n [JsonProperty(\"value\")]\n public virtual object Value { get; set; }\n}\n\nclass TraitString : TraitInfo\n{\n public virtual string Value { get; set; }\n}\n\nclass TraitNumber: TraitInfo\n{\n public virtual int Value { get; set; }\n [JsonProperty(\"min_value\")]\n public int MinValue { get; set; }\n [JsonProperty(\"max_value\")]\n public int MaxValue { get; set; }\n}\n\nclass Root\n{\n [JsonProperty(\"attributes\")]\n public List<TraitInfo> Traits { get; set; }\n}\n JsonConverter TraitInfo class TraitInfoConverter : JsonConverter<TraitInfo>\n{\n public override TraitInfo? ReadJson(JsonReader reader, Type objectType, TraitInfo? existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n var semiParsed = JObject.Load(reader);\n var value = semiParsed[\"value\"];\n return value.Type switch\n {\n JTokenType.String => semiParsed.ToObject<TraitString>(),\n JTokenType.Integer => semiParsed.ToObject<TraitNumber>(),\n _ => throw new NotSupportedException()\n };\n }\n\n public override void WriteJson(JsonWriter writer, TraitInfo? value, JsonSerializer serializer)\n {\n throw new NotImplementedException();\n }\n}\n var result = JsonConvert.DeserializeObject<Root>(json, new JsonSerializerSettings { Converters = { new TraitInfoConverter() } });\n JsonConverterAttribute TraitInfo ReadJson Value Value abstract class TraitInfo\n{\n [JsonProperty(\"trait_type\")]\n public string TraitType { get; set; }\n}\n\nclass TraitString : TraitInfo\n{\n public string Value { get; set; }\n}\n\nclass TraitNumber: TraitInfo\n{\n public int Value { get; set; }\n [JsonProperty(\"min_value\")]\n public int MinValue { get; set; }\n [JsonProperty(\"max_value\")]\n public int MaxValue { get; set; }\n}\n\nclass Root\n{\n [JsonProperty(\"attributes\")]\n public List<TraitInfo> Traits { get; set; }\n}\n"
},
{
"answer_id": 74491618,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 0,
"selected": false,
"text": "public class MetadataAttribute\n{\n //.... your code\n\n \n [System.Text.Json.Serialization.JsonPropertyName(\"value\")]\n public object _value\n {\n get\n {\n if (int.TryParse(value, out var intValue)) return intValue;\n return this.value;\n }\n set { this.value = value.ToString(); }\n }\n \n /// <summary>\n /// the value of the attribute, eg 10\n /// </summary>\n [System.Text.Json.Serialization.JsonIgnore]\n public string value { get; set; }\n \n // ...your code\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8695110/"
] |
74,490,704
|
<p>I am trying to parse value from JSON api response in POSTMAN, but the key i need to parse starts with numerical.</p>
<p>Part of response:</p>
<pre><code>"data": {
"354a24d506af956a0ccf14444b18da38834eabbd": very good,
}
</code></pre>
<p>so using:</p>
<pre><code>var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("poziomoceny", jsonData.data.354a24d506af956a0ccf14444b18da38834eabbd);
</code></pre>
<p>gives me error message:</p>
<pre><code>an identifier or keyword cannot immediately follow a numeric literal
</code></pre>
<p>i tried using:</p>
<pre><code>postman.setGlobalVariable("poziomoceny", jsonData.data.(354)a24d506af956a0ccf14444b18da38834eabbd);
</code></pre>
<p>and also tried to change it:</p>
<pre><code>var po = "354a24d506af956a0ccf14444b18da38834eabbd";
postman.setGlobalVariable("poziomoceny", jsonData.data.po);
</code></pre>
<p>which does not either.</p>
<p>How to solve it?</p>
|
[
{
"answer_id": 74491496,
"author": "Peter Csala",
"author_id": 13268855,
"author_profile": "https://Stackoverflow.com/users/13268855",
"pm_score": 1,
"selected": false,
"text": "abstract class TraitInfo\n{\n [JsonProperty(\"trait_type\")]\n public string TraitType { get; set; }\n [JsonProperty(\"value\")]\n public virtual object Value { get; set; }\n}\n\nclass TraitString : TraitInfo\n{\n public virtual string Value { get; set; }\n}\n\nclass TraitNumber: TraitInfo\n{\n public virtual int Value { get; set; }\n [JsonProperty(\"min_value\")]\n public int MinValue { get; set; }\n [JsonProperty(\"max_value\")]\n public int MaxValue { get; set; }\n}\n\nclass Root\n{\n [JsonProperty(\"attributes\")]\n public List<TraitInfo> Traits { get; set; }\n}\n JsonConverter TraitInfo class TraitInfoConverter : JsonConverter<TraitInfo>\n{\n public override TraitInfo? ReadJson(JsonReader reader, Type objectType, TraitInfo? existingValue, bool hasExistingValue, JsonSerializer serializer)\n {\n var semiParsed = JObject.Load(reader);\n var value = semiParsed[\"value\"];\n return value.Type switch\n {\n JTokenType.String => semiParsed.ToObject<TraitString>(),\n JTokenType.Integer => semiParsed.ToObject<TraitNumber>(),\n _ => throw new NotSupportedException()\n };\n }\n\n public override void WriteJson(JsonWriter writer, TraitInfo? value, JsonSerializer serializer)\n {\n throw new NotImplementedException();\n }\n}\n var result = JsonConvert.DeserializeObject<Root>(json, new JsonSerializerSettings { Converters = { new TraitInfoConverter() } });\n JsonConverterAttribute TraitInfo ReadJson Value Value abstract class TraitInfo\n{\n [JsonProperty(\"trait_type\")]\n public string TraitType { get; set; }\n}\n\nclass TraitString : TraitInfo\n{\n public string Value { get; set; }\n}\n\nclass TraitNumber: TraitInfo\n{\n public int Value { get; set; }\n [JsonProperty(\"min_value\")]\n public int MinValue { get; set; }\n [JsonProperty(\"max_value\")]\n public int MaxValue { get; set; }\n}\n\nclass Root\n{\n [JsonProperty(\"attributes\")]\n public List<TraitInfo> Traits { get; set; }\n}\n"
},
{
"answer_id": 74491618,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 0,
"selected": false,
"text": "public class MetadataAttribute\n{\n //.... your code\n\n \n [System.Text.Json.Serialization.JsonPropertyName(\"value\")]\n public object _value\n {\n get\n {\n if (int.TryParse(value, out var intValue)) return intValue;\n return this.value;\n }\n set { this.value = value.ToString(); }\n }\n \n /// <summary>\n /// the value of the attribute, eg 10\n /// </summary>\n [System.Text.Json.Serialization.JsonIgnore]\n public string value { get; set; }\n \n // ...your code\n}\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20223379/"
] |
74,490,712
|
<p>Have a file <strong>sample.yaml</strong></p>
<pre><code>---
action: "want-to-update"
foo: |-
{
"a" : "actual A",
"b" : "actual B",
"c" : "actual C"
}
---
action: "dont-want-to-update"
foo: |-
.
.
.
</code></pre>
<p>Need to update value in <code>a</code> field from <code>actual a</code> to <code>updated a</code></p>
<p>Tried to update with <code>yq</code> and <code>jq</code></p>
<pre><code>yq 'select(.action == "want-to-update").foo' sample.yaml | jq '.a = "updated a" | tostring' | xargs -0 -n1 -I{} yq 'select(.action == "want-to-update").foo = {}' -i sample.yaml
</code></pre>
<p>Getting output as below:</p>
<pre><code>---
action: "want-to-update"
foo: |-
{"a":"updated a","b":"actual B","c":"actual C"}
---
.
.
</code></pre>
<p>But I want the prettier version of above:</p>
<pre><code>---
action: "want-to-update"
foo: |-
{
"a" : "updated A",
"b" : "actual B",
"c" : "actual C"
}
---
</code></pre>
|
[
{
"answer_id": 74491131,
"author": "glenn jackman",
"author_id": 7552,
"author_profile": "https://Stackoverflow.com/users/7552",
"pm_score": 1,
"selected": false,
"text": "tostring json=$(\n yq 'select(.action == \"want-to-update\").foo' sample.yaml \\\n | jq '.a = \"updated a\"'\n)\nescaped_quotes=${json//\\\"/\\\\\\\"}\nyq 'select(.action == \"want-to-update\").foo = \"'\"${escaped_quotes}\"'\"' sample.yaml\n ---\naction: \"want-to-update\"\nfoo: |-\n {\n \"a\": \"updated a\",\n \"b\": \"actual B\",\n \"c\": \"actual C\"\n }\n\n---\naction: \"dont-want-to-update\"\nfoo: |-\n \"ok\"\n\n"
},
{
"answer_id": 74492299,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 3,
"selected": true,
"text": "fromjson tojson yq -i 'select(.action == \"want-to-update\").foo |= (\n fromjson | .a = \"updated a\" | tojson\n)' sample.yaml\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4901086/"
] |
74,490,790
|
<p>I need to match a group of exact 5 characters 1's. Example below</p>
<pre><code>02011111020 // match
00211111200 // Not match because there are 2 at start and end of group
00111111100 // Not match because there are 6 1's
</code></pre>
<p>So far, I have try with pattern</p>
<ul>
<li><code>(?!2)(1{5}?)(?!2)</code> but fail at <code>00111111100</code></li>
<li><code>\D(1{5}?)\D</code> but fail at <code>02011111020</code></li>
</ul>
|
[
{
"answer_id": 74490831,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 3,
"selected": true,
"text": "(?!2) (?!2) \\D [12] (?<![12])1{5}(?![12])\n (?<![12]) 1{5} (?![12])"
},
{
"answer_id": 74490996,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 1,
"selected": false,
"text": "1 0 .*01{5}0.*\n"
},
{
"answer_id": 74499003,
"author": "Arvind Kumar Avinash",
"author_id": 10819573,
"author_profile": "https://Stackoverflow.com/users/10819573",
"pm_score": 2,
"selected": false,
"text": "(?<=0)1{5}(?=0)\n (?<=0) 1{5} (?=0)"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20540177/"
] |
74,490,801
|
<p>I would like to create random dataset consists of 10 million rows. Unfortunately, I could not find a way to create date column with specific range (example from 01.01.2021-31.12.2021).</p>
<p>I tried with oracle sql, but could not find a way to do that. There is way that I can do in excel, but excel can not handle 10 millions row of data. Therefore, I though Python can be the best way to do that, but I could not figure it out.</p>
|
[
{
"answer_id": 74490896,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "pandas.date_range numpy.random.choice df = pd.DataFrame(\n {\n 'date': np.random.choice(\n pd.date_range('2021-01-01', '2021-12-31', freq='D'), size=10_000_000\n )\n }\n)\n date\n0 2021-04-05\n1 2021-02-01\n2 2021-09-22\n3 2021-10-17\n4 2021-04-28\n... ...\n9999995 2021-07-24\n9999996 2021-03-15\n9999997 2021-07-28\n9999998 2021-11-01\n9999999 2021-03-20\n\n[10000000 rows x 1 columns]\n"
},
{
"answer_id": 74490979,
"author": "Trying to Learn ",
"author_id": 20523271,
"author_profile": "https://Stackoverflow.com/users/20523271",
"pm_score": 0,
"selected": false,
"text": "#Imports the random module\nimport random\n\n#Creates a loop that will run 10 million times\nfor i in range(0,10000000):\n \n #Prints a random number between one and ten on each new row\n print(random.randint(0,10)\n \n"
},
{
"answer_id": 74491298,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "DBMS_RANDOM SELECT DATE '2021-01-01'\n + DBMS_RANDOM.VALUE(0, DATE '2022-01-01' - DATE '2021-01-01')\n AS random_date\nFROM DUAL\nCONNECT BY LEVEL <= 10000000;\n"
}
] |
2022/11/18
|
[
"https://Stackoverflow.com/questions/74490801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20540149/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.