qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,642,254
<p>I am trying to achieve a certain effect with a navbar. The challenges I am facing are as below:</p> <ul> <li>The navigation should appear only when the user scrolls to a certain component on the website and it should work the other way around when scrolling up</li> <li>There should be a progress bar in the navigation on the scroll</li> <li>I could only find how to make that starting from the top of the website but not starting from a certain point on the website</li> </ul> <p>I don't need the code, just an idea of how to approach this. Maybe there are some good libraries that could help.</p> <p>Thanks!</p>
[ { "answer_id": 74642460, "author": "Jason Liam", "author_id": 12002570, "author_profile": "https://Stackoverflow.com/users/12002570", "pm_score": 2, "selected": false, "text": "C<incomplete> constexpr inline C<incomplete> constexpr inline" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14979135/" ]
74,642,259
<p>I have a list of dictionaries</p> <pre><code>[{'elementid': 'BsWfsElement.1.1', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86400', 'lat': '32.05570', 'paramname': 'multiplicity', 'paramvalue': '4'}, {'elementid': 'BsWfsElement.1.2', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86400', 'lat': '32.05570', 'paramname': 'peak_current', 'paramvalue': '-11'}, {'elementid': 'BsWfsElement.1.3', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86400', 'lat': '32.05570', 'paramname': 'cloud_indicator', 'paramvalue': '0'}, {'elementid': 'BsWfsElement.1.4', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86400', 'lat': '32.05570', 'paramname': 'ellipse_major', 'paramvalue': '5.8'}, {'elementid': 'BsWfsElement.2.1', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86350', 'lat': '32.02770', 'paramname': 'multiplicity', 'paramvalue': '0'}, {'elementid': 'BsWfsElement.2.2', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86350', 'lat': '32.02770', 'paramname': 'peak_current', 'paramvalue': '-16'}, {'elementid': 'BsWfsElement.2.3', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86350', 'lat': '32.02770', 'paramname': 'cloud_indicator', 'paramvalue': '0'}, {'elementid': 'BsWfsElement.2.4', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86350', 'lat': '32.02770', 'paramname': 'ellipse_major', 'paramvalue': '1.6'}, {'elementid': 'BsWfsElement.3.1', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86730', 'lat': '32.07100', 'paramname': 'multiplicity', 'paramvalue': '0'}, {'elementid': 'BsWfsElement.3.2', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86730', 'lat': '32.07100', 'paramname': 'peak_current', 'paramvalue': '-35'}, {'elementid': 'BsWfsElement.3.3', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86730', 'lat': '32.07100', 'paramname': 'cloud_indicator', 'paramvalue': '0'}, {'elementid': 'BsWfsElement.3.4' </code></pre> <p>which I want to group by the id subsection in the key <code>elementid</code>, in a way that appends the <code>paramname</code> and <code>paramvalue</code> values from dictionaries that have the <code>.2</code>, <code>.3</code> and <code>.4</code> to the &quot;first&quot; dictionary that has the <code>.1</code> ending, since every other item in the <code>.2</code>, <code>.3</code> and <code>.4</code> dictionaries are duplicates. When this would be done, I'd remove the <code>elementid</code> item and combine the <code>paramname</code> and <code>paramvalue</code> items.</p> <p>So an example of my desired output in the end would then be</p> <pre><code>[{'obstime': '2022-07-11T20:00:05', 'lon': '59.86400', 'lat': '32.05570', 'multiplicity': '4', 'peak_current': '-11', 'cloud_indicator': '0', 'ellipse_major': '58'} ... ] </code></pre> <p>My code that creates the list of dictionaries from an XML file</p> <pre><code>from urllib.request import urlopen import xml.etree.ElementTree as ET from xml.etree.ElementTree import fromstring, ElementTree from itertools import groupby from operator import itemgetter file = urlopen('https://opendata.fmi.fi/wfs?service=WFS&amp;version=2.0.0&amp;request=getFeature&amp;storedquery_id=fmi::observations::lightning::simple&amp;timestep=1&amp;starttime=2022-07-11T20:00:00Z&amp;endtime=2022-07-11T20:05:00Z') data = file.read() tree = ElementTree(fromstring(data)) root = tree.getroot() paramnames = [] paramvalues = [] lon = [] lat = [] obstime = [] ids = [] ET.register_namespace('wfs', &quot;http://www.opengis.net/wfs/2.0&quot;) ET.register_namespace('gml', &quot;http://www.opengis.net/gml/3.2&quot;) ET.register_namespace('BsWfs', &quot;http://xml.fmi.fi/schema/wfs/2.0&quot;) ET.register_namespace('xsi', &quot;http://www.w3.org/2001/XMLSchema-instance&quot;) for pn in root.findall('.//{http://xml.fmi.fi/schema/wfs/2.0}ParameterName'): pnstr = (pn.text.replace('', '')) paramnames.append(pnstr) for pv in root.findall('.//{http://xml.fmi.fi/schema/wfs/2.0}ParameterValue'): pvstr = (pv.text.replace('', '')) paramvalues.append(pvstr) for ps in root.findall('.//{http://www.opengis.net/gml/3.2}pos'): psstr = (ps.text.replace('', '')) lons = psstr.split(None, 1) del lons[-1] lats = psstr.split(None, 2) del lats [-0] lon.append(lons[0]) lat.append(lats[0]) for tm in root.findall('.//{http://xml.fmi.fi/schema/wfs/2.0}Time'): tmstr = (tm.text.replace('Z', '')) obstime.append(tmstr) for i in root.findall('.//{http://xml.fmi.fi/schema/wfs/2.0}BsWfsElement'): idstr = i.get(&quot;{http://www.opengis.net/gml/3.2}id&quot;) ids.append(idstr) zippedlist = list(zip(ids, obstime, lon, lat, paramnames, paramvalues))) dictnames = ('elementid', 'obstime', 'lon', 'lat', 'paramname', 'paramvalue') list_of_dicts = [dict(zip(dictnames,l)) for l in zippedlist] print(list_of_dicts) </code></pre> <p>I tried sorting them by the <code>lon</code> item, but found out that it actually doesn't produce the result I wanted</p> <pre><code>list_of_dicts = sorted(list_of_dicts, key = itemgetter('lon')) for key, value in groupby(list_of_dicts, key = itemgetter('lon')): for k in value: print(k) print(list_of_dicts) </code></pre> <p>Output:</p> <pre><code>{'elementid': 'BsWfsElement.250.1', 'obstime': '2022-07-11T20:02:42', 'lon': '55.16820', 'lat': '30.88440', 'paramname': 'multiplicity', 'paramvalue': '1'} {'elementid': 'BsWfsElement.250.2', 'obstime': '2022-07-11T20:02:42', 'lon': '55.16820', 'lat': '30.88440', 'paramname': 'peak_current', 'paramvalue': '21'} {'elementid': 'BsWfsElement.250.3', 'obstime': '2022-07-11T20:02:42', 'lon': '55.16820', 'lat': '30.88440', 'paramname': 'cloud_indicator', 'paramvalue': '0'} {'elementid': 'BsWfsElement.250.4', 'obstime': '2022-07-11T20:02:42', 'lon': '55.16820', 'lat': '30.88440', 'paramname': 'ellipse_major', 'paramvalue': '2.8'} {'elementid': 'BsWfsElement.240.1', 'obstime': '2022-07-11T20:02:40', 'lon': '55.67710', 'lat': '31.12120', 'paramname': 'multiplicity', 'paramvalue': '1'} {'elementid': 'BsWfsElement.240.2', 'obstime': '2022-07-11T20:02:40', 'lon': '55.67710', 'lat': '31.12120', 'paramname': 'peak_current', 'paramvalue': '109'} {'elementid': 'BsWfsElement.240.3', 'obstime': '2022-07-11T20:02:40', 'lon': '55.67710', 'lat': '31.12120', 'paramname': 'cloud_indicator', 'paramvalue': '0'} {'elementid': 'BsWfsElement.240.4', 'obstime': '2022-07-11T20:02:40', 'lon': '55.67710', 'lat': '31.12120', 'paramname': 'ellipse_major', 'paramvalue': '1.6'} ... </code></pre>
[ { "answer_id": 74642460, "author": "Jason Liam", "author_id": 12002570, "author_profile": "https://Stackoverflow.com/users/12002570", "pm_score": 2, "selected": false, "text": "C<incomplete> constexpr inline C<incomplete> constexpr inline" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19624810/" ]
74,642,283
<p>I have GitHub Runner and docker registry on my server and I'm trying to set up ci/cd for some applications.</p> <p>Directly pushing to the container name with port works smoothly</p> <pre><code>docker pull alpine docker tag alpine:latest docker-registry:5000/alpine:latest docker login docker-registry:5000 Login Succeeded docker push docker-registry:5000/alpine:latest The push refers to repository [docker-registry:5000/alpine] ded7a220bb05: Pushed </code></pre> <p>But I get an problem when I use the domain</p> <pre><code>docker pull alpine docker tag alpine:latest registry.mydomain.com/alpine:latest docker login registry.mydomain.com Login Succeeded docker push registry.mydomain.com/alpine:latest The push refers to repository [registry.mydomain.com/alpine] ded7a220bb05: Retrying in 1 second received unexpected HTTP status: 200 OK </code></pre> <p>My docker containers</p> <pre><code>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES eab92ef5610b registry:2 &quot;/entrypoint.sh /etc…&quot; 22 seconds ago Up 21 seconds 5000/tcp docker-registry bdd4f0886c19 nginx:1.20.2 &quot;/docker-entrypoint.…&quot; 3 months ago Up About an hour 0.0.0.0:80-&gt;80/tcp, :::80-&gt;80/tcp nginx-ingress 5e7e8e1b591e myoung34/github-runner:2.299.1-ubuntu-jammy &quot;/entrypoint.sh ./bi…&quot; 37 hours ago Up 27 minutes github-runner </code></pre> <p>My Nginx config</p> <pre><code>upstream registry { server docker-registry:5000; } map $upstream_http_docker_distribution_api_version $docker_distribution_api_version { '' 'registry/2.0'; } server { listen 443; server_name registry.mydomain.com; client_max_body_size 0; chunked_transfer_encoding on; location /v2/ { if ($http_user_agent ~ &quot;^(docker\/1\.(3|4|5(?!\.[0-9]-dev))|Go ).*$&quot; ) { return 404; } auth_basic &quot;Registry Realm&quot;; auth_basic_user_file /etc/nginx/conf.d/nginx.htpasswd; add_header 'Docker-Distribution-Api-Version' $docker_distribution_api_version always; proxy_pass http://registry; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # default =&gt; $scheme | cloudflare =&gt; https proxy_read_timeout 900; } } </code></pre> <p>Docker registry logs</p> <pre><code>time=&quot;2022-12-01T13:05:21.576274727Z&quot; level=warning msg=&quot;No HTTP secret provided - generated random secret. This may cause problems with uploads if multiple registries are behind a load-balancer. To provide a shared secret, fill in http.secret in the configuration file or set the REGISTRY_HTTP_SECRET environment variable.&quot; go.version=go1.16.15 instance.id=9fae9ec3-fe4f-443e-b6b3-d472db92412a service=registry version=&quot;v2.8.1+unknown&quot; time=&quot;2022-12-01T13:05:21.576362865Z&quot; level=info msg=&quot;redis not configured&quot; go.version=go1.16.15 instance.id=9fae9ec3-fe4f-443e-b6b3-d472db92412a service=registry version=&quot;v2.8.1+unknown&quot; time=&quot;2022-12-01T13:05:21.576419048Z&quot; level=info msg=&quot;Starting upload purge in 9m0s&quot; go.version=go1.16.15 instance.id=9fae9ec3-fe4f-443e-b6b3-d472db92412a service=registry version=&quot;v2.8.1+unknown&quot; time=&quot;2022-12-01T13:05:21.588466586Z&quot; level=info msg=&quot;using inmemory blob descriptor cache&quot; go.version=go1.16.15 instance.id=9fae9ec3-fe4f-443e-b6b3-d472db92412a service=registry version=&quot;v2.8.1+unknown&quot; time=&quot;2022-12-01T13:05:21.588770043Z&quot; level=info msg=&quot;listening on [::]:5000&quot; go.version=go1.16.15 instance.id=9fae9ec3-fe4f-443e-b6b3-d472db92412a service=registry version=&quot;v2.8.1+unknown&quot; 172.18.0.1 - - [01/Dec/2022:13:05:28 +0000] &quot;GET /v2/ HTTP/1.1&quot; 401 87 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; time=&quot;2022-12-01T13:05:28.906573279Z&quot; level=warning msg=&quot;error authorizing context: basic authentication challenge for realm &quot;Registry Realm&quot;: invalid authorization credential&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=4d19514d-336c-4c1c-ad8a-91a8a4be1e0c http.request.method=GET http.request.remoteaddr=&quot;172.18.0.1:42346&quot; http.request.uri=&quot;/v2/&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; 172.18.0.1 - - [01/Dec/2022:13:05:28 +0000] &quot;GET /v2/ HTTP/1.1&quot; 200 2 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; time=&quot;2022-12-01T13:05:28.91635475Z&quot; level=info msg=&quot;authorized request&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=6f0cd72e-52dd-4408-812c-c770c1daeb4c http.request.method=GET http.request.remoteaddr=&quot;172.18.0.1:42348&quot; http.request.uri=&quot;/v2/&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; time=&quot;2022-12-01T13:05:28.916428075Z&quot; level=info msg=&quot;response completed&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=6f0cd72e-52dd-4408-812c-c770c1daeb4c http.request.method=GET http.request.remoteaddr=&quot;172.18.0.1:42348&quot; http.request.uri=&quot;/v2/&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; http.response.contenttype=&quot;application/json; charset=utf-8&quot; http.response.duration=8.872969ms http.response.status=200 http.response.written=2 172.18.0.1 - - [01/Dec/2022:13:05:47 +0000] &quot;GET /v2/ HTTP/1.1&quot; 401 87 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; time=&quot;2022-12-01T13:05:47.955166053Z&quot; level=warning msg=&quot;error authorizing context: basic authentication challenge for realm &quot;Registry Realm&quot;: invalid authorization credential&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=060b8ad8-027d-4e1f-aae8-853e694aa071 http.request.method=GET http.request.remoteaddr=&quot;172.18.0.1:42352&quot; http.request.uri=&quot;/v2/&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; time=&quot;2022-12-01T13:05:47.961400261Z&quot; level=info msg=&quot;authorized request&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=23ab1f44-c687-41a4-854c-88d5223f3c19 http.request.method=HEAD http.request.remoteaddr=&quot;172.18.0.1:42354&quot; http.request.uri=&quot;/v2/alpine/blobs/sha256:c158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; vars.digest=&quot;sha256:c158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715&quot; vars.name=alpine time=&quot;2022-12-01T13:05:47.961616963Z&quot; level=error msg=&quot;response completed with error&quot; auth.user.name=&quot;docker_user&quot; err.code=&quot;blob unknown&quot; err.detail=sha256:c158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715 err.message=&quot;blob unknown to registry&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=23ab1f44-c687-41a4-854c-88d5223f3c19 http.request.method=HEAD http.request.remoteaddr=&quot;172.18.0.1:42354&quot; http.request.uri=&quot;/v2/alpine/blobs/sha256:c158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; http.response.contenttype=&quot;application/json; charset=utf-8&quot; http.response.duration=3.888659ms http.response.status=404 http.response.written=157 vars.digest=&quot;sha256:c158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715&quot; vars.name=alpine 172.18.0.1 - - [01/Dec/2022:13:05:47 +0000] &quot;HEAD /v2/alpine/blobs/sha256:c158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715 HTTP/1.1&quot; 404 157 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; time=&quot;2022-12-01T13:05:48.013676521Z&quot; level=info msg=&quot;authorized request&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=76e692cf-3fec-4739-ac68-dd7e785bc3c0 http.request.method=POST http.request.remoteaddr=&quot;172.18.0.1:42356&quot; http.request.uri=&quot;/v2/alpine/blobs/uploads/&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; vars.name=alpine time=&quot;2022-12-01T13:05:48.026046059Z&quot; level=info msg=&quot;response completed&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=76e692cf-3fec-4739-ac68-dd7e785bc3c0 http.request.method=POST http.request.remoteaddr=&quot;172.18.0.1:42356&quot; http.request.uri=&quot;/v2/alpine/blobs/uploads/&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; http.response.duration=16.091457ms http.response.status=202 http.response.written=0 172.18.0.1 - - [01/Dec/2022:13:05:48 +0000] &quot;POST /v2/alpine/blobs/uploads/ HTTP/1.1&quot; 202 0 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; time=&quot;2022-12-01T13:05:48.037049651Z&quot; level=info msg=&quot;authorized request&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=9d35eb65-a80e-43c7-bcad-42bcd0723ad1 http.request.method=PATCH http.request.remoteaddr=&quot;172.18.0.1:42358&quot; http.request.uri=&quot;/v2/alpine/blobs/uploads/cb21fc83-6e19-4c78-b5c0-badb0ff8fe04?_state=TRS7R1oNENXqtiEnnSLbJD3l9O9Pq9tEtZudktNkQQF7Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiY2IyMWZjODMtNmUxOS00Yzc4LWI1YzAtYmFkYjBmZjhmZTA0IiwiT2Zmc2V0IjowLCJTdGFydGVkQXQiOiIyMDIyLTEyLTAxVDEzOjA1OjQ4LjAxMzc0MDcxN1oifQ%3D%3D&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; vars.name=alpine vars.uuid=cb21fc83-6e19-4c78-b5c0-badb0ff8fe04 time=&quot;2022-12-01T13:05:48.956206497Z&quot; level=info msg=&quot;response completed&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=9d35eb65-a80e-43c7-bcad-42bcd0723ad1 http.request.method=PATCH http.request.remoteaddr=&quot;172.18.0.1:42358&quot; http.request.uri=&quot;/v2/alpine/blobs/uploads/cb21fc83-6e19-4c78-b5c0-badb0ff8fe04?_state=TRS7R1oNENXqtiEnnSLbJD3l9O9Pq9tEtZudktNkQQF7Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiY2IyMWZjODMtNmUxOS00Yzc4LWI1YzAtYmFkYjBmZjhmZTA0IiwiT2Zmc2V0IjowLCJTdGFydGVkQXQiOiIyMDIyLTEyLTAxVDEzOjA1OjQ4LjAxMzc0MDcxN1oifQ%3D%3D&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; http.response.duration=929.13763ms http.response.status=202 http.response.written=0 172.18.0.1 - - [01/Dec/2022:13:05:48 +0000] &quot;PATCH /v2/alpine/blobs/uploads/cb21fc83-6e19-4c78-b5c0-badb0ff8fe04?_state=TRS7R1oNENXqtiEnnSLbJD3l9O9Pq9tEtZudktNkQQF7Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiY2IyMWZjODMtNmUxOS00Yzc4LWI1YzAtYmFkYjBmZjhmZTA0IiwiT2Zmc2V0IjowLCJTdGFydGVkQXQiOiIyMDIyLTEyLTAxVDEzOjA1OjQ4LjAxMzc0MDcxN1oifQ%3D%3D HTTP/1.1&quot; 202 0 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; time=&quot;2022-12-01T13:05:48.960962747Z&quot; level=info msg=&quot;authorized request&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=b4955223-ae69-4d0f-8643-b70148b764fd http.request.method=PUT http.request.remoteaddr=&quot;172.18.0.1:42360&quot; http.request.uri=&quot;/v2/alpine/blobs/uploads/cb21fc83-6e19-4c78-b5c0-badb0ff8fe04?_state=NVqJ2JVvha-PdWnWeVonnGI1qxrWbyJiE3ECtgBK_v17Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiY2IyMWZjODMtNmUxOS00Yzc4LWI1YzAtYmFkYjBmZjhmZTA0IiwiT2Zmc2V0IjozMzcwNzA2LCJTdGFydGVkQXQiOiIyMDIyLTEyLTAxVDEzOjA1OjQ4WiJ9&amp;digest=sha256%3Ac158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; vars.name=alpine vars.uuid=cb21fc83-6e19-4c78-b5c0-badb0ff8fe04 time=&quot;2022-12-01T13:05:48.975845667Z&quot; level=info msg=&quot;response completed&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=b4955223-ae69-4d0f-8643-b70148b764fd http.request.method=PUT http.request.remoteaddr=&quot;172.18.0.1:42360&quot; http.request.uri=&quot;/v2/alpine/blobs/uploads/cb21fc83-6e19-4c78-b5c0-badb0ff8fe04?_state=NVqJ2JVvha-PdWnWeVonnGI1qxrWbyJiE3ECtgBK_v17Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiY2IyMWZjODMtNmUxOS00Yzc4LWI1YzAtYmFkYjBmZjhmZTA0IiwiT2Zmc2V0IjozMzcwNzA2LCJTdGFydGVkQXQiOiIyMDIyLTEyLTAxVDEzOjA1OjQ4WiJ9&amp;digest=sha256%3Ac158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; http.response.duration=18.779158ms http.response.status=201 http.response.written=0 172.18.0.1 - - [01/Dec/2022:13:05:48 +0000] &quot;PUT /v2/alpine/blobs/uploads/cb21fc83-6e19-4c78-b5c0-badb0ff8fe04?_state=NVqJ2JVvha-PdWnWeVonnGI1qxrWbyJiE3ECtgBK_v17Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiY2IyMWZjODMtNmUxOS00Yzc4LWI1YzAtYmFkYjBmZjhmZTA0IiwiT2Zmc2V0IjozMzcwNzA2LCJTdGFydGVkQXQiOiIyMDIyLTEyLTAxVDEzOjA1OjQ4WiJ9&amp;digest=sha256%3Ac158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715 HTTP/1.1&quot; 201 0 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; time=&quot;2022-12-01T13:05:48.987290535Z&quot; level=info msg=&quot;authorized request&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=53c874f2-6f55-4cde-b5ca-596dda13583a http.request.method=HEAD http.request.remoteaddr=&quot;172.18.0.1:42362&quot; http.request.uri=&quot;/v2/alpine/blobs/sha256:c158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; vars.digest=&quot;sha256:c158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715&quot; vars.name=alpine time=&quot;2022-12-01T13:05:48.987671994Z&quot; level=info msg=&quot;response completed&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=53c874f2-6f55-4cde-b5ca-596dda13583a http.request.method=HEAD http.request.remoteaddr=&quot;172.18.0.1:42362&quot; http.request.uri=&quot;/v2/alpine/blobs/sha256:c158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; http.response.contenttype=&quot;application/octet-stream&quot; http.response.duration=10.691772ms http.response.status=200 http.response.written=0 172.18.0.1 - - [01/Dec/2022:13:05:48 +0000] &quot;HEAD /v2/alpine/blobs/sha256:c158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715 HTTP/1.1&quot; 200 0 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; time=&quot;2022-12-01T13:05:48.99996587Z&quot; level=info msg=&quot;authorized request&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=867604cb-09cd-43f4-91b0-52ead32d664e http.request.method=HEAD http.request.remoteaddr=&quot;172.18.0.1:42364&quot; http.request.uri=&quot;/v2/alpine/blobs/sha256:49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; vars.digest=&quot;sha256:49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da&quot; vars.name=alpine time=&quot;2022-12-01T13:05:49.000171622Z&quot; level=error msg=&quot;response completed with error&quot; auth.user.name=&quot;docker_user&quot; err.code=&quot;blob unknown&quot; err.detail=sha256:49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da err.message=&quot;blob unknown to registry&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=867604cb-09cd-43f4-91b0-52ead32d664e http.request.method=HEAD http.request.remoteaddr=&quot;172.18.0.1:42364&quot; http.request.uri=&quot;/v2/alpine/blobs/sha256:49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; http.response.contenttype=&quot;application/json; charset=utf-8&quot; http.response.duration=4.875849ms http.response.status=404 http.response.written=157 vars.digest=&quot;sha256:49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da&quot; vars.name=alpine 172.18.0.1 - - [01/Dec/2022:13:05:48 +0000] &quot;HEAD /v2/alpine/blobs/sha256:49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da HTTP/1.1&quot; 404 157 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; time=&quot;2022-12-01T13:05:49.009848946Z&quot; level=info msg=&quot;authorized request&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=7e29e9ea-0864-44e2-bc75-732d246af8a9 http.request.method=POST http.request.remoteaddr=&quot;172.18.0.1:42366&quot; http.request.uri=&quot;/v2/alpine/blobs/uploads/&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; vars.name=alpine 172.18.0.1 - - [01/Dec/2022:13:05:49 +0000] &quot;POST /v2/alpine/blobs/uploads/ HTTP/1.1&quot; 202 0 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; time=&quot;2022-12-01T13:05:49.022631954Z&quot; level=info msg=&quot;response completed&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=7e29e9ea-0864-44e2-bc75-732d246af8a9 http.request.method=POST http.request.remoteaddr=&quot;172.18.0.1:42366&quot; http.request.uri=&quot;/v2/alpine/blobs/uploads/&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; http.response.duration=21.407075ms http.response.status=202 http.response.written=0 time=&quot;2022-12-01T13:05:49.032911791Z&quot; level=info msg=&quot;authorized request&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=abab2c41-40ee-4c76-8456-3b30b62061af http.request.method=PATCH http.request.remoteaddr=&quot;172.18.0.1:42370&quot; http.request.uri=&quot;/v2/alpine/blobs/uploads/32b60b00-82d6-4003-a470-7502f715be61?_state=E8EC15n0xy4YiaxJAynDeAl0SaoKMX0tvtbqakyT13R7Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiMzJiNjBiMDAtODJkNi00MDAzLWE0NzAtNzUwMmY3MTViZTYxIiwiT2Zmc2V0IjowLCJTdGFydGVkQXQiOiIyMDIyLTEyLTAxVDEzOjA1OjQ5LjAwOTk2MjU3WiJ9&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; vars.name=alpine vars.uuid=32b60b00-82d6-4003-a470-7502f715be61 172.18.0.1 - - [01/Dec/2022:13:05:49 +0000] &quot;PATCH /v2/alpine/blobs/uploads/32b60b00-82d6-4003-a470-7502f715be61?_state=E8EC15n0xy4YiaxJAynDeAl0SaoKMX0tvtbqakyT13R7Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiMzJiNjBiMDAtODJkNi00MDAzLWE0NzAtNzUwMmY3MTViZTYxIiwiT2Zmc2V0IjowLCJTdGFydGVkQXQiOiIyMDIyLTEyLTAxVDEzOjA1OjQ5LjAwOTk2MjU3WiJ9 HTTP/1.1&quot; 202 0 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; time=&quot;2022-12-01T13:05:49.046509563Z&quot; level=info msg=&quot;response completed&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=abab2c41-40ee-4c76-8456-3b30b62061af http.request.method=PATCH http.request.remoteaddr=&quot;172.18.0.1:42370&quot; http.request.uri=&quot;/v2/alpine/blobs/uploads/32b60b00-82d6-4003-a470-7502f715be61?_state=E8EC15n0xy4YiaxJAynDeAl0SaoKMX0tvtbqakyT13R7Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiMzJiNjBiMDAtODJkNi00MDAzLWE0NzAtNzUwMmY3MTViZTYxIiwiT2Zmc2V0IjowLCJTdGFydGVkQXQiOiIyMDIyLTEyLTAxVDEzOjA1OjQ5LjAwOTk2MjU3WiJ9&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; http.response.duration=22.857284ms http.response.status=202 http.response.written=0 time=&quot;2022-12-01T13:05:49.052387956Z&quot; level=info msg=&quot;authorized request&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=8d17d425-4b89-4597-9314-1f2c35e1afdb http.request.method=PUT http.request.remoteaddr=&quot;172.18.0.1:42372&quot; http.request.uri=&quot;/v2/alpine/blobs/uploads/32b60b00-82d6-4003-a470-7502f715be61?_state=uN8teJhzBMwlrLnstzPV492DSwZgwtADfHJWpqUsGpx7Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiMzJiNjBiMDAtODJkNi00MDAzLWE0NzAtNzUwMmY3MTViZTYxIiwiT2Zmc2V0IjoxNDcyLCJTdGFydGVkQXQiOiIyMDIyLTEyLTAxVDEzOjA1OjQ5WiJ9&amp;digest=sha256%3A49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; vars.name=alpine vars.uuid=32b60b00-82d6-4003-a470-7502f715be61 time=&quot;2022-12-01T13:05:49.067768248Z&quot; level=info msg=&quot;response completed&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=8d17d425-4b89-4597-9314-1f2c35e1afdb http.request.method=PUT http.request.remoteaddr=&quot;172.18.0.1:42372&quot; http.request.uri=&quot;/v2/alpine/blobs/uploads/32b60b00-82d6-4003-a470-7502f715be61?_state=uN8teJhzBMwlrLnstzPV492DSwZgwtADfHJWpqUsGpx7Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiMzJiNjBiMDAtODJkNi00MDAzLWE0NzAtNzUwMmY3MTViZTYxIiwiT2Zmc2V0IjoxNDcyLCJTdGFydGVkQXQiOiIyMDIyLTEyLTAxVDEzOjA1OjQ5WiJ9&amp;digest=sha256%3A49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; http.response.duration=20.176783ms http.response.status=201 http.response.written=0 172.18.0.1 - - [01/Dec/2022:13:05:49 +0000] &quot;PUT /v2/alpine/blobs/uploads/32b60b00-82d6-4003-a470-7502f715be61?_state=uN8teJhzBMwlrLnstzPV492DSwZgwtADfHJWpqUsGpx7Ik5hbWUiOiJhbHBpbmUiLCJVVUlEIjoiMzJiNjBiMDAtODJkNi00MDAzLWE0NzAtNzUwMmY3MTViZTYxIiwiT2Zmc2V0IjoxNDcyLCJTdGFydGVkQXQiOiIyMDIyLTEyLTAxVDEzOjA1OjQ5WiJ9&amp;digest=sha256%3A49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da HTTP/1.1&quot; 201 0 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; time=&quot;2022-12-01T13:05:49.073531198Z&quot; level=info msg=&quot;authorized request&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=d77e1f84-f55d-4917-bc8c-aceb4606c23e http.request.method=HEAD http.request.remoteaddr=&quot;172.18.0.1:42374&quot; http.request.uri=&quot;/v2/alpine/blobs/sha256:49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; vars.digest=&quot;sha256:49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da&quot; vars.name=alpine 172.18.0.1 - - [01/Dec/2022:13:05:49 +0000] &quot;HEAD /v2/alpine/blobs/sha256:49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da HTTP/1.1&quot; 200 0 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; time=&quot;2022-12-01T13:05:49.073748384Z&quot; level=info msg=&quot;response completed&quot; go.version=go1.16.15 http.request.host=&quot;docker-registry:5000&quot; http.request.id=d77e1f84-f55d-4917-bc8c-aceb4606c23e http.request.method=HEAD http.request.remoteaddr=&quot;172.18.0.1:42374&quot; http.request.uri=&quot;/v2/alpine/blobs/sha256:49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; http.response.contenttype=&quot;application/octet-stream&quot; http.response.duration=4.891873ms http.response.status=200 http.response.written=0 time=&quot;2022-12-01T13:05:49.081141753Z&quot; level=info msg=&quot;authorized request&quot; go.version=go1.16.15 http.request.contenttype=&quot;application/vnd.docker.distribution.manifest.v2+json&quot; http.request.host=&quot;docker-registry:5000&quot; http.request.id=b2329d48-38dd-471c-8691-6b08c1eb7ec5 http.request.method=PUT http.request.remoteaddr=&quot;172.18.0.1:42376&quot; http.request.uri=&quot;/v2/alpine/manifests/latest&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; vars.name=alpine vars.reference=latest time=&quot;2022-12-01T13:05:49.102368205Z&quot; level=info msg=&quot;response completed&quot; go.version=go1.16.15 http.request.contenttype=&quot;application/vnd.docker.distribution.manifest.v2+json&quot; http.request.host=&quot;docker-registry:5000&quot; http.request.id=b2329d48-38dd-471c-8691-6b08c1eb7ec5 http.request.method=PUT http.request.remoteaddr=&quot;172.18.0.1:42376&quot; http.request.uri=&quot;/v2/alpine/manifests/latest&quot; http.request.useragent=&quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \(linux\))&quot; http.response.duration=27.598063ms http.response.status=201 http.response.written=0 172.18.0.1 - - [01/Dec/2022:13:05:49 +0000] &quot;PUT /v2/alpine/manifests/latest HTTP/1.1&quot; 201 0 &quot;&quot; &quot;docker/20.10.17 go/go1.17.11 git-commit/a89b842 kernel/5.15.0-46-generic os/linux arch/amd64 UpstreamClient(Docker-Client/20.10.17 \\(linux\\))&quot; </code></pre> <p>Cloudflare is used for SSL. It automatically redirects to 443</p>
[ { "answer_id": 74642460, "author": "Jason Liam", "author_id": 12002570, "author_profile": "https://Stackoverflow.com/users/12002570", "pm_score": 2, "selected": false, "text": "C<incomplete> constexpr inline C<incomplete> constexpr inline" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20643143/" ]
74,642,293
<p>I want to make a system where a user will be able to draw a hexagonal grid. The regions and their coordinates will be stored in Database. We are thinking to implement H3 libary for this. How will be the library help is in making H3 hexagons all over the country?</p> <p>I have made a node project with h3-js library but can't figure how which function to actually render or draw hexagons over a projection/map.</p>
[ { "answer_id": 74646108, "author": "Pedro Marques", "author_id": 20658562, "author_profile": "https://Stackoverflow.com/users/20658562", "pm_score": -1, "selected": false, "text": "npm install h3-js\n\n// Import the H3 library\nimport {H3} from 'h3-js';\n\n// Define the center point of the grid\nconst lat = 37.7749;\nconst lng = -122.4194;\n\n// Define the radius of the grid in kilometers\nconst radius = 5;\n\n// Create a new H3 instance\nconst h3 = new H3();\n\n// Generate the hexagonal grid using the H3 instance\nconst hexagons = h3.hexagon(lat, lng, radius);\n\n// Loop through the hexagons and draw them on a map\nhexagons.forEach(hexagon => {\n // Draw the hexagon on a map\n});\n" }, { "answer_id": 74646888, "author": "nrabinowitz", "author_id": 380487, "author_profile": "https://Stackoverflow.com/users/380487", "pm_score": 0, "selected": false, "text": "h3.h3ToGeoBoundary(cell) h3.cellToBoundary(cell) [lat, lng] true [lng, lat] geojson2h3" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11466229/" ]
74,642,312
<p>Azure DevOps lets a reviewer tell the developer that they have completed their review with the &quot;waiting for the author&quot; flag on a PR review.</p> <p>But as the developer how can I tell the reviewer &quot;I have finished addressing comments?&quot; They may get a notification for every reply I make to a review comment but typically, we work that a reviewer won't re-review until I've finished addressing all their comments. I can send them a message but it seems like there should be a way to do it from the PR itself.</p>
[ { "answer_id": 74646108, "author": "Pedro Marques", "author_id": 20658562, "author_profile": "https://Stackoverflow.com/users/20658562", "pm_score": -1, "selected": false, "text": "npm install h3-js\n\n// Import the H3 library\nimport {H3} from 'h3-js';\n\n// Define the center point of the grid\nconst lat = 37.7749;\nconst lng = -122.4194;\n\n// Define the radius of the grid in kilometers\nconst radius = 5;\n\n// Create a new H3 instance\nconst h3 = new H3();\n\n// Generate the hexagonal grid using the H3 instance\nconst hexagons = h3.hexagon(lat, lng, radius);\n\n// Loop through the hexagons and draw them on a map\nhexagons.forEach(hexagon => {\n // Draw the hexagon on a map\n});\n" }, { "answer_id": 74646888, "author": "nrabinowitz", "author_id": 380487, "author_profile": "https://Stackoverflow.com/users/380487", "pm_score": 0, "selected": false, "text": "h3.h3ToGeoBoundary(cell) h3.cellToBoundary(cell) [lat, lng] true [lng, lat] geojson2h3" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197229/" ]
74,642,331
<p>How can I run the above code in the fastest way. What is the best practice?</p> <pre><code>public ActionResult ExampleAction() { // 200K items var results = dbContext.Results.ToList(); foreach (var result in results) { // 10 - 40 items result.Kazanim = JsonConvert.SerializeObject( dbContext.SubTables // 2,5M items .Where(x =&gt; x.FooId == result.FooId) .Select(select =&gt; new { BarId = select.BarId, State = select.State, }).ToList()); dbContext.Entry(result).State = EntityState.Modified; dbContext.SaveChanges(); } return Json(true, JsonRequestBehavior.AllowGet); } </code></pre> <p>This process takes an average of 500 ms as sync. I have about 2M records. The process is done 200K times.</p> <p>How should I code asynchronously?</p> <p>How can I do it faster and easier with an async method.</p>
[ { "answer_id": 74644463, "author": "ɐsɹǝʌ ǝɔıʌ", "author_id": 1548094, "author_profile": "https://Stackoverflow.com/users/1548094", "pm_score": 1, "selected": false, "text": "dbContext.SaveChanges() dbContext.SaveChanges() .SaveChanges()" }, { "answer_id": 74672693, "author": "José Ramírez", "author_id": 13886104, "author_profile": "https://Stackoverflow.com/users/13886104", "pm_score": 0, "selected": false, "text": "async .ToList() ToListAsync() CountAsync() AnyAsync() SaveChangesAsync() Task.Factory.StartNew() TaskCreationOptions.LongRunning" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13901563/" ]
74,642,337
<p>I am trying to get some code to execute at a certain time but I can't figure out what the problem is here. Please help?</p> <pre><code>import datetime dt=datetime set_time=dt.time(12,53) timenow=dt.datetime.now() time=False while not time: if timenow==set_time: print(&quot;yeeehaaa&quot;) time=True break else: print(&quot;naaaaa&quot;) </code></pre>
[ { "answer_id": 74642542, "author": "Indiano", "author_id": 13309379, "author_profile": "https://Stackoverflow.com/users/13309379", "pm_score": 3, "selected": true, "text": "timenow set_time import datetime\ndt=datetime\nset_time=str(dt.time(14,19))[0:5]\ntimenow=dt.datetime.now().time()\ntime=False\nwhile not time:\n timenow=str(dt.datetime.now().time())[0:5]\n# print(timenow)\n if timenow==set_time:\n print(\"yeeehaaa\")\n time=True\n break\nelse:\n print(\"naaaaa\")\n" }, { "answer_id": 74642576, "author": "Jib", "author_id": 20124358, "author_profile": "https://Stackoverflow.com/users/20124358", "pm_score": 0, "selected": false, "text": "import datetime.datetime as dt\nset_time=dt.time(12,53)\n\n# the loop waits for the time condition to be met.\n# we use the lower than condition in order not to miss the time\n# by a few fraction of second.\nwhile (dt.now() < set_time):\n time.sleep(0.1) # 100ms delay\n\n# reaching there implies the time condition is met!\nprint(\"it is time!\")\n time.sleep(time_delta_s)" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547761/" ]
74,642,405
<p>Let's assume I've the following C# class:</p> <pre><code>public class Test { public double X; public double Y; } </code></pre> <p>I want to use the above C# <code>Test</code> class from <a href="https://ironpython.net/" rel="nofollow noreferrer">IronPython</a> and as well from <a href="https://www.python.org/" rel="nofollow noreferrer">CPython</a> (using <a href="https://pypi.org/project/pythonnet/" rel="nofollow noreferrer">Pythonnet</a>).</p> <p>Using <a href="https://ironpython.net/" rel="nofollow noreferrer">IronPython 2.7</a> I was able to generate an object and initializes the fields using <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers" rel="nofollow noreferrer">object initialization</a>, see the following Python code:</p> <pre><code>obj = Test(X = 1.0, Y = 2.0) </code></pre> <p>See as well the following question <a href="https://stackoverflow.com/questions/42109930/object-initialization-in-ironpython">Object initialization in IronPython</a></p> <p>Using <a href="https://www.python.org/" rel="nofollow noreferrer">CPython 3.9.7</a> and <a href="https://pypi.org/project/pythonnet/" rel="nofollow noreferrer">Pythonnet 3.01</a> the above code returns the following error:</p> <pre><code>TypeError: No method matches given arguments for Test..ctor: () </code></pre> <p>As workaround I can use the following Python code:</p> <pre><code>obj = Test() obj.X = 1.0 obj.Y = 2.0 </code></pre> <p>But I would like to use <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers" rel="nofollow noreferrer">object initialization</a>.</p>
[ { "answer_id": 74642479, "author": "Siba Daki", "author_id": 10933030, "author_profile": "https://Stackoverflow.com/users/10933030", "pm_score": 1, "selected": false, "text": "Test test = New Test();\n/* or */ var test = New Test();\n/* then */ test.x = whatever;\n" }, { "answer_id": 74642685, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 0, "selected": false, "text": "var obj = new Test { X = 1.0, Y = 2.0 };\n public class Test\n{\n public double X;\n public double Y;\n\n public Text( double x, double y)\n {\n X = x;\n Y = y;\n }\n}\n var obj = new Test(1.0, 2.0);\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7556646/" ]
74,642,430
<p>My command</p> <pre><code>Windows 11 PowerShell. !pip install tensorflow-datasets pip install tensorflow-datasets # pip install tfds-nightly import tensorflow_datasets as tfds datasets = tfds.load(&quot;imdb_reviews&quot;) train_set = tfds.load(&quot;imdb_reviews&quot;) # 25.000 reviews. test_set = datasets[&quot;test&quot;] # 25.000 reviews. train_set, test_set = tfds.load(&quot;imdb_reviews&quot;, split=[&quot;train&quot;, &quot;test&quot;]) train_set, test_set = tfds.load(&quot;imdb_reviews:1.0.0&quot;, split=[&quot;train&quot;, &quot;test&quot;]) train_set, test_set = tfds.load(&quot;imdb_reviews:1.0.0&quot;, split=[&quot;train&quot;, &quot;test[:60%]&quot;]) train_set, test_set, valid_set = tfds.load(&quot;imdb_reviews:1.0.0&quot;, split=[&quot;train&quot;, &quot;test[:60%]&quot;, &quot;test[60%:]&quot;]) train_set, test_set, valid_set = tfds.load(&quot;imdb_reviews:1.0.0&quot;, split=[&quot;train&quot;, &quot;test[:60%]&quot;, &quot;test[60%:]&quot;], as_supervised = True) for review, label in train_set.take(2): print(review.numpy().decode(&quot;utf-8&quot;)) print(label.numpy()) </code></pre> <pre><code>Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows PS C:\Users\donhu&gt; pip install tensorflow-datasets Collecting tensorflow-datasets Downloading tensorflow_datasets-4.7.0-py3-none-any.whl (4.7 MB) |████████████████████████████████| 4.7 MB 2.2 MB/s Requirement already satisfied: protobuf&gt;=3.12.2 in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from tensorflow-datasets) (3.19.6) Collecting tensorflow-metadata Downloading tensorflow_metadata-1.11.0-py3-none-any.whl (52 kB) |████████████████████████████████| 52 kB ... Requirement already satisfied: numpy in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from tensorflow-datasets) (1.23.4) Requirement already satisfied: requests&gt;=2.19.0 in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from tensorflow-datasets) (2.28.1) Requirement already satisfied: six in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from tensorflow-datasets) (1.16.0) Requirement already satisfied: termcolor in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from tensorflow-datasets) (2.1.0) Collecting etils[epath] Downloading etils-0.9.0-py3-none-any.whl (140 kB) |████████████████████████████████| 140 kB ... Collecting promise Downloading promise-2.3.tar.gz (19 kB) Requirement already satisfied: tqdm in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from tensorflow-datasets) (4.64.1) Collecting toml Downloading toml-0.10.2-py2.py3-none-any.whl (16 kB) Collecting dill Downloading dill-0.3.6-py3-none-any.whl (110 kB) |████████████████████████████████| 110 kB 6.4 MB/s Requirement already satisfied: absl-py in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from tensorflow-datasets) (1.3.0) Collecting googleapis-common-protos&lt;2,&gt;=1.52.0 Downloading googleapis_common_protos-1.57.0-py2.py3-none-any.whl (217 kB) |████████████████████████████████| 217 kB 6.4 MB/s Requirement already satisfied: certifi&gt;=2017.4.17 in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from requests&gt;=2.19.0-&gt;tensorflow-datasets) (2022.9.24) Requirement already satisfied: charset-normalizer&lt;3,&gt;=2 in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from requests&gt;=2.19.0-&gt;tensorflow-datasets) (2.1.1) Requirement already satisfied: idna&lt;4,&gt;=2.5 in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from requests&gt;=2.19.0-&gt;tensorflow-datasets) (3.4) Requirement already satisfied: urllib3&lt;1.27,&gt;=1.21.1 in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from requests&gt;=2.19.0-&gt;tensorflow-datasets) (1.26.12)Requirement already satisfied: typing_extensions; extra == &quot;epath&quot; in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from etils[epath]-&gt;tensorflow-datasets) (4.4.0) Collecting importlib_resources; extra == &quot;epath&quot; Downloading importlib_resources-5.10.0-py3-none-any.whl (34 kB) Requirement already satisfied: zipp; extra == &quot;epath&quot; in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from etils[epath]-&gt;tensorflow-datasets) (3.10.0) Requirement already satisfied: colorama; platform_system == &quot;Windows&quot; in c:\users\donhu\appdata\local\programs\python\python39\lib\site-packages (from tqdm-&gt;tensorflow-datasets) (0.4.6) Building wheels for collected packages: promise Building wheel for promise (setup.py) ... done Created wheel for promise: filename=promise-2.3-py3-none-any.whl size=21554 sha256=8d6db1312d74403cffbe332a56a0caeb292ff65701f5c958a2c836715275b299 Stored in directory: c:\users\donhu\appdata\local\pip\cache\wheels\e1\e8\83\ddea66100678d139b14bc87692ece57c6a2a937956d2532608 Successfully built promise Installing collected packages: googleapis-common-protos, tensorflow-metadata, importlib-resources, etils, promise, toml, dill, tensorflow-datasets Successfully installed dill-0.3.6 etils-0.9.0 googleapis-common-protos-1.57.0 importlib-resources-5.10.0 promise-2.3 tensorflow-datasets-4.7.0 tensorflow-metadata-1.11.0 toml-0.10.2 WARNING: You are using pip version 20.2.3; however, version 22.3.1 is available. You should consider upgrading via the 'c:\users\donhu\appdata\local\programs\python\python39\python.exe -m pip install --upgrade pip' command. </code></pre> <pre><code>PS C:\Users\donhu&gt; python Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; import tensorflow_datasets as tfds &gt;&gt;&gt; datasets = tfds.load(&quot;imdb_reviews&quot;) Downloading and preparing dataset Unknown size (download: Unknown size, generated: Unknown size, total: Unknown size) to C:\Users\donhu\tensorflow_datasets\imdb_reviews\plain_text\1.0.0... Dl Completed...: 0%| | 0/1 [00:11&lt;?, ? url/s] Dl Size...: 26%|███████████████████████████▌ | 21/80 [00:11&lt;00:25, 2.27 MiB/s] Dl Completed...: 0%| | 0/1 [00:12&lt;?, ? url/s] Dl Size...: 28%|████████████████████████████▉ Dl Completed...: 0%| | 0/1 [00:12&lt;?, ? url/s] Dl Size...: 29%|██████████████████████████████▏ Dl Completed...: 0%| | 0/1 [00:13&lt;?, ? url/s] Dl Size...: 30%|███████████████████████████████▌ Dl Completed...: 0%| | 0/1 [00:13&lt;?, ? url/s] Dl Size...: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████| 80/80 [00:51&lt;00:00, 1.55 MiB/s] Dl Completed...: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:51&lt;00:00, 51.53s/ url] Generating splits...: 0%| | 0/3 [00:00&lt;?, ? splits/s] Generating train examples...: 7479 examples [00:02, 6153.86 examples/s] Dataset imdb_reviews downloaded and prepared to C:\Users\donhu\tensorflow_datasets\imdb_reviews\plain_text\1.0.0. Subsequent calls will reuse this data. 2022-12-01 19:48:16.580270: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2 To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. 2022-12-01 19:48:17.465275: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1616] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 3994 MB memory: -&gt; device: 0, name: NVIDIA GeForce GTX 1660 SUPER, pci bus id: 0000:01:00.0, compute capability: 7.5 &gt;&gt;&gt; train_set = tfds.load(&quot;imdb_reviews&quot;) &gt;&gt;&gt; &gt;&gt;&gt; test_set = datasets[&quot;test&quot;] &gt;&gt;&gt; train_set, test_set = tfds.load(&quot;imdb_reviews&quot;, split=[&quot;train&quot;, &quot;test&quot;]) &gt;&gt;&gt; for review, label in train_set.take(2): ... print(review.numpy().decode(&quot;utf-8&quot;)) File &quot;&lt;stdin&gt;&quot;, line 2 print(review.numpy().decode(&quot;utf-8&quot;)) ^ IndentationError: expected an indented block &gt;&gt;&gt; print(review.numpy().decode(&quot;utf-8&quot;)) Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; NameError: name 'review' is not defined </code></pre> <pre><code>&gt;&gt;&gt; Windows 11 PowerShell. File &quot;&lt;stdin&gt;&quot;, line 1 Windows 11 PowerShell. IndentationError: unexpected indent &gt;&gt;&gt; &gt;&gt;&gt; !pip install tensorflow-datasets File &quot;&lt;stdin&gt;&quot;, line 1 !pip install tensorflow-datasets ^ SyntaxError: invalid syntax &gt;&gt;&gt; pip install tensorflow-datasets File &quot;&lt;stdin&gt;&quot;, line 1 pip install tensorflow-datasets ^ SyntaxError: invalid syntax &gt;&gt;&gt; &gt;&gt;&gt; # pip install tfds-nightly &gt;&gt;&gt; &gt;&gt;&gt; import tensorflow_datasets as tfds &gt;&gt;&gt; datasets = tfds.load(&quot;imdb_reviews&quot;) &gt;&gt;&gt; &gt;&gt;&gt; train_set = tfds.load(&quot;imdb_reviews&quot;) # 25.000 reviews. &gt;&gt;&gt; test_set = datasets[&quot;test&quot;] # 25.000 reviews. &gt;&gt;&gt; &gt;&gt;&gt; train_set, test_set = tfds.load(&quot;imdb_reviews&quot;, split=[&quot;train&quot;, &quot;test&quot;]) &gt;&gt;&gt; train_set, test_set = tfds.load(&quot;imdb_reviews:1.0.0&quot;, split=[&quot;train&quot;, &quot;test&quot;]) &gt;&gt;&gt; train_set, test_set = tfds.load(&quot;imdb_reviews:1.0.0&quot;, split=[&quot;train&quot;, &quot;test[:60%]&quot;]) &gt;&gt;&gt; train_set, test_set, valid_set = tfds.load(&quot;imdb_reviews:1.0.0&quot;, split=[&quot;train&quot;, &quot;test[:60%]&quot;], &quot;test[60%:]&quot;) File &quot;&lt;stdin&gt;&quot;, line 1 train_set, test_set, valid_set = tfds.load(&quot;imdb_reviews:1.0.0&quot;, split=[&quot;train&quot;, &quot;test[:60%]&quot;], &quot;test[60%:]&quot;) ^ SyntaxError: positional argument follows keyword argument &gt;&gt;&gt; train_set, test_set, valid_set = tfds.load(&quot;imdb_reviews:1.0.0&quot;, split=[&quot;train&quot;, &quot;test[:60%]&quot;, &quot;test[60%:]&quot;]) &gt;&gt;&gt; for review, label in train_set.take(2): ... print(review.numpy().decode(&quot;utf-8&quot;)) ... print(label.numpy()) ... 2022-12-01 20:07:51.639683: W tensorflow/core/kernels/data/cache_dataset_ops.cc:856] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 2, in &lt;module&gt; AttributeError: 'str' object has no attribute 'numpy' &gt;&gt;&gt; </code></pre>
[ { "answer_id": 74642866, "author": "Cpt.Hook", "author_id": 20599896, "author_profile": "https://Stackoverflow.com/users/20599896", "pm_score": 2, "selected": true, "text": "python powershell my_code.py python my_code.py" }, { "answer_id": 74656889, "author": "OneCricketeer", "author_id": 2308683, "author_profile": "https://Stackoverflow.com/users/2308683", "pm_score": 0, "selected": false, "text": "pip install Windows 11 Powershell reviews not defined 'str' object has no attribute 'numpy' print(review.numpy().decode(\"utf-8\"))" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3728901/" ]
74,642,434
<p>I have a problem depending the Navigator setup that is used with Version 5 of React Navigation.</p> <p>Here is my Code:</p> <pre><code>import React from &quot;react&quot;; import { LogBox, Platform, TouchableOpacity } from &quot;react-native&quot;; import { NavigationContainer } from &quot;@react-navigation/native&quot;; import { createStackNavigator } from &quot;@react-navigation/stack&quot; import { createBottomTabNavigator } from &quot;@react-navigation/bottom-tabs&quot;; import { Auth, Monatsübersicht2, StundenChecken, StundenEintragen, Logout, TagesübersichtDiff, StundenEdit, MonatsberichtComponent, } from &quot;../screens/index&quot;; import Icon from &quot;react-native-vector-icons/Ionicons&quot;; import AsyncStorage from &quot;@react-native-async-storage/async-storage&quot;; LogBox.ignoreAllLogs(); const Stack = createStackNavigator(); function EintragenStack() { return ( &lt;Stack.Navigator initialRouteName=&quot;Eintragen&quot;&gt; &lt;Stack.Screen name=&quot;Eintragen&quot; component={StundenEintragen} options={{ headerTitle: &quot;Stundenverwaltung&quot;, headerTitleStyle: { color: &quot;white&quot;, alignSelf: &quot;center&quot;, }, headerStyle: { backgroundColor: &quot;#a51717&quot;, }, headerRight: () =&gt; ( &lt;TouchableOpacity onPress={console.log(&quot;unlockUserHandler&quot;)}&gt; &lt;Icon style={{ paddingRight: 20 }} size={25} color=&quot;white&quot; name=&quot;lock-open&quot; /&gt; &lt;/TouchableOpacity&gt; ), }} /&gt; &lt;/Stack.Navigator&gt; )}; function CheckStack(){ return ( &lt;Stack.Navigator initialRouteName=&quot;Übersicht&quot; &gt; &lt;Stack.Screen name=&quot;Übersicht&quot; component={StundenChecken} /&gt; &lt;Stack.Screen name=&quot;Monat&quot; component={Monatsübersicht2} options={({navigation}) =&gt; ({ title: &quot;Monatsübersicht&quot; })} /&gt; &lt;Stack.Screen name=&quot;Tag&quot; component={TagesübersichtDiff} options={({navigation}) =&gt; ({ headerRight: () =&gt; ( &lt;TouchableOpacity onPress={() =&gt; console.log(&quot;Ahllo&quot;)}&gt; &lt;Icon style={{ paddingRight: 20 }} size={25} color=&quot;#a51717&quot; name=&quot;lock-open&quot; /&gt; &lt;/TouchableOpacity&gt; ), title: &quot;Tagesübersicht&quot; })} /&gt; &lt;Stack.Screen name=&quot;Edit&quot; component={StundenEdit} options={{ headerTitle: &quot;Stunden bearbeiten&quot;, headerTitleStyle: { color: &quot;white&quot;, alignSelf: &quot;center&quot;, }, headerStyle: { backgroundColor: &quot;#F39237&quot;, }, headerRight: () =&gt; ( &lt;TouchableOpacity onPress={console.log(&quot;unlockUserHandler&quot;)}&gt; &lt;Icon style={{ paddingRight: 20 }} size={25} color=&quot;white&quot; name=&quot;lock-open&quot; /&gt; &lt;/TouchableOpacity&gt; ), }} /&gt; &lt;/Stack.Navigator&gt; )} const Tab = createBottomTabNavigator(); function Tabs() { return ( &lt;Tab.Navigator initialRouteName=&quot;Eintragen&quot; screenOptions={{ backBehavior: &quot;history&quot;, resetOnBlur: true, tabBarOptions: { labelStyle: { fontSize: 12, color: &quot;black&quot;, }, showIcon : true, activeTintColor: &quot;red&quot;, activeBackgroundColor: &quot;#ccc&quot;, } }}&gt; &lt;Tab.Screen name=&quot;Eintragen&quot; component={EintragenStack} options={{ tabBarIcon:() =&gt; (&lt;Icon name=&quot;add-circle-outline&quot; size={Platform.OS == &quot;ios&quot; ? 30 : 28} color={&quot;green&quot;} /&gt;)}}/&gt; &lt;Tab.Screen name=&quot;Übersicht&quot; component={CheckStack} options={{ tabBarIcon:() =&gt; (&lt;Icon name=&quot;calendar&quot; size={Platform.OS == &quot;ios&quot; ? 30 : 28} color={&quot;black&quot;} /&gt;)}}/&gt; &lt;Tab.Screen name=&quot;Monatsbericht&quot; component={MonatsberichtComponent} options={{headerTitle: &quot;Monatsbericht abschließen&quot;, tabBarIcon:() =&gt; (&lt;Icon name=&quot;download&quot; size={Platform.OS == &quot;ios&quot; ? 30 : 28} color={&quot;black&quot;} /&gt;)}}/&gt; &lt;Tab.Screen name=&quot;Logout&quot; component={Logout} options={{ tabBarIcon:() =&gt; (&lt;Icon name=&quot;power&quot; size={Platform.OS == &quot;ios&quot; ? 30 : 28} color={&quot;red&quot;} /&gt;)}}/&gt; &lt;/Tab.Navigator&gt; ) } const AppNavigator = () =&gt; { return ( &lt;NavigationContainer&gt; &lt;Stack.Navigator screenOptions={{ headerShown: false, headerLeft: null, gestureEnabled: false }} &gt; &lt;Stack.Screen name=&quot;Auth&quot; component={Auth} /&gt; &lt;Stack.Screen name=&quot;Tabs&quot; component={Tabs} /&gt; &lt;/Stack.Navigator&gt; &lt;/NavigationContainer&gt; ) } export default function App() { return &lt;AppNavigator/&gt;; } </code></pre> <p>Now in my Auth Screen I can navigate to Tabs - so basically Log into the App by calling:</p> <pre><code>navigation.replace(&quot;Tabs&quot;); </code></pre> <p>But when I try to navigate to my CheckStack for example it wont work and I get thrown this error:</p> <p>The Call: <code>navigation.replace(&quot;CheckStack&quot;);</code></p> <p>The Error:</p> <pre><code>ERROR The action 'REPLACE' with payload {&quot;name&quot;:&quot;CheckStack&quot;} was not handled by any navigator. Do you have a screen named 'CheckStack'? </code></pre>
[ { "answer_id": 74652189, "author": "JSONCMD", "author_id": 20629269, "author_profile": "https://Stackoverflow.com/users/20629269", "pm_score": -1, "selected": false, "text": "navigation.replace(\"Tabs\"); \n navigation.replace(\"CheckStack\");\n" }, { "answer_id": 74654260, "author": "yesIamFaded", "author_id": 11270696, "author_profile": "https://Stackoverflow.com/users/11270696", "pm_score": 0, "selected": false, "text": " <NavigationContainer>\n <Stack.Navigator \n screenOptions={{\n headerShown: false,\n headerLeft: null,\n gestureEnabled: false\n }}\n >\n <Stack.Screen name=\"Auth\" component={Auth} />\n <Stack.Screen name=\"Tabs\" component={Tabs} />\n <Stack.Screen name=\"CheckStack\" component={CheckStack} />\n </Stack.Navigator>\n </NavigationContainer>\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11270696/" ]
74,642,497
<p>I have a following table:-</p> <pre><code>declare @tab table(name varchar(10),id int) insert into @tab values ('A',1),('B',1),('C',1),('D',1),('E',2),('F',2) </code></pre> <p>I need following output:-</p> <pre><code>declare @tab1 table(name varchar(10),id int, cnt int) insert into @tab1 values ('A',1,4),('B',1,4),('C',1,4),('D',1,4),('E',2,2),('F',2,2) select * from @tab1 </code></pre> <p>I tried following query:-</p> <pre><code>select name,id,count(*) as cnt from @tab group by name,id </code></pre> <p>Thanks</p>
[ { "answer_id": 74642570, "author": "Rahul Aggarwal", "author_id": 7769070, "author_profile": "https://Stackoverflow.com/users/7769070", "pm_score": 0, "selected": false, "text": ";with a as\n(\nselect Id,name, count(*) over (partition by id) cnt\n\nfrom @tab\n)\nselect Id,name,cnt\nfrom a\n" }, { "answer_id": 74642586, "author": "PeterClemmensen", "author_id": 4044936, "author_profile": "https://Stackoverflow.com/users/4044936", "pm_score": 2, "selected": true, "text": "select name\n , id\n , count(*) over(partition by id) as cnt\nfrom @tab\n;\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7769070/" ]
74,642,518
<p>I’m working on a Operating Systems project with requirements being the usage of C89 and pedantic flags.</p> <p>Since I am on macOS, I’ve encountered a fair amount of issues with the <code>rand()</code> function during a few exercises. In fact, its macOS man page calls it a “bad number generator”. So, to avoid issues with it I had switched to using <code>random()</code>. Now, since I am compiling with <code>-std=c89</code>, <code>-pedantic</code>, <code>wall</code> and <code>werror</code>, it refuses to function correctly due to having a warning about an implicit declaration for <code>random()</code>. If I remove <code>werror</code>, it does generate the warning, but it compiles (as expected) but more interestingly, it works perfectly fine. It generates a number as expected. What am I doing wrong? Does C89 support <code>random</code> or not? What am I supposed to include that’ll make the warning go away? The man page mentions nothing other than <code>stdlib.h</code> which is included.</p> <p>A viable alternative as mentioned by the manpage, would be <code>arc4random()</code>, however I am pretty sure it doesn't exist cross-platform.</p> <p>My test snippet is</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main() { int test; srandom(5); test = random() % 190; printf(&quot;Hello World %d\n&quot;, test); return 0; } </code></pre> <p>And it generates the following output:</p> <pre><code>main.c:15:5: warning: implicit declaration of function ‘srandom’; did you mean ‘srand’? [-Wimplicit-function-declaration] 15 | srandom(5); | ^~~~~~~ | srand main.c:17:12: warning: implicit declaration of function ‘random’; did you mean ‘rand’? [-Wimplicit-function-declaration] 17 | test = random() % 190; | ^~~~~~ | rand Hello World 115 </code></pre>
[ { "answer_id": 74642690, "author": "P.P", "author_id": 1275169, "author_profile": "https://Stackoverflow.com/users/1275169", "pm_score": 3, "selected": true, "text": "random srandom -std=c89 #define _DEFAULT_SOURCE\n #define _XOPEN_SOURCE 600\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20583148/" ]
74,642,527
<p>I run pytest with several params:</p> <pre><code>@pytest.mark.parametrize('signature_algorithm, cipher, name', [ pytest.param(rsa_pss_rsae_sha256, AES128-GCM-SHA256, &quot;KEY1&quot;), pytest.param(rsa_pss_rsae_sha384, AES128-GCM-SHA256, &quot;KEY2&quot;), .... def test(signature_algorithm, cipher, cert_name, functaion1(&quot;data&quot;)): ..... functaion1(data): Change file in server (using data value) </code></pre> <p>I need to call the functaion1(data) only once when test starts. How can I achieve this using pytest?</p> <p>I tried to add functaion1 as parameter in test function but I got syntax error while I add parentheses to the functaion1 (because I want to send a certain value to function1).</p>
[ { "answer_id": 74642690, "author": "P.P", "author_id": 1275169, "author_profile": "https://Stackoverflow.com/users/1275169", "pm_score": 3, "selected": true, "text": "random srandom -std=c89 #define _DEFAULT_SOURCE\n #define _XOPEN_SOURCE 600\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17914924/" ]
74,642,560
<p><a href="https://i.stack.imgur.com/Uwm59.png" rel="nofollow noreferrer">Why im getting (The argument type 'String?' can't be assigned to the parameter type 'String') error.</a></p> <p><a href="https://i.stack.imgur.com/XmgxH.png" rel="nofollow noreferrer">declaring variables</a></p>
[ { "answer_id": 74642690, "author": "P.P", "author_id": 1275169, "author_profile": "https://Stackoverflow.com/users/1275169", "pm_score": 3, "selected": true, "text": "random srandom -std=c89 #define _DEFAULT_SOURCE\n #define _XOPEN_SOURCE 600\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19792080/" ]
74,642,575
<p>hoping someone can help me with my code. I'm new to python and software development. I'm trying to find the first two elements that are out of order and swap them.</p> <pre><code>arr = [5, 22, 29, 39, 19, 51, 78, 96, 84] i = 0 while (i &lt; arr.len() - 1) and (arr[i] &lt; arr[i+1]): i += i print(i) arr[i] = arr[i+1] arr[i+1] = arr[i] </code></pre>
[ { "answer_id": 74642687, "author": "kamilu", "author_id": 17869889, "author_profile": "https://Stackoverflow.com/users/17869889", "pm_score": 0, "selected": false, "text": "arr = [5,22,29,39,19,51,78,96,84]\n\nfor i in range(len(arr)):\n if arr[i]>arr[i+1]:\n temp = arr[i]\n arr[i] = arr[i+1]\n arr[i+1] = temp\n break\n\nprint(arr)\n# [5, 22, 29, 19, 39, 51, 78, 96, 84]\n" }, { "answer_id": 74642725, "author": "Ivan Perehiniak", "author_id": 20637117, "author_profile": "https://Stackoverflow.com/users/20637117", "pm_score": 1, "selected": false, "text": "arr = [1, 2, 8, 4, 5, 6] \nfor i in range(len(arr)-1):\n if arr[i] > arr[i+1]:\n arr[i], arr[i+1] = arr[i+1], arr[i]\n break\nprint(arr)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20656721/" ]
74,642,594
<p>I am using the <a href="https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines" rel="nofollow noreferrer">StableDiffusionPipeline</a> from the Hugging Face <a href="https://huggingface.co/docs/diffusers/index" rel="nofollow noreferrer">Diffusers</a> library in Python 3.10.2, on an M2 Mac (I tagged it because this might be the issue). When I try to generate 1 image from 1 prompt, the output looks fine, but when I try to generate multiple images using the same prompt, the images are all either black squares or a random image (see example below). What could be the issue?</p> <p>My code is as follows (where I change <code>n_imgs</code> from 1 to more than 1 to break it):</p> <pre><code>from diffusers import StableDiffusionPipeline pipe = StableDiffusionPipeline.from_pretrained(&quot;runwayml/stable-diffusion-v1-5&quot;) pipe = pipe.to(&quot;mps&quot;) # for M1/M2 chips pipe.enable_attention_slicing() prompt = &quot;a photo of an astronaut driving a car on mars&quot; # First-time &quot;warmup&quot; pass (because of weird M1 behaviour) _ = pipe(prompt, num_inference_steps=1) # generate images n_imgs = 1 imgs = pipe([prompt] * n_imgs).images </code></pre> <p>I also tried setting <code>num_images_per_prompt</code> instead of creating a list of repeated prompts in the pipeline call, but this gave the same bad results.</p> <p>Example output (for multiple images):</p> <p><a href="https://i.stack.imgur.com/EOWps.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EOWps.png" alt="white noise image generated by machine learning transformer model" /></a></p> <p>[edit/update]: When I generate the images in a loop surrounding the pipe call instead of passing an iterable to the pipe call, it does work:</p> <pre><code># generate images n_imgs = 3 for i in range(n_imgs): img = pipe(prompt).images[0] # do something with img </code></pre> <p>But it is still a mystery to me as to why.</p>
[ { "answer_id": 74654989, "author": "pcuenca", "author_id": 346029, "author_profile": "https://Stackoverflow.com/users/346029", "pm_score": 0, "selected": false, "text": "import MetalPerformanceShadersGraph\n\nlet graph = MPSGraph()\nlet x = graph.constant(1, shape: [32, 4096, 4096], dataType: .float32)\nlet y = graph.constant(1, shape: [32, 4096, 1], dataType: .float32)\nlet z = graph.matrixMultiplication(primary: x, secondary: y, name: nil)\nlet device = MTLCreateSystemDefaultDevice()!\nlet buf = device.makeBuffer(length: 16384)!\nlet td = MPSGraphTensorData(buf, shape: [64, 64], dataType: .int32)\nlet cmdBuf = MPSCommandBuffer(from: device.makeCommandQueue()!)\ngraph.encode(to: cmdBuf, feeds: [:], targetOperations: nil, resultsDictionary: [z:td], executionDescriptor: nil)\ncmdBuf.commit()\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17973966/" ]
74,642,596
<p>How can I access a state using the same-id across multiple transformers, for example the following stores an Order object via ValueState in OrderMapper class:</p> <pre><code>env.addSource(source1()).keyBy(Order::getId).flatMap(new OrderMapper()).addSink(sink1()); </code></pre> <p>Now I would like to access the same Order object via a SubOrderMapper class:</p> <pre><code>env.addSource(source2()).keyBy(SubOrder::getOrderId).flatMap(new SubOrderMapper()).addSink(sink2()); </code></pre> <p>Edit: Looks like it's not possible to have state maintained across multiple operators, is there a way to have one operator accept multiple inputs, lets say 5 sources?</p>
[ { "answer_id": 74654989, "author": "pcuenca", "author_id": 346029, "author_profile": "https://Stackoverflow.com/users/346029", "pm_score": 0, "selected": false, "text": "import MetalPerformanceShadersGraph\n\nlet graph = MPSGraph()\nlet x = graph.constant(1, shape: [32, 4096, 4096], dataType: .float32)\nlet y = graph.constant(1, shape: [32, 4096, 1], dataType: .float32)\nlet z = graph.matrixMultiplication(primary: x, secondary: y, name: nil)\nlet device = MTLCreateSystemDefaultDevice()!\nlet buf = device.makeBuffer(length: 16384)!\nlet td = MPSGraphTensorData(buf, shape: [64, 64], dataType: .int32)\nlet cmdBuf = MPSCommandBuffer(from: device.makeCommandQueue()!)\ngraph.encode(to: cmdBuf, feeds: [:], targetOperations: nil, resultsDictionary: [z:td], executionDescriptor: nil)\ncmdBuf.commit()\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/411709/" ]
74,642,653
<p>i am trying to write a code in C but i am having some problems with realloc. I had to write a code that will create a stack, and will add to it (dodaj_do_stosu), reamove from it (usun_ze_stosu) and will look at the top thing that is on this stack. I have problem with compiling(it does work for first two words but then it returns (0xC0000374)).</p> <p>I think i am usining the realloc wrong and the sizeof my structure. If someone could look at my code (especially at the function (dodaj_do_stosu) and tell me what am i doing wrong thx. My code look like this:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; typedef struct { int n; char *nazwa; }element_t; typedef struct { int rozmiar; element_t **tablica; }stos_t; void top_of_stack(stos_t *s){ printf(&quot;ostatni element stosu:rozmiar = %d nazwa=%s, n=%d\n&quot;, s-&gt;rozmiar, s-&gt;tablica[s-&gt;rozmiar]-&gt;nazwa, s-&gt;tablica[s-&gt;rozmiar]-&gt;n); } void init(stos_t *s) { s-&gt;rozmiar=0; s-&gt;tablica=malloc(0); } void dodaj_do_stosu(stos_t *s, int n, char *name) { s-&gt;tablica = realloc(s-&gt;tablica, (s-&gt;rozmiar + 1) * sizeof(s-&gt;tablica)); s-&gt;tablica[s-&gt;rozmiar]-&gt;nazwa = name; s-&gt;tablica[s-&gt;rozmiar]-&gt;n = n; printf(&quot;rozmiar=%d, n=%d , nazwa=%s\n&quot;,s-&gt;rozmiar, s-&gt;tablica[s-&gt;rozmiar]-&gt;n, s-&gt;tablica[s-&gt;rozmiar]-&gt;nazwa); s-&gt;rozmiar++; } void usun_ze_stosu(stos_t *s) { s-&gt;tablica = realloc(s-&gt;tablica, (s-&gt;rozmiar - 1) * sizeof(s-&gt;tablica[0])); s-&gt;rozmiar--; } void rm(stos_t s) { free(s.tablica); } int main(int argc, char **argv) { stos_t s; init(&amp;s); int i; srand(time(0)); if (argc&gt;1) for(i=1;i&lt;argc;i++){ printf(&quot;%s\n&quot;, argv[i]); dodaj_do_stosu(&amp;s, rand() % 10, argv[i]); } for(i=0;i&lt;argc-1;i++){ //printf(&quot;i=%d, n=%d, nazwa=%s\n&quot;,i, s.tablica[i].n, s.tablica[i].nazwa); } //top_of_stack(&amp;s); //usun_ze_stosu(&amp;s); //top_of_stack(&amp;s); rm(s); return 0; } </code></pre>
[ { "answer_id": 74642727, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 2, "selected": false, "text": "tablica dodaj_do_stosu element_t s->tablica[s->rozmiar] element_t s->tablica[s->rozmiar] = malloc(sizeof(element_t));\n element_t tablica element_t *tablica; // tablica is an array of objects, not an array of pointers\n" }, { "answer_id": 74642758, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": true, "text": "dodaj_do_stosu tablica element_t **tablica;\n s->tablica[s->rozmiar] element_t * s->tablica[s->rozmiar]->nazwa\n element_t element_t * element_t *tablica;\n s->tablica = realloc(s->tablica, (s->rozmiar + 1) * sizeof( *s->tablica));\n realloc int dodaj_do_stosu( stos_t *s, int n, char *name )\n{\n element_t *tmp = realloc( s->tablica, ( s->rozmiar + 1 ) * sizeof( *s->tablica ) );\n int success = tmp != NULL;\n\n if ( success )\n {\n s->tablica = tmp; \n s->tablica[s->rozmiar]->nazwa = name;\n s->tablica[s->rozmiar]->n = n;\n printf(\"rozmiar=%d, n=%d , nazwa=%s\\n\", s->rozmiar, s->tablica[s->rozmiar]->n, s->tablica[s->rozmiar]->nazwa );\n ++s->rozmiar;\n }\n\n return success;\n}\n s->rozmiar int usun_ze_stosu( stos_t *s )\n{\n int success = s->rozmiar != 0;\n\n if ( success )\n {\n element_t *tmp = realloc( s->tablica, ( s->rozmiar - 1 ) * sizeof( *s->tablica ) );\n success = tmp != NULL;\n\n if ( success )\n {\n s->tablica = tmp;\n --s->rozmiar;\n }\n }\n\n return success;\n}\n init void init(stos_t *s)\n{\n s->rozmiar=0;\n s->tablica = NULL;\n}\n rm void rm(stos_t s)\n{\n free(s.tablica);\n}\n void rm(stos_t *s)\n{\n free( s->tablica );\n s->tablica = NULL;\n s->rozmiar = 0;\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20656737/" ]
74,642,657
<p>I am writing a PySpark code to read PARQUET files from my local machine and process them. My directories and file paths look like this:</p> <pre><code>. ├── customer │   └── day=20220815 │   └── part-00000-4dff7e82-411b-4940-bdb6-33acf5a189b4-c000.snappy.parquet └── customer_interaction └── day=20220815 └── part-00000-7b3ee7fd-c515-41c0-96a6-2f2dbbc0c9cf-c000.snappy.parquet 4 directories, 2 files </code></pre> <p>There are two different files in two different folders that I want to read in my code. As of now, I am using hardcoded values to pass the paths of these files like this:</p> <pre><code>customer_df = spark.read.parquet('customer/day=20220815/part-00000-4dff7e82-411b-4940-bdb6-33acf5a189b4-c000.snappy.parquet') customer_interaction_df = spark.read.parquet('customer_interaction/day=20220815/part-00000-7b3ee7fd-c515-41c0-96a6-2f2dbbc0c9cf-c000.snappy.parquet') </code></pre> <p>But this is not what I want. Is there any other way that I can use for reading the files?</p>
[ { "answer_id": 74642730, "author": "Triceratops", "author_id": 13440165, "author_profile": "https://Stackoverflow.com/users/13440165", "pm_score": 3, "selected": true, "text": "glob pathlib import glob\n\n# Returns a list of names in list files.\nprint(\"Using glob.glob()\")\nfiles = glob.glob('/main_directory/**/*.snappy.parquet', \n recursive = True)\nfor file in files:\n print(file)\n" }, { "answer_id": 74643302, "author": "Hi Chem", "author_id": 14852065, "author_profile": "https://Stackoverflow.com/users/14852065", "pm_score": 0, "selected": false, "text": "X_data_no=[]\nno_images = glob.glob(\"./Dataset/brain_tumor_dataset/no/\"+'*')\nfor myFile in no_images:\n image_no = cv2.imread(myFile)\n print(image_no) \n\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13108058/" ]
74,642,689
<p>I am using python3.11 to create the Delaunay triangulation of a point cloud with script.Delaunay and it is misbehaving by creating some extra faces. In the image below you can see a 3D scatter plot of the points.</p> <p><a href="https://i.stack.imgur.com/8MLVR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8MLVR.png" alt="point cloud image" /></a></p> <p>The image was created using the next very few lines of code:</p> <pre><code>import plotly.graph_objects as go fig = go.Figure() fig.add_scatter3d(x = puntos[:,0], y = puntos[:,1], z = puntos[:,2],mode='markers', marker=dict( size=1, color='rgb(0,0,0)', opacity=0.8 )) fig.update_layout(scene = dict(aspectmode = 'data')) fig.show() </code></pre> <p>The data <strong>puntos</strong> can be downloaded as a csv file <a href="https://drive.google.com/file/d/1ePrLHv32ajUxIaeE26A0ruKTJ1wbsI-U/view?usp=sharing" rel="nofollow noreferrer">in this link</a>. Now, as I said, I am interested in obtaining the Delaunay triangulation of that point could, for which the following piece of code is used.</p> <pre><code>import numpy as np import pandas as pd from scipy.spatial import Delaunay import plotly.figure_factory as ff puntos = pd.read_csv('puntos.csv') puntos = puntos[['0', '1', '2']] tri = Delaunay(np.array([puntos[:,0], puntos[:,1]]).T) simplices = tri.simplices fig = ff.create_trisurf(x=puntos[:,0], y=puntos[:,1], z=puntos[:,2], simplices=simplices, aspectratio=dict(x=1, y=1, z=0.3)) fig.show() </code></pre> <p>This produces the following image (point cloud images and triangulation image do not have exactly same aspect ratio, but I find it sufficient this way):</p> <p><a href="https://i.stack.imgur.com/xdSj4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xdSj4.png" alt="delaunay trinagulation" /></a></p> <p>As you might see, the triangulation is creating some extra faces in the boundary of the surface, and that is repeated along the four sides of the boundary. Anyone knows why this happens and how can I solve it?</p> <p>Thank you in advance!</p>
[ { "answer_id": 74642730, "author": "Triceratops", "author_id": 13440165, "author_profile": "https://Stackoverflow.com/users/13440165", "pm_score": 3, "selected": true, "text": "glob pathlib import glob\n\n# Returns a list of names in list files.\nprint(\"Using glob.glob()\")\nfiles = glob.glob('/main_directory/**/*.snappy.parquet', \n recursive = True)\nfor file in files:\n print(file)\n" }, { "answer_id": 74643302, "author": "Hi Chem", "author_id": 14852065, "author_profile": "https://Stackoverflow.com/users/14852065", "pm_score": 0, "selected": false, "text": "X_data_no=[]\nno_images = glob.glob(\"./Dataset/brain_tumor_dataset/no/\"+'*')\nfor myFile in no_images:\n image_no = cv2.imread(myFile)\n print(image_no) \n\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17744452/" ]
74,642,700
<p>I have the following LateX table that renders as expected when <code>format: pdf</code>:</p> <pre><code>--- title: &quot;Test Table&quot; format: pdf --- \begin{center} \begin{tabular}{|l|l|l|} \hline Var &amp; Class &amp; Description\\ \hline $x $ &amp; numeric &amp; xyz \\ $y$ &amp; numeric &amp; xzh \\ $z $ &amp; integer &amp; xlp \\ \hline \end{tabular} \end{center} </code></pre> <p><a href="https://i.stack.imgur.com/YdXaI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YdXaI.png" alt="enter image description here" /></a></p> <p>I look for possibilities that this table also get's displayed in HTML format, e.g. <code>format: html</code>. I have many (many) LaTeX tables that I need to transform, hence I hope for a solution that avoids the manual work to write them all as markdown tables. Any help is as always much appreciated!</p>
[ { "answer_id": 74642730, "author": "Triceratops", "author_id": 13440165, "author_profile": "https://Stackoverflow.com/users/13440165", "pm_score": 3, "selected": true, "text": "glob pathlib import glob\n\n# Returns a list of names in list files.\nprint(\"Using glob.glob()\")\nfiles = glob.glob('/main_directory/**/*.snappy.parquet', \n recursive = True)\nfor file in files:\n print(file)\n" }, { "answer_id": 74643302, "author": "Hi Chem", "author_id": 14852065, "author_profile": "https://Stackoverflow.com/users/14852065", "pm_score": 0, "selected": false, "text": "X_data_no=[]\nno_images = glob.glob(\"./Dataset/brain_tumor_dataset/no/\"+'*')\nfor myFile in no_images:\n image_no = cv2.imread(myFile)\n print(image_no) \n\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14137004/" ]
74,642,704
<p>hi all im trying to make this</p> <pre><code>2022-11-14 18:49:59 Indicator is &lt; 3 1 No 2022-11-14 18:49:59 Indicator is &lt; 10 1 No 2022-11-14 18:49:59 Indicator is &lt; 22 1 No 2022-11-14 18:49:59 Indicator is &lt; 1 1 No </code></pre> <p>into</p> <pre><code>2022-11-14 18:49:59 Indicator is &lt; 3 1 No 2022-11-14 18:49:59 Indicator is &lt; 10 1 No 2022-11-14 18:49:59 Indicator is &lt; 22 1 No 2022-11-14 18:49:59 Indicator is &lt; 1 1 No </code></pre> <p>i found that you can use <code>sed 's/something/some//2'</code> for every second encounter but how to make it for 1st, 3th, 5th,.... and so one</p>
[ { "answer_id": 74642842, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": true, "text": "awk $ awk -v val=2 'NR % val == 0{print prev, $0} {prev = $0}' file\n2022-11-14 18:49:59 Indicator is < 3 1 No\n2022-11-14 18:49:59 Indicator is < 10 1 No\n2022-11-14 18:49:59 Indicator is < 22 1 No\n2022-11-14 18:49:59 Indicator is < 1 1 No\n NR $0" }, { "answer_id": 74643770, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 2, "selected": false, "text": "$ awk '{printf \"%s%s\", $0, (NR%2 ? OFS : ORS)}' file\n2022-11-14 18:49:59 Indicator is < 3 1 No\n2022-11-14 18:49:59 Indicator is < 10 1 No\n2022-11-14 18:49:59 Indicator is < 22 1 No\n2022-11-14 18:49:59 Indicator is < 1 1 No\n $ seq 5 | awk '{printf \"%s%s\", $0, (NR%2 ? OFS : ORS)}'\n1 2\n3 4\n5 $\n $ seq 5 | awk 'NR % 2 == 0{print prev, $0} {prev = $0}'\n1 2\n3 4\n$\n" }, { "answer_id": 74648154, "author": "karakfa", "author_id": 1435869, "author_profile": "https://Stackoverflow.com/users/1435869", "pm_score": 2, "selected": false, "text": "$ paste - - <file\n\n2022-11-14 18:49:59 Indicator is < 3 1 No\n2022-11-14 18:49:59 Indicator is < 10 1 No\n2022-11-14 18:49:59 Indicator is < 22 1 No\n2022-11-14 18:49:59 Indicator is < 1 1 No\n $ pr -w112 -2at file\n\n2022-11-14 18:49:59 Indicator is < 3 1 No\n2022-11-14 18:49:59 Indicator is < 10 1 No\n2022-11-14 18:49:59 Indicator is < 22 1 No\n2022-11-14 18:49:59 Indicator is < 1 1 No\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4003516/" ]
74,642,705
<p>Given two binary arrays, how can one quickly find the number of 1's occurring between intersecting bits for both arrays?</p> <p>For example, consider a pair of bitsets (<code>i1</code>, <code>i2</code>) and their intersection (<code>i12</code>):</p> <pre><code>i1 = [0001001000100100]; i2 = [0101000100010110]; i12 = [0001000000000100]; // (i1 &amp; i2) </code></pre> <p>The intersecting bits are in position 3 and 13, so count the number of 1's in positions 0-2 and 4-12:</p> <pre><code>x1 = [0, 2] // results i1 x2 = [1, 2] // results for i2 </code></pre> <p>Now generalize this idea to 32-bit integers. Toy example:</p> <pre><code>int i1[2] = {2719269390, 302235938}; int i2[2] = {2315436042, 570885266}; </code></pre> <p>Toy example in binary:</p> <pre><code>i1 = [10100010 00010100 11000010 00001110, 00010010 00000011 11000001 00100010] i2 = [10001010 00000010 11000000 00001010, 00100010 00000111 00000100 10010010] i1 &amp; i2 = [10000010 00000000 11000000 00001010, 00000010 00000011 00000000 00000010] </code></pre> <p>Expected results:</p> <pre><code>x1 = [2, 2, 0, 1, 1, 1, 0, 0, 4]; x2 = [2, 1, 0, 0, 0, 1, 1, 0, 3]; </code></pre> <p>I can see a &quot;brute-force&quot; approach using <code>__builtin_clz()</code> to determine leading zeros in <code>i1 &amp; i2</code>, shifting <code>i1</code> and <code>i2</code> right by that number, doing <code>__builtin_popcount()</code> for the shifted <code>i1</code> and <code>i2</code> results, and repeating the procedure until no intersections remain. My instinct suggests there may be a more elegant approach, as this involves a few temporaries, many instructions, and at least two logical branches.</p> <p>C/C++ implementations are welcome, but I would be satisfied enough with conceptual perspectives. Suffice it to say this approach intends to remove a critical bottleneck in a popular program.</p>
[ { "answer_id": 74642842, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": true, "text": "awk $ awk -v val=2 'NR % val == 0{print prev, $0} {prev = $0}' file\n2022-11-14 18:49:59 Indicator is < 3 1 No\n2022-11-14 18:49:59 Indicator is < 10 1 No\n2022-11-14 18:49:59 Indicator is < 22 1 No\n2022-11-14 18:49:59 Indicator is < 1 1 No\n NR $0" }, { "answer_id": 74643770, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 2, "selected": false, "text": "$ awk '{printf \"%s%s\", $0, (NR%2 ? OFS : ORS)}' file\n2022-11-14 18:49:59 Indicator is < 3 1 No\n2022-11-14 18:49:59 Indicator is < 10 1 No\n2022-11-14 18:49:59 Indicator is < 22 1 No\n2022-11-14 18:49:59 Indicator is < 1 1 No\n $ seq 5 | awk '{printf \"%s%s\", $0, (NR%2 ? OFS : ORS)}'\n1 2\n3 4\n5 $\n $ seq 5 | awk 'NR % 2 == 0{print prev, $0} {prev = $0}'\n1 2\n3 4\n$\n" }, { "answer_id": 74648154, "author": "karakfa", "author_id": 1435869, "author_profile": "https://Stackoverflow.com/users/1435869", "pm_score": 2, "selected": false, "text": "$ paste - - <file\n\n2022-11-14 18:49:59 Indicator is < 3 1 No\n2022-11-14 18:49:59 Indicator is < 10 1 No\n2022-11-14 18:49:59 Indicator is < 22 1 No\n2022-11-14 18:49:59 Indicator is < 1 1 No\n $ pr -w112 -2at file\n\n2022-11-14 18:49:59 Indicator is < 3 1 No\n2022-11-14 18:49:59 Indicator is < 10 1 No\n2022-11-14 18:49:59 Indicator is < 22 1 No\n2022-11-14 18:49:59 Indicator is < 1 1 No\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1436247/" ]
74,642,709
<p>Every time my windows forms desktop app starts up, I need it to send a one-time <strong>string</strong> value to my windows service on the same pc. In most cases, the service will be running constantly even when the desktop app is not. But the desktop app will check and start the service if necessary.</p> <p>What is the easiest/best mechanism for simple communication of a single string on desktop app startup to the windows service? I have no idea how communication with windows service works.</p> <p>Is there any simple example of doing this?</p>
[ { "answer_id": 74642842, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": true, "text": "awk $ awk -v val=2 'NR % val == 0{print prev, $0} {prev = $0}' file\n2022-11-14 18:49:59 Indicator is < 3 1 No\n2022-11-14 18:49:59 Indicator is < 10 1 No\n2022-11-14 18:49:59 Indicator is < 22 1 No\n2022-11-14 18:49:59 Indicator is < 1 1 No\n NR $0" }, { "answer_id": 74643770, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 2, "selected": false, "text": "$ awk '{printf \"%s%s\", $0, (NR%2 ? OFS : ORS)}' file\n2022-11-14 18:49:59 Indicator is < 3 1 No\n2022-11-14 18:49:59 Indicator is < 10 1 No\n2022-11-14 18:49:59 Indicator is < 22 1 No\n2022-11-14 18:49:59 Indicator is < 1 1 No\n $ seq 5 | awk '{printf \"%s%s\", $0, (NR%2 ? OFS : ORS)}'\n1 2\n3 4\n5 $\n $ seq 5 | awk 'NR % 2 == 0{print prev, $0} {prev = $0}'\n1 2\n3 4\n$\n" }, { "answer_id": 74648154, "author": "karakfa", "author_id": 1435869, "author_profile": "https://Stackoverflow.com/users/1435869", "pm_score": 2, "selected": false, "text": "$ paste - - <file\n\n2022-11-14 18:49:59 Indicator is < 3 1 No\n2022-11-14 18:49:59 Indicator is < 10 1 No\n2022-11-14 18:49:59 Indicator is < 22 1 No\n2022-11-14 18:49:59 Indicator is < 1 1 No\n $ pr -w112 -2at file\n\n2022-11-14 18:49:59 Indicator is < 3 1 No\n2022-11-14 18:49:59 Indicator is < 10 1 No\n2022-11-14 18:49:59 Indicator is < 22 1 No\n2022-11-14 18:49:59 Indicator is < 1 1 No\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/458982/" ]
74,642,716
<p>I want to plot graph (which is an undirected connected graph) like the uploaded picture.</p> <p>I want to use the adjacency matrix in order to plot it.</p> <p>So my question is how can I plot a graph from its adjacency matrix.</p> <p>Ideally I want the plot to look like the attached picture.</p> <p>I tried the igraph package in R :</p> <pre><code> data &lt;- matrix(c(0,1,0,0,1, 1,0,1,0,0, 0,1,0,1,0, 0,0,1,0,1, 1,0,0,1,0),nrow=5,ncol = 5) colnames(data) = rownames(data) = LETTERS[1:5] data network &lt;- graph_from_adjacency_matrix(data) plot(network) </code></pre> <p>But it creates a cycle.</p> <p>Any help ?</p> <p><a href="https://i.stack.imgur.com/DSzzi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DSzzi.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74642796, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 3, "selected": true, "text": "mode = \"upper\" library(igraph)\n\ndata <- matrix(0, 5, 5, dimnames = list(LETTERS[1:5], LETTERS[1:5]))\ndata[upper.tri(data)] <- 1\n\ndata\n#> A B C D E\n#> A 0 1 1 1 1\n#> B 0 0 1 1 1\n#> C 0 0 0 1 1\n#> D 0 0 0 0 1\n#> E 0 0 0 0 0\n\nnetwork <- graph_from_adjacency_matrix(data, mode = 'upper')\n\nplot(network)\n ggraph library(ggraph)\n\nggraph(network) +\n geom_edge_link(aes(label = paste0('a', 1:10)), angle_calc = 'along',\n vjust = -0.5, label_colour = 'red') +\n geom_node_circle(aes(r = 0.1), fill = \"#dbdccf\") +\n geom_node_text(aes(label = name), color = 'blue4', fontface = 2,\n size = 8) +\n coord_equal() +\n theme_graph() +\n theme(plot.background = element_rect(color = NA, fill = \"#f5f6e9\"),\n panel.grid.major.y = element_line(size = 0.5, color = 'gray90'),\n panel.grid.minor.y = element_line(size = 0.5, color = 'gray90'))\n" }, { "answer_id": 74642830, "author": "Yacine Hajji", "author_id": 17049772, "author_profile": "https://Stackoverflow.com/users/17049772", "pm_score": 1, "selected": false, "text": "data <- matrix(c(0,1,1,1,1,\n 1,0,1,1,1,\n 1,1,0,1,1,\n 1,1,1,0,1,\n 1,1,1,1,0), nrow=5, ncol=5)\n mode='undirected' network <- graph_from_adjacency_matrix(data, mode='undirected')\nplot(network)\n" }, { "answer_id": 74643114, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 2, "selected": false, "text": "make_full_graph igraph n <- 5\nmake_full_graph(n) %>%\n set_vertex_attr(name = \"name\", value = head(LETTERS, n)) %>%\n plot()\n n <- 5\n`dimnames<-`(1 - diag(n), rep(list(head(LETTERS, n)), 2)) %>%\n graph_from_adjacency_matrix(\"undirected\") %>%\n plot()\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16346449/" ]
74,642,735
<p>I have a data like below:</p> <pre><code>data = &quot;&quot;&quot;1000 2000 3000 4000 5000 6000 7000 8000 9000 10000&quot;&quot;&quot; </code></pre> <p>Now, I want to sum up the elements that appear before the space and maintain the <code>max_sum</code> track with the sum of the next elements that appear before the empty line. So for me, it should be the sum of <code>1000,2000,3000 = 6000</code> compared with the initial max_sum for eg <code>0</code>, and now sum the next element i.e <code>4000</code>, and keep comparing with the max_sum which could be like <code>max(6000, 4000) = 6000</code> and keep on doing the same but need to reset the sum if I encounter a empty line.</p> <p>Below is my code:</p> <pre><code>max_num = 0 sum = 0 for line in data: # print(line) sum = sum + int(line) if line in ['\n', '\r\n']: sum=0 max_num = max(max_num, sum) </code></pre> <p>This gives an error:</p> <pre><code>sum = sum + int(line) ValueError: invalid literal for int() with base 10: '\n' </code></pre>
[ { "answer_id": 74642851, "author": "rtoth", "author_id": 20589189, "author_profile": "https://Stackoverflow.com/users/20589189", "pm_score": 2, "selected": false, "text": "max_num = 0\nsum = 0\nfor line in data:\n print(line)\n if line.strip():\n sum = sum + int(line)\n if line in ['\\n', '\\r\\n']:\n sum=0\n max_num = max(max_num, sum)\n" }, { "answer_id": 74642867, "author": "Loïc Robert", "author_id": 19033618, "author_profile": "https://Stackoverflow.com/users/19033618", "pm_score": 1, "selected": false, "text": "int continue" }, { "answer_id": 74642876, "author": "alex", "author_id": 1185254, "author_profile": "https://Stackoverflow.com/users/1185254", "pm_score": 2, "selected": false, "text": "data = \"\"\"1000\n2000\n3000\n\n4000\n\n5000\n6000\n\n7000\n8000\n9000\n\n10000\"\"\"\n\nmax(\n sum(\n int(i) for i in l.split('\\n')\n ) for l in data.split('\\n\\n')\n)\n 24000 \\n\\n \\n" }, { "answer_id": 74642899, "author": "Usman Arshad", "author_id": 20582506, "author_profile": "https://Stackoverflow.com/users/20582506", "pm_score": 1, "selected": false, "text": "sum \\n strip() max_num = 0\nsum_val = 0\n\n\nfor line in data.split(\"\\n\"):\n line = line.strip()\n sum_val = int(line) + sum_val if line and line.isdigit() else 0\n max_num = max(max_num, sum_val)\nprint(max_num)\n" }, { "answer_id": 74642922, "author": "Harsha Biyani", "author_id": 3457761, "author_profile": "https://Stackoverflow.com/users/3457761", "pm_score": 1, "selected": false, "text": "data = \"\"\"1000\n 2000\n 3000\n \n 4000\n \n 5000\n 6000\n \n 7000\n 8000\n 9000\n \n 10000\n \"\"\"\n\ndata = data.splitlines()\n\nmax_sum = 0\ngroup = []\n\nfor data_index, single_data in enumerate(data):\n single_data = single_data.replace(\" \",\"\")\n if single_data == \"\":\n if max_sum < sum(group):\n max_sum = sum(group)\n group = []\n else:\n group.append(int(single_data))\n\nprint(max_sum)\n 24000\n" }, { "answer_id": 74643006, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 2, "selected": true, "text": "data = \"\"\"1000\n2000\n3000\n\n4000\n\n5000\n6000\n\n7000\n8000\n9000\n\n10000\"\"\"\n\ncurrent_sum = 0\nmax_sum = float('-inf')\n\nfor t in data.splitlines():\n try:\n x = int(t)\n current_sum += x\n except ValueError:\n max_sum = max(max_sum, current_sum)\n current_sum = 0\n\nprint(f'Max sum = {max(max_sum, current_sum)}')\n Max sum = 24000\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9363181/" ]
74,642,771
<p>I want to do a to do list app. I use Sqflite in my project.</p> <h1>Widget</h1> <p>`</p> <pre><code> return FutureBuilder( future: databaseTrans.getTables(), builder: (context, snapshot) { if (snapshot.data == null) { return taskBookErrorWidget(context); } else { return GridView.count( crossAxisCount: 3, children: List.generate(snapshot.data!.length, (i) { return InkWell( onTap: () {}, child: Container( width: 300, height: 300, margin: EdgeInsets.all(10), alignment: Alignment.center, decoration: BoxDecoration( color: Colors.white10, borderRadius: BorderRadius.circular(30), ), child: Text( snapshot.data![i].name.toString(), style: TextStyle(color: Colors.white)), ), ); }), ); } }, ); } </code></pre> <p>`</p> <h1>Errors</h1> <p>`</p> <pre><code>The following _CastError was thrown building FutureBuilder&lt;List&lt;taskBooksDataModel&gt;&gt;(state: _FutureBuilderState&lt;List&lt;taskBooksDataModel&gt;&gt;#da7bd): Null check operator used on a null value The relevant error-causing widget was: FutureBuilder&lt;List&lt;taskBooksDataModel&gt;&gt; FutureBuilder:file:///C:/Users/Administrator/Desktop/todolist/lib/screens/taskBooksScreen/taskBookWidget.dart:16:12 When the exception was thrown, this was the stack: #0 _SnackBarState.initState (package:flutter/src/material/snack_bar.dart:391:21) #1 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:5015:57) #2 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4853:5) #3 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3863:16) #4 Element.updateChild (package:flutter/src/widgets/framework.dart:3586:20) #5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4904:16) </code></pre> <p>`</p> <h1>Database Function</h1> <p>`</p> <pre><code>Future&lt;List&lt;taskBooksDataModel&gt;&gt; getTables() async { Database db = await database; var result = await db.query(&quot;sqlite_master&quot;); return taskBooksDataModel.convertToTaskBookDataModel(result); } </code></pre> <p>`</p> <p>What should i do ? I want to read datas from table and write them into Text() on FutureBuilder. I have two tables. One of them includes task books' names.</p>
[ { "answer_id": 74642851, "author": "rtoth", "author_id": 20589189, "author_profile": "https://Stackoverflow.com/users/20589189", "pm_score": 2, "selected": false, "text": "max_num = 0\nsum = 0\nfor line in data:\n print(line)\n if line.strip():\n sum = sum + int(line)\n if line in ['\\n', '\\r\\n']:\n sum=0\n max_num = max(max_num, sum)\n" }, { "answer_id": 74642867, "author": "Loïc Robert", "author_id": 19033618, "author_profile": "https://Stackoverflow.com/users/19033618", "pm_score": 1, "selected": false, "text": "int continue" }, { "answer_id": 74642876, "author": "alex", "author_id": 1185254, "author_profile": "https://Stackoverflow.com/users/1185254", "pm_score": 2, "selected": false, "text": "data = \"\"\"1000\n2000\n3000\n\n4000\n\n5000\n6000\n\n7000\n8000\n9000\n\n10000\"\"\"\n\nmax(\n sum(\n int(i) for i in l.split('\\n')\n ) for l in data.split('\\n\\n')\n)\n 24000 \\n\\n \\n" }, { "answer_id": 74642899, "author": "Usman Arshad", "author_id": 20582506, "author_profile": "https://Stackoverflow.com/users/20582506", "pm_score": 1, "selected": false, "text": "sum \\n strip() max_num = 0\nsum_val = 0\n\n\nfor line in data.split(\"\\n\"):\n line = line.strip()\n sum_val = int(line) + sum_val if line and line.isdigit() else 0\n max_num = max(max_num, sum_val)\nprint(max_num)\n" }, { "answer_id": 74642922, "author": "Harsha Biyani", "author_id": 3457761, "author_profile": "https://Stackoverflow.com/users/3457761", "pm_score": 1, "selected": false, "text": "data = \"\"\"1000\n 2000\n 3000\n \n 4000\n \n 5000\n 6000\n \n 7000\n 8000\n 9000\n \n 10000\n \"\"\"\n\ndata = data.splitlines()\n\nmax_sum = 0\ngroup = []\n\nfor data_index, single_data in enumerate(data):\n single_data = single_data.replace(\" \",\"\")\n if single_data == \"\":\n if max_sum < sum(group):\n max_sum = sum(group)\n group = []\n else:\n group.append(int(single_data))\n\nprint(max_sum)\n 24000\n" }, { "answer_id": 74643006, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 2, "selected": true, "text": "data = \"\"\"1000\n2000\n3000\n\n4000\n\n5000\n6000\n\n7000\n8000\n9000\n\n10000\"\"\"\n\ncurrent_sum = 0\nmax_sum = float('-inf')\n\nfor t in data.splitlines():\n try:\n x = int(t)\n current_sum += x\n except ValueError:\n max_sum = max(max_sum, current_sum)\n current_sum = 0\n\nprint(f'Max sum = {max(max_sum, current_sum)}')\n Max sum = 24000\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20503448/" ]
74,642,802
<p>I wrote the script below to batch rename files with powershell. It is intended to remove dots (.) and every (-) that is followed by a number from the filenames. Example: text.10-1 becomes text101. However, I feel like there must be a way to do this in a line of code. Also, I wanted it to also enter a subdirectory and do it, how do I write it?</p> <pre><code>Get-ChildItem | ForEach{ $_ | Rename-Item -NewName &quot;$($_.BaseName.Replace(&quot;.&quot;,'')+$_.Extension)&quot; } Get-ChildItem | ForEach{ $_ | Rename-Item -NewName &quot;$($_.BaseName.Replace(&quot;-1&quot;,'1')+$_.Extension)&quot; } Get-ChildItem | ForEach{ $_ | Rename-Item -NewName &quot;$($_.BaseName.Replace(&quot;-0&quot;,'0')+$_.Extension)&quot; } Get-ChildItem | ForEach{ $_ | Rename-Item -NewName &quot;$($_.BaseName.Replace(&quot;-2&quot;,'2')+$_.Extension)&quot; } Get-ChildItem | ForEach{ $_ | Rename-Item -NewName &quot;$($_.BaseName.Replace(&quot;-3&quot;,'3')+$_.Extension)&quot; } Get-ChildItem | ForEach{ $_ | Rename-Item -NewName &quot;$($_.BaseName.Replace(&quot;-4&quot;,'4')+$_.Extension)&quot; } Get-ChildItem | ForEach{ $_ | Rename-Item -NewName &quot;$($_.BaseName.Replace(&quot;-5&quot;,'5')+$_.Extension)&quot; } Get-ChildItem | ForEach{ $_ | Rename-Item -NewName &quot;$($_.BaseName.Replace(&quot;-6&quot;,'6')+$_.Extension)&quot; } Get-ChildItem | ForEach{ $_ | Rename-Item -NewName &quot;$($_.BaseName.Replace(&quot;-7&quot;,'7')+$_.Extension)&quot; } Get-ChildItem | ForEach{ $_ | Rename-Item -NewName &quot;$($_.BaseName.Replace(&quot;-8&quot;,'8')+$_.Extension)&quot; } Get-ChildItem | ForEach{ $_ | Rename-Item -NewName &quot;$($_.BaseName.Replace(&quot;-9&quot;,'9')+$_.Extension)&quot; } </code></pre> <p>Thanks</p>
[ { "answer_id": 74642851, "author": "rtoth", "author_id": 20589189, "author_profile": "https://Stackoverflow.com/users/20589189", "pm_score": 2, "selected": false, "text": "max_num = 0\nsum = 0\nfor line in data:\n print(line)\n if line.strip():\n sum = sum + int(line)\n if line in ['\\n', '\\r\\n']:\n sum=0\n max_num = max(max_num, sum)\n" }, { "answer_id": 74642867, "author": "Loïc Robert", "author_id": 19033618, "author_profile": "https://Stackoverflow.com/users/19033618", "pm_score": 1, "selected": false, "text": "int continue" }, { "answer_id": 74642876, "author": "alex", "author_id": 1185254, "author_profile": "https://Stackoverflow.com/users/1185254", "pm_score": 2, "selected": false, "text": "data = \"\"\"1000\n2000\n3000\n\n4000\n\n5000\n6000\n\n7000\n8000\n9000\n\n10000\"\"\"\n\nmax(\n sum(\n int(i) for i in l.split('\\n')\n ) for l in data.split('\\n\\n')\n)\n 24000 \\n\\n \\n" }, { "answer_id": 74642899, "author": "Usman Arshad", "author_id": 20582506, "author_profile": "https://Stackoverflow.com/users/20582506", "pm_score": 1, "selected": false, "text": "sum \\n strip() max_num = 0\nsum_val = 0\n\n\nfor line in data.split(\"\\n\"):\n line = line.strip()\n sum_val = int(line) + sum_val if line and line.isdigit() else 0\n max_num = max(max_num, sum_val)\nprint(max_num)\n" }, { "answer_id": 74642922, "author": "Harsha Biyani", "author_id": 3457761, "author_profile": "https://Stackoverflow.com/users/3457761", "pm_score": 1, "selected": false, "text": "data = \"\"\"1000\n 2000\n 3000\n \n 4000\n \n 5000\n 6000\n \n 7000\n 8000\n 9000\n \n 10000\n \"\"\"\n\ndata = data.splitlines()\n\nmax_sum = 0\ngroup = []\n\nfor data_index, single_data in enumerate(data):\n single_data = single_data.replace(\" \",\"\")\n if single_data == \"\":\n if max_sum < sum(group):\n max_sum = sum(group)\n group = []\n else:\n group.append(int(single_data))\n\nprint(max_sum)\n 24000\n" }, { "answer_id": 74643006, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 2, "selected": true, "text": "data = \"\"\"1000\n2000\n3000\n\n4000\n\n5000\n6000\n\n7000\n8000\n9000\n\n10000\"\"\"\n\ncurrent_sum = 0\nmax_sum = float('-inf')\n\nfor t in data.splitlines():\n try:\n x = int(t)\n current_sum += x\n except ValueError:\n max_sum = max(max_sum, current_sum)\n current_sum = 0\n\nprint(f'Max sum = {max(max_sum, current_sum)}')\n Max sum = 24000\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11909247/" ]
74,642,826
<p>at my company, my teammate said that&quot;in Flutter, static usage is very harmful for memory. You shouldn't use static variables too much.&quot;</p> <p>After that, I have searched the internet, but I couldn't find satisfaction answer. So, I just wonder that if I use static value like at the below code lines, will it increase memory usage or reduce performance? Many thanks.</p> <pre><code>class { static final String name=&quot;asd&quot;; static final String surname=&quot;ajskandkanjsd&quot;; static final Int age=123; static final isStudent=false; static final String email=&quot;asked@gmail.com&quot;; static final Int password=1231234; } </code></pre>
[ { "answer_id": 74651132, "author": "jamesdlin", "author_id": 179715, "author_profile": "https://Stackoverflow.com/users/179715", "pm_score": 2, "selected": true, "text": "static static static static static static" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18849295/" ]
74,642,835
<p>Given a 2d matrix, I have a start cell, end cell, cells that must be visited and cells that cannot be visited.</p> <p>What would be the optimal way to find a path that:</p> <ul> <li>starts at the start cell</li> <li>ends at the end cell</li> <li>passes through all must visit cell</li> <li>does not pass through any cell that cannot be visited</li> <li>does not pass any cell twice</li> <li>we can only move left, right, up and down</li> </ul> <p>The matrix size can be at most 10x10.</p> <p>For example:</p> <pre><code>S - start E - end 0 - can visit X - can not visit M - must visit S 0 0 M 0 0 0 0 X 0 0 M 0 0 0 0 X 0 0 0 0 0 0 0 E One solution would be: * 0 * * * * 0 * X * * * * 0 * 0 X 0 0 * 0 0 0 0 * </code></pre> <p>The path doesn't necessarily should be the shortest one, but it would be nice if it can be, and it can be calculated quiet fast.</p>
[ { "answer_id": 74653968, "author": "Maurice Perry", "author_id": 7036419, "author_profile": "https://Stackoverflow.com/users/7036419", "pm_score": 2, "selected": true, "text": "Grid width height must mustNot public class Grid {\n private final int width;\n private final int height;\n private final Set<Location> must = new HashSet<>();\n private final Set<Location> mustNot = new HashSet<>();\n\n public Grid(int width, int height,\n Collection<Location> must, Collection<Location> mustNot) {\n this.width = width;\n this.height = height;\n this.must.addAll(must);\n this.mustNot.addAll(mustNot);\n }\n solve start end public PathNode solve(Location start, Location end) {\n ...\n}\n Location public class Location {\n public final int row;\n public final int col;\n\n public Location(int row, int col) {\n this.row = row;\n this.col = col;\n }\n\n @Override\n public int hashCode() {\n int hash = 7;\n hash = 41 * hash + this.row;\n hash = 41 * hash + this.col;\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Location other = (Location) obj;\n if (this.row != other.row) {\n return false;\n }\n return this.col == other.col;\n }\n\n @Override\n public String toString() {\n return \"(\" + row + \", \" + col + ')';\n }\n}\n row col PathNode public class PathNode {\n public final Location loc;\n public final PathNode link;\n\n public PathNode(Location loc, PathNode link) {\n this.loc = loc;\n this.link = link;\n }\n\n public boolean contains(Location loc) {\n PathNode n = this;\n while (n != null) {\n if (n.loc.equals(loc)) {\n return true;\n }\n n = n.link;\n }\n return false;\n }\n}\n contains public PathNode solve(Location start, Location end) {\n List<PathNode> paths = new ArrayList<>();\n if (validLoc(start.row, start.col) == null) {\n return null;\n }\n paths.add(new PathNode(start, null));\n for (int i = 0; i < paths.size(); ++i) {\n PathNode path = paths.get(i);\n Location loc = path.loc;\n if (loc.equals(end)) {\n // at the end point, we must still check the path goes through\n // all the 'must' cells\n if (allMustInPath(path)) {\n // found a path\n return path;\n }\n } else {\n addToPaths(path, left(loc), paths);\n addToPaths(path, right(loc), paths);\n addToPaths(path, up(loc), paths);\n addToPaths(path, down(loc), paths);\n }\n }\n return null;\n}\n private Location left(Location loc) {\n return validLoc(loc.row, loc.col-1);\n}\n\nprivate Location right(Location loc) {\n return validLoc(loc.row, loc.col+1);\n}\n\nprivate Location up(Location loc) {\n return validLoc(loc.row-1, loc.col);\n}\n\nprivate Location down(Location loc) {\n return validLoc(loc.row+1, loc.col);\n}\n\nprivate Location validLoc(int row, int col) {\n if (row >= 0 && row < height && col >= 0 && col < width) {\n Location loc = new Location(row, col);\n return mustNot.contains(loc) ? null : loc;\n }\n return null;\n}\n\nprivate boolean allMustInPath(PathNode path) {\n for (Location loc: must) {\n if (!path.contains(loc)) {\n return false;\n }\n }\n return true;\n}\n\nprivate void addToPaths(PathNode path, Location loc, List<PathNode> paths) {\n if (loc == null) {\n return;\n }\n loc = validLoc(loc.row, loc.col);\n if (loc != null && !path.contains(loc)) {\n paths.add(new PathNode(loc, path));\n }\n}\n solve Grid grid = new Grid(5,5,\n Arrays.asList(\n new Location(0,3),\n new Location(2,1)),\n Arrays.asList(\n new Location(1,3),\n new Location(3,1)));\n PathNode path = grid.solve(\n new Location(0,0),\n new Location(4,4));\n if (path == null) {\n System.out.println(\"No solution found\");\n }\n while (path != null) {\n System.out.println(path.loc);\n path = path.link;\n }\n\n\n(4, 4)\n(3, 4)\n(2, 4)\n(1, 4)\n(0, 4)\n(0, 3)\n(0, 2)\n(1, 2)\n(2, 2)\n(2, 1)\n(1, 1)\n(0, 1)\n(0, 0)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/333918/" ]
74,642,845
<p>Ich have a specific code for Outlook that I would like to convert into late binding. However I am comparing some types, so I don't know how to make that comparison without having the dll loaded already.</p> <pre><code>var ol = (dynamic)Marshal.GetActiveObject(&quot;Outlook.Application&quot;); dynamic windowType = ol.Application.ActiveWindow(); if (windowType is Microsoft.Office.Interop.Outlook.Explorer) { Console.WriteLine(&quot;success&quot;) } </code></pre> <p>I am not able to compile the code if I have not loaded the interop dll for Outlook. So I will have to add</p> <pre><code>using Microsoft.Office.Interop.Outlook </code></pre> <p>Which I do not want to use because I won't know exactly what outlook version will be installed on the machine. This is also the reason why I would want to use late Binding.</p> <p>I tried to get the type with</p> <pre><code>Console.WriteLine($&quot;This is my type {windowType.GetType()}&quot;); </code></pre> <p>But I would only get the result</p> <pre><code>This is my type System.__ComObject </code></pre> <p>Any Ideas how I can late bind outlook and still make type comparisons? Can specific types be loaded for comparison?</p>
[ { "answer_id": 74653968, "author": "Maurice Perry", "author_id": 7036419, "author_profile": "https://Stackoverflow.com/users/7036419", "pm_score": 2, "selected": true, "text": "Grid width height must mustNot public class Grid {\n private final int width;\n private final int height;\n private final Set<Location> must = new HashSet<>();\n private final Set<Location> mustNot = new HashSet<>();\n\n public Grid(int width, int height,\n Collection<Location> must, Collection<Location> mustNot) {\n this.width = width;\n this.height = height;\n this.must.addAll(must);\n this.mustNot.addAll(mustNot);\n }\n solve start end public PathNode solve(Location start, Location end) {\n ...\n}\n Location public class Location {\n public final int row;\n public final int col;\n\n public Location(int row, int col) {\n this.row = row;\n this.col = col;\n }\n\n @Override\n public int hashCode() {\n int hash = 7;\n hash = 41 * hash + this.row;\n hash = 41 * hash + this.col;\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Location other = (Location) obj;\n if (this.row != other.row) {\n return false;\n }\n return this.col == other.col;\n }\n\n @Override\n public String toString() {\n return \"(\" + row + \", \" + col + ')';\n }\n}\n row col PathNode public class PathNode {\n public final Location loc;\n public final PathNode link;\n\n public PathNode(Location loc, PathNode link) {\n this.loc = loc;\n this.link = link;\n }\n\n public boolean contains(Location loc) {\n PathNode n = this;\n while (n != null) {\n if (n.loc.equals(loc)) {\n return true;\n }\n n = n.link;\n }\n return false;\n }\n}\n contains public PathNode solve(Location start, Location end) {\n List<PathNode> paths = new ArrayList<>();\n if (validLoc(start.row, start.col) == null) {\n return null;\n }\n paths.add(new PathNode(start, null));\n for (int i = 0; i < paths.size(); ++i) {\n PathNode path = paths.get(i);\n Location loc = path.loc;\n if (loc.equals(end)) {\n // at the end point, we must still check the path goes through\n // all the 'must' cells\n if (allMustInPath(path)) {\n // found a path\n return path;\n }\n } else {\n addToPaths(path, left(loc), paths);\n addToPaths(path, right(loc), paths);\n addToPaths(path, up(loc), paths);\n addToPaths(path, down(loc), paths);\n }\n }\n return null;\n}\n private Location left(Location loc) {\n return validLoc(loc.row, loc.col-1);\n}\n\nprivate Location right(Location loc) {\n return validLoc(loc.row, loc.col+1);\n}\n\nprivate Location up(Location loc) {\n return validLoc(loc.row-1, loc.col);\n}\n\nprivate Location down(Location loc) {\n return validLoc(loc.row+1, loc.col);\n}\n\nprivate Location validLoc(int row, int col) {\n if (row >= 0 && row < height && col >= 0 && col < width) {\n Location loc = new Location(row, col);\n return mustNot.contains(loc) ? null : loc;\n }\n return null;\n}\n\nprivate boolean allMustInPath(PathNode path) {\n for (Location loc: must) {\n if (!path.contains(loc)) {\n return false;\n }\n }\n return true;\n}\n\nprivate void addToPaths(PathNode path, Location loc, List<PathNode> paths) {\n if (loc == null) {\n return;\n }\n loc = validLoc(loc.row, loc.col);\n if (loc != null && !path.contains(loc)) {\n paths.add(new PathNode(loc, path));\n }\n}\n solve Grid grid = new Grid(5,5,\n Arrays.asList(\n new Location(0,3),\n new Location(2,1)),\n Arrays.asList(\n new Location(1,3),\n new Location(3,1)));\n PathNode path = grid.solve(\n new Location(0,0),\n new Location(4,4));\n if (path == null) {\n System.out.println(\"No solution found\");\n }\n while (path != null) {\n System.out.println(path.loc);\n path = path.link;\n }\n\n\n(4, 4)\n(3, 4)\n(2, 4)\n(1, 4)\n(0, 4)\n(0, 3)\n(0, 2)\n(1, 2)\n(2, 2)\n(2, 1)\n(1, 1)\n(0, 1)\n(0, 0)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1551974/" ]
74,642,853
<pre><code>Unable to get Xcode project information: 2022-12-01 13:57:05.376 xcodebuild[71564:226197] Writing error result bundle to /var/folders/6g/w7cqd0s54c33_20mrl4v2q640000gn/T/ResultBundle_2022-01-12_13-57-0005.xcresult xcodebuild: error: Unable to read project 'Runner.xcodeproj'. Reason: Project /Users/noel/Treegar/treegar-app/ios/Runner.xcodeproj cannot be opened because it is missing its project.pbxproj file. </code></pre> <p>i keep getting this error when ever i run flutter run or flutter build ios.</p> <p>i dont know what to do... it works fine on android but not on ios.</p> <p>ive updated xcode and flutter same problem</p> <p><a href="https://i.stack.imgur.com/J3oyD.png" rel="nofollow noreferrer">flutter doctor -v</a></p> <p>UPdate cocoapod to latest version update flutter update xcode</p>
[ { "answer_id": 74643657, "author": "Henadzi Rabkin", "author_id": 1470374, "author_profile": "https://Stackoverflow.com/users/1470374", "pm_score": 1, "selected": false, "text": "flutter create" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17091972/" ]
74,642,932
<p>im trying to get files in different folders and get some cell values from them and put it in a sheet. but i get below error</p> <p>Exception: Cannot retrieve the next object: iterator has reached the end</p> <p>im using below code and when i run it. it returns error on line 14 it seems code returns some values from first and second folders but for third one it returns error</p> <p>after running macro it gives log below:</p> <pre><code>5:24:43 PM Notice Execution started 5:24:45 PM Info [[]] 5:24:45 PM Info [[]] 5:24:46 PM Error Exception: Cannot retrieve the next object: iterator has reached the end. list_files_in_folders @ macros.gs:14 </code></pre> <p>my code : line 14 error</p> <pre><code>function list_files_in_folders(){ var sh = SpreadsheetApp.getActiveSheet(); var mainfolder = DriveApp.getFolderById('id-here'); // I change the folder ID here var mfolders = mainfolder.getFolders(); var data = []; data.push(['Person Name','File Name','Value 1','Value 2']); while (mfolders.hasNext){ var mfolder = mfolders.next(); var personfolder = DriveApp.getFolderById(mfolder.getId()); var pfiles = personfolder.getFiles(); data.push([personfolder.getName,,,]); while(pfiles.hasNext){ var pfile = pfiles.next(); //error here var personfile = SpreadsheetApp.openById(pfile.getId()); var value1 = personfile.getSheetValues(2,9,1,1); //var value2 = personfile.getSheetValues(); Logger.log(value1); data.push([&quot;&quot;,pfile.getName,value1,&quot;&quot;]); } } sh.getRange(1,1,data.length,data[0].length).setValues(data); } </code></pre>
[ { "answer_id": 74644485, "author": "TheWizEd", "author_id": 3656739, "author_profile": "https://Stackoverflow.com/users/3656739", "pm_score": 1, "selected": false, "text": "mfolders.hasNext\n\npfiles.hasNext\n mfolders.hasNext()\n\npfiles.hasNext()\n" }, { "answer_id": 74648987, "author": "doubleunary", "author_id": 13045193, "author_profile": "https://Stackoverflow.com/users/13045193", "pm_score": 0, "selected": false, "text": "list_files_in_folders() _fileAction _folderAction /** @NotOnlyCurrentDoc */\n'use strict';\n\nfunction list_files_in_folders() {\n const mainFolder = DriveApp.getFolderById('...put folder ID here...');\n const data = generateReport_(mainFolder);\n SpreadsheetApp.getActiveSheet().getRange('A1')\n .offset(0, 0, data.length, data[0].length)\n .setValues(data);\n}\n\n/**\n* Generates a report based on spreadsheets organized by subfolder.\n*\n* @param {DriveApp.Folder} folder A folder with files and subfolders.\n* @return {String[][]} A 2D array that contains a report of files organized by subfolder.\n*/\nfunction generateReport_(folder) {\n const data = [];\n const _errorHandler = (error) => console.log(error.message);\n const _prefix = (folderName, nestingLevel) => ' '.repeat(nestingLevel) + folderName;\n const _folderAction = (folder, nestingLevel) => {\n data.push([_prefix(folder.getName(), nestingLevel), '', '', '']);\n };\n const _fileAction = (file) => {\n const ss = getSpreadsheetFromFile_(file, _errorHandler);\n if (ss) {\n data.push(['', ss.getName(), ss.getSheetValues(2, 9, 1, 1), '']);\n } else {\n data.push(['', file.getName(), '(not a Google Sheet)', '']);\n }\n };\n const timelimit = new Date().getTime() + 4 * 60 * 1000; // stop when 4 minutes have passed\n const error = processFilesInFolderRecursively_(folder, _folderAction, _fileAction, _errorHandler, 1, timelimit);\n if (error) {\n data.push([error.message, '', '', '']);\n _errorHandler(error);\n }\n return [['Person Name', 'File Name', 'Value 1', 'Value 2']].concat(\n data.length ? data : [['(Could not find any files. Check folder ID.)', '', '', '']]\n );\n}\n\n/**\n* Iterates files in a folder and its subfolders, executing\n* _folderAction with each folder and _fileAction with each file.\n*\n* @param {DriveApp.Folder} folder The folder to process.\n* @param {Function} _folderAction The function to run with each folder.\n* @param {Function} _fileAction The function to run with each file.\n* @param {Function} _errorHandler The function to call when an error occurs.\n* @param {String} nestingLevel Optional. A number that indicates the current folder nesting nevel.\n* @param {Number} timelimit Optional. The moment in milliseconds that indicates when to stop processing.\n* @return {Error} An error when the function ran out of time, otherwise undefined.\n* @license https://www.gnu.org/licenses/gpl-3.0.html\n*/\nfunction processFilesInFolderRecursively_(folder, _folderAction, _fileAction, _errorHandler, nestingLevel, timelimit) {\n // version 1.2, written by --Hyde, 1 December 2022\n nestingLevel = nestingLevel || 0;\n const outOfTime = new Error('Ran out of time.');\n if (new Date().getTime() > timelimit) {\n return outOfTime;\n }\n const files = folder.getFiles();\n while (files.hasNext()) {\n if (new Date().getTime() > timelimit) {\n return outOfTime;\n }\n try {\n _fileAction(files.next());\n } catch (error) {\n _errorHandler(error);\n }\n }\n const subfolders = folder.getFolders();\n while (subfolders.hasNext()) {\n const folder = subfolders.next();\n _folderAction(folder, nestingLevel);\n const error = processFilesInFolderRecursively_(folder, _folderAction, _fileAction, _errorHandler, nestingLevel + 1, timelimit);\n if (error) {\n return error; // outOfTime\n };\n }\n}\n\n/**\n* Gets a spreadsheet object from a file object.\n*\n* @param {DriveApp.File} file The file that contains a spreadsheet.\n* @param {Function} _errorHandler The function to call when an error occurs.\n* @return {SpreadsheetApp.Spreadsheet} The spreadsheet object, or null if file is not a spreadsheet or cannot be accessed.\n* @license https://www.gnu.org/licenses/gpl-3.0.html\n*/\nfunction getSpreadsheetFromFile_(file, _errorHandler) {\n // version 1.0, written by --Hyde, 9 October 2022\n if (file.getMimeType() !== 'application/vnd.google-apps.spreadsheet') {\n return null;\n }\n let ss;\n try {\n ss = SpreadsheetApp.open(file);\n } catch (error) {\n _errorHandler(error);\n return null;\n }\n return ss;\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9075702/" ]
74,642,935
<p>I have the following xsd schema:</p> <pre><code>&lt;Person&gt; &lt;Gender&gt; &lt;Any&gt; </code></pre> <p>I have the following xml:</p> <pre><code>&lt;Person&gt; &lt;Gender&gt;Male&lt;/Gender&gt; &lt;Name&gt; &lt;firstName&gt;Elon&lt;/firstName&gt; &lt;lastName&gt;Musk&lt;/lastName&gt; &lt;/Name&gt; &lt;/Person&gt; </code></pre> <p>I want to print the the text &quot;Tesla&quot; if the lastname is equal to &quot;Musk&quot;.<br /> I started with a template-match but I cannot access the Any-element.</p> <p>Any good suggestions on how to access an -element in xslt?</p> <p>I tried writing an template-match for this but I was not able to access the Any-element as expected.</p> <pre><code>&lt;xsl:template match=&quot;/Person//* = 'Musk'&quot;&gt; &lt;text&gt;Tesla&lt;/text&gt; &lt;/xsl:template&gt; </code></pre>
[ { "answer_id": 74644485, "author": "TheWizEd", "author_id": 3656739, "author_profile": "https://Stackoverflow.com/users/3656739", "pm_score": 1, "selected": false, "text": "mfolders.hasNext\n\npfiles.hasNext\n mfolders.hasNext()\n\npfiles.hasNext()\n" }, { "answer_id": 74648987, "author": "doubleunary", "author_id": 13045193, "author_profile": "https://Stackoverflow.com/users/13045193", "pm_score": 0, "selected": false, "text": "list_files_in_folders() _fileAction _folderAction /** @NotOnlyCurrentDoc */\n'use strict';\n\nfunction list_files_in_folders() {\n const mainFolder = DriveApp.getFolderById('...put folder ID here...');\n const data = generateReport_(mainFolder);\n SpreadsheetApp.getActiveSheet().getRange('A1')\n .offset(0, 0, data.length, data[0].length)\n .setValues(data);\n}\n\n/**\n* Generates a report based on spreadsheets organized by subfolder.\n*\n* @param {DriveApp.Folder} folder A folder with files and subfolders.\n* @return {String[][]} A 2D array that contains a report of files organized by subfolder.\n*/\nfunction generateReport_(folder) {\n const data = [];\n const _errorHandler = (error) => console.log(error.message);\n const _prefix = (folderName, nestingLevel) => ' '.repeat(nestingLevel) + folderName;\n const _folderAction = (folder, nestingLevel) => {\n data.push([_prefix(folder.getName(), nestingLevel), '', '', '']);\n };\n const _fileAction = (file) => {\n const ss = getSpreadsheetFromFile_(file, _errorHandler);\n if (ss) {\n data.push(['', ss.getName(), ss.getSheetValues(2, 9, 1, 1), '']);\n } else {\n data.push(['', file.getName(), '(not a Google Sheet)', '']);\n }\n };\n const timelimit = new Date().getTime() + 4 * 60 * 1000; // stop when 4 minutes have passed\n const error = processFilesInFolderRecursively_(folder, _folderAction, _fileAction, _errorHandler, 1, timelimit);\n if (error) {\n data.push([error.message, '', '', '']);\n _errorHandler(error);\n }\n return [['Person Name', 'File Name', 'Value 1', 'Value 2']].concat(\n data.length ? data : [['(Could not find any files. Check folder ID.)', '', '', '']]\n );\n}\n\n/**\n* Iterates files in a folder and its subfolders, executing\n* _folderAction with each folder and _fileAction with each file.\n*\n* @param {DriveApp.Folder} folder The folder to process.\n* @param {Function} _folderAction The function to run with each folder.\n* @param {Function} _fileAction The function to run with each file.\n* @param {Function} _errorHandler The function to call when an error occurs.\n* @param {String} nestingLevel Optional. A number that indicates the current folder nesting nevel.\n* @param {Number} timelimit Optional. The moment in milliseconds that indicates when to stop processing.\n* @return {Error} An error when the function ran out of time, otherwise undefined.\n* @license https://www.gnu.org/licenses/gpl-3.0.html\n*/\nfunction processFilesInFolderRecursively_(folder, _folderAction, _fileAction, _errorHandler, nestingLevel, timelimit) {\n // version 1.2, written by --Hyde, 1 December 2022\n nestingLevel = nestingLevel || 0;\n const outOfTime = new Error('Ran out of time.');\n if (new Date().getTime() > timelimit) {\n return outOfTime;\n }\n const files = folder.getFiles();\n while (files.hasNext()) {\n if (new Date().getTime() > timelimit) {\n return outOfTime;\n }\n try {\n _fileAction(files.next());\n } catch (error) {\n _errorHandler(error);\n }\n }\n const subfolders = folder.getFolders();\n while (subfolders.hasNext()) {\n const folder = subfolders.next();\n _folderAction(folder, nestingLevel);\n const error = processFilesInFolderRecursively_(folder, _folderAction, _fileAction, _errorHandler, nestingLevel + 1, timelimit);\n if (error) {\n return error; // outOfTime\n };\n }\n}\n\n/**\n* Gets a spreadsheet object from a file object.\n*\n* @param {DriveApp.File} file The file that contains a spreadsheet.\n* @param {Function} _errorHandler The function to call when an error occurs.\n* @return {SpreadsheetApp.Spreadsheet} The spreadsheet object, or null if file is not a spreadsheet or cannot be accessed.\n* @license https://www.gnu.org/licenses/gpl-3.0.html\n*/\nfunction getSpreadsheetFromFile_(file, _errorHandler) {\n // version 1.0, written by --Hyde, 9 October 2022\n if (file.getMimeType() !== 'application/vnd.google-apps.spreadsheet') {\n return null;\n }\n let ss;\n try {\n ss = SpreadsheetApp.open(file);\n } catch (error) {\n _errorHandler(error);\n return null;\n }\n return ss;\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14436400/" ]
74,642,954
<p>I am analysing some data with a binomial distribution. We have 2 possible choices for a stimulus, and patients (female and male) have to decide whether they feel pain (1) or not (0).</p> <p>I would like to plot a bargraph showing the number of patients who choose 0 or 1, in a rotated way.</p> <p>An idea of the graph I am looking for is the following, from Sevarika et al, 2022. <a href="https://i.stack.imgur.com/kwqgj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kwqgj.jpg" alt="enter image description here" /></a></p> <pre><code>#my data id&lt;-c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10) trt&lt;-c(&quot;C&quot;,&quot;E&quot;,&quot;C&quot;,&quot;E&quot;,&quot;C&quot;,&quot;E&quot;,&quot;C&quot;,&quot;E&quot;,&quot;C&quot;,&quot;E&quot;,&quot;C&quot;,&quot;E&quot;,&quot;C&quot;,&quot;E&quot;,&quot;C&quot;,&quot;E&quot;,&quot;C&quot;,&quot;E&quot;,&quot;E&quot;,&quot;C&quot;) response&lt;-c(0,1,0,1,0,1,1,1,0,1,0,1,0,1,1,1,0,1,0,1) sex&lt;-c(rep(&quot;male&quot;,5),rep(&quot;female&quot;,5)) data&lt;-data.frame(id,trt,response,sex) </code></pre> <p>So my objective is a flipped boxplot where females and males are separated, and the number of 1 or 0 is shown on each side of the axis. I mean, where it says control, let it say 0, where it says treatment let it say 1, and the top bar should be males and the bottom bar should be females.</p> <p>Thank you very much, best regards</p>
[ { "answer_id": 74643145, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 1, "selected": false, "text": "library(tidyverse)\n\ndata %>%\n count(response, sex) %>%\n mutate(n = ifelse(response == 0, -n, n)) %>%\n ggplot(aes(sex, n, fill = factor(response))) +\n geom_hline(yintercept = 0) +\n geom_hline(yintercept = c(-3, 3), linetype = 2, size = 0.2) +\n geom_col(position = 'identity', color = 'black', width = 0.5) +\n coord_flip() +\n scale_y_continuous(breaks = seq(-7, 7), name = 'count', limits = c(-7, 7)) +\n scale_fill_manual(values = c(\"#bebebe\", \"#2a2a2a\"), guide = 'none') +\n annotate('text', y = c(-4, 4), x = c(2.8, 2.8), vjust = 1, size = 6,\n label = c('RESPONSE = 0', 'RESPONSE = 1'), fontface = 2) +\n scale_x_discrete(expand = c(0, 1), name = NULL) +\n theme_minimal(base_size = 16) +\n theme(axis.line.x = element_line(),\n axis.ticks.x = element_line(),\n panel.grid = element_blank())\n" }, { "answer_id": 74643389, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 3, "selected": true, "text": "# compute percentages\ntab <- t(table(data$response, data$sex) * c(-1, 1))\ntab <- tab / rowSums(abs(tab)) * 100\n\n# positions of x axis labels\nlab.x <- seq(-100, 100, 25)\n# initiate new plot\nframe()\npar(mar=c(2.5, 1, 2, 1))\nplot.window(range(lab.x), c(0, 1))\n# draw x axis\naxis(1, at=lab.x, labels=abs(lab.x))\n# draw vertical lines\nabline(v=0)\nabline(v=c(-1, 1)*50, lty=2)\n# bar middle y coordinates\nbar.mid <- c(.3, .7)\n# bar height\nbar.ht <- .25\n# draw bars\nrect(c(tab), bar.mid - bar.ht/2, 0, bar.mid + bar.ht/2,\n col=rep(gray(c(.8, .2)), each=2))\nmtext(c('No pain', 'Pain'), 3, at=c(-1, 1)*40, cex=1.3, line=.5)\n# print bar labels (male, female)\ntext(min(lab.x), bar.mid, rownames(tab), adj=0)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15760316/" ]
74,642,961
<p>I'm trying to use Stripe Checkout for a subscription service.</p> <p>Using the PHP SDK</p> <pre><code>Session::create([ 'customer' =&gt; $user-&gt;stripeCustomerId, 'payment_method_types' =&gt; ['card'], 'line_items' =&gt; [[ 'price' =&gt; 'price_0MACBYAGG6RS7KP5c1fNa6v9', 'quantity' =&gt; $amount, ]], 'subscription_data' =&gt; [ 'metadata' =&gt; [ 'message' =&gt; $message, ], ], 'mode' =&gt; 'subscription', 'success_url' =&gt; UrlHelper::url('?session_id={CHECKOUT_SESSION_ID}'), 'cancel_url' =&gt; UrlHelper::url('?cancel=true'), ]); </code></pre> <p>but metadata is never attached as per the docs <a href="https://support.stripe.com/questions/using-metadata-with-checkout-sessions?locale=en-GB" rel="nofollow noreferrer">https://support.stripe.com/questions/using-metadata-with-checkout-sessions?locale=en-GB</a></p> <p>I have a single charge option that passes:</p> <pre><code>'payment_intent_data' =&gt; [ 'metadata' =&gt; [ 'message' =&gt; $message, ], ], </code></pre> <p>and that attaches perfectly. What am I missing?</p>
[ { "answer_id": 74643145, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 1, "selected": false, "text": "library(tidyverse)\n\ndata %>%\n count(response, sex) %>%\n mutate(n = ifelse(response == 0, -n, n)) %>%\n ggplot(aes(sex, n, fill = factor(response))) +\n geom_hline(yintercept = 0) +\n geom_hline(yintercept = c(-3, 3), linetype = 2, size = 0.2) +\n geom_col(position = 'identity', color = 'black', width = 0.5) +\n coord_flip() +\n scale_y_continuous(breaks = seq(-7, 7), name = 'count', limits = c(-7, 7)) +\n scale_fill_manual(values = c(\"#bebebe\", \"#2a2a2a\"), guide = 'none') +\n annotate('text', y = c(-4, 4), x = c(2.8, 2.8), vjust = 1, size = 6,\n label = c('RESPONSE = 0', 'RESPONSE = 1'), fontface = 2) +\n scale_x_discrete(expand = c(0, 1), name = NULL) +\n theme_minimal(base_size = 16) +\n theme(axis.line.x = element_line(),\n axis.ticks.x = element_line(),\n panel.grid = element_blank())\n" }, { "answer_id": 74643389, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 3, "selected": true, "text": "# compute percentages\ntab <- t(table(data$response, data$sex) * c(-1, 1))\ntab <- tab / rowSums(abs(tab)) * 100\n\n# positions of x axis labels\nlab.x <- seq(-100, 100, 25)\n# initiate new plot\nframe()\npar(mar=c(2.5, 1, 2, 1))\nplot.window(range(lab.x), c(0, 1))\n# draw x axis\naxis(1, at=lab.x, labels=abs(lab.x))\n# draw vertical lines\nabline(v=0)\nabline(v=c(-1, 1)*50, lty=2)\n# bar middle y coordinates\nbar.mid <- c(.3, .7)\n# bar height\nbar.ht <- .25\n# draw bars\nrect(c(tab), bar.mid - bar.ht/2, 0, bar.mid + bar.ht/2,\n col=rep(gray(c(.8, .2)), each=2))\nmtext(c('No pain', 'Pain'), 3, at=c(-1, 1)*40, cex=1.3, line=.5)\n# print bar labels (male, female)\ntext(min(lab.x), bar.mid, rownames(tab), adj=0)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/833709/" ]
74,642,964
<p>In my to-do app, I'm trying to set local notification at the time when dead line date for task have been came, but i can't figure out whats wrong with calendar trigger, interval trigger working ok. In function body i put default Date()</p> <pre><code> func setupNotifications(id: String, contentTitle: String, contentBody: String, date: Date) { center.getNotificationSettings { (settings) in if (settings.authorizationStatus == .authorized) { let content = UNMutableNotificationContent() content.title = contentTitle content.body = contentBody content.sound = .default let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour], from: Date().addingTimeInterval(5)) let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false) let trigger2 = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false) let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger) let request2 = UNNotificationRequest(identifier: id, content: content, trigger: trigger2) self.center.add(request) } } </code></pre>
[ { "answer_id": 74643145, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 1, "selected": false, "text": "library(tidyverse)\n\ndata %>%\n count(response, sex) %>%\n mutate(n = ifelse(response == 0, -n, n)) %>%\n ggplot(aes(sex, n, fill = factor(response))) +\n geom_hline(yintercept = 0) +\n geom_hline(yintercept = c(-3, 3), linetype = 2, size = 0.2) +\n geom_col(position = 'identity', color = 'black', width = 0.5) +\n coord_flip() +\n scale_y_continuous(breaks = seq(-7, 7), name = 'count', limits = c(-7, 7)) +\n scale_fill_manual(values = c(\"#bebebe\", \"#2a2a2a\"), guide = 'none') +\n annotate('text', y = c(-4, 4), x = c(2.8, 2.8), vjust = 1, size = 6,\n label = c('RESPONSE = 0', 'RESPONSE = 1'), fontface = 2) +\n scale_x_discrete(expand = c(0, 1), name = NULL) +\n theme_minimal(base_size = 16) +\n theme(axis.line.x = element_line(),\n axis.ticks.x = element_line(),\n panel.grid = element_blank())\n" }, { "answer_id": 74643389, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 3, "selected": true, "text": "# compute percentages\ntab <- t(table(data$response, data$sex) * c(-1, 1))\ntab <- tab / rowSums(abs(tab)) * 100\n\n# positions of x axis labels\nlab.x <- seq(-100, 100, 25)\n# initiate new plot\nframe()\npar(mar=c(2.5, 1, 2, 1))\nplot.window(range(lab.x), c(0, 1))\n# draw x axis\naxis(1, at=lab.x, labels=abs(lab.x))\n# draw vertical lines\nabline(v=0)\nabline(v=c(-1, 1)*50, lty=2)\n# bar middle y coordinates\nbar.mid <- c(.3, .7)\n# bar height\nbar.ht <- .25\n# draw bars\nrect(c(tab), bar.mid - bar.ht/2, 0, bar.mid + bar.ht/2,\n col=rep(gray(c(.8, .2)), each=2))\nmtext(c('No pain', 'Pain'), 3, at=c(-1, 1)*40, cex=1.3, line=.5)\n# print bar labels (male, female)\ntext(min(lab.x), bar.mid, rownames(tab), adj=0)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18835853/" ]
74,642,981
<p>I am having difficulties trying to locate multiple values from columns in a csv file.</p> <p>So far i have tried defining the columns from which i want to extract the values as,</p> <pre><code>Assignments = (data.loc[:, ~data.columns.isin(['A', 'B','C'])]) </code></pre> <p>This should take each column not named 'A', 'B' of 'C' from the csv file.</p> <p>I tried running the code,</p> <pre><code>data.loc[(data[Assignments] != 20)] </code></pre> <p>but i am met with the error message: # If we have a listlike key, _check_indexing_error will raise</p> <p>KeyError: 100</p> <p>The wanted outcome is a list of all rows that don't contain the value 20 (I am also not sure how to add more values than one like for example != 20,10,0.</p> <p>Any help is much appreciated.</p>
[ { "answer_id": 74643575, "author": "ImotVoksim", "author_id": 17580723, "author_profile": "https://Stackoverflow.com/users/17580723", "pm_score": 2, "selected": true, "text": "df[(df[:] != 20).all(axis = 1)] ar1 = np.array((df[:] != 20).all(axis = 1))\nar2 = np.array((df[:] != 30).all(axis = 1))\ndf[ar1 & ar2]\n" }, { "answer_id": 74643942, "author": "Robert", "author_id": 7041865, "author_profile": "https://Stackoverflow.com/users/7041865", "pm_score": 0, "selected": false, "text": "~ DataFrame.isin() import pandas as pd\n\n# Load the DataFrame from a CSV file\ndata = pd.read_csv('data.csv')\n\n# Select the columns you want to include\nassignments = data.loc[:, ~data.columns.isin(['A', 'B', 'C'])]\n\n# Select rows that do not contain the value 20\nselected = data.loc[~data.isin([20]).any(axis=1)]\n isin() isin() values import pandas as pd\n\n# Load the DataFrame from a CSV file\ndata = pd.read_csv('data.csv')\n\n# Select the columns you want to include\nassignments = data.loc[:, ~data.columns.isin(['A', 'B', 'C'])]\n\n# Select rows that do not contain the values 20, 10, or 0\nselected = data.loc[~data.isin([20, 10, 0]).any(axis=1)]\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74642981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20624550/" ]
74,643,004
<pre><code>class Solution { public boolean halvesAreAlike(String s) { Set&lt;Character&gt; vowels = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'); int vowelsCount = 0, midIndex = s.length() / 2; for (int i = 0; i &lt; midIndex; i++) { char charA = s.charAt(i); char charB = s.charAt(midIndex + i); if (vowels.contains(charA)) vowelsCount++; if (vowels.contains(charB)) vowelsCount--; } return vowelsCount == 0; //Can you explain this specific return part?? } } </code></pre> <p>if was trying to get output as simple return vowelcount but i did not get it? Why I have to use vowelCount==0</p>
[ { "answer_id": 74643575, "author": "ImotVoksim", "author_id": 17580723, "author_profile": "https://Stackoverflow.com/users/17580723", "pm_score": 2, "selected": true, "text": "df[(df[:] != 20).all(axis = 1)] ar1 = np.array((df[:] != 20).all(axis = 1))\nar2 = np.array((df[:] != 30).all(axis = 1))\ndf[ar1 & ar2]\n" }, { "answer_id": 74643942, "author": "Robert", "author_id": 7041865, "author_profile": "https://Stackoverflow.com/users/7041865", "pm_score": 0, "selected": false, "text": "~ DataFrame.isin() import pandas as pd\n\n# Load the DataFrame from a CSV file\ndata = pd.read_csv('data.csv')\n\n# Select the columns you want to include\nassignments = data.loc[:, ~data.columns.isin(['A', 'B', 'C'])]\n\n# Select rows that do not contain the value 20\nselected = data.loc[~data.isin([20]).any(axis=1)]\n isin() isin() values import pandas as pd\n\n# Load the DataFrame from a CSV file\ndata = pd.read_csv('data.csv')\n\n# Select the columns you want to include\nassignments = data.loc[:, ~data.columns.isin(['A', 'B', 'C'])]\n\n# Select rows that do not contain the values 20, 10, or 0\nselected = data.loc[~data.isin([20, 10, 0]).any(axis=1)]\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20657032/" ]
74,643,043
<p>I come from c++ background and learning rust. I'm trying to implement the rust equivalent code of the following c++ code which makes use of inheritance, but got stuck. This is my sample code</p> <pre class="lang-cpp prettyprint-override"><code>class Vehicle { public: double lat; double lon; double alt; double speed; }; class CabVehicle : public Vehicle { }; class PackerMoverVehicle : public Vehicle { }; int main() { CabVehicle cv; cv.lat = 12.34; cv.lon = 12.34; cv.alt = 12.34; PackerMoverVehicle pmv; pmv.lat = 12.34; pmv.lon = 12.34; pmv.alt = 12.34; } </code></pre>
[ { "answer_id": 74646539, "author": "Kevin Reid", "author_id": 99692, "author_profile": "https://Stackoverflow.com/users/99692", "pm_score": 1, "selected": false, "text": "struct VehicleState {\n lat: f64,\n lon: f64,\n alt: f64,\n speed: f64,\n}\n struct Cab {\n state: VehicleState,\n // ... other fields\n}\n\nstruct PackerMover {\n state: VehicleState,\n // ... other fields\n}\n state state struct Vehicle<T> {\n state: VehicleState,\n details: T,\n}\n\nstruct Cab { /* ... */ }\nstruct PackerMover { /* ... */ }\n\n/// This function only works with Cabs\nfn foo(vehicle: Vehicle<Cab>) { /* ... */ } \n \n/// This function works with any Vehicle\nfn foo<T>(vehicle: Vehicle<T>) { /* ... */ } \n state Vehicle struct Vehicle<T: ?Sized> { /* ... */\n// ^^^^^^^^ remove default restriction on the type parameter\n\ntrait VehicleDetails { /* add methods here */ }\nimpl VehicleDetails for Cab { /* ... */ }\nimpl VehicleDetails for PackerMover { /* ... */ }\n Box &Vehicle<Cab> &Vehicle<dyn VehicleDetails> Vehicle T VehicleDetails Vec<Box<Vehicle<dyn VehicleDetails>>> dyn VehicleDetails Cab Cab enum struct Vehicle {\n state: VehicleState,\n kind: VehicleKind,\n}\n\nenum VehicleKind {\n Cab {\n seats: u16,\n },\n PackerMover {\n cargo_capacity: u64,\n }\n}\n Vehicle enum VehicleKind Vehicle<dyn VehicleDetails>" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3938402/" ]
74,643,048
<p>I'm collecting time series data, but sometimes for some time points there is no data to be collected. Just say for example I am collecting data across four time points, I might get a dataframe like this:</p> <pre><code>df_ = pd.DataFrame({'group': ['A']*3+['B']*3, 'time': [1,2,4,1,3,4], 'value': [100,105,111,200,234,222]}) </code></pre> <p>sometimes there is a datapoint missing and so there is no row for that point, I would like groupby and to forward fill with the previous value to create a new row form which would look like this:</p> <pre><code>df_missing_completed = pd.DataFrame({'group': ['A']*4+['B']*4, 'time': [1,2,3,4,1,2,3,4], 'value': [100, 101, 105,111,200, 202, 234,222]}) </code></pre> <p>I had the idea that I could create an new dataframe as a template with all the dates and time points, without any values, join it with the real data which would induce NA's, and do a <code>ffill</code>on the value column to fill in the missing data, like below:</p> <pre><code>df_template = pd.DataFrame({'group': ['A']*4+['B']*4, 'time': [1,2,3,4,1,2,3,4]}) df_final = pd.merge(df_template, df_, on = ['group', 'time'], how='left') df_final['filled_values'] = df_final['value'].fillna(method='ffill') </code></pre> <p>but this seems like a messy solution, and with the real data the <code>df_templete</code> will be more complex to create. Does anyone know a better one? Thanks!</p>
[ { "answer_id": 74643308, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "(df_.pivot(index='time', columns='group', values='value')\n # reindex only of you want to add missing times for all groups\n .reindex(range(df_['time'].min(), df_['time'].max()+1))\n .ffill().unstack().reset_index(name='value')\n)\n group time value\n0 A 1 100.0\n1 A 2 105.0\n2 A 3 105.0\n3 A 4 111.0\n4 B 1 200.0\n5 B 2 200.0\n6 B 3 234.0\n7 B 4 222.0\n" }, { "answer_id": 74644039, "author": "Stef", "author_id": 3944322, "author_profile": "https://Stackoverflow.com/users/3944322", "pm_score": 1, "selected": false, "text": "reindex ffill new_idx = pd.MultiIndex.from_product([list('AB'), range(1,5)], names=['group', 'time'])\ndf_.set_index(['group', 'time']).reindex(new_idx, method='ffill').reset_index()\n group time value\n0 A 1 100\n1 A 2 105\n2 A 3 105\n3 A 4 111\n4 B 1 200\n5 B 2 200\n6 B 3 234\n7 B 4 222\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5024631/" ]
74,643,079
<p>i am doing this todo list from a youtube channel.below is the code</p> <pre><code>import { useState } from &quot;react&quot;; export default function Todo(){ const[todo,settodo]=useState(&quot;&quot;); const [todolist,settodolist]=useState([]) const Handletodo=(event)=&gt;{ settodo(event.target.value) } const HandleSubmit=(event)=&gt;{ event.preventDefault(); todolist.push(todo); console.log(todolist) settodo(&quot;&quot;) } return( &lt;div&gt; &lt;form onSubmit={HandleSubmit}&gt; &lt;div&gt; &lt;input type={&quot;text&quot;} value={todo} onChange={Handletodo}&gt;&lt;/input&gt; &lt;button type=&quot;submit&quot;&gt;Add&lt;/button&gt; &lt;/div&gt;&lt;br/&gt; &lt;/form&gt; {todolist.map((item)=&gt;{ &lt;h3&gt;item&lt;/h3&gt; })} &lt;/div&gt; ) } </code></pre> <p>why i cant iterate the todolist.map() in return</p> <p>this is the link of that video <a href="https://www.youtube.com/watch?v=eYlC4ReZRCk&amp;list=PLSsAz5wf2lkK_ekd0J__44KG6QoXetZza&amp;index=33" rel="nofollow noreferrer">https://www.youtube.com/watch?v=eYlC4ReZRCk&amp;list=PLSsAz5wf2lkK_ekd0J__44KG6QoXetZza&amp;index=33</a></p>
[ { "answer_id": 74643308, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "(df_.pivot(index='time', columns='group', values='value')\n # reindex only of you want to add missing times for all groups\n .reindex(range(df_['time'].min(), df_['time'].max()+1))\n .ffill().unstack().reset_index(name='value')\n)\n group time value\n0 A 1 100.0\n1 A 2 105.0\n2 A 3 105.0\n3 A 4 111.0\n4 B 1 200.0\n5 B 2 200.0\n6 B 3 234.0\n7 B 4 222.0\n" }, { "answer_id": 74644039, "author": "Stef", "author_id": 3944322, "author_profile": "https://Stackoverflow.com/users/3944322", "pm_score": 1, "selected": false, "text": "reindex ffill new_idx = pd.MultiIndex.from_product([list('AB'), range(1,5)], names=['group', 'time'])\ndf_.set_index(['group', 'time']).reindex(new_idx, method='ffill').reset_index()\n group time value\n0 A 1 100\n1 A 2 105\n2 A 3 105\n3 A 4 111\n4 B 1 200\n5 B 2 200\n6 B 3 234\n7 B 4 222\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14346213/" ]
74,643,093
<p>I'm trying to backup some information from a folder. I try to make it so my collegues can also work with it. The folder in with are the files to backup dosen't have the same name on each machine.</p> <p>I work from a different folder.</p> <p>What I can do is this in CMD:</p> <pre><code>cd %APPDATA%\Mozilla\Firefox\Profiles\*.default-esr </code></pre> <p>and I can navigate to C:\Users***\AppData\Roaming\Mozilla\Firefox\Profiles\k6lfpnug.default-esr</p> <p>I tried to implement it in my batch file :</p> <pre><code>@echo off set CURRENT_DIR=%~dp0 set FIREFOX_DIR=%APPDATA%\Mozilla\Firefox\Profiles\*.default-esr set BAK_FIREFOX_DIR=%CURRENT_DIR%\Firefox-%TIMESTAMP% mkdir %BAK_Firefox_DIR% robocopy %FIREFOX_DIR% %BAK_Firefox_DIR% places.sqlite </code></pre> <p>What I get :</p> <p><code>ERREUR : paramètre non valide #1 : &quot;C:\Users\***\AppData\Roaming\Mozilla\Firefox\Profiles\*.default-esr&quot;</code></p> <p>What I expected is that :</p> <pre><code>set FIREFOX_DIR=%APPDATA%\Mozilla\Firefox\Profiles\*.default-esr echo %FIREFOX_DIR% </code></pre> <p>gives me</p> <p><code>C:\Users\***\AppData\Roaming\Mozilla\Firefox\Profiles\k6lfpnug.default-esr</code></p>
[ { "answer_id": 74646732, "author": "Mofi", "author_id": 3074564, "author_profile": "https://Stackoverflow.com/users/3074564", "pm_score": 2, "selected": true, "text": "@echo off\nsetlocal EnableExtensions DisableDelayedExpansion\nrem Search for the default Firefox profiles directory. If one of the two\nrem possible wildcard patterns return a positive match, make a backup of\nrem the file with annotations, bookmarks, favorite icons, input history,\nrem keywords, and browsing history (a record of visited pages) in that\nrem directory using current date and time in the format yyyy-MM-dd_hh_mm\nrem (international date format + hour and minute) in the destination\nrem directory name.\nfor /D %%# in (\"%APPDATA%\\Mozilla\\Firefox\\Profiles\\*.default-esr\" \"%APPDATA%\\Mozilla\\Firefox\\Profiles\\*.default-release\") do (\n for /F \"tokens=1-5 delims=/: \" %%G in ('%SystemRoot%\\System32\\robocopy.exe \"%SystemDrive%\\|\" . /NJH') do (\n %SystemRoot%\\System32\\robocopy.exe \"%%#\" \"%~dp0Firefox-%%G-%%H-%%I_%%J_%%K\" places.sqlite /NDL /NFL /NJH /NJS /R:1 /W:5 >nul\n goto EndBatch\n )\n)\necho ERROR: Could not find the default Firefox profile folder.\necho/\npause\n:EndBatch\nendlocal\n %~dp0 \\ %~dp0 echo /? endlocal /? for /? goto /? pause /? rem /? robocopy /? setlocal /?" }, { "answer_id": 74652610, "author": "Gulivert", "author_id": 3365217, "author_profile": "https://Stackoverflow.com/users/3365217", "pm_score": 0, "selected": false, "text": "@ECHO OFF\n\nset CURRENT_DIR=%~dp0\nset TASKBAR_DIR=%APPDATA%\\Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar\nset QUICK_ACCES_DIR=%APPDATA%\\Microsoft\\Windows\\Recent\\AutomaticDestinations\nfor /D %%# in (\"%APPDATA%\\Mozilla\\Firefox\\Profiles\\*.default-esr\" \"%APPDATA%\\Mozilla\\Firefox\\Profiles\\*.default-release\") do (\n set FIREFOX_DIR=%%#\n)\nfor /F \"tokens=2 delims==.\" %%I in ('%SystemRoot%\\System32\\wbem\\wmic.exe OS GET LocalDateTime /VALUE') do (set \"DateTime=%%I\")\nset \"TIMESTAMP=%DateTime:~0,8%_%DateTime:~8,2%-%DateTime:~10,2%\"\n\nset BAK_FIREFOX_DIR=%CURRENT_DIR%\\Firefox-%TIMESTAMP%\nmkdir %BAK_Firefox_DIR%\nrobocopy %FIREFOX_DIR% %BAK_Firefox_DIR% key4.db /NDL /NFL /NJH /NJS /R:1 /W:5\nrobocopy %FIREFOX_DIR% %BAK_Firefox_DIR% logins.json /NDL /NFL /NJH /NJS /R:1 /W:5\nrobocopy %FIREFOX_DIR% %BAK_Firefox_DIR% logins-backup.json /NDL /NFL /NJH /NJS /R:1 /W:5\nrobocopy %FIREFOX_DIR% %BAK_Firefox_DIR% places.sqlite /NDL /NFL /NJH /NJS /R:1 /W:5\nrobocopy %FIREFOX_DIR% %BAK_Firefox_DIR% favicons.sqlite /NDL /NFL /NJH /NJS /R:1 /W:5\nrobocopy %FIREFOX_DIR% %BAK_Firefox_DIR% formhistory.sqlite /NDL /NFL /NJH /NJS /R:1 /W:5\nrobocopy %FIREFOX_DIR% %BAK_Firefox_DIR% cookies.sqlite /NDL /NFL /NJH /NJS /R:1 /W:5\nrobocopy %FIREFOX_DIR% %BAK_Firefox_DIR% cert9.db /NDL /NFL /NJH /NJS /R:1 /W:5\nrobocopy %FIREFOX_DIR% %BAK_Firefox_DIR% handlers.json /NDL /NFL /NJH /NJS /R:1 /W:5\n\npause\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3365217/" ]
74,643,252
<p>I'm new to javascript and I'm having difficulty keeping up with the various ways of writing functions, particularly the newer arrow function styles that don't require a return statement.</p> <p>I spent a while trying to write a function that takes a string containing both numbers and number strings, converts all into numbers and then gets the sum / total.</p> <p>From what I can gather, I was on the right path by trying to use the <code>map()</code> method to return a new array, followed by <code>parseInt</code> to change the strings to numbers, and finally <code>reduce()</code> to get the sum.</p> <p>When I tried this, the reduce method would not work, and I would be left with the array of numbers.</p> <p>Someone else wrote a solution that works that uses the same steps as mine, but I am struggling to work out how this would work when written in the longer format that I have learned (I haven't extensively studied shorter form ES6 arrow functions yet).</p> <p>Any advice on how I could change my function so that it works like the shorter one would be greatly appreciated.</p> <p><strong>My function:</strong></p> <pre><code>const myArr = [3, 7, 8, &quot;5&quot;, &quot;9&quot;, 6, &quot;2&quot;]; function sumMix(x) { return x.map((str) =&gt; { return parseInt(str); }); str.reduce((acc, cur) =&gt; { return acc + cur; }); } sumMix(myArr); </code></pre> <p><strong>The working solution I found</strong></p> <pre><code>const myArr = [3, 7, 8, &quot;5&quot;, &quot;9&quot;, 6, &quot;2&quot;]; function sumMix(x){ return x.map( str =&gt; parseInt(str)).reduce( (acc, cur) =&gt; acc + cur ); } sumMix(myArr); </code></pre>
[ { "answer_id": 74643323, "author": "0stone0", "author_id": 5625547, "author_profile": "https://Stackoverflow.com/users/5625547", "pm_score": 0, "selected": false, "text": "map() reduce() parseInt cur 0 reduce() parseInt(cur) const myArr = [3, 7, 8, \"5\", \"9\", 6, \"2\"];\n\nconst sumMix = x => x.reduce((acc, cur) => acc + parseInt(cur), 0)\n\nconst res = sumMix(myArr);\nconsole.log(res); // 40" }, { "answer_id": 74643419, "author": "terpinmd", "author_id": 3542351, "author_profile": "https://Stackoverflow.com/users/3542351", "pm_score": 2, "selected": true, "text": "const myArr = [3, 7, 8, \"5\", \"9\", 6, \"2\"];\n\nfunction sumMix(x) {\n return x.map((str) => { \n return parseInt(str);\n }).reduce((acc, cur) => {\n return acc + cur;\n }); \n}\n\nsumMix(myArr);" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5220731/" ]
74,643,271
<p>I want to apply the widget ColorFiltered to a container which is inside an other container, the problem is the filter takes all the screen =&gt; The filter is also applied to the blue container, and this same container expands.</p> <pre><code>void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold(body:Test1()), ); } } class Test1 extends StatelessWidget { const Test1({super.key}); @override Widget build(BuildContext context) { return Container( color: Colors.blue, height: 300, width: MediaQuery.of( context, ).size.width, child: Align( child: ColorFiltered( colorFilter: const ColorFilter.mode(Colors.grey, BlendMode.saturation), child: Container( width: 100, height: 100, color: Colors.red, ), ))); } } </code></pre>
[ { "answer_id": 74644329, "author": "LorenzOliveto", "author_id": 2290372, "author_profile": "https://Stackoverflow.com/users/2290372", "pm_score": 2, "selected": true, "text": "ClipRect class Test1 extends StatelessWidget {\n const Test1({super.key});\n\n @override\n Widget build(BuildContext context) {\n return Container(\n color: Colors.blue,\n height: 300,\n width: MediaQuery.of(context).size.width,\n child: Align(\n child: ClipRect(\n child: ColorFiltered(\n colorFilter:\n const ColorFilter.mode(Colors.grey, BlendMode.saturation),\n child: Container(\n width: 100,\n height: 100,\n color: Colors.red,\n ),\n ),\n ),\n ),\n );\n }\n}\n" }, { "answer_id": 74645200, "author": "Tushar Mahmud", "author_id": 15565819, "author_profile": "https://Stackoverflow.com/users/15565819", "pm_score": 0, "selected": false, "text": "class TestWidget extends StatelessWidget {\n const TestWidget ({super.key});\n\n @override\n Widget build(BuildContext context) {\n return Container(\n color: Colors.indigo,\n height: 300,\n width: MediaQuery.of(context).size.width,\n child: Align(\n child: ClipRect(\n child: ColorFiltered(\n colorFilter:\n const ColorFilter.mode(Colors.grey, BlendMode.saturation),\n child: Container(\n width: 100,\n height: 100,\n color: Colors.red,\n ),\n ),\n ),\n ),\n );\n }\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7905820/" ]
74,643,277
<p>I have a problem. It includes the condition that to COUNT the rows where its status = 1 (GROUP BY name).</p> <p>However, the result should include the rows WHERE those are not = 1 and NULL. And they are counted as 0.</p> <p>I have tried cte, CASE WHEN, WHERE status = 1 or status IS NULL. It does include null as 0, but there are name containing 1 and 0 or only containing 0.</p> <p>If I use WHERE status IS NULL OR status=1, the name with status 0 is not counted.</p> <p>If I use CASE WHEN status IS NULL THEN 0</p> <pre><code> WHEN status IS 0 THEN 0 WHEN status = 1 THEN COUNT(DISTINCT name) </code></pre> <p>Then the name containing 1 AND 0 will be counted as 0.</p> <p>TABLE:</p> <p>INSERT INTO students (name, student_id, exercise_id, status) VALUES (Uolevi, 1, 1, 0), (Uolevi, 1, 1, 0), (Uolevi, 1, 1, 1), (Uolevi, 1, 2, 0), (Uolevi, 1, 2, 0), (Uolevi, 1, 2, 1), (Maija , 2, 1, 1), (Maija , 2, 2, 1), (Maija , 2, 2, 1), (Maija , 2, 2, 1), (Maija , 2, 3, 0), (Juuso , 3, 1, 0), (Juuso , 3, 2, 0), (Juuso , 3, 3, 0), (Miiko , NULL, NULL, NULL);</p>
[ { "answer_id": 74644329, "author": "LorenzOliveto", "author_id": 2290372, "author_profile": "https://Stackoverflow.com/users/2290372", "pm_score": 2, "selected": true, "text": "ClipRect class Test1 extends StatelessWidget {\n const Test1({super.key});\n\n @override\n Widget build(BuildContext context) {\n return Container(\n color: Colors.blue,\n height: 300,\n width: MediaQuery.of(context).size.width,\n child: Align(\n child: ClipRect(\n child: ColorFiltered(\n colorFilter:\n const ColorFilter.mode(Colors.grey, BlendMode.saturation),\n child: Container(\n width: 100,\n height: 100,\n color: Colors.red,\n ),\n ),\n ),\n ),\n );\n }\n}\n" }, { "answer_id": 74645200, "author": "Tushar Mahmud", "author_id": 15565819, "author_profile": "https://Stackoverflow.com/users/15565819", "pm_score": 0, "selected": false, "text": "class TestWidget extends StatelessWidget {\n const TestWidget ({super.key});\n\n @override\n Widget build(BuildContext context) {\n return Container(\n color: Colors.indigo,\n height: 300,\n width: MediaQuery.of(context).size.width,\n child: Align(\n child: ClipRect(\n child: ColorFiltered(\n colorFilter:\n const ColorFilter.mode(Colors.grey, BlendMode.saturation),\n child: Container(\n width: 100,\n height: 100,\n color: Colors.red,\n ),\n ),\n ),\n ),\n );\n }\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20616169/" ]
74,643,337
<p>Trying to clone with full SSH URL, e.g., <code>git clone ssh://bitbucket.org/myaccount/myrepo.git</code> fails with permission denied (publickey), but using shorthand SSH URL, e.g., <code>git clone git@bitbucket.org/myaccount/myrepo.git</code> works just fine. Furthermore, even doing something like the following fails:</p> <pre class="lang-bash prettyprint-override"><code>ssh-agent bash -c 'ssh-add ~/.ssh/id_mykey_ed25519; git clone ssh://bitbucket.org/myaccount/myrepo.git' </code></pre> <p><strong>EDIT:</strong> I already have an entry of the following form in SSH config:</p> <pre><code>Host bitbucket.org IdentityFile ~/.ssh/id_mykey_ed25519 IdentitiesOnly yes </code></pre>
[ { "answer_id": 74644329, "author": "LorenzOliveto", "author_id": 2290372, "author_profile": "https://Stackoverflow.com/users/2290372", "pm_score": 2, "selected": true, "text": "ClipRect class Test1 extends StatelessWidget {\n const Test1({super.key});\n\n @override\n Widget build(BuildContext context) {\n return Container(\n color: Colors.blue,\n height: 300,\n width: MediaQuery.of(context).size.width,\n child: Align(\n child: ClipRect(\n child: ColorFiltered(\n colorFilter:\n const ColorFilter.mode(Colors.grey, BlendMode.saturation),\n child: Container(\n width: 100,\n height: 100,\n color: Colors.red,\n ),\n ),\n ),\n ),\n );\n }\n}\n" }, { "answer_id": 74645200, "author": "Tushar Mahmud", "author_id": 15565819, "author_profile": "https://Stackoverflow.com/users/15565819", "pm_score": 0, "selected": false, "text": "class TestWidget extends StatelessWidget {\n const TestWidget ({super.key});\n\n @override\n Widget build(BuildContext context) {\n return Container(\n color: Colors.indigo,\n height: 300,\n width: MediaQuery.of(context).size.width,\n child: Align(\n child: ClipRect(\n child: ColorFiltered(\n colorFilter:\n const ColorFilter.mode(Colors.grey, BlendMode.saturation),\n child: Container(\n width: 100,\n height: 100,\n color: Colors.red,\n ),\n ),\n ),\n ),\n );\n }\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12103188/" ]
74,643,354
<p>The first way</p> <pre><code>fun add(a: Int, b: Int): Int { return a + b } fun main() { print(add(a = 2, b = 3)) } </code></pre> <p>The second way</p> <pre><code>fun add(a: Int, b: Int): Int { return a + b } fun main() { print(add(2, 3)) } </code></pre> <p>The end result of the two functions is the same but i was wondering if there is any internal difference between the two ways of function calling.</p>
[ { "answer_id": 74643573, "author": "Robin", "author_id": 10514633, "author_profile": "https://Stackoverflow.com/users/10514633", "pm_score": 0, "selected": false, "text": "fun add(a :Int,b: Int):Int {\n return a+b;\n}\n fun add(a :Int = 2,b: Int = 3, c: Int = 4):Int {\n return a+b+c;\n}\n fun main() {\n print(add(a = 2, c = 3))\n}\n\n// So we did 2 + 3 + 3\n// prints 8\n// Notice we skipped b\n\n" }, { "answer_id": 74643583, "author": "MRF", "author_id": 20204744, "author_profile": "https://Stackoverflow.com/users/20204744", "pm_score": 3, "selected": true, "text": "print(add(b=3, a=2))\n" }, { "answer_id": 74643623, "author": "MoCoding", "author_id": 11617754, "author_profile": "https://Stackoverflow.com/users/11617754", "pm_score": 2, "selected": false, "text": "add(a=2,b=3) a b add(2,3) a b fun minus(a : Int,b:Int):Int{\n return a-b;\n}\nfun main()\n{\n print(minus(a=2,b=3)) // a = 2, b = 3 -> a - b = 2 - 3 = -1\n print(minus(b=2,a=3)) // a = 3, b = 2 -> a - b = 3 - 2 = 1\n print(minus(2,3)) // a = 2, b = 3 -> a - b = 2 - 3 = -1\n}\n minus(a=2,b=3) a b minus(2,3) a b fun add(b : Int,a:Int):Int{\n return a+b;\n}\n minus(a=2,b=3) a b minus(2,3) b a test() test(15) a b b test(b = 15)" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18415790/" ]
74,643,412
<p>I am trying to convert the pandas dataframe column values from -</p> <pre><code>{'01AB': [(&quot;ABC&quot;, 5),(&quot;XYZ&quot;, 4),(&quot;LMN&quot;, 1)], '02AB_QTY': [(&quot;Other&quot;, 20),(&quot;not_Other&quot;, 150)]} </code></pre> <p>this is what i have tried till now, but not working</p> <pre><code>import pandas as pd df = pd.DataFrame.from_records([{'01AB': [(&quot;ABC&quot;, 5),(&quot;XYZ&quot;, 4),(&quot;LMN&quot;, 1)], '02AB_QTY': [(&quot;Other&quot;, 20),(&quot;not_Other&quot;, 150)]}]) col_list = [&quot;01AB&quot;, &quot;02AB_QTY&quot;,] # for col in col_list: # df[col] = df[col].apply(lambda x: {} if x is None else {key: {v[0]:v[1] for v in list_item} for key, list_item in x.items()}) df </code></pre> <p>expected output is like</p> <pre><code>{'01AB': {&quot;ABC&quot;:5,&quot;XYZ&quot;:4,&quot;LMN&quot;:1}, '02AB_QTY': {&quot;Other&quot;:20,&quot;not_Other&quot;:150}} </code></pre>
[ { "answer_id": 74643743, "author": "Adam.Er8", "author_id": 5052365, "author_profile": "https://Stackoverflow.com/users/5052365", "pm_score": 2, "selected": true, "text": "df.applymap() df[col_list] = df[col_list].applymap(lambda lst: {k: v for k, v in lst})\n" }, { "answer_id": 74643762, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 1, "selected": false, "text": "import pandas as pd\n\ndf = pd.DataFrame.from_records([{'01AB': [(\"ABC\", 5),(\"XYZ\", 4),(\"LMN\", 1)], '02AB_QTY': [(\"Other\", 20),(\"not_Other\", 150)]}])\n\nout_dict = dict()\nfor col in df.columns:\n out_dict[col] = dict(df[col][0])\n {'01AB': {'ABC': 5, 'XYZ': 4, 'LMN': 1},\n '02AB_QTY': {'Other': 20, 'not_Other': 150}}\n" }, { "answer_id": 74643786, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "out = {k: dict(x) for k,v in df.iloc[0].to_dict().items()}\n {'01AB': {'ABC': 5, 'XYZ': 4, 'LMN': 1},\n '02AB_QTY': {'ABC': 5, 'XYZ': 4, 'LMN': 1}}\n" }, { "answer_id": 74644163, "author": "NNM", "author_id": 16578438, "author_profile": "https://Stackoverflow.com/users/16578438", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\ndf = pd.DataFrame.from_records([{'01AB': [(\"ABC\", 5),(\"XYZ\", 4),(\"LMN\", 1)], '02AB_QTY': [(\"Other\", 20),(\"not_Other\", 150)]}])\n\ncol_list = [\"01AB\", \"02AB_QTY\",]\n\nprint(df)\n\nfor col in col_list:\n df[col] = df[col].apply(lambda x: {} if x is None else dict(x))\n\nprint(df)\n 01AB 02AB_QTY\n{'ABC': 5, 'XYZ': 4, 'LMN': 1} {'Other': 20, 'not_Other': 150}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16578438/" ]
74,643,456
<p>I am practicing creating my own testing framework on Pycharm in Python with Selenium. However, for some reason the suite is failing to initiate pytest and recognise my test case, I am not sure where I have gone wrong, I usually dont have this problem, and I have marked the test case with test_.</p> <pre><code>import pytest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys import time from myPageObjects.sauce_login_page import sauce_login_page from myPageObjects.sauce_items_page import sauce_item_page from myPageObjects.sauce_details_page import sauce_details_page from myPageObjects.sauce_confirm_page import sauce_confirm_page from myPageObjects.sauce_success_page import sauce_success_page from ownUtilities.Sauce_Base_Class import sauce_base_class class sauce_test_one(sauce_base_class): def test_saucee2e(self): sauceLogin = sauce_login_page(self.driver) # Type in your username in the username box sauceLogin.getUsername().send_keys(&quot;standard_user&quot;) # Type in your password in your password box sauceLogin.getPassword().send_keys(&quot;secret_sauce&quot;) # Click the login button sauceLogin.getLogin().click() sauceItems = sauce_item_page(self.driver) # Click the Backpack to add to the cart sauceItems.getBackpack().click() # Click the Bikelight to add to the cart sauceItems.getBikelight().click() # Click on the T shirt to add to the cart sauceItems.getTshirt().click() # Click on the Jacket and add to the cart sauceItems.getFleecejacket().click() # Click on the shopping cart badge at the top of the page sauceItems.getShoppingcartbadge().click() # Click the checkout button sauceItems.getCheckoutbutton().click() sauceDetails = sauce_details_page(self.driver) # Make sure the next page has loaded self.wait4connection() # Type in the first name in the first name box sauceDetails.getFirstname().send_keys(&quot;Miserable&quot;) # Type in the second name in the second name box sauceDetails.getSecondname().send_keys(&quot;Teen&quot;) # Type in your postcode in the postcode sauceDetails.getPostcode().send_keys(&quot;se15 4qu&quot;) # Click continue SauceDetailsPage.getContinuebutton().click() sauceConfirm = sauce_confirm_page(self.driver) # Make sure the price of the items are correct correctprice = sauceConfirm.getCheckouttotal().text assert &quot;$144.44&quot; in correctprice print(correctprice) sauceSuccess = sauce_success_page(self.driver) # Click the finish button sauceSuccess.getFinishbutton().click() # Check that the successful order message has appeared passedtest = sauceSuccess.getSuccessmessage().text assert &quot;THANK YOU FOR YOUR ORDER&quot; in passedtest print(passedtest) </code></pre> <p><a href="https://i.stack.imgur.com/OWkt7.png" rel="nofollow noreferrer">Pytest result Picture</a> <a href="https://i.stack.imgur.com/rpFlD.png" rel="nofollow noreferrer">Test Case Picture</a></p> <p>Any input or advice would really be appreciated</p> <p>I expected pytest to run the test case and hopefully pass, however, it is not even recognising the test case and telling me its an Empty suite</p>
[ { "answer_id": 74643743, "author": "Adam.Er8", "author_id": 5052365, "author_profile": "https://Stackoverflow.com/users/5052365", "pm_score": 2, "selected": true, "text": "df.applymap() df[col_list] = df[col_list].applymap(lambda lst: {k: v for k, v in lst})\n" }, { "answer_id": 74643762, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 1, "selected": false, "text": "import pandas as pd\n\ndf = pd.DataFrame.from_records([{'01AB': [(\"ABC\", 5),(\"XYZ\", 4),(\"LMN\", 1)], '02AB_QTY': [(\"Other\", 20),(\"not_Other\", 150)]}])\n\nout_dict = dict()\nfor col in df.columns:\n out_dict[col] = dict(df[col][0])\n {'01AB': {'ABC': 5, 'XYZ': 4, 'LMN': 1},\n '02AB_QTY': {'Other': 20, 'not_Other': 150}}\n" }, { "answer_id": 74643786, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "out = {k: dict(x) for k,v in df.iloc[0].to_dict().items()}\n {'01AB': {'ABC': 5, 'XYZ': 4, 'LMN': 1},\n '02AB_QTY': {'ABC': 5, 'XYZ': 4, 'LMN': 1}}\n" }, { "answer_id": 74644163, "author": "NNM", "author_id": 16578438, "author_profile": "https://Stackoverflow.com/users/16578438", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\ndf = pd.DataFrame.from_records([{'01AB': [(\"ABC\", 5),(\"XYZ\", 4),(\"LMN\", 1)], '02AB_QTY': [(\"Other\", 20),(\"not_Other\", 150)]}])\n\ncol_list = [\"01AB\", \"02AB_QTY\",]\n\nprint(df)\n\nfor col in col_list:\n df[col] = df[col].apply(lambda x: {} if x is None else dict(x))\n\nprint(df)\n 01AB 02AB_QTY\n{'ABC': 5, 'XYZ': 4, 'LMN': 1} {'Other': 20, 'not_Other': 150}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647640/" ]
74,643,461
<p>For my dataset, the Date variable has dates in the format of this example: 19-Feb-03 I want to change the above character format dates in the column to a Date format. (As I have to do time series analysis later on)</p> <p>I tried using the as.Date() method but it didn't work.</p>
[ { "answer_id": 74643743, "author": "Adam.Er8", "author_id": 5052365, "author_profile": "https://Stackoverflow.com/users/5052365", "pm_score": 2, "selected": true, "text": "df.applymap() df[col_list] = df[col_list].applymap(lambda lst: {k: v for k, v in lst})\n" }, { "answer_id": 74643762, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": 1, "selected": false, "text": "import pandas as pd\n\ndf = pd.DataFrame.from_records([{'01AB': [(\"ABC\", 5),(\"XYZ\", 4),(\"LMN\", 1)], '02AB_QTY': [(\"Other\", 20),(\"not_Other\", 150)]}])\n\nout_dict = dict()\nfor col in df.columns:\n out_dict[col] = dict(df[col][0])\n {'01AB': {'ABC': 5, 'XYZ': 4, 'LMN': 1},\n '02AB_QTY': {'Other': 20, 'not_Other': 150}}\n" }, { "answer_id": 74643786, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "out = {k: dict(x) for k,v in df.iloc[0].to_dict().items()}\n {'01AB': {'ABC': 5, 'XYZ': 4, 'LMN': 1},\n '02AB_QTY': {'ABC': 5, 'XYZ': 4, 'LMN': 1}}\n" }, { "answer_id": 74644163, "author": "NNM", "author_id": 16578438, "author_profile": "https://Stackoverflow.com/users/16578438", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\ndf = pd.DataFrame.from_records([{'01AB': [(\"ABC\", 5),(\"XYZ\", 4),(\"LMN\", 1)], '02AB_QTY': [(\"Other\", 20),(\"not_Other\", 150)]}])\n\ncol_list = [\"01AB\", \"02AB_QTY\",]\n\nprint(df)\n\nfor col in col_list:\n df[col] = df[col].apply(lambda x: {} if x is None else dict(x))\n\nprint(df)\n 01AB 02AB_QTY\n{'ABC': 5, 'XYZ': 4, 'LMN': 1} {'Other': 20, 'not_Other': 150}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20657318/" ]
74,643,486
<p>Suppose I have 3 elements that I want to check if they are in an iterable say (<code>str</code> or <code>list</code>).</p> <p>I'm going to use an <code>str</code> as an example now but it should be the same in the case of a list:</p> <p>Assuming values to check for are <code>'a','b','c'</code> and string to search in is <code>'abcd'</code> saved in variable <code>line</code>.</p> <p>There are &quot;two&quot; general ways of doing this:</p> <p>One is to just do multiple checks</p> <pre><code>if 'a' in line and 'b' in line and 'c' in line: #Do something pass </code></pre> <p>Another is to use <code>all</code></p> <pre><code>if all( sub_str in line for sub_str in ['a','b','c']): #Do something pass </code></pre> <p>I want to know if there is any time-complexity difference between the two approaches.</p>
[ { "answer_id": 74643504, "author": "AKX", "author_id": 51685, "author_profile": "https://Stackoverflow.com/users/51685", "pm_score": 3, "selected": false, "text": "all all ['a','b','c'] # All found\n~ $ python3 -m timeit -s \"line = 'fooabc'\" \"'a' in line and 'b' in line and 'c' in line\"\n20000000 loops, best of 5: 55 nsec per loop\n~ $ python3 -m timeit -s \"line = 'fooabc'\" \"all( sub_str in line for sub_str in ['a','b','c'])\"\n5000000 loops, best of 5: 397 nsec per loop\n# None found\n~ $ python3 -m timeit -s \"line = 'fooddd'\" \"'a' in line and 'b' in line and 'c' in line\"\n50000000 loops, best of 5: 25.2 nsec per loop\n~ $ python3 -m timeit -s \"line = 'fooddd'\" \"all( sub_str in line for sub_str in ['a','b','c'])\"\n5000000 loops, best of 5: 325 nsec per loop\n" }, { "answer_id": 74643703, "author": "kaya3", "author_id": 12299000, "author_profile": "https://Stackoverflow.com/users/12299000", "pm_score": 1, "selected": false, "text": "or and a|b|c re" }, { "answer_id": 74644150, "author": "John Bollinger", "author_id": 2402272, "author_profile": "https://Stackoverflow.com/users/2402272", "pm_score": 1, "selected": false, "text": "all() all() all() x in line" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10817229/" ]
74,643,499
<p>I have the list <strong>a</strong>:</p> <p><code>a = ['wood', 'stone', 'bricks', 'diamond']</code></p> <p>And the list <strong>b</strong>:</p> <p><code>b = ['iron', 'gold', 'stone', 'diamond', 'wood']</code></p> <p>I need to compare lists and if value of list <strong>a</strong> equals with value from list <strong>b</strong>, it will be added to a list <strong>c</strong>:</p> <p><code>c = ['wood', 'stone', 'diamond']</code></p> <p>How can I compare these lists?</p>
[ { "answer_id": 74643615, "author": "Daniel Robinson", "author_id": 20631228, "author_profile": "https://Stackoverflow.com/users/20631228", "pm_score": 1, "selected": false, "text": "list(set(a) & set(b))\n" }, { "answer_id": 74643653, "author": "Hunter", "author_id": 15076691, "author_profile": "https://Stackoverflow.com/users/15076691", "pm_score": 0, "selected": false, "text": "for loop c = []\n\nfor element in a:\n if element in b:\n c.append(element)\nprint(c)\n c = [element for element in a if element in b]\nprint(c)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20165331/" ]
74,643,520
<p>I want to find a certain string in an array and for the case that it isn't found, add it to the end of the array. Checking if the value is in the array is okay. However, I can't find a method to determine the last next free place to add the value for the case that it's missing.</p> <pre><code>Sub New_3() Dim i As Integer Dim stringToBeFound As Char Dim arr(10) As Variant For i = LBound(arr) To UBound(arr) If arr(i) = stringToBeFound Then ' ??? End If Next i End Sub </code></pre>
[ { "answer_id": 74644046, "author": "FaneDuru", "author_id": 2233308, "author_profile": "https://Stackoverflow.com/users/2233308", "pm_score": 2, "selected": false, "text": "As Char Sub New_3()\n Dim mtch, stringToBeFound As String * 1\n Dim arr As Variant\n\n arr = Split(\"A,B,V,N,G,Y,U,Q,O,S,Z\", \",\")\n stringToBeFound = \"W\"\n mtch = Application.match(stringToBeFound, arr, 0)\n If Not IsNumeric(mtch) Then\n ReDim Preserve arr(UBound(arr) + 1)\n arr(UBound(arr)) = stringToBeFound\n End If\n Debug.Print Join(arr, \"|\") 'see in Immediate Window the result\nEnd Sub\n arr As Variant" }, { "answer_id": 74647699, "author": "T.M.", "author_id": 6460297, "author_profile": "https://Stackoverflow.com/users/6460297", "pm_score": 2, "selected": false, "text": "arr = NewItem(arr, srch) arr = NewItem(arr, srch, 2) arr = NewItem(arr, srch, idx:=2) Sub ExampleCall()\n Dim arr: arr = Split(\"A,B,V,N,G,Y,U,Q,O,S,Z\", \",\")\n Dim srch: srch = \"W\"\n'1) check for matching position\n Dim mtch: mtch = Application.Match(srch, arr, 0)\n'2) append non-matching item\n If Not IsNumeric(mtch) Then arr = NewItem(arr, srch)\n Debug.Print \"arr(\" & LBound(arr) & \" To \" & UBound(arr) & \") = \" & Join(arr, \"|\")\n ' ~~> arr(0 To 11) = A|B|V|N|G|Y|U|Q|O|S|Z|W\nEnd Sub\n Function NewItem(arr, ByVal insert As String, _\n Optional idx As Variant, Optional rebase As Boolean = True)\n'Purpose: - input of 0-based idx argument: inserts item\n' - no input of idx argument: appends item\nWith CreateObject(\"Forms.ComboBox.1\")\n'a) assign array to list property (no Userform ctrl needed!)\n .List = arr\n'b) append or insert?\n If IsMissing(idx) Then\n .AddItem insert ' append item\n Else\n .AddItem insert, idx ' insert item (Index argument idx is zero - based!)\n End If\n'c) change 2-dim .List values to a \"flat\" array\n Dim tmp: tmp = Application.Transpose(.List)\n'd) return function result\n If rebase Then ReDim Preserve tmp(LBound(arr) To UBound(arr) - LBound(arr) + 1)\n NewItem = tmp\nEnd With\n\nEnd Function\n\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11535108/" ]
74,643,572
<p>I have the following dataframe:</p> <pre><code>df=pd.DataFrame({ 'col1' : ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'D'], 'col2' : [9.6,10.4, 11.2, 3.3, 6, 4, 1.94, 15.44, 6.17, 8.16] }) </code></pre> <p>It has the display :</p> <pre><code>col1 col2 0 A 9.60 1 A 10.40 2 A 11.20 3 B 3.30 4 B 6.00 5 B 4.00 6 C 1.94 7 C 15.44 8 C 6.17 9 D 8.16 </code></pre> <p>I want to get the following output:</p> <pre><code>col1 col2 Diff 0 A 9.60 0 1 A 10.40 0.80 2 A 11.20 0.80 3 B 3.30 0 4 B 6.00 2.70 5 B 4.00 -2.00 6 C 1.94 0 7 C 15.44 13.50 8 C 6.17 -9.27 9 D 8.16 0 </code></pre> <p>I tried to use <code>diff()</code> but it calculate differences for all values in <code>col2</code> however I want to do that for each <code>item</code> in <code>col1</code>.</p> <p>So far I tried <code>df['col2'].diff()</code> but not worked,</p> <p>Any help from your side will be highly appreciated, thanks.</p>
[ { "answer_id": 74643701, "author": "ImotVoksim", "author_id": 17580723, "author_profile": "https://Stackoverflow.com/users/17580723", "pm_score": 1, "selected": false, "text": "differences = []\n\nfor val in df.col1.unique():\n diffs = df.loc[df.col1 == val].col2.diff()\n differences.extend(diffs)\n differences" }, { "answer_id": 74643702, "author": "grymlin", "author_id": 19041437, "author_profile": "https://Stackoverflow.com/users/19041437", "pm_score": 2, "selected": false, "text": "df.insert(2, 'Diff', (df.groupby('col1')['col2'].diff()))\n\n col1 col2 Diff\n0 A 9.60 NaN\n1 A 10.40 0.80\n2 A 11.20 0.80\n3 B 3.30 NaN\n4 B 6.00 2.70\n5 B 4.00 -2.00\n6 C 1.94 NaN\n7 C 15.44 13.50\n8 C 6.17 -9.27\n9 D 8.16 NaN\n" }, { "answer_id": 74643709, "author": "TiTo", "author_id": 12934163, "author_profile": "https://Stackoverflow.com/users/12934163", "pm_score": 2, "selected": true, "text": "groupby() diff() Diff fillna(0) df['Diff'] = df.groupby('col1')['col2'].diff().fillna(0)\n col1 col2 Diff\n0 A 9.60 0.00\n1 A 10.40 0.80\n2 A 11.20 0.80\n3 B 3.30 0.00\n4 B 6.00 2.70\n5 B 4.00 -2.00\n6 C 1.94 0.00\n7 C 15.44 13.50\n8 C 6.17 -9.27\n9 D 8.16 0.00\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15852600/" ]
74,643,594
<p>I already have one solution which going like this one below. But at Safari it looks like there is no <strong>margin-right: -5px;</strong>. Are there another ways to done this task <strong>or</strong> fixes for already existing solution.</p> <p><strong>HTML</strong></p> <pre><code>&lt;div class=&quot;card&quot;&gt; Title text &lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.card { width: 243px; height: 400px; display: flex; flex-direction: column; background-color: gray; border: 1px solid black; border-radius: 8px 0px 8px 8px; } &amp;::before { border-right: 1px solid black; width: 30px; height: 55px; margin-top: -22px; margin-right: -5px; content: ''; position: absolute; align-self: flex-end; transform: rotate(130deg); background: gray; } </code></pre> <p>The expected result looks like this <a href="https://i.stack.imgur.com/wdap1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wdap1.png" alt="expected_result" /></a></p>
[ { "answer_id": 74644977, "author": "Kondi", "author_id": 10164453, "author_profile": "https://Stackoverflow.com/users/10164453", "pm_score": -1, "selected": false, "text": "clip-path: polygon(0 0, 80% 0%, 100% 20%, 100% 100%, 0 100%);\n .card {\n width: 243px;\n height: 400px;\n display: flex;\n flex-direction: column;\n background-color: gray;\n border-radius: 5px;\n clip-path: polygon(0 0, 80% 0%, 100% 20%, 100% 100%, 0 100%);\n} <div class=\"card\">\n title text\n</div>" }, { "answer_id": 74647900, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": 2, "selected": true, "text": ".box {\n --b: 5px; /* border */\n --s: 50px; /* size of the cut */\n --c: red;\n \n width: 300px;\n height: 200px;\n \n border: var(--b) solid var(--c);\n border-radius: 20px;\n clip-path: polygon(0 0,calc(100% - var(--s)) 0,100% var(--s),100% 100%,0 100%);\n background: linear-gradient(-135deg,var(--c) calc(0.707*var(--s) + var(--b)),#0000 0) border-box;\n background-color: grey;\n \n} <div class=\"box\"></div>" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18783228/" ]
74,643,599
<p>I have a form in my .ejs file which has 4 number inputs and 1 text input. When clicking the submit button I want to run a script to check if the total of all the <em>number inputs</em> &lt;= 1140. If it is within that boundary, submit. If it is not within that boundary, display that the total is higher than 1140 and ask the user to change their inputs.</p> <p>Here is the code for my .ejs file, which includes my attempt at the script, but I'm not 100% sure on how to implement it.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;MTU Phone Usage Monitor&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;/stylesheets/styleHome.css&quot;&gt;&lt;/link&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot; banner&quot;&gt; &lt;div class=&quot;navbar&quot;&gt; &lt;img src=&quot;\images\logo.png&quot; class=&quot;logo&quot;&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;/&quot;&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;/phone/create&quot;&gt;New Entry&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;/table&quot;&gt;View Data&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;/help&quot;&gt;Help&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class=&quot;content&quot;&gt; &lt;h2&gt;Enter Phone usage data&lt;/h2&gt; &lt;form action=&quot;/phone/create&quot; method=&quot;post&quot;&gt; &lt;p&gt; &lt;label for=&quot;name&quot;&gt;Enter your full name:&lt;/label&gt; &lt;input type=&quot;String&quot; id=&quot;name&quot; name=&quot;name&quot; placeholder=&quot;Name&quot; required&gt; &lt;/p&gt; &lt;br&gt; &lt;p&gt; &lt;label for=&quot;timeEducation&quot;&gt;How much time used for education:&lt;/label&gt; &lt;input type=&quot;Number&quot; id=&quot;timeEducation&quot; name=&quot;timeEducation&quot; placeholder=&quot;Time in minutes&quot; min=&quot;0&quot; max=&quot;1140&quot; required&gt; &lt;/p&gt; &lt;br&gt; &lt;p&gt; &lt;label for=&quot;timeShopping&quot;&gt;How much time used for shopping:&lt;/label&gt; &lt;input type=&quot;Number&quot; id=&quot;timeShopping&quot; name=&quot;timeShopping&quot; placeholder=&quot;time in minutes&quot; min=&quot;0&quot; max=&quot;1140&quot; required&gt; &lt;/p&gt; &lt;br&gt; &lt;p&gt; &lt;label for=&quot;timeBrowsing&quot;&gt;How much time used for browsing and searching:&lt;/label&gt; &lt;input type=&quot;Number&quot; id=&quot;timeBrowsing&quot; name=&quot;timeBrowsing&quot; placeholder=&quot;Time in minutes&quot; min=&quot;0&quot; max=&quot;1140&quot; required&gt; &lt;/p&gt; &lt;br&gt; &lt;p&gt; &lt;label for=&quot;timeSocial&quot;&gt;How much time used for social media:&lt;/label&gt; &lt;input type=&quot;Number&quot; id=&quot;timeSocial&quot; name=&quot;timeSocial&quot; placeholder=&quot;Time in minutes&quot; min=&quot;0&quot; max=&quot;1140&quot; required&gt; &lt;/p&gt; &lt;br&gt; &lt;!-- add date input whenever --&gt; &lt;button id=&quot;button&quot; type=&quot;submit&quot;&gt;submit&lt;/button&gt; &lt;!--make hidden unless values withn 1140 in total--&gt; &lt;script&gt; function findTotal() { var arr = document.getElementById( 'timeEducation', 'timeShopping', 'timeBrowsing', 'timeSocial'); var total = 0; let element = document.getElementById(&quot;button&quot;) for (var i = 0; i &lt; arr.length; i++) { if (parseInt(arr[i].value)) total += parseInt(arr[i].value) } if (total &lt;= 1140) { //on click of button, submit } else { //on click of button, display the total of inputs combined must not exceed 1140 } } &lt;/script&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 74644977, "author": "Kondi", "author_id": 10164453, "author_profile": "https://Stackoverflow.com/users/10164453", "pm_score": -1, "selected": false, "text": "clip-path: polygon(0 0, 80% 0%, 100% 20%, 100% 100%, 0 100%);\n .card {\n width: 243px;\n height: 400px;\n display: flex;\n flex-direction: column;\n background-color: gray;\n border-radius: 5px;\n clip-path: polygon(0 0, 80% 0%, 100% 20%, 100% 100%, 0 100%);\n} <div class=\"card\">\n title text\n</div>" }, { "answer_id": 74647900, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": 2, "selected": true, "text": ".box {\n --b: 5px; /* border */\n --s: 50px; /* size of the cut */\n --c: red;\n \n width: 300px;\n height: 200px;\n \n border: var(--b) solid var(--c);\n border-radius: 20px;\n clip-path: polygon(0 0,calc(100% - var(--s)) 0,100% var(--s),100% 100%,0 100%);\n background: linear-gradient(-135deg,var(--c) calc(0.707*var(--s) + var(--b)),#0000 0) border-box;\n background-color: grey;\n \n} <div class=\"box\"></div>" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20572636/" ]
74,643,621
<p>I want to change the column labels of a Pandas DataFrame from</p> <pre><code>['evaluationId,createdAt,scheduleEndDate,sharedTo, ...] </code></pre> <p>to</p> <pre><code>['EVALUATION_ID,CREATED_AT,SCHEDULE_END_DATE,SHARED_TO,...] </code></pre> <p>I have a lot of columns with this pattern &quot;aaaBb&quot; and I want to create this pattern &quot;AAA_BB&quot; of renamed columns</p> <p>Can anyone help me?</p> <p>Cheers</p> <p>I tried something like</p> <pre><code>new_columns = [unidecode(x).upper() for x in df.columns] </code></pre> <p>But I don't have idea how to create a solution.</p>
[ { "answer_id": 74643649, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "str.replace _ str.upper df.columns = (df.columns\n .str.replace('(?<=[a-z])(?=[A-Z])', '_', regex=True)\n .str.upper()\n )\n evaluationId createdAt scheduleEndDate sharedTo\n0 NaN NaN NaN NaN\n EVALUATION_ID CREATED_AT SCHEDULE_END_DATE SHARED_TO\n0 NaN NaN NaN NaN\n" }, { "answer_id": 74643766, "author": "Robert", "author_id": 7041865, "author_profile": "https://Stackoverflow.com/users/7041865", "pm_score": 0, "selected": false, "text": "DataFrame.rename() import pandas as pd \n# Create a sample DataFrame\ndf = pd.DataFrame(columns=['evaluationId,createdAt,scheduleEndDate,sharedTo, ...'])\n\n# Use the rename() method to change the column labels\ndf = df.rename(columns={'evaluationId,createdAt,scheduleEndDate,sharedTo, ...': 'EVALUATION_ID,CREATED_AT,SCHEDULE_END_DATE,SHARED_TO,...'})\n rename() \"aaaBb\" str.replace() \"aaaBb\" \"AAA_BB\" import pandas as pd\n\n# Create a sample DataFrame\ndf = pd.DataFrame(columns=['aaaBb1', 'aaaBb2', 'aaaBb3', ...])\n\n# Use the rename() method with the str.replace() method to change the column labels\ndf = df.rename(columns=lambda x: x.str.replace('aaaBb', 'AAA_BB'))\n str.replace() \"aaaBb\" \"AAA_BB\"" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6214693/" ]
74,643,622
<p>In my Django project I have a model for a drinks recipe that allows up to 10 ingredients plus their amount. I am wondering if it's possible to make this in a more DRY way than I do now? This is the model I am using currently:</p> <pre><code>class Recipe(models.Model): ingr_name1 = models.CharField(max_length=250, verbose_name='Ingredient') ingr_amount1 = models.DecimalField(max_digits=5, decimal_places=1, verbose_name='Amount') ingr_name2 = models.CharField(max_length=250, blank=True, null=True, verbose_name='Ingredient') ingr_amount2 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name3 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount3 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name4 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount4 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name5 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount5 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name6 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount6 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name7 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount7 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name8 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount8 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name9 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount9 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name10 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount10 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') drink_name = models.CharField(max_length=250,blank=True, null=True, verbose_name='Drink name') drink_story = models.TextField() drink_picture = ResizedImageField(upload_to='drinks/', null=True, blank=True) def __str__(self): return self.drink_name </code></pre>
[ { "answer_id": 74644082, "author": "kimbo", "author_id": 9638991, "author_profile": "https://Stackoverflow.com/users/9638991", "pm_score": 1, "selected": false, "text": "ingredients_changed() class Ingredient(model.Model):\n name = models.CharField()\n amount = models.CharField()\n\nclass Recipe(models.Model):\n ingredients = models.ManyToManyField(Ingredient)\n\n def ingredients_changed(recipe, **kwargs):\n if kwargs['instance'].ingredients.count() > 10:\n raise ValidationError(\"You can't assign more than 10 ingredients\")\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14408344/" ]
74,643,633
<p>html page:</p> <pre><code>&lt;ion-content&gt; &lt;iframe [src]=&quot;qrLink&quot; width=&quot;100%&quot; height=&quot;100%&quot;&gt;&lt;/iframe&gt; &lt;/ion-content&gt; </code></pre> <p>ts page:</p> <pre><code>qrLink: string = null ngOnInit() { this.getShop(); } async getShop(){ const shopId = this.route.snapshot.queryParamMap.get('shopId'); if(shopId){ this.shop = await this.shopService.getShopById(shopId); this.shopName = this.shop[0].name; this.qrLink = this.shop[0].menu.qrLink; } } </code></pre> <p>the qrLink veriable is not null. I checked in this way:</p> <pre><code>&lt;ion-content&gt; &lt;iframe [src]=&quot;qrLink&quot; width=&quot;100%&quot; height=&quot;80%&quot;&gt;&lt;/iframe&gt; {{qrLink} &lt;/ion-content&gt; </code></pre> <p>How can I take this variable value to src?</p>
[ { "answer_id": 74654882, "author": "gokeyn", "author_id": 11854042, "author_profile": "https://Stackoverflow.com/users/11854042", "pm_score": 1, "selected": false, "text": "constructor(\n ...\n private sanitizer: DomSanitizer\n ) {}\n\nngOnInit() {\n this.getShop();\n}\n\nasync getShop(){\n const shopId = this.route.snapshot.queryParamMap.get('shopId');\n\n if(shopId){\n this.qrLink = this.shop[0].menu.qrLink;\n this.safeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(this.qrLink);\n }\n}\n <iframe [src]=\"safeSrc\" width=\"100%\" height=\"100%\"></iframe>\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11854042/" ]
74,643,668
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Client Number</th> <th>Matter Number</th> <th>Address</th> <th>Physical Files</th> <th>Electronic Files</th> <th>If any?</th> </tr> </thead> <tbody> <tr> <td>10001</td> <td>1000101</td> <td>Addy1</td> <td>No</td> <td>No</td> <td>0</td> </tr> <tr> <td>10001</td> <td>1000102</td> <td>||</td> <td>No</td> <td>No</td> <td>0</td> </tr> <tr> <td>10002</td> <td>1000201</td> <td>NULL</td> <td></td> <td></td> <td>1</td> </tr> <tr> <td>10003</td> <td>1000301</td> <td>Addy3</td> <td>Yes</td> <td>Yes</td> <td>1</td> </tr> <tr> <td>10004</td> <td>1000401</td> <td>Addy4</td> <td>No</td> <td>No</td> <td>0</td> </tr> <tr> <td>10004</td> <td>1000402</td> <td>||</td> <td>Yes</td> <td>No</td> <td>1</td> </tr> <tr> <td>10004</td> <td>1000403</td> <td>||</td> <td>No</td> <td>No</td> <td>0</td> </tr> <tr> <td>10005</td> <td>1000501</td> <td>Addy5</td> <td>No</td> <td>Yes</td> <td>1</td> </tr> <tr> <td>10006</td> <td>1000601</td> <td>Addy6</td> <td>No</td> <td>No</td> <td>0</td> </tr> </tbody> </table> </div> <p>I have a large excel sheet that for all intents and purposes looks like this example ^^</p> <p>The &quot;If any?&quot; column has this formula: <code>=IF(AND('Physical Files'=&quot;No&quot;, 'Electronic Files'=&quot;No&quot;),0,1)</code></p> <p>I'm trying to count the number of clients that have no physical or electronic files. Each client has a distinct Client Number, but some appear multiple times with multiple matters. If there is a client address on file, then it is noted as well as whether there are physical and/or electronic files. If there is no address, the Physical/Electronic columns are left blank.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Distinct Client #s</th> <th>Files?</th> </tr> </thead> <tbody> <tr> <td>10001</td> <td>0</td> </tr> <tr> <td>10002</td> <td>1</td> </tr> <tr> <td>10003</td> <td>1</td> </tr> <tr> <td>10004</td> <td>1</td> </tr> <tr> <td>10005</td> <td>1</td> </tr> <tr> <td>10006</td> <td>0</td> </tr> </tbody> </table> </div> <p>Right now I have a generated list of distinct client #s using <code>=UNIQUE()</code>. In the neighboring column I have this formula: <code>=SUM(FILTER(M2:M10, H2:H10=O2))</code> --&gt; Column M = &quot;If any?&quot; and Column H = &quot;Client Number&quot; in the example sheet, and Column O = &quot;Distinct Client #s&quot;.</p> <p>From that, I've used a COUNTIF for when the &quot;Files?&quot; Column = 0 -- the result is 2, which is correct, but I'm trying to find a way to get that result without having to make a list of the distinct client numbers. Is there a way to do this in a single cell?</p>
[ { "answer_id": 74654882, "author": "gokeyn", "author_id": 11854042, "author_profile": "https://Stackoverflow.com/users/11854042", "pm_score": 1, "selected": false, "text": "constructor(\n ...\n private sanitizer: DomSanitizer\n ) {}\n\nngOnInit() {\n this.getShop();\n}\n\nasync getShop(){\n const shopId = this.route.snapshot.queryParamMap.get('shopId');\n\n if(shopId){\n this.qrLink = this.shop[0].menu.qrLink;\n this.safeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(this.qrLink);\n }\n}\n <iframe [src]=\"safeSrc\" width=\"100%\" height=\"100%\"></iframe>\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20657140/" ]
74,643,676
<p>I am working on a simple timesheet/time tracking app in Shiny for personal use. The app will record timestamps for when I start and stop activities. However, there are times during the day where there are natural gaps between specific tasks where you still do stuff. These in-between periods are not captured by the app, but are present in the data as &quot;gaps&quot; between the timestamps. Sample data looks like this (dput of the data at the end of the post):</p> <pre><code># A tibble: 9 x 3 start end activity &lt;dttm&gt; &lt;dttm&gt; &lt;chr&gt; 1 2022-11-28 10:00:00 2022-11-28 10:50:30 Activity 1 2 2022-11-28 10:50:30 2022-11-28 11:39:05 Activity 2 3 2022-11-28 12:01:00 2022-11-28 16:10:45 Activity 2 4 2022-11-29 10:00:00 2022-11-29 10:50:30 Activity 1 5 2022-11-29 10:50:31 2022-11-29 11:00:15 Activity 4 6 2022-11-29 12:00:00 2022-11-29 13:00:00 Activity 5 7 2022-11-29 13:00:00 2022-11-29 16:00:00 Activity 2 8 2022-11-30 08:00:05 2022-11-30 10:00:00 Activity 1 9 2022-11-30 16:03:05 2022-11-30 17:00:00 Activity 2 </code></pre> <p>The gaps in the data are obvious. For example, on the 28th there is no gap between the first and the second entry (end time of the first entry is equal to the start time of the second entry). There is, however, a gap between the second entry and the third entry (the end time of the second entry differs from the third entry). We can find similar gaps for the other days in the sample data.</p> <p>What I want to do is fill in these gaps with an activity called &quot;Other&quot;, such that for each day there are no gaps between the start of the first and the end of the last entry. That is, all existing gaps are filled in. The desired output would look like this:</p> <pre><code># A tibble: 13 x 3 start end activity &lt;dttm&gt; &lt;dttm&gt; &lt;chr&gt; 1 2022-11-28 10:00:00 2022-11-28 10:50:30 Activity 1 2 2022-11-28 10:50:30 2022-11-28 11:39:05 Activity 2 3 2022-11-28 11:39:05 2022-11-28 12:01:00 Other 4 2022-11-28 12:01:00 2022-11-28 16:10:45 Activity 2 5 2022-11-29 10:00:00 2022-11-29 10:50:30 Activity 1 6 2022-11-29 10:50:30 2022-11-29 10:50:31 Other 7 2022-11-29 10:50:31 2022-11-29 11:00:15 Activity 4 8 2022-11-29 11:00:15 2022-11-29 12:00:00 Other 9 2022-11-29 12:00:00 2022-11-29 13:00:00 Activity 5 10 2022-11-29 13:00:00 2022-11-29 16:00:00 Activity 2 11 2022-11-30 08:00:05 2022-11-30 10:00:00 Activity 1 12 2022-11-30 10:00:00 2022-11-30 16:03:05 Other 13 2022-11-30 16:03:05 2022-11-30 17:00:00 Activity 2 </code></pre> <p>The data will be created daily for the forseeable future, so potentially the solution will have to work on larger datasets and a vectorized approach is preferable. Sofar, I've been working within the tidyverse and with lubridate. I am not sure if there is something simple/easy that I've overlookd (I hope so).</p> <p>The first thing I thought about was to write a loop or using a lapply type expression. This can quicly get out hand as the data grows unless I remember to always fill in or run checks and fill in data regularly (I will probably get to this part of the app eventually).</p> <p>Alternatively, I started thinking about pivoting the data longer creating groups of 2 matches with start and end times for each day to work out the gaps. This could potentially be quick, but I struggled to find a good way of setting up the problem.</p> <p>If it matters, the data is submitted to a local SQLite database everytime an entry is added.</p> <p>Any help/input on this is much appreciated.</p> <p><strong>Sample data:</strong></p> <pre><code>library(tidyverse) library(lubridate) db &lt;- structure(list(start = structure(c(1669629600, 1669632630, 1669636860, 1669716000, 1669719031, 1669723200, 1669726800, 1669795205, 1669824185 ), class = c(&quot;POSIXct&quot;, &quot;POSIXt&quot;), tzone = &quot;UTC&quot;), end = structure(c(1669632630, 1669635545, 1669651845, 1669719030, 1669719615, 1669726800, 1669737600, 1669802400, 1669827600), class = c(&quot;POSIXct&quot;, &quot;POSIXt&quot;), tzone = &quot;UTC&quot;), activity = c(&quot;Activity 1&quot;, &quot;Activity 2&quot;, &quot;Activity 2&quot;, &quot;Activity 1&quot;, &quot;Activity 4&quot;, &quot;Activity 5&quot;, &quot;Activity 2&quot;, &quot;Activity 1&quot;, &quot;Activity 2&quot; )), row.names = c(NA, -9L), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot; )) </code></pre>
[ { "answer_id": 74654882, "author": "gokeyn", "author_id": 11854042, "author_profile": "https://Stackoverflow.com/users/11854042", "pm_score": 1, "selected": false, "text": "constructor(\n ...\n private sanitizer: DomSanitizer\n ) {}\n\nngOnInit() {\n this.getShop();\n}\n\nasync getShop(){\n const shopId = this.route.snapshot.queryParamMap.get('shopId');\n\n if(shopId){\n this.qrLink = this.shop[0].menu.qrLink;\n this.safeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(this.qrLink);\n }\n}\n <iframe [src]=\"safeSrc\" width=\"100%\" height=\"100%\"></iframe>\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2878014/" ]
74,643,721
<p>Suppose i have an np array like this-</p> <pre><code>[[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] </code></pre> <p>I want a function fun_strip(x) . After applying this function i want the returned array to look like this:</p> <pre><code>[[ 6 7 8] [11 12 13]] </code></pre>
[ { "answer_id": 74643838, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "a = np.array([[ 0, 1, 2, 3, 4],\n [ 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19]])\n\nout = a[1:a.shape[0]-1, 1:a.shape[1]-1]\n N N = 1\na[N:a.shape[0]-N, N:a.shape[1]-N]\n array([[ 6, 7, 8],\n [11, 12, 13]])\n" }, { "answer_id": 74643869, "author": "ImotVoksim", "author_id": 17580723, "author_profile": "https://Stackoverflow.com/users/17580723", "pm_score": 0, "selected": false, "text": "arr = np.array([[0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19]])\narr[1:3, 1:4]\n def strip_func(arr, r1, r2, c1, c2):\n return(arr[r1:r2+1, c1:c2+1])\n r1 r2 c1 c2" }, { "answer_id": 74643950, "author": "Indiano", "author_id": 13309379, "author_profile": "https://Stackoverflow.com/users/13309379", "pm_score": 0, "selected": false, "text": "def fun_strip(array):\n return np.array([array[1][1:4],array[2][1:4]])\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20538008/" ]
74,643,724
<p>I did find some examples but they do not merge into single column. So, I am trying to join 2 table columns data into single column I have Url1, site1, url2, site2, endurl 5 columns in table1 and keywords column in table2</p> <p>I want to join or merge these columns into one column like url1 site1 keywords,url2 site2 keywords endurl this will convert to a url generation just for understanding.</p> <p>I tried</p> <pre><code>SELECT table1.Url1, table1.site1, table1.url2, table1.site2, table1.endurl, table2.keywords FROM table1 LEFT JOIN table2 ON table1.site1 = table2.keywords AND table1.site2 = table2.keywords; </code></pre> <p>want to merge all columns into single column.</p>
[ { "answer_id": 74643838, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "a = np.array([[ 0, 1, 2, 3, 4],\n [ 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19]])\n\nout = a[1:a.shape[0]-1, 1:a.shape[1]-1]\n N N = 1\na[N:a.shape[0]-N, N:a.shape[1]-N]\n array([[ 6, 7, 8],\n [11, 12, 13]])\n" }, { "answer_id": 74643869, "author": "ImotVoksim", "author_id": 17580723, "author_profile": "https://Stackoverflow.com/users/17580723", "pm_score": 0, "selected": false, "text": "arr = np.array([[0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19]])\narr[1:3, 1:4]\n def strip_func(arr, r1, r2, c1, c2):\n return(arr[r1:r2+1, c1:c2+1])\n r1 r2 c1 c2" }, { "answer_id": 74643950, "author": "Indiano", "author_id": 13309379, "author_profile": "https://Stackoverflow.com/users/13309379", "pm_score": 0, "selected": false, "text": "def fun_strip(array):\n return np.array([array[1][1:4],array[2][1:4]])\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7550189/" ]
74,643,731
<p>I am reading data from a file and the type of the data is stored as a <code>uint8_t</code> which indicates the type of data I am about to read. This is the enum corresponding to the declaration of these values.</p> <pre><code>enum DataType { kInt8, kUint16, kInt16, kUint32, kInt32, kUint64, kInt64, kFloat16, kFloat32, kFloat64 }; </code></pre> <p>I then get a function that reads the values stored in the file with the specific type, something like this:</p> <pre><code>template&lt;typename T&gt; readData(T*&amp; data, size_t numElements) { ifs.read((char*)data, sizeof(T) * numElements); } uint8_t type; ifs.read((char*)&amp;type, 1); uint32_t numElements; ids.read((char*)&amp;numElements, sizeof(uint32_t)); switch (type) { case kUint8: uint8_t* data = new uint8_t[numElements]; readData&lt;uint8_t&gt;(data, numElements); // eventually delete mem ... break; case kUint16: uint16_t* data = new int16_t[numElements]; readData&lt;uint16_t&gt;(data, numElements); // eventually delete mem ... break; case ... etc. default: break; } </code></pre> <p>I have just represented 2 cases but eventually, you'd need to do it for all types. It's a lot of code duplication and so what I'd like to do is find the actual type of the values given the enum value. For example, if the enum value was <code>kUint32</code> then the type would be <code>uint32_t</code>, etc. If I was able to do so, the code could become more compact with something like this (pseudo-code):</p> <pre><code>DataType typeFromFile = kUint32; ActualC++Type T = typeFromFile.getType(); readData&lt;T&gt;(data, numElements); </code></pre> <p>What technique could you recommend to make it work (or what alternative solution may you recommend?).</p>
[ { "answer_id": 74644030, "author": "Rulle", "author_id": 1008794, "author_profile": "https://Stackoverflow.com/users/1008794", "pm_score": 1, "selected": false, "text": "#define FOREACH_DATATYPE(OP) \\\n OP(kUint8, uint8_t) \\\n OP(kInt8, int8_t) \\\n OP(kUint16, uint16_t) \\\n OP(kInt16, int16_t)\n\n // Fill in the rest yourself\n switch switch (type) {\n#define CASE_TYPE(name, type) \\\n case name: { \\\n type* data = new type[numElements]; \\\n readData<type>(data, numElements); \\\n break;}\n FOREACH_DATATYPE(CASE_TYPE)\n#undef CASE_TYPE\n default:\n break;\n }\n" }, { "answer_id": 74644303, "author": "Nicol Bolas", "author_id": 734069, "author_profile": "https://Stackoverflow.com/users/734069", "pm_score": 2, "selected": true, "text": "variant variant<Ts> Ts unique_ptr<T[]> T variant unique_ptr variant switch/case variant_type data_array{};\n\n switch (type) {\n case kUint8:\n data_array = std::make_unique<std::uint8_t[]>(numElements);\n case kUint16:\n data_array = std::make_unique<std::uint16_t[]>(numElements);\n default:\n //error out. `break` is not an option.\n break;\n }\n\n std::visit([&](auto &arr)\n {\n using arrtype = std::remove_cvref_t<decltype(arr)>;\n readData<typename arrtype::element_type>(arr.get(), numElements);\n ///...\n }, data_array);\n\n//data_array's destructor will destroy the allocated arrays.\n" }, { "answer_id": 74661101, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 0, "selected": false, "text": "visit_nth id<type> #include <iostream>\n#include <type_traits>\n\ntemplate<typename T>\nstruct id {\n using type = T;\n};\n\ntemplate<typename... Ts>\nstruct list\n{\n static constexpr size_t size = sizeof...(Ts);\n \n template<typename T>\n static constexpr size_t index_of = -1;\n};\n\ntemplate<typename H, typename... Ts>\nstruct list<H, Ts...>\n{\npublic:\n static constexpr size_t size = sizeof...(Ts) + 1;\n\n template<typename T>\n static constexpr size_t index_of =\n std::is_same_v<H, T> ? 0 : list<Ts...>::template index_of<T> + 1;\n\n template<typename F>\n static void visit_nth(size_t n, F f)\n {\n if constexpr (size > 0) {\n if (n > 0) {\n if constexpr (size > 1) {\n list<Ts...>::visit_nth(n - 1, std::move(f));\n }\n } else {\n f(id<H>());\n }\n }\n }\n};\n\nusing DataTypes = list<int8_t, uint8_t, int16_t, uint16_t>;\n\nenum DataType\n{\n kInt8 = DataTypes::index_of<int8_t>,\n kUint8 = DataTypes::index_of<uint8_t>,\n kInt16 = DataTypes::index_of<int16_t>,\n kUint16 = DataTypes::index_of<uint16_t>\n};\n\n\n\nint main()\n{\n DataType typeFromFile = kUint8;\n DataTypes::visit_nth(typeFromFile, [&](auto type) {\n using T = typename decltype(type)::type;\n std::cout << std::is_same_v<T, uint8_t> << std::endl;\n });\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1794325/" ]
74,643,739
<p>I have the following hexadecimal string: 7609a2fed47be9131ea1b803afc517b8</p> <p>I want to convert it to hexadecimal array each element 1 byte long [76 09 a2 fe d4 7b e9 13 1e a1 b8 03 af c5 17 b8]</p> <p>then i need to convert it to decimal array.</p> <p>i tried converting it to binary then to hexadecimal again, it did not work</p>
[ { "answer_id": 74644030, "author": "Rulle", "author_id": 1008794, "author_profile": "https://Stackoverflow.com/users/1008794", "pm_score": 1, "selected": false, "text": "#define FOREACH_DATATYPE(OP) \\\n OP(kUint8, uint8_t) \\\n OP(kInt8, int8_t) \\\n OP(kUint16, uint16_t) \\\n OP(kInt16, int16_t)\n\n // Fill in the rest yourself\n switch switch (type) {\n#define CASE_TYPE(name, type) \\\n case name: { \\\n type* data = new type[numElements]; \\\n readData<type>(data, numElements); \\\n break;}\n FOREACH_DATATYPE(CASE_TYPE)\n#undef CASE_TYPE\n default:\n break;\n }\n" }, { "answer_id": 74644303, "author": "Nicol Bolas", "author_id": 734069, "author_profile": "https://Stackoverflow.com/users/734069", "pm_score": 2, "selected": true, "text": "variant variant<Ts> Ts unique_ptr<T[]> T variant unique_ptr variant switch/case variant_type data_array{};\n\n switch (type) {\n case kUint8:\n data_array = std::make_unique<std::uint8_t[]>(numElements);\n case kUint16:\n data_array = std::make_unique<std::uint16_t[]>(numElements);\n default:\n //error out. `break` is not an option.\n break;\n }\n\n std::visit([&](auto &arr)\n {\n using arrtype = std::remove_cvref_t<decltype(arr)>;\n readData<typename arrtype::element_type>(arr.get(), numElements);\n ///...\n }, data_array);\n\n//data_array's destructor will destroy the allocated arrays.\n" }, { "answer_id": 74661101, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 0, "selected": false, "text": "visit_nth id<type> #include <iostream>\n#include <type_traits>\n\ntemplate<typename T>\nstruct id {\n using type = T;\n};\n\ntemplate<typename... Ts>\nstruct list\n{\n static constexpr size_t size = sizeof...(Ts);\n \n template<typename T>\n static constexpr size_t index_of = -1;\n};\n\ntemplate<typename H, typename... Ts>\nstruct list<H, Ts...>\n{\npublic:\n static constexpr size_t size = sizeof...(Ts) + 1;\n\n template<typename T>\n static constexpr size_t index_of =\n std::is_same_v<H, T> ? 0 : list<Ts...>::template index_of<T> + 1;\n\n template<typename F>\n static void visit_nth(size_t n, F f)\n {\n if constexpr (size > 0) {\n if (n > 0) {\n if constexpr (size > 1) {\n list<Ts...>::visit_nth(n - 1, std::move(f));\n }\n } else {\n f(id<H>());\n }\n }\n }\n};\n\nusing DataTypes = list<int8_t, uint8_t, int16_t, uint16_t>;\n\nenum DataType\n{\n kInt8 = DataTypes::index_of<int8_t>,\n kUint8 = DataTypes::index_of<uint8_t>,\n kInt16 = DataTypes::index_of<int16_t>,\n kUint16 = DataTypes::index_of<uint16_t>\n};\n\n\n\nint main()\n{\n DataType typeFromFile = kUint8;\n DataTypes::visit_nth(typeFromFile, [&](auto type) {\n using T = typename decltype(type)::type;\n std::cout << std::is_same_v<T, uint8_t> << std::endl;\n });\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20564624/" ]
74,643,740
<p>i have a query that is more slow and i don't understand why. I think, there are the corrects indexes on the tables..</p> <pre><code>SELECT e.id, e.coordinate, e.lat AS latitudine, e.lon AS longitudine, e.dataora, e.indirizzo, e.dato, e.precisione_metri, e.precisione_secondi, e.precisione_invalid, e.distanza, e.velocita, es.descrizione AS evento, es.operazione, es.colore_shape, e.dato barcode, es.gestione_euristica, e.id_dispositivo FROM eventi_kml_polygon AS ekp INNER JOIN eventi AS e ON e.id=ekp.id_evento INNER JOIN sistema_eventi AS es ON es.evento=e.id_evento INNER JOIN kml_polygon AS kp ON kp.id=ekp.id_kml_polygon INNER JOIN kml AS k ON k.id=kp.id_kml INNER JOIN waypoint AS w ON w.id_kml=k.id INNER JOIN waypoint_periodi AS wp ON (wp.id_waypoint=w.id AND e.dataora BETWEEN wp.dataora_inizio AND wp.dataora_fine) INNER JOIN modelli AS m ON m.id=wp.id_modello WHERE m.id=224882 AND es.operazione IN (8,15) </code></pre> <p>The execution plan doesn't propose any index suggestion.. The record on the affected huges tables are:</p> <ul> <li>eventi: 12250946</li> <li>waypoint_periodi: 650703</li> <li>eventi_kml_polygon: 1500040</li> <li>kml_polygon: 21870</li> <li>kml: 9246</li> </ul> <p>This is the execution plan: <a href="https://www.brentozar.com/pastetheplan/?id=rJkTTEIPo" rel="nofollow noreferrer">Execution plan brentozar</a></p> <p>Who could help me please?</p> <p>I tried to analize index, tables ecc.. but i didn't find the solution.. I image that there is an index that can help my query</p>
[ { "answer_id": 74644030, "author": "Rulle", "author_id": 1008794, "author_profile": "https://Stackoverflow.com/users/1008794", "pm_score": 1, "selected": false, "text": "#define FOREACH_DATATYPE(OP) \\\n OP(kUint8, uint8_t) \\\n OP(kInt8, int8_t) \\\n OP(kUint16, uint16_t) \\\n OP(kInt16, int16_t)\n\n // Fill in the rest yourself\n switch switch (type) {\n#define CASE_TYPE(name, type) \\\n case name: { \\\n type* data = new type[numElements]; \\\n readData<type>(data, numElements); \\\n break;}\n FOREACH_DATATYPE(CASE_TYPE)\n#undef CASE_TYPE\n default:\n break;\n }\n" }, { "answer_id": 74644303, "author": "Nicol Bolas", "author_id": 734069, "author_profile": "https://Stackoverflow.com/users/734069", "pm_score": 2, "selected": true, "text": "variant variant<Ts> Ts unique_ptr<T[]> T variant unique_ptr variant switch/case variant_type data_array{};\n\n switch (type) {\n case kUint8:\n data_array = std::make_unique<std::uint8_t[]>(numElements);\n case kUint16:\n data_array = std::make_unique<std::uint16_t[]>(numElements);\n default:\n //error out. `break` is not an option.\n break;\n }\n\n std::visit([&](auto &arr)\n {\n using arrtype = std::remove_cvref_t<decltype(arr)>;\n readData<typename arrtype::element_type>(arr.get(), numElements);\n ///...\n }, data_array);\n\n//data_array's destructor will destroy the allocated arrays.\n" }, { "answer_id": 74661101, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 0, "selected": false, "text": "visit_nth id<type> #include <iostream>\n#include <type_traits>\n\ntemplate<typename T>\nstruct id {\n using type = T;\n};\n\ntemplate<typename... Ts>\nstruct list\n{\n static constexpr size_t size = sizeof...(Ts);\n \n template<typename T>\n static constexpr size_t index_of = -1;\n};\n\ntemplate<typename H, typename... Ts>\nstruct list<H, Ts...>\n{\npublic:\n static constexpr size_t size = sizeof...(Ts) + 1;\n\n template<typename T>\n static constexpr size_t index_of =\n std::is_same_v<H, T> ? 0 : list<Ts...>::template index_of<T> + 1;\n\n template<typename F>\n static void visit_nth(size_t n, F f)\n {\n if constexpr (size > 0) {\n if (n > 0) {\n if constexpr (size > 1) {\n list<Ts...>::visit_nth(n - 1, std::move(f));\n }\n } else {\n f(id<H>());\n }\n }\n }\n};\n\nusing DataTypes = list<int8_t, uint8_t, int16_t, uint16_t>;\n\nenum DataType\n{\n kInt8 = DataTypes::index_of<int8_t>,\n kUint8 = DataTypes::index_of<uint8_t>,\n kInt16 = DataTypes::index_of<int16_t>,\n kUint16 = DataTypes::index_of<uint16_t>\n};\n\n\n\nint main()\n{\n DataType typeFromFile = kUint8;\n DataTypes::visit_nth(typeFromFile, [&](auto type) {\n using T = typename decltype(type)::type;\n std::cout << std::is_same_v<T, uint8_t> << std::endl;\n });\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15661794/" ]
74,643,741
<p>I've been using some of the Linux tooling on my Windows machine for a little while now, since it comes with the git installation and it's a ton of fun to use. I've been particularly enamored with this command, which should theoretically allow me to delete all my extraneous git branches in one go:</p> <pre class="lang-bash prettyprint-override"><code>git branch | grep -v 'master' | xargs git branch -d </code></pre> <p>A while ago, however, this stopped working. Instead I get a series of error messages for each branch along the following lines:</p> <pre><code>error: branch 'extraneous-branch-1?' not found. error: branch 'extraneous-branch-2?' not found. error: branch 'extraneous-branch-3?' not found. ... </code></pre> <p>Note that the question marks are not part of my branch names - those are apparently being added somehow when the values are piped from grep to xargs. When I run xargs in interactive mode to try to see what it's actually producing, I get an output that looks like this:</p> <pre><code>git branch -d 'extraneous-branch-1'$'\r' 'extraneous-branch-2'$'\r' 'extraneous-branch-3'$'\r' ... </code></pre> <p>It seems as if grep is piping the end-of-line and carriage-return entries as part of each match, though I don't know how to prevent it from doing that. What baffles me is that I definitely remember this working before - I have no idea what would have changed. Truthfully I know barely anything about the Linux command line tools, so I wouldn't be surprised if there's something obvious I'm overlooking here. Appreciate any advice either way.</p> <p><strong>Edit</strong></p> <p>When I run <code>git branch | cat -A</code>, I get the following result:</p> <pre><code> extraneous-branch-1$ extraneous-branch-2$ extraneous-branch-3$ </code></pre>
[ { "answer_id": 74644030, "author": "Rulle", "author_id": 1008794, "author_profile": "https://Stackoverflow.com/users/1008794", "pm_score": 1, "selected": false, "text": "#define FOREACH_DATATYPE(OP) \\\n OP(kUint8, uint8_t) \\\n OP(kInt8, int8_t) \\\n OP(kUint16, uint16_t) \\\n OP(kInt16, int16_t)\n\n // Fill in the rest yourself\n switch switch (type) {\n#define CASE_TYPE(name, type) \\\n case name: { \\\n type* data = new type[numElements]; \\\n readData<type>(data, numElements); \\\n break;}\n FOREACH_DATATYPE(CASE_TYPE)\n#undef CASE_TYPE\n default:\n break;\n }\n" }, { "answer_id": 74644303, "author": "Nicol Bolas", "author_id": 734069, "author_profile": "https://Stackoverflow.com/users/734069", "pm_score": 2, "selected": true, "text": "variant variant<Ts> Ts unique_ptr<T[]> T variant unique_ptr variant switch/case variant_type data_array{};\n\n switch (type) {\n case kUint8:\n data_array = std::make_unique<std::uint8_t[]>(numElements);\n case kUint16:\n data_array = std::make_unique<std::uint16_t[]>(numElements);\n default:\n //error out. `break` is not an option.\n break;\n }\n\n std::visit([&](auto &arr)\n {\n using arrtype = std::remove_cvref_t<decltype(arr)>;\n readData<typename arrtype::element_type>(arr.get(), numElements);\n ///...\n }, data_array);\n\n//data_array's destructor will destroy the allocated arrays.\n" }, { "answer_id": 74661101, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 0, "selected": false, "text": "visit_nth id<type> #include <iostream>\n#include <type_traits>\n\ntemplate<typename T>\nstruct id {\n using type = T;\n};\n\ntemplate<typename... Ts>\nstruct list\n{\n static constexpr size_t size = sizeof...(Ts);\n \n template<typename T>\n static constexpr size_t index_of = -1;\n};\n\ntemplate<typename H, typename... Ts>\nstruct list<H, Ts...>\n{\npublic:\n static constexpr size_t size = sizeof...(Ts) + 1;\n\n template<typename T>\n static constexpr size_t index_of =\n std::is_same_v<H, T> ? 0 : list<Ts...>::template index_of<T> + 1;\n\n template<typename F>\n static void visit_nth(size_t n, F f)\n {\n if constexpr (size > 0) {\n if (n > 0) {\n if constexpr (size > 1) {\n list<Ts...>::visit_nth(n - 1, std::move(f));\n }\n } else {\n f(id<H>());\n }\n }\n }\n};\n\nusing DataTypes = list<int8_t, uint8_t, int16_t, uint16_t>;\n\nenum DataType\n{\n kInt8 = DataTypes::index_of<int8_t>,\n kUint8 = DataTypes::index_of<uint8_t>,\n kInt16 = DataTypes::index_of<int16_t>,\n kUint16 = DataTypes::index_of<uint16_t>\n};\n\n\n\nint main()\n{\n DataType typeFromFile = kUint8;\n DataTypes::visit_nth(typeFromFile, [&](auto type) {\n using T = typename decltype(type)::type;\n std::cout << std::is_same_v<T, uint8_t> << std::endl;\n });\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9182405/" ]
74,643,745
<p>I have added smartbutton in res.partner form view header that opens the current partner helpdesk tickets (helpdesk.ticket model). <a href="https://i.stack.imgur.com/3SWIh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3SWIh.png" alt="enter image description here" /></a></p> <p><strong>Smartbutton view</strong> (If i remove this code then button is removed and users can freely open partner form view)</p> <pre><code>&lt;odoo&gt; &lt;data&gt; &lt;record id=&quot;helpdesk_ticket_smart_button&quot; model=&quot;ir.ui.view&quot;&gt; &lt;field name=&quot;name&quot;&gt;partner.helpdesk.ticket.smart.buttons&lt;/field&gt; &lt;field name=&quot;model&quot;&gt;res.partner&lt;/field&gt; &lt;field name=&quot;inherit_id&quot; ref=&quot;base.view_partner_form&quot; /&gt; &lt;field name=&quot;arch&quot; type=&quot;xml&quot;&gt; &lt;div name=&quot;button_box&quot; position=&quot;inside&quot;&gt; &lt;button class=&quot;oe_stat_button&quot; type=&quot;object&quot; name=&quot;action_view_helpdesk_tickets&quot; icon=&quot;fa-ticket&quot;&gt; &lt;field string=&quot;Tickets&quot; name=&quot;helpdesk_ticket_count&quot; widget=&quot;statinfo&quot;/&gt; &lt;/button&gt; &lt;/div&gt; &lt;/field&gt; &lt;/record&gt; &lt;/data&gt; &lt;/odoo&gt; </code></pre> <p>Unfortunately now, after a non-helpdesk user tries to open any partner form he gets blocked due to Access Error. <a href="https://i.stack.imgur.com/gBts7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gBts7.png" alt="enter image description here" /></a></p> <p>What can i change so that <strong>any</strong> odoo user can open partner form view without getting blocked but only helpdesk users can see the Tickets smartbutton?</p> <p>Any help would be appreciated. Let me know if you need more information.</p>
[ { "answer_id": 74644030, "author": "Rulle", "author_id": 1008794, "author_profile": "https://Stackoverflow.com/users/1008794", "pm_score": 1, "selected": false, "text": "#define FOREACH_DATATYPE(OP) \\\n OP(kUint8, uint8_t) \\\n OP(kInt8, int8_t) \\\n OP(kUint16, uint16_t) \\\n OP(kInt16, int16_t)\n\n // Fill in the rest yourself\n switch switch (type) {\n#define CASE_TYPE(name, type) \\\n case name: { \\\n type* data = new type[numElements]; \\\n readData<type>(data, numElements); \\\n break;}\n FOREACH_DATATYPE(CASE_TYPE)\n#undef CASE_TYPE\n default:\n break;\n }\n" }, { "answer_id": 74644303, "author": "Nicol Bolas", "author_id": 734069, "author_profile": "https://Stackoverflow.com/users/734069", "pm_score": 2, "selected": true, "text": "variant variant<Ts> Ts unique_ptr<T[]> T variant unique_ptr variant switch/case variant_type data_array{};\n\n switch (type) {\n case kUint8:\n data_array = std::make_unique<std::uint8_t[]>(numElements);\n case kUint16:\n data_array = std::make_unique<std::uint16_t[]>(numElements);\n default:\n //error out. `break` is not an option.\n break;\n }\n\n std::visit([&](auto &arr)\n {\n using arrtype = std::remove_cvref_t<decltype(arr)>;\n readData<typename arrtype::element_type>(arr.get(), numElements);\n ///...\n }, data_array);\n\n//data_array's destructor will destroy the allocated arrays.\n" }, { "answer_id": 74661101, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 0, "selected": false, "text": "visit_nth id<type> #include <iostream>\n#include <type_traits>\n\ntemplate<typename T>\nstruct id {\n using type = T;\n};\n\ntemplate<typename... Ts>\nstruct list\n{\n static constexpr size_t size = sizeof...(Ts);\n \n template<typename T>\n static constexpr size_t index_of = -1;\n};\n\ntemplate<typename H, typename... Ts>\nstruct list<H, Ts...>\n{\npublic:\n static constexpr size_t size = sizeof...(Ts) + 1;\n\n template<typename T>\n static constexpr size_t index_of =\n std::is_same_v<H, T> ? 0 : list<Ts...>::template index_of<T> + 1;\n\n template<typename F>\n static void visit_nth(size_t n, F f)\n {\n if constexpr (size > 0) {\n if (n > 0) {\n if constexpr (size > 1) {\n list<Ts...>::visit_nth(n - 1, std::move(f));\n }\n } else {\n f(id<H>());\n }\n }\n }\n};\n\nusing DataTypes = list<int8_t, uint8_t, int16_t, uint16_t>;\n\nenum DataType\n{\n kInt8 = DataTypes::index_of<int8_t>,\n kUint8 = DataTypes::index_of<uint8_t>,\n kInt16 = DataTypes::index_of<int16_t>,\n kUint16 = DataTypes::index_of<uint16_t>\n};\n\n\n\nint main()\n{\n DataType typeFromFile = kUint8;\n DataTypes::visit_nth(typeFromFile, [&](auto type) {\n using T = typename decltype(type)::type;\n std::cout << std::is_same_v<T, uint8_t> << std::endl;\n });\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11638716/" ]
74,643,755
<p>Is it possible to specify the individual fields in a dict contained inside a pydantic model? I was not able to find anything but maybe I'm using the wrong keywords. I'm thinking of something like this:</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel class User(BaseModel): id: int name: str = 'Jane Doe' stats = { age: int, height: float, } </code></pre> <hr /> <p>EDIT: After some feedback I feel I need to clarify a bit some of the conditions of this and give a more complete example. What I'm looking to do is more similar to this:</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel, NonNegativeInt, NonNegativeFloat from pydantic.generics import GenericModel DataT = TypeVar('DataT') class Trait(GenericModel, Generic[DataT]): descript: str value: DataT class CharacterBarbarian(BaseModel): id: int name: str = 'Barbarok' traits = { strength: Trait[NonNegativeInt] = Trait[NonNegativeInt](descript='the force', value=18), height: Trait[NonNegativeFloat] = Trait[NonNegativeFloat](descript='tallness', value=1.8), weight: Trait[NonNegativeFloat] = Trait[NonNegativeFloat](descript='width', value=92.1), } class CharacterWizard(BaseModel): id: int name: str = 'Supremus' traits = { intelligence: Trait[NonNegativeInt] = Trait[NonNegativeInt](descript='smarts', value=16), spells: Trait[NonNegativeInt] = Trait[NonNegativeInt](descript='number of them', value=4), } SavedWizard_dict = { # Read from file for example 'id': 1234, 'name': &quot;Gandalf&quot;, 'traits': { 'intelligence': {'descript': 'smarts', 'value': 20} 'spells': {'descript': 'number of them', 'value': 100), }, } SavedWizard = CharacterWizard(**SavedWizard_dict) </code></pre> <p>So basically I'm trying to leverage the intrinsic ability of pydantic to serialize/deserialize dict/json to save and initialize my classes. At the same time, these pydantic classes are composed of a list/dict of specific versions of a generic pydantic class, but the selection of these changes from class to class.</p>
[ { "answer_id": 74643914, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 3, "selected": true, "text": "from pydantic import BaseModel\n\nclass UserStats(BaseModel):\n age: int\n height: float\n\nclass User(BaseModel):\n id: int\n name = 'Jane Doe'\n stats: UserStats\n User user = User(id=1234, stats={\"age\": 30, \"height\": 180.0})\n stats User UserStats print(user.age) # ok!\nprint(user[\"age\"]) # not ok...\n TypedDict typing_extensions typing from typing import TypedDict\nfrom pydantic import BaseModel\n\nclass UserStats(TypedDict):\n age: int\n height: float\n\nclass User(BaseModel):\n id: int\n name = 'Jane Doe'\n stats: UserStats\n\nuser = User(id=1234, stats={\"age\": 30, \"height\": 180.0})\nprint(user.stats[\"age\"]) # will work!\n UserStats User class User(BaseModel):\n id: int\n name = \"Jane Doe\"\n class Stats(TypedDict):\n age: int\n height: float\n stats: Stats\n User stats Stats TypedDict class User(BaseModel):\n id: int\n name = \"Jane Doe\"\n stats: TypedDict(\"Stats\", age=int, height=float)\n" }, { "answer_id": 74644271, "author": "Daniil Fajnberg", "author_id": 19770795, "author_profile": "https://Stackoverflow.com/users/19770795", "pm_score": 2, "selected": false, "text": "TypedDict from typing import TypedDict\nfrom pydantic import BaseModel\n\n\nclass User(BaseModel):\n id: int\n name = 'Jane Doe'\n stats: TypedDict(\"Stats\", {\"age\": int, \"height\": float})\n stats" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/638366/" ]
74,643,757
<p>I want to make 4 different ADC measurements. I want to be that those readed values are floats. After that I want to put those 4 float values in an uint8_t to send it over the function:</p> <pre><code>uint32_t ble_nus_data_send(ble_nus_t * p_nus, uint8_t * p_data, uint16_t * p_length, uint16_t conn_handle) </code></pre> <p>This minimal code works:</p> <pre><code>static void app_timer_handler(void * p_context) { uint8_t p_dat[] = &quot;hi&quot;; uint16_t len = sizeof(p_dat)-1; ret_code_t err_code = ble_nus_data_send(&amp;m_nus, p_dat, &amp;len, m_conn_handle); APP_ERROR_CHECK(err_code); } </code></pre> <p>But when I try to send a val it goes wrong:</p> <pre><code>static void app_timer_handler(void * p_context) { if(m_conn_handle != BLE_CONN_HANDLE_INVALID) { uint8_t values[20]; ret_code_t err_code; err_code = nrfx_saadc_sample_convert(0, &amp;m_sample); APP_ERROR_CHECK(err_code); float value1 = m_sample * 3.0 / 4096; sprintf((char*)values, &quot;%.2f&quot;, value1); uint16_t len = sizeof(values); err_code = ble_nus_data_send(&amp;m_nus, values, &amp;len, m_conn_handle); APP_ERROR_CHECK(err_code); } } </code></pre> <p>After getting the sample value of the ADC I will make calculations to get the voltage. I read it out with a 12-bit adc.</p> <p>The expected received output of the uint8_t must be like [float1 float2 float3 float4]. This because I want to process the values in Python and plot them in a graph.</p> <p>To receive the sended data I do use a dongle.</p> <p>I did try this:</p> <pre><code>static void app_timer_handler(void * p_context) { if(m_conn_handle != BLE_CONN_HANDLE_INVALID) { float values[4]; ret_code_t err_code; err_code = nrfx_saadc_sample_convert(0, &amp;m_sample); APP_ERROR_CHECK(err_code); values[0] = m_sample * 3.0 / 4096; err_code = nrfx_saadc_sample_convert(1, &amp;m_sample); APP_ERROR_CHECK(err_code); values[1] = m_sample * 3.0 / 4096; err_code = nrfx_saadc_sample_convert(2, &amp;m_sample); APP_ERROR_CHECK(err_code); values[2] = m_sample * 3.0 / 4096; err_code = nrfx_saadc_sample_convert(3, &amp;m_sample); APP_ERROR_CHECK(err_code); values[3] = m_sample * 3.0 / 4096; uint16_t len = sizeof(values); err_code = ble_nus_data_send(&amp;m_nus, (uint8_t*)values, &amp;len, m_conn_handle); APP_ERROR_CHECK(err_code); } } </code></pre> <p><a href="https://i.stack.imgur.com/NJVKN.png" rel="nofollow noreferrer">Received values1</a></p> <p>And also tried this:</p> <pre><code>static void app_timer_handler(void * p_context) { if(m_conn_handle != BLE_CONN_HANDLE_INVALID) { uint8_t values[4]; ret_code_t err_code; err_code = nrfx_saadc_sample_convert(0, &amp;m_sample); APP_ERROR_CHECK(err_code); float value1 = m_sample * 3.0 / 4096; err_code = nrfx_saadc_sample_convert(1, &amp;m_sample); APP_ERROR_CHECK(err_code); float value2 = m_sample * 3.0 / 4096; err_code = nrfx_saadc_sample_convert(2, &amp;m_sample); APP_ERROR_CHECK(err_code); float value3 = m_sample * 3.0 / 4096; err_code = nrfx_saadc_sample_convert(3, &amp;m_sample); APP_ERROR_CHECK(err_code); float value4 = m_sample * 3.0 / 4096; sprintf(values, &quot;%.2f %.2f %.2f %.2f\n&quot;, value1, value2, value3, value4); uint16_t len = sizeof(values); err_code = ble_nus_data_send(&amp;m_nus, (uint8_t*)values, &amp;len, m_conn_handle); APP_ERROR_CHECK(err_code); } } </code></pre> <p><a href="https://i.stack.imgur.com/1jUkY.png" rel="nofollow noreferrer">Received values2</a></p> <p>Both ways didn't worked out for the output.</p> <p>The output expected on Python is [val1 val2 val3 val4]. So the values can be seperated.</p> <p>This is the function that handles the received data on the dongle.</p> <pre><code>static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len) { bsp_board_led_invert(LED_BLE_NUS_RX); NRF_LOG_DEBUG(&quot;Received data from BLE NUS. Writing data on CDC ACM.&quot;); NRF_LOG_HEXDUMP_DEBUG(p_data, data_len); memcpy(m_nus_data_array, p_data, data_len); // Add endline characters uint16_t length = data_len; if (length + sizeof(ENDLINE_STRING) &lt; BLE_NUS_MAX_DATA_LEN) { memcpy(m_nus_data_array + length, ENDLINE_STRING, sizeof(ENDLINE_STRING)); length += sizeof(ENDLINE_STRING); } // Send data through CDC ACM ret_code_t ret = app_usbd_cdc_acm_write(&amp;m_app_cdc_acm, m_nus_data_array, length); if(ret != NRF_SUCCESS) { NRF_LOG_INFO(&quot;CDC ACM unavailable, data received: %s&quot;, m_nus_data_array); } } </code></pre> <p>The received values are random chars. I think this might be because the receiving function. Do I have to make changes there or somewhere else?</p>
[ { "answer_id": 74643914, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 3, "selected": true, "text": "from pydantic import BaseModel\n\nclass UserStats(BaseModel):\n age: int\n height: float\n\nclass User(BaseModel):\n id: int\n name = 'Jane Doe'\n stats: UserStats\n User user = User(id=1234, stats={\"age\": 30, \"height\": 180.0})\n stats User UserStats print(user.age) # ok!\nprint(user[\"age\"]) # not ok...\n TypedDict typing_extensions typing from typing import TypedDict\nfrom pydantic import BaseModel\n\nclass UserStats(TypedDict):\n age: int\n height: float\n\nclass User(BaseModel):\n id: int\n name = 'Jane Doe'\n stats: UserStats\n\nuser = User(id=1234, stats={\"age\": 30, \"height\": 180.0})\nprint(user.stats[\"age\"]) # will work!\n UserStats User class User(BaseModel):\n id: int\n name = \"Jane Doe\"\n class Stats(TypedDict):\n age: int\n height: float\n stats: Stats\n User stats Stats TypedDict class User(BaseModel):\n id: int\n name = \"Jane Doe\"\n stats: TypedDict(\"Stats\", age=int, height=float)\n" }, { "answer_id": 74644271, "author": "Daniil Fajnberg", "author_id": 19770795, "author_profile": "https://Stackoverflow.com/users/19770795", "pm_score": 2, "selected": false, "text": "TypedDict from typing import TypedDict\nfrom pydantic import BaseModel\n\n\nclass User(BaseModel):\n id: int\n name = 'Jane Doe'\n stats: TypedDict(\"Stats\", {\"age\": int, \"height\": float})\n stats" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20656617/" ]
74,643,760
<p>I am trying to get all dupicated observations. I was looking but all solutions seems to give for columns. Is it possible get the entire rows?</p> <p>My dataset looks like this</p> <pre><code>structure(list(CrimeId = c(160903280L, 160912272L, 160912590L, 160912801L, 160912811L, 160913003L), OriginalCrimeTypeName = c(&quot;Assault / Battery&quot;, &quot;Homeless Complaint&quot;, &quot;Susp Info&quot;, &quot;Report&quot;, &quot;594&quot;, &quot;Ref'd&quot;), OffenseDate = c(&quot;2016-03-30T00:00:00&quot;, &quot;2016-03-31T00:00:00&quot;, &quot;2016-03-31T00:00:00&quot;, &quot;2016-03-31T00:00:00&quot;, &quot;2016-03-31T00:00:00&quot;, &quot;2016-03-31T00:00:00&quot;), CallTime = c(&quot;18:42&quot;, &quot;15:31&quot;, &quot;16:49&quot;, &quot;17:38&quot;, &quot;17:42&quot;, &quot;18:29&quot;), CallDateTime = c(&quot;2016-03-30T18:42:00&quot;, &quot;2016-03-31T15:31:00&quot;, &quot;2016-03-31T16:49:00&quot;, &quot;2016-03-31T17:38:00&quot;, &quot;2016-03-31T17:42:00&quot;, &quot;2016-03-31T18:29:00&quot;), Disposition = c(&quot;REP&quot;, &quot;GOA&quot;, &quot;GOA&quot;, &quot;GOA&quot;, &quot;REP&quot;, &quot;GOA&quot;), Address = c(&quot;100 Block Of Chilton Av&quot;, &quot;2300 Block Of Market St&quot;, &quot;2300 Block Of Market St&quot;, &quot;500 Block Of 7th St&quot;, &quot;Beale St/bryant St&quot;, &quot;16th St/pond St&quot;), City = c(&quot;San Francisco&quot;, &quot;San Francisco&quot;, &quot;San Francisco&quot;, &quot;San Francisco&quot;, &quot;San Francisco&quot;, &quot;San Francisco&quot;), State = c(&quot;CA&quot;, &quot;CA&quot;, &quot;CA&quot;, &quot;CA&quot;, &quot;CA&quot;, &quot;CA&quot;), AgencyId = c(&quot;1&quot;, &quot;1&quot;, &quot;1&quot;, &quot;1&quot;, &quot;1&quot;, &quot;1&quot;), Range = c(NA, NA, NA, NA, NA, NA), AddressType = c(&quot;Premise Address&quot;, &quot;Premise Address&quot;, &quot;Premise Address&quot;, &quot;Premise Address&quot;, &quot;Intersection&quot;, &quot;Intersection&quot; )), row.names = c(NA, 6L), class = &quot;data.frame&quot;) </code></pre>
[ { "answer_id": 74643914, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 3, "selected": true, "text": "from pydantic import BaseModel\n\nclass UserStats(BaseModel):\n age: int\n height: float\n\nclass User(BaseModel):\n id: int\n name = 'Jane Doe'\n stats: UserStats\n User user = User(id=1234, stats={\"age\": 30, \"height\": 180.0})\n stats User UserStats print(user.age) # ok!\nprint(user[\"age\"]) # not ok...\n TypedDict typing_extensions typing from typing import TypedDict\nfrom pydantic import BaseModel\n\nclass UserStats(TypedDict):\n age: int\n height: float\n\nclass User(BaseModel):\n id: int\n name = 'Jane Doe'\n stats: UserStats\n\nuser = User(id=1234, stats={\"age\": 30, \"height\": 180.0})\nprint(user.stats[\"age\"]) # will work!\n UserStats User class User(BaseModel):\n id: int\n name = \"Jane Doe\"\n class Stats(TypedDict):\n age: int\n height: float\n stats: Stats\n User stats Stats TypedDict class User(BaseModel):\n id: int\n name = \"Jane Doe\"\n stats: TypedDict(\"Stats\", age=int, height=float)\n" }, { "answer_id": 74644271, "author": "Daniil Fajnberg", "author_id": 19770795, "author_profile": "https://Stackoverflow.com/users/19770795", "pm_score": 2, "selected": false, "text": "TypedDict from typing import TypedDict\nfrom pydantic import BaseModel\n\n\nclass User(BaseModel):\n id: int\n name = 'Jane Doe'\n stats: TypedDict(\"Stats\", {\"age\": int, \"height\": float})\n stats" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19110567/" ]
74,643,795
<p>I have this sed command which add's 3 zero's to an id (this occurs only if the id is 13 characters long):</p> <pre><code>sed 's/^\(.\{14\}\)\([0-9]\{13\}[^0-9]\)/\1000\2/' file </code></pre> <p>My input looks like this:</p> <pre><code>A:AAAA:AA: :A:**0123456789ABC **:AAA:AAA : :AA: : : </code></pre> <p>And my output is this one:</p> <pre><code>A:AAAA:AA: :A:**0000123456789ABC **:AAA:AAA : :AA: : : </code></pre> <p>I want to get rid off the 3 whitespaces after the id number. I can't delete the entire column because I have different data on other records so I want to delete the spaces just in the records/lines I expanded previously. So maybe I just need to add something to the existing command. As you can see there are other whitespaces on the record, but I just want to delete the ones next to de ID(bold one).</p> <p>I only found ways to delete entire columns, but I haven't been able to find a way to delete specific characters.</p>
[ { "answer_id": 74643968, "author": "choroba", "author_id": 1030675, "author_profile": "https://Stackoverflow.com/users/1030675", "pm_score": 2, "selected": false, "text": "\\) sed 's/^\\(.\\{14\\}\\)\\([0-9]\\{13\\}[^0-9]\\) /\\1000\\2/'\n [0-9] [0-9A-C]" }, { "answer_id": 74644125, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 2, "selected": true, "text": "sed 's/^\\(.\\{14\\}\\)\\([[:alnum:]]\\{13\\}\\)[[:space:]]*:/\\1000\\2:/' file\n #!/bin/bash\ns='A:AAAA:AA: :A:0123456789ABC :AAA:AAA : :AA: : :'\nsed 's/^\\(.\\{14\\}\\)\\([[:alnum:]]\\{13\\}\\)[[:space:]]*:/\\1000\\2:/' <<< \"$s\"\n A:AAAA:AA: :A:0000123456789ABC:AAA:AAA : :AA: : :\n [[:alnum:]]\\{13\\} [[:space:]]*: : :" }, { "answer_id": 74645942, "author": "Gary_W", "author_id": 2543416, "author_profile": "https://Stackoverflow.com/users/2543416", "pm_score": 0, "selected": false, "text": "awk $ awk -F ':' 'BEGIN { OFS=\":\"}{ gsub(\" \", \"\", $6) };{if(length($6) == 13)$6=\"000\"$6;print $0}' file.txt\nA:AAAA:AA: :A:0000123456789ABC:AAA:AAA : :AA: : :\n$\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069611/" ]
74,643,853
<p>I have would like to add a vector to a column, without specifying the other columns. I have example data as follows.</p> <pre><code>library(data.table) dat &lt;- fread(&quot;A B C D one 2 three four two 3 NA one&quot;) vector_to_add &lt;- c(&quot;five&quot;, &quot;six&quot;) </code></pre> <p>Desired ouput:</p> <pre><code>out &lt;- fread(&quot;A B C D one 2 three four two 3 NA one NA NA five NA NA NA six NA&quot;) </code></pre> <p>I saw some answers using an approach where vectors are used to rowbind:</p> <pre><code>row3 &lt; c(NA, NA, &quot;five&quot;, NA) </code></pre> <p>I would however like to find a solution in which I do not have specify the whole row.</p> <p><strong>EDIT</strong>: Shortly after posting I realised that it would probably be easiest to take an existing row, make the row <code>NA</code>, and replace the value in the column where the vector would be added, for each entry in the vector. This is however still quite a cumbersome solution I guess.</p>
[ { "answer_id": 74643947, "author": "benbelo", "author_id": 9942314, "author_profile": "https://Stackoverflow.com/users/9942314", "pm_score": 0, "selected": false, "text": " library(data.table)\n\ndat <- fread(\"A B C D\n one 2 three four\n two 3 NA one\")\n\nvector_to_add <- c(\"five\", \"six\")\n\n# Create a new vector with the values to add to the data table\nnew_vector <- c(NA, NA, vector_to_add[1], NA)\n\n# Use rbindlist() to append the new vector to the data table\nout <- rbindlist(list(dat, new_vector))\n\n# Add the second value from the vector to the data table\nout <- rbindlist(list(out, c(NA, NA, vector_to_add[2], NA)))\n A B C D\n1: one 2 three four\n2: two 3 NA one\n3: NA NA five NA\n4: NA NA six NA\n" }, { "answer_id": 74644073, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 4, "selected": true, "text": "rbind df_to_add <- data.frame(C=c(\"five\", \"six\"))\nrbind(dat, df_to_add, fill=TRUE)\n A B C D\n1: one 2 three four\n2: two 3 <NA> one\n3: <NA> NA five <NA>\n4: <NA> NA six <NA>\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8071608/" ]
74,643,856
<p>I have table with few columns but I am interested in two of them:</p> <ol> <li>name</li> <li>type - it can be one of tree values: 1, 2, 3</li> </ol> <p>All I want to create is a table where in first column I will SELECT value from column name where type = 1, in second column value from column name where type = 2, in last column value from column name where type = 3</p> <p>I tried to create a subquery (I want to do it via CTE) but I got an error about the subquery returns more than 1 value. I tried something with case clause but its not working anyway. I was thinking about UNION it but I am not sure.<br /> This is how the basic table looks like:</p> <pre><code>SELECT name, type FROM table1 </code></pre> <p>Table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">name</th> <th style="text-align: center;">type</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Product1</td> <td style="text-align: center;">1</td> </tr> <tr> <td style="text-align: left;">Product2</td> <td style="text-align: center;">2</td> </tr> <tr> <td style="text-align: left;">Product3</td> <td style="text-align: center;">1</td> </tr> <tr> <td style="text-align: left;">Product4</td> <td style="text-align: center;">3</td> </tr> </tbody> </table> </div> <p>And how I want to see SELECT it:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Product with type 1</th> <th style="text-align: center;">Product with type 2</th> <th style="text-align: center;">Product with type 3</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Product1</td> <td style="text-align: center;">Product9</td> <td style="text-align: center;">Product33</td> </tr> <tr> <td style="text-align: left;">Product5</td> <td style="text-align: center;">Product11</td> <td style="text-align: center;">Product41</td> </tr> <tr> <td style="text-align: left;">Product3</td> <td style="text-align: center;">Product17</td> <td style="text-align: center;">Product22</td> </tr> <tr> <td style="text-align: left;">Product7</td> <td style="text-align: center;">Product20</td> <td style="text-align: center;">Product23</td> </tr> </tbody> </table> </div> <p>I just don't know how to show values with where type = 1 as one column, type = 2 as second column and type =3 as third.</p>
[ { "answer_id": 74644229, "author": "Ali Enes İşbilen", "author_id": 16260639, "author_profile": "https://Stackoverflow.com/users/16260639", "pm_score": 2, "selected": true, "text": "SELECT\n IF(type=1, name, NULL) as \"Product with type 1\",\n IF(type=2, name, NULL) as \"Product with type 2\",\n IF(type=3, name, NULL) as \"Product with type 3\"\nFROM table1\n SELECT\n CASE WHEN type=1 THEN name ELSE NULL END as \"Product with type 1\",\n CASE WHEN type=2 THEN name ELSE NULL END as \"Product with type 2\",\n CASE WHEN type=3 THEN name ELSE NULL END as \"Product with type 3\"\nFROM table1\n" }, { "answer_id": 74644444, "author": "William Alvarez", "author_id": 19950987, "author_profile": "https://Stackoverflow.com/users/19950987", "pm_score": 0, "selected": false, "text": "SELECT CASE WHEN type = 1 THEN name ELSE NULL END\n , CASE WHEN type = 2 THEN name ELSE NULL END\n , CASE WHEN type = 3 THEN name ELSE NULL END\nFROM table1\nenter code here\n SELECT [1], [2], [3], [4], [5] FROM table1 PIVOT(MAX(name) FOR type IN ([1], [2], [3], [4], [5])) AS P\n" }, { "answer_id": 74649156, "author": "Jeff Moden", "author_id": 313265, "author_profile": "https://Stackoverflow.com/users/313265", "pm_score": 1, "selected": false, "text": "--===== Create some Readily Consumable Test Data.\n -- This is NOT a part of the solution.\n -- We're just creating test data here.\n -- Changed one \"type\" to show how unequal columns are handled.\n SELECT *\n INTO #table1\n FROM (VALUES\n ('Product1' ,1)\n ,('Product3' ,1)\n ,('Product5' ,1)\n ,('Product7' ,1)\n ,('Product9' ,2)\n ,('Product11',2)\n ,('Product17',2)\n ,('Product20',2)\n ,('Product22',2) --Changed type here\n ,('Product23',3)\n ,('Product33',3)\n ,('Product41',3)\n )v(name,type)\n;\n--===== Solve the problem with a classic CROSSTAB.\n -- \"Normal\" sort assumed. If you want 2 part alpha-numeric sort, \n -- then post back in the comments on this post.\n WITH cteEnumerate AS\n(\n SELECT *, RowNum = ROW_NUMBER() OVER (PARTITION BY type ORDER BY name)\n FROM #Table1\n)\n SELECT [Product with Type 1] = MAX(IIF(type = 1,name,''))\n ,[Product with Type 2] = MAX(IIF(type = 2,name,''))\n ,[Product with Type 3] = MAX(IIF(type = 3,name,''))\n FROM cteEnumerate\n GROUP BY RowNum\n;\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9509739/" ]
74,643,861
<p>I wrote a script which count number of lines in each file:</p> <pre><code>todays_day=$(date +%d) if ((todays_day==1)); then month=&quot;$(date --date='1 day ago' +%y%m)&quot; else month=&quot;$(date +%y%m)&quot; fi for catalog in $(find ./ -type d -name &quot;$month&quot;) do sum=0 find $catalog -type f -name &quot;*.z&quot; | while read FN do sum=$((sum+$(zcat $FN | awk 1 | wc -l))) echo &quot;no of lines $sum;source $(find $catalog -type d );data $(date +&quot;%d-%m-%Y %T&quot;)&quot; done done </code></pre> <p>Now it accumulate number of lines and shows in result</p> <pre><code>no of lines 3;source ./AXE/CNA5/LBN/2211;data 01-12-2022 17:35:49 no of lines 6;source ./AXE/CNA5/LBN/2211;data 01-12-2022 17:35:50 no of lines 9;source ./AXE/CNA5/LBN/2211;data 01-12-2022 17:35:50 no of lines 13;source ./AXE/CNA5/LBN/2211;data 01-12-2022 17:35:51 no of lines 3;source ./AXE/TELLIN/2211;data 01-12-2022 17:35:51 no of lines 7;source ./AXE/TELLIN/2211;data 01-12-2022 17:35:51 </code></pre> <p>But it must show</p> <p><code>no of lines 13;source ./AXE/CNA5/LBN/2211;data 01-12-2022 17:35:51</code> <code>no of lines 7;source ./AXE/TELLIN/2211;data 01-12-2022 17:35:51</code></p> <p>How can i fix it?</p> <p>I read <a href="https://stackoverflow.com/questions/450799/shell-command-to-sum-integers-one-per-line">Shell command to sum integers, one per line?</a> but it did not help me . I expecting someone show me how can i change my code</p>
[ { "answer_id": 74645023, "author": "Paul Hodges", "author_id": 8656552, "author_profile": "https://Stackoverflow.com/users/8656552", "pm_score": 0, "selected": false, "text": "todays_day=$(date +%d) \nif ((todays_day==1)); then\n month=\"$(date --date='1 day ago' +%y%m)\"\nelse\n month=\"$(date +%y%m)\"\nfi\n month=\"$(date --date='1 day ago' +%y%m)\"\n month=\"$(date --date='1 day ago' +%y%m)\"\nwhile read catalog \ndo sum=0\n while read lines \n do ((sum+=lines))\n done < <( zgrep -ch . \"$catalog/*.z\" )\n echo \"no of lines $sum;source $catalog;data $(date +\"%d-%m-%Y %T\")\"\ndone < <(find ./ -type d -name \"$month\" )\n find for catalog in ./AXE/*/$month\n shopt -s globstar\nfor catalog in ./AXE/**/$month\n find #!/bin/bash\nmonth=\"$(date --date='1 day ago' +%y%m)\" # sums previous month on the 1st\nfor catalog in ./AXE/*/$month # processes each $month dir\ndo sum=0 # reinit sum for each dir\n while read lines # lines is the count per file\n do ((sum+=lines)) # sum the files in the dir\n done < <( zgrep -ch . \"$catalog/*.z\" ) # zgrep is your friend\n echo \"no of lines $sum;source $catalog;data $(date +\"%d-%m-%Y %T\")\"\ndone \n shopt -s globstar\nfor catalog in ./AXE/**/$month\n #!/bin/bash\nshopt -s globstar # allow ** for arbitrary depth\nmonth=\"$(date --date='1 day ago' +%y%m)\" # sums previous month on the 1st\nfor catalog in ./AXE/**/$month/ # / at the end gets dirs only\ndo sum=0 # reinit sum for each dir\n while read lines # lines is the count per file\n do ((sum+=lines)) # sum the files in the dir\n done < <( zgrep -ch . \"${catalog}*.z\" ) # / is part of $catalog\n echo \"no of lines $sum;source $catalog;data $(date +\"%d-%m-%Y %T\")\"\ndone \n" }, { "answer_id": 74654560, "author": "Kid Jeremy", "author_id": 20623337, "author_profile": "https://Stackoverflow.com/users/20623337", "pm_score": -1, "selected": false, "text": "month=\"$(date --date='1 day ago' +%y%m)\"\nwhile read catalog \ndo\n sum=0\n while read lines \n do ((sum+=lines))\n echo $lines\n done < <( zgrep -ch . \"$catalog\")\n echo \"no of lines $sum;source $catalog;data $(date +\"%d-%m-%Y %T\")\"\ndone < <(find $(find ./ -type d -name \"$month\" ) -type f -name \"*.z\")\n\nit shows\n\n13\nno of lines 13;source ./AXE/CNA5/LBN/2212/3.z;data 02-12-2022 13:45:33\n13\nno of lines 13;source ./AXE/CNA5/LBN/2212/33.z;data 02-12-2022 13:45:34\n13\nno of lines 13;source ./AXE/CNA5/LBN/2212/333.z;data 02-12-2022 13:45:34\n14\nno of lines 14;source ./AXE/CNA5/LBN/2212/4.z;data 02-12-2022 13:45:35\n13\nno of lines 13;source ./AXE/TELLIN/2212/33.z;data 02-12-2022 13:45:36\n14\nno of lines 14;source ./AXE/TELLIN/2212/4.z;data 02-12-2022 13:45:36\n\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20623337/" ]
74,643,867
<p>I need to create a Google Tag Manager Javascript function that would return a label (group label) from a var entry that is a number (id of the group) I created this function but it doesn't work (returns undefined) I'm really new with Javascript so I don't understand what is wrong.</p> <pre><code>function client_group_name(id_client_group) { var id_client_group = {{CONTEXT - User / Group / ID Default Group}}; //this is my GTM variable , numeric could take value 3, 5, 6 ,7 ,8 ,9 ,10 ,11 switch(id_client_group) { case &quot;3&quot; : value = &quot;B2C&quot;; break; case &quot;5&quot; : value = 'B2B Entreprises'; break; case &quot;6&quot;: case &quot;7&quot;: case &quot;8&quot;: case &quot;9&quot;: case &quot;10&quot;: case &quot;11&quot;: value = 'B2B Café, Hôtel, Restaurant - CHR' break; } return value; } </code></pre> <p>Google tag Manager Javascript functions need a function () and return statements to work. Thanks for your help. Best regards.</p>
[ { "answer_id": 74645023, "author": "Paul Hodges", "author_id": 8656552, "author_profile": "https://Stackoverflow.com/users/8656552", "pm_score": 0, "selected": false, "text": "todays_day=$(date +%d) \nif ((todays_day==1)); then\n month=\"$(date --date='1 day ago' +%y%m)\"\nelse\n month=\"$(date +%y%m)\"\nfi\n month=\"$(date --date='1 day ago' +%y%m)\"\n month=\"$(date --date='1 day ago' +%y%m)\"\nwhile read catalog \ndo sum=0\n while read lines \n do ((sum+=lines))\n done < <( zgrep -ch . \"$catalog/*.z\" )\n echo \"no of lines $sum;source $catalog;data $(date +\"%d-%m-%Y %T\")\"\ndone < <(find ./ -type d -name \"$month\" )\n find for catalog in ./AXE/*/$month\n shopt -s globstar\nfor catalog in ./AXE/**/$month\n find #!/bin/bash\nmonth=\"$(date --date='1 day ago' +%y%m)\" # sums previous month on the 1st\nfor catalog in ./AXE/*/$month # processes each $month dir\ndo sum=0 # reinit sum for each dir\n while read lines # lines is the count per file\n do ((sum+=lines)) # sum the files in the dir\n done < <( zgrep -ch . \"$catalog/*.z\" ) # zgrep is your friend\n echo \"no of lines $sum;source $catalog;data $(date +\"%d-%m-%Y %T\")\"\ndone \n shopt -s globstar\nfor catalog in ./AXE/**/$month\n #!/bin/bash\nshopt -s globstar # allow ** for arbitrary depth\nmonth=\"$(date --date='1 day ago' +%y%m)\" # sums previous month on the 1st\nfor catalog in ./AXE/**/$month/ # / at the end gets dirs only\ndo sum=0 # reinit sum for each dir\n while read lines # lines is the count per file\n do ((sum+=lines)) # sum the files in the dir\n done < <( zgrep -ch . \"${catalog}*.z\" ) # / is part of $catalog\n echo \"no of lines $sum;source $catalog;data $(date +\"%d-%m-%Y %T\")\"\ndone \n" }, { "answer_id": 74654560, "author": "Kid Jeremy", "author_id": 20623337, "author_profile": "https://Stackoverflow.com/users/20623337", "pm_score": -1, "selected": false, "text": "month=\"$(date --date='1 day ago' +%y%m)\"\nwhile read catalog \ndo\n sum=0\n while read lines \n do ((sum+=lines))\n echo $lines\n done < <( zgrep -ch . \"$catalog\")\n echo \"no of lines $sum;source $catalog;data $(date +\"%d-%m-%Y %T\")\"\ndone < <(find $(find ./ -type d -name \"$month\" ) -type f -name \"*.z\")\n\nit shows\n\n13\nno of lines 13;source ./AXE/CNA5/LBN/2212/3.z;data 02-12-2022 13:45:33\n13\nno of lines 13;source ./AXE/CNA5/LBN/2212/33.z;data 02-12-2022 13:45:34\n13\nno of lines 13;source ./AXE/CNA5/LBN/2212/333.z;data 02-12-2022 13:45:34\n14\nno of lines 14;source ./AXE/CNA5/LBN/2212/4.z;data 02-12-2022 13:45:35\n13\nno of lines 13;source ./AXE/TELLIN/2212/33.z;data 02-12-2022 13:45:36\n14\nno of lines 14;source ./AXE/TELLIN/2212/4.z;data 02-12-2022 13:45:36\n\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7334566/" ]
74,643,882
<p>I have 2 branches: 4 and 5, which represent 4 and 5 versions of my application (5 is continuation of 4). By my fault I created new branch from branch 5 (instead of 4) and do one commit. How to change my branch in that way: ostensibly I created my branch from branch 4 and added one commit?</p> <p>Now:</p> <pre><code>4 -&gt; \ 5 -&gt; \ my branch with one commit -&gt; </code></pre> <p>I want:</p> <pre><code> my branch with one commit -&gt; / 4 -&gt; \ 5 -&gt; </code></pre>
[ { "answer_id": 74644025, "author": "eftshift0", "author_id": 2437508, "author_profile": "https://Stackoverflow.com/users/2437508", "pm_score": 3, "selected": true, "text": "git rebase 5 my-branch --onto 4\n" }, { "answer_id": 74649885, "author": "tymtam", "author_id": 581076, "author_profile": "https://Stackoverflow.com/users/581076", "pm_score": 1, "selected": false, "text": "rebase --onto o---o---o---o---o master\n \\\n o---o---o---o---o next\n \\\n o---o---o topic\n o---o---o---o---o master\n | \\\n | o'--o'--o' topic\n \\\n o---o---o---o---o next\n git rebase --onto master next topic > git checkout 4 \n> git cherry-pick commitX\n > git reset HEAD~1 --hard > git revert commitX" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19130076/" ]
74,643,924
<p>When i try to clone with ssh eg: <code>git@test.company.com:service/test.git</code> i get a request password for user <code>git@test.company.com</code> yet when i try the same thing with the http git <code>http://test.company.com:service/test.git</code> i get asked shh certificate <strong>userName</strong>,</p> <p>why is that? and how can i make ssh request my actual user rather than <code>git@test.company.com</code></p> <p>I have tried configuring using <code>git config --global</code> commands to setup my username and password but still no avail.</p>
[ { "answer_id": 74644025, "author": "eftshift0", "author_id": 2437508, "author_profile": "https://Stackoverflow.com/users/2437508", "pm_score": 3, "selected": true, "text": "git rebase 5 my-branch --onto 4\n" }, { "answer_id": 74649885, "author": "tymtam", "author_id": 581076, "author_profile": "https://Stackoverflow.com/users/581076", "pm_score": 1, "selected": false, "text": "rebase --onto o---o---o---o---o master\n \\\n o---o---o---o---o next\n \\\n o---o---o topic\n o---o---o---o---o master\n | \\\n | o'--o'--o' topic\n \\\n o---o---o---o---o next\n git rebase --onto master next topic > git checkout 4 \n> git cherry-pick commitX\n > git reset HEAD~1 --hard > git revert commitX" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20657479/" ]
74,643,982
<p>I have a string and an array and I want to loop them both to see if the string is inside the array and if the string is found in the array it should respond true</p> <pre><code>const string = papper const array = [book sissors, apron, tape, paper] </code></pre> <p>How do I do it?</p> <p>I tried</p> <pre><code>const intersection = string.filter(element =&gt; arary.includes(element)); if(intersection) return res.status(400).send('user already exist in group') </code></pre>
[ { "answer_id": 74644135, "author": "Saif", "author_id": 4777670, "author_profile": "https://Stackoverflow.com/users/4777670", "pm_score": 1, "selected": false, "text": "Array.prototype.includes() const string = \"paper\";\nconst array = [\"book\", \"scissors\", \"apron\", \"tape\", \"paper\"];\n\nif (array.includes(string)) {\n console.log(\"String found in array\");\n} else {\n console.log(\"String not found in array\");\n}\n\n Array.prototype.includes() for const string = \"paper\";\nconst array = [\"book\", \"scissors\", \"apron\", \"tape\", \"paper\"];\n\nlet found = false;\nfor (const element of array) {\n if (element === string) {\n found = true;\n break;\n }\n}\n\nif (found) {\n console.log(\"String found in array\");\n} else {\n console.log(\"String not found in array\");\n}\n" }, { "answer_id": 74644421, "author": "Zola", "author_id": 2977188, "author_profile": "https://Stackoverflow.com/users/2977188", "pm_score": 0, "selected": false, "text": " const string = \"papper\";\n const Myarray = [\"book\", \"sissors\", \"apron\", \"tape\", \"paper\"];\n var intersection = Myarray.includes(string);\n alert(intersection);\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20657529/" ]
74,643,983
<p>In my SQL server I run</p> <pre><code>SELECT HashBytes('MD5', CONCAT('A',convert(nvarchar,123),'456')) as mycol </code></pre> <p>and get</p> <pre><code>0xC2E6DDD93A5E4A4FEC8162D4847BD3AA </code></pre> <p>In Oracle I run</p> <pre><code>select standard_hash(concat('A',concat(cast('123' as nvarchar2(255)),'456')), 'MD5') from dual; </code></pre> <p>but I get</p> <pre><code>0x687A57C778D4AC73D90F1EB9290ED283 </code></pre> <p>What do I wrong in Oracle. I want to have the same output!</p>
[ { "answer_id": 74644135, "author": "Saif", "author_id": 4777670, "author_profile": "https://Stackoverflow.com/users/4777670", "pm_score": 1, "selected": false, "text": "Array.prototype.includes() const string = \"paper\";\nconst array = [\"book\", \"scissors\", \"apron\", \"tape\", \"paper\"];\n\nif (array.includes(string)) {\n console.log(\"String found in array\");\n} else {\n console.log(\"String not found in array\");\n}\n\n Array.prototype.includes() for const string = \"paper\";\nconst array = [\"book\", \"scissors\", \"apron\", \"tape\", \"paper\"];\n\nlet found = false;\nfor (const element of array) {\n if (element === string) {\n found = true;\n break;\n }\n}\n\nif (found) {\n console.log(\"String found in array\");\n} else {\n console.log(\"String not found in array\");\n}\n" }, { "answer_id": 74644421, "author": "Zola", "author_id": 2977188, "author_profile": "https://Stackoverflow.com/users/2977188", "pm_score": 0, "selected": false, "text": " const string = \"papper\";\n const Myarray = [\"book\", \"sissors\", \"apron\", \"tape\", \"paper\"];\n var intersection = Myarray.includes(string);\n alert(intersection);\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3579222/" ]
74,643,986
<h1>What I need</h1> <p>I have a data structure <code>Tree</code> with two levels of proxies one for <code>Branch</code> and a more detailed <code>Leaf</code>.</p> <p>Here is a MCVE:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;vector&gt; #include &lt;iostream&gt; class Tree { public: class Leaf; class Branch { public: Branch(Tree* tree, int branch_id) : tree_(tree), branch_id_(branch_id) {}; Leaf leaf(int leaf_id) { return Leaf{ tree_, branch_id_, leaf_id }; } float thickness() const { return tree_-&gt;branch_thickness_[branch_id_]; } void set_thickness(float thickness) { tree_-&gt;branch_thickness_[branch_id_] = thickness; } private: Tree* tree_; int branch_id_; }; class Leaf { public: Leaf(Tree* tree, int branch_id, int leaf_id) : tree_(tree), branch_id_(branch_id), leaf_id_(leaf_id) {}; Branch branch() { return Branch{ tree_, branch_id_ }; } float color() const { return tree_-&gt;leaf_color_[branch_id_][leaf_id_]; } void set_color(float color) { tree_-&gt;leaf_color_[branch_id_][leaf_id_] = color; } private: Tree* tree_; int branch_id_; int leaf_id_; }; Branch branch(int branch_id) { return Branch{ this, branch_id }; } Branch branch(int branch_id) const { // Compile error: // candidate constructor not viable: 1st argument ('const Tree *') would lose const qualifier return Branch{ this, branch_id }; } private: std::vector&lt;float&gt; branch_thickness_{ 0.5 }; std::vector&lt;std::vector&lt;float&gt;&gt; leaf_color_{ {0.2, 0.4} }; }; void demo() { Tree tree; Tree::Branch branch = tree.branch(0); Tree::Leaf leaf = branch.leaf(1); std::cout &lt;&lt; &quot;Branch Thickness &quot; &lt;&lt; branch.thickness() &lt;&lt; '\n'; std::cout &lt;&lt; &quot;Leaf Color &quot; &lt;&lt; leaf.color() &lt;&lt; '\n'; branch.set_thickness(0.25); std::cout &lt;&lt; &quot;Branch Thickness &quot; &lt;&lt; leaf.branch().thickness() &lt;&lt; '\n'; } void demo_const() { const Tree tree; Tree::Branch branch = tree.branch(0); Tree::Leaf leaf = branch.leaf(1); std::cout &lt;&lt; &quot;Branch Thickness &quot; &lt;&lt; branch.thickness() &lt;&lt; '\n'; std::cout &lt;&lt; &quot;Leaf Color &quot; &lt;&lt; leaf.color() &lt;&lt; '\n'; std::cout &lt;&lt; &quot;Branch Thickness &quot; &lt;&lt; leaf.branch().thickness() &lt;&lt; '\n'; } int main() { demo(); demo_const(); return 0; } </code></pre> <p>Compiling gives me the following error:</p> <pre><code>error : no matching constructor for initialization of 'Tree::Branch' return Branch{ this, branch_id }; ^ ~~~~~~~~~~~~~~~~~~~ note: candidate constructor not viable: 1st argument ('const Tree *') would lose const qualifier Branch(Tree* tree, int branch_id) ^ note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided class Branch { ^ note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided </code></pre> <p><a href="https://godbolt.org/z/TWTnv6qcE" rel="nofollow noreferrer">Demo in Compiler Explorer</a></p> <p>How do I get this to compile and both demo and demo_const to work.</p> <h1>What I tried so far</h1> <p>I read up on the topic and the pattern I found to template the reference to the tree und instanciate it for <code>Tree</code> and <code>const Tree</code>, as shown <a href="https://stackoverflow.com/a/26665149/476266">here</a> and <a href="https://stackoverflow.com/questions/62917653/const-correctness-with-proxy-object">here</a>.</p> <pre class="lang-cpp prettyprint-override"><code>template &lt;TreeType&gt; class BranchTemplate { public: BranchTemplate(TreeType *tree, int branch_id) tree_(tree), branch_id_(branch_id) { } private: TreeType *tree_; int branch_id_; }; using Branch = BranchTemplate&lt;Tree&gt;; using ConstBranch= BranchTemplate&lt;const Tree&gt;; class Tree { Branch branch(int branch_id) { return Branch(this, branch_id); } ConstBranch branch(int branch_id) const { return ConstBranch(this, branch_id); } } </code></pre> <p>While this works for <code>Branch</code> I can't do the same for <code>Leaf</code> as we cannot return a Leaf based on the constness of the branch, but this needs to depend on the constness of the template parameter. Adding more template parameters eventually lead to recursion issues.</p> <h1>Plan B</h1> <p>My plan B is to create two more independent classes ConstBranch and ConstLeaf. This however would duplicate the implementation, and might introduce subtle bugs when they are not consistent with each other.</p> <h1>Other ideas</h1> <p>I read about enable_if and think it might help here. However I couldn't find an example that made it clear how that would work.</p> <h1>Question</h1> <p>How are other people solving this issue?</p>
[ { "answer_id": 74644135, "author": "Saif", "author_id": 4777670, "author_profile": "https://Stackoverflow.com/users/4777670", "pm_score": 1, "selected": false, "text": "Array.prototype.includes() const string = \"paper\";\nconst array = [\"book\", \"scissors\", \"apron\", \"tape\", \"paper\"];\n\nif (array.includes(string)) {\n console.log(\"String found in array\");\n} else {\n console.log(\"String not found in array\");\n}\n\n Array.prototype.includes() for const string = \"paper\";\nconst array = [\"book\", \"scissors\", \"apron\", \"tape\", \"paper\"];\n\nlet found = false;\nfor (const element of array) {\n if (element === string) {\n found = true;\n break;\n }\n}\n\nif (found) {\n console.log(\"String found in array\");\n} else {\n console.log(\"String not found in array\");\n}\n" }, { "answer_id": 74644421, "author": "Zola", "author_id": 2977188, "author_profile": "https://Stackoverflow.com/users/2977188", "pm_score": 0, "selected": false, "text": " const string = \"papper\";\n const Myarray = [\"book\", \"sissors\", \"apron\", \"tape\", \"paper\"];\n var intersection = Myarray.includes(string);\n alert(intersection);\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74643986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476266/" ]
74,644,003
<p>I have a simplest nft code. My task is to take an array of buyers (wallet addresses) of this nft when it's minted and to pass it ((array) or them ((addresses))) to another contract of mine, so i could take further action with them. The answer is... HOW? I'm new to programming, so please be gentle with me ^_^</p> <p>Thank you in advance!</p> <p>Andrew</p> <p>Nft code -&gt;</p> <pre><code>// SPDX-License-Identifier: MIT pragma solidity ^0.8.8; import &quot;@openzeppelin/contracts/token/ERC721/ERC721.sol&quot;; contract Nft is ERC721 { string public constant TOKEN_URI = &quot;ipfs://...&quot;; uint256 private s_tokenCounter; constructor() ERC721(&quot;NFT&quot;, &quot;NFT&quot;) { s_tokenCounter = 0; } function mintNft() public { s_tokenCounter = s_tokenCounter + 1; _safeMint(msg.sender, s_tokenCounter); } function tokenURI(uint256 tokenId) public view override returns (string memory) { // require(_exists(tokenId), &quot;ERC721Metadata: URI query for nonexistent token&quot;); return TOKEN_URI; } function getTokenCounter() public view returns (uint256) { return s_tokenCounter; } } </code></pre> <p>I tried to build a getter function but got lost in the code and advices. Tried to import an NFT-contract into an executive contract... Full of mistakes and disappointment.</p>
[ { "answer_id": 74645390, "author": "Petr Galushkin", "author_id": 18125566, "author_profile": "https://Stackoverflow.com/users/18125566", "pm_score": 1, "selected": false, "text": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.17;\n\ninterface InterfaceParentContract {\n\n function viewMyArr() external view returns(address[] memory);\n\n} \n\ncontract ParentContract {\n address[] public myArr; \n\n constructor () {\n myArr.push(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2);\n myArr.push(0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db);\n myArr.push(0x78731D3Ca6b7E34aC0F824c42a7cC18A495cabaB);\n } \n\n function viewMyArr() external view returns(address[] memory) {\n return myArr; \n }\n}\n // SPDX-License-Identifier: MIT\npragma solidity ^0.8.17;\n\nimport \"./ParentContract.sol\"; \n\ncontract Child {\n\n address[] public newArr; \n\n address parentContract; \n\n constructor(address _address) {\n parentContract = _address; \n }\n\n function smth() public {\n InterfaceParentContract b = InterfaceParentContract(parentContract); \n newArr = b.viewMyArr(); \n }\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20657320/" ]
74,644,021
<p>I have created a web api, simple dotnet framework api as below</p> <p><a href="https://i.stack.imgur.com/TBmVv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TBmVv.png" alt="enter image description here" /></a></p> <p>Now i have create dotnet maui blazor app connecting to the android physical device like this</p> <p><a href="https://i.stack.imgur.com/Vkv25.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vkv25.png" alt="enter image description here" /></a></p> <p>this is my button on click code in which i want to connect my application deployed on the phsical device to my web api connected on my laptop?</p> <p>what is the ip address i needed to connect to from my android physical device to my web api on my laptop? it is not connecting . it is giving time-out error but first of all i needed to be sure what ip-address i needed to connect to?</p> <pre><code> async void OnButtonClicked(object sender, EventArgs args) { string baseurl = &quot;https://10.0.2.2:44378&quot;; var httpClientHandler = new HttpClientHandler(); httpClientHandler.SslProtocols = System.Security.Authentication.SslProtocols.Tls; httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =&gt; { return true; }; using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseurl); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(&quot;application/json&quot;)); HttpResponseMessage Res = await client.GetAsync(&quot;/api/values&quot;); if (Res.IsSuccessStatusCode) { var EmpResponse = Res.Content.ReadAsStringAsync().Result; } } </code></pre>
[ { "answer_id": 74645390, "author": "Petr Galushkin", "author_id": 18125566, "author_profile": "https://Stackoverflow.com/users/18125566", "pm_score": 1, "selected": false, "text": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.17;\n\ninterface InterfaceParentContract {\n\n function viewMyArr() external view returns(address[] memory);\n\n} \n\ncontract ParentContract {\n address[] public myArr; \n\n constructor () {\n myArr.push(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2);\n myArr.push(0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db);\n myArr.push(0x78731D3Ca6b7E34aC0F824c42a7cC18A495cabaB);\n } \n\n function viewMyArr() external view returns(address[] memory) {\n return myArr; \n }\n}\n // SPDX-License-Identifier: MIT\npragma solidity ^0.8.17;\n\nimport \"./ParentContract.sol\"; \n\ncontract Child {\n\n address[] public newArr; \n\n address parentContract; \n\n constructor(address _address) {\n parentContract = _address; \n }\n\n function smth() public {\n InterfaceParentContract b = InterfaceParentContract(parentContract); \n newArr = b.viewMyArr(); \n }\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324831/" ]
74,644,026
<p>In the following variables, how do I dynamically pass user.id and friend.id</p> <pre class="lang-kotlin prettyprint-override"><code> class WindViewModel @Inject constructor() : BaseViewModel() { val userWindList = Pager(config = pagingConfig, remoteMediator = WindRemoteMediator(&quot;userWindList&quot;, user.id, friend.id, database!!, api)) { windRepository.pagingModelList(friend.id, &quot;userWindList&quot;) }.flow.map { pagingData -&gt; pagingData.map { it.json.toWind() } }.cachedIn(viewModelScope) } </code></pre>
[ { "answer_id": 74644203, "author": "ndriqa", "author_id": 9410164, "author_profile": "https://Stackoverflow.com/users/9410164", "pm_score": 0, "selected": false, "text": "Kotlin ...\nval sumOfSomeInts = sumOfSomeInts(1, 3, 7, 2)\n...\nfun sumOfSomeInts(vararg num: Int): Int {\n var sum = 0\n for(n in num) {\n sum += n\n }\n return sum\n} \n...\n vararg named arguments" }, { "answer_id": 74644379, "author": "Tenfour04", "author_id": 506796, "author_profile": "https://Stackoverflow.com/users/506796", "pm_score": 2, "selected": true, "text": "flatMapLatest data class WindRemoteMediatorParams(val userId: String, val friendId: String) // helper class\n\nprivate val mediatorParams = MutableSharedFlow<WindRemoteMediatorParams>(replay = 1)\n\n@OptIn(ExperimentalCoroutinesApi::class)\nval userWindList = mediatorParams.flatMapLatest { (userId, friendId) ->\n Pager(config = pagingConfig, remoteMediator = WindRemoteMediator(\"userWindList\", userId, friendId, database!!, api)) {\n windRepository.pagingModelList(friend.id, \"userWindList\")\n }.flow\n}.map { pagingData ->\n pagingData.map { it.json.toWind() }\n}.cachedIn(viewModelScope)\n\nfun beginPaging(userId: String, friendId: String) {\n mediatorParams.tryEmit(WindRemoteMediatorParams(userId, friendId))\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4218245/" ]
74,644,033
<p>I wanted to add &amp; remove (Multiple values) of the input to tag on the click event of checkbox. done the code for single items, please help me to do for getting multiple values.</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>$(document).ready(function() { $('input').click(function() { var selectedval = $(this).val(); $('h3').text(selectedval); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>ul { list-style: none; }</code></pre> <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;div id="banner-message"&gt; &lt;h3&gt;Select&lt;/h3&gt; &lt;ul&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" value="List Item1"/&gt;List Item1&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" value="List Item2"/&gt;List Item2&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" value="List Item3"/&gt;List Item3&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" value="List Item4"/&gt;List Item4&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" value="List Item5"/&gt;List Item5&lt;/label&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/anadmin7776/6yo2dbxj/22/" rel="nofollow noreferrer">http://jsfiddle.net/anadmin7776/6yo2dbxj/22/</a></p>
[ { "answer_id": 74644216, "author": "vmar", "author_id": 7642741, "author_profile": "https://Stackoverflow.com/users/7642741", "pm_score": 1, "selected": false, "text": "$(document).ready(function() {\n $('input').click(function() {\n var selectedval = function() {\n let v = [];\n\n $('input:checked').each(function(i, el) {\n v.push(el.value);\n });\n\n return v.join(', ');\n };\n\n $('h3').text(selectedval);\n });\n}); ul {\n list-style: none;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<div id=\"banner-message\">\n <h3>Select</h3>\n\n <ul>\n <li><label><input type=\"checkbox\" value=\"List Item1\"/>List Item1</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item2\"/>List Item2</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item3\"/>List Item3</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item4\"/>List Item4</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item5\"/>List Item5</label></li>\n </ul>\n</div>" }, { "answer_id": 74644233, "author": "gsharew", "author_id": 13053396, "author_profile": "https://Stackoverflow.com/users/13053396", "pm_score": 0, "selected": false, "text": "var collection = [];\n\n$(document).ready(function() {\n $('input').click(function() {\n var selectedval = $(this).val();\n \n if (!$(this).is(':checked'))\n collection.splice(collection.indexOf(selectedval), 1);\n else\n collection.push(selectedval);\n \n $('h3').text(collection.toString());\n });\n}); ul {\n list-style: none;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<div id=\"banner-message\">\n <h3>Select <span></span></h3>\n\n <ul class=\"selector\">\n <li><label><input type=\"checkbox\" value=\"List Item1\"/>List Item1</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item2\"/>List Item2</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item3\"/>List Item3</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item4\"/>List Item4</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item5\"/>List Item5</label></li>\n </ul>\n</div>" }, { "answer_id": 74644244, "author": "isherwood", "author_id": 1264804, "author_profile": "https://Stackoverflow.com/users/1264804", "pm_score": 1, "selected": false, "text": "change $(document).ready(function() {\n $('.selector input').change(function() {\n let headingString = '';\n\n $('.selector input:checked').each((i, el) => {\n headingString = headingString + ' ' + el.value;\n });\n\n $('#banner-message h3 span').text(headingString);\n });\n}); ul {\n list-style: none;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<div id=\"banner-message\">\n <h3>Selected:<span></span></h3>\n\n <ul class=\"selector\">\n <li><label><input type=\"checkbox\" value=\"List Item1\"/>List Item1</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item2\"/>List Item2</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item3\"/>List Item3</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item4\"/>List Item4</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item5\"/>List Item5</label></li>\n </ul>\n</div>" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3927335/" ]
74,644,103
<blockquote> <p>for y in (random.randint(0,9)) in (x): TypeError: argument of type 'int' is not iterable</p> </blockquote> <pre><code>import random x = (random.randint(0,9)) print (x) y = (random.randint(0,9)) print (y) for y in (random.randint(0,9)) in (x): if (y)==(x): break </code></pre>
[ { "answer_id": 74644216, "author": "vmar", "author_id": 7642741, "author_profile": "https://Stackoverflow.com/users/7642741", "pm_score": 1, "selected": false, "text": "$(document).ready(function() {\n $('input').click(function() {\n var selectedval = function() {\n let v = [];\n\n $('input:checked').each(function(i, el) {\n v.push(el.value);\n });\n\n return v.join(', ');\n };\n\n $('h3').text(selectedval);\n });\n}); ul {\n list-style: none;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<div id=\"banner-message\">\n <h3>Select</h3>\n\n <ul>\n <li><label><input type=\"checkbox\" value=\"List Item1\"/>List Item1</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item2\"/>List Item2</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item3\"/>List Item3</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item4\"/>List Item4</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item5\"/>List Item5</label></li>\n </ul>\n</div>" }, { "answer_id": 74644233, "author": "gsharew", "author_id": 13053396, "author_profile": "https://Stackoverflow.com/users/13053396", "pm_score": 0, "selected": false, "text": "var collection = [];\n\n$(document).ready(function() {\n $('input').click(function() {\n var selectedval = $(this).val();\n \n if (!$(this).is(':checked'))\n collection.splice(collection.indexOf(selectedval), 1);\n else\n collection.push(selectedval);\n \n $('h3').text(collection.toString());\n });\n}); ul {\n list-style: none;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<div id=\"banner-message\">\n <h3>Select <span></span></h3>\n\n <ul class=\"selector\">\n <li><label><input type=\"checkbox\" value=\"List Item1\"/>List Item1</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item2\"/>List Item2</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item3\"/>List Item3</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item4\"/>List Item4</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item5\"/>List Item5</label></li>\n </ul>\n</div>" }, { "answer_id": 74644244, "author": "isherwood", "author_id": 1264804, "author_profile": "https://Stackoverflow.com/users/1264804", "pm_score": 1, "selected": false, "text": "change $(document).ready(function() {\n $('.selector input').change(function() {\n let headingString = '';\n\n $('.selector input:checked').each((i, el) => {\n headingString = headingString + ' ' + el.value;\n });\n\n $('#banner-message h3 span').text(headingString);\n });\n}); ul {\n list-style: none;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<div id=\"banner-message\">\n <h3>Selected:<span></span></h3>\n\n <ul class=\"selector\">\n <li><label><input type=\"checkbox\" value=\"List Item1\"/>List Item1</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item2\"/>List Item2</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item3\"/>List Item3</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item4\"/>List Item4</label></li>\n <li><label><input type=\"checkbox\" value=\"List Item5\"/>List Item5</label></li>\n </ul>\n</div>" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20657228/" ]
74,644,171
<p>I'm trying to import products from an XML with variations. The import for the products works so far but it doesn't create the variations.</p> <p>Here is my code (simplified):</p> <pre class="lang-php prettyprint-override"><code> /** * @return int * @throws \Exception */ public function execute() { // avoid reaching memory limit ini_set('memory_limit', '-1'); // set tax id $this-&gt;setTaxId(); if (empty($this-&gt;taxId)) { return 1; } // read products from import xml file $importProducts = $this-&gt;loadProducts(); $csvBatch = array_chunk($importProducts, self::BATCH); $productNumbers = []; foreach ($csvBatch as $products) { $productNumbers[] = $this-&gt;processImportProducts($products, false); } $this-&gt;deleteProducts(array_merge(...$productNumbers)); return 0; } /** * @param $productsData * @param $progressBar * @return array */ private function processImportProducts($productsData, $progressBar) { $products = []; $productNumbers = []; foreach ($productsData as $product) { $products[$product['SKU']['@cdata']] = $this-&gt;importProducts($product, $progressBar); $productNumbers[] = $product['SKU']['@cdata']; } // upsert product try { $this-&gt;cleanProductProperties($products, $this-&gt;context); $this-&gt;productRepository-&gt;upsert(array_values($products), $this-&gt;context); } catch (WriteException $exception) { $this-&gt;logger-&gt;info(' '); $this-&gt;logger-&gt;info('&lt;error&gt;Products could not be imported. Message: '. $exception-&gt;getMessage() .'&lt;/error&gt;'); } unset($products); return $productNumbers; } /** * @param $product * @param $progressBar * @return array */ private function importProducts($product, $progressBar) { ... $productData = [ 'id' =&gt; $productId, 'productNumber' =&gt; $productNumber, 'price' =&gt; [ [ 'currencyId' =&gt; Defaults::CURRENCY, 'net' =&gt; !empty($product['net']) ? $product['net'] : 0, 'gross' =&gt; !empty($product['net']) ? $product['net'] : 0, 'linked' =&gt; true ] ], 'stock' =&gt; 99999, 'unit' =&gt; [ 'id' =&gt; '3fff95a8077b4f5ba3d1d2a41cb53fab' ], 'unitId' =&gt; '3fff95a8077b4f5ba3d1d2a41cb53fab', 'taxId' =&gt; $this-&gt;taxId, 'name' =&gt; $productNames, 'description' =&gt; $productDescriptions ]; if(isset($product['Variations'])) { $variationIds = $product['Variations']['@cdata'] ?? ''; $productData['variation'] = [$this-&gt;getProductVariationIds($variationIds)]; } return $productData; } /** * Get product variation ids * * @param string $productVariations * @return string */ private function getProductVariationIds($productVariations) { $productVariationIds = explode(',', $productVariations); // get product variationIds in form of a string list $ids = $this-&gt;productRepository-&gt;search( (new Criteria())-&gt;addFilter(new EqualsAnyFilter('productNumber', $productVariationIds)), $this-&gt;context )-&gt;getIds(); return implode(',', $ids); } </code></pre> <p>It loads correctly the ids but nothing happen. Also no error.</p> <p>Anyone an idea how to import variations as well?</p>
[ { "answer_id": 74646118, "author": "dneustadt", "author_id": 8556259, "author_profile": "https://Stackoverflow.com/users/8556259", "pm_score": 2, "selected": true, "text": "variation Runtime parentId options property_group_option $productData = [\n // ...\n 'parentId' => '...'\n 'options' => [\n ['id' => '...'],\n ['id' => '...'],\n ['id' => '...'],\n // ...\n ],\n];\n product_configurator_setting productId $repository = $this->container->get('product_configurator_setting.repository');\n\n$configuratorSettings = [];\nforeach ($options as $option) {\n $configuratorSetting = [\n 'optionId' => $option['id'],\n 'productId' => $parentId,\n ];\n\n $criteria = new Criteria();\n $criteria->addFilter(new EqualsFilter('productId', $parentId));\n $criteria->addFilter(new EqualsFilter('optionId', $option['id']));\n\n $id = $repository->searchIds($criteria, $context)->firstId();\n\n // if the configurator setting already exists, update or skip\n if ($id) {\n $configuratorSetting['id'] = $id;\n }\n\n $configuratorSettings[] = $configuratorSetting;\n}\n\n$repository->upsert(configuratorSettings, $context);\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4153552/" ]
74,644,208
<p>I'm a newbie in PureScript now reading a book &quot;Functional Programming Made Easier: A Step-by-Step Guide&quot;, but when I got to the section on Tuples, I realised that all that was presented appeared to be nonsense.</p> <p>This is the code that's presented that does not work.</p> <pre class="lang-hs prettyprint-override"><code>splitPosAndNeg :: Array Int -&gt; Tuple (Array Int) (Array Int) let Tuple pos neg = splitPosAndNeg [1, -2, 3, -4, 5, -6, -7, 8] let split = splitPosAndNeg [1, -2, 3, -4, 5, -6, -7, 8] pos = fst split neg = snd split </code></pre> <p>Could someone explain how to split an Array of Positive and Negative Numbers into a Tuple of 2 Arrays of Positive and Negative Numbers using PureScript? Would <a href="https://pursuit.purescript.org/packages/purescript-arrays/4.1.1/docs/Data.Array#v:partition" rel="nofollow noreferrer">partition</a> from Data.Array work? How is it used?</p> <p>@Fyodor Soikin, I've tried out the book's code <a href="https://try.purescript.org/?code=LYewJgrgNgpgBAWQIYEsB2cDuALGAnGAKEJWAAcQ8AXOABQKgjCJPMpoBEkqkA6AMRBQwSAEaw4ACgBmQsAEpWFanC49eAFQhlYS9qu59kZOEgDOiJGT0q1fAIJ48SAJ42aAUWnSYAYxqSXj7%2BiqTKnt5%2BVLwAwiBoZkLwklAgAOYAytggmKFsKhp4LrQQBBm%2BeChkVMRmOihUtCBm9mhgAHIwaXAAXD1wjs4ucACSaDQAtAB8cFo6yYOuo%2BPyUovDY1SKdVANTS1tnd1IcAC8cGRI1A0o8VIA%2BnAzAAyrSISwNHMSFBZoXWc4Ds9s1Wh0AQBtACMABo4BMAExwgDMcImABY4QBWNEANjRAHY4QAOAC6HxgNGBNHO1P2YKOcGhaKRcFR8MxcBx8Px8KJcDJhDgwouzUB0jMVPqNRFcH%2B3VpbSB0uIwFQGHOBDa%2BDOAB5dVgGtg4gkknAwCAhXBUplspg4AASC5XKg3O6SR4vVbM%2BGs9kY7F4wkk8nCiYTOBa5h4R1wWTCK3hkUQuDYKFSKggeYANxgUA4fhQZluCUUYYjwtDcCAA" rel="nofollow noreferrer">here with the partition function</a>. It still does not work.</p>
[ { "answer_id": 74645046, "author": "Fyodor Soikin", "author_id": 180286, "author_profile": "https://Stackoverflow.com/users/180286", "pm_score": 2, "selected": true, "text": "splitPosAndNeg :: Array Int -> Tuple (Array Int) (Array Int)\n let Tuple pos neg = splitPosAndNeg [1, -2, 3, -4, 5, -6, -7, 8]\n fst snd let split = splitPosAndNeg [1, -2, 3, -4, 5, -6, -7, 8]\n pos = fst split\n neg = snd split\n pos neg split let" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8256981/" ]
74,644,227
<p>I have table in SAS like below:</p> <p>data type:</p> <ul> <li><p>ID - numeric</p> </li> <li><p>TYPE - character</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>TYPE</th> </tr> </thead> <tbody> <tr> <td>111</td> <td>{&quot;Top&quot;:10}</td> </tr> <tr> <td>222</td> <td>{&quot;abC&quot;:&quot;false&quot;,&quot;Top&quot;:111, &quot;aa&quot;:5}</td> </tr> <tr> <td>333</td> <td>{&quot;Top&quot;:15.2}</td> </tr> <tr> <td>...</td> <td>...</td> </tr> </tbody> </table> </div></li> </ul> <p>And I need to create new column &quot;COL1&quot; base on column &quot;TYPE&quot; where I need to extract value which is after character &quot;Top&quot;:</p> <p>So I need something like below:</p> <pre><code>ID | TYPE | COL1 --- |-----------------------------------|------ 111 | {&quot;Top&quot;:10} | 10 222 | {&quot;abC&quot;:&quot;false&quot;,&quot;Top&quot;:111, &quot;aa&quot;:5} | 111 333 | {&quot;Top&quot;:15.2} | 15.2 ... | ... | ... </code></pre> <p>How can I do that in PROC SQL in SAS Enterprise Guide ?</p>
[ { "answer_id": 74644328, "author": "Kermit", "author_id": 10468613, "author_profile": "https://Stackoverflow.com/users/10468613", "pm_score": 3, "selected": true, "text": "data want;\n set have;\n length col1 $50.;\n col1 = strip(scan(tranwrd(type,'\"Top\":','|'),2,'|},'));\nrun;\n tranwrd() \"Top\": type | scan() | } , id type col1\n 111 {\"Top\":10} 10\n 222 {\"abC\":\"false\",\"Top\":111,\"aa\":5} 111\n 333 {\"Top\":15.2} 15.2\n" }, { "answer_id": 74644473, "author": "Stu Sztukowski", "author_id": 5342700, "author_profile": "https://Stackoverflow.com/users/5342700", "pm_score": 2, "selected": false, "text": "data want;\n set have;\n\n /* Create a regular expression ID */\n regexid = prxparse('/(?<=\"Top\":)(\\d+)/');\n\n /* Find the position and length of the match */\n call prxsubstr(regexid, type, pos, len);\n\n /* Extract the match and convert it to a number */\n COL1 = input(substr(type, pos, len), 8.);\nrun;\n" }, { "answer_id": 74645657, "author": "Tom", "author_id": 4965549, "author_profile": "https://Stackoverflow.com/users/4965549", "pm_score": 0, "selected": false, "text": "data have;\n input ID TYPE $50.;\ncards4;\n111 {\"Top\":10}\n222 {\"abC\":\"false\",\"Top\":111, \"aa\":5}\n333 {\"Top\":15.2}\n;;;;\n Top data want;\n set have;\n do index=1 to countw(type,'{,}','q');\n pair = scan(type,index,'{,}','q');\n name = dequote(scan(pair,1,':','q'));\n value = dequote(scan(pair,2,':','q'));\n if name='Top' then number=input(value,32.);\n end;\n drop index pair name value;\nrun;\n OBS ID TYPE number\n\n 1 111 {\"Top\":10} 10.0\n 2 222 {\"abC\":\"false\",\"Top\":111, \"aa\":5} 111.0\n 3 333 {\"Top\":15.2} 15.2\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12242085/" ]
74,644,248
<p>I have a yaml that I need to process with a python script, the yaml is something like this:</p> <pre><code>user: john description: Blablabla version: 1 data: data1: {type : bool, default: 0, flag: True} data2: {type : bool, default: 0, flag: True} data3: {type : float, default: 0, flag: false} </code></pre> <p>I need a list the the names of all the data that for example are bools or float, or all the ones where &quot;flag&quot; equals True or False, but I'm having difficulties moving around the list and getting what I need.</p> <p>I've tried something like this:</p> <pre><code> x = raw_data.items() for i in range(len(x['data'])): if (x['data'][i]).get('type') == &quot;bool&quot;: print(x['data'][i]) </code></pre> <p>But then I get an error: TypeError: 'dict_items' object is not subscriptable</p>
[ { "answer_id": 74644328, "author": "Kermit", "author_id": 10468613, "author_profile": "https://Stackoverflow.com/users/10468613", "pm_score": 3, "selected": true, "text": "data want;\n set have;\n length col1 $50.;\n col1 = strip(scan(tranwrd(type,'\"Top\":','|'),2,'|},'));\nrun;\n tranwrd() \"Top\": type | scan() | } , id type col1\n 111 {\"Top\":10} 10\n 222 {\"abC\":\"false\",\"Top\":111,\"aa\":5} 111\n 333 {\"Top\":15.2} 15.2\n" }, { "answer_id": 74644473, "author": "Stu Sztukowski", "author_id": 5342700, "author_profile": "https://Stackoverflow.com/users/5342700", "pm_score": 2, "selected": false, "text": "data want;\n set have;\n\n /* Create a regular expression ID */\n regexid = prxparse('/(?<=\"Top\":)(\\d+)/');\n\n /* Find the position and length of the match */\n call prxsubstr(regexid, type, pos, len);\n\n /* Extract the match and convert it to a number */\n COL1 = input(substr(type, pos, len), 8.);\nrun;\n" }, { "answer_id": 74645657, "author": "Tom", "author_id": 4965549, "author_profile": "https://Stackoverflow.com/users/4965549", "pm_score": 0, "selected": false, "text": "data have;\n input ID TYPE $50.;\ncards4;\n111 {\"Top\":10}\n222 {\"abC\":\"false\",\"Top\":111, \"aa\":5}\n333 {\"Top\":15.2}\n;;;;\n Top data want;\n set have;\n do index=1 to countw(type,'{,}','q');\n pair = scan(type,index,'{,}','q');\n name = dequote(scan(pair,1,':','q'));\n value = dequote(scan(pair,2,':','q'));\n if name='Top' then number=input(value,32.);\n end;\n drop index pair name value;\nrun;\n OBS ID TYPE number\n\n 1 111 {\"Top\":10} 10.0\n 2 222 {\"abC\":\"false\",\"Top\":111, \"aa\":5} 111.0\n 3 333 {\"Top\":15.2} 15.2\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13943268/" ]
74,644,351
<p>I am transferring some data from Anylogic to Excel. This happens every time an agent enters the wait block, and I store its ID,processing time and due date. Which would look like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">ID</th> <th style="text-align: center;">p</th> <th style="text-align: right;">d</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">5</td> <td style="text-align: right;">7</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">3</td> <td style="text-align: right;">8</td> </tr> <tr> <td style="text-align: left;">3</td> <td style="text-align: center;">6</td> <td style="text-align: right;">15</td> </tr> </tbody> </table> </div> <p>After one hour, I would like the Excel file to be cleared (except for the headers 'ID' 'p' and 'd'. (after one hour, the orders are released from the wait block).</p> <p>So that the next hour, the Excel file will only contain data from orders coming in the second hour</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">ID</th> <th style="text-align: center;">p</th> <th style="text-align: right;">d</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">4</td> <td style="text-align: center;">7</td> <td style="text-align: right;">7</td> </tr> <tr> <td style="text-align: left;">5</td> <td style="text-align: center;">10</td> <td style="text-align: right;">24</td> </tr> <tr> <td style="text-align: left;">6</td> <td style="text-align: center;">4</td> <td style="text-align: right;">13</td> </tr> </tbody> </table> </div> <p>I tried doing this using an event, triggered after one hour, with the following code I found in the answer of a similar question:</p> <pre><code>for (int i=0;i&lt;15;i++){ //for each column for (int j=2;j&lt;50000;j++){ //for each row ALtoGA.clearCell(1,j,i); } } </code></pre> <p>However, this only clears the entries in the second row, and I want all my entries to be cleared. Does anyone know how to do this?</p>
[ { "answer_id": 74645221, "author": "Felipe", "author_id": 3438111, "author_profile": "https://Stackoverflow.com/users/3438111", "pm_score": 3, "selected": true, "text": "public class ExportInfo(){\n public int id;\n public int P;\n public int d;\n\n public ExportInfo(int id,int P, int d) { \n this.id=id;\n this.P=P;\n this.d=d;\n }\n\n}\n yourList.add(new ExportInfo(a,b,c));\n yourList.clear();\n int row=2;\nfor(ExportInfo e : yourList){\n col=1;\n ALtoGA.setCellNumericValue(e.id,1,row,col++);\n ALtoGA.setCellNumericValue(e.P,1,row,col++);\n ALtoGA.setCellNumericValue(e.d,1,row,col++);\n row++;\n}\nALtoGA.writeFile();\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20511412/" ]
74,644,361
<p>I have a simple terraform code</p> <pre><code># Configure the Microsoft Azure provider provider &quot;azurerm&quot; { features {} } # Create a Resource Group if it doesn’t exist resource &quot;azurerm_resource_group&quot; &quot;example&quot; { name = &quot;example-resources&quot; location = &quot;West US&quot; } </code></pre> <p>It used to work as I logged in the Terminal using my User credentials , but now it throws an error</p> <pre><code>│ Error: building AzureRM Client: 3 errors occurred: │ * A Subscription ID must be configured when authenticating as a Service Principal using a Client Secret. │ * A Client ID must be configured when authenticating as a Service Principal using a Client Secret. │ * A Tenant ID must be configured when authenticating as a Service Principal using a Client Secret. │ │ │ │ with provider[&quot;registry.terraform.io/hashicorp/azurerm&quot;], │ on main.tf line 2, in provider &quot;azurerm&quot;: │ 2: provider &quot;azurerm&quot; { </code></pre> <p>What is causing this issue? I can't create a Service Principal due to lack of permission at the Active Directory. How do I make it work again without the Service Principal?</p>
[ { "answer_id": 74645221, "author": "Felipe", "author_id": 3438111, "author_profile": "https://Stackoverflow.com/users/3438111", "pm_score": 3, "selected": true, "text": "public class ExportInfo(){\n public int id;\n public int P;\n public int d;\n\n public ExportInfo(int id,int P, int d) { \n this.id=id;\n this.P=P;\n this.d=d;\n }\n\n}\n yourList.add(new ExportInfo(a,b,c));\n yourList.clear();\n int row=2;\nfor(ExportInfo e : yourList){\n col=1;\n ALtoGA.setCellNumericValue(e.id,1,row,col++);\n ALtoGA.setCellNumericValue(e.P,1,row,col++);\n ALtoGA.setCellNumericValue(e.d,1,row,col++);\n row++;\n}\nALtoGA.writeFile();\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/261708/" ]
74,644,389
<p>I have a table with <strong>user_id's</strong> and number of <strong>impressions</strong> they received during a certain period of time. A new record is added to the table when there is a new impression. Ex below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>user_id</th> <th>impressions</th> </tr> </thead> <tbody> <tr> <td>#1</td> <td>0</td> </tr> <tr> <td>#2</td> <td>0</td> </tr> <tr> <td>#3</td> <td>1</td> </tr> <tr> <td>#3</td> <td>2</td> </tr> <tr> <td>#3</td> <td>3</td> </tr> <tr> <td>#2</td> <td>1</td> </tr> </tbody> </table> </div> <p><strong>Question: how to count unique user_id's, who received less than 3 impressions during this period of time using SQL?</strong></p> <p>If I use COUNT DISTINCT + WHERE impressions &lt; 3, I will get the result</p> <p>user_id's = 3 (#1, #2, #3), as it will count the first occurrence of #3 that meets my criteria and count it in.</p> <p>But the right answer would be user_id's = 2 (#1 and #2) because only they received less than 3</p>
[ { "answer_id": 74645221, "author": "Felipe", "author_id": 3438111, "author_profile": "https://Stackoverflow.com/users/3438111", "pm_score": 3, "selected": true, "text": "public class ExportInfo(){\n public int id;\n public int P;\n public int d;\n\n public ExportInfo(int id,int P, int d) { \n this.id=id;\n this.P=P;\n this.d=d;\n }\n\n}\n yourList.add(new ExportInfo(a,b,c));\n yourList.clear();\n int row=2;\nfor(ExportInfo e : yourList){\n col=1;\n ALtoGA.setCellNumericValue(e.id,1,row,col++);\n ALtoGA.setCellNumericValue(e.P,1,row,col++);\n ALtoGA.setCellNumericValue(e.d,1,row,col++);\n row++;\n}\nALtoGA.writeFile();\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20657681/" ]
74,644,390
<p>I am trying to obtain the number of times that a certain numerical combination is repeated within a vector.</p> <p>For example, I have this sequence of different numbers and I want to understand how many times is repeated a certain &quot;block of number&quot;:</p> <p><code>test &lt;- c(1,2,3,4,1,2,3,4,4,4,4,4)</code></p> <p>I would like to choose the length of the &quot;block&quot;. Let's say for example length=4.</p> <p>If there's some base function or solutions in R that you know, I would like to get all the possible outcomes that sould be:</p> <p><code>2 times I found the combination 1 2 3 4 </code> <code>1 time I found the combination 4 4 4 4</code></p> <p>Could you help me to fix this? I'm interested in knowing both the number of times a certain combination has been found, and also what numbers make up that combination.</p> <p>I also tried to fix it with hints from <a href="https://stackoverflow.com/questions/18705153/generate-list-of-all-possible-combinations-of-elements-of-vector">Generate list of all possible combinations of elements of vector</a> but I'm not able to obtain the results which I expect.</p>
[ { "answer_id": 74644690, "author": "harre", "author_id": 4786466, "author_profile": "https://Stackoverflow.com/users/4786466", "pm_score": 2, "selected": true, "text": "length(test)/n n <- 4\n\nresults <-\n split(test, cut(seq_along(test), length(test)/n, labels = FALSE)) |> \n lapply(FUN = \\(x) paste(x, collapse = \" \")) |>\n unlist() |>\n table() |>\n stack()\n\npaste(results$values, \"times I found the combination\", results$ind)\n [1] \"2 times I found the combination 1 2 3 4\" \"1 times I found the combination 4 4 4 4\"\n" }, { "answer_id": 74644807, "author": "Bruno Peixoto", "author_id": 4904472, "author_profile": "https://Stackoverflow.com/users/4904472", "pm_score": 0, "selected": false, "text": "S w n w S w S c yes c w" }, { "answer_id": 74644927, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 1, "selected": false, "text": "test <- c(1,2,3,4,1,2,3,4,4,4,4,4)\n\nn<-4\n\neach_seq <- function(x, i){\n w <- length(x) - i + 1\n ids <- matrix(\n rep(1:i - 1, w) + rep(1:w, each = i), nrow = i) \n do.call(rbind, apply(ids, 2, function(j) x[j], simplify = F))\n}\n\ncombs <- as.data.frame(each_seq(test, n))\ngroups <- interaction(combs)\n\naggregate(1:nrow(combs), by=list(comb = groups), length)\n#> comb x\n#> 1 2.3.4.1 1\n#> 2 3.4.1.2 1\n#> 3 4.1.2.3 1\n#> 4 1.2.3.4 2\n#> 5 2.3.4.4 1\n#> 6 3.4.4.4 1\n#> 7 4.4.4.4 2\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19579774/" ]
74,644,420
<p>I'm programming the &quot;Rock, paper, scissors&quot;. I want now to run the function I added below 3 times. I tried using a <code>for _ in range(s)</code> but printed the same result 3 times.</p> <pre><code>import random OPTIONS = [&quot;Rock&quot;, &quot;Paper&quot;, &quot;Scissors&quot;] def get_user_input(): user_choice = input(&quot;Select your play (Rock, Paper or Scissors): &quot;) return user_choice def random_choice(): computer_choice = random.choice(OPTIONS) return computer_choice def game(user_choice, computer_choice): if user_choice == computer_choice: print(f&quot;You selected: {user_choice}.\nComputer selected: {computer_choice}.\nDraw.&quot;) else: if computer_choice == &quot;Rock&quot; and user_choice == &quot;Paper&quot;: print(f&quot;You selected: {user_choice}.\nComputer selected: {computer_choice}.\nYou won!&quot;) if computer_choice == &quot;Rock&quot; and user_choice == &quot;Scissors&quot;: print(f&quot;You selected: {user_choice}.\nComputer selected: {computer_choice}.\nYou lost...&quot;) if computer_choice == &quot;Paper&quot; and user_choice == &quot;Scissors&quot;: print(f&quot;You selected: {user_choice}.\nComputer selected: {computer_choice}.\nYou won!&quot;) if computer_choice == &quot;Paper&quot; and user_choice == &quot;Rock&quot;: print(f&quot;You selected: {user_choice}.\nComputer selected: {computer_choice}.\nYou lost...&quot;) if computer_choice == &quot;Scissors&quot; and user_choice == &quot;Rock&quot;: print(f&quot;You selected: {user_choice}.\nComputer selected: {computer_choice}.\nYou won!&quot;) if computer_choice == &quot;Scissors&quot; and user_choice == &quot;Paper&quot;: print(f&quot;You selected: {user_choice}.\nComputer selected: {computer_choice}.\nYou lost...&quot;) def main(): user_choice = get_user_input() computer_choice = random_choice() for _ in range(3): if game(user_choice, computer_choice): break else: print(&quot;Game has ended!&quot;) main() </code></pre> <p>Any tips on how to implement three rounds?</p>
[ { "answer_id": 74644500, "author": "MorganMLG", "author_id": 16020219, "author_profile": "https://Stackoverflow.com/users/16020219", "pm_score": 3, "selected": true, "text": "def main():\n\n for _ in range(3):\n user_choice = get_user_input()\n computer_choice = random_choice()\n game(user_choice, computer_choice)\n\n print(\"Game has ended!\")\n" }, { "answer_id": 74644554, "author": "Ethan Chartrand", "author_id": 13514681, "author_profile": "https://Stackoverflow.com/users/13514681", "pm_score": 1, "selected": false, "text": "def main():\n user_choice = get_user_input()\n for _ in range(3):\n computer_choice = random_choice()\n game('Rock', computer_choice)\n print(\"Game has ended!\")\n\nmain()\n def main():\n for _ in range(3):\n user_choice = get_user_input()\n computer_choice = random_choice()\n game('Rock', computer_choice)\n print(\"Game has ended!\")\n \n\nmain()\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18685243/" ]
74,644,435
<p>I'm trying to use variadic templates (for the first time really) to make a string replacement function.</p> <p>Essentially, I want to make a function (we'll call it Replace) that takes a key value that is used to search up and modify a template string based on the additional parameters provided in the Replace function. The template string has placeholders using the string &quot;%s&quot;.</p> <p>My problem is, I'm not sure how to iterate through the variadic template parameters... Here is some sample code.</p> <pre><code>const std::string FindOriginal(std::string Key) { if(Key == &quot;Toon&quot;) { return &quot;This is example %s in my program for Mr. %s.&quot;; } return &quot;&quot;; } std::string Replace(std::string OriginalKey) { return &quot;&quot;; } template&lt;typename First, typename ... Strings&gt; std::string Replace(std::string OriginalKey, First arg, const Strings&amp;... rest) { const std::string from = &quot;%s&quot;; std::string the_string = FindOriginal(OriginalKey); int i = 0; size_t start_pos = the_string.find(from); while(start_pos != std::string::npos) { // Ideally here I can somehow get the parameter at index i... the_string.replace(start_pos, from.length(), rest[i]); start_pos = the_string.find(from, start_pos); i++; } Replace(rest...); return the_string; } int main() { std::cout &lt;&lt; Replace(&quot;Toon&quot;, &quot;5&quot;, &quot;Jimmy&quot;) &lt;&lt; std::endl; } </code></pre>
[ { "answer_id": 74644657, "author": "Ricky", "author_id": 2195567, "author_profile": "https://Stackoverflow.com/users/2195567", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <string>\n\nconst std::string FindOriginal(const std::string& Key)\n{\n if(Key == \"Toon\")\n {\n return \"This is example %s in my program for Mr. %s.\";\n }\n \n return \"\";\n}\n\nvoid ReplaceValue(std::string& OriginalString)\n{\n (void)OriginalString;\n}\n\ntemplate<typename First, typename ... Strings>\nvoid ReplaceValue(std::string& OriginalString, First arg, const Strings&... rest)\n{\n const std::string from = \"%s\";\n\n size_t start_pos = OriginalString.find(from);\n if(start_pos != std::string::npos)\n {\n OriginalString.replace(start_pos, from.length(), arg);\n }\n \n ReplaceValue(OriginalString, rest...);\n}\n\ntemplate<typename First, typename ... Strings>\nstd::string GetModifiedString(const std::string& OriginalKey, First arg, const Strings&... rest)\n{\n std::string modified_string = FindOriginal(OriginalKey);\n ReplaceValue(modified_string, arg, rest...);\n \n return modified_string;\n}\n\nint main()\n{\n std::cout << GetModifiedString(\"Toon\", \"5\", \"Jimmyy\") << std::endl; \n}\n" }, { "answer_id": 74645544, "author": "AndyG", "author_id": 27678, "author_profile": "https://Stackoverflow.com/users/27678", "pm_score": 2, "selected": false, "text": "template<class T>\nconst std::string& ReplaceOne(std::string& originalString, const T& replacement)\n{\n static constexpr auto sentinel = \"%s\";\n size_t start_pos = originalString.find(sentinel);\n if(start_pos != std::string::npos)\n originalString.replace(start_pos, 2, replacement);\n return originalString;\n}\n\ntemplate<class...Ts>\nvoid Replace(std::string& originalString, const Ts&... rest)\n{\n (ReplaceOne(originalString, rest) , ...);\n}\n std::string original = \"This is example %s in my program for Mr. %s.\";\n const std::string expected = \"This is example 5 in my program for Mr. Jimmy.\";\nReplace(original, \"5\", \"Jimmy\");\nassert(original == expected);\n ReplaceOne \"%s\" \"%s\" std::string::find \"%s\" O(N * M) N M O(N) find find" }, { "answer_id": 74645662, "author": "rturrado", "author_id": 260313, "author_profile": "https://Stackoverflow.com/users/260313", "pm_score": 1, "selected": false, "text": "rest arg ReplaceImpl Replace ##include <iostream>\n#include <string>\n\nconst std::string FindOriginal(std::string Key) {\n if (Key == \"Toon\") {\n return \"This is example %s in my program for Mr. %s.\";\n }\n return {};\n}\n\nstd::string ReplaceImpl(std::string str) {\n return str;\n}\n\ntemplate <typename First, typename... Strings>\nstd::string ReplaceImpl(std::string str, First arg, const Strings&... rest) {\n if (auto pos{ str.find(\"%s\") }; pos != std::string::npos) {\n return\n str.substr(0, pos) + \n arg +\n ReplaceImpl(str.substr(pos + 2), rest...);\n }\n return str;\n}\n\ntemplate <typename First, typename... Strings>\nstd::string Replace(std::string OriginalKey, First arg, const Strings&... rest) {\n if (auto the_string{ FindOriginal(OriginalKey) }; not the_string.empty()) {\n return ReplaceImpl(the_string, arg, rest...);\n }\n return {};\n}\n\nint main() {\n std::cout << Replace(\"Toon\", \"5\", \"Jimmy\") << \"\\n\";\n}\n\n// Outputs: This is example 5 in my program for Mr. Jimmy.\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2195567/" ]
74,644,443
<p>I am working on a project that requires a form to be built. I am responsible for the base build with just HTML and CSS (so no JQuery/JS or other solutions, if possible, please). I've done my best to style it the way it was requested but I am having trouble with one important detail: affixing the form to the bottom of the page without distorting the sizing or positioning of any interior elements.</p> <p>Important: The form is a three-step process that will be triggered on an initial button click. So CTA -&gt; Step 1 -&gt; Step 2 -&gt; Step 3. As such, I've built the entire form with each step in one big with three separate modules. There are also classes used to show and hide each form step.</p> <p>Here is what I currently have:</p> <p>Snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#conversational { min-height: 100% height: auto !important; height: 100%; width: 375px; padding: 25px 5px 10px 0px; background-color: #f6f6f6; bottom: 0; } p { margin-left: 25px; max-width: 320px; text-align: left; font-family: "Open Sans"; color: #464646; font-size: 14px; letter-spacing: 0; line-height: 18px; } .close { font-size: 9px; color: #a2a2a2; float: right; margin: -20px 5px 0px 0px; } .rectangle { margin-left: 25px; height: 3px; width: 320px; border-radius: 3px; background-color: #dddddd; z-index: 0; } .blue-rectangle-step-1 { height: 3px; width: 88px; border-radius: 3px; background-color: #0160a8; z-index: 1; } .blue-rectangle-step-2 { height: 3px; width: 165px; border-radius: 3px; background-color: #0160a8; z-index: 1; } .blue-rectangle-step-3 { height: 3px; width: 233px; border-radius: 3px; background-color: #0160a8; z-index: 1; } #conversational input { margin-left: 25px; } #step-button { height: 40px; width: 330px; box-sizing: border-box; border: 2px solid #e76c4b; border-radius: 5px; text-align: center; font-family: "Open Sans"; font-weight: bold; font-color: #464646; font-size: 14px; letter-spacing: 0; line-height: 19px; } #step-1 label { margin-left: 25px; } #step-1 .ready-to-experience { max-width: 302px; font-family: "Open Sans Bold"; color: #0160a8; font-size: 22px; letter-spacing: 0px; line-height: 26px; margin: 15px 0px -10px 25px; } #step-1 .get-started { font-family: "Open Sans Bold"; font-size: 18px; letter-spacing: 0px; margin-bottom: -10px; } #step-2 label { margin-left: 25px; } #step-2 .thanks-name { font-family: "Open Sans Bold"; color: #0160a8; font-size: 18px; letter-spacing: 0px; margin-bottom: -10px; } #step-3 label[for="email"] { margin-left: 25px; } #step-3 label[for="phone"] { margin-left: 25px; } #step-3 label[for="home-mobile-phone"] { display: inline-block; margin-left: 5px; } #step-3 label[for="opt-in"] { display: inline-block; margin: 0px 0px 25px 10px; max-width: 265px; font-family: "Open Sans"; color: #464646; font-size: 12px; letter-spacing: 0; line-height: 14px; } #step-3 .almost-done { font-family: "Open Sans Bold"; color: #0160a8; font-size: 18px; letter-spacing: 0px; margin-bottom: -10px; } #step-3 #mobile-disclaimer-copy { font-family: "Open Sans Regular"; font-size: 11px; letter-spacing: 0px; line-height: 14px; margin: -15px 0px 15px 25px; } #conversational input[type="text"] { display: block; width: 320px; margin-bottom: 21px; } #conversational input[type="radio"] { display: inline-block; transform: translateY(1px); } #conversational input[type="checkbox"] { max-width: 320px; transform: translateY(-5px); } #conversational input[type="button"] { display: block; text-align: center; } #phone-radio-buttons { column-count: 2; column-width: 282px; } .page { display: none; } .active { display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="form" class="wrapper"&gt; &lt;form id="step-0" class="page" action=""&gt; &lt;input type="button" id="step-button" value="LOREM IPSUM"&gt;&lt;br&gt; &lt;/form&gt; &lt;form id="step-1" class="page active" action=""&gt; &lt;p class="close"&gt;X&lt;/p&gt; &lt;div class="rectangle"&gt; &lt;div class="blue-rectangle-step-1"&gt;&lt;/div&gt; &lt;/div&gt; &lt;p class="ready-to-experience"&gt;LOREM IPSUM&lt;/p&gt; &lt;p class="get-started"&gt;LOREM IPSUM&lt;/p&gt; &lt;p&gt;LOREM IPSUM&lt;/p&gt; &lt;label for="fname"&gt;&lt;strong&gt;First Name*&lt;/strong&gt;&lt;/strong&gt;&lt;/label&gt;&lt;br&gt; &lt;input type="text" id="fname" name="fname"&gt; &lt;label for="lname"&gt;&lt;strong&gt;Last Name*&lt;/strong&gt;&lt;/label&gt; &lt;input type="text" id="lname" name="lname"&gt; &lt;input type="button" id="step-button" value="NEXT: ADDRESS"&gt;&lt;br&gt; &lt;/form&gt; &lt;form id="step-2" class="page" action=""&gt; &lt;p class="close"&gt;X&lt;/p&gt; &lt;div class="rectangle"&gt; &lt;div class="blue-rectangle-step-2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;p class="thanks-name"&gt;LOREM IPSUM&lt;/p&gt; &lt;p&gt;LOREM IPSUM&lt;/p&gt; &lt;label for="address"&gt;&lt;strong&gt;Address*&lt;/strong&gt;&lt;/label&gt; &lt;input type="text" id="address" name="address"&gt; &lt;label for="city"&gt;&lt;strong&gt;City*&lt;/strong&gt;&lt;/label&gt; &lt;input type="text" id="city" name="city"&gt; &lt;div class="state-zip-fields"&gt; &lt;label for="state-province"&gt;&lt;strong&gt;State/Province*&lt;/strong&gt;&lt;/label&gt;&lt;input type="text" id="state-province" name="state-province"&gt;&lt;label for="zip-code" class="text-label"&gt;&lt;strong&gt;Zip/Postal Code*&lt;/strong&gt;&lt;/label&gt;&lt;input type="text" id="zip-code" name="zip-code"&gt; &lt;/div&gt; &lt;input type="button" id="step-button" value="NEXT: CONTACT INFO"&gt;&lt;br&gt; &lt;/form&gt; &lt;form id="step-3" class="page" action=""&gt; &lt;p class="close"&gt;X&lt;/p&gt; &lt;div class="rectangle"&gt; &lt;div class="blue-rectangle-step-3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;p class="almost-done"&gt;LOREM IPSUM&lt;/p&gt; &lt;p&gt;LOREM IPSUM&lt;/p&gt; &lt;label for="email"&gt;&lt;strong&gt;Email*&lt;/strong&gt;&lt;/label&gt; &lt;input type="text" id="email" name="email"&gt; &lt;label for="phone"&gt;&lt;strong&gt;Phone*&lt;/strong&gt;&lt;/label&gt; &lt;input type="text" id="phone" name="phone"&gt; &lt;p&gt;&lt;strong&gt;Phone Type*&lt;/strong&gt;&lt;/p&gt; &lt;div id="phone-radio-buttons"&gt; &lt;input type="radio" id="home-phone" name="home-mobile-phone" value="Home Phone"&gt; &lt;label for="home-mobile-phone"&gt;Home Phone&lt;/label&gt;&lt;input type="radio" id="mobile-phone" name="home-mobile-phone" value="Mobile Phone"&gt;&lt;label for="home-mobile-phone"&gt;Mobile Phone&lt;/label&gt; &lt;/div&gt; &lt;br&gt; &lt;div class="page"&gt;&lt;input type="checkbox" id="opt-in" name="opt-in" value="Opt-In to Receive SMS Alerts (Optional)"&gt;&lt;label for="opt-in"&gt;&lt;strong&gt;LOREM IPSUM&lt;/strong&gt; &lt;br&gt;(Optional)&lt;/label&gt;&lt;/div&gt; &lt;p id="mobile-disclaimer-copy" class="page"&gt;LOREM IPSUM &lt;/p&gt; &lt;input type="button" id="step-button" value="LAST: CHOOSE DATE &amp; TIME"&gt;&lt;br&gt; &lt;/form&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>So I tried something like position: fixed; and bottom: 0; but that just seems to stretch out the entire form and mess up some positioning of elements. So I need to make sure the form sticks to the bottom of the page (in mobile particularly) and that the sizing is consistent with each individual form step.</p> <p>Thanks.</p>
[ { "answer_id": 74644657, "author": "Ricky", "author_id": 2195567, "author_profile": "https://Stackoverflow.com/users/2195567", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <string>\n\nconst std::string FindOriginal(const std::string& Key)\n{\n if(Key == \"Toon\")\n {\n return \"This is example %s in my program for Mr. %s.\";\n }\n \n return \"\";\n}\n\nvoid ReplaceValue(std::string& OriginalString)\n{\n (void)OriginalString;\n}\n\ntemplate<typename First, typename ... Strings>\nvoid ReplaceValue(std::string& OriginalString, First arg, const Strings&... rest)\n{\n const std::string from = \"%s\";\n\n size_t start_pos = OriginalString.find(from);\n if(start_pos != std::string::npos)\n {\n OriginalString.replace(start_pos, from.length(), arg);\n }\n \n ReplaceValue(OriginalString, rest...);\n}\n\ntemplate<typename First, typename ... Strings>\nstd::string GetModifiedString(const std::string& OriginalKey, First arg, const Strings&... rest)\n{\n std::string modified_string = FindOriginal(OriginalKey);\n ReplaceValue(modified_string, arg, rest...);\n \n return modified_string;\n}\n\nint main()\n{\n std::cout << GetModifiedString(\"Toon\", \"5\", \"Jimmyy\") << std::endl; \n}\n" }, { "answer_id": 74645544, "author": "AndyG", "author_id": 27678, "author_profile": "https://Stackoverflow.com/users/27678", "pm_score": 2, "selected": false, "text": "template<class T>\nconst std::string& ReplaceOne(std::string& originalString, const T& replacement)\n{\n static constexpr auto sentinel = \"%s\";\n size_t start_pos = originalString.find(sentinel);\n if(start_pos != std::string::npos)\n originalString.replace(start_pos, 2, replacement);\n return originalString;\n}\n\ntemplate<class...Ts>\nvoid Replace(std::string& originalString, const Ts&... rest)\n{\n (ReplaceOne(originalString, rest) , ...);\n}\n std::string original = \"This is example %s in my program for Mr. %s.\";\n const std::string expected = \"This is example 5 in my program for Mr. Jimmy.\";\nReplace(original, \"5\", \"Jimmy\");\nassert(original == expected);\n ReplaceOne \"%s\" \"%s\" std::string::find \"%s\" O(N * M) N M O(N) find find" }, { "answer_id": 74645662, "author": "rturrado", "author_id": 260313, "author_profile": "https://Stackoverflow.com/users/260313", "pm_score": 1, "selected": false, "text": "rest arg ReplaceImpl Replace ##include <iostream>\n#include <string>\n\nconst std::string FindOriginal(std::string Key) {\n if (Key == \"Toon\") {\n return \"This is example %s in my program for Mr. %s.\";\n }\n return {};\n}\n\nstd::string ReplaceImpl(std::string str) {\n return str;\n}\n\ntemplate <typename First, typename... Strings>\nstd::string ReplaceImpl(std::string str, First arg, const Strings&... rest) {\n if (auto pos{ str.find(\"%s\") }; pos != std::string::npos) {\n return\n str.substr(0, pos) + \n arg +\n ReplaceImpl(str.substr(pos + 2), rest...);\n }\n return str;\n}\n\ntemplate <typename First, typename... Strings>\nstd::string Replace(std::string OriginalKey, First arg, const Strings&... rest) {\n if (auto the_string{ FindOriginal(OriginalKey) }; not the_string.empty()) {\n return ReplaceImpl(the_string, arg, rest...);\n }\n return {};\n}\n\nint main() {\n std::cout << Replace(\"Toon\", \"5\", \"Jimmy\") << \"\\n\";\n}\n\n// Outputs: This is example 5 in my program for Mr. Jimmy.\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20340500/" ]
74,644,448
<p>I was learning about JRadiobuttons and I made three JRadioButtons in this particular program. The JRadioButtons were pizzaButton, burgerButton and hotdogButton. I wanted to print specific lines when one of them is selected by the user. I overrided the ActionPerformed method and even implemented the ActionListener for each one of the RadioButtons. But after every try, the program seemed to ignore the ActionPerformed method. `</p> <pre><code> public class Main { public static void main(String[] args) { new MyFrame(); } } </code></pre> <p>`` `</p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MyFrame extends JFrame implements ActionListener { JRadioButton pizzaButton; JRadioButton burgerButton; JRadioButton hotdogButton; MyFrame() { this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setLayout(new FlowLayout()); JRadioButton pizzaButton = new JRadioButton(&quot;pizza&quot;); JRadioButton burgerButton = new JRadioButton(&quot;burger&quot;); JRadioButton hotdogButton = new JRadioButton(&quot;hot dog&quot;); ButtonGroup group = new ButtonGroup(); group.add(pizzaButton); group.add(burgerButton); group.add(hotdogButton); pizzaButton.addActionListener(this); burgerButton.addActionListener(this); hotdogButton.addActionListener(this); this.setVisible(true); this.add(pizzaButton); this.add(burgerButton); this.add(hotdogButton); this.pack(); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource()==pizzaButton) { System.out.println(&quot;You ordered a pizza&quot;); } else if (e.getSource()==burgerButton) { System.out.println(&quot;You ordered a burger&quot;); } else if (e.getSource()==hotdogButton) { System.out.println(&quot;You ordered a hot dog&quot;); } } } </code></pre> <p>``</p> <p>I tried checking the things that could go wrong and double checked whether I added the the ActionListener to the JRadioButtons.</p>
[ { "answer_id": 74644657, "author": "Ricky", "author_id": 2195567, "author_profile": "https://Stackoverflow.com/users/2195567", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <string>\n\nconst std::string FindOriginal(const std::string& Key)\n{\n if(Key == \"Toon\")\n {\n return \"This is example %s in my program for Mr. %s.\";\n }\n \n return \"\";\n}\n\nvoid ReplaceValue(std::string& OriginalString)\n{\n (void)OriginalString;\n}\n\ntemplate<typename First, typename ... Strings>\nvoid ReplaceValue(std::string& OriginalString, First arg, const Strings&... rest)\n{\n const std::string from = \"%s\";\n\n size_t start_pos = OriginalString.find(from);\n if(start_pos != std::string::npos)\n {\n OriginalString.replace(start_pos, from.length(), arg);\n }\n \n ReplaceValue(OriginalString, rest...);\n}\n\ntemplate<typename First, typename ... Strings>\nstd::string GetModifiedString(const std::string& OriginalKey, First arg, const Strings&... rest)\n{\n std::string modified_string = FindOriginal(OriginalKey);\n ReplaceValue(modified_string, arg, rest...);\n \n return modified_string;\n}\n\nint main()\n{\n std::cout << GetModifiedString(\"Toon\", \"5\", \"Jimmyy\") << std::endl; \n}\n" }, { "answer_id": 74645544, "author": "AndyG", "author_id": 27678, "author_profile": "https://Stackoverflow.com/users/27678", "pm_score": 2, "selected": false, "text": "template<class T>\nconst std::string& ReplaceOne(std::string& originalString, const T& replacement)\n{\n static constexpr auto sentinel = \"%s\";\n size_t start_pos = originalString.find(sentinel);\n if(start_pos != std::string::npos)\n originalString.replace(start_pos, 2, replacement);\n return originalString;\n}\n\ntemplate<class...Ts>\nvoid Replace(std::string& originalString, const Ts&... rest)\n{\n (ReplaceOne(originalString, rest) , ...);\n}\n std::string original = \"This is example %s in my program for Mr. %s.\";\n const std::string expected = \"This is example 5 in my program for Mr. Jimmy.\";\nReplace(original, \"5\", \"Jimmy\");\nassert(original == expected);\n ReplaceOne \"%s\" \"%s\" std::string::find \"%s\" O(N * M) N M O(N) find find" }, { "answer_id": 74645662, "author": "rturrado", "author_id": 260313, "author_profile": "https://Stackoverflow.com/users/260313", "pm_score": 1, "selected": false, "text": "rest arg ReplaceImpl Replace ##include <iostream>\n#include <string>\n\nconst std::string FindOriginal(std::string Key) {\n if (Key == \"Toon\") {\n return \"This is example %s in my program for Mr. %s.\";\n }\n return {};\n}\n\nstd::string ReplaceImpl(std::string str) {\n return str;\n}\n\ntemplate <typename First, typename... Strings>\nstd::string ReplaceImpl(std::string str, First arg, const Strings&... rest) {\n if (auto pos{ str.find(\"%s\") }; pos != std::string::npos) {\n return\n str.substr(0, pos) + \n arg +\n ReplaceImpl(str.substr(pos + 2), rest...);\n }\n return str;\n}\n\ntemplate <typename First, typename... Strings>\nstd::string Replace(std::string OriginalKey, First arg, const Strings&... rest) {\n if (auto the_string{ FindOriginal(OriginalKey) }; not the_string.empty()) {\n return ReplaceImpl(the_string, arg, rest...);\n }\n return {};\n}\n\nint main() {\n std::cout << Replace(\"Toon\", \"5\", \"Jimmy\") << \"\\n\";\n}\n\n// Outputs: This is example 5 in my program for Mr. Jimmy.\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20599676/" ]
74,644,461
<p>So, I'm trying to insert data from .csv file, but because of the date format I'm using - import causes it to set to 00-00-0000</p> <p>import settings: format - CSV using load data (otherwise it causing errors and failing to import) Specific format options: none</p> <p>Errors I'm receiving after import:</p> <ul> <li>Data truncated for column... my_date sets to 0000-00-00, even with 'DD/MMM/yyyy' date format,</li> </ul> <p>my csv file structure: (just in case if i need to use specific format)</p> <p>name;1;1st Jan 2021;2st Jan 2021;;;;;;;;;;;;;</p> <p>Technically, I could format it manually to 12 jun 2021 / 12.06.2021 / 12/06/2021 but I would like to avoid that.</p> <p>Sorry if it's a dumb question and the answer is simple, but I have no idea how to fix it. :)</p> <p>I already tried this but still nothing.</p> <pre><code>SET lc_time_names = 'en_US'; select date_format(my_date, 'DD MMM yyyy') FROM table1; select date_format(my_date, 'DD/MMM/yyyy') FROM table1; </code></pre>
[ { "answer_id": 74645415, "author": "Ozan Sen", "author_id": 19469088, "author_profile": "https://Stackoverflow.com/users/19469088", "pm_score": 2, "selected": true, "text": "UPDATE myimport\nSET StartDate = STR_TO_DATE(StartDate,'%D %b %Y');\nUPDATE myimport\nSET FinishDate = STR_TO_DATE(FinishDate,'%D %b %Y');\n ALTER TABLE myimport\nMODIFY COLUMN StartDate DATE, \nMODIFY COLUMN FinishDate DATE;\n mysql> SELECT * FROM myimport;\n+------+------+------------+------------+\n| name | Row | StartDate | FinishDate |\n+------+------+------------+------------+\n| name | 1 | 2021-01-01 | 2021-01-02 |\n+------+------+------------+------------+\n1 row in set (0.00 sec)\n SHOW CREATE TABLE myimport;\n+----------+------------------------------------------------------\n| Table | Create Table |\n+----------+------------------------------------------------------\n| myimport | CREATE TABLE `myimport` (\n `name` text,\n `Row` int DEFAULT NULL,\n `StartDate` date DEFAULT NULL,\n `FinishDate` date DEFAULT NULL\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |\n+----------+------------------------------------------------------\n1 row in set (0.00 sec)\n" }, { "answer_id": 74646059, "author": "Md.Tahmid Farzan", "author_id": 20655686, "author_profile": "https://Stackoverflow.com/users/20655686", "pm_score": 0, "selected": false, "text": "select date_format(`created_at`, '%D %b %Y') FROM product_attributes;\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74644461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17709424/" ]