qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,629,888
<p>I want to disable the dates in the datepicker in flutter. Actually I am wokring on an application where user has to generate salary but I don't want him to generate salary if the salary is already created.</p> <p>suppose salary is created 1-10-2022 to 30-10-2022 then i want to disable all the previous dates from 30-10-2022...How can i do this ??</p> <p><a href="https://i.stack.imgur.com/hk38l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hk38l.png" alt="enter image description here" /></a></p> <pre><code> onTap: () async { await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(2000), lastDate: DateTime(3000), ).then((selectedDate) { if (selectedDate != null) { _startDatePickerController.text = DateFormat('d-MM-y') .format(selectedDate) .toString(); } return null; }); }, </code></pre>
[ { "answer_id": 74630233, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 2, "selected": false, "text": "DECLARE @parts TABLE (PartID INT, SubPartID INT, Quantity INT)\nINSERT INTO @parts (PartID, SubPartID, Quantity) VALUES\n(1, 2, 2), (1, 3, 4),\n(1, 5, 8), (2, 8, 13)\n SELECT p.SubPartID\n FROM @parts p\n LEFT OUTER JOIN @parts p2\n ON p.SubPartID = p2.PartID\n WHERE p2.PartID IS NULL\n SubPartID\n---------\n3\n5\n8\n DECLARE @parts TABLE (PartID INT, SubPartID INT, Quantity INT, Name NVARCHAR(20))\nINSERT INTO @parts (PartID, SubPartID, Quantity, name) VALUES\n(1, NULL, 1, 'Bicyle'), (2, 1, 1, 'Wheel'), (5, 2, 1, 'Rim'), (6, 2, 1, 'Tyre'), (7, 5, 1, 'Spoke'),\n(8, 6, 1, 'Rubber'), (9, 6, 1, 'Valve'), (10, NULL, 1, 'Cake'), (11, 10, 3, 'Flour'), (12, 10, 1, 'Milk'),\n(13, 10, 2, 'Egg'),(14, 13, 1, 'Yoke'), (15, 13, 1, 'White'),(16, 10, 3, 'Sugar'), (17, 10, 1, 'Berries'),\n(18, 17, 1, 'Raspberry'),(19, 17, 1, 'Strawberry'), (20, 17, 1, 'Blueberry')\n ;WITH cte AS (\nSELECT PartID AS GlobalParentPartID, PartID, SubPartID, Quantity, Name\n FROM @parts\n UNION ALL\nSELECT GlobalParentPartID, r.PartID, r.SubPartID, r.Quantity, r.Name\n FROM cte a\n INNER JOIN @parts r\n ON a.PartID = r.SubPartID\n)\n\nSELECT i.GlobalParentPartID, i.Name, p.Name, p.SubPartID, p.Quantity\n FROM cte i\n INNER JOIN @parts p\n ON i.GlobalParentPartID = p.PartID\n AND i.PartID <> p.PartID\n LEFT OUTER JOIN @parts p2\n ON i.PartID = p2.SubPartID\n WHERE p2.PartID IS NULL\n ORDER BY i.GlobalParentPartID\n \nGlobalParentPartID Name Name SubPartID Quantity\n------------------------------------------------------------\n1 Rubber Bicyle NULL 1\n1 Valve Bicyle NULL 1\n1 Spoke Bicyle NULL 1\n2 Rubber Wheel 1 1\n2 Valve Wheel 1 1\n2 Spoke Wheel 1 1\n5 Spoke Rim 2 1\n6 Rubber Tyre 2 1\n6 Valve Tyre 2 1\n10 Flour Cake NULL 1\n10 Milk Cake NULL 1\n10 Sugar Cake NULL 1\n10 Raspberry Cake NULL 1\n10 Strawberry Cake NULL 1\n10 Blueberry Cake NULL 1\n10 Yoke Cake NULL 1\n10 White Cake NULL 1\n13 Yoke Egg 10 2\n13 White Egg 10 2\n17 Raspberry Berries 10 1\n17 Strawberry Berries 10 1\n17 Blueberry Berries 10 1\n" }, { "answer_id": 74631934, "author": "Ben Thul", "author_id": 568209, "author_profile": "https://Stackoverflow.com/users/568209", "pm_score": 0, "selected": false, "text": "not exists select *\nfrom @parts as child\nwhere not exists (\n select PartID\n from @parts as parent\n where parent.PartID = child.SubPartID\n);\n group by distinct" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18674968/" ]
74,629,899
<p>I know that there are many similar questions, and <a href="https://stackoverflow.com/questions/25027462/aws-s3-the-bucket-you-are-attempting-to-access-must-be-addressed-using-the-spec">this one</a> is no exception</p> <p>But unfortunately I can't decide on the region for my case, how can I decide on the right region?</p> <p>For example, when making a request to Postman, I encounter a similar error: <a href="https://i.stack.imgur.com/ZfKKs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZfKKs.png" alt="enter image description here" /></a></p> <p>In my console i'm using <code>EU (Frankfurt) eu-central-1</code> and also in terminal write smth like this:</p> <pre><code>heroku config:set region=&quot;eu-central-1&quot; </code></pre> <p>And as I understand it, mine does not fit.</p> <p>Also here is my AWS class:</p> <pre><code>class AmazonFileStorage : FileStorage { private val client: S3Client private val bucketName: String = System.getenv(&quot;bucketName&quot;) init { val region = System.getenv(&quot;region&quot;) val accessKey = System.getenv(&quot;accessKey&quot;) val secretKey = System.getenv(&quot;secretKey&quot;) val credentials = AwsBasicCredentials.create(accessKey, secretKey) val awsRegion = Region.of(region) client = S3Client.builder() .credentialsProvider(StaticCredentialsProvider.create(credentials)) .region(awsRegion) .build() as S3Client } override suspend fun save(file: File): String = withContext(Dispatchers.IO) { client.putObject( PutObjectRequest.builder().bucket(bucketName).key(file.name).acl(ObjectCannedACL.PUBLIC_READ).build(), RequestBody.fromFile(file) ) val request = GetUrlRequest.builder().bucket(bucketName).key(file.name).build() client.utilities().getUrl(request).toExternalForm() } } </code></pre>
[ { "answer_id": 74630233, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 2, "selected": false, "text": "DECLARE @parts TABLE (PartID INT, SubPartID INT, Quantity INT)\nINSERT INTO @parts (PartID, SubPartID, Quantity) VALUES\n(1, 2, 2), (1, 3, 4),\n(1, 5, 8), (2, 8, 13)\n SELECT p.SubPartID\n FROM @parts p\n LEFT OUTER JOIN @parts p2\n ON p.SubPartID = p2.PartID\n WHERE p2.PartID IS NULL\n SubPartID\n---------\n3\n5\n8\n DECLARE @parts TABLE (PartID INT, SubPartID INT, Quantity INT, Name NVARCHAR(20))\nINSERT INTO @parts (PartID, SubPartID, Quantity, name) VALUES\n(1, NULL, 1, 'Bicyle'), (2, 1, 1, 'Wheel'), (5, 2, 1, 'Rim'), (6, 2, 1, 'Tyre'), (7, 5, 1, 'Spoke'),\n(8, 6, 1, 'Rubber'), (9, 6, 1, 'Valve'), (10, NULL, 1, 'Cake'), (11, 10, 3, 'Flour'), (12, 10, 1, 'Milk'),\n(13, 10, 2, 'Egg'),(14, 13, 1, 'Yoke'), (15, 13, 1, 'White'),(16, 10, 3, 'Sugar'), (17, 10, 1, 'Berries'),\n(18, 17, 1, 'Raspberry'),(19, 17, 1, 'Strawberry'), (20, 17, 1, 'Blueberry')\n ;WITH cte AS (\nSELECT PartID AS GlobalParentPartID, PartID, SubPartID, Quantity, Name\n FROM @parts\n UNION ALL\nSELECT GlobalParentPartID, r.PartID, r.SubPartID, r.Quantity, r.Name\n FROM cte a\n INNER JOIN @parts r\n ON a.PartID = r.SubPartID\n)\n\nSELECT i.GlobalParentPartID, i.Name, p.Name, p.SubPartID, p.Quantity\n FROM cte i\n INNER JOIN @parts p\n ON i.GlobalParentPartID = p.PartID\n AND i.PartID <> p.PartID\n LEFT OUTER JOIN @parts p2\n ON i.PartID = p2.SubPartID\n WHERE p2.PartID IS NULL\n ORDER BY i.GlobalParentPartID\n \nGlobalParentPartID Name Name SubPartID Quantity\n------------------------------------------------------------\n1 Rubber Bicyle NULL 1\n1 Valve Bicyle NULL 1\n1 Spoke Bicyle NULL 1\n2 Rubber Wheel 1 1\n2 Valve Wheel 1 1\n2 Spoke Wheel 1 1\n5 Spoke Rim 2 1\n6 Rubber Tyre 2 1\n6 Valve Tyre 2 1\n10 Flour Cake NULL 1\n10 Milk Cake NULL 1\n10 Sugar Cake NULL 1\n10 Raspberry Cake NULL 1\n10 Strawberry Cake NULL 1\n10 Blueberry Cake NULL 1\n10 Yoke Cake NULL 1\n10 White Cake NULL 1\n13 Yoke Egg 10 2\n13 White Egg 10 2\n17 Raspberry Berries 10 1\n17 Strawberry Berries 10 1\n17 Blueberry Berries 10 1\n" }, { "answer_id": 74631934, "author": "Ben Thul", "author_id": 568209, "author_profile": "https://Stackoverflow.com/users/568209", "pm_score": 0, "selected": false, "text": "not exists select *\nfrom @parts as child\nwhere not exists (\n select PartID\n from @parts as parent\n where parent.PartID = child.SubPartID\n);\n group by distinct" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6387618/" ]
74,629,902
<p>&lt;class 'blog.admin.CommentAdmin'&gt;: (admin.E108) The value of 'list_display[4]' refers to 'active', which is not a callable, an attribute of 'CommentAdmin', or an attribute or method on 'blog.Comment'.</p> <p>&lt;class 'blog.admin.CommentAdmin'&gt;: (admin.E116) The value of 'list_filter[0]' refers to 'active', which does not refer to a Field.</p> <p>I am receiving these two errors.</p> <p>This is my models.py code:</p> <pre><code>from django.contrib.auth.models import User # Create your models here. STATUS = ( (0,&quot;Draft&quot;), (1,&quot;Publish&quot;) ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updatedOn = models.DateTimeField(auto_now= True) content = models.TextField() createdOn = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-createdOn'] def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() createdOn = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=False) class Meta: ordering = ['createdOn'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) </code></pre> <p>This is my admin.py code:</p> <pre><code>from django.contrib import admin from .models import Post, Comment # Register your models here. class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'status','createdOn') list_filter = (&quot;status&quot;, 'createdOn') search_fields = ['title', 'content'] prepopulated_fields = {'slug': ('title',)} @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'body', 'post', 'createdOn', 'active') list_filter = ('active', 'createdOn') search_fields = ('name', 'email', 'body') actions = ['approveComments'] def approveComments(self, request, queryset): queryset.update(active=True) admin.site.register(Post, PostAdmin) </code></pre> <p>This is my forms.py code:</p> <pre><code>from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body') </code></pre> <p>Any help is greatly appreciated.</p>
[ { "answer_id": 74630233, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 2, "selected": false, "text": "DECLARE @parts TABLE (PartID INT, SubPartID INT, Quantity INT)\nINSERT INTO @parts (PartID, SubPartID, Quantity) VALUES\n(1, 2, 2), (1, 3, 4),\n(1, 5, 8), (2, 8, 13)\n SELECT p.SubPartID\n FROM @parts p\n LEFT OUTER JOIN @parts p2\n ON p.SubPartID = p2.PartID\n WHERE p2.PartID IS NULL\n SubPartID\n---------\n3\n5\n8\n DECLARE @parts TABLE (PartID INT, SubPartID INT, Quantity INT, Name NVARCHAR(20))\nINSERT INTO @parts (PartID, SubPartID, Quantity, name) VALUES\n(1, NULL, 1, 'Bicyle'), (2, 1, 1, 'Wheel'), (5, 2, 1, 'Rim'), (6, 2, 1, 'Tyre'), (7, 5, 1, 'Spoke'),\n(8, 6, 1, 'Rubber'), (9, 6, 1, 'Valve'), (10, NULL, 1, 'Cake'), (11, 10, 3, 'Flour'), (12, 10, 1, 'Milk'),\n(13, 10, 2, 'Egg'),(14, 13, 1, 'Yoke'), (15, 13, 1, 'White'),(16, 10, 3, 'Sugar'), (17, 10, 1, 'Berries'),\n(18, 17, 1, 'Raspberry'),(19, 17, 1, 'Strawberry'), (20, 17, 1, 'Blueberry')\n ;WITH cte AS (\nSELECT PartID AS GlobalParentPartID, PartID, SubPartID, Quantity, Name\n FROM @parts\n UNION ALL\nSELECT GlobalParentPartID, r.PartID, r.SubPartID, r.Quantity, r.Name\n FROM cte a\n INNER JOIN @parts r\n ON a.PartID = r.SubPartID\n)\n\nSELECT i.GlobalParentPartID, i.Name, p.Name, p.SubPartID, p.Quantity\n FROM cte i\n INNER JOIN @parts p\n ON i.GlobalParentPartID = p.PartID\n AND i.PartID <> p.PartID\n LEFT OUTER JOIN @parts p2\n ON i.PartID = p2.SubPartID\n WHERE p2.PartID IS NULL\n ORDER BY i.GlobalParentPartID\n \nGlobalParentPartID Name Name SubPartID Quantity\n------------------------------------------------------------\n1 Rubber Bicyle NULL 1\n1 Valve Bicyle NULL 1\n1 Spoke Bicyle NULL 1\n2 Rubber Wheel 1 1\n2 Valve Wheel 1 1\n2 Spoke Wheel 1 1\n5 Spoke Rim 2 1\n6 Rubber Tyre 2 1\n6 Valve Tyre 2 1\n10 Flour Cake NULL 1\n10 Milk Cake NULL 1\n10 Sugar Cake NULL 1\n10 Raspberry Cake NULL 1\n10 Strawberry Cake NULL 1\n10 Blueberry Cake NULL 1\n10 Yoke Cake NULL 1\n10 White Cake NULL 1\n13 Yoke Egg 10 2\n13 White Egg 10 2\n17 Raspberry Berries 10 1\n17 Strawberry Berries 10 1\n17 Blueberry Berries 10 1\n" }, { "answer_id": 74631934, "author": "Ben Thul", "author_id": 568209, "author_profile": "https://Stackoverflow.com/users/568209", "pm_score": 0, "selected": false, "text": "not exists select *\nfrom @parts as child\nwhere not exists (\n select PartID\n from @parts as parent\n where parent.PartID = child.SubPartID\n);\n group by distinct" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20254624/" ]
74,629,931
<p>I was assigned a task for university where I have to write a program which deletes all words with more than 4 letters. I really have no clue at all. I would be very thankful for any kind of help.</p> <pre><code>VAR UserString: string; //должна быть строка на 40 символов и точку в конце i, n: byte; BEGIN Writeln('Enter the string:'); Readln(UserString); i:=0; n:=1; repeat //MAIN LOOP: inc(i); if (UserString[i] = ' ') or (UserString[i] = '.') then begin if (i-n&lt;3)then begin delete(UserString, n, i-n+1); i:=n-1; end; n:=i+1 end until (UserString[i] = '.') or (i&gt;length(UserString)); Writeln('Result String: ', UserString); END. </code></pre> <p>I tried this. and its working on onlinegdb but not on Delphi... and I don't know why...</p>
[ { "answer_id": 74630233, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 2, "selected": false, "text": "DECLARE @parts TABLE (PartID INT, SubPartID INT, Quantity INT)\nINSERT INTO @parts (PartID, SubPartID, Quantity) VALUES\n(1, 2, 2), (1, 3, 4),\n(1, 5, 8), (2, 8, 13)\n SELECT p.SubPartID\n FROM @parts p\n LEFT OUTER JOIN @parts p2\n ON p.SubPartID = p2.PartID\n WHERE p2.PartID IS NULL\n SubPartID\n---------\n3\n5\n8\n DECLARE @parts TABLE (PartID INT, SubPartID INT, Quantity INT, Name NVARCHAR(20))\nINSERT INTO @parts (PartID, SubPartID, Quantity, name) VALUES\n(1, NULL, 1, 'Bicyle'), (2, 1, 1, 'Wheel'), (5, 2, 1, 'Rim'), (6, 2, 1, 'Tyre'), (7, 5, 1, 'Spoke'),\n(8, 6, 1, 'Rubber'), (9, 6, 1, 'Valve'), (10, NULL, 1, 'Cake'), (11, 10, 3, 'Flour'), (12, 10, 1, 'Milk'),\n(13, 10, 2, 'Egg'),(14, 13, 1, 'Yoke'), (15, 13, 1, 'White'),(16, 10, 3, 'Sugar'), (17, 10, 1, 'Berries'),\n(18, 17, 1, 'Raspberry'),(19, 17, 1, 'Strawberry'), (20, 17, 1, 'Blueberry')\n ;WITH cte AS (\nSELECT PartID AS GlobalParentPartID, PartID, SubPartID, Quantity, Name\n FROM @parts\n UNION ALL\nSELECT GlobalParentPartID, r.PartID, r.SubPartID, r.Quantity, r.Name\n FROM cte a\n INNER JOIN @parts r\n ON a.PartID = r.SubPartID\n)\n\nSELECT i.GlobalParentPartID, i.Name, p.Name, p.SubPartID, p.Quantity\n FROM cte i\n INNER JOIN @parts p\n ON i.GlobalParentPartID = p.PartID\n AND i.PartID <> p.PartID\n LEFT OUTER JOIN @parts p2\n ON i.PartID = p2.SubPartID\n WHERE p2.PartID IS NULL\n ORDER BY i.GlobalParentPartID\n \nGlobalParentPartID Name Name SubPartID Quantity\n------------------------------------------------------------\n1 Rubber Bicyle NULL 1\n1 Valve Bicyle NULL 1\n1 Spoke Bicyle NULL 1\n2 Rubber Wheel 1 1\n2 Valve Wheel 1 1\n2 Spoke Wheel 1 1\n5 Spoke Rim 2 1\n6 Rubber Tyre 2 1\n6 Valve Tyre 2 1\n10 Flour Cake NULL 1\n10 Milk Cake NULL 1\n10 Sugar Cake NULL 1\n10 Raspberry Cake NULL 1\n10 Strawberry Cake NULL 1\n10 Blueberry Cake NULL 1\n10 Yoke Cake NULL 1\n10 White Cake NULL 1\n13 Yoke Egg 10 2\n13 White Egg 10 2\n17 Raspberry Berries 10 1\n17 Strawberry Berries 10 1\n17 Blueberry Berries 10 1\n" }, { "answer_id": 74631934, "author": "Ben Thul", "author_id": 568209, "author_profile": "https://Stackoverflow.com/users/568209", "pm_score": 0, "selected": false, "text": "not exists select *\nfrom @parts as child\nwhere not exists (\n select PartID\n from @parts as parent\n where parent.PartID = child.SubPartID\n);\n group by distinct" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20645937/" ]
74,629,938
<p>I know how to get the tenant id of Azure AD. But i have registred an APP in Azure AD using microsoft graph powershell and i want to obtain tenant id of this registred app using microsoft graph powershell. I tried to get it using the variable i used to create the app registration:</p> <pre><code>$APP = New-MgApplication -displayName $AppName ` -RequiredResourceAccess @{ ResourceAppId = $GraphResourceId; ResourceAccess = @($resourceAccess) } ` -SignInAudience $SignInAudience ` -PublicClient @{ RedirectUris = $URL } </code></pre> <p>If i use the variable $App and try to get a property called tenantid, there is nth called like this. <code>$App | Select *</code> did not show any tenantid aswell.</p> <p>Anyone know how to read the tenantid of this registred azure app using microsoft graph powershell?</p>
[ { "answer_id": 74638109, "author": "user2250152", "author_id": 2250152, "author_profile": "https://Stackoverflow.com/users/2250152", "pm_score": 2, "selected": true, "text": "Import-Module Microsoft.Graph.Identity.DirectoryManagement\n\n$org = Get-MgOrganization\n $org.id" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10711853/" ]
74,630,000
<p>i'm having a trouble on comparing two dates in laravel. In my app i have a date field to compare:</p> <pre><code>// example $order_date = Carbon::now()-&gt;format('Y-m-d') // returns &quot;2022-11-30&quot; $now = Carbon::now() // returns an object with date at the bottom date: 2022-11-30 15:51:58.207817 Europe/Rome (+01:00) </code></pre> <p>I need to check this condition:</p> <pre><code> if ($order_date-&gt;lessThan($now)) { return redirect()-&gt;back()-&gt;with('error', 'Message error'); } </code></pre> <p>The problem is that i have to compare only the date, not also the time. So i'm getting this error:</p> <p>Call to a member function lessThan() on string</p> <p>For avoid this error i made some changes like this:</p> <pre><code>$date = Carbon::parse($order_date)-&gt;addHour(00)-&gt;addMinute(00)-&gt;addSeconds(00); $now = Carbon::today() </code></pre> <p>By this way both objects return this date:</p> <pre><code>^ Carbon\Carbon @1669762800 {#1317 ▼ #endOfTime: false #startOfTime: false #constructedObjectId: &quot;00000000000005250000000000000000&quot; #localMonthsOverflow: null #localYearsOverflow: null #localStrictModeEnabled: null #localHumanDiffOptions: null #localToStringFormat: null #localSerializer: null #localMacros: null #localGenericMacros: null #localFormatFunction: null #localTranslator: null #dumpProperties: array:3 [▶] #dumpLocale: null #dumpDateProperties: null date: 2022-11-30 00:00:00.0 Europe/Rome (+01:00) } ^ Carbon\Carbon @1669762800 {#1243 ▼ #endOfTime: false #startOfTime: false #constructedObjectId: &quot;00000000000004db0000000000000000&quot; #localMonthsOverflow: null #localYearsOverflow: null #localStrictModeEnabled: null #localHumanDiffOptions: null #localToStringFormat: null #localSerializer: null #localMacros: null #localGenericMacros: null #localFormatFunction: null #localTranslator: null #dumpProperties: array:3 [▶] #dumpLocale: null #dumpDateProperties: null date: 2022-11-30 00:00:00.0 Europe/Rome (+01:00) } </code></pre> <p>As you can see by this way i can use the lessThan() method and it seems to be fine.</p> <p>But is there any other simplier way to do this? To compare two date strings like &quot;2022-11-30&quot; and &quot;2022-11-29&quot; ?</p>
[ { "answer_id": 74638109, "author": "user2250152", "author_id": 2250152, "author_profile": "https://Stackoverflow.com/users/2250152", "pm_score": 2, "selected": true, "text": "Import-Module Microsoft.Graph.Identity.DirectoryManagement\n\n$org = Get-MgOrganization\n $org.id" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20299680/" ]
74,630,132
<p>I have a list:</p> <pre><code>lst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 1, 2, 3], [['Z', 'C'], 1, 2, 3]] </code></pre> <p>And i want to turn it into:</p> <pre><code>new_lst = [['X', 1, 2, 3], ['A', 1, 2, 3] ['Y', 1, 2, 3], ['B', 1, 2, 3], ['Z', 1, 2, 3], ['C', 1, 2, 3]] </code></pre> <p>I've got it to work with a a single one of them with comprehension.</p> <pre><code> lst2 = [['X', 'Y'], 1, 2, 3] fst, *rest = lst2 new_lst3= [[i, *rest] for i in fst] </code></pre> <p>Which gives me <code> new_list3 = [['X', 1, 2, 3], ['Y', 1, 2, 3]]</code></p> <p>But I don't know how to loop to make it work on the full list.</p> <p>Any good solutions?</p>
[ { "answer_id": 74630180, "author": "I_Hate_ReLU", "author_id": 18345621, "author_profile": "https://Stackoverflow.com/users/18345621", "pm_score": -1, "selected": false, "text": "lst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 1, 2, 3], [['Z', 'C'], 1, 2, 3]]\n\nfor item in lst:\n item[0] = item[0][0];\n\nprint(lst)\n" }, { "answer_id": 74630277, "author": "Edo Akse", "author_id": 9267296, "author_profile": "https://Stackoverflow.com/users/9267296", "pm_score": 2, "selected": false, "text": "lst from pprint import pprint\n\n\nlst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 4, 5, 6], [['Z', 'C'], 7, 8, 9]]\n\nnew_lst = []\nfor elem in lst:\n fst, *rest = elem\n new_lst.extend([[i, *rest] for i in fst])\n\npprint(new_lst, indent=4)\n [ ['X', 1, 2, 3],\n ['A', 1, 2, 3],\n ['Y', 4, 5, 6],\n ['B', 4, 5, 6],\n ['Z', 7, 8, 9],\n ['C', 7, 8, 9]]\n" }, { "answer_id": 74630359, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 3, "selected": true, "text": "new_lst = [[c, *rest] for letters, *rest in lst for c in letters]\n" }, { "answer_id": 74630366, "author": "tobias_k", "author_id": 1639625, "author_profile": "https://Stackoverflow.com/users/1639625", "pm_score": 2, "selected": false, "text": ">>> lst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 1, 2, 3], [['Z', 'C'], 1, 2, 3]]\n>>> [[i, *rest] for (fst, *rest) in lst for i in fst]\n[['X', 1, 2, 3], ['A', 1, 2, 3], ['Y', 1, 2, 3], ['B', 1, 2, 3], ['Z', 1, 2, 3], ['C', 1, 2, 3]]\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20471057/" ]
74,630,143
<p>I am trying to create an Excel plug-in to generate custom functions (aka UDFs) to pull data from a web data source that uses a OAUTH1 Three-Step process to gather the data. It's similar to an OAUTH2 process, but can connect to the localhost.</p> <p>I have code that can run on Node.JS to authorize the OUATH1 process. It uses the following code:</p> <pre><code>`var papaParse = require('papaparse');` `const express = require(&quot;express&quot;);` `const {nanoid} = require(&quot;nanoid&quot;);` `const open = require(&quot;open&quot;);` `const crypto = require('crypto');` `const fetch = (...args) =&gt; import('node-fetch').then(({default: fetch}) =&gt; fetch(...args));` </code></pre> <p>Does the Excel plugin run in the browser space and thus doesn't have access to express?</p> <p>I am not sure I understand how I can potentially use these libraries within an Excel Add-In project. In a worse case scenerio, I can require the user to plugin tokens and remove the requirement for express, but I will still need the other libraries.</p> <p>I added each library to the project using &quot;npm install papaparse&quot;, &quot;npm install express&quot;, etc and expected to be able to access these libraries and use them in the project.</p> <p>Below are the errors I am receiving with the above libraries in the code.</p> <pre><code>`WARNING in ./node_modules/express/lib/view.js 81:13-25` `Critical dependency: the request of a dependency is an expression` `@ ./node_modules/express/lib/application.js 22:11-28` `@ ./node_modules/express/lib/express.js 18:12-36` `@ ./node_modules/express/index.js 11:0-41` `@ ./src/functions/functions.js 49:14-32` `WARNING in ./node_modules/on-finished/index.js 207:11-33` `Module not found: Error: Can't resolve 'async_hooks' in 'C:\Users\EricLevy\OneDrive - Meridian Business Services\mb_ns_connector_test\mb_ns_connector_test\node_modules\on-finished'` `@ ./node_modules/express/lib/response.js 23:17-39` `@ ./node_modules/express/lib/express.js 22:10-31` `@ ./node_modules/express/index.js 11:0-41` `@ ./src/functions/functions.js 49:14-32` `WARNING in ./node_modules/raw-body/index.js 302:11-33` `Module not found: Error: Can't resolve 'async_hooks' in 'C:\Users\EricLevy\OneDrive - Meridian Business Services\mb_ns_connector_test\mb_ns_connector_test\node_modules\raw-body'` `@ ./node_modules/body-parser/lib/read.js 16:14-33` `@ ./node_modules/body-parser/lib/types/raw.js 15:11-29` `@ ./node_modules/body-parser/index.js 144:15-41` `@ ./node_modules/express/lib/express.js 15:17-39` `@ ./node_modules/express/index.js 11:0-41` `@ ./src/functions/functions.js 49:14-32` `3 warnings have detailed information that is not shown.` `Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.` `ERROR in ./src/functions/functions.js 56:13-30` `Module not found: Error: Can't resolve 'crypto' in 'C:\Users\EricLevy\OneDrive - Meridian Business Services\mb_ns_connector_test\mb_ns_connector_test\src\functions'` </code></pre>
[ { "answer_id": 74630180, "author": "I_Hate_ReLU", "author_id": 18345621, "author_profile": "https://Stackoverflow.com/users/18345621", "pm_score": -1, "selected": false, "text": "lst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 1, 2, 3], [['Z', 'C'], 1, 2, 3]]\n\nfor item in lst:\n item[0] = item[0][0];\n\nprint(lst)\n" }, { "answer_id": 74630277, "author": "Edo Akse", "author_id": 9267296, "author_profile": "https://Stackoverflow.com/users/9267296", "pm_score": 2, "selected": false, "text": "lst from pprint import pprint\n\n\nlst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 4, 5, 6], [['Z', 'C'], 7, 8, 9]]\n\nnew_lst = []\nfor elem in lst:\n fst, *rest = elem\n new_lst.extend([[i, *rest] for i in fst])\n\npprint(new_lst, indent=4)\n [ ['X', 1, 2, 3],\n ['A', 1, 2, 3],\n ['Y', 4, 5, 6],\n ['B', 4, 5, 6],\n ['Z', 7, 8, 9],\n ['C', 7, 8, 9]]\n" }, { "answer_id": 74630359, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 3, "selected": true, "text": "new_lst = [[c, *rest] for letters, *rest in lst for c in letters]\n" }, { "answer_id": 74630366, "author": "tobias_k", "author_id": 1639625, "author_profile": "https://Stackoverflow.com/users/1639625", "pm_score": 2, "selected": false, "text": ">>> lst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 1, 2, 3], [['Z', 'C'], 1, 2, 3]]\n>>> [[i, *rest] for (fst, *rest) in lst for i in fst]\n[['X', 1, 2, 3], ['A', 1, 2, 3], ['Y', 1, 2, 3], ['B', 1, 2, 3], ['Z', 1, 2, 3], ['C', 1, 2, 3]]\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8906455/" ]
74,630,148
<p>I'm trying to merge columns values from tuples with an index:</p> <p>source tuples with a lot of timestamps (1440 ~):</p> <pre><code>tuples = [('2022-10-15 01:16:00', '5', '', '', 'hdd1', '1234'), ('2022-10-15 01:16:00', '', '4', '', 'hdd1', '1234'), ('2022-10-15 01:17:00', '10', '', '', 'hdd1', '1234'), ('2022-10-15 01:17:00', '', '25', '', 'hdd1', '1234'), ('2022-10-15 01:18:00', '1', '', '', 'hdd1', '1234'), ('2022-10-15 01:18:00', '', '2', '', 'hdd1', '1234'), ...] </code></pre> <p>the index is the first element.</p> <p>desired tuples output:</p> <pre><code>[('2022-10-15 01:16:00', '5', '4', '', 'hdd1', '1234'), ('2022-10-15 01:17:00', '10', '25', '', 'hdd1', '1234'), ('2022-10-15 01:18:00', '1', '2', '', 'hdd1', '1234')] </code></pre> <p>my code:</p> <pre><code>tuples = [('2022-10-15 01:16:00', '5', '', '', 'hdd1', '1234'), ('2022-10-15 01:16:00', '', '4', '', 'hdd1', '1234'),('2022-10-15 01:17:00', '10', '', '', 'hdd1', '1234'), ('2022-10-15 01:17:00', '', '25', '', 'hdd1', '1234'), ('2022-10-15 01:18:00', '1', '', '', 'hdd1', '1234'), ('2022-10-15 01:18:00', '', '2', '', 'hdd1', '1234')] result = [] key = lambda t: t[0] for letter,items in itertools.groupby(sorted(tuples,key=key),key): items = list(items) if len(items) == 1: result.append(items[0]+(0,0)) else: result.append(items[0]+items[1][1:]) print(result) </code></pre> <p>many thanks for any help</p>
[ { "answer_id": 74630371, "author": "Johnny Mopp", "author_id": 669576, "author_profile": "https://Stackoverflow.com/users/669576", "pm_score": 2, "selected": true, "text": "from itertools import groupby\nresult = []\nkey = lambda t: t[0]\nfor _,items in groupby(sorted(tuples, key=key), key):\n item = None\n for i, it in enumerate(items):\n # First item in group. Need to convert to list to edit.\n if not item: item = list(it)\n # Not first. Update item at correct index.\n else: item[1 + i] = it[1 + i]\n # Convert back to tuple and save.\n result.append(tuple(item))\n\nfor item in result: print(item)\n ('2022-10-15 01:16:00', '5', '4', '', 'hdd1', '1234')\n('2022-10-15 01:17:00', '10', '25', '', 'hdd1', '1234')\n('2022-10-15 01:18:00', '1', '2', '', 'hdd1', '1234')\n" }, { "answer_id": 74630475, "author": "alec_djinn", "author_id": 3190076, "author_profile": "https://Stackoverflow.com/users/3190076", "pm_score": 0, "selected": false, "text": "#empty dict with date as key and a list placeholder as value\nr = {t[0]:[\"\", \"\", \"\", \"\", \"\"] for t in tuples} \n\n\n#iterate over the tuples and populate the dict\nfor (date, *other_fields) in tuples:\n for i, value in enumerate(other_fields):\n if value: #skip if it's empty\n r[date][i] = value\n\n\n#convert the dictionary in a list of tuples\nr = [tuple([k, *v]) for k,v in r.items()]\nprint(r)\n\n#[('2022-10-15 01:16:00', '5', '4', '', 'hdd1', '1234'), ('2022-10-15 01:17:00', '10', '25', '', 'hdd1', '1234'), ('2022-10-15 01:18:00', '1', '2', '', 'hdd1', '1234')]\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2804204/" ]
74,630,175
<p>I am trying to redirect to an error page if a product ID is not found in a React project. I then find myself faced with a blank page and this error:</p> <p><a href="https://i.stack.imgur.com/ai02V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ai02V.png" alt="enter image description here" /></a></p> <p>I created a Hook with UseEffect to retrieve data from an API</p> <p>And here is the code for the page that should either return the products or the error page:</p> <pre><code>import React from &quot;react&quot;; import { useParams } from &quot;react-router-dom&quot;; import Rating from &quot;../../Components/Rating&quot;; import Slider from &quot;../../Components/Slider&quot;; import Tags from &quot;../../Components/Tags&quot;; import Host from &quot;../../Components/Host&quot;; import Error from &quot;../Error&quot;; import Accordion from &quot;../../Components/Accordion&quot;; import &quot;./logement.css&quot;; import { useFetch } from &quot;../../utils/hooks&quot;; function Logement() { const { logementId } = useParams(); const { data: logement, isLoading, error, } = useFetch(`http://localhost:8000/logements/${logementId}`); if (isLoading) return &lt;h1&gt;LOADING...&lt;/h1&gt;; if (error) { return &lt;Error /&gt;; } return ( &lt;div className=&quot;logements__page&quot;&gt; &lt;div className=&quot;logements__wrapper&quot;&gt; &lt;Slider slides={logement.pictures} /&gt; &lt;div className=&quot;content&quot;&gt; &lt;div className=&quot;informations&quot;&gt; &lt;h1&gt;{logement.title}&lt;/h1&gt; &lt;p className=&quot;logement__location&quot;&gt;{logement.location}&lt;/p&gt; &lt;div className=&quot;tags__wrapper&quot;&gt; {logement.tags.map((tag, index) =&gt; ( &lt;Tags key={index} getTag={tag} /&gt; ))} &lt;/div&gt; &lt;/div&gt; &lt;div className=&quot;rating__host&quot;&gt; &lt;Rating rating={logement.rating} /&gt; &lt;Host host={logement.host} /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className=&quot;collapsible&quot;&gt; &lt;Accordion title=&quot;Description&quot; content={logement.description} /&gt; &lt;Accordion title=&quot;Equipement&quot; content={logement.equipments} /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ); } export default Logement; </code></pre> <p>Thank you for your answers</p>
[ { "answer_id": 74630371, "author": "Johnny Mopp", "author_id": 669576, "author_profile": "https://Stackoverflow.com/users/669576", "pm_score": 2, "selected": true, "text": "from itertools import groupby\nresult = []\nkey = lambda t: t[0]\nfor _,items in groupby(sorted(tuples, key=key), key):\n item = None\n for i, it in enumerate(items):\n # First item in group. Need to convert to list to edit.\n if not item: item = list(it)\n # Not first. Update item at correct index.\n else: item[1 + i] = it[1 + i]\n # Convert back to tuple and save.\n result.append(tuple(item))\n\nfor item in result: print(item)\n ('2022-10-15 01:16:00', '5', '4', '', 'hdd1', '1234')\n('2022-10-15 01:17:00', '10', '25', '', 'hdd1', '1234')\n('2022-10-15 01:18:00', '1', '2', '', 'hdd1', '1234')\n" }, { "answer_id": 74630475, "author": "alec_djinn", "author_id": 3190076, "author_profile": "https://Stackoverflow.com/users/3190076", "pm_score": 0, "selected": false, "text": "#empty dict with date as key and a list placeholder as value\nr = {t[0]:[\"\", \"\", \"\", \"\", \"\"] for t in tuples} \n\n\n#iterate over the tuples and populate the dict\nfor (date, *other_fields) in tuples:\n for i, value in enumerate(other_fields):\n if value: #skip if it's empty\n r[date][i] = value\n\n\n#convert the dictionary in a list of tuples\nr = [tuple([k, *v]) for k,v in r.items()]\nprint(r)\n\n#[('2022-10-15 01:16:00', '5', '4', '', 'hdd1', '1234'), ('2022-10-15 01:17:00', '10', '25', '', 'hdd1', '1234'), ('2022-10-15 01:18:00', '1', '2', '', 'hdd1', '1234')]\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18619674/" ]
74,630,191
<p>What is the best way to achieve this behavior along with React + TypeScript?</p> <pre class="lang-js prettyprint-override"><code>import { Button, Card } from 'src/components'; const Page = () =&gt; ( &lt;div&gt; &lt;Card mx3 p3 flex justifyContentEnd&gt; /* Card content */ &lt;/Card&gt; &lt;Button my2 mx3&gt; Login &lt;/Button&gt; &lt;/div&gt; ); </code></pre> <p>For instance, <code>mx3</code> will add 16px margin horizontally, <code>my2</code> will add 8px margin vertically, etc., similar to how the Bootstrap framework uses classes to apply utility styles easily.</p> <p>I have looked through a few component libraries with this sort of behavior in order to find a suitable solution; however, I find most do not have strong typing support. Examples are RNUILib, NativeBase, Magnus UI, etc.</p>
[ { "answer_id": 74630371, "author": "Johnny Mopp", "author_id": 669576, "author_profile": "https://Stackoverflow.com/users/669576", "pm_score": 2, "selected": true, "text": "from itertools import groupby\nresult = []\nkey = lambda t: t[0]\nfor _,items in groupby(sorted(tuples, key=key), key):\n item = None\n for i, it in enumerate(items):\n # First item in group. Need to convert to list to edit.\n if not item: item = list(it)\n # Not first. Update item at correct index.\n else: item[1 + i] = it[1 + i]\n # Convert back to tuple and save.\n result.append(tuple(item))\n\nfor item in result: print(item)\n ('2022-10-15 01:16:00', '5', '4', '', 'hdd1', '1234')\n('2022-10-15 01:17:00', '10', '25', '', 'hdd1', '1234')\n('2022-10-15 01:18:00', '1', '2', '', 'hdd1', '1234')\n" }, { "answer_id": 74630475, "author": "alec_djinn", "author_id": 3190076, "author_profile": "https://Stackoverflow.com/users/3190076", "pm_score": 0, "selected": false, "text": "#empty dict with date as key and a list placeholder as value\nr = {t[0]:[\"\", \"\", \"\", \"\", \"\"] for t in tuples} \n\n\n#iterate over the tuples and populate the dict\nfor (date, *other_fields) in tuples:\n for i, value in enumerate(other_fields):\n if value: #skip if it's empty\n r[date][i] = value\n\n\n#convert the dictionary in a list of tuples\nr = [tuple([k, *v]) for k,v in r.items()]\nprint(r)\n\n#[('2022-10-15 01:16:00', '5', '4', '', 'hdd1', '1234'), ('2022-10-15 01:17:00', '10', '25', '', 'hdd1', '1234'), ('2022-10-15 01:18:00', '1', '2', '', 'hdd1', '1234')]\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646575/" ]
74,630,194
<p>Where exactly are the (product) image files stored? I can't find the images in my Shopware 6 installation folders. If it is in the database, explain how it is done and which table because I have looked at the <code>media</code> table and can't seem to decode where the image file is.</p>
[ { "answer_id": 74630371, "author": "Johnny Mopp", "author_id": 669576, "author_profile": "https://Stackoverflow.com/users/669576", "pm_score": 2, "selected": true, "text": "from itertools import groupby\nresult = []\nkey = lambda t: t[0]\nfor _,items in groupby(sorted(tuples, key=key), key):\n item = None\n for i, it in enumerate(items):\n # First item in group. Need to convert to list to edit.\n if not item: item = list(it)\n # Not first. Update item at correct index.\n else: item[1 + i] = it[1 + i]\n # Convert back to tuple and save.\n result.append(tuple(item))\n\nfor item in result: print(item)\n ('2022-10-15 01:16:00', '5', '4', '', 'hdd1', '1234')\n('2022-10-15 01:17:00', '10', '25', '', 'hdd1', '1234')\n('2022-10-15 01:18:00', '1', '2', '', 'hdd1', '1234')\n" }, { "answer_id": 74630475, "author": "alec_djinn", "author_id": 3190076, "author_profile": "https://Stackoverflow.com/users/3190076", "pm_score": 0, "selected": false, "text": "#empty dict with date as key and a list placeholder as value\nr = {t[0]:[\"\", \"\", \"\", \"\", \"\"] for t in tuples} \n\n\n#iterate over the tuples and populate the dict\nfor (date, *other_fields) in tuples:\n for i, value in enumerate(other_fields):\n if value: #skip if it's empty\n r[date][i] = value\n\n\n#convert the dictionary in a list of tuples\nr = [tuple([k, *v]) for k,v in r.items()]\nprint(r)\n\n#[('2022-10-15 01:16:00', '5', '4', '', 'hdd1', '1234'), ('2022-10-15 01:17:00', '10', '25', '', 'hdd1', '1234'), ('2022-10-15 01:18:00', '1', '2', '', 'hdd1', '1234')]\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20221985/" ]
74,630,214
<p>I have a list that looks like this</p> <pre><code>#Make dataframes df1 = data.frame(x = c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;), y = 1:3, stringsAsFactors = F) df2 = df1 %&gt;% mutate(y = y*2) df3 = df1 %&gt;% mutate(y = y*3) #Make a name for each dataframe myvar = &quot;fname&quot; #Combine name and dataframe into a list mylist = list(myvar, df1) #Add the other dataframes and name to the list (done in a loop for my bigger dataset list2 = list(myvar, df2) mylist = rbind(mylist, list2) list3 = list(myvar, df3) mylist = rbind(mylist, list3) </code></pre> <p>I want to pull a subset of the list with all the data associated with &quot;c&quot;</p> <pre><code> x y 3 c 3 x y 3 c 6 x y 3 c 9 </code></pre> <p>This is what I tried but it doesn't work</p> <pre><code>#Find all instances of &quot;c&quot; picksite = &quot;c&quot; site_indices = which(mylist[,2] == picksite) mylist[site_indices,] </code></pre> <p>Any suggestions on how to do this, or even a link to better understand lists? Thanks so much.</p>
[ { "answer_id": 74630331, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 3, "selected": true, "text": "lapply lapply(mylist[,2], FUN = function(i) i[which(i$x == \"c\"),])\n $mylist\n x y\n3 c 3\n\n$list2\n x y\n3 c 6\n\n$list3\n x y\n3 c 9\n" }, { "answer_id": 74631032, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "tidyverse list map if_any filter library(dplyr)\nlibrary(purrr)\nmap(mylist[,2], ~ .x %>%\n filter(if_any(everything(), ~ .x == \"c\")))\n $mylist\n x y\n1 c 3\n\n$list2\n x y\n1 c 6\n\n$list3\n x y\n1 c 9\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13942377/" ]
74,630,221
<p>See the following example:</p> <pre class="lang-none prettyprint-override"><code>$ lua Lua 5.4.4 Copyright (C) 1994-2022 Lua.org, PUC-Rio &gt; local a = 123 &gt; print(a) nil </code></pre> <p>This works as expected:</p> <pre class="lang-none prettyprint-override"><code>&gt; local a = 123; print(a) 123 </code></pre> <p>How should I understand the behavior compared to the <a href="https://www.lua.org/manual/5.4/manual.html#3.5" rel="nofollow noreferrer">doc</a>?</p> <blockquote> <p>The scope of a local variable begins at the first statement after its declaration and lasts until the last non-void statement of the innermost block that includes the declaration.</p> </blockquote>
[ { "answer_id": 74630331, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 3, "selected": true, "text": "lapply lapply(mylist[,2], FUN = function(i) i[which(i$x == \"c\"),])\n $mylist\n x y\n3 c 3\n\n$list2\n x y\n3 c 6\n\n$list3\n x y\n3 c 9\n" }, { "answer_id": 74631032, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "tidyverse list map if_any filter library(dplyr)\nlibrary(purrr)\nmap(mylist[,2], ~ .x %>%\n filter(if_any(everything(), ~ .x == \"c\")))\n $mylist\n x y\n1 c 3\n\n$list2\n x y\n1 c 6\n\n$list3\n x y\n1 c 9\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/900078/" ]
74,630,226
<p>I am trying to overwrite the row values for column A and B in df1 with the values from df2. My dfs look as such:</p> <pre><code>df1 'A' 'B' 'C' 23 0 cat orange 24 0 cat orange 25 0 cat orange df2 'A' 'B' 'C' 56 2 dog yellow 64 4 rat orange 85 2 bat red </code></pre> <p>The indices here are different and I would like to overwrite row 25 of df1 with the values of 64 from df2 for only column A and B.</p> <p>I have tried something like this</p> <pre><code>df1[['A','B']].loc[25] = df2[['A','B']].loc[64] </code></pre> <p>This executes but doesn't actually seem to overwrite anything as when I call <code>df1[['A','B']].loc[25]</code> I still get the original values. I would expect the new df1 to look like this:</p> <pre><code>df 'A' 'B' 'C' 23 0 cat orange 24 0 cat orange 25 2 bat orange </code></pre> <p>Can someone explain why this doesn't work for me please?</p>
[ { "answer_id": 74630331, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 3, "selected": true, "text": "lapply lapply(mylist[,2], FUN = function(i) i[which(i$x == \"c\"),])\n $mylist\n x y\n3 c 3\n\n$list2\n x y\n3 c 6\n\n$list3\n x y\n3 c 9\n" }, { "answer_id": 74631032, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "tidyverse list map if_any filter library(dplyr)\nlibrary(purrr)\nmap(mylist[,2], ~ .x %>%\n filter(if_any(everything(), ~ .x == \"c\")))\n $mylist\n x y\n1 c 3\n\n$list2\n x y\n1 c 6\n\n$list3\n x y\n1 c 9\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10574250/" ]
74,630,263
<p>I'm looking to grab the <code>displayValue</code> from <code>objectAttributeValues</code> where the <code>objectTypeAttributeId = 14</code></p> <p>there are multiple arrays like this, and the position of <code>objectTypeAttributeId = 14</code> isn't always the same. how do I loop over every array to get that specific displayValue?</p> <p>I've got something that looks through every possible array, but I want to clean it up.</p> <p>sample json:</p> <pre><code>{ &quot;objectEntries&quot;: [{ &quot;attributes&quot;: [{ &quot;id&quot;: &quot;5210&quot;, &quot;objectAttributeValues&quot;: [{ &quot;displayValue&quot;: &quot;10/Nov/22 3:33 PM&quot;, &quot;referencedType&quot;: false, &quot;searchValue&quot;: &quot;2022-11-10T15:33:49.298Z&quot;, &quot;value&quot;: &quot;2022-11-10T15:33:49.298Z&quot; }], &quot;objectId&quot;: &quot;1201&quot;, &quot;objectTypeAttributeId&quot;: &quot;12&quot; }, { &quot;id&quot;: &quot;5213&quot;, &quot;objectAttributeValues&quot;: [{ &quot;displayValue&quot;: &quot;02f9ed75-b416-49d0-8515-0601581158e5&quot;, &quot;referencedType&quot;: false, &quot;searchValue&quot;: &quot;02f9ed75-b416-49d0-8515-0601581158e5&quot;, &quot;value&quot;: &quot;02f9ed75-b416-49d0-8515-0601581158e5&quot; }], &quot;objectId&quot;: &quot;1201&quot;, &quot;objectTypeAttributeId&quot;: &quot;14&quot; }, { &quot;id&quot;: &quot;5212&quot;, &quot;objectAttributeValues&quot;: [{ &quot;displayValue&quot;: &quot;&quot;, &quot;referencedType&quot;: false, &quot;searchValue&quot;: &quot;&quot;, &quot;value&quot;: &quot;&quot; }], &quot;objectId&quot;: &quot;1201&quot;, &quot;objectTypeAttributeId&quot;: &quot;11&quot; } ] }, { &quot;attributes&quot;: [{ &quot;id&quot;: &quot;4263&quot;, &quot;objectAttributeValues&quot;: [{ &quot;displayValue&quot;: &quot;427904c5-e2c8-4735-bc38-4013928cd043&quot;, &quot;referencedType&quot;: false, &quot;searchValue&quot;: &quot;427904c5-e2c8-4735-bc38-4013928cd043&quot;, &quot;value&quot;: &quot;427904c5-e2c8-4735-bc38-4013928cd043&quot; }], &quot;objectId&quot;: &quot;1011&quot;, &quot;objectTypeAttributeId&quot;: &quot;14&quot; }, { &quot;id&quot;: &quot;4262&quot;, &quot;objectAttributeValues&quot;: [{ &quot;displayValue&quot;: &quot;&quot;, &quot;referencedType&quot;: false, &quot;searchValue&quot;: &quot;&quot;, &quot;value&quot;: &quot;&quot; }], &quot;objectId&quot;: &quot;1011&quot;, &quot;objectTypeAttributeId&quot;: &quot;11&quot; } ] } ] } </code></pre> <p>for this sample query, the values would be:</p> <ul> <li>02f9ed75-b416-49d0-8515-0601581158e5</li> <li>427904c5-e2c8-4735-bc38-4013928cd043</li> </ul> <p>this is my code so far, and would like to make it for efficient:</p> <pre><code>from jira import JIRA import requests import json base_url = &quot;url&quot; auth = basic_auth=('user', 'pass') headers = { &quot;Accept&quot;: &quot;application/json&quot; } pages = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for page in pages: response = requests.request(&quot;GET&quot;,base_url + '?page=' + str(page),headers=headers,auth=auth) all_output = json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(&quot;,&quot;, &quot;: &quot;)) output_dict = json.loads(response.text) output_list = output_dict[&quot;objectEntries&quot;] for outputs in output_list: print(outputs[&quot;attributes&quot;][0][&quot;objectId&quot;]) print(outputs[&quot;name&quot;]) print(outputs[&quot;objectKey&quot;]) if len(outputs[&quot;attributes&quot;][0][&quot;objectAttributeValues&quot;][0][&quot;displayValue&quot;])==36: print(outputs[&quot;attributes&quot;][0][&quot;objectAttributeValues&quot;][0][&quot;displayValue&quot;]) if len(outputs[&quot;attributes&quot;][1][&quot;objectAttributeValues&quot;][0][&quot;displayValue&quot;])==36: print(outputs[&quot;attributes&quot;][1][&quot;objectAttributeValues&quot;][0][&quot;displayValue&quot;]) if len(outputs[&quot;attributes&quot;][2][&quot;objectAttributeValues&quot;][0][&quot;displayValue&quot;])==36: print(outputs[&quot;attributes&quot;][2][&quot;objectAttributeValues&quot;][0][&quot;displayValue&quot;]) if len(outputs[&quot;attributes&quot;][3][&quot;objectAttributeValues&quot;][0][&quot;displayValue&quot;])==36: print(outputs[&quot;attributes&quot;][3][&quot;objectAttributeValues&quot;][0][&quot;displayValue&quot;]) if len(outputs[&quot;attributes&quot;][4][&quot;objectAttributeValues&quot;][0][&quot;displayValue&quot;])==36: print(outputs[&quot;attributes&quot;][4][&quot;objectAttributeValues&quot;][0][&quot;displayValue&quot;]) print('\n') </code></pre> <p>Any suggestions would be appreciated!!</p>
[ { "answer_id": 74630348, "author": "Jib", "author_id": 20124358, "author_profile": "https://Stackoverflow.com/users/20124358", "pm_score": 0, "selected": false, "text": "# lets browse top level entries of your array\nfor e1 in outputs[\"objectEntries\"]:\n # for each of those entries, browse the entries in the attribute section\n for e2 in e1[\"attributes\"]:\n # does the entry match the rule \"14\"? If not, go to the next one\n if (e2[\"objectTypeAttributeId\"] != 14):\n continue\n # print the current entry's associated value\n for attr in e2[\"objectAttributeValues\"]\n print(attr[\"displayValue\"])\n" }, { "answer_id": 74630455, "author": "Usman Arshad", "author_id": 20582506, "author_profile": "https://Stackoverflow.com/users/20582506", "pm_score": 2, "selected": true, "text": "displayValue search_values display_values = []\nfor object_entries in output_dict.get(\"objectEntries\", []):\n for attribute in object_entries.get(\"attributes\"):\n if attribute.get(\"objectTypeAttributeId\") == \"14\":\n for object_attr in attribute.get(\"objectAttributeValues\", []):\n if object_attr.get(\"displayValue\") not in display_values:\n display_values.append(object_attr.get(\"displayValue\"))\n\n\nprint(display_values)\n" }, { "answer_id": 74630626, "author": "docksdocks", "author_id": 20645767, "author_profile": "https://Stackoverflow.com/users/20645767", "pm_score": 0, "selected": false, "text": "def get_display_value(my_dict, value):\n results = []\n for objectEntries in my_dict['objectEntries']:\n for attributes in objectEntries['attributes']:\n if int(attributes['objectTypeAttributeId']) == value:\n results.append(attributes['objectAttributeValues'][0]['displayValue'])\n return results\n results = get_display_value(my_dict, 14)\nprint(results)\n ['02f9ed75-b416-49d0-8515-0601581158e5', '427904c5-e2c8-4735-bc38-4013928cd043']\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13315358/" ]
74,630,268
<p>I have attempted to write a macro that scans through a folder to pick relevant PDFs belonging to a person (such as AAA) and attach them to an email to be sent to AAA, then move on to pick up PDFs belonging to BBB and attach them to an email to be sent to BBB so on and so forth. My folder containing the PDFs looks like this:</p> <ul> <li>AAA_111111.pdf</li> <li>AAA_222222.pdf</li> <li>AAA_333333.pdf</li> <li>BBB_111111.pdf</li> <li>BBB_222222.pdf</li> <li>BBB_333333.pdf</li> <li>CCC_777777.pdf</li> <li>CCC_888888.pdf</li> <li>CCC_999999.pdf</li> <li>CCC_444444.pdf</li> </ul> <p>The person is identified by the letters before the underscore (initials) and there is a list on another Excel tab that the initials are looked up against to return their email address.</p> <p>I have written the code below and it works fairly well except it has an irritating flaw that I cannot solve. It will successfully generate the email for person AAA and attach all three files listed above for them. On the next pass of the main (outer) &quot;do while&quot; loop it comes to person BBB but the inner &quot;do while mfe=&quot; loop attaches the second and third file listed for them (BBB_222222.pdf &amp; BBB_333333.pdf) and completely ignores BBB_111111.pdf (doesn't attach it) though it seems to be able to see it on. Ditto for the third loop, the &quot;do while mfe=&quot; loop will attach the latter three files for CCC to an email but won't attach CCC_777777.pdf?!</p> <pre><code>Sub emailreports() Dim OutApp As Object Dim OutMail As Object Dim OMail As Object, signature, mfe, sto As String Dim emaillastrow, x, a As Long Dim fso As Scripting.FileSystemObject Set fso = New FileSystemObject Dim folder, strfile As String Dim rundate As Date Application.ScreenUpdating = False Application.Calculation = xlManual Application.AutoRecover.Enabled = False folder = Worksheets(&quot;START&quot;).Range(&quot;A14&quot;) strfile = Dir(folder) rundate = Worksheets(&quot;TEMPLATE&quot;).Range(&quot;E7&quot;) b = Worksheets(&quot;START&quot;).Range(&quot;H25&quot;) Sheets(&quot;EMAIL&quot;).Select emaillastrow = Worksheets(&quot;EMAIL&quot;).Range(&quot;A1000000&quot;).End(xlUp).Row If Dir(folder, vbDirectory) = &quot;&quot; Then MsgBox &quot;PDF destination file path doesn't exist.&quot;, vbcritial, &quot;Path error&quot; Exit Sub End If Do While Len(strfile) &gt; 0 Filename = fso.GetBaseName(folder &amp; strfile) mfe = Left(Filename, InStr(Filename, &quot;_&quot;) - 1) For x = 2 To emaillastrow If mfe = Worksheets(&quot;EMAIL&quot;).Range(&quot;A&quot; &amp; x) Then sto = sto &amp; &quot;;&quot; &amp; Worksheets(&quot;EMAIL&quot;).Range(&quot;B&quot; &amp; x) End If Next Set OutApp = CreateObject(&quot;Outlook.Application&quot;) Set OutMail = OutApp.CreateItem(0) On Error Resume Next With OutMail .Display End With With OutMail .To = LCase(sto) .CC = &quot;&quot; .BCC = &quot;&quot; .Subject = &quot;Test subject text&quot; Do While mfe = Left(Filename, InStr(Filename, &quot;_&quot;) - 1) .Attachments.Add (folder &amp; Filename) Filename = Dir If Filename = &quot;&quot; Then Exit Do End If Loop .signature.Delete .HTMLBody = &quot;&lt;font face=&quot;&quot;arial&quot;&quot; style=&quot;&quot;font-size:10pt;&quot;&quot;&gt;&quot; &amp; &quot;Test email body text&quot; &amp; .HTMLBody .Display End With On Error GoTo 0 With Application .EnableEvents = True .ScreenUpdating = True End With Set OutMail = Nothing Set OutApp = Nothing Set OutAccount = Nothing Skip: sto = &quot;&quot; strfile = Filename Loop Application.StatusBar = False Application.ScreenUpdating = True Application.Calculation = xlAutomatic Application.AutoRecover.Enabled = True End Sub </code></pre> <p>I thought about trying to make it somehow at the end of generating the email to take a step back but being a Do loop this is not possible. My code seems to ignore the PDF that it stopped at as part of the previous email generation and when generating the next email starts from that PDF file but only picks up and attaches subsequent PDFs. Any help would be gratefully received as I've tried all sort of things but can't make it work. This is my first post to Stackoverflow so apologies if my question and/or format is not correct or appropriate.</p>
[ { "answer_id": 74637200, "author": "artnib", "author_id": 14907151, "author_profile": "https://Stackoverflow.com/users/14907151", "pm_score": 0, "selected": false, "text": "On Error Resume Next ...\nfolder = Worksheets(\"START\").Range(\"A14\")\nIf Dir(folder, vbDirectory) = \"\" Then\n MsgBox \"PDF destination file path doesn't exist.\", vbcritial, \"Path error\"\n Exit Sub\nEnd If\nstrfile = Dir(fso.BuildPath(folder, \"*_*.pdf\")\nrundate = Worksheets(\"TEMPLATE\").Range(\"E7\")\nb = Worksheets(\"START\").Range(\"H25\")\n'Sheets(\"EMAIL\").Select 'no need to select a sheet\nemaillastrow = Worksheets(\"EMAIL\").Range(\"A1000000\").End(xlUp).Row\n" }, { "answer_id": 74644735, "author": "CDP1802", "author_id": 12704593, "author_profile": "https://Stackoverflow.com/users/12704593", "pm_score": 1, "selected": false, "text": "Option Explicit\n\nSub emailreports()\n \n Dim dict As Scripting.Dictionary, key\n Set dict = New Scripting.Dictionary\n \n Dim folder As String, strfile As String, mfe As String\n Dim sTo As String, arPDF, arAddr, f\n Dim ws As Worksheet, r As Long, emaillastrow As Long\n \n folder = Worksheets(\"START\").Range(\"A14\")\n strfile = Dir(folder & \"*.pdf\")\n If strfile = \"\" Then\n MsgBox \"PDF destination file path doesn't exist.\", vbCritical, \"Path error \" & folder\n Exit Sub\n Else\n ' group files by prefix\n Do While strfile <> \"\"\n mfe = Left(strfile, InStr(strfile, \"_\") - 1)\n If dict.Exists(mfe) Then\n dict(mfe) = dict(mfe) & vbTab & strfile\n Else\n dict.Add mfe, strfile\n End If\n strfile = Dir ' get next pdf\n Loop\n End If\n \n Set ws = Worksheets(\"EMAIL\")\n emaillastrow = ws.Cells(Rows.Count, \"A\").End(xlUp).Row\n \n ' read email address lookup into array\n arAddr = ws.Range(\"A2:B\" & emaillastrow)\n \n ' prepare one email per key\n Dim OutApp As Object, OutMail As Object, OMail As Object\n 'Set OutApp = CreateObject(\"Outlook.Application\")\n For Each key In dict.Keys\n \n ' build array of file names for one key\n mfe = Trim(key)\n arPDF = Split(dict(mfe), vbTab)\n \n ' get email addresses\n sTo = \"\"\n For r = 1 To UBound(arAddr)\n If mfe = arAddr(r, 1) Then\n sTo = sTo & arAddr(r, 2) & \";\"\n End If\n Next\n Debug.Print key, sTo\n \n 'Set OutMail = OutApp.CreateItem(0)\n 'With OutMail\n \n '.To = LCase(sTo)\n '.cc = \"\"\n '.BCC = \"\"\n '.Subject = \"Test subject text\"\n ' attach pdfs\n For Each f In arPDF\n '.Attachments.Add folder & f\n Debug.Print , folder & f\n Next\n '.signature.Delete\n '.HTMLBody = \"<font face=\"\"arial\"\" style=\"\"font-size:10pt;\"\">\" & \"Test email body text\" & .HTMLBody\n '.Display\n \n 'End With\n Next\n \n 'OutApp.quit\nEnd Sub\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20645863/" ]
74,630,271
<p>My question is highly related to the following thread: <a href="https://stackoverflow.com/questions/35157307/concatenate-values-across-two-rows-in-r">concatenate values across two rows in R</a></p> <p>The main difference is that I would like concatenate only those rows, which are of the same ID. So I need to include a grouping of some kind, but I wasn't able to do it.</p> <pre><code># desired input input &lt;- data.frame(ID = c(1,1,1,3,3,3), X1 = c(&quot;A&quot;, 1, 11, &quot;D&quot;, 4, 44), X2 = c(&quot;B&quot;, 2, 22, &quot;E&quot;, 5, 55), X3 = c(&quot;C&quot;, 3, 33, &quot;F&quot;, 6, 66)) # desired output output &lt;- data.frame(ID = c(1,3), X1 = c(&quot;A-1-11&quot;, &quot;D-4-44&quot;), X2 = c(&quot;B-2-22&quot;, &quot;E-5-55&quot;), X3 = c(&quot;C-3-33&quot;, &quot;F-6-66&quot;)) </code></pre> <p>I tried the solution from the mentioned thread, but this concatenates all six rows:</p> <pre><code>output_v1 &lt;- data.table::rbindlist(list(input, data.table::setDT(input)[, lapply(.SD, paste, collapse='-')])) </code></pre> <p>Obviously this does not work, since I am not grouping by ID. But in the documentation I do not find a way for grouping. Can anyone point me in the right direction?</p> <p>Thanks a lot!</p> <p>The question above was answered perfectly, however I noticed a second layer of complexity in my data:</p> <pre><code># desired input input2 &lt;- data.frame(ID = c(1,1,1,3,3,3), X1 = c(&quot;A&quot;, 1, 11, &quot;D&quot;, 4, 44), X2 = c(&quot;B&quot;, 2, 22, &quot;E&quot;, 5, 55), X3 = c(&quot;C&quot;, 3, 33, &quot;F&quot;, 6, 66), X4 = c(&quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;H&quot;, 8, 88), X5 = c(&quot;I&quot;, &quot;I&quot;, &quot;I&quot;, &quot;J&quot;, &quot;J&quot;, &quot;J&quot;), X6 = c(&quot;K&quot;, &quot;K&quot;, &quot;0&quot;, &quot;L&quot;, &quot;L&quot;, &quot;L&quot;)) # desired output output2 &lt;- data.frame(ID = c(1,3), X1 = c(&quot;A-1-11&quot;, &quot;D-4-44&quot;), X2 = c(&quot;B-2-22&quot;, &quot;E-5-55&quot;), X3 = c(&quot;C-3-33&quot;, &quot;F-6-66&quot;), X4 = c(&quot;G&quot;, &quot;H-8-88&quot;), X5 = c(&quot;I&quot;, &quot;J&quot;), X6 = c(&quot;K-K-0&quot;, &quot;L&quot;)) </code></pre> <p>Sometimes a column is completly identical within one ID. In this case I do not want to concatenate the same value multiple times, but rather have it once.</p> <p>I tried the following to identify columns with differences within one ID - those columns I'd like to concatenate:</p> <pre><code>changes &lt;- input2 |&gt; group_by(ID) |&gt; mutate(across(everything(), ~n_distinct(.x) &gt; 1)) |&gt; pivot_longer(-ID, names_to = &quot;col&quot;, values_to = &quot;changed&quot;) |&gt; filter(changed) |&gt; select(-changed) |&gt; distinct() </code></pre> <p>Then I can treat the two cases differently:</p> <pre><code>data_concat &lt;- input2 |&gt; as_tibble() |&gt; group_by(ID) |&gt; select(changes$col) |&gt; summarise(across(everything(), list(function(col) str_flatten(col, &quot;, &quot;)))) data_unique &lt;- input2 |&gt; dplyr::select(!all_of(changes$col)) |&gt; dplyr::distinct() data_new &lt;- data_unique |&gt; left_join(data_concat, by = 'ID') </code></pre> <p>However this only works for column X5, where every entry within one ID is duplicated. How I can treat X$ and X6 correctly I wasn't able to figure out yet. Any suggestions?</p> <p>Additional Information: If the value is completely unique within one column and one ID, then it should become only one. If thats not the case it should be concatenated. So: KKKKK -&gt; &quot;K&quot;, KKKK0 -&gt; &quot;K-K-K-K-0&quot;, 5MMM5 -&gt; &quot;5-M-M-M-5&quot;, GGG99 -&gt; &quot;G-G-G-9-9&quot; etc.</p> <p>P.S.: I can create an additional question if it is not considered good style to enlarge the scope of a question. If that's the case, please comment. The first part was perfectly answered already.</p>
[ { "answer_id": 74630316, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 2, "selected": false, "text": "library(dplyr)\ninput %>% \n group_by(ID) %>% \n mutate(across(everything(), ~paste0(.,collapse = \"-\"))) %>% \n slice(1)\n# A tibble: 2 × 4\n# Groups: ID [2]\n ID X1 X2 X3 \n <dbl> <chr> <chr> <chr> \n1 1 A-1-11 B-2-22 C-3-33\n2 3 D-4-44 E-5-55 F-6-66\n" }, { "answer_id": 74630400, "author": "Jan Z", "author_id": 20477576, "author_profile": "https://Stackoverflow.com/users/20477576", "pm_score": 3, "selected": true, "text": "library(tidyverse)\ninput %>% as_tibble() %>% group_by(ID) %>% summarise(across(everything(), list(function(col) str_flatten(col, '-'))))\n # A tibble: 2 × 4\n ID X1_1 X2_1 X3_1 \n <dbl> <chr> <chr> <chr> \n1 1 A-1-11 B-2-22 C-3-33\n2 3 D-4-44 E-5-55 F-6-66\n input2 %>% as_tibble() %>% group_by(ID) %>% \n summarise(across(everything(), ~if_else(length(unique(.))==1, str_flatten(unique(.), '-'), str_flatten(., '-'))))\n # A tibble: 2 × 7\n ID X1 X2 X3 X4 X5 X6 \n <dbl> <chr> <chr> <chr> <chr> <chr> <chr>\n1 1 A-1-11 B-2-22 C-3-33 G I K-K-0\n2 3 D-4-44 E-5-55 F-6-66 H-8-88 J L \n" }, { "answer_id": 74630995, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "data.table library(data.table)\nsetDT(input)[, lapply(.SD, paste, collapse='-'), by = ID]\n ID X1 X2 X3\n1: 1 A-1-11 B-2-22 C-3-33\n2: 3 D-4-44 E-5-55 F-6-66\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15407689/" ]
74,630,290
<p>I have two dataframes as such:</p> <pre><code>DF1&lt;-data.frame(VAR1 = c(1,1,1,1,2,2,2,2,3,3,3,3), VAR2 = c('John','Bob','Hannah'), VAR3 = c(1,1,1,2), VAR4=NA) DF2&lt;-data.frame(VAR1 = c(1,1,1,1,2,2,2,2,3,3,3,3), VAR2 = c('John','Bob','Hannah','Dave'), VAR4 = c('A','B','C')) </code></pre> <p>I want to copy DF2$VAR4 into DF1$VAR4, for each row where the condition (DF1$VAR1==DF2$VAR1)&amp;(DF1$VAR2==DF2$VAR2) is met, hence regardless of the value DF1$VAR3 takes. DF2$VAR4 only has one element for each pair (VAR1, VAR2), while DF1 has not. In fact, DF1$VAR3 counts the number of occurrences of each pair (DF1$VAR1, DF1$VAR2).</p> <p>I tried (from another topic)</p> <pre><code>DF3&lt;-merge(DF1, DF2[,'VAR4'], by= c('VAR1','VAR2')) </code></pre> <p>which <em>should</em> do the trick, but I get: &quot;Error in fix.by(by.y,y): 'by' must specify a uniquely valid column&quot;</p> <p>I checked multiple times but there are no misspells, and both VAR1 and VAR2 exist in both dataframes, with consistent heading. I don't know what I'm missing here.</p> <p>I am VERY new to R syntax, so I solved it with the nested loop:</p> <pre><code>for (i in DF1$VAR1){ for (j in DF1$VAR2[DF1$VAR1==i]){ DF1$VAR4[DF1$VAR1==i &amp; DF1$VAR2==j] &lt;- DF2$VAR4[DF2$VAR1==i &amp; DF2$VAR2==j] } } </code></pre> <p>Which works but is excruciatingly slow. I'm pretty sure the solution is trivial, but I just can't work it out. Thanks a lot for your time</p>
[ { "answer_id": 74630415, "author": "harre", "author_id": 4786466, "author_profile": "https://Stackoverflow.com/users/4786466", "pm_score": 2, "selected": false, "text": "rows_update dplyr library(dplyr)\n\nDF1 |>\n rows_update(DF2, by = c(\"VAR1\", \"VAR2\"), unmatched = \"ignore\")\n VAR1 VAR2 VAR3 VAR4\n1 1 John 1 A\n2 1 Bob 1 B\n3 1 Hannah 1 C\n4 1 John 2 A\n5 2 Bob 1 C\n6 2 Hannah 1 A\n7 2 John 1 B\n8 2 Bob 2 C\n9 3 Hannah 1 B\n10 3 John 1 C\n11 3 Bob 1 A\n12 3 Hannah 2 B\n" }, { "answer_id": 74630595, "author": "islem", "author_id": 11952767, "author_profile": "https://Stackoverflow.com/users/11952767", "pm_score": 1, "selected": false, "text": "library(dplyr) \n\nDF1<-data.frame(VAR1 = c(1,1,1,1,2,2,2,2,3,3,3,3),\n VAR2 = c('John','Bob','Hannah'), VAR3 = c(1,1,1,2),\n VAR4=NA)\n\nDF2<-data.frame(VAR1 = c(1,1,1,1,2,2,2,2,3,3,3,3), \n VAR2 = c('John','Bob','Hannah','Dave'),\n VAR4 = c('A','B','C'))\n\nDF3<-left_join(DF1, DF2, by= c('VAR1','VAR2'))%>%\n mutate(VAR4=VAR4.y)%>%\n select(-c(VAR4.x,VAR4.y))\nDF3\n# > DF3\n# VAR1 VAR2 VAR3 VAR4\n# 1 1 John 1 A\n# 2 1 Bob 1 B\n# 3 1 Hannah 1 C\n# 4 1 John 2 A\n# 5 2 Bob 1 C\n# 6 2 Hannah 1 A\n# 7 2 John 1 B\n# 8 2 Bob 2 C\n# 9 3 Hannah 1 B\n# 10 3 John 1 C\n# 11 3 Bob 1 A\n# 12 3 Hannah 2 B\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646660/" ]
74,630,330
<p>I'm trying to have a ggplot with two vertical lines on it, with a separate custom legend to explain what the lines represent. This is my code (using iris):</p> <pre><code>irate &lt;- as.data.frame(iris) irate$Species &lt;- as.character(irate$Species) irritating &lt;- ggplot(irate) + geom_line(aes(y = Sepal.Length, x = Sepal.Width), color = &quot;blue&quot;) + geom_point(aes(y = Sepal.Length, x = Sepal.Width, color = Species), size = 5) + theme(legend.position = &quot;right&quot;, axis.text.y = element_blank(), axis.title.y = element_blank(), axis.ticks.y = element_blank(), panel.grid.major.y = element_blank())+ labs(title = &quot;The chart&quot;, x = &quot;Sepal Width&quot;) + geom_vline(color = &quot;black&quot;, linetype = &quot;dashed&quot;, aes(xintercept = 3))+ geom_vline(color = &quot;purple&quot;, linetype = &quot;dashed&quot;, aes(xintercept = 4)) irritating </code></pre> <p><a href="https://i.stack.imgur.com/lKh8P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lKh8P.png" alt="Result" /></a></p> <p>I've tried using things like scale_color_manual (etc), but for some reason when doing so it will interfere with the main legend and not produce a separate one.</p> <p>Using answers to questions like: <a href="https://stackoverflow.com/questions/37660694/add-legend-to-geom-vline">Add legend to geom_vline</a></p> <p>I add: <code>+scale_color_manual(name = &quot;still problematic&quot;, values = c(&quot;black&quot;, &quot;purple&quot;, &quot;red&quot;))</code></p> <p>the addition of &quot;red&quot; in the vector the only way to get it to produce a chart (otherwise there's a: &quot;Insufficient values in manual scale. 3 needed but only 2 provided.&quot; error). <a href="https://i.stack.imgur.com/q5pef.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q5pef.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74631091, "author": "Andy Baxter", "author_id": 10744082, "author_profile": "https://Stackoverflow.com/users/10744082", "pm_score": 2, "selected": false, "text": "linetype aes library(ggplot2)\n\nirate <- as.data.frame(iris)\nirate$Species <- as.character(irate$Species)\n\nirritating <- ggplot(irate) +\n geom_line(aes(y = Sepal.Length, x = Sepal.Width), color = \"white\") +\n geom_point(aes(y = Sepal.Length, x = Sepal.Width, color = Species), size = 5) +\n theme(\n legend.position = \"right\",\n axis.text.y = element_blank(),\n axis.title.y = element_blank(),\n axis.ticks.y = element_blank(),\n panel.grid.major.y = element_blank()\n ) +\n labs(title = \"The chart\", x = \"Sepal Width\") +\n geom_vline(linewidth = 1.5,\n color = \"black\",\n aes(xintercept = 3, linetype = \"Something\")) +\n geom_vline(linewidth = 1.5,\n color = \"purple\",\n aes(xintercept = 4, linetype = \"Another thing\")) +\n scale_linetype_manual(\n \"Things\",\n values = c(\"dashed\", \"dashed\"),\n guide = guide_legend(override.aes = list(colour = c(\"purple\", \"black\")))\n )\n\nirritating\n" }, { "answer_id": 74631113, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": false, "text": "linetype override.aes guide_legend irate <- as.data.frame(iris)\nirate$Species <- as.character(irate$Species)\n\nlibrary(ggplot2)\n#> Warning: package 'ggplot2' was built under R version 4.2.2\n\nbase <- ggplot(irate) +\n geom_line(aes(y = Sepal.Length, x = Sepal.Width), color = \"white\") +\n geom_point(aes(y = Sepal.Length, x = Sepal.Width, color = Species), size = 5) +\n theme(legend.position = \"right\", axis.text.y = element_blank(), axis.title.y = element_blank(), axis.ticks.y = element_blank(), panel.grid.major.y = element_blank())+\n labs(title = \"The chart\", x = \"Sepal Width\") \n\nbase +\n geom_vline(color = \"black\", aes(xintercept = 3, linetype = \"Black Line\"))+\n geom_vline(color = \"purple\", aes(xintercept = 4, linetype = \"Purple line\")) +\n scale_linetype_manual(name = \"still problematic\", values = c(\"dashed\", \"dashed\")) +\n guides(linetype = guide_legend(override.aes = list(color = c(\"black\", \"purple\"))))\n ggnewscale \nlibrary(ggnewscale)\n\nbase +\n new_scale_color() +\n geom_vline(linetype = \"dashed\", aes(xintercept = 3, color = \"Black Line\"))+\n geom_vline(linetype = \"dashed\", aes(xintercept = 4, color = \"Purple line\")) +\n scale_color_manual(name = \"still problematic\", values = c(\"black\", \"purple\"))\n" }, { "answer_id": 74631145, "author": "Rui Barradas", "author_id": 8245406, "author_profile": "https://Stackoverflow.com/users/8245406", "pm_score": 3, "selected": true, "text": "ggnewscale color data geom_vline new_scale_color() library(ggplot2)\nlibrary(ggnewscale)\n\nirate <- iris\nirate$Species <- as.character(irate$Species)\nhappy <- data.frame(xintercept = c(3, 4), color = c(\"black\", \"purple\"))\n\ndelightful <- ggplot(irate) +\n geom_line(aes(y = Sepal.Length, x = Sepal.Width), color = \"blue\") +\n geom_point(aes(y = Sepal.Length, x = Sepal.Width, color = Species), size = 5) +\n theme(legend.position = \"right\", axis.text.y = element_blank(), axis.title.y = element_blank(), axis.ticks.y = element_blank(), panel.grid.major.y = element_blank())+\n labs(title = \"The chart\", x = \"Sepal Width\") +\n new_scale_color() +\n geom_vline(\n data = happy,\n mapping = aes(xintercept = xintercept, color = color),\n linetype = \"dashed\"\n ) +\n scale_color_manual(values = c(black = \"black\", purple = \"purple\"))\n\ndelightful \n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17081051/" ]
74,630,337
<p>I'm only aiming to retrieve rows before negative total values for each nickname and the same date.</p> <p><strong>Table :</strong></p> <p><a href="https://i.stack.imgur.com/YDJsX.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I don't want to retrieve the orderid 8 and the orderid9 because the above rows for the same nickname and the same day contain negative total value. For the same reason, I don't want to retrieve the row with orderid 7. I don't want to retrieve the orderid 5 and the orderid 6 since they contain negative total value. I'm aiming to retrieve the orderid10 although the above rows for the same nickname contain negative value, because the date has changed.</p> <p><strong>Expected result:</strong> <a href="https://i.stack.imgur.com/yNm51.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I've tried to solve using with clauses and subqueries but I've failed.</p>
[ { "answer_id": 74630562, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 1, "selected": false, "text": "DECLARE @table TABLE (RowID INT IDENTITY, Value INT, Name NVARCHAR(10))\nINSERT INTO @table (Value, Name) VALUES\n(1, 'E'),(2, 'D'),(3, 'C'),(4, 'B'),(5, 'A'),\n(1, 'V'),(2, 'W'),(3, 'X'),(4, 'Y'),(5, 'Z'),\n(1, 'M'),(2, 'N'),(3, 'O'),(4, 'P'),(5, 'Q')\n SELECT *, LAG(Name,1) OVER (PARTITION BY Value ORDER BY RowID) AS PreviousName, LEAD(Name,1) OVER (PARTITION BY Value ORDER BY RowID) AS NextName\n FROM @table\n RowID Value Name PreviousName NextName\n------------------------------------------------\n1 1 E NULL V\n6 1 V E M\n11 1 M V NULL\n2 2 D NULL W\n7 2 W D N\n12 2 N W NULL\n3 3 C NULL X\n8 3 X C O\n13 3 O X NULL\n4 4 B NULL Y\n9 4 Y B P\n14 4 P Y NULL\n5 5 A NULL Z\n10 5 Z A Q\n15 5 Q Z NULL\n" }, { "answer_id": 74630612, "author": "Tim Schmelter", "author_id": 284240, "author_profile": "https://Stackoverflow.com/users/284240", "pm_score": 0, "selected": false, "text": "NOT EXISTS SELECT t.*\nFROM TableName t\nWHERE NOT EXISTS\n(\n SELECT 1 FROM TableName t2\n WHERE t1.Nickname = t2.Nickname \n AND CAST(t1.Date as date) = CAST(t2.Date as date)\n AND t2.Total < 0\n)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17648303/" ]
74,630,364
<p>im noob at prog, so i need help.</p> <p>Need to make a string from each word in the array so that each letter copies itself as many times as the serial number in the word it has, and each new character must starts with uppercase;</p> <p>Example:</p> <p>&quot;abcd&quot; -&gt; &quot;A-Bb-Ccc-Dddd&quot;</p> <p>&quot;RqaEzty&quot; -&gt; &quot;R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy&quot;</p> <p>&quot;cwAt&quot; -&gt; &quot;C-Ww-Aaa-Tttt&quot;</p> <p>One of ways I tried to do it:</p> <pre><code>public static String Accum(string s) { string res; for(int i = 0; i &lt; s.Length; i++) { res += s[i].ToUpper() + s[i].ToLower().Repeat(i) + (i &lt; s.Length - 1 ? &quot;-&quot;: &quot;&quot;); } return res; } </code></pre> <ul> <li>some errors, that I understand, but can't understand what to do with them(google didnt help so much):</li> </ul> <p>error CS1501: No overload for method 'ToUpper' takes 0 arguments</p> <p>error CS0165: Use of unassigned local variable 'res'</p>
[ { "answer_id": 74630844, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": true, "text": "string Accum(string s) \n{\n var sb = new StringBuilder(s.Length * s.Length); // a bit too long, but that's Ok\n for(int i=0; i < s.Length; ++i)\n {\n sb.Append(Char.ToUpper(s[i]));\n sb.Append(Char.ToLower(s[i]), i); // i is repeat count. Fortunately, it silently accepts 0 for count\n sb.Append('-');\n }\n \n // Trick to remove last character;\n sb.Length--;\n \n return sb.ToString();\n}\n ToUpper() s[i] s res" }, { "answer_id": 74630885, "author": "Drag and Drop", "author_id": 6560478, "author_profile": "https://Stackoverflow.com/users/6560478", "pm_score": 1, "selected": false, "text": "string f(string s) => CultureInfo.CurrentCulture.TextInfo.ToTitleCase(\n String.Join(\"-\", \n s.Select((x, i) => new string (Char.ToLower(x), i+1))\n )\n );\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646944/" ]
74,630,379
<p>I've been working with JS + JSON, and I can't find a way to make a new object out of a value of some parent object. For example:</p> <pre class="lang-js prettyprint-override"><code>const parent = { &quot;child&quot;: {&quot;value&quot;: 12}, &quot;otherChild&quot;: {&quot;value&quot;: 83} } // I want to create a duplicate without editing the original const newChild = parent.child; newChild.value = 25; // Logs 25 console.log(parent.child.value); </code></pre> <p>I've tried using <code>new Object();</code> and it still doesn't work. :/</p>
[ { "answer_id": 74630426, "author": "mcnk", "author_id": 5069866, "author_profile": "https://Stackoverflow.com/users/5069866", "pm_score": 1, "selected": false, "text": "lodash const _ = require('lodash');\n \nvar obj = {\n x: 23\n};\n \n// Deep copy\nvar deepCopy = _.cloneDeep(obj);\n \nconsole.log('Comparing original with'\n + ' deep ', obj === deepCopy);\n \nobj.x = 10; // Changing original value\n \nconsole.log('After changing original value');\n \nconsole.log(\"Original value \", obj);\n \nconsole.log(\"Deep Copy value \", deepCopy);\n" }, { "answer_id": 74630442, "author": "yeya", "author_id": 3107689, "author_profile": "https://Stackoverflow.com/users/3107689", "pm_score": 2, "selected": false, "text": "const parent = {\n \"child\": {\"value\": 12},\n \"otherChild\": {\"value\": 83}\n}\n\n// I want to create a duplicate without editing the original\nconst newChild = JSON.parse(JSON.stringify(parent.child));\nnewChild.value = 25;\n const newChild = structuredClone(parent)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14924831/" ]
74,630,413
<p>I have been getting the following error.</p> <blockquote> <p>django.db.utils.IntegrityError: NOT NULL constraint failed: doctor_owner.doc_name</p> </blockquote> <p>This error primarily arises on when I save the owner information using .save() and the error it gives is on doc_name, which is not present in the model definition of the class Owner. I am clueless why it is giving such an error.</p> <p>My model is attached below: .</p> <p>This is my model description:</p> <pre><code>from django.db import models # Create your models here. from base.models import BaseModel class Owner(BaseModel): owner_id = models.CharField(max_length=50) owner_name = models.CharField(max_length=250) class Pet(BaseModel): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) pet_name = models.CharField(max_length=100) pet_age = models.DecimalField(max_length=3, decimal_places=2, max_digits=50) pet_specie = models.CharField(max_length=250) pet_gender = models.CharField(max_length=1) class Medicine(BaseModel): medicine_name = models.CharField(max_length=250) frequency = models.CharField(max_length=100) duration = models.CharField(max_length=100) class Prescription(BaseModel): pet = models.ForeignKey(Pet, on_delete=models.CASCADE) medicine = models.ForeignKey(Medicine, on_delete=models.CASCADE) class Treatment(BaseModel): pet = models.ForeignKey(Pet, on_delete=models.CASCADE) owner = models.ForeignKey(Owner, on_delete=models.CASCADE) doc_name = models.CharField(max_length=250) prescription = models.ForeignKey(Prescription, on_delete=models.CASCADE) </code></pre>
[ { "answer_id": 74630426, "author": "mcnk", "author_id": 5069866, "author_profile": "https://Stackoverflow.com/users/5069866", "pm_score": 1, "selected": false, "text": "lodash const _ = require('lodash');\n \nvar obj = {\n x: 23\n};\n \n// Deep copy\nvar deepCopy = _.cloneDeep(obj);\n \nconsole.log('Comparing original with'\n + ' deep ', obj === deepCopy);\n \nobj.x = 10; // Changing original value\n \nconsole.log('After changing original value');\n \nconsole.log(\"Original value \", obj);\n \nconsole.log(\"Deep Copy value \", deepCopy);\n" }, { "answer_id": 74630442, "author": "yeya", "author_id": 3107689, "author_profile": "https://Stackoverflow.com/users/3107689", "pm_score": 2, "selected": false, "text": "const parent = {\n \"child\": {\"value\": 12},\n \"otherChild\": {\"value\": 83}\n}\n\n// I want to create a duplicate without editing the original\nconst newChild = JSON.parse(JSON.stringify(parent.child));\nnewChild.value = 25;\n const newChild = structuredClone(parent)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2015669/" ]
74,630,428
<p>As you can see I am using the type=&quot;range&quot; input slider for this purpose. But I need slider where I will have texts instead of numbers.</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>var slider = document.getElementById("myRange"); var output = document.getElementById("demo"); output.innerHTML = slider.value; slider.oninput = function() { output.innerHTML = this.value; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.slidecontainer { width: 100%; } .slider { -webkit-appearance: none; width: 100%; height: 15px; border-radius: 5px; background: #d3d3d3; outline: none; opacity: 0.7; -webkit-transition: .2s; transition: opacity .2s; } .slider:hover { opacity: 1; } .slider::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 25px; height: 25px; border-radius: 50%; background: #04AA6D; cursor: pointer; } .slider::-moz-range-thumb { width: 25px; height: 25px; border-radius: 50%; background: #04AA6D; cursor: pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="slidecontainer"&gt; &lt;input type="range" min="1" max="3" value="2" class="slider" id="myRange"&gt; &lt;p&gt;Value: &lt;span id="demo"&gt;&lt;/span&gt;&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>So I need three options &quot;None&quot;, &quot;Open&quot; and &quot;Close&quot; and when I slide, automatically if will be moved to the text.</p> <p>Something like this</p> <p>Until now I just got the value that is slided on with</p> <pre><code>slider.oninput = function() { output.innerHTML = this.value; } </code></pre> <p>but I need to insert some text dynamically when 1 is chosen then I need to have Open option for example etc...</p> <p>Note: It needs to be responsive</p> <p>image: <a href="https://i.stack.imgur.com/Xqa8A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xqa8A.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74630426, "author": "mcnk", "author_id": 5069866, "author_profile": "https://Stackoverflow.com/users/5069866", "pm_score": 1, "selected": false, "text": "lodash const _ = require('lodash');\n \nvar obj = {\n x: 23\n};\n \n// Deep copy\nvar deepCopy = _.cloneDeep(obj);\n \nconsole.log('Comparing original with'\n + ' deep ', obj === deepCopy);\n \nobj.x = 10; // Changing original value\n \nconsole.log('After changing original value');\n \nconsole.log(\"Original value \", obj);\n \nconsole.log(\"Deep Copy value \", deepCopy);\n" }, { "answer_id": 74630442, "author": "yeya", "author_id": 3107689, "author_profile": "https://Stackoverflow.com/users/3107689", "pm_score": 2, "selected": false, "text": "const parent = {\n \"child\": {\"value\": 12},\n \"otherChild\": {\"value\": 83}\n}\n\n// I want to create a duplicate without editing the original\nconst newChild = JSON.parse(JSON.stringify(parent.child));\nnewChild.value = 25;\n const newChild = structuredClone(parent)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647302/" ]
74,630,436
<p>I am trying to filter out content from a file but some-why it's not working. My goal is to filter out whatever starts with &quot;build-&quot; and it's age is above 1 day. Sometimes it displays minutes / hours / days, therefore I need to filter 1d, 24h, 1440m and above. ( X &gt;= 1d || X &gt;= 24h || X &gt;= 1440m ).</p> <p>This is my text file:</p> <pre><code>NAME STATUS AGE argocd Active 10d build-start-a Active 1d build-start-b Active 22h build-start-s Active 145m default Active 12d games Active 9d kube-node-lease Active 12d kube-public Active 12d kube-system Active 12d start-build-s Active 96m </code></pre> <p>This is my command:</p> <pre><code>cat test.txt | grep &quot;^build-*&quot; | awk '{ if ($3 &gt;= 1d || $3 &gt;= 24h || $3 &gt;= 1440m) print $1 }' </code></pre> <p>and the result is:</p> <p>build-start-a <br /> build-start-b <br /> build-start-s</p> <p>(instead of just &quot;build-start-a&quot;, as it is the only one that matches the condition I wish.)</p> <p>My guess is, bash compares &quot;22h&quot; + &quot;145m&quot; and &quot;1d&quot; and assumes &quot;22h&quot; + &quot;145m&quot; is greater than &quot;1d&quot; and that is why I see three lines. I tried multiple different if conditions but it didn't work for me. Tried to &quot;hard-code&quot; the values and put &quot;1d&quot; &quot;24h&quot; and it didn't work as well. Tried to implement it using else if but the result was the same.</p> <p>I'd be grateful to understand what I have done wrong and get your help!</p> <p>Thanks :)</p>
[ { "answer_id": 74630570, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 3, "selected": true, "text": "awk awk '\n/^build-/ &&\n( (/d$/ && $3+0 >= 1) ||\n (/h$/ && $3+0 >= 24) ||\n (/m$/ && $3+0 >= 1440) )' file\n\nbuild-start-a Active 1d\n $3 $3+0" }, { "answer_id": 74635576, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 1, "selected": false, "text": "$ cat tst.awk\n{ mult = 1 }\n/h$/ { mult = 60 }\n/d$/ { mult = 24 * 60 }\n/^build-/ && ($3*mult >= 1440)\n $ awk -f tst.awk test.txt\nbuild-start-a Active 1d\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19364640/" ]
74,630,477
<p>I'm trying to create a zoom in button, in my unity scene I saw this video, but the 'zoom cam' isn't working. <a href="https://www.youtube.com/watch?v=ACR-W9QZQwE&amp;t=127s&amp;ab_channel=DesignandDeploy" rel="nofollow noreferrer">https://www.youtube.com/watch?v=ACR-W9QZQwE&amp;t=127s&amp;ab_channel=DesignandDeploy</a> Does anyone know how to do this?</p> <p>Here is my code and 'lupa' is the button i want to click to do the zoom in</p> <p><a href="https://i.stack.imgur.com/My6g5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/My6g5.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/rBczd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rBczd.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/EXmqa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EXmqa.png" alt="enter image description here" /></a> Thank you</p>
[ { "answer_id": 74634405, "author": "Gauluser", "author_id": 20649876, "author_profile": "https://Stackoverflow.com/users/20649876", "pm_score": 0, "selected": false, "text": "zoom cam Main Camera GameObject.Find(\"Main Camera\").GetComponent<Camera>().enabled = false;\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17646296/" ]
74,630,480
<p>I'm having object like this,</p> <pre><code> const rolePermission = { adminView: true, adminCreate: true, adminDelete: true, userView: true, userEdit: true, userDelete: false, }; </code></pre> <p>i expecting like this,</p> <pre><code> const rolePermission = [ { role: &quot;admin&quot;, action: [&quot;View&quot;, &quot;Create&quot;, &quot;Delete&quot;] }, { role: &quot;user&quot;, action: [&quot;View&quot;, &quot;Edit&quot;] }, ]; </code></pre>
[ { "answer_id": 74630693, "author": "Cerbrus", "author_id": 1835379, "author_profile": "https://Stackoverflow.com/users/1835379", "pm_score": 0, "selected": false, "text": "const rolePermission = { adminView: true, adminCreate: true, adminDelete: true, userView: true, userEdit: true, userDelete: false };\n\n// We want all the entries in `rolePermission`\nconst intermediate = Object\n .entries(rolePermission)\n .reduce((result, [key, enabled]) => {\n // Split the entry's key into the role and action, using a positive lookahead.\n const [role, action] = key.split(/(?=[A-Z])/);\n\n // If the action is enabled,\n if (enabled) {\n // Make sure the action array exists,\n result[role] = result[role] || [];\n // And add the current action to it.\n result[role].push(action);\n }\n\n return result;\n }, {});\n\nconsole.log('intermediate:\\n', intermediate);\n\n// Now map those entries to the desired output format.\nconst permissions = Object\n .entries(intermediate)\n .map(([role, action]) => ({ role, action }));\n\nconsole.log('result:\\n', permissions); .as-console-wrapper {\n max-height: 100% !important;\n}" }, { "answer_id": 74630826, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 1, "selected": false, "text": "true Object.values const rolePermission={adminView:!0,adminCreate:!0,adminDelete:!0,userView:!0,userEdit:!0,userDelete:!1};\n\n// Match admin or user as one group, and the rest\n// of the string as another group\nconst re = /^(admin|user)(.+)$/;\n\n// Declare temporary working object\nconst temp = {};\n\nfor (const key in rolePermission) {\n\n // When a match is made the role will be the first\n // element in the returned array, the action the second element\n const [role, action] = key.match(re).slice(1);\n\n // If the role doesn't exist in the temporary object\n // create it and assign a new default object to it\n temp[role] ??= { role, action: [] };\n\n // If the property value identified by the key\n // is true push the action to the actions array\n if (rolePermission[key]) {\n temp[role].action.push(action);\n }\n\n}\n\n// Get the array of objects\nconsole.log(Object.values(temp));" }, { "answer_id": 74630840, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": -1, "selected": false, "text": "const rolePermission = {\n adminView: true,\n adminCreate: true,\n adminDelete: true,\n userView: true,\n userEdit: true,\n userDelete: false,\n};\n\nconst output = Object.entries(\n Object.entries(rolePermission)\n .map(([key, allowed]) => {\n const regex = new RegExp(\"(.*)(View|Edit|Create|Delete)\", \"g\");\n const [, role, action] = regex.exec(key)\n return [role, action, allowed];\n }).filter(([,,allowed]) => allowed)\n .reduce((prev, [role, action]) => {\n prev[role] = prev[role] ? prev[role].concat([action]) : [action];\n return prev;\n }, {})\n).map(([role, action]) => ({ role, action }));\n\nconsole.log(output);" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647233/" ]
74,630,488
<p>I have issue styling my font-family using bootstrap. any help thanks</p> <pre><code>&lt;div class=&quot;float-start my-2 f-Arial&quot;&gt; &lt;label for=&quot;maleFemale&quot;&gt;Gender:&lt;/label&gt; &lt;select name=&quot;sex&quot; id=&quot;maleFemale&quot;&gt; &lt;option value=&quot;&quot;&gt;Select Gender:&lt;/option&gt; &lt;option value=&quot;male&quot;&gt;Male&lt;/option&gt; &lt;option value=&quot;female&quot;&gt;Female&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 74645837, "author": "herrstrietzel", "author_id": 15015675, "author_profile": "https://Stackoverflow.com/users/15015675", "pm_score": 1, "selected": false, "text": ":root {\n --bs-blue: #0d6efd;\n --bs-indigo: #6610f2;\n --bs-purple: #6f42c1;\n --bs-pink: #d63384;\n --bs-red: #dc3545;\n --bs-orange: #fd7e14;\n --bs-yellow: #ffc107;\n --bs-green: #198754;\n --bs-teal: #20c997;\n --bs-cyan: #0dcaf0;\n --bs-white: #fff;\n --bs-gray: #6c757d;\n --bs-gray-dark: #343a40;\n --bs-primary: #0d6efd;\n --bs-secondary: #6c757d;\n --bs-success: #198754;\n --bs-info: #0dcaf0;\n --bs-warning: #ffc107;\n --bs-danger: #dc3545;\n --bs-light: #f8f9fa;\n --bs-dark: #212529;\n --bs-font-sans-serif: system-ui, -apple-system, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, \"Noto Sans\", \"Liberation Sans\", sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\", \"Noto Color Emoji\";\n --bs-font-monospace: SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace;\n --bs-gradient: linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));\n}\n --bs-font-sans-serif :root{\n --bs-font-sans-serif: Arial\n}\n f-Arial .f-Arial{\n font-family: Arial\n}\n :root{\n --bs-font-sans-serif: Arial\n}\n\n.f-Arial{\n font-family: Arial\n} <link href=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css\" rel=\"stylesheet\"/>\n<p class=\"f-Arial\">Hamburg1234</p>\n\n<div class=\"float-start my-2 f-Arial\">\n <label for=\"maleFemale\">Gender:</label>\n <select name=\"sex\" id=\"maleFemale\">\n <option value=\"\">Select Gender:</option>\n <option value=\"male\">Male</option>\n <option value=\"female\">Female</option>\n </select>\n</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647272/" ]
74,630,496
<p>I am a bit confused as to what and what I need to install in order to start my app development using Visual Studio code.</p> <p>I've tried installing VS Code, and then just as I was about getting started it said something about having SDK</p>
[ { "answer_id": 74645837, "author": "herrstrietzel", "author_id": 15015675, "author_profile": "https://Stackoverflow.com/users/15015675", "pm_score": 1, "selected": false, "text": ":root {\n --bs-blue: #0d6efd;\n --bs-indigo: #6610f2;\n --bs-purple: #6f42c1;\n --bs-pink: #d63384;\n --bs-red: #dc3545;\n --bs-orange: #fd7e14;\n --bs-yellow: #ffc107;\n --bs-green: #198754;\n --bs-teal: #20c997;\n --bs-cyan: #0dcaf0;\n --bs-white: #fff;\n --bs-gray: #6c757d;\n --bs-gray-dark: #343a40;\n --bs-primary: #0d6efd;\n --bs-secondary: #6c757d;\n --bs-success: #198754;\n --bs-info: #0dcaf0;\n --bs-warning: #ffc107;\n --bs-danger: #dc3545;\n --bs-light: #f8f9fa;\n --bs-dark: #212529;\n --bs-font-sans-serif: system-ui, -apple-system, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, \"Noto Sans\", \"Liberation Sans\", sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\", \"Noto Color Emoji\";\n --bs-font-monospace: SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace;\n --bs-gradient: linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));\n}\n --bs-font-sans-serif :root{\n --bs-font-sans-serif: Arial\n}\n f-Arial .f-Arial{\n font-family: Arial\n}\n :root{\n --bs-font-sans-serif: Arial\n}\n\n.f-Arial{\n font-family: Arial\n} <link href=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css\" rel=\"stylesheet\"/>\n<p class=\"f-Arial\">Hamburg1234</p>\n\n<div class=\"float-start my-2 f-Arial\">\n <label for=\"maleFemale\">Gender:</label>\n <select name=\"sex\" id=\"maleFemale\">\n <option value=\"\">Select Gender:</option>\n <option value=\"male\">Male</option>\n <option value=\"female\">Female</option>\n </select>\n</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647340/" ]
74,630,536
<p>I have to use Semaphore to work on two different processes at the same time. But they work in a specific sequence and have to exclude each other.</p> <p>Process 1 &quot;p1&quot; has to print out first number &quot;1&quot; and after p1 is ready, p2 is allowed to work and print out the number 2. After p2 has finished, p1 should be allowed to work again on p1 and after p2 and so on.. The output shoult be 12121212....121212. My solution has somewhere an error and I am not able to see where it is. Unfortunately I need to solve this problem with a Semaphore. I think the problem could also be solved with mutex.</p> <p>How would the solution look like for: Semaphore? Mutex?</p> <p>I initialized two Semaphores sem1 and sem2. Sem1 has a permit of 1 and sem2 starts with a permit of 0.</p> <p>Both threads start simultaneously but since sem2 doesn't have a permit, sem1 enters the critical area with the acquire(); method. There it prints out &quot;1&quot; and after it's done, it will release a permit for sem2.</p> <p>sem2 is now allowed to enter its process with acquire(); and prints out &quot;2&quot;, when it is finished it releases a permit for sem1.</p> <p>The algorithm should continue this way, but somewhere is a lock and the program stops after printing 1</p> <pre><code>import java.util.concurrent.Semaphore; public class SemTest { Semaphore sem1 = new Semaphore(1); Semaphore sem2 = new Semaphore(0); public static void main(String args[]) { final SemTest semTest1 = new SemTest(); final SemTest semTest2 = new SemTest(); new Thread() { @Override public void run() { try { semTest1.numb1(); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); new Thread() { @Override public void run() { try { semTest2.numb2(); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); } private void numb1() { while (true) { try { sem1.acquire(); System.out.println(&quot; 1&quot;); sem2.release(); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } private void numb2() { while (true) { try { sem2.acquire(); System.out.println(&quot; 2&quot;); sem1.release(); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } </code></pre>
[ { "answer_id": 74630959, "author": "hooknc", "author_id": 42962, "author_profile": "https://Stackoverflow.com/users/42962", "pm_score": 0, "selected": false, "text": "sem1 sem2 package semaphore;\n\nimport java.util.concurrent.Semaphore;\n\npublic class MySemaphore {\n\n public static void main(String args[]) {\n\n Semaphore sem1 = new Semaphore(1);\n Semaphore sem2 = new Semaphore(0);\n\n new Thread()\n {\n @Override\n public void run()\n {\n try {\n numb1();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n private void numb1()\n {\n while (true) {\n try {\n sem1.acquire();\n System.out.println(\" 1\");\n sem2.release();\n\n Thread.sleep(1000);\n }\n catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n }\n }.start();\n\n new Thread()\n {\n @Override\n public void run()\n {\n try {\n numb2();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n private void numb2()\n {\n while (true) {\n try {\n sem2.acquire();\n System.out.println(\" 2\");\n sem1.release();\n Thread.sleep(1000);\n }\n\n catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n }.start();\n }\n}\n 1\n 2\n 1\n 2\n 1\n 2\n 1\n 2\n...\n" }, { "answer_id": 74631033, "author": "Solomon Slow", "author_id": 801894, "author_profile": "https://Stackoverflow.com/users/801894", "pm_score": 1, "selected": false, "text": "SemTest sem1 sem2 sem1 sem2 main() Runnable" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20424991/" ]
74,630,538
<p>I am using Laravel 8 and using Raw Query. I have added query to fetch count of product by manufacturers but facing below error.</p> <pre><code>SQLSTATE[42000]: Syntax error or access violation: 1055 'ngtonlin_superadmin.m.manufacturerid' isn't in GROUP BY (SQL: select `m`.`manufacturerid` as `id`, `m`.`name`, `m`.`logowidth`, `m`.`logoheight`, count(p.id) as total from `products` as `p` inner join `manufacturer` as `m` on `m`.`manufacturerid` = `p`.`manufacturer_id` group by `p`.`manufacturer_id` order by `total` desc limit 5) </code></pre> <p>and my query is</p> <pre><code>DB::table('products as p') -&gt;select('m.manufacturerid as id','m.name','m.logowidth','m.logoheight', DB::raw('count(p.id) as total')) -&gt;join('manufacturer as m','m.manufacturerid','=','p.manufacturer_id') -&gt;groupBy('p.manufacturer_id') -&gt;orderBy('total', 'DESC') -&gt;limit(5) -&gt;get(); </code></pre>
[ { "answer_id": 74630721, "author": "ronrun", "author_id": 3562689, "author_profile": "https://Stackoverflow.com/users/3562689", "pm_score": 2, "selected": true, "text": "->groupBy('m.manufacturerid', 'm.name','m.logowidth','m.logoheight')\n ->groupBy('p.manufacturer_id')\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16365514/" ]
74,630,563
<p>I'm running Mosquitto 2.0.15 on ubuntu 20.04</p> <p>and I want to configure to listen on a specific interface, but I don't want to hardcode the interface address</p> <p>the interface I want to listen on is:</p> <pre><code>enp3s0: connected to Wired connection 1 &quot;Realtek RTL8111/8168/8411&quot; ethernet (r8169), 00:E2:69:3D:CA:C2, hw, mtu 1500 ip4 default inet4 192.168.2.115/24 route4 0.0.0.0/0 route4 192.168.2.0/24 inet6 fe80::9490:96c4:9f56:d81c/64 route6 fe80::/64 </code></pre> <p>Can anybody please help me?</p> <p>Thanks, Nadav</p> <p>I run the mosquitto like this:</p> <p><code>sudo mosquitto -v -c mosquitto.conf</code></p> <p>If I configure the mosquitto like this:</p> <pre><code>listener 8882 192.168.2.115 protocol mqtt allow_anonymous true </code></pre> <p>it works OK,</p> <p>I tried this:</p> <pre><code>listener 8882 bind_interface enp3s0 protocol mqtt allow_anonymous true </code></pre> <p>but I get error:</p> <pre><code>2022/11/30 10:35:12: Opening ipv4 listen socket on port 8882. 2022/11/30 10:35:12: Opening ipv6 listen socket on port 8882. 2022/11/30 10:35:12: Error: Invalid argument </code></pre> <p>I tried this:</p> <pre><code>listener 8882 bind_interface Wired connection 1 protocol mqtt allow_anonymous true </code></pre> <p>and I get:</p> <pre><code>2022/11/30 10:35:55: Opening ipv4 listen socket on port 8882. 2022/11/30 10:35:55: Warning: Interface Wired connection 1 does not support IPv4 configuration. 2022/11/30 10:35:55: Opening ipv6 listen socket on port 8882. 2022/11/30 10:35:55: Warning: Interface Wired connection 1 does not support IPv6 configuration. </code></pre> <p>I even tried (there is NO eth0 interface):</p> <pre><code>listener 8882 bind_interface XXXX protocol mqtt allow_anonymous true </code></pre> <p>and I get:</p> <pre><code>2022/11/30 10:37:29: Opening ipv4 listen socket on port 8882. 2022/11/30 10:37:29: Warning: Interface XXXX does not support IPv4 configuration. 2022/11/30 10:37:29: Opening ipv6 listen socket on port 8882. 2022/11/30 10:37:29: Warning: Interface XXXX does not support IPv6 configuration. </code></pre>
[ { "answer_id": 74631310, "author": "hardillb", "author_id": 504554, "author_profile": "https://Stackoverflow.com/users/504554", "pm_score": 1, "selected": false, "text": "listener 8882\nbind_interface enp3s0\nprotocol mqtt\nallow_anonymous true\n" }, { "answer_id": 74638170, "author": "Nadav Popplewell", "author_id": 20213906, "author_profile": "https://Stackoverflow.com/users/20213906", "pm_score": 0, "selected": false, "text": "bind(5, {sa_family=AF_INET6, sin6_port=htons(8882), sin6_flowinfo=htonl(0), inet_pton(AF_INET6, \"fe80::9490:96c4:9f56:d81c\", &sin6_addr), sin6_scope_id=0}, 28) = -1 EINVAL (Invalid argument)\nwrite(2, \"1669878630: Error: Invalid argum\"..., 361669878630: Error: Invalid argument\n)\n socket_domain ipv4\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20213906/" ]
74,630,565
<p>I want to generate a v5 UUID for a string using a given namespace.</p> <p><a href="https://man.archlinux.org/man/uuid_generate_time.3.en" rel="nofollow noreferrer">https://man.archlinux.org/man/uuid_generate_time.3.en</a> talks about <code>uuid_generate_sha1()</code> but I could not find any good examples on how to use them in our code.</p> <p>My pseudocode looks like:</p> <pre><code>_generate_v5_uuid(const char *inputStr, const char *namespace, char **outputString) { uuid_t uuid; uuid_generate_sha1(inputStr, &amp;uuid); *outputStr = convert_uuid_to_string(uuid); return; } </code></pre> <p>What exactly needs to be passed to <code>uuid_generate_sha1</code>?</p>
[ { "answer_id": 74631310, "author": "hardillb", "author_id": 504554, "author_profile": "https://Stackoverflow.com/users/504554", "pm_score": 1, "selected": false, "text": "listener 8882\nbind_interface enp3s0\nprotocol mqtt\nallow_anonymous true\n" }, { "answer_id": 74638170, "author": "Nadav Popplewell", "author_id": 20213906, "author_profile": "https://Stackoverflow.com/users/20213906", "pm_score": 0, "selected": false, "text": "bind(5, {sa_family=AF_INET6, sin6_port=htons(8882), sin6_flowinfo=htonl(0), inet_pton(AF_INET6, \"fe80::9490:96c4:9f56:d81c\", &sin6_addr), sin6_scope_id=0}, 28) = -1 EINVAL (Invalid argument)\nwrite(2, \"1669878630: Error: Invalid argum\"..., 361669878630: Error: Invalid argument\n)\n socket_domain ipv4\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10901567/" ]
74,630,583
<p>I have the following problem and I'm wondering if it could be solved just with CSS Flexible Box Layout:</p> <p>I have a number of boxes (divs) with the same width, and I want:</p> <ul> <li>the first box to stay in the first row</li> <li>all other boxes on row below wrapping when necessary BUT also:</li> <li>I want the first box to be aligned with the first boxes in the other rows.</li> </ul> <p>Basically:</p> <pre><code>[] [] [] [] [] [] [] [] [] </code></pre> <p>and I want this behaviour no matter what the <code>justify-content</code> value is.</p> <p>Is it possible?</p>
[ { "answer_id": 74630958, "author": "Diego D", "author_id": 1221208, "author_profile": "https://Stackoverflow.com/users/1221208", "pm_score": 1, "selected": false, "text": "flex-basis .flex {\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n gap: 10px;\n outline: solid 1px blue;\n}\n\n/*items in the flex container all equally sized for easy demoing*/\n.flex .item{\n outline: solid 1px darkgray;\n width: 50px;\n height: 50px;\n /* the flex layout for items it's for the sake of easily center their content*/\n display: flex;\n justify-content:center;\n align-items: center;\n}\n\n.flex > *:first-child {\n outline: solid 1px red;\n flex-basis: 100%;\n} <div class=\"flex\">\n <!-- the first item was wrapped in its own div so that only that will change its width to occupy the whole row preventing its inner child to change dimensions -->\n <div>\n <div class=\"item\">1</div>\n </div>\n <div class=\"item\">2</div>\n <div class=\"item\">3</div>\n <div class=\"item\">4</div>\n <div class=\"item\">5</div>\n <div class=\"item\">6</div>\n <div class=\"item\">7</div>\n <div class=\"item\">8</div>\n <div class=\"item\">9</div>\n <div class=\"item\">10</div>\n <div class=\"item\">11</div>\n <div class=\"item\">12</div>\n <div class=\"item\">13</div>\n <div class=\"item\">14</div>\n <div class=\"item\">15</div>\n <div class=\"item\">16</div>\n</div>" }, { "answer_id": 74634455, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": 2, "selected": false, "text": ".box {\n display: flex;\n flex-wrap: wrap;\n gap: 10px;\n}\n.box div {\n width: 80px;\n aspect-ratio: 1;\n background: red;\n}\n\n/* the pseudo element will be the separator */\n.box:before {\n content:\"\";\n flex-basis:100%;\n}\n/* the first element before it*/\n.box div:first-child {\n order: -1;\n} <div class=\"box\">\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2175261/" ]
74,630,596
<p>Using Python 3...</p> <p>I've written code that rounds the values for ArcGIS symbology labels. The label is given as a string like &quot;0.3324 - 0.6631&quot;. My reproducible code is...</p> <pre><code>label = &quot;0.3324 - 0.6631&quot; label_list = [] label_split = label.split(&quot; - &quot;) for num in label_split: num = round(float(num), 2) # rounded to 2 decimals num = str(num) label_list.append(num) label = label_list[0]+&quot; - &quot;+label_list[1] </code></pre> <p>This code works but does anyone have any recommendations/better approaches for rounding numbers inside of strings?</p>
[ { "answer_id": 74630770, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 1, "selected": false, "text": "\\b\\d+\\.\\d+\\b ABC0.1234 \\b\\d+\\.\\d+\\b\n\n\\b \\b : Word boundary\n \\d+ \\d+ : One or more digits\n \\. : Decimal point\n re.sub match float def round_to_2(match):\n num = float(match.group(0))\n return f\"{num:.2f}\"\n repl re.sub label = \"0.3324 - 0.6631 ABC0.1234 0.12 1.234 1.23 123.4567 1.2\"\nlabel_rep = re.sub(r\"\\b\\d+\\.\\d+\\b\", round_to_2, label)\n label_rep '0.33 - 0.66 ABC0.1234 0.12 1.23 1.23 123.46 1.20'\n" }, { "answer_id": 74630838, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 3, "selected": true, "text": "x, _, y = label.partition(\" - \")\nlabel = f\"{float(x):.2f} - {float(y):.2f}\"\n" }, { "answer_id": 74632334, "author": "SergFSM", "author_id": 18344512, "author_profile": "https://Stackoverflow.com/users/18344512", "pm_score": 1, "selected": false, "text": "label = \"0.3324 - 0.6631\"\n'{:.2f}-{:.2f}'.format(*map(float,label.split('-')))\n\n>>>\n'0.33-0.66'\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16138574/" ]
74,630,608
<p>I have a bunch of folders which look like the below, I need to remove the point between the 2.0:</p> <pre><code>0010_DWI_MS_2.0_first_2874028735_10.bvec 0010_DWI_MS_2.0_first_2874028735_10.bval 0010_DWI_MS_2.0_first_2874028735_10.nii 0011_DWI_MS_2.0_first_2874028735_11.bvec 0011_DWI_MS_2.0_first_2874028735_11.bval 0011_DWI_MS_2.0_first_2874028735_11.nii </code></pre> <p>What I'm trying to acheive:</p> <pre><code>0010_DWI_MS_20_first_2874028735_10.bvec 0010_DWI_MS_20_first_2874028735_10.bval 0010_DWI_MS_20_first_2874028735_10.nii 0011_DWI_MS_20_first_2874028735_11.bvec 0011_DWI_MS_20_first_2874028735_11.bval 0011_DWI_MS_20_first_2874028735_11.nii </code></pre> <p>Is there also a way to do this for folders rather than files?</p>
[ { "answer_id": 74630770, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 1, "selected": false, "text": "\\b\\d+\\.\\d+\\b ABC0.1234 \\b\\d+\\.\\d+\\b\n\n\\b \\b : Word boundary\n \\d+ \\d+ : One or more digits\n \\. : Decimal point\n re.sub match float def round_to_2(match):\n num = float(match.group(0))\n return f\"{num:.2f}\"\n repl re.sub label = \"0.3324 - 0.6631 ABC0.1234 0.12 1.234 1.23 123.4567 1.2\"\nlabel_rep = re.sub(r\"\\b\\d+\\.\\d+\\b\", round_to_2, label)\n label_rep '0.33 - 0.66 ABC0.1234 0.12 1.23 1.23 123.46 1.20'\n" }, { "answer_id": 74630838, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 3, "selected": true, "text": "x, _, y = label.partition(\" - \")\nlabel = f\"{float(x):.2f} - {float(y):.2f}\"\n" }, { "answer_id": 74632334, "author": "SergFSM", "author_id": 18344512, "author_profile": "https://Stackoverflow.com/users/18344512", "pm_score": 1, "selected": false, "text": "label = \"0.3324 - 0.6631\"\n'{:.2f}-{:.2f}'.format(*map(float,label.split('-')))\n\n>>>\n'0.33-0.66'\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16344097/" ]
74,630,637
<p>I was investigating STL implementations, and I'm failing to understand how the code compiles.</p> <p>Take <code>std::set</code> as an example. <a href="https://github.com/gcc-mirror/gcc/blob/3832c6f7e672e76bba74a508bf3a49740ea38046/libstdc++-v3/include/bits/stl_set.h" rel="nofollow noreferrer">Here's a reference to libstdc++ on github.</a>.</p> <p>Internally, <code>std::set</code> uses a red-black tree, using <code>class _Rb_tree</code>, lines 131-133.</p> <p>It appears <code>class _Rb_tree</code> is defined in stl_tree.h, available <a href="https://github.com/gcc-mirror/gcc/blob/3832c6f7e672e76bba74a508bf3a49740ea38046/libstdc++-v3/include/bits/stl_tree.h" rel="nofollow noreferrer">here</a>, line 425.</p> <p>I'm confused because <code>stl_set.h</code> does not include <code>stl_tree.h</code>. Why does this not fail?</p>
[ { "answer_id": 74630770, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 1, "selected": false, "text": "\\b\\d+\\.\\d+\\b ABC0.1234 \\b\\d+\\.\\d+\\b\n\n\\b \\b : Word boundary\n \\d+ \\d+ : One or more digits\n \\. : Decimal point\n re.sub match float def round_to_2(match):\n num = float(match.group(0))\n return f\"{num:.2f}\"\n repl re.sub label = \"0.3324 - 0.6631 ABC0.1234 0.12 1.234 1.23 123.4567 1.2\"\nlabel_rep = re.sub(r\"\\b\\d+\\.\\d+\\b\", round_to_2, label)\n label_rep '0.33 - 0.66 ABC0.1234 0.12 1.23 1.23 123.46 1.20'\n" }, { "answer_id": 74630838, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 3, "selected": true, "text": "x, _, y = label.partition(\" - \")\nlabel = f\"{float(x):.2f} - {float(y):.2f}\"\n" }, { "answer_id": 74632334, "author": "SergFSM", "author_id": 18344512, "author_profile": "https://Stackoverflow.com/users/18344512", "pm_score": 1, "selected": false, "text": "label = \"0.3324 - 0.6631\"\n'{:.2f}-{:.2f}'.format(*map(float,label.split('-')))\n\n>>>\n'0.33-0.66'\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5822257/" ]
74,630,698
<p>I'm currently discovering the automation tool Cypress, and I have a problem with the most basic functionality.</p> <p>What I want to do in my this is access this URL: <code>https://www.unicef.fr/se-connecter/</code><br /> Click on the password input, then type a password.</p> <p>But whenever my code is about to type, the screen scrolls down and I get an error message saying that the password input cannot be found.</p> <p>Here is the code I'm using :</p> <pre class="lang-js prettyprint-override"><code>cy.visit('https://www.unicef.fr/se-connecter/'); cy.get('#js-account-login-input-id').type(&quot;01223442342&quot;); </code></pre> <p>Any ideas how I can stop that auto scroll or is there something I'm doing wrong?</p>
[ { "answer_id": 74631327, "author": "jjhelguero", "author_id": 17917809, "author_profile": "https://Stackoverflow.com/users/17917809", "pm_score": 0, "selected": false, "text": "js-account-login-input-password cy.get('input[type=password]')\n" }, { "answer_id": 74633367, "author": "Fody", "author_id": 16997707, "author_profile": "https://Stackoverflow.com/users/16997707", "pm_score": 3, "selected": true, "text": "cy.get('#js-account-login-input-id')\n .type(\"01223442342\", {scrollBehavior: 'center'})\n .type() cy.viewport() cy.viewport(1500,1000)\ncy.visit('https://www.unicef.fr/se-connecter/')\n\ncy.contains('button', \"C'est OK pour moi\").click() // accept cookies\n\ncy.get('#js-account-login-input-id')\n .type(\"01223442342\", {scrollBehavior: 'center'})\n .if() cy.contains('button', \"C'est OK pour moi\")\n .if() // does cookie button show?\n .click() // accept cookies\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647451/" ]
74,630,707
<p>I am creating an algorithm to count natural numbers however the output is a long number:</p> <pre><code>1532752% </code></pre> <p>Here is what I have tried:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int sumN(int N){ int S = 0; int I = 1; int *p = &amp;I; for(int i = *p; i &lt; N; i++){ S += S + i; I += i + 1; if( i &lt;= N){ continue; } } return S; } int main(void){ int N = 15; printf(&quot;%i&quot;, sumN(N)); return EXIT_SUCCESS; } </code></pre> <p>I am new to C and would appreciate feedback because I am likely missing much technical information.</p>
[ { "answer_id": 74631447, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 2, "selected": false, "text": " int sum =0;\n For (int i =1; i<=N; i++){\n sum += i;\n }\n" }, { "answer_id": 74631741, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint sumN(int N)\n{\n return N*(N+1)/2;\n}\n\nint sumN2(int N)\n{\n int sum = 0;\n for(int i=1; i<=N; sum+=i++);\n return sum;\n}\n\nint main(void){\n int N = 15;\n printf(\"%i\\n\", sumN(N));\n printf(\"%i\\n\", sumN2(N));\n return EXIT_SUCCESS;\n}\n 120 \n120\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16470943/" ]
74,630,743
<p>I'm trying to change the values inside inputs. I got those values from the db. But it doesn't allow me to type or edit the value. I've added an <code>handleInputChange</code> function to put inside <code>onChange</code> inside each input tag but it didn't work. I need those values to be inside inputs at the beginning and disappear after the user starts typing.</p> <p>I thought about <code>ref={ref}</code> and <code>defaultValue</code>, but I don't know how I'll get updated values than in order to send it back to the db.</p> <p>EditFeedbackPage.js</p> <pre><code> const EditFeedbackPage = () =&gt; { const initialState = { category: &quot;All&quot;, comments: [], detail: &quot;&quot;, id: nanoid(), createdAt: Timestamp.now().toDate(), status: &quot;Suggestion&quot;, title: &quot;&quot;, upVotesCount: [] } const [state, setState] = useState(initialState); const { feedback } = useSelector((state) =&gt; state.data); const { category, detail, title, status } = feedback; console.log(feedback) const params = useParams(); const { id } = params; console.log(&quot;id from params =&gt; &quot;, id) const dispatch = useDispatch(); const navigate = useNavigate(); const cancelAddFeedback = () =&gt; { navigate(&quot;/&quot;) } useEffect(() =&gt; { dispatch(getSingleFeedback(id)); console.log(&quot;feedbackId =&gt; &quot;, id); }, []); const editFeedback = async (e, id) =&gt; { e.preventDefault(); console.log(&quot;feedbackId =&gt; &quot;, id); dispatch(editFeedbackInit(id, feedback)) } const handleInputChange = (e) =&gt; { let { name, value } = e.target; setState({ ...state, [name]: value }) } const handleSubmit = (e) =&gt; { e.preventDefault(); setState({ ...state, title: '', detail: &quot;&quot;, category: &quot;All&quot; }) } return ( &lt;EditFeedbackFormContainer onSubmit={handleSubmit} &gt; &lt;h4&gt;Feedback Title&lt;/h4&gt; &lt;label htmlFor=&quot;title&quot;&gt;Add a short, descriptive headline&lt;/label&gt; &lt;input type=&quot;text&quot; name='title' value={title} onChange={handleInputChange} /&gt; &lt;h4&gt;Category&lt;/h4&gt; &lt;label htmlFor=&quot;category&quot;&gt;Change a category for your feedback&lt;/label&gt; &lt;select name=&quot;category&quot; id=&quot;category&quot; value={category} onChange={handleInputChange} &gt; &lt;option value=&quot;All&quot;&gt;All&lt;/option&gt; &lt;option value=&quot;UI&quot;&gt;UI&lt;/option&gt; &lt;option value=&quot;UX&quot;&gt;UX&lt;/option&gt; &lt;option value=&quot;Enhancement&quot;&gt;Enhancement&lt;/option&gt; &lt;option value=&quot;Bug&quot;&gt;Bug&lt;/option&gt; &lt;option value=&quot;Feature&quot;&gt;Feature&lt;/option&gt; &lt;/select&gt; &lt;h4&gt;Update Status&lt;/h4&gt; &lt;label htmlFor=&quot;status&quot;&gt;Change feedback status&lt;/label&gt; &lt;select name=&quot;status&quot; id=&quot;status&quot; value={status} onChange={handleInputChange} &gt; &lt;option value=&quot;Suggestion&quot;&gt;Suggestion&lt;/option&gt; &lt;option value=&quot;Planned&quot;&gt;Planned&lt;/option&gt; &lt;option value=&quot;In-Progress&quot;&gt;In-Progress&lt;/option&gt; &lt;option value=&quot;Live&quot;&gt;Live&lt;/option&gt; &lt;/select&gt; &lt;h4&gt;Change a feedback detail&lt;/h4&gt; &lt;label htmlFor=&quot;detail&quot;&gt;Include any specific comments on what should be improved, added, etc.&lt;/label&gt; &lt;textarea name=&quot;detail&quot; id=&quot;detail&quot; value={detail} onChange={handleInputChange} /&gt; &lt;EditFeedbackButtonsContainer&gt; &lt;EditFeedbackButtonDelete onClick={deleteFeedback} &gt; Delete &lt;/EditFeedbackButtonDelete&gt; &lt;EditFeedbackButtonCancel onClick={cancelAddFeedback}&gt;Cancel&lt;/EditFeedbackButtonCancel&gt; &lt;EditFeedbackButtonAdd onClick={editFeedback} &gt;Edit Feedback&lt;/EditFeedbackButtonAdd&gt; &lt;/EditFeedbackButtonsContainer&gt; &lt;/EditFeedbackFormContainer&gt; ) </code></pre>
[ { "answer_id": 74631447, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 2, "selected": false, "text": " int sum =0;\n For (int i =1; i<=N; i++){\n sum += i;\n }\n" }, { "answer_id": 74631741, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint sumN(int N)\n{\n return N*(N+1)/2;\n}\n\nint sumN2(int N)\n{\n int sum = 0;\n for(int i=1; i<=N; sum+=i++);\n return sum;\n}\n\nint main(void){\n int N = 15;\n printf(\"%i\\n\", sumN(N));\n printf(\"%i\\n\", sumN2(N));\n return EXIT_SUCCESS;\n}\n 120 \n120\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13271745/" ]
74,630,757
<p>I want to have only one blurred circle but this is not possible and the outer parts of the circle i.e. Container are completely blurred. The same is true for CustomPoint. <a href="https://i.stack.imgur.com/xTEKm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xTEKm.png" alt="This Image" /></a></p> <p>Codes :</p> <pre><code>Center( child: Stack(alignment: Alignment.center, children: [ Image.network( &quot;https://mojekooh.com/wp-content/uploads/2020/09/1024px-Matterhorn_from_Domh%C3%BCtte_-_2.jpg&quot;), ClipRRect( child: BackdropFilter( filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), child: Container( width: 200, height: 100, decoration: const BoxDecoration( color: Color.fromARGB(33, 255, 0, 0), shape: BoxShape.circle), ), ), ) ]), ), </code></pre> <p>I searched the internet and did not find anything</p> <p><strong>Update</strong>:</p> <p>My friends, I solved this problem:</p> <pre><code> Stack(alignment: Alignment.center, children: [ Image.network( &quot;https://mojekooh.com/wp-content/uploads/2020/09/1024px-Matterhorn_from_Domh%C3%BCtte_-_2.jpg&quot;), ClipOval( clipper: CoustomCircle(), child: BackdropFilter( filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), child: Container( width: 200, height: 200, decoration: const BoxDecoration( color: Color.fromARGB(57, 255, 0, 0), shape: BoxShape.circle), ), ), ) ]), class CoustomCircle extends CustomClipper&lt;Rect&gt; { @override Rect getClip(size){ return const Rect.fromLTWH(0, 0, 200, 200); } @override bool shouldReclip(oldClipper){ return true; } } </code></pre>
[ { "answer_id": 74631447, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 2, "selected": false, "text": " int sum =0;\n For (int i =1; i<=N; i++){\n sum += i;\n }\n" }, { "answer_id": 74631741, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint sumN(int N)\n{\n return N*(N+1)/2;\n}\n\nint sumN2(int N)\n{\n int sum = 0;\n for(int i=1; i<=N; sum+=i++);\n return sum;\n}\n\nint main(void){\n int N = 15;\n printf(\"%i\\n\", sumN(N));\n printf(\"%i\\n\", sumN2(N));\n return EXIT_SUCCESS;\n}\n 120 \n120\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15574325/" ]
74,630,771
<p>So I start put with a file that lists title, actor, title, actor, etc.</p> <pre><code> 12 Years a Slave Topsy Chapman 12 Years a Slave Devin Maurice Evans 12 Years a Slave Brad Pitt 12 Years a Slave Jay Huguley 12 Years a Slave Devyn A. Tyler 12 Years a Slave Willo Jean-Baptiste American Hustle Christian Bale American Hustle Bradley Cooper American Hustle Amy Adams American Hustle Jeremy Renner American Hustle Jennifer Lawrence </code></pre> <p>I need to make a dictionary that looks like what's below and lists all actors in the movie</p> <pre><code> {'Movie Title': ['All actors'], 'Movie Title': ['All Actors]} </code></pre> <p>So far I only have this</p> <pre><code>d = {} with open(file), 'r') as f: for key in f: d[key.strip()] = next(f).split() print(d) </code></pre>
[ { "answer_id": 74631437, "author": "Edo Akse", "author_id": 9267296, "author_profile": "https://Stackoverflow.com/users/9267296", "pm_score": 0, "selected": false, "text": "# pretty printer to make the output nice\nfrom pprint import pprint\n\n\ndata = \"\"\" 12 Years a Slave\n Topsy Chapman\n 12 Years a Slave\n Devin Maurice Evans\n 12 Years a Slave\n Brad Pitt\n 12 Years a Slave\n Jay Huguley\n 12 Years a Slave\n Devyn A. Tyler\n 12 Years a Slave\n Willo Jean-Baptiste\n American Hustle\n Christian Bale\n American Hustle\n Bradley Cooper\n American Hustle\n Amy Adams\n American Hustle\n Jeremy Renner\n American Hustle\n Jennifer Lawrence\"\"\"\n\n\nresult = {}\ntitle = None\nfor line in data.splitlines():\n # clean here once\n line = line.strip()\n if not title:\n # store the title\n title = line\n else:\n # check if title already exists\n if title in result:\n # if yes, append actor\n result[title].append(line)\n else:\n # if no, create it with new list for actors\n # and of course, add the current line as actor\n result[title] = [line]\n # reset title to None\n title = None\n\npprint(result)\n {'12 Years a Slave': ['Topsy Chapman',\n 'Devin Maurice Evans',\n 'Brad Pitt',\n 'Jay Huguley',\n 'Devyn A. Tyler',\n 'Willo Jean-Baptiste'],\n 'American Hustle': ['Christian Bale',\n 'Bradley Cooper',\n 'Amy Adams',\n 'Jeremy Renner',\n 'Jennifer Lawrence']}\n from pprint import pprint\n\nresult = {}\ntitle = None\nwith open(\"somefile.txt\") as infile:\n for line in infile.read().splitlines():\n line = line.strip()\n if not title:\n title = line\n else:\n if title in result:\n result[title].append(line)\n else:\n result[title] = [line]\n title = None\n\n\npprint(result)\n" }, { "answer_id": 74631753, "author": "Bharel", "author_id": 1658617, "author_profile": "https://Stackoverflow.com/users/1658617", "pm_score": 1, "selected": false, "text": "defaultdict from collections import defaultdict\ndata = defaultdict(list)\n\nwith open(\"filename.txt\", 'r') as f:\n stripped = map(str.strip, f)\n for movie, actor in zip(stripped, stripped):\n data[movie].append(actor)\n\nprint(data)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20565396/" ]
74,630,799
<p>I'm very new to Python and have an issue. I was wondering if there was a way I could create a list of objects created. For example, say I have a class:</p> <pre><code>list_triangles = [] def class Triangle: def __init__(self, h, w): self.h = h self.w = w a = Triangle(5,6) b = Triangle(3,3) </code></pre> <p>What I would have to add such that each time I defined a new object, it would append to <code>list_triangles</code>, such that in the end I have a list of objects?</p> <p>e.g <code>list_triangles = (a, b)</code></p> <p>I'm thinking I'd have to make a for loop, but I'm not sure because what would I say <code>for i in range ____</code>?</p>
[ { "answer_id": 74630856, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 2, "selected": false, "text": "params = [(5, 6), (3, 3)]\nlist_triangles = [Triangle(*p) for p in params]\n" }, { "answer_id": 74631173, "author": "kacpo1", "author_id": 12671140, "author_profile": "https://Stackoverflow.com/users/12671140", "pm_score": 1, "selected": false, "text": "self class Cat():\n instances = []\n def __init__(self, name):\n self.name = name\n Cat.instances.append(self)\n\na = Cat(\"Bob\")\nb = Cat(\"John\")\n\nprint(Cat.instances)\nprint(Cat.instances[0].name)\n >> [<__main__.Cat object at 0x00000000014BE790>, <__main__.Cat object at 0x00000000014BE610>]\n>> Bob\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20300079/" ]
74,630,807
<p>Context:</p> <p><em>I've found a bug in a selenium framework I'm working on, in which the Web Browser (at least Chrome) crashes unexpectedly with no notification.<br /> As a patch, I'm reinitializing the WebDriver so it keeps working, but right now I'm creating a new EdgeDriver and I want to create a new WebDriver of the <strong>same type</strong> it was before (the one that crashed).</em></p> <p>I came up with this approach:</p> <pre><code>driver = Map.of( ChromeDriver.class, getFunction(ChromeDriver.class), EdgeDriver.class, getFunction(EdgeDriver.class), FirefoxDriver.class, getFunction(FirefoxDriver.class), OperaDriver.class, getFunction(OperaDriver.class) ).entrySet().stream().filter((e) -&gt; e.getKey().isInstance(driver)) .map((e)-&gt;e.getValue().identity()).findFirst().orElseThrow(() -&gt; new RuntimeException(&quot;WebDriver not detected&quot;)); </code></pre> <p>...</p> <pre><code>@SneakyThrows static Function&lt;Class&lt;? extends RemoteWebDriver&gt;, RemoteWebDriver&gt; getFunction(Class&lt;? extends RemoteWebDriver&gt; driverClass){ return c -&gt; { try { return c.getConstructor().newInstance(); } catch (IllegalAccessException | InstantiationException e) { throw new RuntimeException(e); } }; } </code></pre> <p>The problem is that I can't use this type of call</p> <pre><code>e.getValue().identity() </code></pre> <p>Do you know how can I achieve this?</p> <p>I'm using the <strong>Map</strong> approach so I don't have to specify a bunch of <code>if</code>'s with all the code inside.<br /> And I'm using a separate method returning a <strong>Function</strong> so I don't have to spend resources in creating the instances before (and if they) are required.</p> <p>I have faced this problem before and I'm pretty sure I'm going to keep facing it, I have almost no idea what I'm writing in the functional programming section because I'm very new to it. I hope I'm on the right track but honestly, I doubt it.</p> <p><em>As an extra tip if you can provide a way to become an expert in functional programming in Java will be great because I've been looking for a course or any resources deep enough and I have not been able to find anything so far. Not only will solve this problem but it will help me to solve any future problems like this.</em></p>
[ { "answer_id": 74630856, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 2, "selected": false, "text": "params = [(5, 6), (3, 3)]\nlist_triangles = [Triangle(*p) for p in params]\n" }, { "answer_id": 74631173, "author": "kacpo1", "author_id": 12671140, "author_profile": "https://Stackoverflow.com/users/12671140", "pm_score": 1, "selected": false, "text": "self class Cat():\n instances = []\n def __init__(self, name):\n self.name = name\n Cat.instances.append(self)\n\na = Cat(\"Bob\")\nb = Cat(\"John\")\n\nprint(Cat.instances)\nprint(Cat.instances[0].name)\n >> [<__main__.Cat object at 0x00000000014BE790>, <__main__.Cat object at 0x00000000014BE610>]\n>> Bob\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1180993/" ]
74,630,823
<p><a href="https://i.stack.imgur.com/QfkEB.png" rel="nofollow noreferrer">EPLgames2018/19 CSV</a>I am fairly new to python.</p> <p>I am reading in a CSV file that contains the stats from every english premier league match in 2018/19.</p> <p>I have created a list of all of the teams. I am then trying to take each team in turn and loop through all of the matches to calculate each teams total points for the season.</p> <p>It seems to work for the first team. It takes Man Utd and I get the correct points for them. The problem I have is getting to the next team in the list and then looping through the points code with them.</p> <pre><code>import csv with open('EPL1819.csv') as file: eplgames = csv.DictReader(file) teampoints = list() eplteams = list() teamcount = 0 count = 0 # Outer loop going through teams one at a time for i in range(20): points = 0 # Inner loop going through each match for x in eplgames: # Populates the eplteams list if x['HomeTeam'] not in eplteams: eplteams.append(x['HomeTeam']) teamcount += 1 #print(eplteams[i]) # Works out the match result if x['FTHG'] &gt; x['FTAG']: match_result = x['HomeTeam'] elif x['FTHG'] &lt; x['FTAG']: match_result = x['AwayTeam'] else: match_result = &quot;Draw&quot; if eplteams[i] == match_result: points += 3 if eplteams[i] == x['HomeTeam']: if match_result == &quot;Draw&quot;: points += 1 if eplteams[i] == x['AwayTeam']: if match_result == &quot;Draw&quot;: points += 1 # Populates the teampoints list teampoints.append(points) print(eplteams[i]) print(&quot;Points:&quot;, points) print(&quot;Points List:&quot;, teampoints[i]) </code></pre>
[ { "answer_id": 74630856, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 2, "selected": false, "text": "params = [(5, 6), (3, 3)]\nlist_triangles = [Triangle(*p) for p in params]\n" }, { "answer_id": 74631173, "author": "kacpo1", "author_id": 12671140, "author_profile": "https://Stackoverflow.com/users/12671140", "pm_score": 1, "selected": false, "text": "self class Cat():\n instances = []\n def __init__(self, name):\n self.name = name\n Cat.instances.append(self)\n\na = Cat(\"Bob\")\nb = Cat(\"John\")\n\nprint(Cat.instances)\nprint(Cat.instances[0].name)\n >> [<__main__.Cat object at 0x00000000014BE790>, <__main__.Cat object at 0x00000000014BE610>]\n>> Bob\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647456/" ]
74,630,829
<p>I have a input for phone number, and its type is not number is text, and I want to check if the input has characters to validate it as wrong, I have set it like that because I put a format to the input like 123-123-1234 here is my input</p> <pre><code>&lt;input (keyup)=&quot;format()&quot; (change)=&quot;format()&quot; maxlength=&quot;12&quot; inputmode=&quot;numeric&quot; type='text' class=&quot;input&quot; formControlName=&quot;celular&quot; id=&quot;celular&quot; name=&quot;celular&quot;&gt; </code></pre> <p>Here is my ts where I set the format</p> <pre><code> format(){ $('#celular').val($('#celular').val().replace(/^(\d{3})(\d{3})(\d+)$/, &quot;$1-$2-$3&quot;)); } </code></pre> <p>so what I want to do, is to know if the value of my input has characters from aA-zZ and some specials characters that are not -</p>
[ { "answer_id": 74630856, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 2, "selected": false, "text": "params = [(5, 6), (3, 3)]\nlist_triangles = [Triangle(*p) for p in params]\n" }, { "answer_id": 74631173, "author": "kacpo1", "author_id": 12671140, "author_profile": "https://Stackoverflow.com/users/12671140", "pm_score": 1, "selected": false, "text": "self class Cat():\n instances = []\n def __init__(self, name):\n self.name = name\n Cat.instances.append(self)\n\na = Cat(\"Bob\")\nb = Cat(\"John\")\n\nprint(Cat.instances)\nprint(Cat.instances[0].name)\n >> [<__main__.Cat object at 0x00000000014BE790>, <__main__.Cat object at 0x00000000014BE610>]\n>> Bob\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20531528/" ]
74,630,841
<pre><code>def itr(n): s = 0 for i in range(0, n+1): s = s + i * i return s </code></pre> <p>I have difficulties turning this iterative function to a recursive function called rec(n).</p>
[ { "answer_id": 74630988, "author": "realhuman", "author_id": 15690172, "author_profile": "https://Stackoverflow.com/users/15690172", "pm_score": 1, "selected": false, "text": "def rec(n, s = 0): # s = 0 is a default variable, so if we don't specify what s is when we call the function, it's default variable will be 0\n if n == 0: # base case, so if we've run through the entire program n times, it will exit and return the final value\n return s\n \n s = s + n * n # your task, where n replaces i because we change n the same amount of times as i runs\n n -= 1 # we change n so that every time we run the function it eventually reaches 0\n\n return rec(n, s) # recursively run the function again\n n 0 n i n n n" }, { "answer_id": 74631277, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 0, "selected": false, "text": "def rec(n):\n return 0 if n <= 0 else n * n + rec(n-1)\n\nprint(rec(10))\n 385\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17533925/" ]
74,630,865
<p>I'm very new to file and struct and I just don't know how to do it. Now, I try to find how to do it everywhere but I can't find it. This is my code.</p> <pre><code>#include &lt;stdio.h&gt; typedef struct { int site_id_num; int day_of_month[14]; int wind_speed[14]; int temperature[14]; }measured_data_t; int main() { FILE *read; measured_data_t station[5]; read = fopen(&quot;data&quot;, &quot;r&quot;); for(int i = 0; i &lt; 5; i++) { for(int j = 0; j &lt; 14; j++) { fscanf(read, &quot;%d %d %d %d&quot;, station[i].site_id_num, station[i].day_of_month[j], station[i].wind_speed[j], station[i].temperature[j]); } } for(int i = 0; i &lt; 5; i++) { for(int j = 0; j &lt; 14; j++) { printf(&quot;%d %d %d %d\n&quot;, station[i].site_id_num, station[i].day_of_month[j], station[i].wind_speed[j], station[i].temperature[j]); } } fclose(read); return 1; } </code></pre> <p>And this is the text file that I want to read and save into an array of struct.</p> <pre><code>1000 1 6 22 1000 2 9 21 1000 3 15 27 1000 4 24 26 1000 5 11 23 1000 6 24 22 1000 7 21 16 1000 8 10 20 1000 9 22 22 1000 10 3 25 1000 11 14 32 1000 12 23 33 1000 13 4 22 1000 14 25 35 2000 1 13 20 2000 2 1 28 2000 3 18 31 2000 4 2 34 2000 5 4 31 2000 6 18 15 2000 7 10 34 2000 8 14 33 2000 9 12 25 2000 10 11 24 2000 11 6 21 2000 12 12 26 2000 13 17 35 2000 14 20 25 3000 1 5 23 3000 2 17 33 3000 3 20 19 3000 4 7 35 3000 5 17 16 3000 6 2 28 3000 7 13 15 3000 8 23 33 3000 9 19 19 3000 10 16 27 3000 11 21 28 3000 12 22 18 3000 13 11 20 3000 14 1 32 4000 1 10 30 4000 2 2 28 4000 3 24 19 4000 4 11 22 4000 5 25 26 4000 6 1 23 4000 7 24 16 4000 8 13 24 4000 9 23 28 4000 10 2 15 4000 11 3 24 4000 12 7 28 4000 13 17 16 4000 14 10 18 5000 1 12 31 5000 2 10 24 5000 3 3 18 5000 4 25 16 5000 5 14 21 5000 6 11 24 5000 7 15 29 5000 8 4 28 5000 9 2 28 5000 10 22 21 5000 11 9 18 500 12 11 16 5000 13 2 33 5000 14 21 27 </code></pre> <p>I want each station to have id, 14 days, 14 wind speeds, and 14 temperatures. But I have no clues right now. Please help me.</p>
[ { "answer_id": 74631184, "author": "Bodo", "author_id": 10622916, "author_profile": "https://Stackoverflow.com/users/10622916", "pm_score": 0, "selected": false, "text": "main.c: In function ‘main’:\nmain.c:23:28: warning: format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘int’ [-Wformat=]\n 23 | fscanf(read, \"%d %d %d %d\", station[i].site_id_num, station[i].day_of_month[j], station[i].wind_speed[j], station[i].temperature[j]);\n | ~^ ~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | int * int\nmain.c:23:31: warning: format ‘%d’ expects argument of type ‘int *’, but argument 4 has type ‘int’ [-Wformat=]\n & fscanf fscanf(read, \"%d %d %d %d\", &station[i].site_id_num, &station[i].day_of_month[j], &station[i].wind_speed[j], &station[i].temperature[j]);\n *scanf fscanf sscanf char line[100];\n if(fgets(line, sizeof(line), read) == NULL)\n {\n /* handle EOF or error */\n }\n /* check for trailing newline to detect input lines that are too long */\n if(sscanf(line, \"%d %d %d %d\", &station[i].site_id_num, &station[i].day_of_month[j], &station[i].wind_speed[j], &station[i].temperature[j]) != 4)\n {\n /* handle error */\n }\n typedef struct\n{\n int site_id_num;\n struct record {\n int day_of_month;\n int wind_speed;\n int temperature;\n } data[14];\n}measured_data_t;\n" }, { "answer_id": 74631233, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 2, "selected": true, "text": "fscanf() fscanf() #include <stdio.h>\n\ntypedef struct {\n int site_id_num;\n int day_of_month[14];\n int wind_speed[14];\n int temperature[14];\n} measured_data_t;\n\nint main(void) {\n FILE *read = fopen(\"data\", \"r\");\n measured_data_t station[5] = { 0 };\n for(size_t i = 0; i < sizeof station / sizeof *station; i++) {\n for(size_t j = 0; j < sizeof station->day_of_month / sizeof *station->day_of_month; j++) {\n int r = fscanf(read, \"%d %d %d %d\",\n &station[i].site_id_num,\n &station[i].day_of_month[j],\n &station[i].wind_speed[j],\n &station[i].temperature[j]\n );\n if(r != 4) {\n printf(\"fscanf failed\\n\");\n return 1;\n }\n }\n }\n fclose(read);\n\n for(size_t i = 0; i < sizeof station / sizeof *station; i++)\n for(size_t j = 0; j < sizeof station->day_of_month / sizeof *station->day_of_month; j++)\n printf(\"%d %d %d %d\\n\", station[i].site_id_num, station[i].day_of_month[j], station[i].wind_speed[j], station[i].temperature[j]);\n}\n" }, { "answer_id": 74634087, "author": "risbo", "author_id": 10911242, "author_profile": "https://Stackoverflow.com/users/10911242", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct measured_data\n{\n int site_id_num;\n int day_of_month;\n int wind_speed;\n int temperature;\n} measured_data_t;\n\nint main()\n{\n FILE *fp;\n int stations = 5;\n int measurements = 14;\n measured_data_t data[stations * measurements];\n \n\n if( (fp = fopen(\"data\", \"r\")) == NULL )\n {\n printf(\"error opening file\\n\");\n exit(1);\n }\n\n int retv = 0;\n \n for(int i = 0; i < stations * measurements && retv != EOF; i++ )\n { \n retv = fscanf(fp, \"%d %d %d %d\", \n &data[i].site_id_num, \n &data[i].day_of_month, \n &data[i].wind_speed, \n &data[i].temperature);\n \n }\n\n for(int i = 0; i < stations * measurements ; i++ )\n { \n printf( \"%d %d %d %d\\n\", \n data[i].site_id_num, \n data[i].day_of_month, \n data[i].wind_speed, \n data[i].temperature);\n \n }\n\n\n fclose(fp);\n}\n" }, { "answer_id": 74638681, "author": "Elia Karrer", "author_id": 17653989, "author_profile": "https://Stackoverflow.com/users/17653989", "pm_score": 0, "selected": false, "text": "fp = fopen(\"data.bin\", \"wb\");\n\nfor(int i = 0; i < 5; i++)\n fwrite(&station, 1, sizeof(measured_data_t), fp);\n fp = fopen(\"data.bin\", \"rb\");\n\nfor(int i = 0; i < 5; i++)\n fread(&station, 1, sizeof(measured_data_t), fp);\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20079730/" ]
74,630,940
<p>I am trying to trace quadratic bezier curves, placing &quot;markers&quot; at a given step length <code>distance</code>. Tried to do it a naive way:</p> <pre><code> const p = toPoint(map, points[section + 1]); const p2 = toPoint(map, points[section]); const {x: cx, y: cy} = toPoint(map, cp); const ll1 = toLatLng(map, p), ll2 = toLatLng(map, p2), llc = toLatLng(map, { x: cx, y: cy }); const lineLength = quadraticBezierLength( ll1.lat, ll1.lng, llc.lat, llc.lng, ll2.lat, ll2.lng ); for (let index = 0; index &lt; Math.floor(lineLength / distance); index++) { const t = distance / lineLength; const markerPoint = getQuadraticPoint( t * index, p.x, p.y, cx, cy, p2.x, p2.y ); const markerLatLng = toLatLng(map, markerPoint); markers.push(markerLatLng); } </code></pre> <p>This approach does not work since the correlation of a quadratic curve between <code>t</code> and <code>L</code> is not linear. I could not find a formula, that would give me a good approximation, so looking at solving this problem using numeric methods [Newton]. One simple option that I am considering is to split the curve into <code>x</code> [for instance 10] times more pieces than needed. After that, using the same <code>quadraticBezierLength()</code> function calculate the distance to each of those points. After this, chose the point so that the length is closest to the <code>distance * index</code>.</p> <p>This however would be a huge overkill in terms of algorithm complexity. I could probably start comparing points for <code>index + 1</code> from the subset after/without the point I selected already, thus skipping the beginning of the set. This would lower the complexity some, yet still very inefficient.</p> <p>Any ideas and/or suggestions?</p> <p>Ideally, I want a function that would take <code>d</code> - distance along the curve, <code>p0, cp, p1</code> - three points defining a quadratic bezier curve and return an array of coordinates, implemented with the least complexity possible.</p>
[ { "answer_id": 74637798, "author": "Spektre", "author_id": 2521214, "author_profile": "https://Stackoverflow.com/users/2521214", "pm_score": 2, "selected": true, "text": "t //---------------------------------------------------------------------------\nfloat x0,x1,x2,y0,y1,y2; // control points\nfloat ax[3],ay[3]; // coefficients\n//---------------------------------------------------------------------------\nvoid get_xy(float &x,float &y,float t) // get point on curve from parameter t=<0,1>\n {\n float tt=t*t;\n x=ax[0]+(ax[1]*t)+(ax[2]*tt);\n y=ay[0]+(ay[1]*t)+(ay[2]*tt);\n }\n//---------------------------------------------------------------------------\nfloat get_l_naive(float t) // get arclength from parameter t=<0,1>\n {\n // naive iteration\n float x0,x1,y0,y1,dx,dy,l=0.0,dt=0.001;\n get_xy(x1,y1,t);\n for (int e=1;e;)\n {\n t-=dt; if (t<0.0){ e=0; t=0.0; }\n x0=x1; y0=y1; get_xy(x1,y1,t);\n dx=x1-x0; dy=y1-y0;\n l+=sqrt((dx*dx)+(dy*dy));\n }\n return l;\n }\n//---------------------------------------------------------------------------\nfloat get_l(float t) // get arclength from parameter t=<0,1>\n {\n // analytic fomula from: https://stackoverflow.com/a/11857788/2521214\n float ax,ay,bx,by,A,B,C,b,c,u,k,cu,cb;\n ax=x0-x1-x1+x2;\n ay=y0-y1-y1+y2;\n bx=x1+x1-x0-x0;\n by=y1+y1-y0-y0;\n A=4.0*((ax*ax)+(ay*ay));\n B=4.0*((ax*bx)+(ay*by));\n C= (bx*bx)+(by*by);\n b=B/(2.0*A);\n c=C/A;\n u=t+b;\n k=c-(b*b);\n cu=sqrt((u*u)+k);\n cb=sqrt((b*b)+k);\n return 0.5*sqrt(A)*((u*cu)-(b*cb)+(k*log(fabs((u+cu))/(b+cb))));\n }\n//---------------------------------------------------------------------------\nfloat get_t(float l0) // get parameter t=<0,1> from arclength\n {\n float t0,t,dt,l;\n for (t=0.0,dt=0.5;dt>1e-10;dt*=0.5)\n {\n t0=t; t+=dt;\n l=get_l(t);\n if (l>l0) t=t0;\n }\n return t;\n }\n//---------------------------------------------------------------------------\nvoid set_coef() // compute coefficients from control points\n {\n ax[0]= ( x0);\n ax[1]= +(2.0*x1)-(2.0*x0);\n ax[2]=( x2)-(2.0*x1)+( x0);\n ay[0]= ( y0);\n ay[1]= +(2.0*y1)-(2.0*y0);\n ay[2]=( y2)-(2.0*y1)+( y0);\n }\n//---------------------------------------------------------------------------\n x0,y0 t=get_t(wanted_arclength) get_t_naive get_xy set_coef 1e-10 get_l,get_t //---------------------------------------------------------------------------\nfloat get_t(float l0) // get parameter t=<0,1> from arclength\n {\n float t0,t,dt,l;\n float ax,ay,bx,by,A,B,C,b,c,u,k,cu,cb,cA;\n // precompute get_l(t) constants\n ax=x0-x1-x1+x2;\n ay=y0-y1-y1+y2;\n bx=x1+x1-x0-x0;\n by=y1+y1-y0-y0;\n A=4.0*((ax*ax)+(ay*ay));\n B=4.0*((ax*bx)+(ay*by));\n C= (bx*bx)+(by*by);\n b=B/(2.0*A);\n c=C/A;\n k=c-(b*b);\n cb=sqrt((b*b)+k);\n cA=0.5*sqrt(A);\n // bin search t so get_l == l0\n for (t=0.0,dt=0.5;dt>1e-10;dt*=0.5)\n {\n t0=t; t+=dt;\n // l=get_l(t);\n u=t+b; cu=sqrt((u*u)+k);\n l=cA*((u*cu)-(b*cb)+(k*log(fabs((u+cu))/(b+cb))));\n if (l>l0) t=t0;\n }\n return t;\n }\n//---------------------------------------------------------------------------\n" }, { "answer_id": 74645685, "author": "Igor Shmukler", "author_id": 5800846, "author_profile": "https://Stackoverflow.com/users/5800846", "pm_score": 0, "selected": false, "text": " for (let index = 0; index < Math.floor(numFloat * times); index++) {\n const t = distance / lineLength / times;\n const l1 = toLatLng(map, p), lcp = toLatLng(map, new L.Point(cx, cy));\n const lutPoint = getQuadraticPoint(\n t * index,\n p.x,\n p.y,\n cx,\n cy,\n p2.x,\n p2.y\n );\n const lutLatLng = toLatLng(map, lutPoint);\n const length = quadraticBezierLength(l1.lat, l1.lng, lcp.lat, lcp.lng, lutLatLng.lat, lutLatLng.lng);\n lut.push({t: t * index, length});\n }\n const lut1 = lut.filter(({length}) => !isNaN(length));\n console.log('lookup table:', lut1);\n for (let index = 0; index < Math.floor(numFloat); index++) {\n const t = distance / lineLength;\n // find t closest to distance * index\n const markerT = lut1.reduce((a, b) => {\n return a.t && Math.abs(b.length - distance * index) < Math.abs(a.length - distance * index) ? b.t : a.t || 0;\n });\n const markerPoint = getQuadraticPoint(\n markerT,\n p.x,\n p.y,\n cx,\n cy,\n p2.x,\n p2.y\n );\n const markerLatLng = toLatLng(map, markerPoint);\n }\n function quadraticBezierLength(x1, y1, x2, y2, x3, y3) {\n let a, b, c, d, e, u, a1, e1, c1, d1, u1, v1x, v1y;\n\n v1x = x2 * 2;\n v1y = y2 * 2;\n d = x1 - v1x + x3;\n d1 = y1 - v1y + y3;\n e = v1x - 2 * x1;\n e1 = v1y - 2 * y1;\n c1 = a = 4 * (d * d + d1 * d1);\n c1 += b = 4 * (d * e + d1 * e1);\n c1 += c = e * e + e1 * e1;\n c1 = 2 * Math.sqrt(c1);\n a1 = 2 * a * (u = Math.sqrt(a));\n u1 = b / u;\n a = 4 * c * a - b * b;\n c = 2 * Math.sqrt(c);\n return (\n (a1 * c1 + u * b * (c1 - c) + a * Math.log((2 * u + u1 + c1) / (u1 + c))) /\n (4 * a1)\n );\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5800846/" ]
74,630,946
<p>I want to set an image to the button <a href="https://i.stack.imgur.com/xK9eV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xK9eV.jpg" alt="enter image description here" /></a></p> <p>But every time when I add an image to the button it shows a huge image and the image doesn't fit the button size. Like this: <a href="https://i.stack.imgur.com/P4hOa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P4hOa.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74637798, "author": "Spektre", "author_id": 2521214, "author_profile": "https://Stackoverflow.com/users/2521214", "pm_score": 2, "selected": true, "text": "t //---------------------------------------------------------------------------\nfloat x0,x1,x2,y0,y1,y2; // control points\nfloat ax[3],ay[3]; // coefficients\n//---------------------------------------------------------------------------\nvoid get_xy(float &x,float &y,float t) // get point on curve from parameter t=<0,1>\n {\n float tt=t*t;\n x=ax[0]+(ax[1]*t)+(ax[2]*tt);\n y=ay[0]+(ay[1]*t)+(ay[2]*tt);\n }\n//---------------------------------------------------------------------------\nfloat get_l_naive(float t) // get arclength from parameter t=<0,1>\n {\n // naive iteration\n float x0,x1,y0,y1,dx,dy,l=0.0,dt=0.001;\n get_xy(x1,y1,t);\n for (int e=1;e;)\n {\n t-=dt; if (t<0.0){ e=0; t=0.0; }\n x0=x1; y0=y1; get_xy(x1,y1,t);\n dx=x1-x0; dy=y1-y0;\n l+=sqrt((dx*dx)+(dy*dy));\n }\n return l;\n }\n//---------------------------------------------------------------------------\nfloat get_l(float t) // get arclength from parameter t=<0,1>\n {\n // analytic fomula from: https://stackoverflow.com/a/11857788/2521214\n float ax,ay,bx,by,A,B,C,b,c,u,k,cu,cb;\n ax=x0-x1-x1+x2;\n ay=y0-y1-y1+y2;\n bx=x1+x1-x0-x0;\n by=y1+y1-y0-y0;\n A=4.0*((ax*ax)+(ay*ay));\n B=4.0*((ax*bx)+(ay*by));\n C= (bx*bx)+(by*by);\n b=B/(2.0*A);\n c=C/A;\n u=t+b;\n k=c-(b*b);\n cu=sqrt((u*u)+k);\n cb=sqrt((b*b)+k);\n return 0.5*sqrt(A)*((u*cu)-(b*cb)+(k*log(fabs((u+cu))/(b+cb))));\n }\n//---------------------------------------------------------------------------\nfloat get_t(float l0) // get parameter t=<0,1> from arclength\n {\n float t0,t,dt,l;\n for (t=0.0,dt=0.5;dt>1e-10;dt*=0.5)\n {\n t0=t; t+=dt;\n l=get_l(t);\n if (l>l0) t=t0;\n }\n return t;\n }\n//---------------------------------------------------------------------------\nvoid set_coef() // compute coefficients from control points\n {\n ax[0]= ( x0);\n ax[1]= +(2.0*x1)-(2.0*x0);\n ax[2]=( x2)-(2.0*x1)+( x0);\n ay[0]= ( y0);\n ay[1]= +(2.0*y1)-(2.0*y0);\n ay[2]=( y2)-(2.0*y1)+( y0);\n }\n//---------------------------------------------------------------------------\n x0,y0 t=get_t(wanted_arclength) get_t_naive get_xy set_coef 1e-10 get_l,get_t //---------------------------------------------------------------------------\nfloat get_t(float l0) // get parameter t=<0,1> from arclength\n {\n float t0,t,dt,l;\n float ax,ay,bx,by,A,B,C,b,c,u,k,cu,cb,cA;\n // precompute get_l(t) constants\n ax=x0-x1-x1+x2;\n ay=y0-y1-y1+y2;\n bx=x1+x1-x0-x0;\n by=y1+y1-y0-y0;\n A=4.0*((ax*ax)+(ay*ay));\n B=4.0*((ax*bx)+(ay*by));\n C= (bx*bx)+(by*by);\n b=B/(2.0*A);\n c=C/A;\n k=c-(b*b);\n cb=sqrt((b*b)+k);\n cA=0.5*sqrt(A);\n // bin search t so get_l == l0\n for (t=0.0,dt=0.5;dt>1e-10;dt*=0.5)\n {\n t0=t; t+=dt;\n // l=get_l(t);\n u=t+b; cu=sqrt((u*u)+k);\n l=cA*((u*cu)-(b*cb)+(k*log(fabs((u+cu))/(b+cb))));\n if (l>l0) t=t0;\n }\n return t;\n }\n//---------------------------------------------------------------------------\n" }, { "answer_id": 74645685, "author": "Igor Shmukler", "author_id": 5800846, "author_profile": "https://Stackoverflow.com/users/5800846", "pm_score": 0, "selected": false, "text": " for (let index = 0; index < Math.floor(numFloat * times); index++) {\n const t = distance / lineLength / times;\n const l1 = toLatLng(map, p), lcp = toLatLng(map, new L.Point(cx, cy));\n const lutPoint = getQuadraticPoint(\n t * index,\n p.x,\n p.y,\n cx,\n cy,\n p2.x,\n p2.y\n );\n const lutLatLng = toLatLng(map, lutPoint);\n const length = quadraticBezierLength(l1.lat, l1.lng, lcp.lat, lcp.lng, lutLatLng.lat, lutLatLng.lng);\n lut.push({t: t * index, length});\n }\n const lut1 = lut.filter(({length}) => !isNaN(length));\n console.log('lookup table:', lut1);\n for (let index = 0; index < Math.floor(numFloat); index++) {\n const t = distance / lineLength;\n // find t closest to distance * index\n const markerT = lut1.reduce((a, b) => {\n return a.t && Math.abs(b.length - distance * index) < Math.abs(a.length - distance * index) ? b.t : a.t || 0;\n });\n const markerPoint = getQuadraticPoint(\n markerT,\n p.x,\n p.y,\n cx,\n cy,\n p2.x,\n p2.y\n );\n const markerLatLng = toLatLng(map, markerPoint);\n }\n function quadraticBezierLength(x1, y1, x2, y2, x3, y3) {\n let a, b, c, d, e, u, a1, e1, c1, d1, u1, v1x, v1y;\n\n v1x = x2 * 2;\n v1y = y2 * 2;\n d = x1 - v1x + x3;\n d1 = y1 - v1y + y3;\n e = v1x - 2 * x1;\n e1 = v1y - 2 * y1;\n c1 = a = 4 * (d * d + d1 * d1);\n c1 += b = 4 * (d * e + d1 * e1);\n c1 += c = e * e + e1 * e1;\n c1 = 2 * Math.sqrt(c1);\n a1 = 2 * a * (u = Math.sqrt(a));\n u1 = b / u;\n a = 4 * c * a - b * b;\n c = 2 * Math.sqrt(c);\n return (\n (a1 * c1 + u * b * (c1 - c) + a * Math.log((2 * u + u1 + c1) / (u1 + c))) /\n (4 * a1)\n );\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18897610/" ]
74,630,956
<p>I have a small doubt.</p> <p>I have a dataframe where I have one column displaying the hourly time and the columns with the dates, is there a way to put all this together? (In this case using pandas)</p> <p>actual dataframe</p> <p><a href="https://i.stack.imgur.com/WDiOe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WDiOe.png" alt="enter image description here" /></a></p> <p>The desired output</p> <p><a href="https://i.stack.imgur.com/kDM04.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kDM04.png" alt="enter image description here" /></a></p> <p>The dataset</p> <p><a href="https://docs.google.com/spreadsheets/d/1BNPmSZlFHmEkGJC--iBgZiCdM81a5Dt4wj8C8J1pH3A/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1BNPmSZlFHmEkGJC--iBgZiCdM81a5Dt4wj8C8J1pH3A/edit?usp=sharing</a></p>
[ { "answer_id": 74631013, "author": "Chris", "author_id": 4718350, "author_profile": "https://Stackoverflow.com/users/4718350", "pm_score": 3, "selected": true, "text": "pd.melt import pandas as pd\ndf = pd.DataFrame({'August': ['00:00 - 01:00', '01:00 - 02:00', '02:00 - 03:00'], '1/ aug/': ['273,285', '2,708,725', '2,702,913'], '2/ aug/': ['310,135', '2,876,725', '28,409'], '3/ aug/': ['3,077,438', '3,076,075', '307,595'], '4/ aug/': ['2,911,175', '2,876,663', '2,869,738'], '5/ aug/': ['289,075', '2,842,425', '2,839,088']})\n\ndf = df.melt(id_vars='August', var_name='date', value_name='count').rename(columns={'August':'time'})\n\ndf = df[['date','time','count']]\n\nprint(df)\n date time count\n0 1/ aug/ 00:00 - 01:00 273,285\n1 1/ aug/ 01:00 - 02:00 2,708,725\n2 1/ aug/ 02:00 - 03:00 2,702,913\n3 2/ aug/ 00:00 - 01:00 310,135\n4 2/ aug/ 01:00 - 02:00 2,876,725\n5 2/ aug/ 02:00 - 03:00 28,409\n6 3/ aug/ 00:00 - 01:00 3,077,438\n7 3/ aug/ 01:00 - 02:00 3,076,075\n8 3/ aug/ 02:00 - 03:00 307,595\n9 4/ aug/ 00:00 - 01:00 2,911,175\n10 4/ aug/ 01:00 - 02:00 2,876,663\n11 4/ aug/ 02:00 - 03:00 2,869,738\n12 5/ aug/ 00:00 - 01:00 289,075\n13 5/ aug/ 01:00 - 02:00 2,842,425\n14 5/ aug/ 02:00 - 03:00 2,839,088\n" }, { "answer_id": 74631044, "author": "sophocles", "author_id": 9167382, "author_profile": "https://Stackoverflow.com/users/9167382", "pm_score": 1, "selected": false, "text": "stack() df.set_index('August').stack().reset_index().sort_values('level_1').rename(\n {'August':'time','level_1':'date',0:'count'},axis=1)\n\n time Date count\n0 00:00 - 01:00 1/ aug/ 273,285\n5 01:00 - 02:00 1/ aug/ 2,708,725\n10 02:00 - 03:00 1/ aug/ 2,702,913\n1 00:00 - 01:00 2/ aug/ 310,135\n6 01:00 - 02:00 2/ aug/ 2,876,725\n11 02:00 - 03:00 2/ aug/ 28,409\n2 00:00 - 01:00 3/ aug/ 3,077,438\n7 01:00 - 02:00 3/ aug/ 3,076,075\n12 02:00 - 03:00 3/ aug/ 307,595\n3 00:00 - 01:00 4/ aug/ 2,911,175\n8 01:00 - 02:00 4/ aug/ 2,876,663\n13 02:00 - 03:00 4/ aug/ 2,869,738\n4 00:00 - 01:00 5/ aug/ 289,075\n9 01:00 - 02:00 5/ aug/ 2,842,425\n14 02:00 - 03:00 5/ aug/ 2,839,088\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13382780/" ]
74,630,965
<p>If I have a list like</p> <pre><code> [[a, b], [c, d], [e, f]] </code></pre> <p>How would I know that element a is in index 0 of the big list. I'm unsure on how to do this with a 2 dimensional array.</p> <p>I tried to use index, but it not works</p> <pre><code>s = [['a', 'b'], ['c', 'd'], ['e', 'f']] s.index('a') </code></pre> <pre><code>Traceback (most recent call last): File &quot;C:/Users/xxy/PycharmProjects/tb/test.py&quot;, line 3, in &lt;module&gt; s.index('a') ValueError: 'a' is not in list </code></pre>
[ { "answer_id": 74630983, "author": "xingyu xia", "author_id": 20646924, "author_profile": "https://Stackoverflow.com/users/20646924", "pm_score": 2, "selected": true, "text": "s = [['a', 'b'], ['c', 'd'], ['e', 'f']]\nx = 'a'\nfind = False\nfor i, line in enumerate(s):\n if x in line:\n print(f'find {x} at', i, line.index(x))\n find = True\n break\nif not find:\n print(f'{x} is not in list')\n" }, { "answer_id": 74631096, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 0, "selected": false, "text": "any() s = [['a', 'b'], ['c', 'd'], ['e', 'f']]\n\nfor i, v in enumerate(s):\n if any('a' in x for x in v):\n print(i)\n 0\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647609/" ]
74,630,968
<p>I just started learning SQL and there is my problem. I have a column that contains acronyms like &quot;GP2&quot;, &quot;MU1&quot;, &quot;FR10&quot;, .... and I want to add '0's to the acronyms that don't have enough characters.</p> <p>For example I want acronyms like &quot;FR10&quot;, &quot;GP48&quot;,... to stay like this but acronyms like &quot;MU3&quot; must be converted into &quot;MU03&quot; to be as the same size as the others.</p> <p>I already heard about LPAD and RPAD but it just add the wanted character at the left or the right.</p> <p>Thanks !</p>
[ { "answer_id": 74631235, "author": "Isolated", "author_id": 13118009, "author_profile": "https://Stackoverflow.com/users/13118009", "pm_score": 2, "selected": false, "text": "case expression concat with my_data as (\n select 'GP2' as col1 union all\n select 'MU1' union all\n select 'FR10'\n )\nselect col1, \n case\n when length(col1) = 3 then concat(left(col1, 2), '0', right(col1, 1))\n else col1\n end padded_col1\nfrom my_data;\n" }, { "answer_id": 74632284, "author": "Zegarek", "author_id": 5298879, "author_profile": "https://Stackoverflow.com/users/5298879", "pm_score": 0, "selected": false, "text": "regexp_replace() with tests(example) as (values\n('ab02'),('ab1'),('A'),('1'),('A1'),('123'),('ABC'),('abc0'),('a123'),('abcd0123'),('1a'),('a1a'),('1a1') )\nselect example,\n regexp_replace(\n example,\n '^(\\D{0,4})(\\d{0,4})$',\n '\\1' || repeat('0',4-length(example)) || '\\2' )\nfrom tests;\n\n example | regexp_replace\n----------+----------------\n ab02 | ab02\n ab1 | ab01\n A | A000\n 1 | 0001\n A1 | A001\n 123 | 0123\n ABC | ABC0\n abc0 | abc0\n a123 | a123\n abcd0123 | abcd0123 --caught, repeat('0',-4) is same as repeat('0',0), so nothing\n 1a | 1a --doesn't start with non-digits \n a1a | a1a --doesn't end with digits\n 1a1 | 1a1 --doesn't start with non-digits \n\n \\D ^ \\d $ {0,4} () \\1 \\2 repeat()" }, { "answer_id": 74645980, "author": "TRKirua", "author_id": 20647584, "author_profile": "https://Stackoverflow.com/users/20647584", "pm_score": 0, "selected": false, "text": "SELECT CONCAT(LEFT(acronym, 2), LPAD(RIGHT(acronym, LENGTH(acronym) - 2), 2, '0')) AS acronym\nFROM destination\nORDER BY acronym;\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647584/" ]
74,630,969
<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 result = { "records": [ { "recordid": "15986521", "sf_Parent ID": "10156246", "sf_Created Date": "2022-11-30 17:04:45", "sf_Status ID": "64521", "sf_Type ID": "64551", "cf_txtSourceRecordID": "15986054", "sf_Level Two ID": "15986521" } ] } //statement that works if(result &amp;&amp; result.records &amp;&amp; result.records.length &gt; 0) { const getLatestDACCodesID = result.records[0]["sf_Level Two ID"]; console.log('getLatestDACCodesID ',getLatestDACCodesID); } //trying to achieve the same result with Optional chaining (?.) //statement that doesn't works when my result = {}; if(result &amp;&amp; (result?.records)[0]?.["sf_Level Two ID"]) { const getLatestDACCodesID = (result?.records)[0]?.["sf_Level Two ID"]; console.log('getLatestDACCodesID ',getLatestDACCodesID); }</code></pre> </div> </div> </p>
[ { "answer_id": 74631049, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 2, "selected": false, "text": "records undefined const result = {}\n\nif (result && result.records && result.records.length > 0) {\n const getLatestDACCodesID = result.records[0][\"sf_Level Two ID\"];\n console.log('getLatestDACCodesID ', getLatestDACCodesID);\n}\n\nif (result.records?.[0][\"sf_Level Two ID\"]) {\n const getLatestDACCodesID = result.records?.[0][\"sf_Level Two ID\"];\n console.log('getLatestDACCodesID ', getLatestDACCodesID);\n}" }, { "answer_id": 74631084, "author": "Noam Nol", "author_id": 10727283, "author_profile": "https://Stackoverflow.com/users/10727283", "pm_score": 2, "selected": false, "text": "result?.records?.[0]?.[\"sf_Level Two ID\"] ?? \"default\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/603380/" ]
74,630,972
<p>I have a dataframe, about 800,000 rows and 16 columns, below is an example from the data,</p> <pre><code>import pandas as pd import datetime start = datetime.datetime.now() print('Starting time,'+str(start)) dict1 = {'id':['person1','person2','person3','person4','person5'], \ 'food1':['A','A','A','C','D' ], \ 'food2':['B','C','B','A','B'], \ 'food3':['','D','C','',''], 'food4':['','','D','','',] } demo = pd.DataFrame(dict1) demo &gt;&gt;&gt;Out[13] Starting time,2022-11-30 12:08:41.414807 id food1 food2 food3 food4 0 person1 A B 1 person2 A C D 2 person3 A B C D 3 person4 C A 4 person5 D B </code></pre> <p>My ideal result format is as follows,</p> <pre><code>&gt;&gt;&gt;Out[14] A B C D A 0 2 3 2 B 2 0 1 2 C 3 1 0 2 D 2 2 2 0 </code></pre> <p>I did the following:</p> <p>I've searched a bit through stackoverflow, google, but so far haven't come across an answer that helps with my problem.</p> <p>I tried to code it myself, my idea was to first build each pairing, then combine everything into a string, and finally find the number of duplicates, but limited by my code capabilities, it's a work in progress.Also, the &quot;new&quot; combination of the next of one pair and the previous of another pair may cause errors in the process of finding duplicates.</p> <p>Thank you for your help.</p>
[ { "answer_id": 74631049, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 2, "selected": false, "text": "records undefined const result = {}\n\nif (result && result.records && result.records.length > 0) {\n const getLatestDACCodesID = result.records[0][\"sf_Level Two ID\"];\n console.log('getLatestDACCodesID ', getLatestDACCodesID);\n}\n\nif (result.records?.[0][\"sf_Level Two ID\"]) {\n const getLatestDACCodesID = result.records?.[0][\"sf_Level Two ID\"];\n console.log('getLatestDACCodesID ', getLatestDACCodesID);\n}" }, { "answer_id": 74631084, "author": "Noam Nol", "author_id": 10727283, "author_profile": "https://Stackoverflow.com/users/10727283", "pm_score": 2, "selected": false, "text": "result?.records?.[0]?.[\"sf_Level Two ID\"] ?? \"default\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20023326/" ]
74,630,987
<p>I was following a tutorial to learn to react. In this tutorial, they asked me to do an information page and add some styling to this page. When I hard coded the styles inside my index.js there will be no problem but when I want to use separate Style.css I can't import it. I don't know why. All files are on the same level.</p> <pre><code>import'./Style.css'; // Children Components function Header() { return ( &lt;div&gt; &lt;header&gt; &lt;nav className=&quot;header&quot;&gt; &lt;div&gt;&lt;img src=&quot;images.png&quot; width=&quot;80px&quot;&gt;&lt;/img&gt;&lt;/div&gt; &lt;div&gt;&lt;h1&gt;RedCloud&lt;/h1&gt;&lt;/div&gt; &lt;div &gt;&lt;ul className=&quot;navitems&quot;&gt; &lt;div &gt;&lt;li&gt;Home&lt;/li&gt;&lt;/div&gt; &lt;div &gt;&lt;li&gt;Profile&lt;/li&gt;&lt;/div&gt; &lt;div &gt;&lt;li&gt;Movies&lt;/li&gt;&lt;/div&gt; &lt;/ul&gt;&lt;/div&gt; &lt;/nav&gt; &lt;/header&gt; &lt;/div&gt; ) } //parent function Page() { return ( &lt;div&gt; &lt;Header /&gt; &lt;/div&gt; ) } ReactDOM.render(&lt;Page /&gt;, document.getElementById(&quot;root&quot;)); </code></pre> <p>For ReactDOM I am using CDNs which I am calling them in HTML file instead of importing them. And this is my CSS file.</p> <pre><code>.header { display: &quot;flex&quot;; } .navitems{ display: &quot;flex&quot;; list-style: none; justify-content:'space-between'; } .navitems &gt; div{ padding:&quot;10px&quot;; justify-content:'space-between'; } </code></pre> <p>I don't know why but it seems like I can not import Style.css. And below I added my HTML file for extra. Thank you.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Document&lt;/title&gt; &lt;link href=&quot;/Style.css&quot;&gt; &lt;script crossorigin src=&quot;https://unpkg.com/react@18/umd/react.development.js&quot;&gt;&lt;/script&gt; &lt;script crossorigin src=&quot;https://unpkg.com/react-dom@18/umd/react-dom.development.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://unpkg.com/babel-standalone@6/babel.min.js&quot;&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;root&quot;&gt;&lt;/div&gt; &lt;script src=&quot;index.js&quot; type=&quot;text/babel&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <pre><code>{ &quot;dependencies&quot;: { &quot;css&quot;: &quot;^2.2.1&quot;, &quot;react&quot;: &quot;^18.2.0&quot;, &quot;react-dom&quot;: &quot;^18.2.0&quot; }, &quot;devDependencies&quot;: { &quot;css-loader&quot;: &quot;^6.7.2&quot;, &quot;style-loader&quot;: &quot;^3.3.1&quot; } } </code></pre> <p>I double checked the file name, pathing, unsaved files and correct naming of the attributes.</p>
[ { "answer_id": 74631049, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 2, "selected": false, "text": "records undefined const result = {}\n\nif (result && result.records && result.records.length > 0) {\n const getLatestDACCodesID = result.records[0][\"sf_Level Two ID\"];\n console.log('getLatestDACCodesID ', getLatestDACCodesID);\n}\n\nif (result.records?.[0][\"sf_Level Two ID\"]) {\n const getLatestDACCodesID = result.records?.[0][\"sf_Level Two ID\"];\n console.log('getLatestDACCodesID ', getLatestDACCodesID);\n}" }, { "answer_id": 74631084, "author": "Noam Nol", "author_id": 10727283, "author_profile": "https://Stackoverflow.com/users/10727283", "pm_score": 2, "selected": false, "text": "result?.records?.[0]?.[\"sf_Level Two ID\"] ?? \"default\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74630987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15477041/" ]
74,631,005
<p>I'm wondering how to stop counting money (iloscPieniedzy) when HP (iloscZycia) is 0 in this code:</p> <pre><code>let iloscZycia = 20; const sumaZycia = document.getElementById(&quot;suma-zycia&quot;); const dodajZycie = document.getElementById('dodaj-zycie'); const odejmijZycie = document.getElementById('odejmij-zycie'); dodajZycie.addEventListener(&quot;click&quot;, function() { iloscZycia++; sumaZycia.textContent = iloscZycia; }); odejmijZycie.addEventListener(&quot;click&quot;, function() { iloscZycia = iloscZycia - 5; if (iloscZycia &lt;= 0) { iloscZycia = 0 }; sumaZycia.textContent = iloscZycia; }); let iloscPieniedzy = 0; const sumaPieniedzy = document.getElementById(&quot;suma-pieniedzy&quot;); const dodajPieniadze = document.getElementById('dodaj-pieniadze'); const odejmijPieniadze = document.getElementById('odejmij-pieniadze'); dodajPieniadze.addEventListener(&quot;click&quot;, function() { iloscPieniedzy = iloscPieniedzy + 10; sumaPieniedzy.textContent = iloscPieniedzy; }); odejmijPieniadze.addEventListener(&quot;click&quot;, function() { iloscPieniedzy = iloscPieniedzy - 1; if (iloscPieniedzy &lt;= 0) { iloscPieniedzy = 0 }; sumaPieniedzy.textContent = iloscPieniedzy; }); </code></pre> <p>I tried something like this:</p> <pre><code>if (sumaZycia=0){ sumaPieniedzy=0 }; </code></pre> <p>but even this doesn't work like it's not connected.</p>
[ { "answer_id": 74631170, "author": "SalahM", "author_id": 13560490, "author_profile": "https://Stackoverflow.com/users/13560490", "pm_score": 1, "selected": false, "text": "if (iloscZycia === 0){\n iloscPieniedzy = 0\n};\n" }, { "answer_id": 74631455, "author": "jsejcksn", "author_id": 438273, "author_profile": "https://Stackoverflow.com/users/438273", "pm_score": 1, "selected": true, "text": "0 // hp: iloscZycia\n// element1: sumaZycia\n// element2: dodajZycie\n// element3: odejmijZycie\n\n// money: iloscPieniedzy\n// element4: sumaPieniedzy\n// element5: dodajPieniadze\n// element6: odejmijPieniadze\n\nlet hp = 20;\n\nconst adjustHp = (amount) => {\n hp += amount;\n if (hp < 0) hp = 0;\n\n element1.textContent = hp;\n};\n\nconst element1 = document.getElementById(\"suma-zycia\");\nconst element2 = document.getElementById(\"dodaj-zycie\");\nconst element3 = document.getElementById(\"odejmij-zycie\");\n\nelement1.textContent = hp;\n\nelement2.addEventListener(\"click\", () => adjustHp(1));\nelement3.addEventListener(\"click\", () => adjustHp(-5));\n\nlet money = 0;\n\nconst adjustMoney = (amount) => {\n // Update money, but ONLY if hp is not 0:\n if (hp !== 0) {\n money += amount;\n if (money < 0) money = 0;\n }\n\n element4.textContent = money;\n};\n\nconst element4 = document.getElementById(\"suma-pieniedzy\");\nconst element5 = document.getElementById(\"dodaj-pieniadze\");\nconst element6 = document.getElementById(\"odejmij-pieniadze\");\n\nelement4.textContent = money;\n\nelement5.addEventListener(\"click\", () => adjustMoney(10));\nelement6.addEventListener(\"click\", () => adjustMoney(-1)); .group { display: flex; gap: 0.5rem; } <h2>HP</h2>\n<div class=\"group\">\n <button id=\"odejmij-zycie\">-</button>\n <div id=\"suma-zycia\">0</div>\n <button id=\"dodaj-zycie\">+</button>\n</div>\n\n<h2>Money</h2>\n<div class=\"group\">\n <button id=\"odejmij-pieniadze\">-</button>\n <div id=\"suma-pieniedzy\">0</div>\n <button id=\"dodaj-pieniadze\">+</button>\n</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647589/" ]
74,631,066
<p>I have created an expandable toolbar that also contains a bootstrap dropdown component. I need this toolbar to be a fixed height, with all components that extend beyond the toolbar size to be hidden (except for popups). So I have applied <code>overflow:hidden</code> to that toolbar container. However, this has the undesired effect of hiding part of the dropdown when it is expanded. Is there a way that I can prevent this dropdown from getting clipped?</p> <p>My main concern is the vertical clipping, not the horizontal clipping.</p> <p>I have tried adjusting the <code>z-index</code> as shown in the example without success.</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>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"&gt;&lt;/script&gt; &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;html&gt; &lt;body&gt; &lt;div style='position:absolute;top:12px;left:12px;width:300px;height:100px;border:solid 1px #888;overflow:hidden;'&gt; &lt;div class="input-group" style='z-index:9998;'&gt; &lt;input type="text" class="form-control" aria-label="Text input with dropdown button"&gt; &lt;div class="input-group-append"&gt; &lt;button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false"&gt;Dropdown&lt;/button&gt; &lt;div class="dropdown-menu dropdown-menu-right" style='z-index:9999;'&gt; &lt;a class="dropdown-item" href="#"&gt;Action&lt;/a&gt; &lt;a class="dropdown-item" href="#"&gt;Another action&lt;/a&gt; &lt;a class="dropdown-item" href="#"&gt;Something else here&lt;/a&gt; &lt;div role="separator" class="dropdown-divider"&gt;&lt;/div&gt; &lt;a class="dropdown-item" href="#"&gt;Separated link&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt; Expandable toolbar here. Expandable toolbar here. Expandable toolbar here. Expandable toolbar here. Expandable toolbar here. Expandable toolbar here. Expandable toolbar here. Expandable toolbar here. Expandable toolbar here. Expandable toolbar here. Expandable toolbar here. Expandable toolbar here. &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>The example provided is just a minimal example. Below shows screenshots of the real toolbar, to provide context. <a href="https://i.stack.imgur.com/wVfj9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wVfj9.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74633126, "author": "Seyfullah Akgun", "author_id": 18068342, "author_profile": "https://Stackoverflow.com/users/18068342", "pm_score": -1, "selected": false, "text": "<div class=\"dropdown-menu dropdown-menu-right\" style='z-index:9999; height: 50px; max-height: 100px; overflow: hidden;'>\n <a class=\"dropdown-item\" href=\"#\">Action</a>\n <a class=\"dropdown-item\" href=\"#\">Another action</a>\n <a class=\"dropdown-item\" href=\"#\">Something else here</a>\n <div role=\"separator\" class=\"dropdown-divider\"></div>\n <a class=\"dropdown-item\" href=\"#\">Separated link</a>\n</div>" }, { "answer_id": 74633511, "author": "fnostro", "author_id": 1971438, "author_profile": "https://Stackoverflow.com/users/1971438", "pm_score": 0, "selected": false, "text": "data-boundary=\"viewport\" overflow function toggle(e) {\n let o = document.getElementById(\"thing1\")\n o.classList.toggle(\"opened\");\n} .SomeCustomNav {\n display: flex;\n align-items: stretch;\n justify-content: space-between;\n flex-direction: column;\n width: 600px;\n height: 100%;\n border: solid 1px red;\n}\n\n.SomeCustomNavRow {\n display: flex;\n gap: 8px;\n flex-flow: row nowrap;\n align-items: stretch;\n justify-content: space-between;\n}\n\n.MiniContent {\n position: relative;\n border: dashed 1px grey;\n}\n\n.MiniContent.A {\n flex: 1 1 70%;\n height: 100px;\n overflow: hidden;\n}\n\n.MiniContent.A.opened {\n height: 200px;\n overflow: visible;\n}\n\n.MiniContent.B {\n flex: 1 1 30%;\n height: 100px;\n}\n\n.CustomDropdownControl {\n margin-top: 10px;\n display: flex;\n flex-flow: column;\n width: 300px;\n border: solid 1px blue;\n}\n\n.text-and-dropdown {\n flex: 1 0 auto;\n}\n\n.expandable-toolbar {\n overflow: hidden;\n flex: 0 1 auto;\n border: solid 1px #888;\n}\n\n#T {\n position: absolute;\n top: 0;\n right: 0\n}\n\n.fakewrapper {\n display: flex;\n flex-wrap: wrap;\n align-items: stretch;\n justify-content: space-between;\n width: 300px;\n}\n\n.fake {\n width: 45%;\n height: 50px;\n flex: 1 1 auto;\n border: 1px dashed green;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js\"></script>\n<link href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" />\n<html>\n\n<body>\n <div class=\"SomeCustomNav\">\n <div class=\"SomeCustomNavRow\">\n <div id=\"thing1\" class=\"MiniContent A\">\n <button id=\"T\" type=\"button\" onclick=\"toggle(event)\">toggle</button>\n <div class=\"fakewrapper\">\n <div class=\"fake\">A</div>\n <div class=\"fake\">B</div>\n <div class=\"fake\">C</div>\n <div class=\"fake\">D</div>\n </div>\n\n <div class=\"CustomDropdownControl\">\n <div class=\"text-and-dropdown\">\n <div class=\"input-group\" style='z-index:9998;'>\n <input type=\"text\" class=\"form-control\" aria-label=\"Text input with dropdown button\">\n <div class=\"input-group-append\">\n <button class=\"btn btn-outline-secondary dropdown-toggle\" type=\"button\" data-toggle=\"dropdown\" data-boundary=\"viewport\" aria-expanded=\"false\">Dropdown</button>\n <div class=\"dropdown-menu dropdown-menu-right\" style='z-index:9999;'>\n <a class=\"dropdown-item\" href=\"#\">Action</a>\n <a class=\"dropdown-item\" href=\"#\">Another action</a>\n <a class=\"dropdown-item\" href=\"#\">Something else here</a>\n <div role=\"separator\" class=\"dropdown-divider\"></div>\n <a class=\"dropdown-item\" href=\"#\">Separated link</a>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n <div class=\"MiniContent B\">Other stuff</div>\n </div>\n\n </div>\n</body>\n\n</html>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7411852/" ]
74,631,072
<p>Ok so I have a list of the same dictionaries and I want to get the values of the dictionaries into a list of lists. For example this is what one dictionary might look like:</p> <p><code>mylist = [{'a': 0, 'b': 2},{'a':1, 'b':3}]</code></p> <p>I want the lists of lists to look like:</p> <p><code>[[0,2],[1,3]]</code></p> <p>I have tried doing</p> <p><code>zip(*[d.values() for d in mylist])</code></p> <p>however this results in a list of different keys for example:</p> <p><code>[[0,1],[2,3]]</code></p>
[ { "answer_id": 74631185, "author": "ViktorGlushak", "author_id": 11663862, "author_profile": "https://Stackoverflow.com/users/11663862", "pm_score": 1, "selected": false, "text": "[list(i.values()) for i in mylist]" }, { "answer_id": 74631207, "author": "realhuman", "author_id": 15690172, "author_profile": "https://Stackoverflow.com/users/15690172", "pm_score": 3, "selected": true, "text": "zip() [list(i.values()) for i in mylist] list() .values()" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15972232/" ]
74,631,074
<p>I have two properties in my application properties and trying to overwrite them from command line arguments , but its not overwriting, I have checked the variable name/etc . all is fine but still isn't being overwritten. Please note: it was being overwritten earlier suddenly it stopped.</p> <pre><code>application.properties: com.records=default com.count=default </code></pre> <p>Command used to run from command line is: java -jar myJarname.jar &quot;--com.records=10 --com.count=10&quot;</p> <p>Also, my program works perfectly fine when i try to overwrite just one command line argument and its able to do so. But when i try to over write application.properties with multiple command line arguments , it fails.</p>
[ { "answer_id": 74633383, "author": "Elmer homero", "author_id": 20638963, "author_profile": "https://Stackoverflow.com/users/20638963", "pm_score": 1, "selected": false, "text": "java -Dcom.records=10 -Dcom.count=10 -jar myJarname.jar\n java -Dspring-boot.run.arguments=\"--com.records=10,--com.count=10\" -jar myJarname.jar\n -jar" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17198927/" ]
74,631,118
<p>I have a <strong>container</strong> <code>div</code> set to <code>width: 1000px</code> and <code>height: 500px</code>. Inside it there is an <strong>innner</strong> <code>div</code> set to <code>width: 200%</code> and <code>height: 100%</code> which makes <strong>container</strong> overflow horizontally.</p> <p>The thing is, when I scale <strong>inner</strong> to double in the X axis, <strong>container</strong> suddenly doesn't show the first part of <strong>inner</strong> and I can't scroll enough to see it.</p> <p>I gave <strong>inner</strong> a background separated by colors to make it more understandable, when scaled, the blue section (which is the first one) isn't viewable anymore.</p> <p>How can I make <strong>container</strong> to scroll enough to see the entire blue part? Here is the HTML and CSS</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>.container { width: 1000px; height: 500px; overflow: auto; } .inner { width: 200%; height: 100%; background-image: linear-gradient(90deg, lightblue 0% 25%, yellow 25% 50%, lime 50% 75%, orange 75% 100%); transform: scaleX(2) }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="inner"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74631232, "author": "jerry", "author_id": 20493210, "author_profile": "https://Stackoverflow.com/users/20493210", "pm_score": 0, "selected": false, "text": ".container {\n width: 1000px;\n height: 500px;\n overflow: auto;\n }\n\n .inner {\n width: 200%;\n height: 100%;\n background-image: linear-gradient(\n 90deg,\n lightblue 0% 25%,\n yellow 25% 50%,\n lime 50% 75%,\n orange 75% 100%\n );\n\n transform: translateX(50%) scaleX(2);\n } <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Document</title>\n </head>\n <body>\n <div class=\"container\">\n <div class=\"inner\"></div>\n </div>\n </body>\n</html>" }, { "answer_id": 74631526, "author": "Anas Mohammad Sheikh", "author_id": 18045679, "author_profile": "https://Stackoverflow.com/users/18045679", "pm_score": 2, "selected": true, "text": "transform-origin: left;\n .container {\n width: 1000px;\n height: 500px;\n\n overflow: auto;\n}\n\n.inner {\n width: 200%;\n height: 100%;\n\n background-image: linear-gradient(\n 90deg,\n lightblue 0% 25%,\n yellow 25% 50%,\n lime 50% 75%,\n orange 75% 100%\n );\n\n transform: scaleX(2);\n transform-origin: left;\n} <div class=\"container\">\n <div class=\"inner\"></div>\n</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19889695/" ]
74,631,165
<p>how can i get a signal that my external agenda in my own app needs to be updated when there is a new event been made. at this moment my code looks like this but i can't retrieve a new event from google calendar. what do i do wrong.</p> <pre><code>public async Task&lt;List&lt;EventModel&gt;&gt; GetAllEventsAsync() { var refresToken = RetrieveRefreshTokenAndRevoke.RefreshToken(); if (refresToken == &quot;ok&quot;) { var tokens = JObject.Parse(System.IO.File.ReadAllText(ConstantJsonFileLink.TOKEN)); RestClient restClient = new RestClient(new Uri(&quot;https://www.googleapis.com/calendar/v3/calendars/primary/events&quot;)); RestRequest restRequest = new RestRequest(Method.GET); restRequest.AddQueryParameter(&quot;key&quot;, $&quot;{ApiKey}&quot;); restRequest.AddHeader(&quot;Authorization&quot;, &quot;Bearer &quot; + tokens[&quot;access_token&quot;]); restRequest.AddHeader(&quot;Accept&quot;, &quot;application/json&quot;); try { var response = await restClient.ExecuteAsync(restRequest); if (response.StatusCode == System.Net.HttpStatusCode.OK) { JObject calendarEvents = JObject.Parse(response.Content); var allEvents = calendarEvents[&quot;items&quot;].ToObject&lt;List&lt;EventModel&gt;&gt;(); return allEvents; } } catch (Exception ex) { throw new Exception(&quot;Coulden't connect to google agenda.&quot;); } } return null; } </code></pre>
[ { "answer_id": 74631232, "author": "jerry", "author_id": 20493210, "author_profile": "https://Stackoverflow.com/users/20493210", "pm_score": 0, "selected": false, "text": ".container {\n width: 1000px;\n height: 500px;\n overflow: auto;\n }\n\n .inner {\n width: 200%;\n height: 100%;\n background-image: linear-gradient(\n 90deg,\n lightblue 0% 25%,\n yellow 25% 50%,\n lime 50% 75%,\n orange 75% 100%\n );\n\n transform: translateX(50%) scaleX(2);\n } <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Document</title>\n </head>\n <body>\n <div class=\"container\">\n <div class=\"inner\"></div>\n </div>\n </body>\n</html>" }, { "answer_id": 74631526, "author": "Anas Mohammad Sheikh", "author_id": 18045679, "author_profile": "https://Stackoverflow.com/users/18045679", "pm_score": 2, "selected": true, "text": "transform-origin: left;\n .container {\n width: 1000px;\n height: 500px;\n\n overflow: auto;\n}\n\n.inner {\n width: 200%;\n height: 100%;\n\n background-image: linear-gradient(\n 90deg,\n lightblue 0% 25%,\n yellow 25% 50%,\n lime 50% 75%,\n orange 75% 100%\n );\n\n transform: scaleX(2);\n transform-origin: left;\n} <div class=\"container\">\n <div class=\"inner\"></div>\n</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20165469/" ]
74,631,218
<p>I am an experienced java enterprise developer but very new to python enterprise development shop. I am currently, struggling to understand why some imports work while others don't.</p> <p>Some background: Our dev team recently upgraded python from 3.6 to 3.10.5 and following is our package structure</p> <pre><code>src/ bunch of files (dockerfile, Pipfile, requrirements.txt, shell scripts, etc) package/ __init__.py moduleA.py subpackage1/ __init__.py moduleX.py moduleY.py subpackage2/ __init__.py moduleZ.py tests/ __init__.py test1.py </code></pre> <p>Now, inside the moduleA.py, I am trying to import subpackage2/moduleZ.py like so</p> <pre><code>from .subpackage2 import moduleZ </code></pre> <p>But, I get the error saying</p> <pre><code>ImportError: attempted relative import with no known parent package </code></pre> <p>The funny thing is that if I move moduleA.py out of package/ and into src/ then it is able to find everything. I am not sure why is this the case.</p> <p>I run the moduleA.py by executiong python package/moduleA.py.</p> <p>Now, I read that maybe there is a problem becasue you have you give a -m parameter if running a module as a script (or something on those lines). But, if I do that, I get the following error:</p> <pre><code>ModuleNotFoundError: No module names 'package/moduleA.py' </code></pre> <p>I even try running package1/moduleA and remove the .py, but that does not work either. I can understand why as I technically never installed it ?</p> <p>All of this happened because apparently, the tests broke and to make it work they added relative imports. They changed the import from &quot;from subpackage2 import moduleZ&quot; to &quot;from .subpackage2 import moduleZ&quot; and the tests started working, but the app started failing.</p> <p>Any understanding I can get would be much appreciated.</p>
[ { "answer_id": 74631328, "author": "ShadowRanger", "author_id": 364696, "author_profile": "https://Stackoverflow.com/users/364696", "pm_score": 3, "selected": true, "text": "-m python3 -m package.moduleA . / .py python3 -m package/moduleA.py package.moduleA sys.path src package $ cd path/to/src\n$ python3 -m package.moduleA\n moduleA.py from .subpackage2 import moduleZ package.moduleA package moduleA subpackage2 moduleZ cd src src PYTHONPATH site-packages site-packages venv virtualenv site-packages sys.path -m" }, { "answer_id": 74631627, "author": "Ivan Perehiniak", "author_id": 20637117, "author_profile": "https://Stackoverflow.com/users/20637117", "pm_score": 0, "selected": false, "text": "from package.moduleA import *\nfrom package.subpackage1.moduleX import *\n # this is inside moduleX\nfrom package.subpackage1.moduleY import *\n import sys\nfor p in sys.path:\n print(p)\n new_path = \"/path/to/application/app/folder/src/package/subpackage1\"\nif new_path not in sys.path:\n sys.path.append(new_path)\n from package.subpackage1.moduleX import *\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3792396/" ]
74,631,243
<pre><code>void main(char *param_1) { long lVar1; int iVar2; lVar1 = strtol(param_1,(char **)0x0,10); if (1000 &lt; lVar1 - 1U) { } iVar2 = fun9(n1,lVar1); if (iVar2 == 2) { return; } } </code></pre> <p>Trying to backwards engineer but stuck on this. Some of the variables don't make sense so hard to understand what the output will be. Trying to use test cases but those aren't going through either.</p>
[ { "answer_id": 74631506, "author": "Ali Hassan", "author_id": 17962313, "author_profile": "https://Stackoverflow.com/users/17962313", "pm_score": -1, "selected": false, "text": "int main () {\n char str[30] = \"2030300 This is test\";\n char *ptr;\n long ret;\n\n ret = strtol(str, &ptr, 10);\n printf(\"The number(unsigned long integer) is %ld\\n\", ret);\n printf(\"String part is |%s|\", ptr);\n\n return(0);\n}\n" }, { "answer_id": 74631615, "author": "Jerry Coffin", "author_id": 179910, "author_profile": "https://Stackoverflow.com/users/179910", "pm_score": 0, "selected": false, "text": "main int main(void) { /* ... */ }\n argc argv int main(int argc, char *argv[]) { /* ... */ }\n int typedef int argv char ** argv void main(char *param_1) main void if if (1000 < lVar1 - 1U) {\n }\n {} if return void main(char *param_1)\n\n{\n long lVar1;\n int iVar2;\n \n lVar1 = strtol(param_1,(char **)0x0,10);\n iVar2 = fun9(n1,lVar1);\n}\n fun9 void main(char *param_1) {\n long lVar1 = strtol(param_1,(char **)0x0,10);\n}\n 0x0 long lvar1 = strtol(parm_1, NULL, 10) param_1 lvar1 fun9" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647708/" ]
74,631,268
<p>i am relative new to typescript (coming from java) and i have currently the following problem:</p> <p><strong>Given:</strong> String with a length of 3, it can only contain the charts '0', '1' and '2'. Each of them are representing a different state. Lets assume here the following: '0' -&gt; 'no', '1' -&gt; 'yes', '2' -&gt; 'unknown'. What is the most readable and simplified way to implement it? Currently i am just using simple if functions which are checking what state i have at every index, like:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let state: 'no' | 'yes' | 'unknown'; if (input[1] === '0') { state = 'locked'; } else if (input[1] === '1') { state = 'unlocked'; } else { state = 'unknown'; }</code></pre> </div> </div> Because i am still new into Typescript i don't know if there is a better way to do that in Typescript :/</p> <p>Thanks :)</p>
[ { "answer_id": 74631506, "author": "Ali Hassan", "author_id": 17962313, "author_profile": "https://Stackoverflow.com/users/17962313", "pm_score": -1, "selected": false, "text": "int main () {\n char str[30] = \"2030300 This is test\";\n char *ptr;\n long ret;\n\n ret = strtol(str, &ptr, 10);\n printf(\"The number(unsigned long integer) is %ld\\n\", ret);\n printf(\"String part is |%s|\", ptr);\n\n return(0);\n}\n" }, { "answer_id": 74631615, "author": "Jerry Coffin", "author_id": 179910, "author_profile": "https://Stackoverflow.com/users/179910", "pm_score": 0, "selected": false, "text": "main int main(void) { /* ... */ }\n argc argv int main(int argc, char *argv[]) { /* ... */ }\n int typedef int argv char ** argv void main(char *param_1) main void if if (1000 < lVar1 - 1U) {\n }\n {} if return void main(char *param_1)\n\n{\n long lVar1;\n int iVar2;\n \n lVar1 = strtol(param_1,(char **)0x0,10);\n iVar2 = fun9(n1,lVar1);\n}\n fun9 void main(char *param_1) {\n long lVar1 = strtol(param_1,(char **)0x0,10);\n}\n 0x0 long lvar1 = strtol(parm_1, NULL, 10) param_1 lvar1 fun9" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6145451/" ]
74,631,274
<p>I have a React app that I'm trying to Dockerize. Here is my Dockerfile and docker-compose:</p> <pre><code>FROM node:16.13.1 WORKDIR /app ENV PATH /app/node_modules/.bin:$PATH COPY package.json . COPY package-lock.json . RUN mkdir -p node_modules/node-sass/vendor/linux-x64-93 RUN curl -L https://github.com/sass/node-sass/releases/download/v7.0.1/linux-x64-93_binding.node -o node_modules/node-sass/vendor/linux-x64-93/binding.node RUN npm install -g npm@9.1.2 RUN npm install react-scripts@5.0.0 -g RUN npm rebuild node-sass COPY . . EXPOSE 3000 CMD \[&quot;npm&quot;, &quot;start&quot;\] </code></pre> <pre class="lang-yaml prettyprint-override"><code>version: &quot;3.8&quot; services: web-cnss: build: './editor' ports: [ &quot;3000:3000&quot; ] container_name: WEB-CNSS volumes: - '/app/node_modules' </code></pre> <p>Somehow I need to specify the npm version and also install react-scripts, otherwise it gives an error in another computer. Besides this, in my computer everything works well, however, my objective is that anyone can clone my project and build it by just simply running &quot;docker-compose up&quot;.</p> <p>I tested it on my colleague's computer, and this was the error:</p> <pre><code>Error: Cannot find module 'react' WEB-CNSS | Require stack: WEB-CNSS | - /usr/local/lib/node_modules/react-scripts/scripts/start.js WEB-CNSS | at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15) WEB-CNSS | at Function.resolve (node:internal/modules/cjs/helpers:108:19) WEB-CNSS | at Object.&lt;anonymous&gt; (/usr/local/lib/node_modules/react-scripts/scripts/start.js:43:31) WEB-CNSS | at Module._compile (node:internal/modules/cjs/loader:1101:14) WEB-CNSS | at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) WEB-CNSS | at Module.load (node:internal/modules/cjs/loader:981:32) WEB-CNSS | at Function.Module._load (node:internal/modules/cjs/loader:822:12) WEB-CNSS | at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) WEB-CNSS | at node:internal/main/run_main_module:17:47 { WEB-CNSS | code: 'MODULE_NOT_FOUND', WEB-CNSS | requireStack: [ '/usr/local/lib/node_modules/react-scripts/scripts/start.js' ] WEB-CNSS | } </code></pre> <p>Maybe it is my package.json that has some errors, so here it is as well:</p> <pre><code>{ &quot;name&quot;: &quot;editor&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;private&quot;: true, &quot;dependencies&quot;: { &quot;@babel/runtime&quot;: &quot;^7.18.3&quot;, &quot;@convergence/convergence&quot;: &quot;^1.0.0-rc.12&quot;, &quot;@testing-library/jest-dom&quot;: &quot;^5.16.4&quot;, &quot;@testing-library/react&quot;: &quot;^12.1.4&quot;, &quot;@testing-library/user-event&quot;: &quot;^13.5.0&quot;, &quot;ace-builds&quot;: &quot;^1.4.14&quot;, &quot;bootstrap&quot;: &quot;^5.1.3&quot;, &quot;dropzone&quot;: &quot;^6.0.0-beta.2&quot;, &quot;easymde&quot;: &quot;^2.16.0&quot;, &quot;node-sass&quot;: &quot;^7.0.1&quot;, &quot;react&quot;: &quot;^18.0.0&quot;, &quot;react-ace&quot;: &quot;^9.5.0&quot;, &quot;react-bootstrap&quot;: &quot;^2.2.3&quot;, &quot;react-dom&quot;: &quot;^18.0.0&quot;, &quot;react-drag-drop-files&quot;: &quot;^2.3.7&quot;, &quot;react-dropzone&quot;: &quot;^14.2.2&quot;, &quot;react-pro-sidebar&quot;: &quot;^0.7.1&quot;, &quot;react-scripts&quot;: &quot;5.0.0&quot;, &quot;react-simplemde-editor&quot;: &quot;^5.0.2&quot;, &quot;react-sticky-box&quot;: &quot;^1.0.2&quot;, &quot;simplemde&quot;: &quot;^1.11.2&quot;, &quot;web-vitals&quot;: &quot;^2.1.4&quot; }, &quot;scripts&quot;: { &quot;predeploy&quot;: &quot;npm run build&quot;, &quot;deploy&quot;: &quot;gh-pages -d build&quot;, &quot;start&quot;: &quot;react-scripts start&quot;, &quot;build&quot;: &quot;react-scripts build&quot;, &quot;test&quot;: &quot;react-scripts test&quot;, &quot;eject&quot;: &quot;react-scripts eject&quot; }, &quot;eslintConfig&quot;: { &quot;extends&quot;: [ &quot;react-app&quot;, &quot;react-app/jest&quot; ] }, &quot;browserslist&quot;: { &quot;production&quot;: [ &quot;&gt;0.2%&quot;, &quot;not dead&quot;, &quot;not op_mini all&quot; ], &quot;development&quot;: [ &quot;last 1 chrome version&quot;, &quot;last 1 firefox version&quot;, &quot;last 1 safari version&quot; ] }, &quot;devDependencies&quot;: { &quot;@convergencelabs/ace-collab-ext&quot;: &quot;^0.6.0&quot;, &quot;gh-pages&quot;: &quot;^4.0.0&quot; } } </code></pre> <p>I also tested the answers on another similar questions posted here on StackOverflow, but they didn't work.</p>
[ { "answer_id": 74631506, "author": "Ali Hassan", "author_id": 17962313, "author_profile": "https://Stackoverflow.com/users/17962313", "pm_score": -1, "selected": false, "text": "int main () {\n char str[30] = \"2030300 This is test\";\n char *ptr;\n long ret;\n\n ret = strtol(str, &ptr, 10);\n printf(\"The number(unsigned long integer) is %ld\\n\", ret);\n printf(\"String part is |%s|\", ptr);\n\n return(0);\n}\n" }, { "answer_id": 74631615, "author": "Jerry Coffin", "author_id": 179910, "author_profile": "https://Stackoverflow.com/users/179910", "pm_score": 0, "selected": false, "text": "main int main(void) { /* ... */ }\n argc argv int main(int argc, char *argv[]) { /* ... */ }\n int typedef int argv char ** argv void main(char *param_1) main void if if (1000 < lVar1 - 1U) {\n }\n {} if return void main(char *param_1)\n\n{\n long lVar1;\n int iVar2;\n \n lVar1 = strtol(param_1,(char **)0x0,10);\n iVar2 = fun9(n1,lVar1);\n}\n fun9 void main(char *param_1) {\n long lVar1 = strtol(param_1,(char **)0x0,10);\n}\n 0x0 long lvar1 = strtol(parm_1, NULL, 10) param_1 lvar1 fun9" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647295/" ]
74,631,285
<p>Running VS Code on WSL.</p> <p>I have tried opening keybindings.json at [USER]/AppData/Roaming/Code/User/keybindings.json</p> <p>... and adding the following:</p> <pre class="lang-json prettyprint-override"><code> { &quot;key&quot;: &quot;escape+backspace&quot;, &quot;command&quot;: &quot;deleteWordLeft&quot;, &quot;when&quot;: &quot;textInputFocus &amp;&amp; !editorReadonly&quot; } </code></pre> <p>To no avail. This despite the fact that:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;key&quot;: &quot;ctrl+backspace&quot;, &quot;command&quot;: &quot;deleteWordLeft&quot;, &quot;when&quot;: &quot;textInputFocus &amp;&amp; !editorReadonly&quot; } </code></pre> <p>Works as intended. Is there some other escape command that I need to remove/disable?</p>
[ { "answer_id": 74631506, "author": "Ali Hassan", "author_id": 17962313, "author_profile": "https://Stackoverflow.com/users/17962313", "pm_score": -1, "selected": false, "text": "int main () {\n char str[30] = \"2030300 This is test\";\n char *ptr;\n long ret;\n\n ret = strtol(str, &ptr, 10);\n printf(\"The number(unsigned long integer) is %ld\\n\", ret);\n printf(\"String part is |%s|\", ptr);\n\n return(0);\n}\n" }, { "answer_id": 74631615, "author": "Jerry Coffin", "author_id": 179910, "author_profile": "https://Stackoverflow.com/users/179910", "pm_score": 0, "selected": false, "text": "main int main(void) { /* ... */ }\n argc argv int main(int argc, char *argv[]) { /* ... */ }\n int typedef int argv char ** argv void main(char *param_1) main void if if (1000 < lVar1 - 1U) {\n }\n {} if return void main(char *param_1)\n\n{\n long lVar1;\n int iVar2;\n \n lVar1 = strtol(param_1,(char **)0x0,10);\n iVar2 = fun9(n1,lVar1);\n}\n fun9 void main(char *param_1) {\n long lVar1 = strtol(param_1,(char **)0x0,10);\n}\n 0x0 long lvar1 = strtol(parm_1, NULL, 10) param_1 lvar1 fun9" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/830841/" ]
74,631,296
<p>I have two classes and I want to inject one class into another using Spring</p> <pre><code>public class A { private B b; ... } @Component public class B { ... } </code></pre> <p>But when I try to call b object method i cath NullPointerException. And I didn't understand why Spring didn't inject bean in A class. Can someone explain to me what's wrong?</p> <p>I have read all the Spring documentation in the world and have not found a solution.</p>
[ { "answer_id": 74631372, "author": "Yonatan Karp-Rudin", "author_id": 3899765, "author_profile": "https://Stackoverflow.com/users/3899765", "pm_score": 0, "selected": false, "text": "@Component\npublic class A {\n private B b;\n ...\n}\n\n@Component\npublic class B {\n ...\n}\n @Component\npublic class A {\n private final B b;\n\n public A(final B b) {\n this.b = b;\n }\n}\n\n@Component\npublic class B {\n ...\n}\n" }, { "answer_id": 74635025, "author": "Kumar Ashutosh", "author_id": 5324721, "author_profile": "https://Stackoverflow.com/users/5324721", "pm_score": 0, "selected": false, "text": "Class B @Component Class A B A @Component\npublic class A {\n private final B b;\n\n @Autowired\n public A(B b){\n this.b = b; \n }\n\n // other methods\n}\n @Component\npublic class B {\n ...\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647774/" ]
74,631,374
<p>The question is: Calculate the value of π from the infinite series. Print a table that shows the value of π approximated by one term of this series, by two terms, by three terms, and so on. How many terms of this series do you have to use before you first get 3.14? 3.141? 3.1415? 3.14159?</p> <pre><code>int n = 2; double sum, pi = 4, den; printf(&quot;Calculating the value of pi.\n&quot;); while (pi != 3.140000) { if (n % 2 == 0) { den = (2 * n) - 1; sum = (4.0 / den); pi = pi - sum; } else { den = (2 * n) - 1; sum = (4.0 / den); pi = pi + sum; } pi = (round(pi * 100)) / 100; printf(&quot;pi=%lf\n&quot;, pi); if (pi == 3.140000) { break; } n = n + 1; } printf(&quot;The number of terms to get pi=3.14 is %d.\n&quot;, n - 2); </code></pre> <p>This code works, and shows that we would get 3.14 at term 30 but when I repeat this code to get the term numbers where pi=3.141,pi=3.1415 and pi=3.14159, the code doesn't work and on execution just shows black screen with the statement, Calculating the value of pi.<a href="https://i.stack.imgur.com/w5M7h.jpg" rel="nofollow noreferrer">This is not the exact output I want but kind of. Actually I want that the table should print till I get 3.14,then I should get the statement showing the term number where I get 3.14, the the table starts from where I left and as soon as I get 3.141,the statement showing the term number where I get 3.141 prints and so on.</a> Please help me in this regard.(In C language) (I have to do this without using prec ,trunc or some other features as I am not allowed)</p> <p>Edit: I did this:</p> <pre><code>int main() { int n = 2, x = 2, y = 2, z = 2; double sum, pi = 4; printf(&quot;Calculating the value of pi.\n&quot;); while (pi != 3.140000) { if (n % 2 == 0) { sum = (4.0 / ((2 * n) - 1)); pi = pi - sum; } else { sum = (4.0 / ((2 * n) - 1)); pi = pi + sum; } pi = (round(pi * 100)) / 100; if (pi == 3.140000) { break; } n = n + 1; } while (pi != 3.141000) { if (n % 2 == 0) { sum = (4.0 / ((2 * n) - 1)); pi = pi - sum; } else { sum = (4.0 / ((2 * n) - 1)); pi = pi + sum; } pi = (round(pi * 100)) / 100; if (pi == 3.141000) { break; } n = n + 1; } while (pi != 3.141500) { if (n % 2 == 0) { sum = (4.0 / ((2 * n) - 1)); pi = pi - sum; } else { sum = (4.0 / ((2 * n) - 1)); pi = pi + sum; } pi = (round(pi * 100)) / 100; if (pi == 3.141500) { break; } n = n + 1; } while (pi != 3.141590) { if (n % 2 == 0) { sum = (4.0 / ((2 * n) - 1)); pi = pi - sum; } else { sum = (4.0 / ((2 * n) - 1)); pi = pi + sum; } pi = (round(pi * 100)) / 100; if (pi == 3.141590) { break; } n = n + 1; } printf(&quot;The number of terms to get pi=3.14 is %d.\n&quot;, n - 2); printf(&quot;The number of terms to get pi=3.141 is %d.\n&quot;, n - 2); printf(&quot;The number of terms to get pi=3.1415 is %d.\n&quot;, n - 2); printf(&quot;The number of terms to get pi=3.14159 is %d.\n&quot;, n - 2); } </code></pre> <p>but screen shows no output.</p>
[ { "answer_id": 74631709, "author": "NoDakker", "author_id": 6032177, "author_profile": "https://Stackoverflow.com/users/6032177", "pm_score": -1, "selected": false, "text": "pi=(round(pi*100))/100;\n #include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define check 3.14100\n#define precision 1000\n\nint main()\n{\n int n=2;\n double sum,pi=4.000000,den;\n\n printf(\"Calculating the value of pi.\\n\");\n while(pi != check)\n {\n if(n%2==0)\n {\n den=(2*n)-1;\n sum=(4.0/den);\n pi=pi-sum;\n }\n else\n {\n den=(2*n)-1;\n sum=(4.0/den);\n pi=pi+sum;\n }\n pi=(round(pi*precision))/precision; /* Provide enough precision */\n printf(\"pi=%lf\\n\",pi);\n if(pi == check)\n {\n break;\n }\n n=n+1;\n }\n printf(\"The number of terms to get pi= %f is %d.\\n\", check, n-2);\n\n return 0;\n}\n pi=3.142000\npi=3.137000\npi=3.141000\nThe number of terms to get pi= 3.141000 is 443.\n" }, { "answer_id": 74632028, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 2, "selected": false, "text": "while ( pi != 3.140000 ) pi double precision = 0.01;\ndouble pi = 4;\nwhile ( 1 ) {\n double previous_pi = 4;\n\n # Refine the value of `pi` here...\n\n if ( fabs( previous_pi - pi ) < precision / 2 )\n break;\n}\n 0.01" }, { "answer_id": 74635362, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": -1, "selected": false, "text": "pi != 3.14xxx fabs(pi - pi_Appoximate) >= 0.5 / limit\n int main(void) {\n printf(\"Calculating the value of pi.\\n\");\n char *pi_string = \"3.1415926535897932384626433832795\";\n for (unsigned i = 4; i<17; i++) {\n char buf[i + 1];\n buf[0] = '\\0';\n double pi_Appoximate = atof(strncat(buf, pi_string, i));\n double limit = pow(10, i - 1);\n unsigned n = 2;\n double sum;\n double pi = 4;\n printf(\"i:%2u limit:%e ~pi:%.*g\", i, limit, i, pi_Appoximate);\n fflush(stdout);\n while (fabs(pi - pi_Appoximate) >= 0.5 / limit) {\n if (n % 2 == 0) {\n sum = (4.0 / ((2 * n) - 1));\n pi = pi - sum;\n } else {\n sum = (4.0 / ((2 * n) - 1));\n pi = pi + sum;\n }\n pi = (round(pi * limit)) / limit;\n n = n + 1;\n }\n printf(\" pi:%.*g n:%u\\n\", i, pi, n);\n }\n puts(pi_string);\n}\n Calculating the value of pi.\ni: 4 limit:1.000000e+03 ~pi:3.14 pi:3.14 n:802\ni: 5 limit:1.000000e+04 ~pi:3.141 pi:3.141 n:1145\ni: 6 limit:1.000000e+05 ~pi:3.1415 pi:3.1415 n:36366\ni: 7 limit:1.000000e+06 ~pi:3.14159 pi:3.14159 n:72729\ni: 8 limit:1.000000e+07 ~pi:3.141592 pi:3.141592 n:1379312\ni: 9 limit:1.000000e+08 ~pi:3.1415926 pi:3.1415926 n:2649009\ni:10 limit:1.000000e+09 ~pi:3.14159265 pi:3.14159265 n:7476638\ni:11 limit:1.000000e+10 ~pi:3.141592653 pi:3.141592653 n:40363271\ni:12 limit:1.000000e+11 ~pi:3.1415926535 pi:3.1415926535 n:58402689\ni:13 limit:1.000000e+12 ~pi:3.14159265358 pi:3.14159265358 n:62874301\ni:14 limit:1.000000e+13 ~pi:3.141592653589 pi:3.141592653589 n:68508285\ni:15 limit:1.000000e+14 ~pi:3.1415926535897 pi:3.1415926535897 n:53634827\ni:16 limit:1.000000e+15 ~pi:3.14159265358979 pi:3.14159265358979 n:59359529\n3.1415926535897932384626433832795\n double" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647681/" ]
74,631,383
<p>I want to find the name of the state that shares the longest border with one or more other state? I have two table state, and borders. The table provided are simplified, to only have 5 states</p> <p>&quot;state&quot; Code is our key that is unquie for each state</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>code</th> </tr> </thead> <tbody> <tr> <td>Michigan</td> <td>MI</td> </tr> <tr> <td>Indiana</td> <td>IN</td> </tr> <tr> <td>Illinois</td> <td>IL</td> </tr> <tr> <td>Ohio</td> <td>OH</td> </tr> <tr> <td>Wisconsin</td> <td>WI</td> </tr> </tbody> </table> </div> <p>&quot;borders&quot; two state codes to refer to border between two states</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>code1</th> <th>code2</th> <th>length</th> </tr> </thead> <tbody> <tr> <td>MI</td> <td>IN</td> <td>20</td> </tr> <tr> <td>IL</td> <td>IN</td> <td>50</td> </tr> <tr> <td>Mi</td> <td>OH</td> <td>5</td> </tr> <tr> <td>IN</td> <td>OH</td> <td>40</td> </tr> <tr> <td>WI</td> <td>MI</td> <td>30</td> </tr> </tbody> </table> </div> <p>Expected result : Because from our data IN has the longest border, combined length 20 + 50 + 40</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>state</th> </tr> </thead> <tbody> <tr> <td>Indiana</td> </tr> </tbody> </table> </div> <p>edit: The query i have made so far.</p> <pre><code>SELECT s.name FROM state s INNER JOIN boarder b ON s.code = b.code1 WHERE SUM(b.length); </code></pre> <p>My thinking is I want to select the name, join it with borders table. Then get the sum. The two problems I see this this is it lists a bunch of names, where i only want one, and I'm not taking into account if the boarder on the other side. example being the first row in the boarders table. There are not two seperate rows of MI, IN and then IN, MI. So Should I try and do two subquires on either side, but how would i add the lengths?</p>
[ { "answer_id": 74631722, "author": "Alex Poole", "author_id": 266304, "author_profile": "https://Stackoverflow.com/users/266304", "pm_score": 2, "selected": false, "text": "select *\nfrom borders\nunpivot (code for code_idx in (code1 as 1, code2 as 2)) u\n ...\njoin state s on s.code = u.code\n sum() select s.name, sum(u.length)\nfrom borders\nunpivot (code for code_idx in (code1 as 1, code2 as 2)) u\njoin state s on s.code = u.code\ngroup by s.name\n select s.name\nfrom borders\nunpivot (code for code_idx in (code1 as 1, code2 as 2)) u\njoin state s on s.code = u.code\ngroup by s.name\norder by sum(u.length) desc\nfetch first 1 row only\n only with ties fetch where order by on (s.code = b.code1 or s.code = b.code2)\n select s.name\nfrom state s\njoin borders b\non (s.code = b.code1 or s.code = b.code2)\ngroup by s.name\norder by sum(b.length) desc\nfetch first 1 row only;\n" }, { "answer_id": 74631755, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 2, "selected": false, "text": "UNPIVOT borders state SELECT s.name\nFROM state s\n INNER JOIN (\n SELECT code,\n SUM(length) AS total_length\n FROM borders\n UNPIVOT (\n code FOR key IN (code1, code2)\n )\n GROUP BY code\n ORDER BY SUM(length) DESC\n FETCH FIRST ROW WITH TIES\n ) b\n ON s.code = b.code\n CREATE TABLE state (name, code) AS\nSELECT 'Michigan', 'MI' FROM DUAL UNION ALL\nSELECT 'Indiana', 'IN' FROM DUAL UNION ALL\nSELECT 'Illinois', 'IL' FROM DUAL UNION ALL\nSELECT 'Ohio', 'OH' FROM DUAL UNION ALL\nSELECT 'Wisconsin', 'WI' FROM DUAL;\n\nCREATE TABLE borders (code1, code2, length) AS\nSELECT 'MI', 'IN', 20 FROM DUAL UNION ALL\nSELECT 'IL', 'IN', 50 FROM DUAL UNION ALL\nSELECT 'MI', 'OH', 5 FROM DUAL UNION ALL\nSELECT 'IN', 'OH', 40 FROM DUAL UNION ALL\nSELECT 'WI', 'MI', 30 FROM DUAL;\n" }, { "answer_id": 74632032, "author": "GWR", "author_id": 17768469, "author_profile": "https://Stackoverflow.com/users/17768469", "pm_score": 0, "selected": false, "text": "with state_borders as\n(\n select code1 as code, length from border\n union all select code2 as code, lenght from border\n)\nselect top 1\n s.name,\n sum(b.length) as border_length\nfrom\n state_borders as b\n left join state as s on s.code = b.code\ngroup by\n s.name\norder by\n sum(b.length) desc;\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20265307/" ]
74,631,388
<p>firstly, thanks for any help in advance, and secondly I'm new to PowerShell, so am playing around with it, and probably off on the wrong track ;)</p> <p>I have a CSV file that i am reading the contents of, which is all good, and when i read the CSV i get an array. The CSV file contains something like the following information:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Value1</th> <th>Value2</th> </tr> </thead> <tbody> <tr> <td>IT</td> <td>444</td> <td>32</td> </tr> <tr> <td>HR</td> <td>34</td> <td>21</td> </tr> <tr> <td>IT</td> <td>31</td> <td>5</td> </tr> <tr> <td>IT</td> <td>75</td> <td>3</td> </tr> <tr> <td>HR</td> <td>64</td> <td>2</td> </tr> </tbody> </table> </div> <p>What I'm trying to achieve is to add the value based on grouping the name - so i will end up with: IT: 550,40 and HR: 98,23</p> <p>I have tried using array lists and hastables and ForEach-Object, but I'm afraid that i am not getting very far. I have been using Get-Unique after converting the array to an arraylist, however i am stuck on the best approach to firstly lookup and update based on the name property, and then as to whether i should have an array of hashtables to hold the multiple items of data.</p> <p>I'd appreciate any pointers, and thanks again.</p> <p>J</p>
[ { "answer_id": 74631985, "author": "jdweng", "author_id": 5015238, "author_profile": "https://Stackoverflow.com/users/5015238", "pm_score": 0, "selected": false, "text": "$input = @\"\nName, Value1, Value2\nIT,444,32\nHR,34,21\nIT,31,21\nIT, 31,5\nHR,64,2\n\"@\n\n$table = $input | ConvertFrom-Csv\n$table | Format-Table\n\n$groups = $table | Group-Object {$_.Name}\n\n$outputTable = [System.Collections.ArrayList]::new()\nforeach($group in $groups)\n{\n$group | Format-Table\n $newRow = New-Object -TypeName psobject\n $newRow | Add-Member -NotePropertyName Name -NotePropertyValue $group.Name\n\n $sum = 0\n $group.Group | foreach{$sum += $_.Value1}\n $newRow | Add-Member -NotePropertyName Value1 -NotePropertyValue $sum\n\n $sum = 0\n $group.Group | foreach{$sum += $_.Value2}\n $newRow | Add-Member -NotePropertyName Value2 -NotePropertyValue $sum\n\n $outputTable.Add($newRow) | Out-Null\n}\n$outputTable | Format-Table\n" }, { "answer_id": 74632466, "author": "zett42", "author_id": 7571258, "author_profile": "https://Stackoverflow.com/users/7571258", "pm_score": 3, "selected": true, "text": "Group-Object Measure-Object # Create sample data\n$data = @'\nName,Value1,Value2\nIT,444,32\nHR,34,21\nIT,31,5\nIT,75,3\nHR,64,2\n'@ | ConvertFrom-Csv\n\n# Group sample data by value of Name property\n$data | Group-Object Name | ForEach-Object {\n\n # Create an output object for the current group\n [pscustomobject]@{\n Name = $_.Name\n Value1 = ($_.Group | Measure-Object -Property Value1 -Sum).Sum\n Value2 = ($_.Group | Measure-Object -Property Value2 -Sum).Sum\n }\n}\n Import-Csv data.csv | Group-Object Name | ForEach-Object { ... }\n Name Value1 Value2\n---- ------ ------\nIT 550 40\nHR 98 23\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1176737/" ]
74,631,445
<p>I'm looking for something like the ForEach method but it only runs on one element.</p> <pre><code>// Do something with every element. SomeList.ForEach(o =&gt; DoSomethingWith(o)) // Do something with just the first element, if any, or nothing at all for an empty list. SomeLine.ForFirst(o =&gt; DoSomethingWith(o)) </code></pre> <p>I'm trying to stick with a functional paradigm, and using the <code>First</code>, <code>FirstOrOptional</code>, <code>FirstOrDefault</code>, seem to end up involving a lot of Null checking or exception handling.</p> <p>What is the Linq one-line way of doing this?</p>
[ { "answer_id": 74631552, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 2, "selected": true, "text": "collection.Take(1).ToList().ForEach(o => DoSomethingWith(o));\n" }, { "answer_id": 74631736, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "public static void ForFirst<T>(this IEnumerable<T> source, Action<T> action)\n{\n using (var iterator = source.GetEnumerator())\n {\n if (iterator.MoveNext())\n {\n action(iterator.Current);\n }\n }\n}\n public static void ForFirst<T>(this IEnumerable<T> source, Action<T> action)\n{\n // The foreach loop will automatically dispose the iterator\n foreach (var item in source)\n {\n action(item);\n // Stop directly after the first element anyway\n break;\n }\n}\n ForFirst" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18832188/" ]
74,631,450
<pre><code>import numpy as np x = np.array([1, -1, 2, 5, 7]) print(sum(x%2==0)) </code></pre> <p>This is the code, and I can't understand what does ' sum(x%2==0) ' mean.</p> <p>Does it mean to sum even number?</p> <p>I'm studying for school test and My professor said output of the above code is 1. But I can't understand what does ' sum(x%2==0)' mean..</p>
[ { "answer_id": 74631552, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 2, "selected": true, "text": "collection.Take(1).ToList().ForEach(o => DoSomethingWith(o));\n" }, { "answer_id": 74631736, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "public static void ForFirst<T>(this IEnumerable<T> source, Action<T> action)\n{\n using (var iterator = source.GetEnumerator())\n {\n if (iterator.MoveNext())\n {\n action(iterator.Current);\n }\n }\n}\n public static void ForFirst<T>(this IEnumerable<T> source, Action<T> action)\n{\n // The foreach loop will automatically dispose the iterator\n foreach (var item in source)\n {\n action(item);\n // Stop directly after the first element anyway\n break;\n }\n}\n ForFirst" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647906/" ]
74,631,454
<p>I'm using PrimeNG 14 (and Angular 14). I have a form in which I enter product information, and I would like to associate the product with one or more categories, each of which is displayed as a checkbox.</p> <pre><code>&lt;form [formGroup]=&quot;form&quot; (ngSubmit)=&quot;submit()&quot;&gt; ... &lt;p-table #dt [value]=&quot;(categories$ | async)!&quot; [(selection)]=&quot;selectedCategories&quot; dataKey=&quot;categoryId&quot;&gt; &lt;ng-template pTemplate=&quot;header&quot;&gt; &lt;tr&gt; &lt;th&gt; &lt;p-tableHeaderCheckbox&gt;&lt;/p-tableHeaderCheckbox&gt; &lt;/th&gt; &lt;th pSortableColumn=&quot;name&quot;&gt; &lt;div&gt; Category &lt;p-sortIcon field=&quot;name&quot;&gt;&lt;/p-sortIcon&gt; &lt;p-columnFilter type=&quot;text&quot; field=&quot;name&quot; display=&quot;menu&quot;&gt;&lt;/p-columnFilter&gt; &lt;/div&gt; &lt;/th&gt; &lt;/tr&gt; &lt;/ng-template&gt; &lt;ng-template pTemplate=&quot;body&quot; let-category&gt; &lt;tr class=&quot;p-selectable-row&quot;&gt; &lt;td&gt; &lt;p-tableCheckbox [value]=&quot;category&quot; [formControl]=&quot;$any(form.controls['categoryIds'])&quot;&gt;&lt;/p-tableCheckbox&gt; &lt;/td&gt; &lt;td&gt; &lt;span class=&quot;p-column-title&quot;&gt;Category&lt;/span&gt; {{category.name}} &lt;/td&gt; &lt;/tr&gt; &lt;/ng-template&gt; &lt;/p-table&gt; </code></pre> <p>In my service class I have</p> <pre><code> form!: FormGroup; ... ngOnInit(): void { ... this.form = this.fb.group({ ... categoryIds: [] }); </code></pre> <p>The issue is, I'm not sure how to bind the category ID checkboxes to the form control. Using the above approach doesn't work because when I check one checkbox, they all get checked.</p>
[ { "answer_id": 74631552, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 2, "selected": true, "text": "collection.Take(1).ToList().ForEach(o => DoSomethingWith(o));\n" }, { "answer_id": 74631736, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "public static void ForFirst<T>(this IEnumerable<T> source, Action<T> action)\n{\n using (var iterator = source.GetEnumerator())\n {\n if (iterator.MoveNext())\n {\n action(iterator.Current);\n }\n }\n}\n public static void ForFirst<T>(this IEnumerable<T> source, Action<T> action)\n{\n // The foreach loop will automatically dispose the iterator\n foreach (var item in source)\n {\n action(item);\n // Stop directly after the first element anyway\n break;\n }\n}\n ForFirst" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1235929/" ]
74,631,480
<p>I have a text example like</p> <blockquote> <p><code>0s11 0s12 0s33 my name is 0sgfh 0s1 0s22 0s87</code></p> </blockquote> <p>I want to detect the consecutive sequences that start 0s.</p> <p>So, the expected output should be <code>0s11 0s12 0s33</code>, <code>0sgfh 0s1 0s22 0s87</code></p> <p>I tried using regex</p> <pre><code>(0s\w+) </code></pre> <p>but that would detect each <code>0s11</code>, <code>0s12</code>, <code>0s33</code>, etc. individually.</p> <p>Any idea on how to modify the pattern?</p>
[ { "answer_id": 74634176, "author": "Koedlt", "author_id": 15405732, "author_profile": "https://Stackoverflow.com/users/15405732", "pm_score": 0, "selected": false, "text": "re.findall() import re\ntestString = \"0s11 0s12 0s33 my name is 0sgfh 0s1 0s22 0s87\"\nprint(re.findall('0s\\w', testString))\n\n['0s11', '0s12', '0s33', '0sgfh', '0s1', '0s22', '0s87']\n" }, { "answer_id": 74634325, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "\\b0s\\w+(?:\\s+0s\\w+)+\n \\b 0s\\w+ os (?:\\s+0s\\w+)+ 0s \\b0s\\w+(?:\\s+0s\\w+)*\n \\w+ 0s" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11794033/" ]
74,631,482
<p>I'm hoping someone might be able to point me in the right direction. I've got a fairly simple grid of flex items where the height is set to auto but they have varying widths 33%, 50%, 67%, 100% and wrap to the next row.</p> <p>This is all good when the items are in the right order. But what I'm trying to achieve is a way to shuffle the items into an order which fits when they're added to the page randomly.</p> <p>Example, a list of items 50 | 33 | 67 | 50 | 100 might be reordered to 50 | 50 | 67 | 33 | 100 so each row uses up the most horizontal space it can. I might have a list of 100 or so items, and it would also be nice to mix them up a bit and not have say 10 50% width items all together, but some rows of 33 | 33 | 33 or 33 | 67 mixed in between them.</p> <p>I can't think of a way to do this using CSS alone. So I've been looking at various JavaScript libraries, but they all seem to be focused on shuffling items of varying height and a fixed width.</p> <p>I don't need to change the display or position of the items, just the order based on their widths, so maybe I'm overthinking it and something like putting them into an array and sorting that would work better.</p> <p>Any help would be much appreciated! :)</p>
[ { "answer_id": 74632229, "author": "David Clarke", "author_id": 3834455, "author_profile": "https://Stackoverflow.com/users/3834455", "pm_score": 1, "selected": false, "text": "grid-auto-flow: dense" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834455/" ]
74,631,492
<p>I am trying to do (preferably Stochastic) Gradient Descent to minimize a custom loss function. I tried using scikit learn <code>SGDRegressor</code> class. However, <code>SGDRegressor</code> doesn't seem to allow me to minimize a custom loss function without data, and if I can use custom loss function, I can only use it as regression to fit data with <code>fit()</code> method.</p> <p>Is there a way to use scikit implementation or any other Python implementation of stochastic gradient descent to minimize a custom function without data?</p>
[ { "answer_id": 74631613, "author": "D P", "author_id": 20622893, "author_profile": "https://Stackoverflow.com/users/20622893", "pm_score": 1, "selected": false, "text": "def gradient_descent(gradient, start, learn_rate, n_iter):\n vector = start\n for _ in range(n_iter):\n diff = -learn_rate * gradient(vector)\n vector += diff\n return vector\n gradient_descent() gradient start learn_rate n_iter gradient_descent() import numpy as np\n\ndef gradient_descent(\n gradient, start, learn_rate, n_iter=50, tolerance=1e-06):\n vector = start\n for _ in range(n_iter):\n diff = -learn_rate * gradient(vector)\n if np.all(np.abs(diff) <= tolerance):\n break\n vector += diff\n return vector\n gradient_descent() gradient_descent() numpy.all() numpy.abs() >>> gradient_descent(\n... gradient=lambda v: 2 * v, start=10.0, learn_rate=0.2)\n2.210739197207331e-06\n lambda v: 2 * v import numpy as np\n\ndef gradient_descent(\n gradient, x, y, start, learn_rate=0.1, n_iter=50, tolerance=1e-06,\n dtype=\"float64\"):\n # Checking if the gradient is callable\n if not callable(gradient):\n raise TypeError(\"'gradient' must be callable\")\n\n # Setting up the data type for NumPy arrays\n dtype_ = np.dtype(dtype)\n\n # Converting x and y to NumPy arrays\n x, y = np.array(x, dtype=dtype_), np.array(y, dtype=dtype_)\n if x.shape[0] != y.shape[0]:\n raise ValueError(\"'x' and 'y' lengths do not match\")\n\n # Initializing the values of the variables\n vector = np.array(start, dtype=dtype_)\n\n # Setting up and checking the learning rate\n learn_rate = np.array(learn_rate, dtype=dtype_)\n if np.any(learn_rate <= 0):\n raise ValueError(\"'learn_rate' must be greater than zero\")\n\n # Setting up and checking the maximal number of iterations\n n_iter = int(n_iter)\n if n_iter <= 0:\n raise ValueError(\"'n_iter' must be greater than zero\")\n\n # Setting up and checking the tolerance\n tolerance = np.array(tolerance, dtype=dtype_)\n if np.any(tolerance <= 0):\n raise ValueError(\"'tolerance' must be greater than zero\")\n\n # Performing the gradient descent loop\n for _ in range(n_iter):\n # Recalculating the difference\n diff = -learn_rate * np.array(gradient(x, y, vector), dtype_)\n\n # Checking if the absolute difference is small enough\n if np.all(np.abs(diff) <= tolerance):\n break\n\n # Updating the values of the variables\n vector += diff\n\n return vector if vector.shape else vector.item()\n" }, { "answer_id": 74659895, "author": "Cyzanfar", "author_id": 3307520, "author_profile": "https://Stackoverflow.com/users/3307520", "pm_score": 0, "selected": false, "text": "from sklearn.linear_model import SGDRegressor\n\n# Define your custom loss function\ndef custom_loss_function(y_true, y_pred):\n # Your custom loss function implementation goes here\n pass\n\n# Create an SGDRegressor object with the custom loss function\nsgd_regressor = SGDRegressor(loss=custom_loss_function)\n\n# Use the fit() method to minimize the custom loss function without data\nsgd_regressor.fit(X=None, y=None)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10544368/" ]
74,631,508
<p>Why does this work:</p> <pre><code>def hamming_distance(dna_1,dna_2): hamming_distance = sum(1 for a, b in zip(dna_1, dna_2) if a != b) return hamming_distance </code></pre> <p>As opposed to this:</p> <pre><code>def hamming_distance(dna_1,dna_2): hamming_distance = sum(for a, b in zip(dna_1, dna_2) if a != b) return hamming_distance </code></pre> <p>I get this error:</p> <pre><code> Input In [90] hamming_distance = sum(for a, b in zip(dna_1, dna_2) if a != b) ^ SyntaxError: invalid syntax </code></pre> <p>I expected the function to work without the 1 after the ()</p>
[ { "answer_id": 74631613, "author": "D P", "author_id": 20622893, "author_profile": "https://Stackoverflow.com/users/20622893", "pm_score": 1, "selected": false, "text": "def gradient_descent(gradient, start, learn_rate, n_iter):\n vector = start\n for _ in range(n_iter):\n diff = -learn_rate * gradient(vector)\n vector += diff\n return vector\n gradient_descent() gradient start learn_rate n_iter gradient_descent() import numpy as np\n\ndef gradient_descent(\n gradient, start, learn_rate, n_iter=50, tolerance=1e-06):\n vector = start\n for _ in range(n_iter):\n diff = -learn_rate * gradient(vector)\n if np.all(np.abs(diff) <= tolerance):\n break\n vector += diff\n return vector\n gradient_descent() gradient_descent() numpy.all() numpy.abs() >>> gradient_descent(\n... gradient=lambda v: 2 * v, start=10.0, learn_rate=0.2)\n2.210739197207331e-06\n lambda v: 2 * v import numpy as np\n\ndef gradient_descent(\n gradient, x, y, start, learn_rate=0.1, n_iter=50, tolerance=1e-06,\n dtype=\"float64\"):\n # Checking if the gradient is callable\n if not callable(gradient):\n raise TypeError(\"'gradient' must be callable\")\n\n # Setting up the data type for NumPy arrays\n dtype_ = np.dtype(dtype)\n\n # Converting x and y to NumPy arrays\n x, y = np.array(x, dtype=dtype_), np.array(y, dtype=dtype_)\n if x.shape[0] != y.shape[0]:\n raise ValueError(\"'x' and 'y' lengths do not match\")\n\n # Initializing the values of the variables\n vector = np.array(start, dtype=dtype_)\n\n # Setting up and checking the learning rate\n learn_rate = np.array(learn_rate, dtype=dtype_)\n if np.any(learn_rate <= 0):\n raise ValueError(\"'learn_rate' must be greater than zero\")\n\n # Setting up and checking the maximal number of iterations\n n_iter = int(n_iter)\n if n_iter <= 0:\n raise ValueError(\"'n_iter' must be greater than zero\")\n\n # Setting up and checking the tolerance\n tolerance = np.array(tolerance, dtype=dtype_)\n if np.any(tolerance <= 0):\n raise ValueError(\"'tolerance' must be greater than zero\")\n\n # Performing the gradient descent loop\n for _ in range(n_iter):\n # Recalculating the difference\n diff = -learn_rate * np.array(gradient(x, y, vector), dtype_)\n\n # Checking if the absolute difference is small enough\n if np.all(np.abs(diff) <= tolerance):\n break\n\n # Updating the values of the variables\n vector += diff\n\n return vector if vector.shape else vector.item()\n" }, { "answer_id": 74659895, "author": "Cyzanfar", "author_id": 3307520, "author_profile": "https://Stackoverflow.com/users/3307520", "pm_score": 0, "selected": false, "text": "from sklearn.linear_model import SGDRegressor\n\n# Define your custom loss function\ndef custom_loss_function(y_true, y_pred):\n # Your custom loss function implementation goes here\n pass\n\n# Create an SGDRegressor object with the custom loss function\nsgd_regressor = SGDRegressor(loss=custom_loss_function)\n\n# Use the fit() method to minimize the custom loss function without data\nsgd_regressor.fit(X=None, y=None)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647949/" ]
74,631,513
<p>I'm trying to convert an array with a dictionary to a flattened dictionary and export it to a JSON file. I have an initial tab-delimited file, and have tried multiple ways but not coming to the final result. If there is more than one row present then save these as arrays in the dictionary</p> <pre><code>Name file code file_location TESTLIB1 443 123 location1 TESTLIB2 444 124 location2 </code></pre> <p>Current Output:</p> <pre><code>{'library': 'TESTLIB2', 'file': '444', 'code': '124', 'file_location': 'location2'} </code></pre> <p>Desired Output if num_lines &gt; 1:</p> <pre><code>{'library': ['TEST1', 'TEST2'], 'file': ['443', '444'], 'code': ['123', 123], 'file_location': ['location1', 'location2]} </code></pre> <p>Code Snippet</p> <pre><code>data_dict = {} with open('file.tmp') as input: reader = csv.DictReader(input, delimiter='\t') num_lines = sum(1 for line in open('write_object.tmp')) for row in reader: data_dict.update(row) if num_lines &gt; 1: data_dict.update(row) with open('output.json', 'w') as output: output.write(json.dumps(data_dict)) print(data_dict) </code></pre>
[ { "answer_id": 74631708, "author": "JayPeerachai", "author_id": 12135518, "author_profile": "https://Stackoverflow.com/users/12135518", "pm_score": 2, "selected": true, "text": "list import csv\nimport json \n\n# read file\nd = {}\nwith open('write_object.tmp') as f:\n reader = csv.reader(f, delimiter='\\t')\n headers = next(reader)\n for head in headers:\n d[head] = []\n for row in reader:\n for i, head in enumerate(headers):\n d[head].append(row[i])\n\n# save as json file\nwith open('output.json', 'w') as f:\n json.dump(d, f)\n {'Name': ['TESTLIB1', 'TESTLIB2'],\n 'file': ['443', '444'],\n 'code': ['123', '124'],\n 'file_location': ['location1', 'location2']}\n" }, { "answer_id": 74631793, "author": "Woodford", "author_id": 8451814, "author_profile": "https://Stackoverflow.com/users/8451814", "pm_score": 0, "selected": false, "text": "from collections import defaultdict\n\ndata_dict = defaultdict(list)\nwith open('input-file') as inp:\n for row in csv.DictReader(inp, delimiter='\\t'):\n for key, val in row.items():\n data_dict[key].append(val)\nprint(data_dict)\n # output\n{'Name': ['TESTLIB1', 'TESTLIB2'],\n 'file': ['443', '444'],\n 'code': ['123', '124'],\n 'file_location': ['location1', 'location2']}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20131595/" ]
74,631,524
<p>To use an example, I have 2 columns of data that I need to combine into 1...</p> <p>This is the data I have:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> </tr> </thead> <tbody> <tr> <td>Blue</td> <td>Red</td> </tr> <tr> <td>Yellow</td> <td>Green</td> </tr> </tbody> </table> </div> <p>This is what I want the formula to do:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> </tr> </thead> <tbody> <tr> <td>Blue</td> </tr> <tr> <td>Yellow</td> </tr> <tr> <td>Red</td> </tr> <tr> <td>Green</td> </tr> </tbody> </table> </div> <p>Tried searching on Google but results keep showing merge and concatenate. Maybe this is because I can't word it correctly...</p> <p>I've tried ={Column A, Column B etc.} and FILTER() but I appear to be way off</p>
[ { "answer_id": 74631696, "author": "doubleunary", "author_id": 13045193, "author_profile": "https://Stackoverflow.com/users/13045193", "pm_score": 1, "selected": false, "text": "flatten() =flatten(A1:B) query() =query( { A1:A; B1:B }, \"where Col1 is not null\", 0 ) A A ={ B1:B } B1:B A1:A" }, { "answer_id": 74634012, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=QUERY(FLATTEN(TRANSPOSE(A1:B)), \"where Col1 is not null\", )\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10787152/" ]
74,631,534
<p>I make a Taboo-like word game using Unity game engine. I want to randomly access blocks in json. For example, load words in second block (Computer, Game, Work ...). Is there any way to access with indexes? Or another way? My json is like this: <br>(Scroll down for solution)</p> <pre><code>{ &quot;word&quot;:&quot;Game&quot;, &quot;tabooWords&quot;:[ &quot;Ball&quot;, &quot;Sport&quot;, &quot;Computer&quot;, &quot;Phone&quot;, &quot;Fun&quot; ] } { &quot;word&quot;:&quot;Computer&quot;, &quot;tabooWords&quot;:[ &quot;Game&quot;, &quot;Work&quot;, &quot;Laptop&quot;, &quot;PC&quot;, &quot;Electronic&quot; ] } { &quot;word&quot;:&quot;Software&quot;, &quot;tabooWords&quot;:[ &quot;Computer&quot;, &quot;GitHub&quot;, &quot;Developer&quot;, &quot;İnsan&quot;, &quot;Hikaye&quot; ] } </code></pre> <p>I tried:</p> <pre><code>[Serializable] public class TabooData { public string word; public List&lt;string&gt; tabuWords; public TabooData() { word = &quot;&quot;; tabuWords = new(); } } </code></pre> <pre><code>string path = Application.dataPath + &quot;/DataSet/words.json&quot;; if (File.Exists(path)) { string jsonString = File.ReadAllText(path); TabooData tabooWords = JsonConvert.DeserializeObject&lt;TabooData&gt;(jsonString); } </code></pre> <p>I don't know what is wrong and what to do next.</p> <p><strong>Update:</strong> I tried after replies and I did. I phrased my question more clearly. Thanks for the responses. <br> Json:</p> <pre><code>[ { &quot;word&quot;: &quot;Game&quot;, &quot;tabooWords&quot;: [ &quot;Ball&quot;, &quot;Sport&quot;, &quot;Computer&quot;, &quot;Phone&quot;, &quot;Fun&quot; ] }, { &quot;word&quot;: &quot;Computer&quot;, &quot;tabooWords&quot;: [ &quot;Game&quot;, &quot;Work&quot;, &quot;Laptop&quot;, &quot;PC&quot;, &quot;Electronic&quot; ] }, { &quot;word&quot;: &quot;Software&quot;, &quot;tabooWords&quot;: [ &quot;Computer&quot;, &quot;GitHub&quot;, &quot;Developer&quot;, &quot;Hacker&quot;, &quot;Code&quot; ] } ] </code></pre> <p>The code:</p> <pre><code>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using UnityEngine; public class GameUIManager : MonoBehaviour { public class TabooData { public string word { get; set; } public List&lt;string&gt; tabooWords { get; set; } } private void Start() { string path = Application.dataPath + &quot;/DataSet/words.json&quot;; string jsonString = File.ReadAllText(path); var myWordsFromJson = JsonConvert.DeserializeObject&lt;List&lt;TabooData&gt;&gt;(jsonString); int randomIndex = new System.Random().Next(myWordsFromJson.Count); Console.WriteLine(myWordsFromJson[randomIndex].word); // Access the word Console.WriteLine(myWordsFromJson[randomIndex].tabooWords); // Access tabooWords Console.WriteLine(myWordsFromJson[randomIndex].tabooWords[1]); // Access tabooWords at any index } } </code></pre>
[ { "answer_id": 74631711, "author": "JimmyV", "author_id": 3561956, "author_profile": "https://Stackoverflow.com/users/3561956", "pm_score": 0, "selected": false, "text": "public class TabooGame\n{\n [JsonProperty(\"word\")]\n public string Word { get; set; }\n [JsonProperty(\"tabooWords\")]\n public string[] TabooWords { get; set; }\n}\n\npublic class Game\n{\n public string GetRandomWords(string jsonString)\n {\n var taboo = JsonConvert.DeserializeObject<TabooGame>(jsonString);\n var wordCount = taboo.TabooWords.Count();\n\n var randomIndex = new Random().Next(0, wordCount - 1);\n\n return taboo.TabooWords[randomIndex];\n }\n}\n" }, { "answer_id": 74631846, "author": "Neil", "author_id": 759558, "author_profile": "https://Stackoverflow.com/users/759558", "pm_score": 2, "selected": true, "text": "using System;\nusing System.Text.Json.Serialization;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n public class Item\n {\n public string word {get;set;}\n public List<string> tabooWords {get;set;}\n }\n \n public static void Main()\n {\n const string input = @\"\n [{\n \"\"word\"\":\"\"Game\"\",\n \"\"tabooWords\"\":[ \"\"Ball\"\", \"\"Sport\"\", \"\"Computer\"\", \"\"Phone\"\", \"\"Fun\"\" ]\n},\n{\n \"\"word\"\":\"\"Computer\"\",\n \"\"tabooWords\"\":[ \"\"Game\"\", \"\"Work\"\", \"\"Laptop\"\", \"\"PC\"\", \"\"Electronic\"\" ]\n},\n{\n \"\"word\"\":\"\"Software\"\",\n \"\"tabooWords\"\":[ \"\"Computer\"\", \"\"GitHub\"\", \"\"Developer\"\", \"\"İnsan\"\", \"\"Hikaye\"\" ]\n}]\";\n \n var d = System.Text.Json.JsonSerializer.Deserialize<List<Item>>(input);\n var words = d.First(x=>x.word == \"Game\");\n\n Console.WriteLine(words.tabooWords.ElementAt(new Random().Next(words.tabooWords.Count())));\n }\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12539961/" ]
74,631,541
<p>I have a requirement to match all <code>array&lt;..&gt;</code> in the entire sentence and replace only <code>&lt;&gt;</code> to <code>[]</code> (replace &lt;&gt; with [] which have prefix array).</p> <p>I haven't got any clue to resolve this. It will be great if anyone can provide any clue for this issue?</p> <p><strong>Input</strong></p> <pre><code>&lt;tr&gt;&lt;td&gt;Asdft array&lt;object&gt; tesnp array&lt;int&gt;&lt;/td&gt; &lt;td&gt;asldhj ashd repl array&lt;String&gt; array asdhl afe array&lt;object&gt; endoftest&lt;/td&gt;&lt;/tr&gt; </code></pre> <p><strong>Expected Output</strong></p> <pre><code>&lt;tr&gt;&lt;td&gt;Asdft array[object] tesnp array[int]&lt;/td&gt; &lt;td&gt;asldhj ashd repl array[String] array asdhl afe array[object] endoftest&lt;/tr&gt;&lt;/td&gt; </code></pre>
[ { "answer_id": 74632340, "author": "MaicolAntali", "author_id": 20631377, "author_profile": "https://Stackoverflow.com/users/20631377", "pm_score": 0, "selected": false, "text": ".replace() String replacedStr = text.replace(\"array<object>\", \"array[object]\");\n" }, { "answer_id": 74638717, "author": "oleg.cherednik", "author_id": 3461397, "author_profile": "https://Stackoverflow.com/users/3461397", "pm_score": 0, "selected": false, "text": "public static String replaceMacro(String str) {\n final String pattern = \"array<\";\n StringBuilder buf = new StringBuilder(str.length());\n int fromIndex = 0;\n\n while (true) {\n int lo = str.indexOf(pattern, fromIndex);\n\n if (lo >= 0) {\n lo += pattern.length() - 1;\n int hi = str.indexOf('>', lo);\n\n buf.append(str, fromIndex, lo);\n buf.append('[');\n buf.append(str.substring(lo + 1, hi));\n buf.append(']');\n\n fromIndex = hi + 1;\n } else {\n buf.append(str.substring(fromIndex));\n break;\n }\n }\n\n return buf.toString();\n}\n public static String replaceMacro(String str) {\n Pattern pattern = Pattern.compile(\"(array)<(\\\\w+)>\");\n Matcher matcher = pattern.matcher(str);\n\n StringBuilder buf = new StringBuilder(str.length());\n int fromIndex = 0;\n\n while (matcher.find(fromIndex)) {\n int lo = matcher.start();\n int hi = matcher.end();\n\n buf.append(str, fromIndex, lo).append(matcher.group(1));\n buf.append('[').append(matcher.group(2)).append(']');\n\n fromIndex = hi;\n }\n\n if (fromIndex < str.length()) {\n buf.append(str.substring(fromIndex));\n }\n\n return buf.toString();\n}\n" }, { "answer_id": 74639092, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 1, "selected": false, "text": "array<(\\w+)> array< > array public class Main {\n public static void main(String[] args) {\n String str = \"\"\"\n <tr><td>Asdft array<object> tesnp array<int></td>\n <td>asldhj\n ashd\n repl array<String>\n array\n asdhl\n afe array<object>\n endoftest</td></tr>\n \"\"\";\n\n String result = str.replaceAll(\"array<(\\\\w+)>\", \"array[$1]\");\n\n System.out.println(result);\n }\n}\n <tr><td>Asdft array[object] tesnp array[int]</td>\n<td>asldhj\nashd\nrepl array[String]\narray\nasdhl\nafe array[object]\nendoftest</td></tr>\n" }, { "answer_id": 74646335, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 1, "selected": false, "text": "(?<=array) // positive lookbehind (preceded by \"array\")\n< // opening angle bracket\n(\\w+) // one or more word characters (matching group)\n> // closing angle bracket\n import java.util.regex.*;\n\npublic class Example {\n public static String replace(String str, String pattern, String replacement) {\n return Pattern\n .compile(pattern, Pattern.MULTILINE)\n .matcher(str)\n .replaceAll(replacement);\n }\n \n public static String fixHtmlText(String htmlText) {\n return replace(htmlText, \"(?<=array)<(\\\\w+)>\", \"[$1]\");\n }\n \n public static void main(String[] args) {\n String htmlText = \"<tr><td>Asdft array<object> tesnp array<int></td>\\n\"\n + \"<td>asldhj\\n\"\n + \"ashd\\n\"\n + \"repl array<String>\\n\"\n + \"array\\n\"\n + \"asdhl\\n\"\n + \"afe array<object>\\n\"\n + \"endoftest</td></tr>\";\n \n System.out.println(fixHtmlText(htmlText));\n }\n}\n <tr><td>Asdft array[object] tesnp array[int]</td>\n<td>asldhj\nashd\nrepl array[String]\narray\nasdhl\nafe array[object]\nendoftest</td></tr>\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3945679/" ]
74,631,549
<p>I need a regex to validate only 0s or 1s in a phone number. For eg - 0000000000 or 1111111111 should be invalid. Also my phone number range is from 7-15 only. Below is my regex [0-9]{7,15} it should add validation in the regex to invalidate only 0 and only 1 in the phone number</p>
[ { "answer_id": 74632340, "author": "MaicolAntali", "author_id": 20631377, "author_profile": "https://Stackoverflow.com/users/20631377", "pm_score": 0, "selected": false, "text": ".replace() String replacedStr = text.replace(\"array<object>\", \"array[object]\");\n" }, { "answer_id": 74638717, "author": "oleg.cherednik", "author_id": 3461397, "author_profile": "https://Stackoverflow.com/users/3461397", "pm_score": 0, "selected": false, "text": "public static String replaceMacro(String str) {\n final String pattern = \"array<\";\n StringBuilder buf = new StringBuilder(str.length());\n int fromIndex = 0;\n\n while (true) {\n int lo = str.indexOf(pattern, fromIndex);\n\n if (lo >= 0) {\n lo += pattern.length() - 1;\n int hi = str.indexOf('>', lo);\n\n buf.append(str, fromIndex, lo);\n buf.append('[');\n buf.append(str.substring(lo + 1, hi));\n buf.append(']');\n\n fromIndex = hi + 1;\n } else {\n buf.append(str.substring(fromIndex));\n break;\n }\n }\n\n return buf.toString();\n}\n public static String replaceMacro(String str) {\n Pattern pattern = Pattern.compile(\"(array)<(\\\\w+)>\");\n Matcher matcher = pattern.matcher(str);\n\n StringBuilder buf = new StringBuilder(str.length());\n int fromIndex = 0;\n\n while (matcher.find(fromIndex)) {\n int lo = matcher.start();\n int hi = matcher.end();\n\n buf.append(str, fromIndex, lo).append(matcher.group(1));\n buf.append('[').append(matcher.group(2)).append(']');\n\n fromIndex = hi;\n }\n\n if (fromIndex < str.length()) {\n buf.append(str.substring(fromIndex));\n }\n\n return buf.toString();\n}\n" }, { "answer_id": 74639092, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 1, "selected": false, "text": "array<(\\w+)> array< > array public class Main {\n public static void main(String[] args) {\n String str = \"\"\"\n <tr><td>Asdft array<object> tesnp array<int></td>\n <td>asldhj\n ashd\n repl array<String>\n array\n asdhl\n afe array<object>\n endoftest</td></tr>\n \"\"\";\n\n String result = str.replaceAll(\"array<(\\\\w+)>\", \"array[$1]\");\n\n System.out.println(result);\n }\n}\n <tr><td>Asdft array[object] tesnp array[int]</td>\n<td>asldhj\nashd\nrepl array[String]\narray\nasdhl\nafe array[object]\nendoftest</td></tr>\n" }, { "answer_id": 74646335, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 1, "selected": false, "text": "(?<=array) // positive lookbehind (preceded by \"array\")\n< // opening angle bracket\n(\\w+) // one or more word characters (matching group)\n> // closing angle bracket\n import java.util.regex.*;\n\npublic class Example {\n public static String replace(String str, String pattern, String replacement) {\n return Pattern\n .compile(pattern, Pattern.MULTILINE)\n .matcher(str)\n .replaceAll(replacement);\n }\n \n public static String fixHtmlText(String htmlText) {\n return replace(htmlText, \"(?<=array)<(\\\\w+)>\", \"[$1]\");\n }\n \n public static void main(String[] args) {\n String htmlText = \"<tr><td>Asdft array<object> tesnp array<int></td>\\n\"\n + \"<td>asldhj\\n\"\n + \"ashd\\n\"\n + \"repl array<String>\\n\"\n + \"array\\n\"\n + \"asdhl\\n\"\n + \"afe array<object>\\n\"\n + \"endoftest</td></tr>\";\n \n System.out.println(fixHtmlText(htmlText));\n }\n}\n <tr><td>Asdft array[object] tesnp array[int]</td>\n<td>asldhj\nashd\nrepl array[String]\narray\nasdhl\nafe array[object]\nendoftest</td></tr>\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20273825/" ]
74,631,566
<p>hi i have remove the expanded , now the bold text of child has curly wave , what i did wrong over here.</p> <p>below is my code i, please advice, thanks</p> <pre><code> import 'package:flutter/material.dart'; class Introduction extends StatefulWidget { const Introduction({super.key}); @override State&lt;Introduction&gt; createState() =&gt; _IntroductionState(); } class _IntroductionState extends State&lt;Introduction&gt; { @override Widget build(BuildContext context) { return Scaffold( body: Column(children: [ Container( color: Color.fromARGB(255, 255, 255, 255), child: Column(mainAxisAlignment: MainAxisAlignment.start), **child**: const Center( child: Image( height: 1000, width: 1000, image: AssetImage(&quot;lib/images/instruction.png&quot;))), ) ])); } } </code></pre>
[ { "answer_id": 74632340, "author": "MaicolAntali", "author_id": 20631377, "author_profile": "https://Stackoverflow.com/users/20631377", "pm_score": 0, "selected": false, "text": ".replace() String replacedStr = text.replace(\"array<object>\", \"array[object]\");\n" }, { "answer_id": 74638717, "author": "oleg.cherednik", "author_id": 3461397, "author_profile": "https://Stackoverflow.com/users/3461397", "pm_score": 0, "selected": false, "text": "public static String replaceMacro(String str) {\n final String pattern = \"array<\";\n StringBuilder buf = new StringBuilder(str.length());\n int fromIndex = 0;\n\n while (true) {\n int lo = str.indexOf(pattern, fromIndex);\n\n if (lo >= 0) {\n lo += pattern.length() - 1;\n int hi = str.indexOf('>', lo);\n\n buf.append(str, fromIndex, lo);\n buf.append('[');\n buf.append(str.substring(lo + 1, hi));\n buf.append(']');\n\n fromIndex = hi + 1;\n } else {\n buf.append(str.substring(fromIndex));\n break;\n }\n }\n\n return buf.toString();\n}\n public static String replaceMacro(String str) {\n Pattern pattern = Pattern.compile(\"(array)<(\\\\w+)>\");\n Matcher matcher = pattern.matcher(str);\n\n StringBuilder buf = new StringBuilder(str.length());\n int fromIndex = 0;\n\n while (matcher.find(fromIndex)) {\n int lo = matcher.start();\n int hi = matcher.end();\n\n buf.append(str, fromIndex, lo).append(matcher.group(1));\n buf.append('[').append(matcher.group(2)).append(']');\n\n fromIndex = hi;\n }\n\n if (fromIndex < str.length()) {\n buf.append(str.substring(fromIndex));\n }\n\n return buf.toString();\n}\n" }, { "answer_id": 74639092, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 1, "selected": false, "text": "array<(\\w+)> array< > array public class Main {\n public static void main(String[] args) {\n String str = \"\"\"\n <tr><td>Asdft array<object> tesnp array<int></td>\n <td>asldhj\n ashd\n repl array<String>\n array\n asdhl\n afe array<object>\n endoftest</td></tr>\n \"\"\";\n\n String result = str.replaceAll(\"array<(\\\\w+)>\", \"array[$1]\");\n\n System.out.println(result);\n }\n}\n <tr><td>Asdft array[object] tesnp array[int]</td>\n<td>asldhj\nashd\nrepl array[String]\narray\nasdhl\nafe array[object]\nendoftest</td></tr>\n" }, { "answer_id": 74646335, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 1, "selected": false, "text": "(?<=array) // positive lookbehind (preceded by \"array\")\n< // opening angle bracket\n(\\w+) // one or more word characters (matching group)\n> // closing angle bracket\n import java.util.regex.*;\n\npublic class Example {\n public static String replace(String str, String pattern, String replacement) {\n return Pattern\n .compile(pattern, Pattern.MULTILINE)\n .matcher(str)\n .replaceAll(replacement);\n }\n \n public static String fixHtmlText(String htmlText) {\n return replace(htmlText, \"(?<=array)<(\\\\w+)>\", \"[$1]\");\n }\n \n public static void main(String[] args) {\n String htmlText = \"<tr><td>Asdft array<object> tesnp array<int></td>\\n\"\n + \"<td>asldhj\\n\"\n + \"ashd\\n\"\n + \"repl array<String>\\n\"\n + \"array\\n\"\n + \"asdhl\\n\"\n + \"afe array<object>\\n\"\n + \"endoftest</td></tr>\";\n \n System.out.println(fixHtmlText(htmlText));\n }\n}\n <tr><td>Asdft array[object] tesnp array[int]</td>\n<td>asldhj\nashd\nrepl array[String]\narray\nasdhl\nafe array[object]\nendoftest</td></tr>\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20438315/" ]
74,631,591
<p>This code creates tabs, but I have issues displaying the content of the tab.</p> <p>How can I rewrite the JS to be able to pull the tab-content from anywhere of my page?</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 btn = [].slice.call(document.getElementsByTagName('button')) btn.forEach((item, index) =&gt; { item.addEventListener('click', function() { btn.forEach((item) =&gt; { item.classList.remove('active') }) item.classList.add('active') document.getElementById('tab').setAttribute('data-tab', index) }) })</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="wrapper"&gt; &lt;button&gt; Tab 1&lt;/button&gt; &lt;button&gt; Tab 2&lt;/button&gt; &lt;button&gt; Tab 3&lt;/button&gt; &lt;div id="tab" class="tabs inliner"&gt; &lt;div&gt; &lt;h2&gt; CONTENT HAST TO BE HERE &lt;/h2&gt; &lt;/div&gt; &lt;div&gt; &lt;h2&gt; OR HERE &lt;/h2&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Since I'm using WordPress shortcodes, they don't get executed. I have to place them somewhere else and then display them wherever the tabs are as tabcontent.</p> <p>Recreating only the <code>&lt;div id=&quot;tab&quot; class=&quot;tabs inliner&quot;&gt;</code> while rest stays in place is not working either.</p> <p>Any ideas?</p> <p>As i stated, tried to replicate the specific but did not work.</p>
[ { "answer_id": 74632340, "author": "MaicolAntali", "author_id": 20631377, "author_profile": "https://Stackoverflow.com/users/20631377", "pm_score": 0, "selected": false, "text": ".replace() String replacedStr = text.replace(\"array<object>\", \"array[object]\");\n" }, { "answer_id": 74638717, "author": "oleg.cherednik", "author_id": 3461397, "author_profile": "https://Stackoverflow.com/users/3461397", "pm_score": 0, "selected": false, "text": "public static String replaceMacro(String str) {\n final String pattern = \"array<\";\n StringBuilder buf = new StringBuilder(str.length());\n int fromIndex = 0;\n\n while (true) {\n int lo = str.indexOf(pattern, fromIndex);\n\n if (lo >= 0) {\n lo += pattern.length() - 1;\n int hi = str.indexOf('>', lo);\n\n buf.append(str, fromIndex, lo);\n buf.append('[');\n buf.append(str.substring(lo + 1, hi));\n buf.append(']');\n\n fromIndex = hi + 1;\n } else {\n buf.append(str.substring(fromIndex));\n break;\n }\n }\n\n return buf.toString();\n}\n public static String replaceMacro(String str) {\n Pattern pattern = Pattern.compile(\"(array)<(\\\\w+)>\");\n Matcher matcher = pattern.matcher(str);\n\n StringBuilder buf = new StringBuilder(str.length());\n int fromIndex = 0;\n\n while (matcher.find(fromIndex)) {\n int lo = matcher.start();\n int hi = matcher.end();\n\n buf.append(str, fromIndex, lo).append(matcher.group(1));\n buf.append('[').append(matcher.group(2)).append(']');\n\n fromIndex = hi;\n }\n\n if (fromIndex < str.length()) {\n buf.append(str.substring(fromIndex));\n }\n\n return buf.toString();\n}\n" }, { "answer_id": 74639092, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 1, "selected": false, "text": "array<(\\w+)> array< > array public class Main {\n public static void main(String[] args) {\n String str = \"\"\"\n <tr><td>Asdft array<object> tesnp array<int></td>\n <td>asldhj\n ashd\n repl array<String>\n array\n asdhl\n afe array<object>\n endoftest</td></tr>\n \"\"\";\n\n String result = str.replaceAll(\"array<(\\\\w+)>\", \"array[$1]\");\n\n System.out.println(result);\n }\n}\n <tr><td>Asdft array[object] tesnp array[int]</td>\n<td>asldhj\nashd\nrepl array[String]\narray\nasdhl\nafe array[object]\nendoftest</td></tr>\n" }, { "answer_id": 74646335, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 1, "selected": false, "text": "(?<=array) // positive lookbehind (preceded by \"array\")\n< // opening angle bracket\n(\\w+) // one or more word characters (matching group)\n> // closing angle bracket\n import java.util.regex.*;\n\npublic class Example {\n public static String replace(String str, String pattern, String replacement) {\n return Pattern\n .compile(pattern, Pattern.MULTILINE)\n .matcher(str)\n .replaceAll(replacement);\n }\n \n public static String fixHtmlText(String htmlText) {\n return replace(htmlText, \"(?<=array)<(\\\\w+)>\", \"[$1]\");\n }\n \n public static void main(String[] args) {\n String htmlText = \"<tr><td>Asdft array<object> tesnp array<int></td>\\n\"\n + \"<td>asldhj\\n\"\n + \"ashd\\n\"\n + \"repl array<String>\\n\"\n + \"array\\n\"\n + \"asdhl\\n\"\n + \"afe array<object>\\n\"\n + \"endoftest</td></tr>\";\n \n System.out.println(fixHtmlText(htmlText));\n }\n}\n <tr><td>Asdft array[object] tesnp array[int]</td>\n<td>asldhj\nashd\nrepl array[String]\narray\nasdhl\nafe array[object]\nendoftest</td></tr>\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647925/" ]
74,631,596
<p>I have a string in an input that needs to be split into separate values and left in a list. I am using the following construct to enter values. How can the value <code>-1</code> be noticed on a variable <code>var</code>?</p> <pre><code>import sys readline = sys.stdin.readline var = 10**5 current_line = list(map(int, readline().split())) </code></pre> <p>Example input:</p> <pre><code>-1 3 0 -1 4 5 </code></pre> <p>Required value <code>current_line</code>:</p> <pre><code>[var, 3, 0, var, 4, 5] </code></pre>
[ { "answer_id": 74632340, "author": "MaicolAntali", "author_id": 20631377, "author_profile": "https://Stackoverflow.com/users/20631377", "pm_score": 0, "selected": false, "text": ".replace() String replacedStr = text.replace(\"array<object>\", \"array[object]\");\n" }, { "answer_id": 74638717, "author": "oleg.cherednik", "author_id": 3461397, "author_profile": "https://Stackoverflow.com/users/3461397", "pm_score": 0, "selected": false, "text": "public static String replaceMacro(String str) {\n final String pattern = \"array<\";\n StringBuilder buf = new StringBuilder(str.length());\n int fromIndex = 0;\n\n while (true) {\n int lo = str.indexOf(pattern, fromIndex);\n\n if (lo >= 0) {\n lo += pattern.length() - 1;\n int hi = str.indexOf('>', lo);\n\n buf.append(str, fromIndex, lo);\n buf.append('[');\n buf.append(str.substring(lo + 1, hi));\n buf.append(']');\n\n fromIndex = hi + 1;\n } else {\n buf.append(str.substring(fromIndex));\n break;\n }\n }\n\n return buf.toString();\n}\n public static String replaceMacro(String str) {\n Pattern pattern = Pattern.compile(\"(array)<(\\\\w+)>\");\n Matcher matcher = pattern.matcher(str);\n\n StringBuilder buf = new StringBuilder(str.length());\n int fromIndex = 0;\n\n while (matcher.find(fromIndex)) {\n int lo = matcher.start();\n int hi = matcher.end();\n\n buf.append(str, fromIndex, lo).append(matcher.group(1));\n buf.append('[').append(matcher.group(2)).append(']');\n\n fromIndex = hi;\n }\n\n if (fromIndex < str.length()) {\n buf.append(str.substring(fromIndex));\n }\n\n return buf.toString();\n}\n" }, { "answer_id": 74639092, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 1, "selected": false, "text": "array<(\\w+)> array< > array public class Main {\n public static void main(String[] args) {\n String str = \"\"\"\n <tr><td>Asdft array<object> tesnp array<int></td>\n <td>asldhj\n ashd\n repl array<String>\n array\n asdhl\n afe array<object>\n endoftest</td></tr>\n \"\"\";\n\n String result = str.replaceAll(\"array<(\\\\w+)>\", \"array[$1]\");\n\n System.out.println(result);\n }\n}\n <tr><td>Asdft array[object] tesnp array[int]</td>\n<td>asldhj\nashd\nrepl array[String]\narray\nasdhl\nafe array[object]\nendoftest</td></tr>\n" }, { "answer_id": 74646335, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 1, "selected": false, "text": "(?<=array) // positive lookbehind (preceded by \"array\")\n< // opening angle bracket\n(\\w+) // one or more word characters (matching group)\n> // closing angle bracket\n import java.util.regex.*;\n\npublic class Example {\n public static String replace(String str, String pattern, String replacement) {\n return Pattern\n .compile(pattern, Pattern.MULTILINE)\n .matcher(str)\n .replaceAll(replacement);\n }\n \n public static String fixHtmlText(String htmlText) {\n return replace(htmlText, \"(?<=array)<(\\\\w+)>\", \"[$1]\");\n }\n \n public static void main(String[] args) {\n String htmlText = \"<tr><td>Asdft array<object> tesnp array<int></td>\\n\"\n + \"<td>asldhj\\n\"\n + \"ashd\\n\"\n + \"repl array<String>\\n\"\n + \"array\\n\"\n + \"asdhl\\n\"\n + \"afe array<object>\\n\"\n + \"endoftest</td></tr>\";\n \n System.out.println(fixHtmlText(htmlText));\n }\n}\n <tr><td>Asdft array[object] tesnp array[int]</td>\n<td>asldhj\nashd\nrepl array[String]\narray\nasdhl\nafe array[object]\nendoftest</td></tr>\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20133865/" ]
74,631,662
<p>What is the best way to protect (enhance security) the publically accessible brokers?</p> <p>There are only a few posts and docs from AWS that talk about Authentication, Encryption and Auth, but there's very little information regarding combining things like WAF to shield the brokers from internet attacks.</p>
[ { "answer_id": 74632340, "author": "MaicolAntali", "author_id": 20631377, "author_profile": "https://Stackoverflow.com/users/20631377", "pm_score": 0, "selected": false, "text": ".replace() String replacedStr = text.replace(\"array<object>\", \"array[object]\");\n" }, { "answer_id": 74638717, "author": "oleg.cherednik", "author_id": 3461397, "author_profile": "https://Stackoverflow.com/users/3461397", "pm_score": 0, "selected": false, "text": "public static String replaceMacro(String str) {\n final String pattern = \"array<\";\n StringBuilder buf = new StringBuilder(str.length());\n int fromIndex = 0;\n\n while (true) {\n int lo = str.indexOf(pattern, fromIndex);\n\n if (lo >= 0) {\n lo += pattern.length() - 1;\n int hi = str.indexOf('>', lo);\n\n buf.append(str, fromIndex, lo);\n buf.append('[');\n buf.append(str.substring(lo + 1, hi));\n buf.append(']');\n\n fromIndex = hi + 1;\n } else {\n buf.append(str.substring(fromIndex));\n break;\n }\n }\n\n return buf.toString();\n}\n public static String replaceMacro(String str) {\n Pattern pattern = Pattern.compile(\"(array)<(\\\\w+)>\");\n Matcher matcher = pattern.matcher(str);\n\n StringBuilder buf = new StringBuilder(str.length());\n int fromIndex = 0;\n\n while (matcher.find(fromIndex)) {\n int lo = matcher.start();\n int hi = matcher.end();\n\n buf.append(str, fromIndex, lo).append(matcher.group(1));\n buf.append('[').append(matcher.group(2)).append(']');\n\n fromIndex = hi;\n }\n\n if (fromIndex < str.length()) {\n buf.append(str.substring(fromIndex));\n }\n\n return buf.toString();\n}\n" }, { "answer_id": 74639092, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 1, "selected": false, "text": "array<(\\w+)> array< > array public class Main {\n public static void main(String[] args) {\n String str = \"\"\"\n <tr><td>Asdft array<object> tesnp array<int></td>\n <td>asldhj\n ashd\n repl array<String>\n array\n asdhl\n afe array<object>\n endoftest</td></tr>\n \"\"\";\n\n String result = str.replaceAll(\"array<(\\\\w+)>\", \"array[$1]\");\n\n System.out.println(result);\n }\n}\n <tr><td>Asdft array[object] tesnp array[int]</td>\n<td>asldhj\nashd\nrepl array[String]\narray\nasdhl\nafe array[object]\nendoftest</td></tr>\n" }, { "answer_id": 74646335, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 1, "selected": false, "text": "(?<=array) // positive lookbehind (preceded by \"array\")\n< // opening angle bracket\n(\\w+) // one or more word characters (matching group)\n> // closing angle bracket\n import java.util.regex.*;\n\npublic class Example {\n public static String replace(String str, String pattern, String replacement) {\n return Pattern\n .compile(pattern, Pattern.MULTILINE)\n .matcher(str)\n .replaceAll(replacement);\n }\n \n public static String fixHtmlText(String htmlText) {\n return replace(htmlText, \"(?<=array)<(\\\\w+)>\", \"[$1]\");\n }\n \n public static void main(String[] args) {\n String htmlText = \"<tr><td>Asdft array<object> tesnp array<int></td>\\n\"\n + \"<td>asldhj\\n\"\n + \"ashd\\n\"\n + \"repl array<String>\\n\"\n + \"array\\n\"\n + \"asdhl\\n\"\n + \"afe array<object>\\n\"\n + \"endoftest</td></tr>\";\n \n System.out.println(fixHtmlText(htmlText));\n }\n}\n <tr><td>Asdft array[object] tesnp array[int]</td>\n<td>asldhj\nashd\nrepl array[String]\narray\nasdhl\nafe array[object]\nendoftest</td></tr>\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17479642/" ]
74,631,683
<p>I'm building a small e-commerce store with an admin panel for myself. I use <code>Firebase firestore</code> as my backend to store all the user's data.<br /> I have a root 'users' collection with a document for every single registered user and everything else each user has is branching out of the user doc.</p> <p>Here are firestore commands i perform so you understand the structure better.</p> <p><code>db.collection('users').doc(userId).collection('categories').doc(subCategoryId)...</code> <code>db.collection('users').doc(userId).collection('subcategories').doc(subCategoryId)...</code></p> <p>I use Vuex so every time i need to change something on my firestore (update a product category, remove a category etc.), i dispatch an appropriate action. The first thing any of those actions does is to go ahead and dispatch another action from <code>auth.js</code> that gets the userId.</p> <p>The problem is that if the action in question should run in a <code>mounted()</code> lifecycle hook, then it fails to grab the <code>userId</code>.<br /> In <code>EditCategory.vue</code> <code>updateCategory</code> action works perfectly well because <code>SubmitHandler()</code> is triggered on click event but in <code>Categories.vue</code> the <code>fetchCategories</code> does not work and spit out an error:</p> <pre><code>[Vue warn]: Error in mounted hook (Promise/async): &quot;FirebaseError: [code=invalid-argument]: Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: null&quot; Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: null </code></pre> <p>Which, as far as i understand it, basically tells me that <code>fetchCategories()</code> action's firestore query could not be performed because the <code>userId</code> was not recieved.</p> <p>After two days of moving stuff around i noticed that errors only occur if i refresh the page. If i switch to other tab and back on without refreshing, then <code>fetchCategories()</code> from <code>Categories.vue</code> <code>mounted()</code> hook works. Placing the code in to <code>created()</code> hook gives the same result.</p> <p>I think that there is some fundamental thing i am missing about asynchronous code and lifecycle hooks.</p> <p>Categories.vue component</p> <pre><code> &lt;template&gt; &lt;div class=&quot;category-main&quot;&gt; &lt;section&gt; &lt;div class=&quot;section-cols&quot; v-if=&quot;!loading&quot;&gt; &lt;EditCategory v-on:updatedCategory=&quot;updatedCategory&quot; v-bind:categories=&quot;categories&quot; v-bind:key=&quot;categories.length + updateCount&quot; /&gt; &lt;/div&gt; &lt;/section&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import EditCategory from '@/components/admin/EditCategory.vue' export default { name: 'AdminCategories', components: { EditCategory, }, data: () =&gt; ({ updateCount: 0, loading: true, categories: [], }), async mounted() { this.categories = await this.$store.dispatch('fetchCategories');// FAILS! this.loading = false; }, methods: { addNewCategory(category) { this.categories.push(category); }, updatedCategory(category) { const catIndex = this.categories.findIndex(c =&gt; c.id === category.id); this.categories[catIndex].title = category.title; this.categories[catIndex].path = category.path; this.updateCount++; } } } &lt;/script&gt; </code></pre> <p>category.js store file</p> <pre><code>import firebase, { firestore } from &quot;firebase/app&quot;; import db from '../../fb'; export default { actions: { async getUserId() { const user = firebase.auth().currentUser; return user ? user.uid : null; }, export default { state: { test: 10, categories: [], subCategories: [], currentCategory: '', }, mutations: { setCategories(state, payload){ state.categories = payload; }, }, actions: { async fetchCategories({commit, dispatch}) { try { const userId = await dispatch('getUserId'); const categoryArr = []; await db.collection('users').doc(userId).collection('categories').get().then((querySnapshot) =&gt; { querySnapshot.forEach((doc) =&gt; { categoryArr.push({ id: doc.id, ...doc.data() }) }); }) commit('setCategories', categoryArr); return categoryArr; } catch (err) { throw err; } }, async updateCategory({commit, dispatch}, {title, path, id}) { try { const userId = await dispatch('getUserId'); console.log('[category.js] updateCategory', userId); await db.collection('users').doc(userId).collection('categories').doc(id).update({ title, path }) commit('rememberCurrentCategory', id); return; } catch (err) {throw err;} } }, } </code></pre> <p>auth.js store file</p> <pre><code>import firebase, { firestore } from &quot;firebase/app&quot;; import db from '../../fb'; export default { actions: { ...async login(), async register(), async logout() async getUserId() { const user = firebase.auth().currentUser; return user ? user.uid : null; }, }, } </code></pre> <p>index.js store file</p> <pre><code>import Vue from 'vue' import Vuex from 'vuex' import auth from './auth' import products from './products' import info from './info' import category from './category' Vue.use(Vuex) export default new Vuex.Store({ modules: { auth, products, info, category, } }) </code></pre> <p>EditCategory.vue</p> <pre><code>export default { name: 'EditCategory', data: () =&gt; ({ select: null, title: '', path: '', current: null }), props: { categories: { type: Array, required: true } }, methods: { async submitHandler() { if (this.$v.invalid){ this.$v.$touch() return; } try { const categoryData = { id : this.current, title: this.title, path: this.path }; await this.$store.dispatch('updateCategory', categoryData);// WORKS! this.$emit('updatedCategory', categoryData); } catch (err) { throw err; } }, }, //takes current category id from store getter computed: { categoryFromState() { return this.$store.state.currentCategory; } }, created() { console.log('[EditCategory.vue'], currentCategory); }, mounted(){ this.select = M.FormSelect.init(this.$refs.select); M.updateTextFields(); }, destroyed() { if (this.select &amp;&amp; this.select.destroy) { this.select.destroy; } } } &lt;/script&gt; </code></pre>
[ { "answer_id": 74632828, "author": "Dony", "author_id": 13343311, "author_profile": "https://Stackoverflow.com/users/13343311", "pm_score": 2, "selected": true, "text": "async getUserId() {\n const user = firebase.auth().currentUser;\n return user ? user.uid : null;\n}\n\nconst userId = await dispatch('getUserId')\n getUserId() {\n const user = firebase.auth().currentUser;\n return user ? user.uid : null;\n}\n\nconst userId = dispatch('getUserId')\n" }, { "answer_id": 74642058, "author": "MGUdodik666", "author_id": 12868956, "author_profile": "https://Stackoverflow.com/users/12868956", "pm_score": 0, "selected": false, "text": "import Vue from 'vue'\nimport Router from 'vue-router'\nimport firebase from 'firebase/app';\n\nVue.use(Router);\n\nconst router = new Router({\n mode: 'history',\n routes: [\n {\n path: '/',\n name: 'home',\n meta: {layout: 'main-layout'},\n component: () => import('./views/main/Home.vue')\n },\n {\n path: '/bouquets',\n name: 'bouquets',\n meta: {layout: 'main-layout'},\n component: () => import('./views/main/Bouquets.vue')\n },\n {\n path: '/sets',\n name: 'sets',\n meta: {layout: 'main-layout'},\n component: () => import('./views/main/Sets.vue')\n },\n {\n path: '/cart',\n name: 'cart',\n meta: {layout: 'main-layout'},\n component: () => import('./views/main/Cart.vue')\n },\n {\n path: '/login',\n name: 'login',\n meta: {layout: 'empty-layout'},\n component: () => import('./views/empty/Login.vue')\n },\n {\n path: '/register',\n name: 'register',\n meta: {layout: 'empty-layout'},\n component: () => import('./views/empty/Register.vue')\n },\n {\n path: '/admin',\n name: 'admin',\n meta: {layout: 'admin-layout', auth: true},\n component: () => import('./views/admin/Home.vue'),\n children: [\n {\n path: 'categories',\n name: 'adminCategories',\n meta: {layout: 'admin-layout', auth: true},\n component: () => import('./views/admin/Categories'),\n },\n {\n path: 'subcategories',\n name: 'adminSubcategories',\n meta: {layout: 'admin-layout', auth: true},\n component: () => import('./views/admin/SubCategories'),\n },\n {\n path: 'products',\n name: 'adminProducts',\n meta: {layout: 'admin-layout', auth: true},\n component: () => import('./views/admin/Products'),\n },\n ]\n },\n {\n path: '/checkout',\n name: 'checkout',\n meta: {layout: 'main-layout'},\n component: () => import('./views/main/Checkout.vue')\n },\n {\n path: '/:subcategory',\n name: 'subcategory',\n meta: {layout: 'main-layout'},\n props: true,\n params: true,\n component: () => import('./views/main/Subcategory.vue')\n },\n ]\n})\n\nrouter.beforeEach((to, from, next) => {\n //if currentUser exists then user is logged in\n const currentUser = firebase.auth().currentUser;\n //does a route has auth == true\n const requireAuth = to.matched.some(record => record.meta.auth);\n //if auth is required but user is not authentificated than redirect to login\n if (requireAuth && !currentUser) {\n // next('/login?message=login');\n next('login')\n } else {\n next();\n }\n})\n\nexport default router;\n fetchCategories() async fetchCategories({commit, dispatch}) {\n const userId = await dispatch('getUserId')\n\n try {\n const categoryArr = [];\n await db.collection('users').doc(userId).collection('categories').get().then((querySnapshot) => {\n querySnapshot.forEach((doc) => {\n categoryArr.push({ id: doc.id, ...doc.data() })\n });\n })\n commit('setCategories', categoryArr);\n return categoryArr;\n } catch (err) { throw err; }\n }, \n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12868956/" ]
74,631,702
<p>I don't have any Ubuntu machines enabled with internet and I have requirement to have a docker image ready with some basic softwares enabled as this need to be configured as our Azuredevops build agent.</p> <p>So in order to work my Dockerfile , I used one of aksnode itself to build my docker image as there I could see some of the apt-get commands working somehow (may be with default internet connectivity enabled there for aks functionalities).</p> <p>Below is the source.list content of aks node and I tried to copy the same to my Ubuntu based Dockerfile</p> <pre><code>deb http://azure.archive.ubuntu.com/ubuntu/ bionic main restricted # deb-src http://azure.archive.ubuntu.com/ubuntu/ bionic main restricted ## Major bug fix updates produced after the final release of the ## distribution. deb http://azure.archive.ubuntu.com/ubuntu/ bionic-updates main restricted # deb-src http://azure.archive.ubuntu.com/ubuntu/ bionic-updates main restricted ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team. Also, please note that software in universe WILL NOT receive any ## review or updates from the Ubuntu security team. deb http://azure.archive.ubuntu.com/ubuntu/ bionic universe # deb-src http://azure.archive.ubuntu.com/ubuntu/ bionic universe deb http://azure.archive.ubuntu.com/ubuntu/ bionic-updates universe # deb-src http://azure.archive.ubuntu.com/ubuntu/ bionic-updates universe ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team, and may not be under a free licence. Please satisfy yourself as to ## your rights to use the software. Also, please note that software in ## multiverse WILL NOT receive any review or updates from the Ubuntu ## security team. deb http://azure.archive.ubuntu.com/ubuntu/ bionic multiverse # deb-src http://azure.archive.ubuntu.com/ubuntu/ bionic multiverse deb http://azure.archive.ubuntu.com/ubuntu/ bionic-updates multiverse # deb-src http://azure.archive.ubuntu.com/ubuntu/ bionic-updates multiverse ## N.B. software from this repository may not have been tested as ## extensively as that contained in the main release, although it includes ## newer versions of some applications which may provide useful features. ## Also, please note that software in backports WILL NOT receive any review ## or updates from the Ubuntu security team. deb http://azure.archive.ubuntu.com/ubuntu/ bionic-backports main restricted universe multiverse # deb-src http://azure.archive.ubuntu.com/ubuntu/ bionic-backports main restricted universe multiverse ## Uncomment the following two lines to add software from Canonical's ## 'partner' repository. ## This software is not part of Ubuntu, but is offered by Canonical and the ## respective vendors as a service to Ubuntu users. # deb http://archive.canonical.com/ubuntu bionic partner # deb-src http://archive.canonical.com/ubuntu bionic partner deb http://azure.archive.ubuntu.com/ubuntu/ bionic-security main restricted # deb-src http://azure.archive.ubuntu.com/ubuntu/ bionic-security main restricted deb http://azure.archive.ubuntu.com/ubuntu/ bionic-security universe # deb-src http://azure.archive.ubuntu.com/ubuntu/ bionic-security universe deb http://azure.archive.ubuntu.com/ubuntu/ bionic-security multiverse # deb-src http://azure.archive.ubuntu.com/ubuntu/ bionic-security multiverse </code></pre> <p>After copying the same file to my Docker image build step as below.</p> <pre><code>COPY ./sources.list /etc/apt/ </code></pre> <p>I could successfully install the basic software's like, curl wget, jq, git, python, etc...</p> <p>But I am not able to install softwares like, AzureCLI, Docker, dockerce-and nodejs, chrome-headless, etc..</p> <p>My dockerfile parts for them as below as below.</p> <pre><code>#4-Install AzureCLI RUN curl -LsS https://aka.ms/InstallAzureCLIDeb | bash \ &amp;&amp; rm -rf /var/lib/apt/lists/* #7-install node RUN curl -sL https://deb.nodesource.com/setup_11.x | bash - RUN apt-get -y install nodejs RUN npm install #9-install docker daemon inside docker RUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg RUN echo \ &quot;deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) stable&quot; | tee /etc/apt/sources.list.d/docker.list &gt; /dev/null RUN apt-get update RUN apt-get install docker-ce docker-ce-cli containerd.io -y </code></pre> <p>where all I am getting the error as below</p> <pre><code>curl: (35) OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to </code></pre> <p>So looking for a way to get succeeded with all the above softwares installed without internet or do we have any azure archive repo for the same like other softwares enabled?</p>
[ { "answer_id": 74632828, "author": "Dony", "author_id": 13343311, "author_profile": "https://Stackoverflow.com/users/13343311", "pm_score": 2, "selected": true, "text": "async getUserId() {\n const user = firebase.auth().currentUser;\n return user ? user.uid : null;\n}\n\nconst userId = await dispatch('getUserId')\n getUserId() {\n const user = firebase.auth().currentUser;\n return user ? user.uid : null;\n}\n\nconst userId = dispatch('getUserId')\n" }, { "answer_id": 74642058, "author": "MGUdodik666", "author_id": 12868956, "author_profile": "https://Stackoverflow.com/users/12868956", "pm_score": 0, "selected": false, "text": "import Vue from 'vue'\nimport Router from 'vue-router'\nimport firebase from 'firebase/app';\n\nVue.use(Router);\n\nconst router = new Router({\n mode: 'history',\n routes: [\n {\n path: '/',\n name: 'home',\n meta: {layout: 'main-layout'},\n component: () => import('./views/main/Home.vue')\n },\n {\n path: '/bouquets',\n name: 'bouquets',\n meta: {layout: 'main-layout'},\n component: () => import('./views/main/Bouquets.vue')\n },\n {\n path: '/sets',\n name: 'sets',\n meta: {layout: 'main-layout'},\n component: () => import('./views/main/Sets.vue')\n },\n {\n path: '/cart',\n name: 'cart',\n meta: {layout: 'main-layout'},\n component: () => import('./views/main/Cart.vue')\n },\n {\n path: '/login',\n name: 'login',\n meta: {layout: 'empty-layout'},\n component: () => import('./views/empty/Login.vue')\n },\n {\n path: '/register',\n name: 'register',\n meta: {layout: 'empty-layout'},\n component: () => import('./views/empty/Register.vue')\n },\n {\n path: '/admin',\n name: 'admin',\n meta: {layout: 'admin-layout', auth: true},\n component: () => import('./views/admin/Home.vue'),\n children: [\n {\n path: 'categories',\n name: 'adminCategories',\n meta: {layout: 'admin-layout', auth: true},\n component: () => import('./views/admin/Categories'),\n },\n {\n path: 'subcategories',\n name: 'adminSubcategories',\n meta: {layout: 'admin-layout', auth: true},\n component: () => import('./views/admin/SubCategories'),\n },\n {\n path: 'products',\n name: 'adminProducts',\n meta: {layout: 'admin-layout', auth: true},\n component: () => import('./views/admin/Products'),\n },\n ]\n },\n {\n path: '/checkout',\n name: 'checkout',\n meta: {layout: 'main-layout'},\n component: () => import('./views/main/Checkout.vue')\n },\n {\n path: '/:subcategory',\n name: 'subcategory',\n meta: {layout: 'main-layout'},\n props: true,\n params: true,\n component: () => import('./views/main/Subcategory.vue')\n },\n ]\n})\n\nrouter.beforeEach((to, from, next) => {\n //if currentUser exists then user is logged in\n const currentUser = firebase.auth().currentUser;\n //does a route has auth == true\n const requireAuth = to.matched.some(record => record.meta.auth);\n //if auth is required but user is not authentificated than redirect to login\n if (requireAuth && !currentUser) {\n // next('/login?message=login');\n next('login')\n } else {\n next();\n }\n})\n\nexport default router;\n fetchCategories() async fetchCategories({commit, dispatch}) {\n const userId = await dispatch('getUserId')\n\n try {\n const categoryArr = [];\n await db.collection('users').doc(userId).collection('categories').get().then((querySnapshot) => {\n querySnapshot.forEach((doc) => {\n categoryArr.push({ id: doc.id, ...doc.data() })\n });\n })\n commit('setCategories', categoryArr);\n return categoryArr;\n } catch (err) { throw err; }\n }, \n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16092023/" ]
74,631,728
<p>I want to parallely send a GET request for the specified count say 100 times. How to achieve this using JMeter or Python ?</p> <p>I tried bzm parallel executor but that doesn't workout.</p>
[ { "answer_id": 74631854, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "import requests\nimport threading\n\ntotalRequests = 0\nnumberOfThreads = 10\nthreads = [0] * numberOfThreads\n\n\ndef worker(thread):\n r = requests.get(\"url\")\n threads[thread] = 0 # free thread\n\n\nwhile totalRequests < 100:\n for thread in range(numberOfThreads):\n if threads[thread] == 0:\n threads[thread] = 1 # occupy thread\n t = threading.Thread(target=worker, args=(thread,))\n t.start()\n totalRequests += 1\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11341832/" ]
74,631,739
<p>So this is the menu, but I want the circled three buttons to be on the right side...How can I do this? I am using Angular material.</p> <p><a href="https://i.stack.imgur.com/KxY6r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KxY6r.png" alt="menu" /></a></p>
[ { "answer_id": 74632160, "author": "Dargio", "author_id": 11564060, "author_profile": "https://Stackoverflow.com/users/11564060", "pm_score": 2, "selected": true, "text": "<mat-toolbar-row>\n <span>Second Line</span>\n <span class=\"example-spacer\"></span>\n <mat-icon class=\"example-icon\" aria-hidden=\"false\" aria-label=\"Example user verified icon\">verified_user</mat-icon>\n</mat-toolbar-row>\n .example-spacer {\n flex: 1 1 auto;\n}\n" }, { "answer_id": 74633245, "author": "Hossein Rahmian", "author_id": 15953442, "author_profile": "https://Stackoverflow.com/users/15953442", "pm_score": 0, "selected": false, "text": "<div class=\"parent\">\n <div class=\"child\" style=\"display : flex , justify-content :\"space-between\">\n <any Element(Tag)></any Element(Tag)>\n <any Element(Tag)></any Element(Tag)>\n </div>\n</div>\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17384995/" ]
74,631,748
<p>I have a field in a table of our db that works like an event-like payload, where all changes to different entities are gathered. See example below for a single field of the object:</p> <pre><code>'---\nfield_one: 1\nfield_two: 20\nfield_three: 4\nid: 1234\nanother_id: 5678\nsome_text: Hey you\na_date: 2022-11-29\nutc: this_utc\nanother_date: 2022-11-30\nutc: another_utc' </code></pre> <p>Since accessing this field with pure SQL is a pain, I was thinking of parsing it as a JSON so that it would look like this:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;field_one&quot;:&quot;1&quot;, &quot;field_two&quot;: &quot;20&quot;, &quot;field_three&quot;: &quot;4&quot;, &quot;id&quot;: &quot;1234&quot;, &quot;another_id&quot;: &quot;5678&quot;, &quot;some_text&quot;: &quot;Hey you&quot;, &quot;a_date&quot;: &quot;2022-11-29&quot;, &quot;utc&quot;: &quot;2022-11-29 15:29:28.159296000 Z&quot;, &quot;another_date&quot;: &quot;2022-11-30&quot;, &quot;utc&quot;: &quot;2022-11-30 13:34:59.000000000 Z&quot; } </code></pre> <p>And then just use a Snowflake-native approach to access the values I need.</p> <p>As you can see, though, there are two fields that are called <code>utc</code>, since one is referring to the first date (<code>a_date</code>), and the second one is referring to the second date (<code>another_date)</code>. I believe these are nested in the object, but it's difficult to assess with the format of the field.</p> <p>This is a problem since I can't differentiate between one <code>utc</code> and another when giving the string the format I need and running a <code>parse_json()</code> function (due to both keys using the same name).</p> <p>My SQL so far looks like the following:</p> <pre class="lang-sql prettyprint-override"><code>select object, replace(object, '---\n', '{&quot;') || '&quot;}' as first, replace(first, '\n', '&quot;,&quot;') as second_, replace(second_, ': ', '&quot;:&quot;') as third, replace(third, ' ', '') as fourth, replace(fourth, ' ', '') as last from my_table </code></pre> <p>(Steps third and fourth are needed because I have some fields that have extra spaces in them)</p> <p>And this actually gives me the format I need, but due to what I mentioned around the <code>utc</code> keys, I cannot parse the string as a JSON.</p> <p>Also note that the structure of the string might change from row to row, meaning that some rows might gather two <code>utc</code> keys, while others might have one, and others even five.</p> <p>Any ideas on how to overcome that?</p>
[ { "answer_id": 74637630, "author": "Felipe Hoffa", "author_id": 132438, "author_profile": "https://Stackoverflow.com/users/132438", "pm_score": 2, "selected": true, "text": "regexp_replace() with data as (\n select '---\\nfield_one: 1\\nfield_two: 20\\nfield_three: 4\\nid: 1234\\nanother_id: 5678\\nsome_text: Hey you\\na_date: 2022-11-29\\nutc: this_utc\\nanother_date: 2022-11-30\\nutc: another_utc' o\n)\n\nselect parse_json(last2)\nfrom (\n select o,\n replace(o, '---\\n', '{\"') || '\"}' as first,\n replace(first, '\\n', '\",\"') as second_,\n replace(second_, ': ', '\":\"') as third,\n replace(third, ' ', '') as fourth,\n replace(fourth, ' ', '') as last,\n regexp_replace(last, '\"utc\"', '\"utc2\"', 1, 2) last2\n from data\n)\n;\n" }, { "answer_id": 74646700, "author": "Rajat", "author_id": 9947159, "author_profile": "https://Stackoverflow.com/users/9947159", "pm_score": 0, "selected": false, "text": "parse_json set str='---\\nfield_one: 1\\nfield_two: 20\\nfield_three: 4\\nid: 1234\\nanother_id: 5678\\nsome_text: Hey you\\na_date: 2022-11-29\\nutc: 2022-11-29 15:29:28.159296000 Z\\nanother_date: 2022-11-30\\nutc: 2022-11-30 13:34:59.000000000 Z';\n\n \nselect regexp_replace($str,'[0-9]{4}-[0-9]{2}-[0-9]{2}\\nutc:')\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11532919/" ]
74,631,749
<p>Let's say I have some sql that is going to return a result set that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>A1</td> <td>Val1</td> </tr> <tr> <td>A1</td> <td>Val2</td> </tr> <tr> <td>A1</td> <td>Val3</td> </tr> <tr> <td>B1</td> <td>Val4</td> </tr> <tr> <td>B1</td> <td>Val5</td> </tr> <tr> <td>B1</td> <td>Val6</td> </tr> </tbody> </table> </div> <pre><code>val query = sql&quot;&quot;&quot;select blah&quot;&quot;&quot;.query[(ID, VALUE)] val result: ConnectionIO[(ID, List[VALUE])] = for { tuples &lt;- query.to[List] } yield tuples.traverse(t =&gt; t._1 -&gt; t._2) </code></pre> <p>This is the closest I can get, but I get a compiler error:</p> <pre><code>Could not find an instance of Applicative for [+T2](ID, T2) </code></pre> <p>What I want is to turn this into a Map[ID, List[VALUE]]</p>
[ { "answer_id": 74637630, "author": "Felipe Hoffa", "author_id": 132438, "author_profile": "https://Stackoverflow.com/users/132438", "pm_score": 2, "selected": true, "text": "regexp_replace() with data as (\n select '---\\nfield_one: 1\\nfield_two: 20\\nfield_three: 4\\nid: 1234\\nanother_id: 5678\\nsome_text: Hey you\\na_date: 2022-11-29\\nutc: this_utc\\nanother_date: 2022-11-30\\nutc: another_utc' o\n)\n\nselect parse_json(last2)\nfrom (\n select o,\n replace(o, '---\\n', '{\"') || '\"}' as first,\n replace(first, '\\n', '\",\"') as second_,\n replace(second_, ': ', '\":\"') as third,\n replace(third, ' ', '') as fourth,\n replace(fourth, ' ', '') as last,\n regexp_replace(last, '\"utc\"', '\"utc2\"', 1, 2) last2\n from data\n)\n;\n" }, { "answer_id": 74646700, "author": "Rajat", "author_id": 9947159, "author_profile": "https://Stackoverflow.com/users/9947159", "pm_score": 0, "selected": false, "text": "parse_json set str='---\\nfield_one: 1\\nfield_two: 20\\nfield_three: 4\\nid: 1234\\nanother_id: 5678\\nsome_text: Hey you\\na_date: 2022-11-29\\nutc: 2022-11-29 15:29:28.159296000 Z\\nanother_date: 2022-11-30\\nutc: 2022-11-30 13:34:59.000000000 Z';\n\n \nselect regexp_replace($str,'[0-9]{4}-[0-9]{2}-[0-9]{2}\\nutc:')\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135624/" ]
74,631,751
<p>I am currently running python 3.6 on my Mac, and installed the latest version of Python (3.11) by downloading and installing through the <a href="https://www.python.org/downloads/release/python-3110/" rel="nofollow noreferrer">official python releases</a>. Running <code>python3.11</code> opens the interpreter in 3.11, and <code>python3.11 --version</code> returns <code>Python 3.11.0</code>, but <code>python -V</code> in terminal returns <code>Python 3.6.1 :: Continuum Analytics, Inc.</code>.</p> <p>I tried to install again via homebrew using <code>brew install python@3.11</code> but got the same results.</p> <p>More frustrating, when I try to open a virtual environment using <code>python3 -m venv env</code> I get</p> <pre><code>Error: Command '['/Users/User/env/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1. </code></pre> <p>I altered <code>.bash_profile</code> with</p> <pre><code># Setting PATH for Python 3.11 # The original version is saved in .bash_profile.pysave PATH=&quot;/Library/Frameworks/Python.framework/Versions/3.11/bin:${PATH}&quot; export PATH . &quot;$HOME/.cargo/env&quot; </code></pre> <p>And created a <code>.zprofile</code> <a href="https://stackoverflow.com/a/67692362/6069097">based on this post</a> with</p> <pre><code>export PYTHONPATH=$HOME/Users/User </code></pre> <p>and a <code>.zshrc</code> <a href="https://stackoverflow.com/a/71842117/6069097">based on this post</a>, but <code>--version</code> still throws <code>python3.6</code>.</p> <p>I'm running Big Sur OS. Pip and homebrew are up to date and upgraded. Acknowledging that I'm totally foolish, what do I need to do to get python &gt;3.7 running in terminal?</p>
[ { "answer_id": 74637630, "author": "Felipe Hoffa", "author_id": 132438, "author_profile": "https://Stackoverflow.com/users/132438", "pm_score": 2, "selected": true, "text": "regexp_replace() with data as (\n select '---\\nfield_one: 1\\nfield_two: 20\\nfield_three: 4\\nid: 1234\\nanother_id: 5678\\nsome_text: Hey you\\na_date: 2022-11-29\\nutc: this_utc\\nanother_date: 2022-11-30\\nutc: another_utc' o\n)\n\nselect parse_json(last2)\nfrom (\n select o,\n replace(o, '---\\n', '{\"') || '\"}' as first,\n replace(first, '\\n', '\",\"') as second_,\n replace(second_, ': ', '\":\"') as third,\n replace(third, ' ', '') as fourth,\n replace(fourth, ' ', '') as last,\n regexp_replace(last, '\"utc\"', '\"utc2\"', 1, 2) last2\n from data\n)\n;\n" }, { "answer_id": 74646700, "author": "Rajat", "author_id": 9947159, "author_profile": "https://Stackoverflow.com/users/9947159", "pm_score": 0, "selected": false, "text": "parse_json set str='---\\nfield_one: 1\\nfield_two: 20\\nfield_three: 4\\nid: 1234\\nanother_id: 5678\\nsome_text: Hey you\\na_date: 2022-11-29\\nutc: 2022-11-29 15:29:28.159296000 Z\\nanother_date: 2022-11-30\\nutc: 2022-11-30 13:34:59.000000000 Z';\n\n \nselect regexp_replace($str,'[0-9]{4}-[0-9]{2}-[0-9]{2}\\nutc:')\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6069097/" ]
74,631,789
<p>Given this data how can give rank for each repeating data. 1 to 5 i want to rank as 1 and next 1 to 5 i want to rank as 2</p> <p>Data</p> <pre><code>1 2 3 4 5 1 2 3 4 5 </code></pre> <p>Expecting output</p> <p>Data | Column</p> <pre><code>1 1 2 1 3 1 4 1 5 1 1 2 2 2 3 2 4 2 5 2 </code></pre> <p>I was trying to implement using row number but Below is the exact requirement that i have to implement :</p> <pre><code>Refcol value column 1 refers to time 2 refers to name 3 refers to location 4 refers to Available (1 or 0 or null) ID | Refcol | Metric 1 1 02/02/2022 1 2 Adam 1 3 Japan 1 4 1 1 1 03/02/2022 1 2 Smith 1 3 England 1 4 0 </code></pre> <p>Now i want to transform above data as shown below</p> <p><strong>Expected Ouput</strong></p> <pre><code>ID | time | name | location | Available 1 02/02/2022 Adam Japan 1 1 03/02/2022 Smith England 0 </code></pre>
[ { "answer_id": 74631867, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 0, "selected": false, "text": "DECLARE @ints TABLE (INT INT)\nINSERT INTO @ints (INT) VALUES\n(1), (2), (3), (4), (5),\n(1), (2), (3), (4), (5)\n SELECT INT, ROW_NUMBER() OVER (PARTITION BY INT ORDER BY INT) AS rn\n FROM @ints\n ORDER BY rn, INT\n INT rn\n------\n1 1\n2 1\n3 1\n4 1\n5 1\n1 2\n2 2\n3 2\n4 2\n5 2\n" }, { "answer_id": 74631890, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 2, "selected": true, "text": "CREATE TABLE Numbers (\n num int not null\n );\n \nINSERT INTO Numbers\nVALUES (1),(2),(3),(4),(5),(1),(2),(3),(4),(5)\n WITH prelim AS (\n SELECT n.num\n , ROW_NUMBER() OVER(PARTITION BY n.num ORDER BY n.num ASC) as row_num\n FROM Numbers as n\n)\nSELECT\n p.num\n , p.row_num\nFROM prelim as p\nORDER BY p.row_num, p.num\n | num | row_num |\n|-----|---------|\n| 1 | 1 |\n| 2 | 1 |\n| 3 | 1 |\n| 4 | 1 |\n| 5 | 1 |\n| 1 | 2 |\n| 2 | 2 |\n| 3 | 2 |\n| 4 | 2 |\n| 5 | 2 |\n CREATE TABLE attributes (\n ID int not null\n , RefCol int not null\n , Metric nvarchar(50) not null\n , SetID int null\n);\n\nINSERT INTO attributes (ID, RefCol, Metric) \nVALUES \n (1,1,'02/02/2022')\n ,(1,2,'Adam')\n ,(1,3,'Japan')\n ,(1,4,'1')\n ,(1,1,'03/02/2022')\n ,(1,2,'Smith')\n ,(1,3,'England')\n ,(1,4,'0')\n;\n\nDECLARE @setID int = 0;\n\nWHILE (EXISTS (SELECT ID FROM attributes WHERE SetID is NULL))\nBEGIN\n UPDATE TOP (4) attributes\n SET SetID = @setID\n FROM attributes\n WHERE SetID IS NULL\n ;\n\n SET @setID = @setID + 1;\nEND\n\nSELECT * FROM attributes;\n\nSELECT DISTINCT \n a.SetID\n , a.ID\n , aTime.Metric as [time]\n , aName.Metric as [name]\n , aLoc.Metric as [location]\n , aAvail.Metric as [Available]\nFROM attributes as a\n LEFT OUTER JOIN attributes as aTime\n ON aTime.SetID = a.SetID\n AND aTime.RefCol = 1\n LEFT OUTER JOIN attributes as aName\n ON aName.SetID = a.SetID\n AND aName.RefCol = 2\n LEFT OUTER JOIN attributes as aLoc\n ON aLoc.SetID = a.SetID\n AND aLoc.RefCol = 3\n LEFT OUTER JOIN attributes as aAvail\n ON aAvail.SetID = a.SetID\n AND aAvail.RefCol = 4\n;\n\n\n\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9510880/" ]
74,631,799
<p>I want to integrate a ASP.NET Core WebApi into a solution which consists of many other projects. (I use dotnet 6.0) Within the solution the WebAPI is started as Thread by the Main project. The problem is that if I run the WebApi from the other project only an empty WebApi is started. (Default Ports are used, not the configured one and there are no controllers...)</p> <p>Can anybody help me?</p> <p>This is a minimal soltution with the same problem I discribed above:</p> <p><a href="https://i.stack.imgur.com/8xY6m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8xY6m.png" alt="Solution structure" /></a></p> <p>The WebApi is the default VisualStudio 2022 project. I only made small changes in the Program.cs file. This is the Code of the WebApi Project's Program.cs file:</p> <pre><code>namespace WebApi; public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); } } </code></pre> <p>Code of the Programm.cs of the Main Project:</p> <pre><code>using WebApi; internal class Program { private static void Main(string[] args) { Console.WriteLine(&quot;Hello, World!&quot;); WebApi.Program.Main(Array.Empty&lt;string&gt;()); } } </code></pre> <p>launchSettings.json</p> <pre><code>{ &quot;$schema&quot;: &quot;https://json.schemastore.org/launchsettings.json&quot;, &quot;iisSettings&quot;: { &quot;windowsAuthentication&quot;: false, &quot;anonymousAuthentication&quot;: true, &quot;iisExpress&quot;: { &quot;applicationUrl&quot;: &quot;http://localhost:56423&quot;, &quot;sslPort&quot;: 44385 } }, &quot;profiles&quot;: { &quot;WebApi&quot;: { &quot;commandName&quot;: &quot;Project&quot;, &quot;dotnetRunMessages&quot;: true, &quot;launchBrowser&quot;: true, &quot;launchUrl&quot;: &quot;swagger&quot;, &quot;applicationUrl&quot;: &quot;https://localhost:7257;http://localhost:5257&quot;, &quot;environmentVariables&quot;: { &quot;ASPNETCORE_ENVIRONMENT&quot;: &quot;Development&quot; } }, &quot;IIS Express&quot;: { &quot;commandName&quot;: &quot;IISExpress&quot;, &quot;launchBrowser&quot;: true, &quot;launchUrl&quot;: &quot;swagger&quot;, &quot;environmentVariables&quot;: { &quot;ASPNETCORE_ENVIRONMENT&quot;: &quot;Development&quot; } } } } </code></pre> <p>This is how it looks if I run the WebApi from the Main project:</p> <pre><code>Hello, World! info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5000 info: Microsoft.Hosting.Lifetime[14] Now listening on: https://localhost:5001 info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down. info: Microsoft.Hosting.Lifetime[0] Hosting environment: Production info: Microsoft.Hosting.Lifetime[0] Content root path: C:\data\Experimental\CallWebApiFromOtherProject\Main\bin\Debug\net6.0\ </code></pre> <p>(Controllers and Swagger is not available. Also the ports are not the ones defined above. -&gt; Only a Webserver without anything)</p> <p>What I did wrong?</p>
[ { "answer_id": 74631867, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 0, "selected": false, "text": "DECLARE @ints TABLE (INT INT)\nINSERT INTO @ints (INT) VALUES\n(1), (2), (3), (4), (5),\n(1), (2), (3), (4), (5)\n SELECT INT, ROW_NUMBER() OVER (PARTITION BY INT ORDER BY INT) AS rn\n FROM @ints\n ORDER BY rn, INT\n INT rn\n------\n1 1\n2 1\n3 1\n4 1\n5 1\n1 2\n2 2\n3 2\n4 2\n5 2\n" }, { "answer_id": 74631890, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 2, "selected": true, "text": "CREATE TABLE Numbers (\n num int not null\n );\n \nINSERT INTO Numbers\nVALUES (1),(2),(3),(4),(5),(1),(2),(3),(4),(5)\n WITH prelim AS (\n SELECT n.num\n , ROW_NUMBER() OVER(PARTITION BY n.num ORDER BY n.num ASC) as row_num\n FROM Numbers as n\n)\nSELECT\n p.num\n , p.row_num\nFROM prelim as p\nORDER BY p.row_num, p.num\n | num | row_num |\n|-----|---------|\n| 1 | 1 |\n| 2 | 1 |\n| 3 | 1 |\n| 4 | 1 |\n| 5 | 1 |\n| 1 | 2 |\n| 2 | 2 |\n| 3 | 2 |\n| 4 | 2 |\n| 5 | 2 |\n CREATE TABLE attributes (\n ID int not null\n , RefCol int not null\n , Metric nvarchar(50) not null\n , SetID int null\n);\n\nINSERT INTO attributes (ID, RefCol, Metric) \nVALUES \n (1,1,'02/02/2022')\n ,(1,2,'Adam')\n ,(1,3,'Japan')\n ,(1,4,'1')\n ,(1,1,'03/02/2022')\n ,(1,2,'Smith')\n ,(1,3,'England')\n ,(1,4,'0')\n;\n\nDECLARE @setID int = 0;\n\nWHILE (EXISTS (SELECT ID FROM attributes WHERE SetID is NULL))\nBEGIN\n UPDATE TOP (4) attributes\n SET SetID = @setID\n FROM attributes\n WHERE SetID IS NULL\n ;\n\n SET @setID = @setID + 1;\nEND\n\nSELECT * FROM attributes;\n\nSELECT DISTINCT \n a.SetID\n , a.ID\n , aTime.Metric as [time]\n , aName.Metric as [name]\n , aLoc.Metric as [location]\n , aAvail.Metric as [Available]\nFROM attributes as a\n LEFT OUTER JOIN attributes as aTime\n ON aTime.SetID = a.SetID\n AND aTime.RefCol = 1\n LEFT OUTER JOIN attributes as aName\n ON aName.SetID = a.SetID\n AND aName.RefCol = 2\n LEFT OUTER JOIN attributes as aLoc\n ON aLoc.SetID = a.SetID\n AND aLoc.RefCol = 3\n LEFT OUTER JOIN attributes as aAvail\n ON aAvail.SetID = a.SetID\n AND aAvail.RefCol = 4\n;\n\n\n\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12453461/" ]
74,631,808
<p>When opening my webpage none of the Ajax content loads until one of the links is clicked then displaying the content connected to that link.</p> <p>This is where the content is loaded into the main webpage at ext-content:</p> <pre class="lang-html prettyprint-override"><code>&lt;main&gt; &lt;article class=&quot;ext-content&quot;&gt; &lt;/article&gt; &lt;/main&gt; </code></pre> <p>This is the javascript which loads the content when one of the links is clicked:</p> <pre class="lang-js prettyprint-override"><code>$('section li').click(function() { $.ajax({ type: 'GET', url: 'includes/ext-content/'+$(this).data('content')+'.html', dataType: 'html', success: function(response) { $('.ext-content').html(response); } }); }); </code></pre> <p>These are the links which then load the content into ext-content when clicked:</p> <pre class="lang-html prettyprint-override"><code>&lt;section id=&quot;section-links&quot;&gt; &lt;p&gt;Kies een van de onderstaande opties:&lt;/p&gt; &lt;ul id=&quot;componenten-links&quot;&gt; &lt;li data-content=&quot;cpu-shop&quot;&gt;CPU's&lt;/li&gt; &lt;li data-content=&quot;moederbord-shop&quot;&gt;Moederborden&lt;/li&gt; &lt;li data-content=&quot;geheugen-shop&quot;&gt;Geheugen&lt;/a&gt;&lt;/li&gt; &lt;li data-content=&quot;hardschijf-shop&quot;&gt;Harde schijven&lt;/a&gt;&lt;/li&gt; &lt;li data-content=&quot;grafischekaart-shop&quot;&gt;Grafische kaarten&lt;/a&gt;&lt;/li&gt; &lt;li data-content=&quot;voeding-shop&quot;&gt;Voedingen&lt;/a&gt;&lt;/li&gt; &lt;li data-content=&quot;behuizing-shop&quot;&gt;Behuizingen&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/section&gt; </code></pre> <p>The code below will automatically load a specific webpage when the page loads, but this only works if I manually type in the webpage.html. Is there a way to make this code below work where it automatically takes one of the links listed above instead of me having to type in a specific webpage.html? Otherwise I would need a different script for each webpage.</p> <pre class="lang-js prettyprint-override"><code> $('section li').ready(function() { $.ajax({ type: 'GET', url: 'includes/ext-content/cpu-shop.html', dataType: 'html', success: function(response) { $('.ext-content2').html(response); } }); }); </code></pre> <p>Thanks for the help</p>
[ { "answer_id": 74631847, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "$('section li').load(function() {\n $.ajax({\n type: 'GET',\n url: 'includes/ext-content/cpu-shop.html',\n dataType: 'html',\n success: function(response) {\n $('.ext-content2').html(response);\n }\n });\n });\n" }, { "answer_id": 74631875, "author": "Kaushik Makwana", "author_id": 5729416, "author_profile": "https://Stackoverflow.com/users/5729416", "pm_score": 0, "selected": false, "text": "document.ready $( document ).ready(function() {\n$.ajax({\n type: 'GET',\n url: 'includes/ext-content/cpu-shop.html',\n dataType: 'html',\n success: function(response) {\n $('.ext-content2').html(response);\n }\n });\n});\n" }, { "answer_id": 74631883, "author": "Twisty", "author_id": 463319, "author_profile": "https://Stackoverflow.com/users/463319", "pm_score": 2, "selected": true, "text": "$(function(){\n $('.ext-content').load('includes/ext-content/' + $('section li').eq(0).data('content') + '.html');\n \n $('section li').click(function() {\n $('.ext-content').load('includes/ext-content/' + $(this).data('content') + '.html');\n });\n});\n .load() .html() .load() LI data" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20637346/" ]
74,631,829
<p>I have two tables. Need to list the Name field randomly in the User col in tbl 2 using Big query SQL. Can someone help me please?</p> <p>Table 1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Id</th> <th style="text-align: left;">Name</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1</td> <td style="text-align: left;">Tom</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: left;">Jack</td> </tr> <tr> <td style="text-align: left;">3</td> <td style="text-align: left;">Harry</td> </tr> </tbody> </table> </div> <p>Table 2</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Month</th> <th style="text-align: left;">Year</th> <th style="text-align: left;">User</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Jan</td> <td style="text-align: left;">2023</td> <td style="text-align: left;"></td> </tr> <tr> <td style="text-align: left;">Feb</td> <td style="text-align: left;">2023</td> <td style="text-align: left;"></td> </tr> <tr> <td style="text-align: left;">Mar</td> <td style="text-align: left;">2023</td> <td style="text-align: left;"></td> </tr> <tr> <td style="text-align: left;">Apr</td> <td style="text-align: left;">2023</td> <td style="text-align: left;"></td> </tr> <tr> <td style="text-align: left;">May</td> <td style="text-align: left;">2033</td> <td style="text-align: left;"></td> </tr> </tbody> </table> </div>
[ { "answer_id": 74631847, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "$('section li').load(function() {\n $.ajax({\n type: 'GET',\n url: 'includes/ext-content/cpu-shop.html',\n dataType: 'html',\n success: function(response) {\n $('.ext-content2').html(response);\n }\n });\n });\n" }, { "answer_id": 74631875, "author": "Kaushik Makwana", "author_id": 5729416, "author_profile": "https://Stackoverflow.com/users/5729416", "pm_score": 0, "selected": false, "text": "document.ready $( document ).ready(function() {\n$.ajax({\n type: 'GET',\n url: 'includes/ext-content/cpu-shop.html',\n dataType: 'html',\n success: function(response) {\n $('.ext-content2').html(response);\n }\n });\n});\n" }, { "answer_id": 74631883, "author": "Twisty", "author_id": 463319, "author_profile": "https://Stackoverflow.com/users/463319", "pm_score": 2, "selected": true, "text": "$(function(){\n $('.ext-content').load('includes/ext-content/' + $('section li').eq(0).data('content') + '.html');\n \n $('section li').click(function() {\n $('.ext-content').load('includes/ext-content/' + $(this).data('content') + '.html');\n });\n});\n .load() .html() .load() LI data" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3634428/" ]
74,631,839
<p>At the end of the day, in my Google Sheet I'm trying to filter a large data set by multiple criteria and sum a certain column. I have a mostly working formula but I'm running into a problem.</p> <p>Here is an example that works:</p> <pre><code>=sum(INDEX(FILTER('Invoice Data'!H3:P, 'Invoice Data'!N3:N&gt;=DATE(2022,1,1), ('Invoice Data'!H3:H=&quot;Arc&quot;)+('Invoice Data'!H3:H=&quot;Technical Products&quot;) ),0,9)) </code></pre> <p>The ()+() in the second criteria works well as an OR condition. However, I want that criteria to be dynamic based on other information. So I've created the following formula that generates a text string as follows:</p> <pre><code>=&quot;('Invoice Data'!H3:H=&quot;&amp;CHAR(34)&amp;join(CHAR(34)&amp;&quot;)+('Invoice Data'!H3:H=&quot;&amp;CHAR(34),FILTER('Dropdown Menus'!D2:D34, A2='Dropdown Menus'!C2:C34))&amp;CHAR(34)&amp;&quot;)&quot; </code></pre> <p>This successfully generates the text &quot;('Invoice Data'!H3:H=&quot;Arc&quot;)+('Invoice Data'!H3:H=&quot;Technical Products&quot;)&quot;.</p> <p>The problem is, when I put it into the original formula, it doesn't work.</p> <pre><code>=sum(INDEX(FILTER('Invoice Data'!H3:P, 'Invoice Data'!N3:N&gt;=DATE(2022,1,1), TO_TEXT(&quot;('Invoice Data'!H3:H=&quot;&amp;CHAR(34)&amp;join(CHAR(34)&amp;&quot;)+('Invoice Data'!H3:H=&quot;&amp;CHAR(34),FILTER('Dropdown Menus'!D2:D34, A2='Dropdown Menus'!C2:C34))&amp;CHAR(34)&amp;&quot;)&quot;) ),0,9)) </code></pre> <p>I get the following error:</p> <blockquote> <p>FILTER has mismatched range sizes. Expected row count: 27436. column count: 1. Actual row count: 1, column count: 1.</p> </blockquote> <p>Any thoughts on what might be happening? I try to use &quot;Indirect()&quot; to have it be a cell reference, but that didn't work either.</p>
[ { "answer_id": 74631847, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "$('section li').load(function() {\n $.ajax({\n type: 'GET',\n url: 'includes/ext-content/cpu-shop.html',\n dataType: 'html',\n success: function(response) {\n $('.ext-content2').html(response);\n }\n });\n });\n" }, { "answer_id": 74631875, "author": "Kaushik Makwana", "author_id": 5729416, "author_profile": "https://Stackoverflow.com/users/5729416", "pm_score": 0, "selected": false, "text": "document.ready $( document ).ready(function() {\n$.ajax({\n type: 'GET',\n url: 'includes/ext-content/cpu-shop.html',\n dataType: 'html',\n success: function(response) {\n $('.ext-content2').html(response);\n }\n });\n});\n" }, { "answer_id": 74631883, "author": "Twisty", "author_id": 463319, "author_profile": "https://Stackoverflow.com/users/463319", "pm_score": 2, "selected": true, "text": "$(function(){\n $('.ext-content').load('includes/ext-content/' + $('section li').eq(0).data('content') + '.html');\n \n $('section li').click(function() {\n $('.ext-content').load('includes/ext-content/' + $(this).data('content') + '.html');\n });\n});\n .load() .html() .load() LI data" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647871/" ]