qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,451,565 | <p>I want to get the index of min, I tried ways like getIndexOf etc. but none of them worked. How can I do this?</p>
<pre><code>import java.util.Arrays;
class getIndexOfMin {
public static void main(String[] args) {
double arr[] = {263.5, 393.75, 5.0, 289.75};
double min = Arrays.stream(arr).min().getAsDouble();
System.out.println(min);
}
}
</code></pre>
| [
{
"answer_id": 74451608,
"author": "Cole Henrich",
"author_id": 14921272,
"author_profile": "https://Stackoverflow.com/users/14921272",
"pm_score": 1,
"selected": false,
"text": "int index;\nfor (int i = 0; i < arr.length; i++){\n double d = arr[i];\n if (d == min){\n index =... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20036187/"
] |
74,451,583 | <p>I have a global object that store 2 custom class objects, something like this:</p>
<pre><code> /////// Separated object file ////////
object ApplicationData {
var profiledata:ProfileData = ProfileData(null)
var OVOlists = ArrayList<OVOList>()
}
/////// Separated class file ////////
class OVOList (
private var OVOIcon: Int,
private var OVOName: String?,
private var OVOPlace: String?,
private var OVOstatus: Int
) :Parcelable {
private var Humidity:String? =""
private var Temperature:String? = ""
private var PH:String? =""
private var WaterLvl :String? = ""
constructor(parcel: Parcel) : this(
parcel.readValue(Int::class.java.classLoader) as Int,
parcel.readString(),
parcel.readString(),
parcel.readValue(Int::class.java.classLoader) as Int
) {
Humidity = parcel.readString()
Temperature = parcel.readString()
PH = parcel.readString()
WaterLvl = parcel.readString()
} ... + setters , getters and parcel lines
/////// separated class file ////////
class ProfileData(private var email:String?):Parcelable {
private var token:String? =""
private var profile_image: String? =""
private var profile_image_path:String? = ""
private var nombre:String? = ""
private var uid:String? = ""
constructor(parcel: Parcel) : this(
parcel.readString(),
) {
token=parcel.readString()
profile_image = parcel.readString()
profile_image_path = parcel.readString()
nombre = parcel.readString()
uid=parcel.readString()
} ... + setters,getters and parcel lines
</code></pre>
<p>The classes are parcelable, because i was moving some information via bundles, but now im using this global object so there is no need to keep them like that.
But the question is how to store the whole object into memory, i have try the Gson/preferences aproach but i cannot make it work :(, it doesnt store the object, maybe its because it has 2 custom class objects inside, i dont think the parcelable attribute should affect. I made something like this:</p>
<pre><code>//write//
mprefs.edit().putString("MyappData",gson.toJson(ApplicationData)).apply()
//read//
String json = mprefs.getString("MyappData", "")
val obj = gson.fromJson(json, ApplicationData::java.class)
ApplicationData.profiledata = obj.profiledata
ApplicationData.OVOlists = obj.OVOlists
</code></pre>
<p>It seems that its failing in the writing part , any ideas what to do?</p>
| [
{
"answer_id": 74463911,
"author": "OVO Cuenta",
"author_id": 19861170,
"author_profile": "https://Stackoverflow.com/users/19861170",
"pm_score": 0,
"selected": false,
"text": "object ApplicationData {\nvar profiledata:ProfileData = ProfileData(null)\nvar OVOlists = ArrayList<OVOList>()\... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19861170/"
] |
74,451,606 | <p>I have a div, which has an image inside another div. I would like to place the inner div over the second div. So the arrow in the image below should go over the red. Is this possible?</p>
<p><a href="https://i.stack.imgur.com/3jep9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3jep9.png" alt="enter image description here" /></a></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>.puscicaAnimacija {
bottom: -2%;
height: 5%;
margin-bottom: -10px;
z-index: 2;
position: absolute;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="first">
<div style="display: flex; justify-content: center;">
<img src="https://via.placeholder.com/100" class="puscicaAnimacija" />
</div>
</div>
<div class="second">
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74451658,
"author": "Skin_phil",
"author_id": 13258195,
"author_profile": "https://Stackoverflow.com/users/13258195",
"pm_score": 1,
"selected": false,
"text": "position:relative"
},
{
"answer_id": 74451811,
"author": "matteominin",
"author_id": 13922670,
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14052161/"
] |
74,451,619 | <p>I was given the task to code the following recursive method. midresult is supposed to be 0 when I call the method. It works if I call the method just once, but because I have this midresult variable, as soon as I call it more than once in a row it returns wrong values because it adds up midresult.</p>
<p>How do I set back midresult to 0 each time after the method is done running? Im not allowed to put it in my main method, but I can't put it into the actual recursive method because this will mess up the recursion right?</p>
<p>eg for x=5, y=9 the result should be 15, which works if I only call the method once. But if I call it with x=5 and y=9 after calling it with other xy values the return value is wrong.</p>
<pre><code>static int midresult;
public static int recursivemethod(int x, int y) {
// TODO
if(x==0) {
return y + midresult;
}
else{
if((x+midresult)%2==0) {
midresult+= (x/2);
int temp= y;
y=(x/2);
x=temp;
return recursivemethod(x, y);
}
else {
midresult+= y;
x-=1;
y=(y/2);
return recursivemethod(x, y);
}
}
}
</code></pre>
| [
{
"answer_id": 74451689,
"author": "human bean",
"author_id": 17186475,
"author_profile": "https://Stackoverflow.com/users/17186475",
"pm_score": 2,
"selected": false,
"text": "midresult"
},
{
"answer_id": 74500385,
"author": "WJS",
"author_id": 1552534,
"author_profi... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19293033/"
] |
74,451,647 | <p>Hello everyone I want to make a matrix that looks like the image, what I did first was to create a matrix of zeros and then with a for I made the diagonal of the matrix but now I need to make the diagonals that are above and below the -2 but in those there is not a single value, those have zeros and ones so I am not very clear how to make them.</p>
<p>try to make them with this code
<a href="https://i.stack.imgur.com/CXScC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CXScC.jpg" alt="enter image description here" /></a></p>
<pre><code>N=3
</code></pre>
<pre><code>D2=np.zeros((N**2,N**2))
</code></pre>
<pre><code>for i in range(N**2):
for j in range(N**2):
if i==j:
D2[i,j]=-2
elif np.abs(i-j)==1:
D2[i,j]=1
</code></pre>
| [
{
"answer_id": 74451689,
"author": "human bean",
"author_id": 17186475,
"author_profile": "https://Stackoverflow.com/users/17186475",
"pm_score": 2,
"selected": false,
"text": "midresult"
},
{
"answer_id": 74500385,
"author": "WJS",
"author_id": 1552534,
"author_profi... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20326515/"
] |
74,451,654 | <p>I am creating a trigger in SQL to sum up all the values in a column after a change is made. I am stuck and encountering an error when I try this:
`</p>
<pre><code>CREATE OR REPLACE TRIGGER GET_NUM_ATHLETES
AFTER DELETE OR UPDATE OF NUM_ATHLETES OR INSERT ON DELEGATION
BEGIN
SELECT
SUM("A1"."NUM_") "SUM(NUM_)"
INTO x_1 FROM
"DBF19"."DELEGATION" "A1";
END;
</code></pre>
<p>`
My table looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Num_</th>
</tr>
</thead>
<tbody>
<tr>
<td>ABC</td>
<td>2</td>
</tr>
<tr>
<td>XYZ</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
<p>I just used the Oracle SQL Developer GUI to create, but obviously doing something wrong.</p>
| [
{
"answer_id": 74451689,
"author": "human bean",
"author_id": 17186475,
"author_profile": "https://Stackoverflow.com/users/17186475",
"pm_score": 2,
"selected": false,
"text": "midresult"
},
{
"answer_id": 74500385,
"author": "WJS",
"author_id": 1552534,
"author_profi... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18627693/"
] |
74,451,663 | <p>I have 4 lists of couples of numbers and a list that contains all the 4 lists. I need to create a list with 4 numbers in total, in which <strong>only one</strong> couple is from the list_couples and the rest are randomly generated (for example:[1,21,5,6]). Does anyone have an idea how to make a condition of checking whether the rest of the randomly generated numbers form a couple that exist in list_couples? (so that i dont get something like this: [1,21,2,22])</p>
<pre><code>list1=[1,21]
list2=[1,31]
list3=[2,12]
list4=[2,22]
list5=[10,20]
list_couples = [list1, list2,list3,list4]
</code></pre>
| [
{
"answer_id": 74451689,
"author": "human bean",
"author_id": 17186475,
"author_profile": "https://Stackoverflow.com/users/17186475",
"pm_score": 2,
"selected": false,
"text": "midresult"
},
{
"answer_id": 74500385,
"author": "WJS",
"author_id": 1552534,
"author_profi... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17835716/"
] |
74,451,764 | <p>I would like to write some code like the following:</p>
<pre><code>using int_list_t = std::initializer_list<int>;
struct ThreeDimensionalBox {
static constexpr int_list_t kDims = {1, 2, 3};
};
struct FourDimensionalBox {
static constexpr int_list_t kDims = {4, 5, 6, 7};
};
template<typename Box1, typename Box2>
struct CombinedBox {
static constexpr int_list_t kDims = Box1::kDims + Box2::kDims; // error
};
using SevenDimensionalBox = CombinedBox<ThreeDimensionalBox, FourDimensionalBox>;
</code></pre>
<p>Is there some way to fix the implementation of <code>CombinedBox</code>, so that <code>SevenDimensionalBox::kDims</code> is effectively bound to <code>{1, 2, 3, 4, 5, 6, 7}</code>?</p>
<p>I know that I can replace <code>std::initializer_list<int></code> with a custom template class with a variadic int template parameter list, with concatenation effectively achieved via standard metaprogramming recursion techniques. I was just wondering if a solution exists using only <code>std::initializer_list</code>.</p>
| [
{
"answer_id": 74452066,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 3,
"selected": true,
"text": "std::initializer_list"
},
{
"answer_id": 74452114,
"author": "Nicol Bolas",
"author_id": 73406... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/543913/"
] |
74,451,770 | <p>I am having two arrays,</p>
<p>the first array contains:</p>
<pre><code>1, 2, 3, 4, 5
</code></pre>
<p>and the second one contains:</p>
<pre><code>100, 200, 300, 400, 500
</code></pre>
<p>the result should be:</p>
<pre><code>[ [ '1', '100' ],
[ '2', '200' ],
[ '3', '300' ],
[ '4', '400' ],
[ '5', '500' ] ]
</code></pre>
| [
{
"answer_id": 74452066,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 3,
"selected": true,
"text": "std::initializer_list"
},
{
"answer_id": 74452114,
"author": "Nicol Bolas",
"author_id": 73406... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20513823/"
] |
74,451,774 | <p>I have 2 tables name and match. The name and match table have columns type.
The columns and data in the name table</p>
<pre><code>ID| type |
--| ---- |
1| 1ABC |
2| 2DEF |
3| 3DEF |
4| 4IJK |
</code></pre>
<p>The columns and data in match table is</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>type</th>
<th>DATA</th>
</tr>
</thead>
<tbody>
<tr>
<td>NOT %ABC% AND NOT %DEF%</td>
<td>NOT ABC AND NOT DEF</td>
</tr>
<tr>
<td>%DEF%</td>
<td>DEF ONLY</td>
</tr>
<tr>
<td>NOT %DEF% AND NOT %IJK%</td>
<td>NOT DEF AND NOT IJK</td>
</tr>
</tbody>
</table>
</div>
<p>I have tried using case statement. The first 3 characters will be NOT if there is a NOT in the type in match table.
The below query is giving me a missing keyword error. I am not sure what I am missing here</p>
<pre><code>SELECT s.id, s.type, m.data
where case when substr(m.type1,3)='NOT' then s.type not in (REPLACE(REPLACE(m.type,'NOT',''),'AND',','))
ELSE s.type in (m.type) end
from source s, match m;
</code></pre>
<p>I need the output to match the type in source column and display the data in match column.</p>
<p>The output should be</p>
<pre><code>ID|type|DATA
1 |1ABC|NOT DEF AND NOT IJK
2 |2DEF|DEF ONLY
3 |3DEF|DEF ONLY
4 |4IJK|NOT ABC AND NOT DEF
</code></pre>
| [
{
"answer_id": 74457849,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 0,
"selected": false,
"text": "WITH \n tbl_name AS\n (\n Select 1 \"ID\", '1ABC' \"A_TYPE\" From Dual Union All\n Select 2 ... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9290911/"
] |
74,451,798 | <p>I'm trying to build a project using vanilla CSS and React Js and I need help writing a "conditional" css.</p>
<p>In a previous project I wrote a conditional css using tailwind:</p>
<pre><code><p>
className={`text-cyan-600 font-medium text-sm ${
post.description.length > 300 ? "text-red-600" : ""
}`}
>
{post.description.length}/300
</p>
</code></pre>
<p>This code will turn a text red if it exceeds 300 words.
I'd like to do the same using vanilla CSS but I'm not finding a way to properly write in line styles.
Thanks in advance for your help!</p>
| [
{
"answer_id": 74451886,
"author": "RedhaBenKortbi",
"author_id": 17743517,
"author_profile": "https://Stackoverflow.com/users/17743517",
"pm_score": 2,
"selected": false,
"text": "text.active{color:red;}"
},
{
"answer_id": 74451959,
"author": "Chris Hamilton",
"author_id... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20029377/"
] |
74,451,808 | <p>I am using VBA in my Access DB to launch a batch file which is linked to PS1 script.</p>
<p>That all works as intended. The issue is that I want to run some queries after that action is completed, but as it stands I need to babysit the whole thing. So I am looking for a solution to keep the VBA paused while the batch is running.</p>
<p>I found this article: <a href="https://danwagner.co/how-to-run-a-batch-file-and-wait-until-it-finishes-with-vba/" rel="nofollow noreferrer">https://danwagner.co/how-to-run-a-batch-file-and-wait-until-it-finishes-with-vba/</a></p>
<p>But the solution doesn't work for me for some reason. The batch runs, but the VBA just steams on ahead without pausing.</p>
<p>Here is my code:</p>
<pre><code>Private Sub Button_UpdateOffline_Click()
Dim strCommand As String
Dim lngErrorCode As Long
Dim wsh As WshShell
Set wsh = New WshShell
DoCmd.OpenForm "Please_Wait"
'Run the batch file using the WshShell object
strCommand = Chr(34) & _
"C:\Users\Rip\Q_Update.bat" & _
Chr(34)
lngErrorCode = wsh.Run(strCommand, _
WindowStyle:=0, _
WaitOnReturn:=True)
If lngErrorCode <> 0 Then
MsgBox "Uh oh! Something went wrong with the batch file!"
Exit Sub
End If
DoCmd.Close acForm, "Please_Wait"
End Sub
</code></pre>
<p>Here is my batch code if that helps:</p>
<pre><code>START PowerShell.exe -ExecutionPolicy Bypass -Command "& 'C:\Users\Rip\PS1\OfflineFAQ_Update.ps1' "
</code></pre>
| [
{
"answer_id": 74456922,
"author": "Erik A",
"author_id": 7296893,
"author_profile": "https://Stackoverflow.com/users/7296893",
"pm_score": 3,
"selected": true,
"text": "/WAIT"
},
{
"answer_id": 74458422,
"author": "Gustav",
"author_id": 3527297,
"author_profile": "ht... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10177803/"
] |
74,451,818 | <p>I would like to make a sql query than return me the distance between two cities.</p>
<pre><code>SELECT c1.name, c2.name, d.distance
FROM cities_distance d, city c1, city c2
WHERE c1.name = d.name_city1
AND c2.name = d.name_city2
AND c1.id = c2.id
AND (c1.name = 'paris'
AND c2.name = 'berlin')
or (c1.name = 'berlin'
AND c2.name = 'paris');
</code></pre>
<p>This query return all lines where Paris or Berlin is registered. But in my database I got just 1 line who match with "Paris-Berlin"</p>
<p>My database (<code>cities_distance</code>) :</p>
<pre><code>-----------------------------------
| id | city1 | city2 | distance |
| 1 | berlin | paris | 1055 |
| 2 | rome | berlin | 1500 |
-----------------------------------
</code></pre>
| [
{
"answer_id": 74451873,
"author": "Johnny Bones",
"author_id": 2174085,
"author_profile": "https://Stackoverflow.com/users/2174085",
"pm_score": 0,
"selected": false,
"text": "SELECT \n c1.name, \n c2.name, \n d.distance\nFROM cities_distance d, city c1, city c2\nWHERE \n c1.i... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7867717/"
] |
74,451,820 | <p>When I try kicking someone from an account that has no kick permissions, the bot says "the application did not respond".
The code I'm using:</p>
<pre><code>@bot.slash_command(description = "Kickar alguém", guild_ids=[1041057700823449682])
@has_permissions(kick_members=True)
@option("member",description = "Seleciona o membro")
@option("reason",description = "O motivo do kick (podes deixar vazio)")
async def kick(
ctx,
member: discord.Member,
reason=None):
if reason==None:
reason="és idiota"
await ctx.respond(f"Kickaste {member} com sucesso :)")
await member.send(f'Foste kickado de {ctx.guild} porque {reason}.')
await ctx.guild.kick(member)
@kick.error
async def kick_error(error, ctx):
if isinstance(error, MissingPermissions):
await ctx.respond("Desculpa {ctx.message.author}, não tens permissões para isso!")
</code></pre>
<p>Kicking someone from an account with these permissions works well, but when I try from an account without perms, the bot doesn't respond with "Sorry user, you dont have perms".</p>
| [
{
"answer_id": 74451873,
"author": "Johnny Bones",
"author_id": 2174085,
"author_profile": "https://Stackoverflow.com/users/2174085",
"pm_score": 0,
"selected": false,
"text": "SELECT \n c1.name, \n c2.name, \n d.distance\nFROM cities_distance d, city c1, city c2\nWHERE \n c1.i... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20417932/"
] |
74,451,822 | <p>I need write dataframe to snowflake, by using snowflake.snowpark. I have some pandas.DataFrame, have some transformation (corr matrix, description stats, model output,...), but I cant write it back to my snowflake database. Thanks for help.</p>
<pre><code>from snowflake.snowpark import Session
from snowflake.snowpark import table
from snowflake.snowpark.functions import udf
from snowflake.snowpark.functions import col
from snowflake.snowpark.types import StringType
sess = None
print('Connecting...')
cnn_params = {
"account": "eu-west-1",
"user": "user",
"password": 'pass',
"warehouse": "xs",
"database": "demodb",
"schema": "demosch",
"role": "ACCOUNTADMIN"
}
try:
print('session...')
import pandas as pd
import numpy as np
sess = Session.builder.configs(cnn_params).create()
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
#print(df.describe())
df.describe().write.mode("overwrite").save_as_table("describe_output", table_type="temporary")
except Exception as e:
print(e)
finally:
if sess:
sess.close()
print('connection closed...')
print('done.')
</code></pre>
<p>My output:</p>
<pre><code>'DataFrame' object has no attribute 'write'
connection closed...
</code></pre>
| [
{
"answer_id": 74463539,
"author": "clb",
"author_id": 20521809,
"author_profile": "https://Stackoverflow.com/users/20521809",
"pm_score": 2,
"selected": false,
"text": "session.write_pandas(df)"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7676365/"
] |
74,451,834 | <p>This is my query so far, struggling with how not to display the JONES record though...</p>
<p>SELECT SNAME, JOB FROM STAFF
WHERE JOB IN (SELECT JOB FROM STAFF WHERE SNAME = 'JONES');</p>
<p>Result...</p>
<p>SNAME JOB</p>
<hr />
<p>JONES MANAGER<br />
HAYAT MANAGER<br />
CLARK MANAGER</p>
| [
{
"answer_id": 74463539,
"author": "clb",
"author_id": 20521809,
"author_profile": "https://Stackoverflow.com/users/20521809",
"pm_score": 2,
"selected": false,
"text": "session.write_pandas(df)"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,451,862 | <p>I have a 11 columns x 13,470,621 rows pytable. The first column of the table contains a unique identifier to each row (this identifier is always only present once in the table).</p>
<p>This is how I select rows from the table at the moment:</p>
<pre><code>my_annotations_table = h5r.root.annotations
# Loop through table and get rows that match gene identifiers (column labeled gene_id).
for record in my_annotations_table.where("(gene_id == b'gene_id_36624' ) | (gene_id == b'gene_id_14701' ) | (gene_id == b'gene_id_14702')"):
# Do something with the data.
</code></pre>
<p>Now this works fine with small datasets, but I will need to routinely perform queries in which I can have many thousand of unique identifiers to match for in the table's gene_id column. For these larger queries, the query string can quickly get very large and I get an exception:</p>
<pre><code> File "/path/to/my/software/python/python-3.9.0/lib/python3.9/site-packages/tables/table.py", line 1189, in _required_expr_vars
cexpr = compile(expression, '<string>', 'eval')
RecursionError: maximum recursion depth exceeded during compilation
</code></pre>
<p>I've looked at this question (<a href="https://stackoverflow.com/questions/23142788/what-is-the-pytables-counterpart-of-a-sql-query-select-col2-from-table-where-co">What is the PyTables counterpart of a SQL query "SELECT col2 FROM table WHERE col1 IN (val1, val2, val3...)"?</a>), which is somehow similar to mine, but was not satisfactory.</p>
<p>I come from an R background where we often do these kinds of queries (i.e. <code>my_data_frame[my_data_frame$gene_id %in% c("gene_id_1234", "gene_id_1235"),]</code> and was wondering if there was comparable solution that I could use with pytables.</p>
<p>Thanks very much,</p>
| [
{
"answer_id": 74466936,
"author": "julio514",
"author_id": 4792074,
"author_profile": "https://Stackoverflow.com/users/4792074",
"pm_score": 0,
"selected": false,
"text": "expectedrows=<int>"
},
{
"answer_id": 74468943,
"author": "kcw78",
"author_id": 10462884,
"auth... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792074/"
] |
74,451,998 | <p>Let's assume that we have this small code:</p>
<pre><code>template<typename T>
struct Test {
Test(T t) : m_t(t) {}
T m_t;
};
int main() {
Test t = 1;
}
</code></pre>
<p>This code easily compiles with <code>[T=int]</code> for <code>Test</code> class. Now if I write a code like this:</p>
<pre><code>template<typename T>
struct Test {
Test(T t) : m_t(t) {}
T m_t;
};
struct S {
Test t = 1;
};
int main() {
S s;
}
</code></pre>
<p>This code fails to compile with the following error:</p>
<pre><code>invalid use of template-name 'Test' without an argument list
</code></pre>
<p>I need to write it like <code>Test<int> t = 1;</code> as a class member to work. Any idea why this happens?</p>
| [
{
"answer_id": 74452068,
"author": "NathanOliver",
"author_id": 4342498,
"author_profile": "https://Stackoverflow.com/users/4342498",
"pm_score": 3,
"selected": false,
"text": "struct S {\n Test t = 1;\n};\n"
},
{
"answer_id": 74452091,
"author": "Quimby",
"author_id":... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74451998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5529197/"
] |
74,452,015 | <p>I have columns of probabilities in a pandas dataframe as an output from multiclass machine learning.</p>
<p>I am looking to filter rows for which the model had very close probabilities between the classes for that row, and ideally only care about similar values that are similar to the highest value in that row, but I'm not sure where to start.</p>
<p>For example my data looks like this:</p>
<pre><code>ID class1 class2 class3 class4 class5
row1 0.97 0.2 0.4 0.3 0.2
row2 0.97 0.96 0.4 0.3 0.2
row3 0.7 0.5 0.3 0.4 0.5
row4 0.97 0.98 0.99 0.3 0.2
row5 0.1 0.2 0.3 0.78 0.8
row6 0.1 0.11 0.3 0.9 0.2
</code></pre>
<p>I'd like to filter for rows where at least 2 (or more) probability class columns have a probability that is close to at least one other probability column in that row (e.g., maybe within 0.05). So an example output would filter to:</p>
<pre><code>ID class1 class2 class3 class4 class5
row2 0.97 0.96 0.4 0.3 0.2
row4 0.97 0.98 0.99 0.3 0.2
row5 0.1 0.2 0.3 0.78 0.8
</code></pre>
<p>I don't mind if a filter includes <code>row6</code> as it also meets my <0.05 different main requirement, but ideally because the 0.05 difference isn't with the largest probability I'd prefer to ignore this too.</p>
<p>What can I do to develop a filter like this?</p>
<p>Example data:</p>
<p>Edit: I have increased the size of my example data, as I do not want pairs specifically but any and all rows that in inside their row their column values for 2 or more probabilities have close values</p>
<pre><code>
d = {'ID': ['row1', 'row2', 'row3', 'row4', 'row5', 'row6'],
'class1': [0.97, 0.97, 0.7, 0.97, 0.1, 0.1],
'class2': [0.2, 0.96, 0.5, 0.98, 0.2, 0.11],
'class3': [0.4, 0.4, 0.3, 0.2, 0.3, 0.3],
'class4': [0.3, 0.3, 0.4, 0.3, 0.78, 0.9],
'class5': [0.2, 0.2, 0.5, 0.2, 0.8, 0.2]}
df = pd.DataFrame(data=d)
</code></pre>
| [
{
"answer_id": 74452275,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "numpy"
},
{
"answer_id": 74499324,
"author": "Hamzah",
"author_id": 16733101,
"author_profile": ... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8831033/"
] |
74,452,036 | <p>So I have this text file</p>
<pre><code>(1, 15), 'indice3 = [4, 5, 6]'
(7, 1), "indice1 = {3: 'A B C'}"
(11, 7), "indice4 = '(1, 2)'"
(11, 17), 'typage = mode de déclaration des types de variable'
(23, 5), "indice5 = '(3, 4)'"
(25, 1), '27 * 37 = 999'
</code></pre>
<p>As you can see, there's at first coordinates and then a text.</p>
<p>Here's an example of what it would look like at the end (for the first two elements)</p>
<pre><code>{
(1,15): "indice3 = [4, 5, 6]",
(7, 1): "indice1 = {3: 'A B C'}"
}
</code></pre>
<p>I know that I should start by reading the file (<code>f = open("dico_objets.txt", "r")</code>) and then read it line by line but I don't know how to split it correctly.</p>
| [
{
"answer_id": 74452096,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": false,
"text": "ast.literal_eval"
},
{
"answer_id": 74452245,
"author": "vamsikakuru",
"author_id": 9258968,... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18129904/"
] |
74,452,049 | <p>Here is my file name text and it has below contents</p>
<pre><code>system
{
host name $HOSTNAME
value 25
as 635
}
</code></pre>
<p>I am writing below code to read the file :</p>
<pre><code>set HOSTNAME "NEw york"
set cf [open text r]
foreach line [split [read $cf] \n] {
puts $line
close $cf
</code></pre>
<p>When I do <code>puts $line</code> variable substitution for HOSTNAME is not done, how to do that ??</p>
| [
{
"answer_id": 74452312,
"author": "Chris Heithoff",
"author_id": 16350882,
"author_profile": "https://Stackoverflow.com/users/16350882",
"pm_score": 2,
"selected": false,
"text": "subst"
},
{
"answer_id": 74474186,
"author": "Donal Fellows",
"author_id": 301832,
"aut... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20513967/"
] |
74,452,054 | <p>Want a simple htaccess to redirect html root filename to a sub-directory.</p>
<p><a href="http://www.xyz.com/About****.php" rel="nofollow noreferrer">www.xyz.com/About****.php</a> where **** is arbitrary. The words "About" and ".php" are fixed</p>
<p>convert to <a href="http://www.xyz.com/coach/articles/About****.php" rel="nofollow noreferrer">www.xyz.com/coach/articles/About****.php</a></p>
<p>Haven't used regular expressions and htaccess for many years. Relearning curve is time consuming.</p>
| [
{
"answer_id": 74452154,
"author": "Valeriu Ciuca",
"author_id": 4527645,
"author_profile": "https://Stackoverflow.com/users/4527645",
"pm_score": 2,
"selected": false,
"text": "About****.php"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20513908/"
] |
74,452,083 | <p>I'm currently working on trying to separate values inside of a .txt file into tuples. This is so that, later on, I want to create a simple database using these tuples to look up the data. Here is my current code:</p>
<pre><code>with open("data.txt") as load_file:
data = [tuple(line.split()) for line in load_file]
c = 0
pts = []
while c < len(data):
pts.append(data[c][0])
c += 1
print(pts)
pts = []
</code></pre>
<p>Here is the text file:</p>
<pre><code>John|43|123 Apple street|514 428-3452
Katya|26|49 Queen Mary Road|514 234-7654
Ahmad|91|1888 Pepper Lane|
</code></pre>
<p>I want to store each value that is separated with a "|" and store these into my tuple in order for this database to work. Here is my current output:</p>
<pre><code>['John|43|123']
['Katya|26|49']
['Ahmad|91|1888']
</code></pre>
<p>So it is storing some of the data as a single string, and I can't figure out how to make this work. My desired end result is something like this:</p>
<pre><code>['John', 43, '123 Apple street', 514 428-3452]
['Katya', 26, '49 Queen Mary Road', 514 234-7654]
['Ahmad', 91, '1888 Pepper Lane', ]
</code></pre>
| [
{
"answer_id": 74452154,
"author": "Valeriu Ciuca",
"author_id": 4527645,
"author_profile": "https://Stackoverflow.com/users/4527645",
"pm_score": 2,
"selected": false,
"text": "About****.php"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17360950/"
] |
74,452,088 | <p>I am trying to make a interactive rating component. I have no clue how I can return the result on a span element after a rating is chosen.</p>
<p>When I enter the rating on buttons:</p>
<p><img src="https://i.stack.imgur.com/gUJi6.png" alt="enter image description here" /></p>
<p>After I submit the rating:</p>
<p><img src="https://i.stack.imgur.com/M0oG9.jpg" alt="enter image description here" /></p>
<p>There I want to return the result.</p>
<p>I was trying an if statement in the forEach function but didn't know how to return the result on the span element.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const allBtns = document.querySelectorAll('.btn');
allBtns.forEach(btn => {
btn.addEventListener('click', function onClick() {
btn.style.backgroundColor = 'orange';
})
});
function ShowAndHide() {
let y = document.querySelector('.ratingbox');
let x = document.querySelector('.thankyou');
if (x.style.display == 'none') {
y.style.display = 'none';
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="ratingbox">
<div class="backgroundstar">
<img src="images/icon-star.svg" alt="" class="star">
</div>
<div class="writing">
<h1>How did we do?</h1>
<p>Please let us know how we did with your support request. All feedback is appreciated to help us improve our offering! </p>
</div>
<div class="flexbox">
<ul>
<li><button class="btn"><p id="num">1</p></button></li>
<li><button class="btn"><p id="num">2</p></button></li>
<li><button class="btn"><p id="num">3</p></button></li>
<li><button class="btn"><p id="num">4</p></button></li>
<li><button class="btn"><p id="num">5</p></button></li>
</ul>
<button class="submit" onclick="ShowAndHide()">SUBMIT</button>
</div>
</div>
<div class="thankyou " style="display: none; ">
<div class="message ">
<img src="https://via.placeholder.com/50" alt=" " class="img ">
<div class="selected ">
<span id="rating "></span>
</div>
<div class="greeting ">
<h2>Thank you!</h2>
<p id="appreciate ">We appreciate you taking the thime to give a rating.<br> If you ever need more support, don't hesitate to <br> get in touch!
</p>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74452288,
"author": "h0r53",
"author_id": 5199418,
"author_profile": "https://Stackoverflow.com/users/5199418",
"pm_score": 0,
"selected": false,
"text": "id"
},
{
"answer_id": 74453122,
"author": "John Li",
"author_id": 20436957,
"author_profile": "htt... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19156627/"
] |
74,452,129 | <p>Various R functions make it easy to use group_by and summarize to pull a value from a grouped variable. So in the resulting dataframe, I can use group_by and summarise to create, for example, a new column that contains the maximum or minimum value of a variable within each group. Meaning, with this data:</p>
<pre><code>name, value
foo, 100
foo, 200
foo, 300
bar, 400
bar, 500
bar, 600
</code></pre>
<p>I can easily get the max or min for each value of name:</p>
<pre><code>group_by(name) %>% summarize(maxValue = max(value)
</code></pre>
<p>But suppose I want the second ranked value for each name? Meaning suppose I want my result to be</p>
<pre><code>name maxValue midValue
foo 300 200
bar 600 500
</code></pre>
<p>In other words, how do I fill in the blank in this:</p>
<pre><code>df %>% group_by(name) %>%
summarize(maxValue = max(value),
secondValue = _________)
</code></pre>
<p>Thanks, from an r newbie, for any help!</p>
| [
{
"answer_id": 74452271,
"author": "Juan C",
"author_id": 9462829,
"author_profile": "https://Stackoverflow.com/users/9462829",
"pm_score": 1,
"selected": false,
"text": "df %>% group_by(name) %>% arrange(desc(value)) %>% slice(2)\n"
},
{
"answer_id": 74453305,
"author": "San... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5176356/"
] |
74,452,136 | <p>I need a way to prevent showing duplicated content in angular template.
I have an array of data, and some of those data share the same formId. In my template I am showing the name of the array, and if the formId is unique, then after there is a divider line, but if the array share the same formId the divider line is not shown until the formId is changed.
So If I have the array:</p>
<pre><code>
</code></pre>
<pre><code>[
{
id: 1,
name: 'Test 1'
formId: '8979f9879f'
},
{
id: 2,
name: 'Test 2'
formId: '8979f9879f'
},
{
id: 3,
name: 'Test 3'
formId: 'a8098981'
},
]
</code></pre>
<pre><code>
The result should be:
Test 1
Test 2
_______
Test 3 ... and so on
The ones that share the same formId, I need to put in the same table layout, so I needed to group the data with same formId, getting the result like this:
</code></pre>
<pre><code>
[
8979f9879f: [
{
id: 1,
name: Test 1,
formId: 8979f9879f
},
{
id: 2,
name: Test 2,
formId: 8979f9879f
},
],
a8098981: [
{
id: 3,
name: Test 3,
formId: a8098981
}
]
]
</code></pre>
<pre><code>Which is fine. But now in a template when I loop though this arrays:
</code></pre>
<pre><code><ng-container *ngFor="let formItem of formListItems | async, index as i">
<div *ngFor="let groupedItem of groupedFormListItems[formItem.formId]" ...
</code></pre>
<pre><code></code></pre>
<p>I get the correct layout and result, only I get the duplicated result, because nested loop.
So the layout on the page looks like this:</p>
<p>Test 1
Test 2</p>
<hr />
<p>Test 1
Test 2</p>
<hr />
<p>Test 3</p>
<p>I need somehow to check if the formId is already been looped through, but don't know how to do that.</p>
| [
{
"answer_id": 74452271,
"author": "Juan C",
"author_id": 9462829,
"author_profile": "https://Stackoverflow.com/users/9462829",
"pm_score": 1,
"selected": false,
"text": "df %>% group_by(name) %>% arrange(desc(value)) %>% slice(2)\n"
},
{
"answer_id": 74453305,
"author": "San... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19744898/"
] |
74,452,150 | <p>i want use loop correctly inside function</p>
<p>This is my code :</p>
<pre><code>def test():
for i in range(1,10):
return i
def check():
print(test())
check()
</code></pre>
<p>output is 1</p>
<p>i want to full iteration
output : 1 ,2,4....10</p>
| [
{
"answer_id": 74452182,
"author": "wizzwizz4",
"author_id": 5223757,
"author_profile": "https://Stackoverflow.com/users/5223757",
"pm_score": 0,
"selected": false,
"text": "return"
},
{
"answer_id": 74452225,
"author": "stdfile",
"author_id": 13722988,
"author_profil... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20315528/"
] |
74,452,169 | <p>I am currently attempting to turn a list into a frequency dictionary. I am reading a file, separating the file into each individual words on a line and attempting to turn each word into its own frequency dictionary in order to find how many times it occurs. I was wondering how I would accomplish this. This is what I currently have:</p>
<pre><code>with open(file, 'r', encoding = 'utf-8') as fp:
lines = fp.readlines()
for row in lines:
for word in row.split():
print(word)
</code></pre>
<p>Currently, my program outputs a new word on each line. How would I make it so that the words are each their own dictionaries and can find the frequency of them?</p>
| [
{
"answer_id": 74452217,
"author": "Tim Roberts",
"author_id": 1883316,
"author_profile": "https://Stackoverflow.com/users/1883316",
"pm_score": 2,
"selected": false,
"text": "Counter"
},
{
"answer_id": 74452438,
"author": "treuss",
"author_id": 19838568,
"author_prof... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20481720/"
] |
74,452,183 | <p>What option is recommended in C to return an array from a function?</p>
<p><strong>Option 1:</strong></p>
<pre><code>void function_a(int *return_array){
return_array[0] = 1;
return_array[1] = 0;
}
</code></pre>
<p><strong>Option 2:</strong></p>
<pre><code>int* function_b(){
int return_array[2];
return_array[0] = 1;
return_array[1] = 0;
return return_array;
}
</code></pre>
| [
{
"answer_id": 74452218,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 3,
"selected": true,
"text": "int* function_b(){\n int return_array[2];\n return_array[0] = 1;\n return_array[1] = 0;\n return... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16350154/"
] |
74,452,205 | <p>I have created a <code>BottomNavigationBar</code> with my app, but when I navigate to a new page by clicking on <code>Profile</code> the <code>BottomNavigationBar</code> goes away. I have been working on this for hours and I am about to give up lol. Any ideas?</p>
<p><code>app.dart</code></p>
<pre><code>@override
Widget build(BuildContext context, WidgetRef ref) {
return MaterialApp(
routes: {
'/home':(context) => HomePage(),
'/activity':(context) => ActivityPage(),
'/profile':(context) => ProfilePage(),
},
home: Builder(
builder: (context) => Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home_filled), label: 'Home',),
BottomNavigationBarItem(
icon: Icon(Icons.track_changes), label: 'Activity'),
BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'),
],
onTap: (index) {
switch (index) {
case 0:
Navigator.pushNamed(context, '/home');
break;
case 1:
Navigator.pushNamed(context, '/activity');
break;
case 2:
Navigator.pushNamed(context, '/profile');
break;
}
},
),
body: MaterialApp.router(
builder: EasyLoading.init(),
theme: ThemeData(
appBarTheme: const AppBarTheme(color: Color(0xFF13B9FF)),
colorScheme: ColorScheme.fromSwatch(
accentColor: const Color(0xFF13B9FF),
),
),
routerDelegate: AutoRouterDelegate(
_appRouter,
navigatorObservers: () => [AppRouteObserver()],
),
routeInformationProvider: _appRouter.routeInfoProvider(),
routeInformationParser: _appRouter.defaultRouteParser(),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
debugShowCheckedModeBanner: false,
),
),
),
);
}
}
</code></pre>
<p>I tried clicking on different pages and still did not get the navbar to follow.</p>
| [
{
"answer_id": 74452218,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 3,
"selected": true,
"text": "int* function_b(){\n int return_array[2];\n return_array[0] = 1;\n return_array[1] = 0;\n return... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20453098/"
] |
74,452,212 | <p>I've got an incoming bytestream of blocks of 16 uint8_t that I need to expand into 4x uint32x4_t neon registers for further processing. This is going to run on a core based on Cortex-A55. Here's an example bytestream: {0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0xA,0xB,0xC,0xD,0xF}.</p>
<p>Here's what I've got so far:</p>
<pre><code>#include <stdint.h>
#if defined(__aarch64__)
#include <arm_neon.h>
#else
typedef unsigned int uint32x4_t __attribute__ ((vector_size (16)));
typedef unsigned char uint8x16_t __attribute__ ((vector_size (16)));
#endif
#if defined(__BYTE_ORDER__)&&(__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
#define select_u8x4_from_u8x16( a, b, c, d) {255,255,255,(a),255,255,255,(b),255,255,255,(c),255,255,255,(d)}
#else
#define select_u8x4_from_u8x16( a, b, c, d) {(a),255,255,255,(b),255,255,255,(c),255,255,255,(d),255,255,255}
#endif
//Wrapper around vqtbl1q_u8()
static inline uint8x16_t table_16u8(uint8x16_t mat, uint8x16_t indexes)
{
#if defined( __aarch64__ )
return vqtbl1q_u8(mat, indexes);
#else
uint8x16_t result;
for( unsigned i = 0; i < sizeof(mat); ++i )
{
result[i] = mat[indexes[i]];
}
return result;
#endif
}
uint32_t test_function(const uint8_t * samples, unsigned num_samples/*always divisible by 16*/)
{
static const uint8x16_t idx_a = select_u8x4_from_u8x16(0,1,2,3);
static const uint8x16_t idx_b = select_u8x4_from_u8x16(4,5,6,7);
static const uint8x16_t idx_c = select_u8x4_from_u8x16(8,9,10,11);
static const uint8x16_t idx_d = select_u8x4_from_u8x16(12,13,14,15);
uint32x4_t dummy_accumulator = {0,0,0,0};
for(unsigned x = 0; x < num_samples; x += 16)
{
/*Begin section I'd like help with*/
uint8x16_t pxvect = *((uint8x16_t*)(samples+x));
uint32x4_t temp_a = (uint32x4_t)table_16u8(pxvect, idx_a);/*holds {0x0,0x1,0x2,0x3}*/
uint32x4_t temp_b = (uint32x4_t)table_16u8(pxvect, idx_b);/*holds {0x4,0x5,0x6,0x7}*/
uint32x4_t temp_c = (uint32x4_t)table_16u8(pxvect, idx_c);/*holds {0x8,0x9,0xA,0xB}*/
uint32x4_t temp_d = (uint32x4_t)table_16u8(pxvect, idx_d);/*holds {0xC,0xD,0xE,0xF}*/
/*End section I'd like help with.*/
/*Sum the values to produce a return value*/
dummy_accumulator += temp_a;
dummy_accumulator += temp_b;
dummy_accumulator += temp_c;
dummy_accumulator += temp_d;
}
return dummy_accumulator[0]+dummy_accumulator[1]+dummy_accumulator[2]+dummy_accumulator[3];
}
uint32_t test_harness(void)
{
uint8_t test_vec[] = {0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0xA,0xB,0xC,0xD,0xF};
return test_function(test_vec, sizeof(test_vec));
}
</code></pre>
<p>I've seen VLD4, but that packs the results, and I don't want that. If I calculate transposed(I'd prefer not to, there's a cost for the rest of the math not shown), my first pass was:</p>
<pre><code>uint32_t test_function(const uint8_t * samples, unsigned num_samples/*always divisible by 16*/)
{
#define splat_u32x4(a){(a),(a),(a),(a)}
static const uint32x4_t mask_a = splat_u32x4(0xffUL);
static const uint32x4_t mask_b = splat_u32x4(0xffUL<<8);
static const uint32x4_t mask_c = splat_u32x4(0xffUL<<16);
static const uint32x4_t mask_d = splat_u32x4(0xffUL<<24);
uint32x4_t dummy_accumulator = {0,0,0,0};
for(unsigned x = 0; x < num_samples; x += 16)
{
/*Begin section I'd like help with*/
uint8x16_t pxvect = *((uint8x16_t*)(samples+x));
uint32x4_t temp_a = ((uint32x4_t)pxvect & mask_a) >> 0; /*holds{0x0,0x4,0x8,0xC}*/
uint32x4_t temp_b = ((uint32x4_t)pxvect & mask_b) >> 8; /*holds{0x1,0x5,0x9,0xD}*/
uint32x4_t temp_c = ((uint32x4_t)pxvect & mask_c) >> 16;/*holds{0x2,0x6,0xA,0xE}*/
uint32x4_t temp_d = ((uint32x4_t)pxvect & mask_d) >> 24;/*holds{0x3,0x7,0xB,0xF}*/
/*End section I'd like help with.*/
/*Sum the values to produce a return value*/
dummy_accumulator += temp_a;
dummy_accumulator += temp_b;
dummy_accumulator += temp_c;
dummy_accumulator += temp_d;
}
return dummy_accumulator[0]+dummy_accumulator[1]+dummy_accumulator[2]+dummy_accumulator[3];
}
</code></pre>
<p>I'd like to do this operation of loading 16 bytes and spreading them into 4x zero-extended uint32x4_t registers as quickly as possible, ideally in linear order rather than 4x4 transposed. Is there a better way to do so?</p>
| [
{
"answer_id": 74452694,
"author": "solidpixel",
"author_id": 533037,
"author_profile": "https://Stackoverflow.com/users/533037",
"pm_score": 0,
"selected": false,
"text": "q0 = 16 packed byte values\nq1 = Zeros\nq2 = Zeros\nq3 = Zeros\n\nvzip.u8 q0, q2 // Interleave u8 and zeros to get... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1125660/"
] |
74,452,216 | <p>I wrote this sample code to show only a single image after passing it to my model. The model should have only one convolutional layer and one pooling layer. Or in another way, how can I visualize a single image by passing it to a simple neural network that has one convolutional and one pooling layer?</p>
<pre class="lang-py prettyprint-override"><code>import torch
import torch.nn as nn #creating neural network
from PIL import Image
from numpy import asarray
# Set up GPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# load the image
image = Image.open('./img.png')
# convert image to numpy array
data = asarray(image)
print(type(data))
print(data.shape)
</code></pre>
<p>now building the arch.</p>
<pre><code>class ConvNet(nn.Module):
def __init__(self):
super().__init__()
#convolutional layer
self.layer = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=3, kernel_size=2, stride=1, padding=0),
nn.MaxPool2d(kernel_size=2, stride=2))
def forward(self, x):
out = self.layer(x)
return out
convnet = ConvNet().to(device) #set up for GPU if available
convnet
</code></pre>
<p>pass image to my model
<code>outputs = convnet(data) imshow(outputs)</code></p>
<p>got the error below</p>
<pre><code>TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_3184/1768392595.py in <module>
----> 1 outputs = convnet(data)
2 imshow(outputs)
TypeError: conv2d() received an invalid combination of arguments - got (numpy.ndarray, Parameter, Parameter, tuple, tuple, tuple, int), but expected one of:
* (Tensor input, Tensor weight, Tensor bias, tuple of ints stride, tuple of ints padding, tuple of ints dilation, int groups)
didn't match because some of the arguments have invalid types: (numpy.ndarray, Parameter, Parameter, tuple, tuple, tuple, int)
* (Tensor input, Tensor weight, Tensor bias, tuple of ints stride, str padding, tuple of ints dilation, int groups)
didn't match because some of the arguments have invalid types: (numpy.ndarray, Parameter, Parameter, tuple, tuple, tuple, int)
</code></pre>
<p>I expect to show image after passed during this sample network</p>
| [
{
"answer_id": 74452694,
"author": "solidpixel",
"author_id": 533037,
"author_profile": "https://Stackoverflow.com/users/533037",
"pm_score": 0,
"selected": false,
"text": "q0 = 16 packed byte values\nq1 = Zeros\nq2 = Zeros\nq3 = Zeros\n\nvzip.u8 q0, q2 // Interleave u8 and zeros to get... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20252189/"
] |
74,452,220 | <p>I am trying to get the resource limits & requests for Kubernetes pods. I am attempting to output to a comma delimited row that lists the namespace, pod name, container name and then the mem & CPU limits/requests for each container. Running into issues when there's multiple containers per pod.</p>
<p>The closest I've been able to get is this which will print out a single row for each pod. If there are multiple containers, they are listed in separate "columns" in the same row.</p>
<p><code>kubectl get pods --all-namespaces -o jsonpath='{range .items[*]}{@.metadata.namespace}{","}{@.metadata.name}{","}{range .spec.containers[*]}{.name}{","}{@.resources.requests.cpu}{","}{@.resources.requests.memory}{","}{@.resources.limits.cpu}{","}{@.resources.limits.memory}{","}{end}{"\n"}{end}'</code></p>
<p>The output looks like this:</p>
<pre><code>kube-system,metrics-server-5f8d84558d-g926z,metrics-server-vpa,5m,30Mi,100m,300Mi,metrics-server,46m,63Mi,46m,63Mi,
</code></pre>
<p>What I would like to see is something like this:</p>
<pre><code>kube-system,metrics-server-5f8d84558d-g926z,metrics-server-vpa,5m,30Mi,100m,300Mi,
kube-system,metrics-server-5f8d84558d-g926z,metrics-server,46m,63Mi,46m,63Mi,
</code></pre>
<p>Appreciate any assistance. Thanks.</p>
| [
{
"answer_id": 74452694,
"author": "solidpixel",
"author_id": 533037,
"author_profile": "https://Stackoverflow.com/users/533037",
"pm_score": 0,
"selected": false,
"text": "q0 = 16 packed byte values\nq1 = Zeros\nq2 = Zeros\nq3 = Zeros\n\nvzip.u8 q0, q2 // Interleave u8 and zeros to get... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20514037/"
] |
74,452,229 | <p>I have <code>Prolog</code> database with airplane schedules. Here is how it looks like:</p>
<pre><code>fly(id, from, to, days(1, 0, 1, 0, 1, 0, 1)).
</code></pre>
<p>As you can see there are 7 values in <code>days</code> predicate - from Monday to Sunday. What I want to do is to print every day, where value is <code>1</code>, but print it into just text. I was trying to use <code>if - else</code> statement, but in this case it doesn't work how it is supposed to:</p>
<pre><code>(
A = 1 -> write(monday), nl;
(
B = 1 -> write(tuesday), nl;
(
C = 1 -> write(wednesday), nl;
(
D = 1 -> write(thursday), nl;
(
E = 1 -> write(friday), nl;
(
F = 1 -> write(saturday), nl;
(
G = 1 -> write(sunday), nl
)
)
)
)
)
)
)
</code></pre>
<p>In example case it should print 4 days:</p>
<pre><code>monday
wednesday
friday
sunday
</code></pre>
<p>How can I do that?</p>
| [
{
"answer_id": 74452679,
"author": "dokichan",
"author_id": 16732680,
"author_profile": "https://Stackoverflow.com/users/16732680",
"pm_score": 3,
"selected": true,
"text": "loop"
},
{
"answer_id": 74453320,
"author": "brebs",
"author_id": 17628336,
"author_profile": ... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16732680/"
] |
74,452,242 | <p>I created an iframe in vex6.html and a js file in styles.gq/test.js and in that file there is the link and id but when I try to call the code in html it does not work.</p>
<p>Here is my code for vex6.html</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<script type="text/javascript" src="https://styles.gq/test.js" ></script>
<iframe id="vex6" width="100%" height="500" style="border:1px solid black;"></iframe>
</body>
</html>
</code></pre>
<p>here is my js code</p>
<pre><code>document.getElementById("vex3").src
= "https://www.obviousplays.tk/gfiles/vex3";
document.getElementById("vex4").src
= "https://www.obviousplays.tk/gfiles/vex4";
document.getElementById("vex5").src
= "https://www.obviousplays.tk/gfiles/vex5";
document.getElementById("vex6").src
= "https://www.obviousplays.tk/Gfiles6/vex6";
document.getElementById("slope").src
= "https://www.obviousplays.tk/gfiles/slope";
</code></pre>
<p>I expected an iframe but instead there seems to be no link for the iframe
it is also spitting out the error cannot set properties of null (setting(src))</p>
| [
{
"answer_id": 74452499,
"author": "Stefan Scharinger",
"author_id": 16052813,
"author_profile": "https://Stackoverflow.com/users/16052813",
"pm_score": 2,
"selected": true,
"text": "<script type=\"text/javascript\" src=\"https://styles.gq/test.js</script>"
},
{
"answer_id": 7445... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19333152/"
] |
74,452,337 | <p>I imported some custom checkboxes but they're displaying vertically and I want them to be displayed horizontally in a row</p>
<p>I tried changing the flex-direction and some other things but none of that has changed anything.
Here is my code:</p>
<pre><code>import { Pressable, StyleSheet, Text, View } from "react-native";
import React from "react";
import { MaterialCommunityIcons } from "@expo/vector-icons";
const CheckBox = (props) => {
const iconName = props.isChecked
? "checkbox-marked"
: "checkbox-blank-outline";
return (
<View style={styles.container}>
<Pressable onPress={props.onPress}>
<MaterialCommunityIcons name={iconName} size={40} color="#000" />
</Pressable>
<Text style={styles.title}>{props.title}</Text>
</View>
);
};
export default CheckBox;
const styles = StyleSheet.create({
container: {
justifyContent: "center",
alignItems: "center",
flexDirection: "column",
width: 150,
marginTop: 5,
marginHorizontal: 5,
flexWrap: "wrap",
},
title: {
fontSize: 20,
color: "#000a",
textAlign: "left",
top: 50,
marginTop: 40,
},
});
</code></pre>
| [
{
"answer_id": 74452667,
"author": "David Scholz",
"author_id": 14969281,
"author_profile": "https://Stackoverflow.com/users/14969281",
"pm_score": 0,
"selected": false,
"text": "flexDirection"
},
{
"answer_id": 74452819,
"author": "Rohit Soni",
"author_id": 20514408,
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20513383/"
] |
74,452,364 | <p>Im new to React and im trying build a live chat website , but i got stuck in the section of login and registration , im just trying to navigate between these 2 pages i will put my code under , if i did something wrong don't hesitate please :</p>
<p><strong>App.js :</strong>
`</p>
<pre><code>import './App.css';
import React ,{Component} from 'react';
import { Typography } from '@material-ui/core'
import Button from '@mui/material/Button';
import {
BrowserRouter as Router,
Route,
Routes, Link
} from "react-router-dom";
import LoginPage from './componenets/login/LoginPage';
import Register from './componenets/Register/Register';
class App extends Component {
render() {
return (
<Router>
<div className='App-header'>
<Typography variant="h1" component="h2">
Live Chat
</Typography>
<div className='group_btn'>
<div className='btn'>
<Link to='/logn'>
<Button className='btn_s' variant="contained" color='success' size="large">
Login
</Button>
</Link>
</div>
<div className='btnc'>
<Link to='/reg'>
<Button className='btn_s' variant="contained" color='success' size="large">
Register
</Button>
</Link>
</div>
<Routes>
<Route path='/logn' exact element={<LoginPage/>}/>
<Route path='/reg' exact element={<Register/>}/>
</Routes>
</div>
</div>
</Router>
);
}
}
export default App;
</code></pre>
<p><code>**LoginPage.js :**</code></p>
<pre><code>import React ,{Component} from 'react'
import './LoginPage.css'
import { Typography } from '@material-ui/core'
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
class Login_Page extends Component {
render() {
return (
<div className='lgn'>
<div className='title'>
<Typography variant="h1" component="h2">
Live Chat
</Typography>
</div>
<div className='lgn_inputs'>
<Box
component="form"
sx={{
'& > :not(style)': { m: 1, width: '45ch' },
}}
noValidate
autoComplete="off"
>
<TextField id="outlined-basic" label="Username" variant="outlined" />
<TextField id="outlined-basic" label="Email" variant="outlined" />
<TextField id="outlined-basic" label="Password" variant="outlined" />
</Box>
</div>
<div className='btn'>
<Button className='btn_s' href='#' onClick={ () => alert('You are Logged in') } variant="contained" color='success' size="large">
Login
</Button>
</div>
</div>
);
}
}
export default Login_Page;
</code></pre>
<p>`</p>
<p>i've tried so many things like : Switch but it gives me blank page , i did use useNavigate and i got the same result like the code above.</p>
| [
{
"answer_id": 74452632,
"author": "mmender22",
"author_id": 19346492,
"author_profile": "https://Stackoverflow.com/users/19346492",
"pm_score": 0,
"selected": false,
"text": "<Route></Route>\n"
},
{
"answer_id": 74545774,
"author": "mohammad ali",
"author_id": 9545762,
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19431629/"
] |
74,452,367 | <p>I am really new to javascript so forgive any mistakes in my presentation of my question. I have the following object and am trying to figure out how to find the sum quantity of all items. I am looking for the output of "17".</p>
<p>Here is the object:</p>
<pre><code>const cart = {
"tax": .10,
"items": [
{
"title": "milk",
"price": 4.99,
"quantity": 2
},
{
"title": "rice",
"price": 0.99,
"quantity": 2
},
{
"title": "candy",
"price": 0.99,
"quantity": 3
},
{
"title": "bread",
"price": 2.99,
"quantity": 1
},
{
"title": "apples",
"price": 0.75,
"quantity": 9
}
]
}
</code></pre>
<p>I have been working on finding solutions for the last 4 hours. This includes trying to find videos/written info on how to understand objects/arrays that are nested within properties. Any help in getting pointed in the right direction would be greatly appreciated. Thank you.</p>
| [
{
"answer_id": 74452632,
"author": "mmender22",
"author_id": 19346492,
"author_profile": "https://Stackoverflow.com/users/19346492",
"pm_score": 0,
"selected": false,
"text": "<Route></Route>\n"
},
{
"answer_id": 74545774,
"author": "mohammad ali",
"author_id": 9545762,
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20504727/"
] |
74,452,368 | <p>I am creating a shuffle game and for that, I have set 3 levels of the grid,</p>
<p>I have taken a fixed-sized container of 300x300 and I don't want to change its size,</p>
<p>here I want to place all grid buttons properly inside a grid but I am getting space at top of the grid view and due to that, the buttons are not showing properly fit.</p>
<p>here is my code</p>
<pre><code>final kdecoration = BoxDecoration(
border: Border.all(color: Colors.yellow, width: 1),
borderRadius: BorderRadius.circular(5),
color: Colors.red);
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
double w = 300;
double h = 300;
int gridvalue = 3;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Center(
child: Text(
'$gridvalue x $gridvalue',
style: TextStyle(fontSize: 30, color: Colors.blue),
)),
SizedBox(
height: 20,
),
Container(
color: Colors.blue,
height: h,
width: w,
child: GridView.builder(
physics: NeverScrollableScrollPhysics(),
itemCount: gridvalue * gridvalue,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
mainAxisSpacing: 0,
crossAxisSpacing: 0,
crossAxisCount: gridvalue,
),
itemBuilder: (context, index) {
return Container(
decoration: kdecoration,
child: Center(
child: Text(
(index + 1).toString(),
style: TextStyle(fontSize: 20, color: Colors.white),
)),
//color: Colors.green,
);
})),
SizedBox(
height: 20,
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () {
setState(() {
gridvalue = 3;
});
},
child: Text('3x3')),
ElevatedButton(
onPressed: () {
setState(() {
gridvalue = 4;
});
},
child: Text('4x4')),
ElevatedButton(
onPressed: () {
setState(() {
gridvalue = 5;
});
},
child: Text('5x5')),
],
),
)
],
),
);
}
}
</code></pre>
<p>placed output image as well...<a href="https://i.stack.imgur.com/aaDuM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aaDuM.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74455286,
"author": "Kasymbek R. Tashbaev",
"author_id": 14891973,
"author_profile": "https://Stackoverflow.com/users/14891973",
"pm_score": 3,
"selected": true,
"text": "GridView"
},
{
"answer_id": 74455456,
"author": "aminjafari-dev",
"author_id": 1969965... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18817235/"
] |
74,452,388 | <p>I would like to write a simple function (I'm beginner), in my script, to check and test user's API KEY from VirusTotal.</p>
<p>That's my idea:</p>
<p>Firstly, I would like to check if user type his API KEY in code or field is empty.</p>
<p>Secondly, I would like to check if API KEY is correct. I had no idea how to check it the easiest way, so I use the simplest query I found on VirusTotal and check if the response code is 200.</p>
<p>But I have problem when API Key field is empty and user type wrong API Key. After that, my function ends. I would like to return to the previous if condition and check if this time the api key is correct.</p>
<p>When user type correct API KEY, function print proper message.</p>
<p>This is my code:</p>
<pre><code>import requests
import json
def auth_vt_apikey():
"""This function test VirusTotal's Api Key"""
api_key = ''
if api_key == '':
api_key = str(input("Please enter your VirusTotal's API Key: "))
else:
None
url = 'https://www.virustotal.com/vtapi/v2/url/report'
params = {'apikey': api_key}
response = requests.get(url, params=params)
if response.status_code == 200:
print('Your Api Key is correct')
else:
api_key = str(input("Your Api Key is incorrect. Please re-type your Api Key: "))
auth_vt_apikey()
</code></pre>
<p>Can you explain to me what I'm doing wrong here and what is worth adding? I will also be grateful for links to guides, so that I can educate myself on this example.</p>
| [
{
"answer_id": 74455286,
"author": "Kasymbek R. Tashbaev",
"author_id": 14891973,
"author_profile": "https://Stackoverflow.com/users/14891973",
"pm_score": 3,
"selected": true,
"text": "GridView"
},
{
"answer_id": 74455456,
"author": "aminjafari-dev",
"author_id": 1969965... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509308/"
] |
74,452,411 | <p>How may I find in two (or more) arrays duplicates and show it ?</p>
<p>I want to use filter, It's a good idea to use it ?</p>
<p>This is what I tried <strong>:</strong></p>
<pre><code>let monday = ["task1", "task2", "task3", "task4", "taks5", "task6", "taks7"];
let tuesday = ["task2", "task3", "task4", "task5", "taks6"];
let wendesday = ["task7", "task8", "task9", "task10", "taks11", "task12"];
const takePastList = monday
.concat(tuesday)
.join(" ")
.filter((task, index) => index !== monday.indexOf(task));
</code></pre>
<p>In above solution, <code>concat</code> works but <code>filter</code> not.</p>
<p>Find how to fix it and understand how to use filter or other method to find duplicate when I work on many arrays with many methods.</p>
| [
{
"answer_id": 74452711,
"author": "esQmo_",
"author_id": 5374691,
"author_profile": "https://Stackoverflow.com/users/5374691",
"pm_score": 0,
"selected": false,
"text": "let monday = [\"task1\", \"task2\", \"task3\", \"task4\", \"taks5\", \"task6\", \"taks7\"];\nlet tuesday = [\"task2\"... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19792261/"
] |
74,452,418 | <p>Here is my config file:</p>
<pre><code>{
"credentials":
{
"server": "0.1.2.3,6666",
"database": "db",
"username": "user",
"password": "password"
}
}
</code></pre>
<p>Here is my python script in a separate file:</p>
<pre><code>import pandas as pd
import datatest as dt
import datetime
import json
import pyodbc
with open(r"path_to_config.json", 'r') as config_file:
lines=config_file.readlines()
df = json.load(config_file)
server=config_file['server']
database=config_file['database']
username=config_file['username']
password=config_file['password']
connection_string = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER='+server+';'
'DATABASE='+database+';'
'UID='+username+';'
'PWD='+password+';')
cursor = connection_string.cursor()
SQL_STATEMENT = "SELECT COUNT(*) FROM table1"
cursor.execute(SQL_STATEMENT)
for i in cursor:
print(i)
</code></pre>
<p>Here is my error:</p>
<pre><code> raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code></pre>
<p>I've tried using json.loads(), I have tried creating a dictionary in my json file, I'm using readlines() and I've tried read() as well, I'm not sure what to do. My JSON file has data in it, not sure why the error is saying it expects data because it's right there. I think the issue lies where I am defining: <code>server=config_file['server']</code></p>
| [
{
"answer_id": 74452711,
"author": "esQmo_",
"author_id": 5374691,
"author_profile": "https://Stackoverflow.com/users/5374691",
"pm_score": 0,
"selected": false,
"text": "let monday = [\"task1\", \"task2\", \"task3\", \"task4\", \"taks5\", \"task6\", \"taks7\"];\nlet tuesday = [\"task2\"... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20412585/"
] |
74,452,431 | <p>I'm sorry if this is a duplicate post but search seemed to yield no useful results...or maybe I'm such a noob that I'm not understanding what is being said in the answers.</p>
<p>I wrote this small code for practice (following "learning Python the hard way"). I tried to make a shorter version of a code which was already given to me.</p>
<pre><code>from sys import argv
script, from_file, to_file = argv
# here is the part where I tried to simplify the commands and see if I still get the same result,
# Turns out it's the same 2n+2
trial = open(from_file)
trial_data = trial.read()
print(len(trial_data))
trial.close()
# actual code after defining the argumentative variables
in_file = open(from_file).read()
input(f"Transfering {len(in_file)} characters from {from_file} to {to_file}, hit RETURN to continue, CRTL-C to abort.")
#'in_data = in_file.read()
out_file = open(to_file, 'w').write(in_file)
</code></pre>
<p>When using len() it always seems to return 2n+2 value instead of n, where n is the actual number of characters in the text file. I also made sure there are no extra lines in the text file.</p>
<p>Can someone kindly explain?</p>
<p>TIA</p>
<p>I was expecting the exact number of characters found in the txt file to be returned. Turns out it's too much to ask.</p>
<p>Edit: since so many are asking for a practical example....here it goes:</p>
<pre><code>The poem
dedicated to Puxijn
The Chonk one
</code></pre>
<p>What i get is</p>
<pre><code>ÿþT h e p o e m
d e d i c a t e d t o P u x i j n
T h e C h o n k o n e
</code></pre>
<p>I think it is an encoding problem. I'm using the latest python if that is of any help.</p>
| [
{
"answer_id": 74452475,
"author": "partizanos",
"author_id": 4061637,
"author_profile": "https://Stackoverflow.com/users/4061637",
"pm_score": -1,
"selected": false,
"text": "echo \"a\" > test_file\n"
},
{
"answer_id": 74452517,
"author": "cafce25",
"author_id": 442760,
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20514139/"
] |
74,452,443 | <p>so I am trying to make a object parameter optional, with optional props, and have a default value at the same time:</p>
<pre><code>const myfunc = ({ stop = false }: { stop?: boolean } = { stop: false }) => {
// do stuff with "stop"
}
</code></pre>
<p>this works fine, but notice that crazy function definition!</p>
<p>Any way to not repeat so much code?</p>
| [
{
"answer_id": 74452502,
"author": "CollinD",
"author_id": 5298696,
"author_profile": "https://Stackoverflow.com/users/5298696",
"pm_score": 3,
"selected": true,
"text": "interface MyFuncOptions {\n stop: boolean;\n}\nconst myFunc = (options: Partial<MyFuncOptions> = {}) => {\n const d... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/376947/"
] |
74,452,453 | <p>I am creating a kafka instance creation script and I want to gather the bootstrap server from a describe command.</p>
<p>The command to gather the kafka instance details is.</p>
<pre><code>rhoas kafka describe
</code></pre>
<p>the output looks something like this</p>
<pre><code>"admin_api_server_url": "server-address",
"billing_model": "standard",
"bootstrap_server_host": "foobar",
"browser_url": "browser-url",
"cloud_provider": "aws",
</code></pre>
<p>What I am looking for is a grep command that will return just <code>foobar</code> from <code>"bootstrap_server_host"</code><br></p>
<p>I have tried
<code>rhoas kafka describe | grep bootstrap_server_host</code> which returns the whole line. <br></p>
<pre><code>"bootstrap_server_host": "foobar",
</code></pre>
<p>I just want <code>foobar</code> by itself.
Thanks</p>
| [
{
"answer_id": 74452506,
"author": "Arnaud Valmary",
"author_id": 6255757,
"author_profile": "https://Stackoverflow.com/users/6255757",
"pm_score": 2,
"selected": true,
"text": "rhoas kafka describe | grep bootstrap_server_host | cut -d \\\" -f 4\n"
},
{
"answer_id": 74452654,
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20281834/"
] |
74,452,460 | <p>My app has different parts and I want them to have different theme colors, including for all the subroutes in the navigation.</p>
<p>But if I use a Theme, it's not applied to the widgets in the subroutes.
I also tried to use nested MaterialApps but this won't work because I can't pop back to the root menu.
I'd prefer not to have to pass a Color parameter to all the screens.
What should I do?</p>
<p>Here is a test code:</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart';
main() {
runApp(MaterialApp(home: _Test()));
}
class _Test extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
child: Text('Red section'),
onPressed: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) {
return Theme(
data: ThemeData(colorScheme: ColorScheme.light(primary: Colors.red)),
child: _TestSubRoute(),
);
},
));
},
),
const SizedBox(height: 16),
ElevatedButton(
child: Text('Green section'),
onPressed: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) {
return Theme(
data: ThemeData(colorScheme: ColorScheme.light(primary: Colors.green)),
child: _TestSubRoute(),
);
},
));
},
),
],
),
),
);
}
}
class _TestSubRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).colorScheme.primary.withOpacity(0.2),
appBar: AppBar(
title: Text('Should keep the same color through the navigation...'),
actions: [
IconButton(
icon: Icon(Icons.help),
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Hello'),
actions: [
TextButton(
child: Text('OK'),
onPressed: () => Navigator.pop(context),
),
],
);
},
);
},
),
],
),
body: Center(
child: ElevatedButton(
child: Text('Push...'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => _TestSubRoute()),
);
},
),
),
);
}
}
</code></pre>
| [
{
"answer_id": 74452531,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 2,
"selected": false,
"text": "ThemeData"
},
{
"answer_id": 74505135,
"author": "baek",
"author_id": 1049200,
"author_profile"... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/639722/"
] |
74,452,463 | <p>I am fairly new to working with python and finally encountered a problem I cannot circumvent. I will make this fairly simple.</p>
<p>I have a csv file with many lines that looks like this once I create a list variable:</p>
<pre><code>['1\t10000\t11000\tabcdef\t1\t+\t10000\t11000\t"0,0,0"\t1\t1000\t0\n']
</code></pre>
<p>I want to add 2 new string variables after the final \t0 before the \n. Its important to indicate I still want the \t before str1 and str2. So the output I desire should look like this:</p>
<pre><code>['1\t10000\t11000\tabcdef\t1\t+\t10000\t11000\t"0,0,0"\t1\t1000\t0\tstr1\tstr2n']
</code></pre>
<p>Thanks for your help!</p>
<pre><code>str1 = hello
str2 = world
line = ['1\t10000\t11000\tabcdef\t1\t+\t10000\t11000\t"0,0,0"\t1\t1000\t0\n']
line.append(('\t') + str1 + ('\t') + str2)
print(line)
</code></pre>
<p>Current output:</p>
<pre><code>['1\t10000\t11000\tabcdef\t1\t+\t10000\t11000\t"0,0,0"\t1\t1000\t0\n', '\tstr1\tstr2']
</code></pre>
| [
{
"answer_id": 74452531,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 2,
"selected": false,
"text": "ThemeData"
},
{
"answer_id": 74505135,
"author": "baek",
"author_id": 1049200,
"author_profile"... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330606/"
] |
74,452,533 | <p>Given this dataframe:</p>
<pre><code>+-----+-----+----+
|num_a|num_b| sum|
+-----+-----+----+
| 1| 1| 2|
| 12| 15| 27|
| 56| 11|null|
| 79| 3| 82|
| 111| 114| 225|
+-----+-----+----+
</code></pre>
<p>How would you fill up <code>Null</code> values in sum column if the value can be gathered from other columns? In this example 56+11 would be the value.</p>
<p>I've tried <code>df.fillna</code> with an udf, but that doesn't seems to work, as it was just getting the column name not the actual value. I would want to compute the value just for the rows with missing values, so creating a new column would not be a viable option.</p>
| [
{
"answer_id": 74452531,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 2,
"selected": false,
"text": "ThemeData"
},
{
"answer_id": 74505135,
"author": "baek",
"author_id": 1049200,
"author_profile"... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13608873/"
] |
74,452,544 | <p>A task:
Write a function that takes an array and a number n. Then output an array in which there are no elements that are repeated more than n times.<br />
Example:<br />
Input:<br />
n = 3;<br />
arr = [1, 2, 4, 4, 4, 2, 2, 2, 2]<br />
Output:<br />
result = [1, 2, 4, 4, 4, 2, 2]</p>
<p>Tried to do something like that, but it's not working correctly.</p>
<pre><code>let arr = [1, 2, 4, 4, 4, 2, 2, 2, 2];
let new_set = [...new Set(arr)];
let result = [];
console.log(new_set); // [1, 2, 4]
first:
for (let i = 0; i < arr.length; i++) {
if (arr[i] === arr[i - 1]) {
continue first;
}
else {
let count = 0;
for (let j = i; j < arr.length; j++) {
if ((arr[i] === arr[j]) && (count < 3)) {
result.push(arr[j]);
}
}
}
}
</code></pre>
| [
{
"answer_id": 74452622,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 2,
"selected": true,
"text": "const arr = [1, 2, 4, 4, 4, 2, 2, 2, 2]\nlet n = 3;\n\nconst counts = {};\nconst result = [];\nfor (const ... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8840199/"
] |
74,452,565 | <p>I am trying to write this scalar UDF:</p>
<pre><code>CREATE FUNCTION [dbo].[DAYSADDNOWK](@addDate AS DATE, @numDays AS INT)
RETURNS DATETIME
AS
BEGIN
WHILE @numDays>0
BEGIN
SET @addDate=DATEADD(d,1,@addDate)
IF DATENAME(DW,@addDate)='saturday' SET @addDate=DATEADD(d,1,@addDate)
IF DATENAME(DW,@addDate)='sunday' SET @addDate=DATEADD(d,1,@addDate)
SET @numDays=@numDays-1
END
RETURN CAST(@addDate AS DATETIME)
END
GO
</code></pre>
<p>as an inline TVF.</p>
<p>I have been trying to use CTEs in the TVF to replace the <code>while</code> loop, but I keep running into myriad issues, so if anyone has any ideas and could help I would be incredibly grateful.</p>
<p>Requirements: Take in a date, <code>d</code>, and an integer, <code>i</code>, as parameters and return a date that is that is <code>i</code> many business days (weekdays) from the date, <code>d</code>, argument passed in.</p>
<p>While I appreciate that there may be better ways to go about this, and would love to read them if they're suggested here, I also really would like to know how to accomplish this using recursive CTE(s) in a Inline TVF as I am more doing this as practice so I can apply this technique to more complicated scalar UDF's I may need to refactor in the future.</p>
| [
{
"answer_id": 74452836,
"author": "John Cappelletti",
"author_id": 1570000,
"author_profile": "https://Stackoverflow.com/users/1570000",
"pm_score": 2,
"selected": true,
"text": "CREATE FUNCTION [dbo].[YourFunctionName] (@D date,@I int)\nReturns Table\nReturn (\n\nSelect WorkDate = D\n ... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10362066/"
] |
74,452,567 | <p>I am making a function to categorize data, but i am recieving this error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p>
<pre><code>import pandas as pd
df=pd.read_csv(r'C:\Users\gabri\Downloads\credit_scoring_eng.csv')
def economic_class(valor):
if valor<=16000:
return 'economic_class'
elif valor<=24000:
return 'executive_class'
elif valor<=32000:
return 'first_class'
else:
return 'five_star_class'
df['class'] = df['total_income'].apply(economic_class)
</code></pre>
<p>Here is the complete error:</p>
<pre><code>Cell In [172], line 3
1 # Criar coluna com categorias
2 print(df['total_income'])
----> 3 df['class'] = df['total_income'].apply(economic_class)
File c:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\series.py:4433, in Series.apply(self, func, convert_dtype, args, **kwargs)
4323 def apply(
4324 self,
4325 func: AggFuncType,
(...)
4328 **kwargs,
4329 ) -> DataFrame | Series:
4330 """
4331 Invoke function on values of Series.
4332
(...)
4431 dtype: float64
4432 """
-> 4433 return SeriesApply(self, func, convert_dtype, args, kwargs).apply()
File c:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\apply.py:1082, in SeriesApply.apply(self)
1078 if isinstance(self.f, str):
1079 # if we are a string, try to dispatch
...
1528 f"The truth value of a {type(self).__name__} is ambiguous. "
1529 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
1530 )
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code></pre>
<p>I already try a lot of solutions of this error on internet, but didnt work ;-;</p>
<p>I was expecting make a new column to the dataframe.</p>
<p><a href="https://i.stack.imgur.com/6nSZY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6nSZY.png" alt="df.head()" /></a></p>
| [
{
"answer_id": 74452816,
"author": "Carson Whitley",
"author_id": 9982613,
"author_profile": "https://Stackoverflow.com/users/9982613",
"pm_score": 2,
"selected": false,
"text": "import pandas as pd\n\ndata = {'Name':['Bob','Kyle','Kevin','Dave'],\n 'Value':[1000,20000,40000,30000... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18439954/"
] |
74,452,582 | <p>I have a dataframe where I have a date and a time column.
Each row describes some event. I want to calculate the timespan for each different day and add it as new row. The actual calculation is not that important (which units etc.), I just want to know, how I can the first and last row for each date, to access the time value.
The dataframe is already sorted by date and all rows of the same date are also ordered by the time.</p>
<p>Minimal example of what I have</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"Date": ["01.01.2020", "01.01.2020", "01.01.2020", "02.02.2022", "02.02.2022"],
"Time": ["12:00", "13:00", "14:45", "02:00", "08:00"]})
df
</code></pre>
<p><a href="https://i.stack.imgur.com/Rhyp6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rhyp6.png" alt="" /></a></p>
<p>and what I want</p>
<p><a href="https://i.stack.imgur.com/Puig0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Puig0.png" alt="" /></a></p>
<p>EDIT: The duration column should be calculated by
14:45 - 12:00 = 2:45 for the first date and
08:00 - 02:00 = 6:00 for the second date.</p>
<p>I suspect this is possible with the groupby function but I am not sure how exactly to do it.</p>
| [
{
"answer_id": 74452720,
"author": "Ricardo",
"author_id": 16353662,
"author_profile": "https://Stackoverflow.com/users/16353662",
"pm_score": 0,
"selected": false,
"text": "df['Start time'] = df.apply(lambda row: df[df['Date'] == row['Date']]['Time'].max(), axis=1)\ndf\n"
},
{
"... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8929547/"
] |
74,452,586 | <pre><code>def reversed_list(lst1, lst2):
for index in range(len(lst1)):
if lst1[index] != lst2[len(lst2) - 1- index]:
return False
else:
return True
</code></pre>
<p>It should copmare first element of the lst1 and the last element of lst2. When I run with next comands:</p>
<pre><code>print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))
</code></pre>
<p>It returns True, however second time should be False</p>
| [
{
"answer_id": 74452720,
"author": "Ricardo",
"author_id": 16353662,
"author_profile": "https://Stackoverflow.com/users/16353662",
"pm_score": 0,
"selected": false,
"text": "df['Start time'] = df.apply(lambda row: df[df['Date'] == row['Date']]['Time'].max(), axis=1)\ndf\n"
},
{
"... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20514295/"
] |
74,452,595 | <p>Trying to sort lines in a file. The column1 is HH:MM:SS format and col2 is AM/PM. Need to arrange lines from AM to PM firstly and then progressive time.</p>
<p>Current :</p>
<pre><code>11:36:48 AM col3 ...
11:32:00 AM col3 ...
03:18:54 PM col3 ...
02:26:40 PM col3 ...
01:51:56 PM col3 ...
12:55:58 PM col3 ...
11:58:48 AM col3 ...
09:38:41 AM col3 ...
</code></pre>
<p>Final:</p>
<pre><code>09:38:41 AM col3 ...
11:32:00 AM col3 ...
11:36:48 AM col3 ...
11:58:48 AM col3 ...
12:55:58 PM col3 ...
01:51:56 PM col3 ...
02:26:40 PM col3 ...
03:18:54 PM col3 ...
</code></pre>
<p>Thanks</p>
| [
{
"answer_id": 74452893,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "12:xx"
},
{
"answer_id": 74453275,
"author": "Maximilian Ballard",
"author_id": 6060841,
"aut... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4450504/"
] |
74,452,596 | <p>Sorry for the title, but don't know how to explain it. (.NET ASP MVC)
So what I'm trying is to create a payment request via TripleA API(redirect on their page), if the payment is successful, they will redirect on my success page with some parameters, how can I handle those parameters?</p>
<p>What I've tried:</p>
<pre><code>public IActionResult ErrorPage(string payment_reference, string status)
{
return View(payment_reference,status);
}
</code></pre>
<p><a href="https://developers.triple-a.io/docs/triplea-api-doc/dd286311a5afc-make-a-payment-request" rel="nofollow noreferrer">https://developers.triple-a.io/docs/triplea-api-doc/dd286311a5afc-make-a-payment-request</a>
(scroll down to success_url for more info)</p>
| [
{
"answer_id": 74452893,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "12:xx"
},
{
"answer_id": 74453275,
"author": "Maximilian Ballard",
"author_id": 6060841,
"aut... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20372223/"
] |
74,452,611 | <p>We are porting some code from SSIS to Python. As part of this project, I'm recreating some packages but I'm having issues with the database access. I've managed to query the DB like this:</p>
<p>employees_table = (spark.read <br>
.format("jdbc")<br>
.option("url", "jdbc:sqlserver://dev.database.windows.net:1433;database=Employees;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;")<br>
.option("query", query)<br>
.option("user", username)<br>
.option("password", password)<br>
.load()<br>
)<br><br></p>
<p>With this I make API calls, and want to put the results into the DB, but everything I've tried causes errors.<br></p>
<pre><code> df.write.method("append") \
.format("jdbc") \
.option("url", "jdbc:sqlserver://dev.database.windows.net:1433;database=Employees;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;") \
.option("v_SQL_Insert", query) \
.option("user", username) \
.option("password", password) \
.option("query",v_SQL_Insert) \
.save()</p>
</code></pre>
<p>Gives me the error AttributeError: 'DataFrame' object has no attribute 'write'. <br>
I get the same error using spark.write or if I try creating an actual dataframe, populate it and try to use the write function.</p></p>
<p>My question is, what is the best way to populate a db table from Python? Is it to create a dataframe and save it to the DB, or create an SQL command? And how do we go about sending that data in?</p>
| [
{
"answer_id": 74452893,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "12:xx"
},
{
"answer_id": 74453275,
"author": "Maximilian Ballard",
"author_id": 6060841,
"aut... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4385614/"
] |
74,452,631 | <p>Upper only letters that I have indexes on the list (PYTHON)</p>
<pre><code>s = "string"
l = [1,3]
# output is: sTrIng
</code></pre>
<p>Tried this but it wont work</p>
<pre><code>for i in l:
s[i] = s[i].upper()
</code></pre>
<pre><code></code></pre>
| [
{
"answer_id": 74452963,
"author": "KEHINDE ELELU",
"author_id": 12917476,
"author_profile": "https://Stackoverflow.com/users/12917476",
"pm_score": -1,
"selected": false,
"text": "s = \"string\"\nl = [1,3]\n\nfor i in l:\n newStr = s[i]\n print(newStr.upper())\n"
},
{
"answe... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20514345/"
] |
74,452,643 | <p>I've written my own std::any implementation that has configurable small value optimization (STL has no configuration for this and default values are very small, e. g. in GCC it's just one pointer size).</p>
<pre><code>#pragma once
#include <cstddef>
#include <cstring>
#include <typeinfo>
#include <new>
#include <utility>
template<std::size_t STORAGE_SIZE> class Any {
typedef void (*CopyFunc)(void *dst, const void *src);
typedef void (*MoveFunc)(void *dst, void *src);
typedef void(*DestroyFunc)(void *val);
struct Operations {
const std::type_info &typeInfo;
std::size_t size;
std::size_t align;
CopyFunc copy;
MoveFunc move;
DestroyFunc destroy;
};
template<typename T> static inline constexpr Operations OPERATIONS = {
.typeInfo = typeid(T),
.size = ([]() {
if constexpr (std::is_same_v<T, void>) {
return 0;
} else {
return sizeof(T);
}
})(),
.align = ([]() {
if constexpr (std::is_same_v<T, void>) {
return 0;
} else {
return alignof(T);
}
})(),
.copy = ([]() {
if constexpr (std::is_same_v<T, void> || std::is_trivially_copy_constructible_v<T>) {
return nullptr;
} else {
return static_cast<CopyFunc>([](void *dst, const void *src) {
new (dst) T(*reinterpret_cast<const T*>(src));
});
}
})(),
.move = ([]() {
if constexpr (std::is_same_v<T, void> || std::is_trivially_move_constructible_v<T>) {
return nullptr;
} else {
return static_cast<MoveFunc>([](void *dst, void *src) {
new (dst) T(std::move(*reinterpret_cast<T*>(src)));
});
}
})(),
.destroy = ([]() {
if constexpr (std::is_same_v<T, void> || std::is_trivially_destructible_v<T>) {
return nullptr;
} else {
return static_cast<DestroyFunc>([](void *arg) {
reinterpret_cast<T*>(arg)->~T();
});
}
})()
};
std::size_t m_storage[(STORAGE_SIZE + sizeof(std::size_t) - 1) / sizeof(std::size_t)];
void *m_heapStorage = nullptr;
const Operations *m_operations = &OPERATIONS<void>;
public:
Any() = default;
template<typename T> Any(const T &value) {
if constexpr (sizeof(T) > sizeof(m_storage) || alignof(T) > alignof(std::size_t)) {
m_heapStorage = new T(value);
} else {
new (m_storage) T(value);
}
m_operations = &OPERATIONS<T>;
}
template<typename T> Any(T &&value) noexcept {
if constexpr (sizeof(T) > sizeof(m_storage) || alignof(T) > alignof(std::size_t)) {
m_heapStorage = new T(std::move(value));
} else {
new (m_storage) T(std::move(value));
}
m_operations = &OPERATIONS<T>;
}
template<std::size_t N> Any(const Any<N> &value) {
if (value.m_heapStorage || value.m_operations->size > sizeof(m_storage)) {
m_heapStorage = new (std::align_val_t(value.m_operations->align)) char[value.m_operations->size];
if (value.m_operations) {
value.m_operations->copy(m_heapStorage, value.m_heapStorage ? value.m_heapStorage : value.m_storage);
} else {
std::memcpy(
m_heapStorage,
value.m_heapStorage ? value.m_heapStorage : value.m_storage,
value.m_operations->size
);
}
} else {
if (value.m_operations->copy) {
value.m_operations->copy(m_storage, value.m_storage);
} else {
std::memcpy(m_storage, value.m_storage, value.m_operations->size);
}
}
m_operations = value.m_operations;
}
template<std::size_t N> Any(Any<N> &&value) noexcept {
m_operations = value.m_operations;
if (value.m_heapStorage) {
m_heapStorage = value.m_heapStorage;
value.m_heapStorage = nullptr;
value.m_operations = &OPERATIONS<void>;
} else {
if (value.m_operations->size > STORAGE_SIZE) {
m_heapStorage = new (std::align_val_t(value.m_operations->align)) char[value.m_operations->size];
}
if (m_operations->move) {
m_operations->move(m_heapStorage ? m_heapStorage : m_storage, value.m_storage);
} else {
std::memcpy(m_heapStorage ? m_heapStorage : m_storage, value.m_storage, value.m_operations->size);
}
}
}
~Any() {
if (m_operations->destroy) {
m_operations->destroy(m_heapStorage ? m_heapStorage : m_storage);
}
if (m_heapStorage) {
delete static_cast<char*>(m_heapStorage);
}
}
[[nodiscard]] const std::type_info &type() const {
return m_operations->typeInfo;
}
[[nodiscard]] std::size_t size() const {
return m_operations->size;
}
[[nodiscard]] std::size_t align() const {
return m_operations->align;
}
[[nodiscard]] bool isHeapAllocated() const {
return m_heapStorage != nullptr;
}
template<typename T> [[nodiscard]] const T *get() const {
if (m_operations->typeInfo == typeid(T)) {
return reinterpret_cast<const T*>(m_heapStorage ? m_heapStorage : m_storage);
} else {
return nullptr;
}
}
template<typename T> [[nodiscard]] T *get() {
if (m_operations->typeInfo == typeid(T)) {
return reinterpret_cast<T*>(m_heapStorage ? m_heapStorage : m_storage);
} else {
return nullptr;
}
}
void clear() {
if (m_operations->destroy) {
m_operations->destroy(m_heapStorage ? m_heapStorage : m_storage);
}
if (m_heapStorage) {
delete static_cast<char*>(m_heapStorage);
m_heapStorage = nullptr;
}
m_operations = &OPERATIONS<void>;
}
template<typename T, typename... Args> void emplace(Args &&...args) {
clear();
if constexpr (sizeof(T) > sizeof(m_storage) || alignof(T) > alignof(std::size_t)) {
m_heapStorage = new T(std::forward<Args...>(args)...);
} else {
new (m_storage) T(std::forward<Args...>(args)...);
}
m_operations = &OPERATIONS<T>;
}
template<std::size_t N> Any<STORAGE_SIZE> &operator=(const Any<N> &value) {
clear();
if (value.m_heapStorage || value.m_operations->size > sizeof(m_storage)) {
m_heapStorage = new (std::align_val_t(value.m_operations->align)) char[value.m_operations->size];
if (value.m_operations) {
value.m_operations->copy(m_heapStorage, value.m_heapStorage ? value.m_heapStorage : value.m_storage);
} else {
std::memcpy(
m_heapStorage,
value.m_heapStorage ? value.m_heapStorage : value.m_storage,
value.m_operations->size
);
}
} else {
if (value.m_operations->copy) {
value.m_operations->copy(m_storage, value.m_storage);
} else {
std::memcpy(m_storage, value.m_storage, value.m_operations->size);
}
}
m_operations = value.m_operations;
return *this;
}
template<std::size_t N> Any<STORAGE_SIZE> &operator=(Any<N> &&value) noexcept {
clear();
m_operations = value.m_operations;
if (value.m_heapStorage) {
m_heapStorage = value.m_heapStorage;
value.m_heapStorage = nullptr;
value.m_operations = &OPERATIONS<void>;
} else {
if (value.m_operations->size > STORAGE_SIZE) {
m_heapStorage = new (std::align_val_t(value.m_operations->align)) char[value.m_operations->size];
}
if (m_operations->move) {
m_operations->move(m_heapStorage ? m_heapStorage : m_storage, value.m_storage);
} else {
std::memcpy(m_heapStorage ? m_heapStorage : m_storage, value.m_storage, value.m_operations->size);
}
}
return *this;
}
template<typename T> Any &operator=(T &&value) noexcept {
using TT = typename std::decay<T>::type;
emplace<TT>(std::forward<T>(value));
return *this;
}
};
</code></pre>
<p>But I have problem with some constructors:</p>
<pre><code>int x = 10;
Any<64> v0 = x; // Error
Any<64> v1 = 10; // Works
Any<128> v2 = v1; // Error
</code></pre>
<p>In both error cases compiler picks <code>template<typename T> Any(T &&value)</code> instead of <code>template<typename T> Any(const T &value)</code> for the first case and <code>template<std::size_t N> Any(const Any<N> &value)</code> for the second.</p>
<p>How constructors overloading can be fixed?</p>
<p>P. S.: There is the same problem for an assignment operator when we pass <code>Any</code> instead of some value (for value everything works fine).</p>
| [
{
"answer_id": 74452880,
"author": "ALX23z",
"author_id": 10803671,
"author_profile": "https://Stackoverflow.com/users/10803671",
"pm_score": 1,
"selected": false,
"text": "template<typename T> Any(T &&value)"
},
{
"answer_id": 74452946,
"author": "Nelfeal",
"author_id": ... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7549594/"
] |
74,452,655 | <p>Issue: I cannot get a clickable variable that points the chosen anime title. The title is an tag that has a tag that contains the anime name.
What I want to do is:
1)Get all anime that appear from the website
2)Select the anime that has the same name as the input variable "b"
3)Get the chosen anime title clickable to redirect to its page and datascrape it.</p>
<p>What is causing me a lot of issues is the selection of the right anime, because all anime titles only share the same class name and the "presence of the strong tag" and that doesn't seem enough to get the title clickable</p>
<p><a href="https://i.stack.imgur.com/ovPCg.png" rel="nofollow noreferrer">Website I use selenium on:</a></p>
<p>This is the full program code for the moment:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time</p>
<pre><code>a = input("Inserisci l'anime che cerchi: ")
b = str(a)
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://myanimelist.net/anime.php")
print(driver.title)
'''CHIUDIAMO LA FINESTRA DEI COOKIE, CHE NON MI PERMETTE DI PROSEGUIRE COL
PROGRAMMA'''
puls_cookie = driver.find_element(By.CLASS_NAME, "css-47sehv")
puls_cookie.click()
search = driver.find_element(By.XPATH,
"/html/body/div[2]/div[2]/div[3]/div[2]/div[3]/form/div[1]/div[1]/input")
time.sleep(2)
search.click()
search.send_keys(b)
search.send_keys(Keys.RETURN)
search2 = driver.find_elements(By.TAG_NAME, "strong")
i = 0
link = driver.find_element(By.XPATH, f"// a[contains(text(),\{b})]")
# the a represents the <a> tag and the be represents your input text
link.click()
time.sleep(10)
driver.quit()
</code></pre>
<p>I wanted to open the page by clicking the blue name of one of the anime that came up as result of the previus input on the searchbar</p>
<p>I AM VERY SORRY IF THIS EDIT DOESN'T STILL MAKE THE ISSUE CLEAR, english is not my native lenguage and I'm pretty new to programming too so its very difficult for me.
I thank everyone that spent and (I wish) will spend time trying to help me; God bless you all</p>
| [
{
"answer_id": 74452880,
"author": "ALX23z",
"author_id": 10803671,
"author_profile": "https://Stackoverflow.com/users/10803671",
"pm_score": 1,
"selected": false,
"text": "template<typename T> Any(T &&value)"
},
{
"answer_id": 74452946,
"author": "Nelfeal",
"author_id": ... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20507887/"
] |
74,452,666 | <p>I would like an elegant way to safely read data in a field which is wrapped in "nullable types" such as std::optional and std::shared_ptr. Take as example:</p>
<pre><code>#include <iostream>
#include <memory>
#include <optional>
struct Entry
{
std::optional<std::string> name;
};
struct Container
{
std::optional<std::shared_ptr<Entry>> entry;
};
int main()
{
Entry entry{"name"};
Container container{std::make_shared<Entry>(entry)};
// ...
return 0;
}
</code></pre>
<p>To read the "name" field from Entry given a Container, I could write:</p>
<pre><code> std::cout << *((*container.entry)->name) << std::endl;
</code></pre>
<p>But I don't find this particularly easy to read or write. And since the optionals and shared pointers may not be set, I can't anyway.</p>
<p>I want to avoid code like this:</p>
<pre><code> if (container.entry)
{
const auto ptr = *container.entry;
if (ptr != nullptr)
{
const auto opt = ptr->name;
if (opt)
{
const std::string name = *opt;
std::cout << name << std::endl;
}
}
}
</code></pre>
<p>And I am looking for something more like this:</p>
<pre><code> const auto entry = recursive_dereference(container.entry);
const auto name = recursive_dereference(entry.name);
std::cout << name.value_or("empty") << std::endl;
</code></pre>
<p>This would be based on this <a href="https://stackoverflow.com/a/20223229/1812722">recursive_dereference</a> implementation.</p>
<p>The trouble is, it would crash if an optional or shared_ptr is not set. Is there a way to modify <code>recursive_dereference</code> so that it returns its result in an optional which is left empty when a field along the way is unset?</p>
<p>I think we could use <code>std::enable_if_t<std::is_constructible<bool, T>::value</code> to check if the field can be used as a bool in an <code>if</code> (which would be the case for optionals and shared pointers) which would allow us to check if they are set. If they are set we can continue the dereferencing recursion. If one is not set, we can interrupt the recursion and return an empty optional of the final type.</p>
<p>Unfortunately, I couldn't formulate this into working code. The solution should at best be limited to "C++14 with optionals".</p>
<p><strong>Update:</strong></p>
<p>First a remark. I realized that using <code>std::is_constructible<bool, T></code> is unnecessary. <code>recursive_dereference</code> checks if a type can be dereferenced and when it can be then we can check if it is set with <code>if (value)</code>. At least it would work with optionals and shared pointers.</p>
<p>An alternative I found is first separately checking if it is safe to dereference the value and then call <code>recursive_dereference</code> unmodified.</p>
<p>So we can do:</p>
<pre><code> if (is_safe(container.entry)) {
const auto entry = recursive_dereference(container.entry);
// use entry
}
</code></pre>
<p>Implementation of <code>is_safe</code>:</p>
<pre><code>template<typename T>
bool is_safe(T&& /*t*/, std::false_type /*can_deref*/)
{
return true;
}
// Forward declaration
template<typename T>
bool is_safe(T&& t);
template<typename T>
bool is_safe(T&& t, std::true_type /*can_deref*/)
{
if (t)
{
return is_safe(*std::forward<T>(t));
}
return false;
}
template<typename T>
bool is_safe(T&& t)
{
return is_safe(std::forward<T>(t), can_dereference<T>{});
}
</code></pre>
<p>I'm still open for a better solution that would avoid checking and deferencing separately. So that we get a value or "empty" in one pass.</p>
<p><strong>Update 2</strong></p>
<p>I managed to get a version that does not need a separate check. We have to explicitly give the final type that we expect as template parameter though. It returns an optional with the value or an empty optional if one reference along the way is not set.</p>
<pre><code>template <typename FT, typename T>
auto deref(T&& t, std::false_type) -> std::optional<FT>
{
return std::forward<T>(t);
}
template <typename FT, typename T>
auto deref(T&& t) -> std::optional<FT>;
template <typename FT, typename T>
auto deref(T&& t, std::true_type) -> std::optional<FT>
{
if (t)
{
return deref<FT>(*std::forward<T>(t));
}
return std::nullopt;
}
template <typename FT, typename T>
auto deref(T&& t) -> std::optional<FT>
{
return deref<FT>(std::forward<T>(t), can_dereference<T>{});
}
</code></pre>
<p>Usage:</p>
<pre><code>std::cout << deref<Entry>(container.entry).has_value() << std::endl;
std::cout << deref<Entry>(emptyContainer.entry).has_value() << std::endl;
</code></pre>
<p>Output:</p>
<pre><code>1
0
</code></pre>
| [
{
"answer_id": 74452880,
"author": "ALX23z",
"author_id": 10803671,
"author_profile": "https://Stackoverflow.com/users/10803671",
"pm_score": 1,
"selected": false,
"text": "template<typename T> Any(T &&value)"
},
{
"answer_id": 74452946,
"author": "Nelfeal",
"author_id": ... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1812722/"
] |
74,452,672 | <p>I have an array which consists of 10 random integers, what will be the fastest way to sort it from the largest to the smallest?</p>
<pre><code>public class Main {
public static void main(String args[])
{
int [] array = new int[10];
array[0] = ((int)(Math.random()*100+1));
array[1] = ((int)(Math.random()*100+1));
array[2] = ((int)(Math.random()*100+1));
array[3] = ((int)(Math.random()*100+1));
array[4] = ((int)(Math.random()*100+1));
array[5] = ((int)(Math.random()*100+1));
array[6] = ((int)(Math.random()*100+1));
array[7] = ((int)(Math.random()*100+1));
array[8] = ((int)(Math.random()*100+1));
array[9] = ((int)(Math.random()*100+1));
for (int i = 0; i < 10; i++){
System.out.println(i + ") " + array[i]);
}
}
}
</code></pre>
<p>The only thing that comes to mind is bubble sort and the insertion sort</p>
| [
{
"answer_id": 74452707,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": false,
"text": " array = Arrays.stream(array) // turn into an IntStream\n .boxed() // Then into a Stream<... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20514343/"
] |
74,452,683 | <p>How can I create a new column (like below) to separate out values if they start with a number? I've attempted utilizing variations of isdigit() and slicing the value to look at the first character [:1], but I haven't been able to get this to work. <code>df.apply(lambda x: x if x['attr'][:1].isdigit()==False)</code></p>
<p><strong>Dummy Data:</strong></p>
<pre><code>data = {'Name':['Bob','Kyle','Kevin'],
'attr':['abc123','1230','(ab)']}
df = pd.DataFrame(data)
</code></pre>
<p><strong>Desired Output:</strong></p>
<pre><code>data = {'Name':['Bob','Kyle','Kevin'],
'attr':['abc123','1230','(ab)'],
'num_start':[None,'1230',None],
'str_start':['abc123',None,'(ab)']}
df = pd.DataFrame(data)
</code></pre>
| [
{
"answer_id": 74452707,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": false,
"text": " array = Arrays.stream(array) // turn into an IntStream\n .boxed() // Then into a Stream<... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9982613/"
] |
74,452,706 | <p>I need to modify my CSS styles to make the design look exactly like the following picture</p>
<p><a href="https://i.stack.imgur.com/Bwwhz.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>At the moment my design looks like this</p>
<p><a href="https://i.stack.imgur.com/5ISyH.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Here my code</p>
<pre><code> <div class="row">
<h4 class="font-form">Documentos adjuntos</h4>
<div class="item-container">
<ng-container *ngFor="let item of listDoc">
<div class="item-list">
<img src="./assets/img/radicar.svg" alt="" height="40px" />
<p class="item-text">{{ item.nombreArchivo }}</p>
<a [href]="item.archivoBase64" target="_blank" mat-button matSuffix mat-icon-button>
<mat-icon class="icons">visibility</mat-icon>
</a>
</div>
<div class="item-description">Acta</div>
</ng-container>
</div>
</div>
</code></pre>
<pre><code>.item-container {
background-color: #f4f5f8;
border-radius: 12px;
}
.item-list {
display: flex;
align-items: center;
background-color: #FFFFFF;
padding: 5px 5px 5px 10px;
border-radius: 5px 5px 5px 0px;
}
.item-text {
margin: 0px 30px 0px 15px;
}
.item-description {
background-color: #BC293E;
color: #FFFFFF;
padding: 5px;
margin-bottom: 10px;
border-radius: 0px 0px 4px 4px;
}
</code></pre>
<p>The white div I also need to leave it the same as the image. Currently it is taking up the whole width, and I would like them to be positioned side by side, but the red label to stay at the bottom.</p>
<p><a href="https://i.stack.imgur.com/TtOOs.png" rel="nofollow noreferrer">enter image description here</a></p>
| [
{
"answer_id": 74452707,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": false,
"text": " array = Arrays.stream(array) // turn into an IntStream\n .boxed() // Then into a Stream<... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14134518/"
] |
74,452,708 | <p>I have the requirement to set particular time of the day to Date Object. The Time is in String and is CET, so "16:00" means "15:00" in UTC in Winter time. The following code does the job in node.js on my local machine which is in CET Timezone:</p>
<pre><code>addTimetoDate(new Date(),"16:00");
function addTimetoDate(theDate,theTime){
var dtDate = new Date(theDate)
try{
var strTime = theTime.replace(/ /g,'');
var hourArray = strTime.split(":");
dtDate.setHours(parseInt(hourArray[0]), parseInt(hourArray[1]), 0)
if (dtDate == "Invalid Date"){
dtDate = theDate;
}
} catch (e){
dtDate = theDate;
}
return dtDate
}
</code></pre>
<p>However when deployed to remote server it produces Date Object which is offset by one hour the other direction when displayed with toLocaleString it shows "17:00".
How to do it elegant way (as simple deduction of one hour will work only in Winter Time.
---EDIT---
To clarify the question is - Is there anything I can do prior to using .setHours to make it right. Or I should not use setHours but rather manipulate the string for Date Constructor, so 16.00 CET gets properly converted to UTC representation?</p>
| [
{
"answer_id": 74458591,
"author": "MatnikR",
"author_id": 5177123,
"author_profile": "https://Stackoverflow.com/users/5177123",
"pm_score": -1,
"selected": false,
"text": "function addTimetoDate(theDate,theTime){\nvar d = new Date();\nvar hourLocal = d.toLocaleString({timezone:'Europe/B... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5177123/"
] |
74,452,719 | <p>I am currently working on converting, refactoring, and optimizing a code base from R to Python.</p>
<p>The R code base uses the <code>source()</code> function a lot. From my understanding this is similar to importing a python file.</p>
<p>In python I can do the following: <br/>
<code>import</code> <em>myFile</em> <br/>
<em>myFile</em>.<em>some_function_or_variable_in_the_file</em></p>
<p>Seems like you can not do this in R, which means I have to look at the R file in the <code>source()</code> function to know the functions and variables.</p>
<p>Also it seems like bad practice to be calling a function or variable from another file without <code>::</code> or <code>.</code> since this syntax indicates the file source to the left and the variable or function name to the right.</p>
<p>Maybe this is not as big of an issue when you are in R studio but I am working in Jupyter Lab for both the R and Python work.
It would be really nice if I did not have to always look at the files I was referencing.</p>
<p>Upon my google searches I found nothing. Any help or information would be helpful.</p>
| [
{
"answer_id": 74452905,
"author": "Gwang-Jin Kim",
"author_id": 9690090,
"author_profile": "https://Stackoverflow.com/users/9690090",
"pm_score": 0,
"selected": false,
"text": "source()"
},
{
"answer_id": 74452908,
"author": "G. Grothendieck",
"author_id": 516548,
"a... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15773858/"
] |
74,452,722 | <p>When compiling with Microsoft's <code>/analyze</code> static analysis command line option for <code>cl.exe</code>, I get the warning</p>
<pre><code>warning C6011: Dereferencing NULL pointer 'foo'
</code></pre>
<p>on a code path that calls a trivial function that guarantees that <code>foo</code> is not NULL where the analyzer thinks it can be.</p>
<p>The trivial function:</p>
<pre class="lang-c prettyprint-override"><code>bool check_ptr(void* ptr)
{
if (!ptr)
{
// The original does more things here, but
// the repro is valid even without that.
return false;
}
return true;
}
</code></pre>
<p>The calling site:</p>
<pre class="lang-c prettyprint-override"><code>foo_t* foo = lookup_foo(id);
if (!check_ptr(foo))
return;
foo->bar = 4711; // warning C6011: Dereferencing NULL pointer 'foo'
</code></pre>
<p>The analyzer is really bad at seeing through function calls, even trivial ones. If <code>check_ptr</code> is reduced to</p>
<pre class="lang-c prettyprint-override"><code>bool check_ptr(void* ptr)
{
return !!ptr;
}
</code></pre>
<p>then the analyzer can deduce that <code>foo</code> cannot be NULL when dereferenced, but that's not an option. The checker function is there for a reason.</p>
<p>So, I assume that there is an ungodly SAL annotation combination that can be applied to <code>check_ptr</code> to convince the analyzer that if it returns <code>true</code>, then the <code>foo</code> argument is not NULL.</p>
<p>Is there such a SAL annotation?</p>
<p><strong>EDIT:</strong> I found a SAL solution and added it as a separate answer <a href="https://stackoverflow.com/a/74459650/6345">https://stackoverflow.com/a/74459650/6345</a></p>
| [
{
"answer_id": 74452790,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": 1,
"selected": false,
"text": "template<typename Then, typename Else>\nvoid if_check_ptr(Foo* ptr, Then then, Else els)\n{\n if (!ptr)\n {\n ... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6345/"
] |
74,452,724 | <p>I am trying to implement a trait for types such that the reference to the type is convertible into an iterator with <code>Item</code> implementing a specific trait</p>
<p>Specifically, consider the following code:</p>
<pre class="lang-rust prettyprint-override"><code>struct Arena;
pub trait Scan {
fn scan(&self, arena: &mut Arena);
}
impl<'a, 'b, Iterable, Item> Scan for Iterable
where
&'b Iterable: IntoIterator<Item = Item>,
Item: Scan + 'a,
{
fn scan(&self, arena: &mut Arena) {
for item in (&self).into_iter() {
item.scan(arena);
}
}
}
</code></pre>
<p>(<a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4004c4609d53628a59b7d3a381eeb362" rel="nofollow noreferrer">See</a> this example in the Playground)</p>
<p>The compiler complains, underlining <code>Item</code>:</p>
<pre><code>the type parameter `Item` is not constrained by the impl trait, self type, or predicates
unconstrained type parameter
</code></pre>
<p>I do not really understand for now where am I going in the wrong direction: to me, it looks like if the generic implementation is pretty much constrained by the conditions under <code>where</code>. How do I explain the idea to the compiler?</p>
| [
{
"answer_id": 74453043,
"author": "rodrigo",
"author_id": 865874,
"author_profile": "https://Stackoverflow.com/users/865874",
"pm_score": 3,
"selected": true,
"text": "impl<'a, 'b, Iterable, Item> Scan for Iterable\n"
},
{
"answer_id": 74453776,
"author": "kmdreko",
"aut... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6187172/"
] |
74,452,725 | <p>I have been using code from <a href="https://stackoverflow.com/a/74048270/45375">this answer</a> to check for additions/changes to class rosters from MS Teams:</p>
<pre><code>$set = [System.Collections.Generic.HashSet[string]]::new(
[string[]] (Import-CSV -Path stundent.csv).UserPrincipalName,
[System.StringComparer]::InvariantCultureIgnoreCase
)
Import-Csv ad.csv | Where-Object { $set.Add($_.UserPrincipalName) } |
Export-Csv path\to\output.csv -NoTypeInformation
</code></pre>
<p>Ideally, I want to be able to check if there have been removals when compared to a new file, swap the import file positions, and check for additions. If my files look like Source1 and Source2 (below), the check for removals would return Export1, and the check for additions would return Export2.
Since there will be multiple instances of students across multiple classes, I want to include TeamDesc in the filter query to make sure only the specific instance of that student with that class is returned.</p>
<p>Source1.csv</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">TeamDesc</th>
<th style="text-align: center;">UserPrincipalName</th>
<th style="text-align: center;">Name</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">Team 1</td>
<td style="text-align: center;">student1@domain.com</td>
<td style="text-align: center;">john smith</td>
</tr>
<tr>
<td style="text-align: center;">Team 1</td>
<td style="text-align: center;">student2@domain.com</td>
<td style="text-align: center;">nancy drew</td>
</tr>
<tr>
<td style="text-align: center;">Team 2</td>
<td style="text-align: center;">student3@domain.com</td>
<td style="text-align: center;">harvey dent</td>
</tr>
<tr>
<td style="text-align: center;">Team 3</td>
<td style="text-align: center;">student1@domain.com</td>
<td style="text-align: center;">john smith</td>
</tr>
</tbody>
</table>
</div>
<p>Source2.csv</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">TeamDesc</th>
<th style="text-align: center;">UserPrincipalName</th>
<th style="text-align: center;">Name</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">Team 1</td>
<td style="text-align: center;">student2@domain.com</td>
<td style="text-align: center;">nancy drew</td>
</tr>
<tr>
<td style="text-align: center;">Team 2</td>
<td style="text-align: center;">student3@domain.com</td>
<td style="text-align: center;">harvey dent</td>
</tr>
<tr>
<td style="text-align: center;">Team 2</td>
<td style="text-align: center;">student4@domain.com</td>
<td style="text-align: center;">tim tams</td>
</tr>
<tr>
<td style="text-align: center;">Team 3</td>
<td style="text-align: center;">student1@domain.com</td>
<td style="text-align: center;">john smith</td>
</tr>
</tbody>
</table>
</div>
<p>Export1.csv</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">TeamDesc</th>
<th style="text-align: center;">UserPrincipalName</th>
<th style="text-align: center;">Name</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">Team 1</td>
<td style="text-align: center;">student1@domain.com</td>
<td style="text-align: center;">john smith</td>
</tr>
</tbody>
</table>
</div>
<p>Export2.csv</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">TeamDesc</th>
<th style="text-align: center;">UserPrincipalName</th>
<th style="text-align: center;">Name</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">Team 2</td>
<td style="text-align: center;">student4@domain.com</td>
<td style="text-align: center;">tim tams</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74453277,
"author": "Santiago Squarzon",
"author_id": 15339544,
"author_profile": "https://Stackoverflow.com/users/15339544",
"pm_score": 2,
"selected": false,
"text": "Source1.csv"
},
{
"answer_id": 74454531,
"author": "mklement0",
"author_id": 45375,
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19848263/"
] |
74,452,730 | <p>If I have this url address</p>
<p><a href="https://googledroids.com/post.html?limit=25&since=1374196005&md5=d8959d12ab687ed5db978cb078f1e&time=0dfdbac117" rel="nofollow noreferrer">https://googledroids.com/post.html?limit=25&since=1374196005&md5=d8959d12ab687ed5db978cb078f1e&time=0dfdbac117</a></p>
<p>How could I get (or split) parameters (avoiding hard coding)?</p>
<p>I need separated values:</p>
<ul>
<li>https</li>
<li>googledroids.com</li>
<li>/post.html</li>
<li>parameters and values: <code>{limit=25, time=0dfdbac117, since=1374196005, md5=d8959d12ab687ed5db978cb078f1e}</code></li>
</ul>
| [
{
"answer_id": 74452731,
"author": "Jorgesys",
"author_id": 250260,
"author_profile": "https://Stackoverflow.com/users/250260",
"pm_score": 1,
"selected": false,
"text": "import android.net.Uri\n"
},
{
"answer_id": 74452942,
"author": "undermark5",
"author_id": 3251429,
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/250260/"
] |
74,452,738 | <p>I need some help consolidating columns in R</p>
<p>I have ~130 columns, some of which have a similar name. For example, I have ~25 columns called "pathogen".
However, after importing my datasheet into R, these colums are now listed as follows : pathogen..1, pathogen...2, etc. Because of how R renamed these columns, I'm not sure how to proceed.</p>
<p>I need to consolidate all my columns with the same/similar name, so that I have only 1 column called "pathogen". I also need this consolidated column to include the sums of all the consolidated columns called "pathogen".</p>
<p>here an example of my input</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>sample Unidentified…1 Unidentified…2 Pathogen..1 Pathogen…2
1 5 3 6 8
2 7 2 1 0
3 8 4 2 9
4 9 6 4 0
5 0 7 5 1</code></pre>
</div>
</div>
</p>
<p>Here is my desired output</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Sample Unidentified Pathogen
1 8 14
2 9 1
3 12 11
4 15 4
5 7 6</code></pre>
</div>
</div>
</p>
<p>Any help would be really appreciated.</p>
| [
{
"answer_id": 74452731,
"author": "Jorgesys",
"author_id": 250260,
"author_profile": "https://Stackoverflow.com/users/250260",
"pm_score": 1,
"selected": false,
"text": "import android.net.Uri\n"
},
{
"answer_id": 74452942,
"author": "undermark5",
"author_id": 3251429,
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17371915/"
] |
74,452,744 | <p>I am having input data as below, I need to phrase it to be a JSON. Working on a legacy node and don't have <code>jq</code>(mentioning in advance)</p>
<pre><code>e1
status: up
temp: 140
alarm: none
e2
status: down
temp: 141
alarm: none
e3
status: up
temp: 144
alarm: 2
e4
status: up
temp: 65
alarm: 2
region: us-east
</code></pre>
<p>I was hoping to get the following output:</p>
<pre><code>{"e1" : { "status": "up", "temp": "140", "alarm": "none"}}
{"e2" : { "status": "down", "temp": "141", "alarm": "none"}}
{"e3" : { "status": "up", "temp": "144", "alarm": "2"}}
{"e4" : { "status": "up", "temp": "65", "alarm": "2", "region": "us-east"}}
</code></pre>
<p>I tried to make a workaround using <code>awk</code> but not able to combine the results by key:</p>
<pre><code>awk '!/:/{node=$0} /:/{print "{\"",node,"\"}",":", "{", $0 ,"}" }' inputfile
{" e1 "} : { status: up }
{" e1 "} : { temp: 140 }
{" e1 "} : { alarm: none }
{" e3 "} : { status: down }
{" e3 "} : { temp: 141 }
{" e3 "} : { alarm: none }
{" e3 "} : { status: up }
{" e3 "} : { temp: 144 }
{" e3 "} : { alarm: 2 }
</code></pre>
<p>Any suggestions ?</p>
| [
{
"answer_id": 74453026,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 4,
"selected": true,
"text": "awk"
},
{
"answer_id": 74453733,
"author": "glenn jackman",
"author_id": 7552,
"author_profile... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5584716/"
] |
74,452,784 | <p>I wrote an onEdit script that takes values from one spreadsheet and sets them in another.
I have used SpreadsheetApp.openById on other onOpen scrips without any issues.
But only for this specific new script it tells me I don't have the permissions to use openById.
I read other answers that said to change the oauthScopes an I did, but it still says I don't have permition.</p>
<pre><code>{
"oauthScopes": [
"https://www.googleapis.com/auth/spreadsheets.readonly",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/spreadsheets"
],
"timeZone": "America/Argentina/Buenos_Aires",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8"
}
</code></pre>
<p>This is the script I wrote.</p>
<pre><code>function onEdit(e){
//reemplazar targetID por ID de hoja real
var targetID = '14VgIUDG7m0-Z9SGCec5GBfaivrA_8bakUTu2qfWw_Ho';
var ss = SpreadsheetApp.openById(targetID);
var s = ss.getSheetByName('Cortes');
const row = e.range.getRow();
const col = e.range.getColumn();
const SHEET_NAME = 'Pendientes';
const DATE_COLUMN = 4;
const FIXEDROW = 2;
const ESTADO_COLUMN = 5;
const ESTADO_COLUMN_2 = 25;
const RESP_COLUMN = 3;
const TARGET_ROW_COLUMN = 26;
const ESTADO = e.source.getActiveSheet().getRange(row, ESTADO_COLUMN).getValue();
const ESTADO_2 = e.source.getActiveSheet().getRange(row, ESTADO_COLUMN_2).getValue();
const RESP = e.source.getActiveSheet().getRange(row, RESP_COLUMN).getValue();
Logger.log(row);
Logger.log(TARGET_ROW_COLUMN);
const TARGET_ROW = e.source.getActiveSheet().getRange(row, TARGET_ROW_COLUMN).getValue();
const TARGET_RESP_COLUMN = 3;
const TARGET_ESTADO_COLUMN = 5;
const TARGET_TIME_COLUMN = 4;
var cellRange = s.getRange(TARGET_ROW, targetColumn);
//set estado y resp
if (e.source.getActiveSheet().getName() == SHEET_NAME && row > FIXEDROW){
//si modifica el estado
if (ESTADO !== '' && ESTADO !== ESTADO_2) {
var targetColumn = TARGET_ESTADO_COLUMN;
var targetValue = ESTADO;
}
//si modifica el responsable
else if (RESP !== ''){
var targetColumn = TARGET_RESP_COLUMN;
var targetValue = RESP;
}
cellRange.setValue(targetValue);
}
//set timestamp if estado=preparado o estado=entregado y resp<>"" y timestamp=""
//actualizar si cambian los nombres de los pasos de preparación
if ((ESTADO == 'Preparado' || ESTADO == 'Entregado') && RESP !== ''){
var targetColumn = TARGET_TIME_COLUMN;
var targetValue = new Date();
cellRange.setValue(targetValue);
}
}
</code></pre>
<p>This is the spreadsheet where the script is posted, from where i source the values:
<a href="https://docs.google.com/spreadsheets/d/1bo6mgrn4LBCU6wHvTVsaCkHxKc-q7oS7JOnN7AqLH7U/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1bo6mgrn4LBCU6wHvTVsaCkHxKc-q7oS7JOnN7AqLH7U/edit?usp=sharing</a></p>
<p>This is the target spreadsheet where the values must be copies (the one I reference with openByID):
<a href="https://docs.google.com/spreadsheets/d/14VgIUDG7m0-Z9SGCec5GBfaivrA_8bakUTu2qfWw_Ho/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/14VgIUDG7m0-Z9SGCec5GBfaivrA_8bakUTu2qfWw_Ho/edit?usp=sharing</a></p>
| [
{
"answer_id": 74452920,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 0,
"selected": false,
"text": "onEdit()"
},
{
"answer_id": 74453326,
"author": "Cooper",
"author_id": 7215091,
"author... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13470816/"
] |
74,452,794 | <p>I am trying to disable button and input-field through angular directive based on the permission. I have tried few ways but it doesn't help</p>
<pre><code>if (this.permission==true) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
const viewRootElement : HTMLElement = this.viewContainer.createEmbeddedView(
this.templateRef
).rootNodes[0];
viewRootElement.setAttribute('disabled', 'false');
}
</code></pre>
| [
{
"answer_id": 74452920,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 0,
"selected": false,
"text": "onEdit()"
},
{
"answer_id": 74453326,
"author": "Cooper",
"author_id": 7215091,
"author... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11104519/"
] |
74,452,839 | <p>Why can't python seem to find the <code>InterfaceWithNoMenu</code> class</p>
<pre><code>class Settings(Screen):
class SettingsWithNoMenu(kivy.uix.settings.SettingsWithNoMenu):
def __init__(self, *args, **kwargs):
self.interface_cls = InterfaceWithNoMenu
kivy.uix.settings.SettingsWithNoMenu.__init__( self, *args, **kwargs )
class InterfaceWithNoMenu(kivy.uix.settings.ContentPanel):
def add_widget(self, widget):
if self.container is not None and len(self.container.children) > 0:
raise Exception(
'ContentNoMenu cannot accept more than one settings panel')
super(InterfaceWithNoMenu, self).add_widget(widget)
kivy.uix.settings.InterfaceWithNoMenu.__init__( self, *args, **kwargs )
actionview = ObjectProperty(None)
settings_content = ObjectProperty(None)
def __init__(self, **kwargs):
super(Settings, self).__init__(**kwargs)
...
</code></pre>
<p>I'm trying to change the look/feel/behaviour of the <a href="https://kivy.org/doc/stable/api-kivy.uix.settings.html" rel="nofollow noreferrer">Settings module</a> in a <a href="https://en.wikipedia.org/wiki/Kivy_(framework)" rel="nofollow noreferrer">kivy-based</a> python GUI app.</p>
<p>Unfortunately, when I create a settings window with the above program that creates an instance of the locally-overridden <code>self.SettingsWithNoMenu</code> class, I get the following error:</p>
<pre><code> self.interface_cls = InterfaceWithNoMenu
NameError: name 'InterfaceWithNoMenu' is not defined
</code></pre>
<p>I don't understand. It's right there. I mean, the class <code>InterfaceWithNoMenu</code> is literally defined right underneath the one (<code>SettingsWithNoMenu</code>) that's referencing it.</p>
<p>Why can't the class <code>SettingsWithNoMenu</code> find <code>InterfaceWithNoMenu</code>? Why am I getting a <code>NameError</code> here?</p>
| [
{
"answer_id": 74452868,
"author": "Noscere",
"author_id": 10728583,
"author_profile": "https://Stackoverflow.com/users/10728583",
"pm_score": 0,
"selected": false,
"text": "InterfaceWithNoMenu"
},
{
"answer_id": 74452898,
"author": "Samwise",
"author_id": 3799759,
"a... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1174102/"
] |
74,452,857 | <p>I'm struggeling a bit with arrays and user what's inside with loops. I have this question for example (ignore what's inside of the previewOrder method, i was trying stuff out):</p>
<pre><code>
public class Ex1_19 {
final static String NAMES[]= {"Spa reine 25 ","Bru plate 50","Bru pét 50",
"Pepsi","Spa orange", "Schweppes Tonic","Schweppes Agr","Ice Tea","Ice Tea Pêche",
"Jus d'orange Looza", "Cécémel", "Red Bull","Petit Expresso","Grand Expresso","Café décaféiné ",
"Lait Russe ","Thé et infusions","Irish Coffee ","French Coffee ","Cappuccino","Cécémel chaud",
"Passione Italiano","Amour Intense", "Rhumba Caliente ","Irish Kisses ","Cuvée Trolls 25",
"Cuvee Trolls 50","Ambrasse-Temps 25","Ambrasse-Temps 50 ","Brasse-Temps Cerises 25",
"Brasse-Temps Cerises 50","La Blanche Ste Waudru 25","Blanche Ste Waudru 50",
"Brasse-Temps citr 25","Brasse-Temps citr 50","Spaghetti Bolo ","Tagl Carbonara",
"Penne poulet baslc ","Tagl American","Tagl saum"};
final static double NETPRICES[]= {2.2, 2.3,3.9,2.2,2.2,2.6,2.6,2.6,2.6,2.6,2.6,4.5,2.2,2.2,2.2,2.5,2.5,7.0,7.0,2.8,2.8,6.2,6.2,6.2,6.2,
2.9,5.5,2.7,5.1,3.1,5.8,2.6,4.9,2.6,4.9,10.8,11.2,12.2,14.5,16.9};
public static void main(String[] args) {
int Order[][]={{3,2},{1,3},{12,4},{37,1},{36,3},{0,0},{0,0},{0,0}, {0,0}};
previewOrder(Order);
}
public static void previewOrder(int order[][]) {
int i = 0;
int j = 0;
while(i < order.length && j < order.length) {
System.out.println(NAMES[i]);
i++;
j++;
}
}
}
</code></pre>
<p>My result has to be something like this but with what's inside the "order" array:</p>
<p>Bru pét 50 3.9 2 7,80
Spa reine 25 2.2 3 6,60
Red Bull 4.5 4 18,00
Tagl Carbonara 11.2 1 11,20
Spaghetti Bolo 10.8 3 32,40</p>
<p>In my exercice I have to use a while loop and I have to put the order array in my method parameters. I can't figure out how to make them all communicate.</p>
<p>Sorry if this question has been answered somewhere else but I don't know how to search for it.</p>
<p><strong>EDIT:</strong> I know that Orders does not use zero based index, but starts at 1. This is probably because "Order" is supposed to be a user entry. The first number of the array is like a drink number.</p>
<p>I wasn't very clear on the expected output.
Bru pét 50 (NAME[3]) 3.9 (NETPRICE[3]) 2 (Order[][2]) 7.80 NETPRICE[3] * Order[][2] and this for every occurence in Order</p>
| [
{
"answer_id": 74452868,
"author": "Noscere",
"author_id": 10728583,
"author_profile": "https://Stackoverflow.com/users/10728583",
"pm_score": 0,
"selected": false,
"text": "InterfaceWithNoMenu"
},
{
"answer_id": 74452898,
"author": "Samwise",
"author_id": 3799759,
"a... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9022721/"
] |
74,452,864 | <p>How to find all permutations of positive integers for a given <em>sum</em> and given <em>number of elements</em>.</p>
<p>For example,</p>
<pre><code>Input: sum = 4, number of elements = 2.
Output: (1,3), (3,1), (2,2)
</code></pre>
<p>My thinking is, since I know the number of elements is <code>N</code>, I will create N arrays, each from 1 to the sum <code>S-1</code>. So for the example, I will start with two arrays, <code>[1,2,3]</code> and <code>[1,2,3]</code>. Then I will iterate through each array, something like</p>
<pre><code>output = []
for x in array1:
for y in array2:
if x+y == target:
output.append((x,y))
</code></pre>
<p>But I don't know how to make it for any <code>N</code>, since that would be variable number of for loops.</p>
<p>Now I have a second idea, I think this works.</p>
<pre><code>import numpy as np
from itertools import combinations
def find_permutations(S,N):
x = np.asarray([x+1 for x in range(S)]*N)
y = [seq for seq in combinations(x,N) if sum(seq)==S]
return list(dict.fromkeys(y)) # remove duplicates
find_permutations(4,2)
[(1, 3), (2, 2), (3, 1)]
</code></pre>
<p>But this is extremely slow, since it first create a very long array and find ALL combinations and then filter down. Something like <code>find_permutations(16,16)</code> takes extremely long time but it's obviously just <code>[(1,1,...,1)]</code>.</p>
| [
{
"answer_id": 74452868,
"author": "Noscere",
"author_id": 10728583,
"author_profile": "https://Stackoverflow.com/users/10728583",
"pm_score": 0,
"selected": false,
"text": "InterfaceWithNoMenu"
},
{
"answer_id": 74452898,
"author": "Samwise",
"author_id": 3799759,
"a... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1382745/"
] |
74,452,872 | <p>When I use my GPS module in u-center, I get latitude of 11.27000000 and longitude of 100.34000000. But when I read and format the nmea messages in a python script I see latitude of 100.00000000 and longitude of 100.00000000. These are for example, but the difference of approximately 1.27... degrees latitude and 0.34... degrees longitude is accurate.</p>
<p>Here is my code:</p>
<pre><code>import serial
try:
gps = serial.Serial('com5', baudrate=9600)
while True:
ser_bytes = gps.readline()
decoded_bytes = ser_bytes.decode("utf-8")
data = decoded_bytes.split(",")
if data[0] == '$GNRMC':
lat_nmea = (data[3],data[4])
lat_degrees = float(lat_nmea[0][0:2])
if lat_nmea[1 ] == 'S':
lat_degrees = -lat_degrees
lat_minutes = float(lat_nmea[0][2:])
lat = lat_degrees + (lat_minutes/60)
lon_nmea = (data[5],data[6])
lon_degrees = float(lon_nmea[0][0:3])
if lon_nmea[1] == 'W':
lon_degrees = -lon_degrees
lon_minutes = float(lon_nmea[0][3:])
lon = lon_degrees + (lon_minutes/60)
print("%0.8f" %lat, "%0.8f" %lon)
except KeyboardInterrupt:
print("Keyboard Interrupt")
</code></pre>
<p>output:</p>
<blockquote>
<p>10.0000000 100.0000000</p>
</blockquote>
<p>When I just use:</p>
<pre><code>print(data)
</code></pre>
<p>on line 11, I get the correct coordinates in the form of the GNRMC NMEA message I singled out on line 10:</p>
<blockquote>
<p>['$GNRMC', '...', '...', '1127.00000', 'N', '10034.00000', 'W', ...]</p>
</blockquote>
<p>but they're not in the format one usually expects (e.g. 11.2712345, 100.3412345). So, I use the code above to change the way they look. I can't see what I'm doing that would cause the latitude and longitude to change.</p>
<p>Any help would be appreciated! Thanks :)</p>
| [
{
"answer_id": 74460768,
"author": "Sam Mason",
"author_id": 1358308,
"author_profile": "https://Stackoverflow.com/users/1358308",
"pm_score": 0,
"selected": false,
"text": "data = ['$GNRMC', '...', '...', \"5416.89\", \"S\", \"03630.48\", \"W\", ...]\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20171448/"
] |
74,452,882 | <p>I am trying to fill my variable 'test' with items from 'mylist'. If the condition <code>totaltime < 6</code> is met, the iteration starts over at mylist[0], so the lists never get beyond '3' (2nd indice in mylist). However, I want that if the condition is met, then the iteration will continue filling the second list. How can I ensure that my iteration continues where it left off? so that the result is the following:</p>
<pre><code>mylist = [1, 2, 3, 4, 5, 6, 7, 8]
time = [2, 2, 2, 5, 1, 6, 5, 1]
test = [[], [], [], []]
</code></pre>
<p>I tried the following</p>
<pre><code>mylist = [1, 2, 3, 4, 5, 6, 7, 8]
time = [2, 2, 2, 5, 1, 6, 5, 1]
test = [[], [], [], []]
totaltime = 0
for i in range(len(test)):
for jobs in range(len(mylist)):
if totaltime < 6:
test[i].append(mylist[jobs])
totaltime += time[jobs]
totaltime = 0
print(test)
</code></pre>
<p>with the result:</p>
<p><code>[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]</code></p>
<p><code>[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]</code></p>
<p><code>[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]</code></p>
<p>However, I want my iteration not to start over again, as stated above. As a result, the desired result should be the following:</p>
<pre><code>test = [1, 2, 3], [4,5], [6], [7, 8]
</code></pre>
| [
{
"answer_id": 74460768,
"author": "Sam Mason",
"author_id": 1358308,
"author_profile": "https://Stackoverflow.com/users/1358308",
"pm_score": 0,
"selected": false,
"text": "data = ['$GNRMC', '...', '...', \"5416.89\", \"S\", \"03630.48\", \"W\", ...]\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330710/"
] |
74,452,891 | <p>I'm very new to HTML and have been struggling to get my dropdown to work for a few hours now. I've searched many posts facing similar issues but I still can't find and resolve the issue. I'm unsure if the issue is caused by my scripts as well</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<header class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#" id="logo">Logo</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent">
<span class="navbar-toggler-icon"></span>
</button>
<nav class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item"><a class="nav-link active" href="#">Home <span class="sr-only">(current)</span></a></li>
<li class="nav-item"><a class="nav-link" href="#">Link</a></li>
<li class="nav-item">
<div class="dropdown">
<a href="#" class="nav-link dropdown-toggle" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a href="#" class="dropdown-item">Action</a>
<a href="#" class="dropdown-item">Another action</a>
<div class="dropdown-divider"></div>
<a href="#" class="dropdown-item">Something else here</a>
</div>
</div>
</li>
<li class="nav-item"><a class="nav-link" href="#">Disabled</a></li>
</ul>
</nav>
</header></code></pre>
</div>
</div>
</p>
<p>Thanks in advance!</p>
<p>I tried replacing <code>data-toggle="dropdown"</code> with <code>data-bs-toggle="dropdown"</code> but it didn't work since I'm using bootstrap 4, copied and pasted the codes directly from bootstrap and it still failed</p>
| [
{
"answer_id": 74460768,
"author": "Sam Mason",
"author_id": 1358308,
"author_profile": "https://Stackoverflow.com/users/1358308",
"pm_score": 0,
"selected": false,
"text": "data = ['$GNRMC', '...', '...', \"5416.89\", \"S\", \"03630.48\", \"W\", ...]\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20514344/"
] |
74,452,909 | <p>I am trying to unit test the following function. As you can see the function output is dependent on the value of count. What is the appropriate syntax and functions to be used to test this type of function? I am very new to Jest and javascript.</p>
<pre><code>function greetings(){
if(count == 0){
return "Hello! I am here to assist you in picking your ideal Apple product! YAYYY :D! We can start off by selecting the type of Apple product you wish to buy";
}else if(count == 1){
return "Hello again! Once we get your budget I can narrow down options for your ideal product! Whats your max budget?";
}else if(count == 2){
return "Hello again my friend! Once we get your ideal device size I can narrow down options for your ideal product! Whats your ideal size for this device?";
}
}
</code></pre>
<p>this is what I tried</p>
<pre><code>test ('greetings message test', () => {
expect(responses.greetings().toBe("Hello! I am here to assist you in picking your ideal Apple product! YAYYY :D! We can start off by selecting the type of Apple product you wish to buy" || "Hello again! Once we get your budget I can narrow down options for your ideal product! Whats your max budget?" || "Hello again my friend! Once we get your ideal device size I can narrow down options for your ideal product! Whats your ideal size for this device?"))
});
</code></pre>
<p>the test just fails. I am not sure what the correct approach is. Help would be very much appreciated.</p>
| [
{
"answer_id": 74460768,
"author": "Sam Mason",
"author_id": 1358308,
"author_profile": "https://Stackoverflow.com/users/1358308",
"pm_score": 0,
"selected": false,
"text": "data = ['$GNRMC', '...', '...', \"5416.89\", \"S\", \"03630.48\", \"W\", ...]\n"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20370018/"
] |
74,452,927 | <p>I am trying to use GNU Parallel to run a script that has multiple binary flags. I would like to enable/disable these as follows:</p>
<p>Given a script named "<code>sample.py</code>", with two options, "<code>--seed</code>" which takes an integer and "<code>--something</code>" which is a binary flag and takes no input, I would like to construct a call to parallel that produces the following calls:</p>
<pre><code>python sample.py --seed 1111
python sample.py --seed 1111 --something
python sample.py --seed 2222
python sample.py --seed 2222 --something
python sample.py --seed 3333
python sample.py --seed 3333 --something
</code></pre>
<p>I've tried things like</p>
<pre><code>parallel python sample.py --seed {1} {2} ::: 1111 2222 3333 ::: "" --something
parallel python sample.py --seed {1} {2} ::: 1111 2222 3333 ::: '' --something
parallel python sample.py --seed {1} {2} ::: 1111 2222 3333 ::: \ --something
</code></pre>
<p>but haven't had any luck. Is what I'm trying to achieve possible with GNU parallel? I can modify my script to take explicit TRUE/FALSE values for the flag but I'd prefer to avoid that if possible.</p>
| [
{
"answer_id": 74456942,
"author": "root",
"author_id": 10678955,
"author_profile": "https://Stackoverflow.com/users/10678955",
"pm_score": 0,
"selected": false,
"text": "> bash$ cat sample.py \n#!/usr/bin/python3\n\nimport sys\nimport time\n\ntime.sleep(0.2)\nprint(sys.argv)\n> bash$ ca... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4364569/"
] |
74,452,932 | <p>I create a repository in Github and on my local machine I ran the code:</p>
<pre><code>git init
git branch -m main
git remote add origin https://github.com/.../Project.git
git push -u origin main
</code></pre>
<p>Instead of using <code>master</code> branch I want to use <code>main</code> branch.</p>
<p>When running <code>git push -u origin main</code> I get the error:</p>
<pre><code>failed to push some refs to 'https://github.com/.../Project.git'
</code></pre>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 74453011,
"author": "Noscere",
"author_id": 10728583,
"author_profile": "https://Stackoverflow.com/users/10728583",
"pm_score": 2,
"selected": false,
"text": " git pull --rebase origin main\n git push origin main\n"
},
{
"answer_id": 74453113,
"author": "... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577805/"
] |
74,452,950 | <p>I have this query in my rails application where I get the <code>name</code> of the <code>Books</code>.</p>
<pre><code>Book.where(:name => @name_list).pluck(:name)
</code></pre>
<p>Basically it find the <code>Book</code> whose name is present in the <code>@name_list</code> and then return an array of their <code>names</code> if present.
But since there are a huge number of books present in the database, the request is getting timed out when I call this particular endpoint.</p>
<p>Please let me know if there is any way we can make this faster so that endpoint will work.
Also will the query speed increase if we add this <code>name</code> column as an <code>index</code> into the <code>Books</code> table ?</p>
<pre><code>add_index :books, :name
</code></pre>
| [
{
"answer_id": 74455276,
"author": "spickermann",
"author_id": 2483313,
"author_profile": "https://Stackoverflow.com/users/2483313",
"pm_score": 1,
"selected": false,
"text": "books.name"
}
] | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19574843/"
] |
74,452,974 | <p>I created a custom PropertyDrawer that for a certain field decorated with my attribute, shows the parameters from the animator object referenced in the same script.</p>
<p>That way, I can make sure the field's value is a valid parameter in the referenced animator.</p>
<p>This is my code:</p>
<pre><code>
public class AnimationParamAttribute : PropertyAttribute
{
public string AnimatorName { get; }
public AnimatorControllerParameterType[] AllowedParameters { get; }
public AnimationParamAttribute(string animatorName, params AnimatorControllerParameterType[] allowedParameters)
{
AnimatorName = animatorName;
this.AllowedParameters = allowedParameters;
}
}
public class AnimationController : MonoBehaviour
{
[SerializeField] private Animator animator;
[SerializeField, AnimationParam(nameof(animator), AnimatorControllerParameterType.Trigger)]
private string trigger;
[ContextMenu("Print value")]
private void PrintValue()
{
Debug.Log(trigger);
}
public void StartAnimation()
{
animator.SetTrigger(trigger);
}
}
</code></pre>
<p>And my <code>PropertyDrawer</code> looks like this:</p>
<pre><code>[CustomPropertyDrawer(typeof(AnimationParamAttribute))]
public class AnimationParamDrawer : PropertyDrawer
{
// Draw the property inside the given rect
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
AnimationParamAttribute a = (AnimationParamAttribute)attribute;
if (property.propertyType == SerializedPropertyType.String)
{
var targetObject = property.serializedObject.targetObject;
var field = targetObject.GetType().GetField(a.AnimatorName,
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
Animator animator = field?.GetValue(targetObject) as Animator;
if (animator == null)
{
EditorGUI.LabelField(position, label.text, "Select an animator.");
return;
}
var options = animator.parameters
.Where(parameter => a.AllowedParameters.Contains(parameter.type))
.Select(parameter => parameter.name)
.ToArray();
var s = string.Join(", ", options);
Debug.Log($"Options: {s}");
int selection = Array.IndexOf(options, property.stringValue);
Debug.Log($"{property.stringValue} is option {selection}");
if (selection < 0) selection = 0;
position = EditorGUI.PrefixLabel(position, label);
EditorGUI.BeginProperty(position, label, property);
EditorGUI.BeginChangeCheck();
selection = EditorGUI.Popup(position, selection, options);
if (EditorGUI.EndChangeCheck())
{
Debug.Log($"New selection: {selection}");
property.stringValue = options[selection];
}
EditorGUI.EndProperty();
}
else
EditorGUI.LabelField(position, label.text, "Use with string fields.");
}
}
</code></pre>
<p>The code works fine, but for some reason when I change the parameters in the animator object, <code>animator.parameters</code> returns an empty array.</p>
<p>When I modify the code to force Unity to recompile, I get the correct values and the code works again.</p>
<p>What is the reason for this, and how can I fix it?</p>
| [
{
"answer_id": 74454127,
"author": "Milan Egon Votrubec",
"author_id": 8051819,
"author_profile": "https://Stackoverflow.com/users/8051819",
"pm_score": 1,
"selected": false,
"text": "AnimationPropertyDrawer"
},
{
"answer_id": 74465559,
"author": "SagiZiv",
"author_id": 9... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9977758/"
] |
74,452,982 | <pre><code>import random
def foo():
list_of_odd_num = []
for i in range (1, 10000, 2):
list_of_odd_num.append(i)
return list_of_odd_num
def bar():
list_of_uppercase_letters = []
for k in range(1, 100):
rand_num = random.randint(65, 90)
letter = chr(rand_num)
k = list_of_uppercase_letters.append(letter)
return list_of_uppercase_letters
def qux(any_list: list):
i = 0
while i < 20:
for j in range (len(any_list)):
rand_01 = random.randint(0,1)
if rand_01 == 1:
i = i + 1
any_list.insert(j, '?')
return any_list
print(qux(bar()))
</code></pre>
<p>output:
['?', 'D', 'I', '?', 'Y', '?', 'X', 'Q', 'L', 'E', '?', '?', 'I', '?', 'H', '?', '?', '?', '?', 'E', '?', '?', 'B', '?', '?', '?', 'G', '?', '?', '?', '?', 'S', '?', 'U', 'W', 'I', 'G', '?', '?', 'L', '?', 'J', 'M', '?', '?', 'A', 'K', '?', 'X', '?', 'Y', 'J', 'L', 'S', '?', '?', '?', 'I', '?', 'Q', '?', 'S', 'L', 'R', '?', '?', 'L', '?', '?', '?', 'M', 'K', 'E', '?', 'B', '?', 'V', '?', 'I', 'L', '?', 'S', '?', '?', 'O', 'F', '?', 'O', 'S', 'J', '?', 'P', '?', 'X', '?', 'T', 'B', '?', 'Q', 'N', 'T', 'H', 'F', 'A', 'D', 'E', 'P', 'Y', 'Z', 'Q', 'M', 'X', 'I', 'H', 'Z', 'F', 'Q', 'G', 'Q', 'B', 'A', 'G', 'B', 'R', 'N', 'J', 'K', 'C', 'P', 'P', 'E', 'E', 'A', 'R', 'P', 'S', 'A', 'O', 'A', 'I', 'R', 'B', 'W', 'V', 'M', 'I', 'P']</p>
<p>i was trying to insert 20 "?"s in random indexes in a list that was given as an argument to the function qux() without overwriting the original items in the list by writng a while loop with a condition i < 20 and then in the for loop io kept adding up the i until its supposed to reach to 20 and then finish the while loop, but what ended up happening is that the program kept on printing "?"s that reached beyond the number 20 in any list unless it was was empty</p>
| [
{
"answer_id": 74454127,
"author": "Milan Egon Votrubec",
"author_id": 8051819,
"author_profile": "https://Stackoverflow.com/users/8051819",
"pm_score": 1,
"selected": false,
"text": "AnimationPropertyDrawer"
},
{
"answer_id": 74465559,
"author": "SagiZiv",
"author_id": 9... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20513406/"
] |
74,452,987 | <p>I want to know that when we open localhost:4200/signin?url=login at that time I want to open login component and when we open localhost:4200/signin?url=register at that time I have to load register component. So what is the best way to achieve this functionality.</p>
| [
{
"answer_id": 74454127,
"author": "Milan Egon Votrubec",
"author_id": 8051819,
"author_profile": "https://Stackoverflow.com/users/8051819",
"pm_score": 1,
"selected": false,
"text": "AnimationPropertyDrawer"
},
{
"answer_id": 74465559,
"author": "SagiZiv",
"author_id": 9... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74452987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3978465/"
] |
74,453,047 | <p>I am creating a menu for a billing program with tuples inside lists, how would you do to delete a data requested by the user deleting all its values?</p>
<pre><code>menu = """
(1) Añadir Cliente
(2) Eliminar Cliente
(3) Añadir Factura
(4) Procesar facturacion del mes
(5) Listar todos los clientes
(6) Terminar
"""
lista_nom =[]
list_borra2 = []
ventas = []
while True:
print(menu)
opc = input("Escriba una opcion: ")
opc = int(opc)
if opc == 1:
nombre = input("Escribe el nombre del cliente: ")
cif = input('Escribe el cif de cliente: ')
direccion = input("Escribe el direccion de cliente: ")
lista_nom1 = (nombre,cif,direccion)
lista_nom.append(lista_nom1)
print(lista_nom)
#print(lista_nom1)mismo dato en tupla
if opc == 2:
nombre = input('Escriba el nombre del cliente a borrar: ')
for nombre in lista_nom[0]:
lista_nom.remove[(nombre)]
else:
print('No existe el cliente con el nombre', nombre)
# for nom in range(len(lista_nom)):
# for eli in range(len(lista_nom[nom])):
# if lista_nom[nom][eli][0] == nombre:
# del lista_nom[nom:nom+1]
# print(lista_nom)
</code></pre>
<p>I have tried to access the element with nested for but it simply does nothing.</p>
<p>try to create a new list to store the deleted data and then install it in the first list with the main values to be deleted</p>
<pre><code> # list_borra2.append(nombre)
# for nom in range(len(lista_nom)):
# for eli in range(len(lista_nom[nom])):
# if lista_nom[nom][eli][0] == nombre:
# del lista_nom[nom:nom+1]
# print(lista_nom)
# lista_nom.remove(nombre)
# list_borra2 += lista_nom
# # print(list_borra2)
# print(list_borra2)
</code></pre>
| [
{
"answer_id": 74453169,
"author": "wallbloggerbeing",
"author_id": 16581025,
"author_profile": "https://Stackoverflow.com/users/16581025",
"pm_score": 1,
"selected": false,
"text": "nom_remove = lista_nom[:nom] + lista_nom[(nom+1):]\n"
},
{
"answer_id": 74453474,
"author": "... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13926648/"
] |
74,453,055 | <p>Can someone explain the following, please?</p>
<ol>
<li>this compiles (explanation: NLL <code>y</code> not referenced after initial definition?)</li>
</ol>
<pre><code>fn main() {
let mut x = 5;
let y = &x;
let z = &mut x;
println!("z: {}", z);
}
</code></pre>
<ol start="2">
<li>this <strong>doesn't</strong> compile (explanation: <code>z</code> not referenced but only introduced the line before so still active?)</li>
</ol>
<pre><code>fn main() {
let mut x = 5;
let y = &x;
let z = &mut x;
println!("y: {}", y);
}
</code></pre>
<ol start="3">
<li>this compiles (explanation: NLL <code>z</code> not referenced after initial definition?)</li>
</ol>
<pre><code>fn main() {
let mut x = 5;
let z = &mut x;
let y = &x;
println!("y: {}", y);
}
</code></pre>
<ol start="4">
<li>this <strong>doesn't</strong> compile (just to see whether introducing lines would lead to <code>z</code> not being active by the <code>println</code>)</li>
</ol>
<pre><code>fn main() {
let mut x = 5;
let y = &x;
let z = &mut x;
let foo = String::from("foo");
println!("y: {}, foo: {}", y, foo);
}
</code></pre>
<p>I'm confused... I couldn't find anything that covers this specific case in the book but if somebody has a link to something that explains this behaviour, I would appreciate it.</p>
| [
{
"answer_id": 74453176,
"author": "Adam Smith",
"author_id": 3058609,
"author_profile": "https://Stackoverflow.com/users/3058609",
"pm_score": 2,
"selected": true,
"text": "// example one\nfn main() {\n let mut x = 5;\n let y = &x; // y is declared here, but never used\n ... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2333690/"
] |
74,453,141 | <p>I am having problems implementing the <a href="https://laravel-vue-pagination.org/guide/quick-start.html" rel="nofollow noreferrer">gilbertron laravel vue pagination package</a></p>
<p>I followed the instructions as far as I can tell to implement it, however I am re-learning javascript after 20 years hiatus from development, so I need your assistance.</p>
<p>This is the data I am trying to paginate that is posted using a route & controller in laravel using the paginate() function.</p>
<p><a href="https://i.stack.imgur.com/qsq4c.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qsq4c.jpg" alt="enter image description here" /></a></p>
<p>I get this warning when looking at the console to try and troubleshoot the problem.</p>
<p><a href="https://i.stack.imgur.com/ML7pA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ML7pA.jpg" alt="enter image description here" /></a></p>
<p>This is my code I am using in my vue file.</p>
<pre><code><script setup>
import AppLayout from '@/Layouts/AppLayout.vue';
import { Link } from "@inertiajs/inertia-vue3";
import { TailwindPagination } from 'laravel-vue-pagination';
defineProps({
articles: Object,
});
</script>
<template>
<AppLayout title="Articles">
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
Articles
</h2>
</template>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
<section class="flex md:flex-row m-2 p-2">
<div class="w-11/12">
<div v-if="articles.length > 0">
<div v-for="article in articles.data" :key="article.id">
<!-- Add articles data here -->
</div>
</div>
</div>
<div class="mt-4 p-2">
<TailwindPagination
:data="articles"
@pagination-change-page="getData"
/>
</div>
</section>
</div>
</div>
</div>
</AppLayout>
</template>
</code></pre>
<p>Currently the page renders as there is no serious errors that it points too, but the page links don't actually render the new page.</p>
<p>I know the "getData" for the page click property is not correct, but I can't find in the documentation how to correctly implement it, so I was hoping that someone could assist or alternatively point me in the direction of a similar package or tutorial that could teach me how to paginate in vue for laravel paginate() function correctly.</p>
| [
{
"answer_id": 74453176,
"author": "Adam Smith",
"author_id": 3058609,
"author_profile": "https://Stackoverflow.com/users/3058609",
"pm_score": 2,
"selected": true,
"text": "// example one\nfn main() {\n let mut x = 5;\n let y = &x; // y is declared here, but never used\n ... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20413406/"
] |
74,453,149 | <p>The route should be resolved only for the given params list (Validate params)</p>
<p>e.g. valid names ["Sam", "Alice"]</p>
<pre><code>//route
{
path: "/customers/:names"
}
// expectation
path = /customers/Sam => matched
path = /customers/Alice => matched
path = /customers/XYZ => Not matched
path = /customers/ABC => Not matched
</code></pre>
<p>How this can be achieved ??</p>
| [
{
"answer_id": 74453176,
"author": "Adam Smith",
"author_id": 3058609,
"author_profile": "https://Stackoverflow.com/users/3058609",
"pm_score": 2,
"selected": true,
"text": "// example one\nfn main() {\n let mut x = 5;\n let y = &x; // y is declared here, but never used\n ... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2247677/"
] |
74,453,157 | <p>This works to select top 100 columns, but it gives me all of the columns</p>
<p><code>select top 100 * from dw.test</code></p>
<p>This works, but it gives me endless rows,</p>
<p><code>select Slot, ID from dw.test</code></p>
<p>I need to select top 100 rows that only show these two columns <code>Slot, ID</code></p>
<p>I cannot get it to work no matter how I try to combine them,
Please help create this query. Thank you</p>
| [
{
"answer_id": 74453291,
"author": "Brandt",
"author_id": 687896,
"author_profile": "https://Stackoverflow.com/users/687896",
"pm_score": 0,
"selected": false,
"text": "SELECT TOP(100) Slot, ID FROM dw.test;\n"
},
{
"answer_id": 74454416,
"author": "lavantho0508_java_dev",
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056201/"
] |
74,453,170 | <p>When i scroll on the website the image and nav bar mix together. The image goes through the navigation bar
and it looks like the background of the navigation bar is the image.</p>
<p>i put the position of the nav bar fixed and the z-index 1 and the div of the image position relative and z-index 0</p>
<pre><code> <div class="header-top">
<a href="#home" class="meny-link"><span class="br">BR</span><span class="arch"> Architects</span></a>
<div class="meny">
<a href="#projects" class="meny-link">Projects</a>
<a href="about" class="meny-link">About</a>
<a href="contact" class="meny-link">Contact</a>
</div>
</div>
<div id="home">
<div class="image">
<img src="skyscraper.jpg" alt="">
</div>
</div>
</html>
</code></pre>
<pre><code>.header-top{
box-shadow: 0px 5px 8px -2px rgba(0,0,0,0.75);
position: fixed;
width: 100%;
top: 0;
left: 0;
padding: 6px 0px;
z-index: 1;
}
.meny{
float: right;
word-spacing: 26px;
padding: 0px 25px 0px 0px;
}
.meny-link{
color: black;
text-decoration: none;
letter-spacing: 3px;
}
.br{
padding: 0px 0px 0px 10px;
font-weight: bold;
}
#home{
position: relative;
top: 23px;
z-index: 0;
}
.image img{
width: 100%;
height: 675px;
}
</code></pre>
| [
{
"answer_id": 74453291,
"author": "Brandt",
"author_id": 687896,
"author_profile": "https://Stackoverflow.com/users/687896",
"pm_score": 0,
"selected": false,
"text": "SELECT TOP(100) Slot, ID FROM dw.test;\n"
},
{
"answer_id": 74454416,
"author": "lavantho0508_java_dev",
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20136506/"
] |
74,453,212 | <p>Is there any way to execute the set method when an instance is created?. I have this piece of code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class CoffeeMachine {
_power;
constructor(power) {
this._power = power;
}
set power(value) {
if (value < 100) {
this._power = 100;
}
}
get power() {
return this._power;
}
}
// create the coffee machine
let machine = new CoffeeMachine(90);
console.log(machine)</code></pre>
</div>
</div>
</p>
<p>I know that if I set "power" to public the setter is executed but I need it to be a protected property. Power is still 90 even it's less than 100, so it doesn't work. Any tips?</p>
| [
{
"answer_id": 74453372,
"author": "epascarello",
"author_id": 14104,
"author_profile": "https://Stackoverflow.com/users/14104",
"pm_score": 2,
"selected": false,
"text": "power"
},
{
"answer_id": 74453821,
"author": "Gavin Morrow",
"author_id": 15920018,
"author_prof... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18111526/"
] |
74,453,226 | <p>Various R functions make it easy to use group_by and summarize to pull a value from a grouped variable. So in the resulting dataframe, I can use group_by and summarise to create, for example, a new column that contains the maximum or minimum value of a variable within each group. Meaning, with this data:</p>
<pre><code>name, value
foo, 100
foo, 200
foo, 300
bar, 400
bar, 500
bar, 600
</code></pre>
<p>I can easily get the max or min for each value of name:</p>
<pre><code>group_by(name) %>% summarize(maxValue = max(value)
</code></pre>
<p>But suppose I want the second ranked value for each name? Meaning suppose I want my result to be</p>
<pre><code>name maxValue secondValue
foo 300 200
bar 600 500
</code></pre>
<p>In other words, how do I fill in the blank in this:</p>
<pre><code>df %>% group_by(name) %>%
summarize(maxValue = max(value),
secondValue = _________)
</code></pre>
<p>Thanks, from an r newbie, for any help!</p>
| [
{
"answer_id": 74453372,
"author": "epascarello",
"author_id": 14104,
"author_profile": "https://Stackoverflow.com/users/14104",
"pm_score": 2,
"selected": false,
"text": "power"
},
{
"answer_id": 74453821,
"author": "Gavin Morrow",
"author_id": 15920018,
"author_prof... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5176356/"
] |
74,453,286 | <p>I have a series of functions that I need to call, and all the calls are of the form:</p>
<pre><code>StartingFunctionName[Thing]Callback(&[Thing]);
</code></pre>
<p>Where <code>[Thing]</code> is the same thing each time
for example, I have to call</p>
<pre><code>StartingFunctionNameMyFunctionCallback(&MyFunction);
</code></pre>
<p>and I'd like to rather do <code>foo(MyFunction);</code> where foo would be the macro.</p>
<p>I was wondering if there was a way to use a macro, so that its input is the string (or something like that) Thing, and the output is the correct line of code.</p>
| [
{
"answer_id": 74453365,
"author": "Erdal Küçük",
"author_id": 11867590,
"author_profile": "https://Stackoverflow.com/users/11867590",
"pm_score": 2,
"selected": false,
"text": "StartingFunctionName[Thing]Callback(&[Thing]);\n"
},
{
"answer_id": 74453377,
"author": "Guelque H... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12705701/"
] |
74,453,306 | <p>I have a matrix (two-dimensional list) filled with dictionary-type variable in the entire scope containing <code>"val": False</code></p>
<p>The problem is when I want to change only one item in the matrix and chanhge the value to True for this one paticular item.</p>
<p>Somehow this part of code: <code>matrix[3][2]["val"] = True</code> causes the entire matrix to update the "val" value and changes all False values to True.</p>
<p>Here is my code:</p>
<pre><code>defval = {
"val": False
}
matrix = []
for x in range(5):
row = []
for i in range(5):
row.append(defval)
matrix.append(row)
matrix[3][2]["val"] = True
</code></pre>
| [
{
"answer_id": 74453386,
"author": "Lorenz Hetterich",
"author_id": 20473701,
"author_profile": "https://Stackoverflow.com/users/20473701",
"pm_score": 1,
"selected": false,
"text": "row.append(defval)"
},
{
"answer_id": 74453470,
"author": "Siew",
"author_id": 17315005,
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1850012/"
] |
74,453,346 | <p>I'm trying to display an image I have saved as a resource under the properties category.
This property however returns a <code>byte[]</code> which can't be displayed by <code><Image></code> since it can't convert it to <code>ImageSource</code>.
The code looks like this:</p>
<pre class="lang-cs prettyprint-override"><code>public byte[] MyImage = Properties.ImageResources.MyImage
</code></pre>
<p>but plugging <code>MyImage</code> into</p>
<pre class="lang-xml prettyprint-override"><code><Image Source="{x:Bind MyImage}"
</code></pre>
<p>gives me a conversion error as described above.</p>
<p>I've already tried converting the image to a bitmap to display this instead, but I got the very same error.
I've read alot about something like</p>
<pre class="lang-cs prettyprint-override"><code>bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
</code></pre>
<p>but then it tells me it can't resolve any of the <code>BitmapImage</code> Functions -> BeginInit, EndInit, StreamSource and CacheOption.</p>
<p>I've searched far and wide but they all end in this <code>BeginInit()</code> and <code>EndInit()</code> function which do not exist for me.</p>
| [
{
"answer_id": 74453386,
"author": "Lorenz Hetterich",
"author_id": 20473701,
"author_profile": "https://Stackoverflow.com/users/20473701",
"pm_score": 1,
"selected": false,
"text": "row.append(defval)"
},
{
"answer_id": 74453470,
"author": "Siew",
"author_id": 17315005,
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20453719/"
] |
74,453,395 | <p>In a .NET 7 project, I use Serilog (the latest <a href="https://www.nuget.org/packages/Serilog.Extensions.Logging.File/3.0.0" rel="nofollow noreferrer"><code>Serilog.Extensions.Logging.File v3.0.0</code></a>) and get a bunch of errors <code>NU1605</code> when trying to compile the project with <code>dotnet publish</code>:</p>
<pre><code>Agent.csproj : error NU1605: Detected package downgrade: System.IO from 4.3.0 to 4.1.0. Reference the package directly from the project to select a different version.
Agent.csproj : error NU1605: Agent -> Serilog.Extensions.Logging.File 3.0.0 -> Serilog.Sinks.RollingFile 3.3.0 -> Serilog.Sinks.File 3.2.0 -> System.IO.FileSystem 4.0.1 -> runtime.win.System.IO.FileSystem 4.3.0 -> System.IO (>= 4.3.0)
Agent.csproj : error NU1605: Agent -> Serilog.Extensions.Logging.File 3.0.0 -> Serilog.Sinks.RollingFile 3.3.0 -> System.IO (>= 4.1.0)
Agent.csproj : error NU1605: Detected package downgrade: System.IO.FileSystem.Primitives from 4.3.0 to 4.0.1. Reference the package directly from the project to select a different version.
Agent.csproj : error NU1605: Agent -> Serilog.Extensions.Logging.File 3.0.0 -> Serilog.Sinks.RollingFile 3.3.0 -> Serilog.Sinks.File 3.2.0 -> System.IO.FileSystem 4.0.1 -> runtime.win.System.IO.FileSystem 4.3.0 -> System.IO.FileSystem.Primitives (>= 4.3.0)
Agent.csproj : error NU1605: Agent -> Serilog.Extensions.Logging.File 3.0.0 -> Serilog.Sinks.RollingFile 3.3.0 -> System.IO.FileSystem.Primitives (>= 4.0.1)
Agent.csproj : error NU1605: Detected package downgrade: System.Runtime.Handles from 4.3.0 to 4.0.1. Reference the package directly from the project to select a different version.
Agent.csproj : error NU1605: Agent -> Serilog.Extensions.Logging.File 3.0.0 -> Serilog.Sinks.RollingFile 3.3.0 -> Serilog.Sinks.File 3.2.0 -> System.IO.FileSystem 4.0.1 -> runtime.win.System.IO.FileSystem 4.3.0 -> System.Runtime.Handles (>= 4.3.0)
Agent.csproj : error NU1605: Agent -> Serilog.Extensions.Logging.File 3.0.0 -> Serilog.Sinks.RollingFile 3.3.0 -> Serilog.Sinks.File 3.2.0 -> System.IO.FileSystem 4.0.1 -> System.Runtime.Handles (>= 4.0.1)
</code></pre>
<p>Upon some digging, I've found that adding the following to my <code>.csproj</code> file solves the problem:</p>
<pre class="lang-xml prettyprint-override"><code> <PackageReference Include="Microsoft.NETCore.Platforms" Version="7.0.0" />
<PackageReference Include="Microsoft.NETCore.Targets" Version="5.0.0" PrivateAssets="All" />
</code></pre>
<p>However, the <a href="https://www.nuget.org/packages/Microsoft.NETCore.Targets/6.0.0-preview.4.21253.7" rel="nofollow noreferrer"><code>Microsoft.NETCore.Targets</code></a> package was stopped being updated at <code>v6.0.0-preview.4.21253.7</code>. Apparently, it has been deprecated, see the <a href="https://github.com/dotnet/runtime/pull/52261" rel="nofollow noreferrer">"Delete Microsoft.NETCore.Targets package"</a> issue.</p>
<p>To troubleshoot it further, I've enabled <a href="https://devblogs.microsoft.com/nuget/enable-repeatable-package-restores-using-a-lock-file/" rel="nofollow noreferrer">"repeatable package restores using a lock file"</a> (the right thing to do for CI builds anyway). Here's what I see in my <code>packages.lock.json</code>:</p>
<pre class="lang-json prettyprint-override"><code> "Serilog.Sinks.RollingFile": {
"type": "Transitive",
"resolved": "3.3.0",
"contentHash": "2lT5X1r3GH4P0bRWJfhA7etGl8Q2Ipw9AACvtAHWRUSpYZ42NGVyHoVs2ALBZ/cAkkS+tA4jl80Zie144eLQPg==",
"dependencies": {
"Serilog.Sinks.File": "3.2.0",
"System.IO": "4.1.0",
"System.IO.FileSystem.Primitives": "4.0.1",
"System.Runtime.InteropServices": "4.1.0",
"System.Text.Encoding.Extensions": "4.0.11"
}
},
// ...
"System.IO": {
"type": "Transitive",
"resolved": "4.1.0",
"contentHash": "3KlTJceQc3gnGIaHZ7UBZO26SHL1SHE4ddrmiwumFnId+CEHP+O8r386tZKaE6zlk5/mF8vifMBzHj9SaXN+mQ==",
"dependencies": {
"Microsoft.NETCore.Platforms": "1.0.1",
"Microsoft.NETCore.Targets": "1.0.1",
"System.Runtime": "4.1.0",
"System.Text.Encoding": "4.0.11",
"System.Threading.Tasks": "4.0.11"
}
},
"System.IO.FileSystem": {
"type": "Transitive",
"resolved": "4.0.1",
"contentHash": "IBErlVq5jOggAD69bg1t0pJcHaDbJbWNUZTPI96fkYWzwYbN6D9wRHMULLDd9dHsl7C2YsxXL31LMfPI1SWt8w==",
"dependencies": {
"Microsoft.NETCore.Platforms": "1.0.1",
"Microsoft.NETCore.Targets": "1.0.1",
"System.IO": "4.1.0",
"System.IO.FileSystem.Primitives": "4.0.1",
"System.Runtime": "4.1.0",
"System.Runtime.Handles": "4.0.1",
"System.Text.Encoding": "4.0.11",
"System.Threading.Tasks": "4.0.11"
}
},
</code></pre>
<p>Given that <code>Microsoft.NETCore.Targets</code> has been deprecated, <strong>what is the proper strategy to solve this problem</strong>, which I believe can be pretty common these days, now that .NET 3.x LTS is nearing EOL and .NET has been released?</p>
<p>Also, what is the magic behind the current workaround, provided that <code>Microsoft.NETCore.Targets</code> is basically just an empty package, with a zero-length <code>lib\netstandard1.0\_._</code> file inside it?</p>
| [
{
"answer_id": 74453386,
"author": "Lorenz Hetterich",
"author_id": 20473701,
"author_profile": "https://Stackoverflow.com/users/20473701",
"pm_score": 1,
"selected": false,
"text": "row.append(defval)"
},
{
"answer_id": 74453470,
"author": "Siew",
"author_id": 17315005,
... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768303/"
] |
74,453,409 | <p>this is part of the database. The extention is .sql</p>
<pre><code>-- phpMyAdmin SQL Dump
-- version 3.2.0.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: May 20, 2011 at 05:08 PM
-- Server version: 5.1.36
-- PHP Version: 5.2.9-2
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `bincomphptest`
--
-- --------------------------------------------------------
--
-- Table structure for table `agentname`
--
DROP TABLE IF EXISTS `agentname`;
CREATE TABLE IF NOT EXISTS `agentname` (
`name_id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(255) NOT NULL,
`lastname` varchar(255) NOT NULL,
`email` varchar(255) DEFAULT NULL,
`phone` char(13) NOT NULL,
`pollingunit_uniqueid` int(11) NOT NULL,
PRIMARY KEY (`name_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
</code></pre>
<p>I was creating a new database on django with mysqlite but I think I'm inexperience and this maybe possible</p>
| [
{
"answer_id": 74454039,
"author": "user11717481",
"author_id": 11717481,
"author_profile": "https://Stackoverflow.com/users/11717481",
"pm_score": 0,
"selected": false,
"text": "name_id"
},
{
"answer_id": 74460271,
"author": "Mina Atef",
"author_id": 12860808,
"autho... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20514833/"
] |
74,453,422 | <p>I am having trouble adding hulls to my plot. I have added a photo for reference + my existing script below.</p>
<p><a href="https://i.stack.imgur.com/33s3u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/33s3u.png" alt="enter image description here" /></a></p>
<p>The X and Y axes represent the PC1 scores for shape measurements of two different bones. I have successfully plotted this and gotten the r2 to measure correlation of shape between the bones across different genera of primates. Within this plot, each dot represents a different genus of primate. What I want to do now, is create hulls to represent specific groupings of these genera.</p>
<p>I have found a lot online about adding hulls to other plots (and have done this just fine) but am struggling to add it to this. My code is below (sans any attempts to add a hull).</p>
<pre><code>ggplot(myd_,aes(x = PC1_mean_calcaneus, y = PC1_mean_hamate, label=genus)) +
geom_point() +
geom_text(hjust=0, vjust=0)+ #add my labels per dot
geom_smooth(method = "lm", se=FALSE) +
stat_regline_equation(label.y = .6, aes(label = ..eq.label..)) +
stat_regline_equation(label.y = .5, aes(label = ..rr.label..))
</code></pre>
| [
{
"answer_id": 74454361,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 0,
"selected": false,
"text": "chull()"
},
{
"answer_id": 74454455,
"author": "Dan Adams",
"author_id": 13210554,
"author_pro... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74453422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20514821/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.