qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
70,925,248
So, I was working on commerce.js API. But when I press add to cart, it takes a bit of time to update the cart items number (from API) so I thought I should add a loading button until the cart items load. I found LoadingButton from **@mui/lab** so I used it. but the problem is even though that button is inside the loop when pressing onClick all the other button also goes to the loading state. IDK am I missing something or is my coding false?. Please check below & help me. Thanks. :) ***Here is the main problem.*** [![material ui](https://i.stack.imgur.com/g3p6N.gif)](https://i.stack.imgur.com/g3p6N.gif) Here is the app.js where you can see loading state & other API fetching [![enter image description here](https://i.stack.imgur.com/qEncG.png)](https://i.stack.imgur.com/qEncG.png) products component in app.js. you can see I passed down the products & loading props [![enter image description here](https://i.stack.imgur.com/EKAbS.png)](https://i.stack.imgur.com/EKAbS.png) products loop & props down to product component [![enter image description here](https://i.stack.imgur.com/yH4iW.png)](https://i.stack.imgur.com/yH4iW.png) finally the cart loading button in the product component with loading props. it works but all other buttons also loads at the same time. [![enter image description here](https://i.stack.imgur.com/x908f.png)](https://i.stack.imgur.com/x908f.png)
2022/01/31
[ "https://Stackoverflow.com/questions/70925248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12328282/" ]
It is not possible to use the value of a non-static member as default argument. You can use an overload instead: ``` struct S { int a; int func(int b) { // do something } int func() { return func(a); } }; ```
Another alternative is to use [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional): ``` struct S { int a; int func(std::optional<int> ob = std::nullopt) { int b = ob.value_or(a); // do something } }; ```
42,805,018
I want to use SSL with varnish on my magento store, with nginx I did a proxy pass to the port 80 (varnish listen it). But when I do that the ESI block returns 404. If I bypass varnish (change proxy port to 8080 for nginx) it works. Varnish config : ``` C{ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <pthread.h> static pthread_mutex_t lrand_mutex = PTHREAD_MUTEX_INITIALIZER; void generate_uuid(char* buf) { pthread_mutex_lock(&lrand_mutex); long a = lrand48(); long b = lrand48(); long c = lrand48(); long d = lrand48(); pthread_mutex_unlock(&lrand_mutex); sprintf(buf, "frontend=%08lx%04lx%04lx%04lx%04lx%08lx", a, b & 0xffff, (b & ((long)0x0fff0000) >> 16) | 0x4000, (c & 0x0fff) | 0x8000, (c & (long)0xffff0000) >> 16, d ); return; } }C import std; backend default { .host = "127.0.0.1"; .port = "8080"; .first_byte_timeout = 600s; .between_bytes_timeout = 600s; } backend admin { .host = "127.0.0.1"; .port = "8080"; .first_byte_timeout = 21600s; .between_bytes_timeout = 21600s; } acl crawler_acl { "127.0.0.1"; } acl debug_acl { "100.100.100.100"; } acl purge { "localhost"; "192.168.10.0"/24; } sub generate_session { if (req.url ~ ".*[&?]SID=([^&]+).*") { set req.http.X-Varnish-Faked-Session = regsub( req.url, ".*[&?]SID=([^&]+).*", "frontend=\1"); } else { C{ char uuid_buf [50]; generate_uuid(uuid_buf); VRT_SetHdr(sp, HDR_REQ, "\030X-Varnish-Faked-Session:", uuid_buf, vrt_magic_string_end ); }C } if (req.http.Cookie) { std.collect(req.http.Cookie); set req.http.Cookie = req.http.X-Varnish-Faked-Session + "; " + req.http.Cookie; } else { set req.http.Cookie = req.http.X-Varnish-Faked-Session; } } sub generate_session_expires { C{ time_t now = time(NULL); struct tm now_tm = *gmtime(&now); now_tm.tm_sec += 3600; mktime(&now_tm); char date_buf [50]; strftime(date_buf, sizeof(date_buf)-1, "%a, %d-%b-%Y %H:%M:%S %Z", &now_tm); VRT_SetHdr(sp, HDR_RESP, "\031X-Varnish-Cookie-Expires:", date_buf, vrt_magic_string_end ); }C } sub vcl_recv { if (req.request == "PURGE") { if (!client.ip ~ purge) { error 405 "Not allowed."; } return (lookup); } if (req.restarts == 0) { if (req.http.X-Forwarded-For) { set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", " + client.ip; } else { set req.http.X-Forwarded-For = client.ip; } } if (!true || req.http.Authorization || req.request !~ "^(GET|HEAD)$" || req.http.Cookie ~ "varnish_bypass=1") { return (pipe); } set req.url = regsuball(req.url, "(.*)//+(.*)", "\1/\2"); if (req.http.Accept-Encoding) { if (req.http.Accept-Encoding ~ "gzip") { set req.http.Accept-Encoding = "gzip"; } else if (req.http.Accept-Encoding ~ "deflate") { set req.http.Accept-Encoding = "deflate"; } else { unset req.http.Accept-Encoding; } } if (req.url ~ "^(/media/|/skin/|/js/|/)(?:(?:index|litespeed)\.php/)?") { set req.http.X-Turpentine-Secret-Handshake = "1"; if (req.url ~ "^(/media/|/skin/|/js/|/)(?:(?:index|litespeed)\.php/)?(?:admin|compare)") { set req.backend = admin; return (pipe); } if (req.http.Cookie ~ "\bcurrency=") { set req.http.X-Varnish-Currency = regsub( req.http.Cookie, ".*\bcurrency=([^;]*).*", "\1"); } if (req.http.Cookie ~ "\bstore=") { set req.http.X-Varnish-Store = regsub( req.http.Cookie, ".*\bstore=([^;]*).*", "\1"); } if (req.url ~ "/turpentine/esi/get(?:Block|FormKey)/") { set req.http.X-Varnish-Esi-Method = regsub( req.url, ".*/method/(\w+)/.*", "\1"); set req.http.X-Varnish-Esi-Access = regsub( req.url, ".*/access/(\w+)/.*", "\1"); if (req.http.X-Varnish-Esi-Method == "esi" && req.esi_level == 0 && !(false || client.ip ~ debug_acl)) { error 403 "External ESI requests are not allowed"; } } if (req.http.Cookie !~ "frontend=") { if (client.ip ~ crawler_acl || req.http.User-Agent ~ "^(?:ApacheBench/.*|.*Googlebot.*|JoeDog/.*Siege.*|magespeedtest\.com|Nexcessnet_Turpentine/.*)$") { set req.http.Cookie = "frontend=crawler-session"; } else { call generate_session; } } if (true && req.url ~ ".*\.(?:css|js|jpe?g|png|gif|ico|swf)(?=\?|&|$)") { unset req.http.Cookie; unset req.http.X-Varnish-Faked-Session; return (lookup); } # if (req.url ~ "(checkout|BackgroundTask)"){ # return (pass); # } if (req.url ~ "^(/media/|/skin/|/js/|/)(?:(?:index|litespeed)\.php/)?(?:admin|compare|varnish|Purchase|scripts)" || req.url ~ "^/media/flux" || req.url ~ "^/media/catalog/btob/21/" || req.url ~ "/wp-(login|admin)" || req.url ~ "preview=true" || req.url ~ "\?.*__from_store=") { return (pipe); } if (true && req.url ~ "(?:[?&](?:__SID|XDEBUG_PROFILE)(?=[&=]|$))") { return (pass); } if (req.url ~ "[?&](utm_source|utm_medium|utm_campaign|gclid|cx|ie|cof|siteurl)=") { set req.url = regsuball(req.url, "(?:(\?)?|&)(?:utm_source|utm_medium|utm_campaign|gclid|cx|ie|cof|siteurl)=[^&]+", "\1"); set req.url = regsuball(req.url, "(?:(\?)&|\?$)", "\1"); } return (lookup); } } sub vcl_pipe { unset bereq.http.X-Turpentine-Secret-Handshake; set bereq.http.Connection = "close"; } sub vcl_hash { hash_data(req.url); if (req.http.Host) { hash_data(req.http.Host); } else { hash_data(server.ip); } hash_data(req.http.Ssl-Offloaded); if (req.http.X-Normalized-User-Agent) { hash_data(req.http.X-Normalized-User-Agent); } if (req.http.Accept-Encoding) { hash_data(req.http.Accept-Encoding); } if (req.http.X-Varnish-Store || req.http.X-Varnish-Currency) { hash_data("s=" + req.http.X-Varnish-Store + "&c=" + req.http.X-Varnish-Currency); } if (req.http.X-Varnish-Esi-Access == "private" && req.http.Cookie ~ "frontend=") { hash_data(regsub(req.http.Cookie, "^.*?frontend=([^;]*);*.*$", "\1")); } return (hash); } sub vcl_hit { if (req.request == "PURGE") { purge; error 200 "Purged."; } } sub vcl_miss { if (req.request == "PURGE") { purge; error 200 "Purged."; } } sub vcl_fetch { set req.grace = 15s; set beresp.http.X-Varnish-Host = req.http.host; set beresp.http.X-Varnish-URL = req.url; if (req.url ~ "^(/festival/media/|/festival/skin/|/festival/js/|/festival/|/media/|/skin/|/js/|/)(?:(?:index|litespeed)\.php/)?") { unset beresp.http.Vary; set beresp.do_gzip = true; # if (beresp.status != 200 && beresp.status != 404) { if (beresp.status != 200) { set beresp.ttl = 15s; return (hit_for_pass); } else { if (beresp.http.Set-Cookie) { set beresp.http.X-Varnish-Set-Cookie = beresp.http.Set-Cookie; unset beresp.http.Set-Cookie; } unset beresp.http.Cache-Control; unset beresp.http.Expires; unset beresp.http.Pragma; unset beresp.http.Cache; unset beresp.http.Age; if (beresp.http.X-Turpentine-Esi == "1") { set beresp.do_esi = true; } if (beresp.http.X-Turpentine-Cache == "0") { set beresp.ttl = 15s; return (hit_for_pass); } else { if (true && bereq.url ~ ".*\.(?:css|js|jpe?g|png|gif|ico|swf)(?=\?|&|$)") { set beresp.ttl = 315360000s; set beresp.http.Cache-Control = "max-age=315360000"; } elseif (req.http.X-Varnish-Esi-Method) { if (req.http.X-Varnish-Esi-Access == "private" && req.http.Cookie ~ "frontend=") { set beresp.http.X-Varnish-Session = regsub(req.http.Cookie, "^.*?frontend=([^;]*);*.*$", "\1"); } if (req.http.X-Varnish-Esi-Method == "ajax" && req.http.X-Varnish-Esi-Access == "public") { set beresp.http.Cache-Control = "max-age=" + regsub( req.url, ".*/ttl/(\d+)/.*", "\1"); } set beresp.ttl = std.duration( regsub( req.url, ".*/ttl/(\d+)/.*", "\1s"), 300s); if (beresp.ttl == 0s) { set beresp.ttl = 15s; return (hit_for_pass); } } else { set beresp.ttl = 3600s; } } } return (deliver); } } sub vcl_deliver { if (req.http.X-Varnish-Faked-Session) { call generate_session_expires; set resp.http.Set-Cookie = req.http.X-Varnish-Faked-Session + "; expires=" + resp.http.X-Varnish-Cookie-Expires + "; path=/"; if (req.http.Host) { set resp.http.Set-Cookie = resp.http.Set-Cookie + "; domain=" + regsub(req.http.Host, ":\d+$", ""); } set resp.http.Set-Cookie = resp.http.Set-Cookie + "; httponly"; unset resp.http.X-Varnish-Cookie-Expires; } if (req.http.X-Varnish-Esi-Method == "ajax" && req.http.X-Varnish-Esi-Access == "private") { set resp.http.Cache-Control = "no-cache"; } if (false || client.ip ~ debug_acl) { set resp.http.X-Varnish-Hits = obj.hits; set resp.http.X-Varnish-Esi-Method = req.http.X-Varnish-Esi-Method; set resp.http.X-Varnish-Esi-Access = req.http.X-Varnish-Esi-Access; set resp.http.X-Varnish-Currency = req.http.X-Varnish-Currency; set resp.http.X-Varnish-Store = req.http.X-Varnish-Store; } else { unset resp.http.X-Varnish; unset resp.http.Via; unset resp.http.X-Powered-By; unset resp.http.Server; unset resp.http.X-Turpentine-Cache; unset resp.http.X-Turpentine-Esi; unset resp.http.X-Turpentine-Flush-Events; unset resp.http.X-Turpentine-Block; unset resp.http.X-Varnish-Session; unset resp.http.X-Varnish-Host; unset resp.http.X-Varnish-URL; unset resp.http.X-Varnish-Set-Cookie; } } ``` Nginx conf : ``` server{ listen 443 ssl; server_name new.mywebsite.com; ssl_certificate /etc/nginx/ssl/bundle.crt; ssl_certificate_key /etc/nginx/ssl/website.key; location /{ proxy_pass http://127.0.0.1:80; 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 https; proxy_set_header X-Forwarded-Port 443; proxy_set_header Host $host; } } server { listen 8080; server_name new.website.com; #charset koi8-r; access_log /var/log/nginx/log/website.access.log main; error_log /var/log/nginx/log/website.error.log; set $ua ''; set $zget /zget; set $mzi /ZOOM_INDEX; set $code mywebsite; set $zoombase /var/zoom/$code$ua; set $zoomuri $zoombase$uri; set $zoomuriget $zoomuri$zget; set $p 1; set $dir $cookie_zoom_dir; set $limit $cookie_zoom_limit; set $mode $cookie_zoom_mode; set $order $cookie_zoom_order; set $zoomg $zoomuriget; set $cat ""; set $price ""; if ($arg_p) { set $p $arg_p; } if ($arg_dir) { set $dir $arg_dir; } if ($arg_limit) { set $limit $arg_limit; } if ($arg_mode) { set $mode $arg_mode; } if ($arg_order) { set $order $arg_order; } # Layered navigation will be appended in alphabetical order to the final string if ($arg_cat) { set $cat /cat/$arg_cat; } if ($arg_price) { set $price /price/$arg_price; } set $control &dir=$dir&limit=$limit&mode=$mode&order=$order; # If there is no given toolbar state, look for symlink of the default state (at the given page) if ($control = "&dir=&limit=&mode=&order=") { set $zoomg $zoomg/p/$p; } # Otherwise, construct complete cache filename (this requires normalized URL for consistent hits) if ($zoomg = $zoomuriget) { set $zoomg $zoomg/p/$p/dir/$dir/limit/$limit/mode/$mode/order/$order$cat$price; } # A fix to redirect the index page to the proper file if ($request_uri = /) { set $zoomuri $zoomuri$mzi; } # Append the "ZOOM_INDEX" to the file category path set $zoomg $zoomg$mzi; # Now clean the filename of irregular characters if ($zoomg ~ (.*)/price/([0-9]+),([0-9]+)(.*)) { set $zoomg $1/price/$2%2C$3$4; } set $my_ssl "off"; if ($http_x_forwarded_proto = "https"){ set $my_ssl "on"; } root /home/site/mywebsite; location / { index index.html index.htm index.php; default_type text/html; try_files $zoomuri $zoomg $uri $uri/ @redirect; } location @redirect { rewrite / /index.php; } location ~ \.php$ { if (!-e $request_filename) { rewrite / /index.php last; } expires off; try_files $uri /index.php; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param HTTPS $my_ssl; fastcgi_param MAGE_RUN_CODE mywebsite; fastcgi_param MAGE_RUN_TYPE website; fastcgi_param SCRIPT_NAME $fastcgi_script_name; } } ```
2017/03/15
[ "https://Stackoverflow.com/questions/42805018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343313/" ]
You should **always** explicitly add the columns you want to update in a table, it's good practice, your need for shortening the query notwithstanding. That being said, try inserting "null" and checking if it works. No guarantee here, haven't tried so myself.
I've never seen an `UPDATE` written the way you have it in MySQL. A typical `UPDATE` along the lines of what you want you want would look something like this: ``` UPDATE tbl SET f1 = 'new-f1-val', f2 = 'new-f2-val', f4 = 'new-f4-val' WHERE <some condition> ``` If you don't want to modify the `f3` column, then just leave it out of your `UPDATE` statement.
42,805,018
I want to use SSL with varnish on my magento store, with nginx I did a proxy pass to the port 80 (varnish listen it). But when I do that the ESI block returns 404. If I bypass varnish (change proxy port to 8080 for nginx) it works. Varnish config : ``` C{ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <pthread.h> static pthread_mutex_t lrand_mutex = PTHREAD_MUTEX_INITIALIZER; void generate_uuid(char* buf) { pthread_mutex_lock(&lrand_mutex); long a = lrand48(); long b = lrand48(); long c = lrand48(); long d = lrand48(); pthread_mutex_unlock(&lrand_mutex); sprintf(buf, "frontend=%08lx%04lx%04lx%04lx%04lx%08lx", a, b & 0xffff, (b & ((long)0x0fff0000) >> 16) | 0x4000, (c & 0x0fff) | 0x8000, (c & (long)0xffff0000) >> 16, d ); return; } }C import std; backend default { .host = "127.0.0.1"; .port = "8080"; .first_byte_timeout = 600s; .between_bytes_timeout = 600s; } backend admin { .host = "127.0.0.1"; .port = "8080"; .first_byte_timeout = 21600s; .between_bytes_timeout = 21600s; } acl crawler_acl { "127.0.0.1"; } acl debug_acl { "100.100.100.100"; } acl purge { "localhost"; "192.168.10.0"/24; } sub generate_session { if (req.url ~ ".*[&?]SID=([^&]+).*") { set req.http.X-Varnish-Faked-Session = regsub( req.url, ".*[&?]SID=([^&]+).*", "frontend=\1"); } else { C{ char uuid_buf [50]; generate_uuid(uuid_buf); VRT_SetHdr(sp, HDR_REQ, "\030X-Varnish-Faked-Session:", uuid_buf, vrt_magic_string_end ); }C } if (req.http.Cookie) { std.collect(req.http.Cookie); set req.http.Cookie = req.http.X-Varnish-Faked-Session + "; " + req.http.Cookie; } else { set req.http.Cookie = req.http.X-Varnish-Faked-Session; } } sub generate_session_expires { C{ time_t now = time(NULL); struct tm now_tm = *gmtime(&now); now_tm.tm_sec += 3600; mktime(&now_tm); char date_buf [50]; strftime(date_buf, sizeof(date_buf)-1, "%a, %d-%b-%Y %H:%M:%S %Z", &now_tm); VRT_SetHdr(sp, HDR_RESP, "\031X-Varnish-Cookie-Expires:", date_buf, vrt_magic_string_end ); }C } sub vcl_recv { if (req.request == "PURGE") { if (!client.ip ~ purge) { error 405 "Not allowed."; } return (lookup); } if (req.restarts == 0) { if (req.http.X-Forwarded-For) { set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", " + client.ip; } else { set req.http.X-Forwarded-For = client.ip; } } if (!true || req.http.Authorization || req.request !~ "^(GET|HEAD)$" || req.http.Cookie ~ "varnish_bypass=1") { return (pipe); } set req.url = regsuball(req.url, "(.*)//+(.*)", "\1/\2"); if (req.http.Accept-Encoding) { if (req.http.Accept-Encoding ~ "gzip") { set req.http.Accept-Encoding = "gzip"; } else if (req.http.Accept-Encoding ~ "deflate") { set req.http.Accept-Encoding = "deflate"; } else { unset req.http.Accept-Encoding; } } if (req.url ~ "^(/media/|/skin/|/js/|/)(?:(?:index|litespeed)\.php/)?") { set req.http.X-Turpentine-Secret-Handshake = "1"; if (req.url ~ "^(/media/|/skin/|/js/|/)(?:(?:index|litespeed)\.php/)?(?:admin|compare)") { set req.backend = admin; return (pipe); } if (req.http.Cookie ~ "\bcurrency=") { set req.http.X-Varnish-Currency = regsub( req.http.Cookie, ".*\bcurrency=([^;]*).*", "\1"); } if (req.http.Cookie ~ "\bstore=") { set req.http.X-Varnish-Store = regsub( req.http.Cookie, ".*\bstore=([^;]*).*", "\1"); } if (req.url ~ "/turpentine/esi/get(?:Block|FormKey)/") { set req.http.X-Varnish-Esi-Method = regsub( req.url, ".*/method/(\w+)/.*", "\1"); set req.http.X-Varnish-Esi-Access = regsub( req.url, ".*/access/(\w+)/.*", "\1"); if (req.http.X-Varnish-Esi-Method == "esi" && req.esi_level == 0 && !(false || client.ip ~ debug_acl)) { error 403 "External ESI requests are not allowed"; } } if (req.http.Cookie !~ "frontend=") { if (client.ip ~ crawler_acl || req.http.User-Agent ~ "^(?:ApacheBench/.*|.*Googlebot.*|JoeDog/.*Siege.*|magespeedtest\.com|Nexcessnet_Turpentine/.*)$") { set req.http.Cookie = "frontend=crawler-session"; } else { call generate_session; } } if (true && req.url ~ ".*\.(?:css|js|jpe?g|png|gif|ico|swf)(?=\?|&|$)") { unset req.http.Cookie; unset req.http.X-Varnish-Faked-Session; return (lookup); } # if (req.url ~ "(checkout|BackgroundTask)"){ # return (pass); # } if (req.url ~ "^(/media/|/skin/|/js/|/)(?:(?:index|litespeed)\.php/)?(?:admin|compare|varnish|Purchase|scripts)" || req.url ~ "^/media/flux" || req.url ~ "^/media/catalog/btob/21/" || req.url ~ "/wp-(login|admin)" || req.url ~ "preview=true" || req.url ~ "\?.*__from_store=") { return (pipe); } if (true && req.url ~ "(?:[?&](?:__SID|XDEBUG_PROFILE)(?=[&=]|$))") { return (pass); } if (req.url ~ "[?&](utm_source|utm_medium|utm_campaign|gclid|cx|ie|cof|siteurl)=") { set req.url = regsuball(req.url, "(?:(\?)?|&)(?:utm_source|utm_medium|utm_campaign|gclid|cx|ie|cof|siteurl)=[^&]+", "\1"); set req.url = regsuball(req.url, "(?:(\?)&|\?$)", "\1"); } return (lookup); } } sub vcl_pipe { unset bereq.http.X-Turpentine-Secret-Handshake; set bereq.http.Connection = "close"; } sub vcl_hash { hash_data(req.url); if (req.http.Host) { hash_data(req.http.Host); } else { hash_data(server.ip); } hash_data(req.http.Ssl-Offloaded); if (req.http.X-Normalized-User-Agent) { hash_data(req.http.X-Normalized-User-Agent); } if (req.http.Accept-Encoding) { hash_data(req.http.Accept-Encoding); } if (req.http.X-Varnish-Store || req.http.X-Varnish-Currency) { hash_data("s=" + req.http.X-Varnish-Store + "&c=" + req.http.X-Varnish-Currency); } if (req.http.X-Varnish-Esi-Access == "private" && req.http.Cookie ~ "frontend=") { hash_data(regsub(req.http.Cookie, "^.*?frontend=([^;]*);*.*$", "\1")); } return (hash); } sub vcl_hit { if (req.request == "PURGE") { purge; error 200 "Purged."; } } sub vcl_miss { if (req.request == "PURGE") { purge; error 200 "Purged."; } } sub vcl_fetch { set req.grace = 15s; set beresp.http.X-Varnish-Host = req.http.host; set beresp.http.X-Varnish-URL = req.url; if (req.url ~ "^(/festival/media/|/festival/skin/|/festival/js/|/festival/|/media/|/skin/|/js/|/)(?:(?:index|litespeed)\.php/)?") { unset beresp.http.Vary; set beresp.do_gzip = true; # if (beresp.status != 200 && beresp.status != 404) { if (beresp.status != 200) { set beresp.ttl = 15s; return (hit_for_pass); } else { if (beresp.http.Set-Cookie) { set beresp.http.X-Varnish-Set-Cookie = beresp.http.Set-Cookie; unset beresp.http.Set-Cookie; } unset beresp.http.Cache-Control; unset beresp.http.Expires; unset beresp.http.Pragma; unset beresp.http.Cache; unset beresp.http.Age; if (beresp.http.X-Turpentine-Esi == "1") { set beresp.do_esi = true; } if (beresp.http.X-Turpentine-Cache == "0") { set beresp.ttl = 15s; return (hit_for_pass); } else { if (true && bereq.url ~ ".*\.(?:css|js|jpe?g|png|gif|ico|swf)(?=\?|&|$)") { set beresp.ttl = 315360000s; set beresp.http.Cache-Control = "max-age=315360000"; } elseif (req.http.X-Varnish-Esi-Method) { if (req.http.X-Varnish-Esi-Access == "private" && req.http.Cookie ~ "frontend=") { set beresp.http.X-Varnish-Session = regsub(req.http.Cookie, "^.*?frontend=([^;]*);*.*$", "\1"); } if (req.http.X-Varnish-Esi-Method == "ajax" && req.http.X-Varnish-Esi-Access == "public") { set beresp.http.Cache-Control = "max-age=" + regsub( req.url, ".*/ttl/(\d+)/.*", "\1"); } set beresp.ttl = std.duration( regsub( req.url, ".*/ttl/(\d+)/.*", "\1s"), 300s); if (beresp.ttl == 0s) { set beresp.ttl = 15s; return (hit_for_pass); } } else { set beresp.ttl = 3600s; } } } return (deliver); } } sub vcl_deliver { if (req.http.X-Varnish-Faked-Session) { call generate_session_expires; set resp.http.Set-Cookie = req.http.X-Varnish-Faked-Session + "; expires=" + resp.http.X-Varnish-Cookie-Expires + "; path=/"; if (req.http.Host) { set resp.http.Set-Cookie = resp.http.Set-Cookie + "; domain=" + regsub(req.http.Host, ":\d+$", ""); } set resp.http.Set-Cookie = resp.http.Set-Cookie + "; httponly"; unset resp.http.X-Varnish-Cookie-Expires; } if (req.http.X-Varnish-Esi-Method == "ajax" && req.http.X-Varnish-Esi-Access == "private") { set resp.http.Cache-Control = "no-cache"; } if (false || client.ip ~ debug_acl) { set resp.http.X-Varnish-Hits = obj.hits; set resp.http.X-Varnish-Esi-Method = req.http.X-Varnish-Esi-Method; set resp.http.X-Varnish-Esi-Access = req.http.X-Varnish-Esi-Access; set resp.http.X-Varnish-Currency = req.http.X-Varnish-Currency; set resp.http.X-Varnish-Store = req.http.X-Varnish-Store; } else { unset resp.http.X-Varnish; unset resp.http.Via; unset resp.http.X-Powered-By; unset resp.http.Server; unset resp.http.X-Turpentine-Cache; unset resp.http.X-Turpentine-Esi; unset resp.http.X-Turpentine-Flush-Events; unset resp.http.X-Turpentine-Block; unset resp.http.X-Varnish-Session; unset resp.http.X-Varnish-Host; unset resp.http.X-Varnish-URL; unset resp.http.X-Varnish-Set-Cookie; } } ``` Nginx conf : ``` server{ listen 443 ssl; server_name new.mywebsite.com; ssl_certificate /etc/nginx/ssl/bundle.crt; ssl_certificate_key /etc/nginx/ssl/website.key; location /{ proxy_pass http://127.0.0.1:80; 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 https; proxy_set_header X-Forwarded-Port 443; proxy_set_header Host $host; } } server { listen 8080; server_name new.website.com; #charset koi8-r; access_log /var/log/nginx/log/website.access.log main; error_log /var/log/nginx/log/website.error.log; set $ua ''; set $zget /zget; set $mzi /ZOOM_INDEX; set $code mywebsite; set $zoombase /var/zoom/$code$ua; set $zoomuri $zoombase$uri; set $zoomuriget $zoomuri$zget; set $p 1; set $dir $cookie_zoom_dir; set $limit $cookie_zoom_limit; set $mode $cookie_zoom_mode; set $order $cookie_zoom_order; set $zoomg $zoomuriget; set $cat ""; set $price ""; if ($arg_p) { set $p $arg_p; } if ($arg_dir) { set $dir $arg_dir; } if ($arg_limit) { set $limit $arg_limit; } if ($arg_mode) { set $mode $arg_mode; } if ($arg_order) { set $order $arg_order; } # Layered navigation will be appended in alphabetical order to the final string if ($arg_cat) { set $cat /cat/$arg_cat; } if ($arg_price) { set $price /price/$arg_price; } set $control &dir=$dir&limit=$limit&mode=$mode&order=$order; # If there is no given toolbar state, look for symlink of the default state (at the given page) if ($control = "&dir=&limit=&mode=&order=") { set $zoomg $zoomg/p/$p; } # Otherwise, construct complete cache filename (this requires normalized URL for consistent hits) if ($zoomg = $zoomuriget) { set $zoomg $zoomg/p/$p/dir/$dir/limit/$limit/mode/$mode/order/$order$cat$price; } # A fix to redirect the index page to the proper file if ($request_uri = /) { set $zoomuri $zoomuri$mzi; } # Append the "ZOOM_INDEX" to the file category path set $zoomg $zoomg$mzi; # Now clean the filename of irregular characters if ($zoomg ~ (.*)/price/([0-9]+),([0-9]+)(.*)) { set $zoomg $1/price/$2%2C$3$4; } set $my_ssl "off"; if ($http_x_forwarded_proto = "https"){ set $my_ssl "on"; } root /home/site/mywebsite; location / { index index.html index.htm index.php; default_type text/html; try_files $zoomuri $zoomg $uri $uri/ @redirect; } location @redirect { rewrite / /index.php; } location ~ \.php$ { if (!-e $request_filename) { rewrite / /index.php last; } expires off; try_files $uri /index.php; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param HTTPS $my_ssl; fastcgi_param MAGE_RUN_CODE mywebsite; fastcgi_param MAGE_RUN_TYPE website; fastcgi_param SCRIPT_NAME $fastcgi_script_name; } } ```
2017/03/15
[ "https://Stackoverflow.com/questions/42805018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343313/" ]
You should **always** explicitly add the columns you want to update in a table, it's good practice, your need for shortening the query notwithstanding. That being said, try inserting "null" and checking if it works. No guarantee here, haven't tried so myself.
Check out for update query syntax. <https://dev.mysql.com/doc/refman/5.7/en/update.html> ``` Update tbl set f1=new-f1-val, f2=new-f2-val, f4=new-f4-val ```
387,528
Consider that the outcome of Alice's efforts are understood to be satisfactory or even excellent, by her peers and the upper hierarchy. Given that Alice recognises she can deliver even better than she did, how should Alice formally state that she aims to do better than she has achieved without risking being misunderstood to imply she has been underachieving? Assuming Alice had expressed the following in a written statement ***"my goal is to be more efficient and to close more deals per month"***, if Bob when reading that may be unaware of Alice's performance history, how could Alice have phrased her statement better to guarantee that someone like Bob would never perceive it negatively?
2017/05/02
[ "https://english.stackexchange.com/questions/387528", "https://english.stackexchange.com", "https://english.stackexchange.com/users/126985/" ]
Without substantially altering your sentence, the simplest way to convey that her current achievement is already very good, would be (in my opinion) to use 'even more' as an intensified form of 'more' as in > > "my goal is to be **even more efficient** and to close more deals per month" > > > where she can clearly convey the meaning 'I know I am efficient; I aim to be 'even more efficient!' Note: You might be tempted to use 'even more' twice in the sentence as in > > 'my goal is to be **even more** efficient and to close **even more** more deals per month' > > > in order to be **even more** impressive, but beware! -- repetition of intensified statements actually reduces the impact and can even be misinterpreted in many ways, therefore best avoided.
Most people would not take the statement as negative. However the simplest change the emphasis to the positive is to add the word 'even' before the goals. > > My goal is to be *even* more efficient and to close *even* more sales per month. > > > It's not a subtle change.
387,528
Consider that the outcome of Alice's efforts are understood to be satisfactory or even excellent, by her peers and the upper hierarchy. Given that Alice recognises she can deliver even better than she did, how should Alice formally state that she aims to do better than she has achieved without risking being misunderstood to imply she has been underachieving? Assuming Alice had expressed the following in a written statement ***"my goal is to be more efficient and to close more deals per month"***, if Bob when reading that may be unaware of Alice's performance history, how could Alice have phrased her statement better to guarantee that someone like Bob would never perceive it negatively?
2017/05/02
[ "https://english.stackexchange.com/questions/387528", "https://english.stackexchange.com", "https://english.stackexchange.com/users/126985/" ]
Without substantially altering your sentence, the simplest way to convey that her current achievement is already very good, would be (in my opinion) to use 'even more' as an intensified form of 'more' as in > > "my goal is to be **even more efficient** and to close more deals per month" > > > where she can clearly convey the meaning 'I know I am efficient; I aim to be 'even more efficient!' Note: You might be tempted to use 'even more' twice in the sentence as in > > 'my goal is to be **even more** efficient and to close **even more** more deals per month' > > > in order to be **even more** impressive, but beware! -- repetition of intensified statements actually reduces the impact and can even be misinterpreted in many ways, therefore best avoided.
When taken without the full context, yes, it may appear that Alice is acknowledging inferior performance by saying "my goal is to be more efficient and to close more deals per month". One way for Alice to restate this in a positive way would be > > My successes come from continuously looking for ways to improve. > > > Having a goal of continuous improvement is always taken as a positive attribute. Tying it to prior and ongoing successes emphasizes why she would do this.
387,528
Consider that the outcome of Alice's efforts are understood to be satisfactory or even excellent, by her peers and the upper hierarchy. Given that Alice recognises she can deliver even better than she did, how should Alice formally state that she aims to do better than she has achieved without risking being misunderstood to imply she has been underachieving? Assuming Alice had expressed the following in a written statement ***"my goal is to be more efficient and to close more deals per month"***, if Bob when reading that may be unaware of Alice's performance history, how could Alice have phrased her statement better to guarantee that someone like Bob would never perceive it negatively?
2017/05/02
[ "https://english.stackexchange.com/questions/387528", "https://english.stackexchange.com", "https://english.stackexchange.com/users/126985/" ]
When taken without the full context, yes, it may appear that Alice is acknowledging inferior performance by saying "my goal is to be more efficient and to close more deals per month". One way for Alice to restate this in a positive way would be > > My successes come from continuously looking for ways to improve. > > > Having a goal of continuous improvement is always taken as a positive attribute. Tying it to prior and ongoing successes emphasizes why she would do this.
Most people would not take the statement as negative. However the simplest change the emphasis to the positive is to add the word 'even' before the goals. > > My goal is to be *even* more efficient and to close *even* more sales per month. > > > It's not a subtle change.
24,204,167
Pretty short, I'm not really sure if possible, plus I can't find an example. ``` void Order<T>(List<T> lista) { // get all properties, T is always a class List<PropertyInfo> props = typeof(T).GetProperties().ToList(); // just order by one property, let's say: props[0] List<T> oList = lista.OrderBy( /* props[0] */ ); } ``` Just want the new ordered list.
2014/06/13
[ "https://Stackoverflow.com/questions/24204167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1524477/" ]
Using the code from [this Blog](http://www.daedtech.com/linq-order-by-when-you-have-property-name) results in the following [Extension Method](http://msdn.microsoft.com/en-US/en-en/library/bb383977.aspx): ``` public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> entities, string propertyName) { if (!entities.Any() || string.IsNullOrEmpty(propertyName)) return entities; var propertyInfo = entities.First().GetType().GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); return entities.OrderBy(e => propertyInfo.GetValue(e, null)); } ``` Now you can just do the following: ``` lista.OrderBy(props[0].Name).ToList(); ```
I think this should work (if the property array is not empty) ``` List<T> oList = lista.OrderBy(item => props[0].GetValue(item)).ToList(); ``` On Mono, there's no overload of GetValue that takes a single argument. ``` List<T> oList = lista.OrderBy(item => props[0].GetValue(item, null)).ToList(); ```
444,147
I have been reading lately about electricity markets and I have stumbled upon the term ["volume risk"](https://en.wikipedia.org/wiki/Electricity_market#Risk_management). > > Volume risk is often used to denote the phenomenon whereby electricity market participants have uncertain volumes or quantities of consumption or production. For example, a retailer is unable to accurately predict consumer demand for any particular hour more than a few days into the future and a producer is unable to predict the precise time that they will have plant outage or shortages of fuel. > > > Basically, a fault in the prediction of both the buyer and seller may occur and either the electricity that has been purchased, may not end up being delivered or vice versa, the buyer may have ended up purchasing more electricity than needed. However, I haven't found a clear explanation, what is done in these two cases. Who would cover the electricity difference if the generator does not end up producing the quantity stated in the trade or where would the overproduced electricity go, if the consumer has estimated his consumption poorly?
2019/06/18
[ "https://electronics.stackexchange.com/questions/444147", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/217809/" ]
> > where would the overproduced electricity go, if the consumer has > estimated his consumption poorly? > > > It doesn't go anywhere - if the consumer under-consumes compared to the original prediction then, that under-consumption is physically less-current being taken and less-power being supplied by the generator. Electricity isn't like a delivery van setting off to deliver bread or cakes - it's much more instant than that and if a load takes less current or power then it's pretty much instantly reflected in the generator producing less power and the oil/coal/energy being used by the turbine and generator being less. There is a financial deficit only and that gets resolved by credit arrangements (my guess).
The simple answer to "where would the overproduced electricity go" is that the generator will not produce excess electricity and that causes a reduction in the fuel that feeds the driver of the generator. It is more complex than that. Some types and sizes of generating equipment are easier to "throttle back" than others. Suppliers or groups of suppliers have a range of generating equipment. In general, small and inefficient generators are easy to throttle back and large, more efficient ones can not be efficiently throttled back very much without being shut down completely. Once they are shut down completely, the larger generators tend to require more time and effort (cost) to restart. Suppliers that are interconnected can negotiate over how much energy will be produced by each supplier so that the most efficient mix of equipment is always in operation. A distribution system that does not have a good assortment of supply equipment may be forced, either economically or technically, to discontinue service to some customers in order to shut down some equipment that does not have sufficient customer demand. With interconnected suppliers, situations occasionally arise where one supplier pays another supplier to take "excess energy" for a short time to avoid shutting down equipment that will be difficult tor restart etc. Suppliers will offer to sell energy at the lowest price to customers who accurately predict their demand. To get such a price, the customer may need to agree to compensate the supplier if the actual energy used deviates too much from the prediction. Large customers will have a contract that covers a range of possibilities.
444,147
I have been reading lately about electricity markets and I have stumbled upon the term ["volume risk"](https://en.wikipedia.org/wiki/Electricity_market#Risk_management). > > Volume risk is often used to denote the phenomenon whereby electricity market participants have uncertain volumes or quantities of consumption or production. For example, a retailer is unable to accurately predict consumer demand for any particular hour more than a few days into the future and a producer is unable to predict the precise time that they will have plant outage or shortages of fuel. > > > Basically, a fault in the prediction of both the buyer and seller may occur and either the electricity that has been purchased, may not end up being delivered or vice versa, the buyer may have ended up purchasing more electricity than needed. However, I haven't found a clear explanation, what is done in these two cases. Who would cover the electricity difference if the generator does not end up producing the quantity stated in the trade or where would the overproduced electricity go, if the consumer has estimated his consumption poorly?
2019/06/18
[ "https://electronics.stackexchange.com/questions/444147", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/217809/" ]
> > where would the overproduced electricity go, if the consumer has > estimated his consumption poorly? > > > It doesn't go anywhere - if the consumer under-consumes compared to the original prediction then, that under-consumption is physically less-current being taken and less-power being supplied by the generator. Electricity isn't like a delivery van setting off to deliver bread or cakes - it's much more instant than that and if a load takes less current or power then it's pretty much instantly reflected in the generator producing less power and the oil/coal/energy being used by the turbine and generator being less. There is a financial deficit only and that gets resolved by credit arrangements (my guess).
> > Who would cover the electricity difference if the generator does not > end up producing the quantity stated in the trade or where would the > overproduced electricity go, if the consumer has estimated his > consumption poorly? > > > This is why continuous grid management is needed. Electricity in the grid in most cases cannot be stored for later use. It is a good approximation to assume that at any instant the electric power consumed is exactly equal to the electric power produced. As you know, there are different ways to generate electricity. Some of them are almost 100% predictable (e.g. nuclear power plant), others are not (wind/solar). The challenge for grid management is now to first try and predict production and consumption for a certain period, then to acquire the predicted needed amount of production capacity for that period, and then to keep monitoring fluctuations in production or consumption, i.e. deviations from the predictions, and react on those fluctuations by adding or removing electricity production (sometimes also consumption) as quickly as possible. This is done by employing a certain mix of power producers: A nuclear power plant takes significant time (hours maybe) to significantly increase or decrease power output, wind/solar can very quickly (seconds) be taken off the grid, but e.g. at night solar power cannot be requested to generate some extra power to accomodate increased demand. Gas-powered power plants can be regulated up or down relatively quickly and are thus in demand exactly to fill the gap between the constant base load of the big (e.g. nuclear) power plants and consumption which may vary faster than a nuclear plant could accomodate. The whole thing works very much along the basic economical model, putting a certain price to a certain risk. Nuclear plants produce cheap electricity, but are in-flexible. Solar/wind is also not very flexible. In fact, solar and wind energy are a grid operator's worst nightmare and they're not even cheap but are usually subsidized and otherwise politically encouraged. Gas is more flexible than nuclear and more controllable than solar/wind, but also more expensive per unit of energy (Joule, Wh,...) produced than nuclear and disliked due to CO². Bottomline: Grid operators try to get the cheapest electricity they can, but at the same time they absolutely *must* make sure to always be able to adjust production to varying, unpredictable consumption (or production), because at every instant power supplied to the grid exactly matches the power taken from the grid. If they try and supply more or less than is actually demanded, installations connected to the grid will malfunction (under-supply, i.e. under-voltage) or be destroyed (over-supply, over-voltage). That's just physics.
444,147
I have been reading lately about electricity markets and I have stumbled upon the term ["volume risk"](https://en.wikipedia.org/wiki/Electricity_market#Risk_management). > > Volume risk is often used to denote the phenomenon whereby electricity market participants have uncertain volumes or quantities of consumption or production. For example, a retailer is unable to accurately predict consumer demand for any particular hour more than a few days into the future and a producer is unable to predict the precise time that they will have plant outage or shortages of fuel. > > > Basically, a fault in the prediction of both the buyer and seller may occur and either the electricity that has been purchased, may not end up being delivered or vice versa, the buyer may have ended up purchasing more electricity than needed. However, I haven't found a clear explanation, what is done in these two cases. Who would cover the electricity difference if the generator does not end up producing the quantity stated in the trade or where would the overproduced electricity go, if the consumer has estimated his consumption poorly?
2019/06/18
[ "https://electronics.stackexchange.com/questions/444147", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/217809/" ]
> > where would the overproduced electricity go, if the consumer has > estimated his consumption poorly? > > > It doesn't go anywhere - if the consumer under-consumes compared to the original prediction then, that under-consumption is physically less-current being taken and less-power being supplied by the generator. Electricity isn't like a delivery van setting off to deliver bread or cakes - it's much more instant than that and if a load takes less current or power then it's pretty much instantly reflected in the generator producing less power and the oil/coal/energy being used by the turbine and generator being less. There is a financial deficit only and that gets resolved by credit arrangements (my guess).
There are different kinds of generators. Some do supply constant electricity with monthly schedules like nuclear and thermal power plant, these can't dynamically change the production. The variable part of the demand is supplied by power plants that can quickly turn on and off, these are gas turbine, hydroelectric plant, diesel. In case of increased demand, these power plants are turned on. In case of unplanned decreased demand, and if all small power plants are off, they will try: fill the basins full for reversible power plants (generator/motor), to sell the electricity for small money (or even to pay for) to foreign country, contact steel forgeries to increase production, turn on street lights even in daylight,...whatever to gain time until the demand is repristinated.
15,533,258
If I have a method call in a for loop that is the same for all iterations of the loop - is the compiler smart enough to optimize it? ``` for (int j = 0; j < 24; j++ ) { *destinationPointer++ = identityArray[j] * (1 / powf(2, valueFromAboveInMethod)); } ``` Or should I be explicit and assign it to a value before the loop? ``` float value = 1 / powf(2, valueFromAboveInMethod); // populate the array for (int j = 0; j < 24; j++ ) { *destinationPointer++ = identityArray[j] * value; } ``` I'd be happier if the compiler did something awesome here and I didn't have to use the 4 bytes for the float - this is inside a recursive method.
2013/03/20
[ "https://Stackoverflow.com/questions/15533258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/698947/" ]
It depends on with what options do you compile it. Usually even with minimal optimization enabled compilers deal with such simple optimizations, however it's better to just do it yourself as you have written in the second code. Anyway if compiler will optimize it, it will keep `additional 4 bytes` too, because value need to be stored anywhere.
The compiler may not be smart enough to realize powf is stateless. When in doubt, compile to assembler and check it yourself.
15,533,258
If I have a method call in a for loop that is the same for all iterations of the loop - is the compiler smart enough to optimize it? ``` for (int j = 0; j < 24; j++ ) { *destinationPointer++ = identityArray[j] * (1 / powf(2, valueFromAboveInMethod)); } ``` Or should I be explicit and assign it to a value before the loop? ``` float value = 1 / powf(2, valueFromAboveInMethod); // populate the array for (int j = 0; j < 24; j++ ) { *destinationPointer++ = identityArray[j] * value; } ``` I'd be happier if the compiler did something awesome here and I didn't have to use the 4 bytes for the float - this is inside a recursive method.
2013/03/20
[ "https://Stackoverflow.com/questions/15533258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/698947/" ]
I personally would use a variable here. Not only because it may provide better code, but also because it shows to anyone reading the code that the value doesn't change [I'd give it a better variable-name than "value", however]. I do expect the compiler to actually pre-calculate the value, but as has been mentioned, it does rely on the compiler understanding that `powf` is a pure function (has no side-effects and give the same result for the same input every time). Any additional storage as a consequence of using an extra variable in a recursive call would either be a case of "well, it shouldn't matter" or "you are playing very close to the edge of the abyss of stack overflow". Stack overflow is probably one of the worst types of crashes, as it gives absolutely no warning or way to recover, since the program needs to use a stack to recover, and it may well be the only stack available that overflowed... If your recursive function is either unbounded or you can't guarantee that that the number of recursive calls are well within the limits of the stack, then I would suggest you should redesign this function. Deep recursion is often quite inefficient as well as the fact that it's prone to crashing with stackoverflow [and with a stack that contains forty-thousand calls to the same function, which makes it very easy to figure out why it crashed, but not necessarily easy to figure out the original cause of the deep recursion]. -- Mats
It depends on with what options do you compile it. Usually even with minimal optimization enabled compilers deal with such simple optimizations, however it's better to just do it yourself as you have written in the second code. Anyway if compiler will optimize it, it will keep `additional 4 bytes` too, because value need to be stored anywhere.
15,533,258
If I have a method call in a for loop that is the same for all iterations of the loop - is the compiler smart enough to optimize it? ``` for (int j = 0; j < 24; j++ ) { *destinationPointer++ = identityArray[j] * (1 / powf(2, valueFromAboveInMethod)); } ``` Or should I be explicit and assign it to a value before the loop? ``` float value = 1 / powf(2, valueFromAboveInMethod); // populate the array for (int j = 0; j < 24; j++ ) { *destinationPointer++ = identityArray[j] * value; } ``` I'd be happier if the compiler did something awesome here and I didn't have to use the 4 bytes for the float - this is inside a recursive method.
2013/03/20
[ "https://Stackoverflow.com/questions/15533258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/698947/" ]
I personally would use a variable here. Not only because it may provide better code, but also because it shows to anyone reading the code that the value doesn't change [I'd give it a better variable-name than "value", however]. I do expect the compiler to actually pre-calculate the value, but as has been mentioned, it does rely on the compiler understanding that `powf` is a pure function (has no side-effects and give the same result for the same input every time). Any additional storage as a consequence of using an extra variable in a recursive call would either be a case of "well, it shouldn't matter" or "you are playing very close to the edge of the abyss of stack overflow". Stack overflow is probably one of the worst types of crashes, as it gives absolutely no warning or way to recover, since the program needs to use a stack to recover, and it may well be the only stack available that overflowed... If your recursive function is either unbounded or you can't guarantee that that the number of recursive calls are well within the limits of the stack, then I would suggest you should redesign this function. Deep recursion is often quite inefficient as well as the fact that it's prone to crashing with stackoverflow [and with a stack that contains forty-thousand calls to the same function, which makes it very easy to figure out why it crashed, but not necessarily easy to figure out the original cause of the deep recursion]. -- Mats
The compiler may not be smart enough to realize powf is stateless. When in doubt, compile to assembler and check it yourself.
64,162,161
In CSS I would use `input[type="radio"]:checked { color: #000}` but in Material UI that expression is not valid. In Material UI I create rules using makeStyles: `const useStyles = makeStyles(() => ({ text: { color: "red", }, }));` How can I target `input[type="radio"]` elements using makeStyles?
2020/10/01
[ "https://Stackoverflow.com/questions/64162161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13385688/" ]
You can use `"&:checked"` to target checked radio buttons. That is assuming you are using the native `input` DOM component. If you are using the MUI `<Radio/>`, you can target the [rule name checked](https://material-ui.com/api/radio/#css) ```js const useStyles = makeStyles({ customRadio: { "& + label" : { color: "green" }, "&:checked + label" : { color: "red" } } }) function App() { const classes = useStyles(); return ( <div> <div> <input className={classes.customRadio} type="radio" id="foo" name="test" value="foo" defaultChecked={true} /> <label htmlFor="foo">foo</label> </div> <div> <input className={classes.customRadio} type="radio" id="bar" name="test" value="bar" /> <label htmlFor="bar">bar</label> </div> </div> ); } ReactDOM.render(<App/>, document.getElementById("root")); ``` ```html <body> <div id="root"></div> <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script> <script type="text/babel"> const { makeStyles } = MaterialUI; </script> </body> ```
Have you tried something like this? ``` const useStyles = makeStyles(() => ({ text: { color: "red", }, 'input[type="radio"]:checked': { color: '#000' } })); ```
21,401,891
Can somebody help me to getting the last word from a text which contains only letters. I should use regex I think... For example: ``` 100 r St Lazare, 75009 PARIS ``` I need the word `PARIS`
2014/01/28
[ "https://Stackoverflow.com/questions/21401891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3243871/" ]
You can try with: ``` $input = '100 r St Lazare, 75009 PARIS'; $words = explode(' ', $input); $last = array_pop($words); ``` or ``` $last = $words[count($words) - 1]; ```
Regular expressions and `explode` are possible solutions, however, the fastest one is `substr` in my opinion: ``` $last = substr($words, strrpos($words, " ")+1); ``` `strrpos` returns the offset of last space. That's all you need.
21,401,891
Can somebody help me to getting the last word from a text which contains only letters. I should use regex I think... For example: ``` 100 r St Lazare, 75009 PARIS ``` I need the word `PARIS`
2014/01/28
[ "https://Stackoverflow.com/questions/21401891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3243871/" ]
If you want a **pure** regex solution, you can use ``` ([a-z]+)$|^.*\b([a-z]+)\b ``` as your regex. (Again, replace `[a-z]` with `[^\s\d]` if you're dealing with non-ascii chars) [Demo @ regex101](http://regex101.com/r/yC4vK5) --- Essentially there are two cases: 1. A word consists only of letters *or* numbers. So there won't be a word like `Im1Word`. If this is the case, I'd go for ``` /([a-z]+)$|([a-z]+)[^a-z]+$/i ``` This will match `PARIS` in `100 r St Lazare, 75009 PARIS` and, for another example it will match `test` in `just a test 7509`. See the [demo @ regex101](http://regex101.com/r/pL9gU3) (the `g` and `m` flags are just to match on multiple lines, so you see everything it would match). 2. A word consists of letters *and* numbers. There may be words like `Im1Word`. The above regex won't be enough and I would do this with some more logic in the code: ``` $input = "100 r St Lazare, 75009 PARIS 123 abc123 123"; $words = explode(' ', $input); for($i = count($words)-1; $i >= 0; $i--) { if(preg_match("/\b[a-z]+\b/i",$words[$i]) == 1) { echo "Match: " . $words[$i]; break; } } ``` Essentially, we split the string by a space and iterate over each element from the end until the beginning. Whenever an element matches `\b[a-z]+\b` we found last word consisting only of letters. [Example @ ideone](http://ideone.com/TKqEQs) Now, if you have any non-ascii characters both of the above solutions will fail. You need to change both regexes: 1. `([^\s\d]+)$|([^\s\d]+)[\s\d]+$` 2. `"/\b[^\s\d]+\b/i"` This way you will match non-ascii words, too.
You can try with: ``` $input = '100 r St Lazare, 75009 PARIS'; $words = explode(' ', $input); $last = array_pop($words); ``` or ``` $last = $words[count($words) - 1]; ```
21,401,891
Can somebody help me to getting the last word from a text which contains only letters. I should use regex I think... For example: ``` 100 r St Lazare, 75009 PARIS ``` I need the word `PARIS`
2014/01/28
[ "https://Stackoverflow.com/questions/21401891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3243871/" ]
You can try with: ``` $input = '100 r St Lazare, 75009 PARIS'; $words = explode(' ', $input); $last = array_pop($words); ``` or ``` $last = $words[count($words) - 1]; ```
you may try ``` $text = "100 r St Lazare, 75009 PARIS"; $exploded = explode(" ",$text); echo $exploded[count($exploded)-1] ```
21,401,891
Can somebody help me to getting the last word from a text which contains only letters. I should use regex I think... For example: ``` 100 r St Lazare, 75009 PARIS ``` I need the word `PARIS`
2014/01/28
[ "https://Stackoverflow.com/questions/21401891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3243871/" ]
If you want a **pure** regex solution, you can use ``` ([a-z]+)$|^.*\b([a-z]+)\b ``` as your regex. (Again, replace `[a-z]` with `[^\s\d]` if you're dealing with non-ascii chars) [Demo @ regex101](http://regex101.com/r/yC4vK5) --- Essentially there are two cases: 1. A word consists only of letters *or* numbers. So there won't be a word like `Im1Word`. If this is the case, I'd go for ``` /([a-z]+)$|([a-z]+)[^a-z]+$/i ``` This will match `PARIS` in `100 r St Lazare, 75009 PARIS` and, for another example it will match `test` in `just a test 7509`. See the [demo @ regex101](http://regex101.com/r/pL9gU3) (the `g` and `m` flags are just to match on multiple lines, so you see everything it would match). 2. A word consists of letters *and* numbers. There may be words like `Im1Word`. The above regex won't be enough and I would do this with some more logic in the code: ``` $input = "100 r St Lazare, 75009 PARIS 123 abc123 123"; $words = explode(' ', $input); for($i = count($words)-1; $i >= 0; $i--) { if(preg_match("/\b[a-z]+\b/i",$words[$i]) == 1) { echo "Match: " . $words[$i]; break; } } ``` Essentially, we split the string by a space and iterate over each element from the end until the beginning. Whenever an element matches `\b[a-z]+\b` we found last word consisting only of letters. [Example @ ideone](http://ideone.com/TKqEQs) Now, if you have any non-ascii characters both of the above solutions will fail. You need to change both regexes: 1. `([^\s\d]+)$|([^\s\d]+)[\s\d]+$` 2. `"/\b[^\s\d]+\b/i"` This way you will match non-ascii words, too.
Regular expressions and `explode` are possible solutions, however, the fastest one is `substr` in my opinion: ``` $last = substr($words, strrpos($words, " ")+1); ``` `strrpos` returns the offset of last space. That's all you need.
21,401,891
Can somebody help me to getting the last word from a text which contains only letters. I should use regex I think... For example: ``` 100 r St Lazare, 75009 PARIS ``` I need the word `PARIS`
2014/01/28
[ "https://Stackoverflow.com/questions/21401891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3243871/" ]
Regular expressions and `explode` are possible solutions, however, the fastest one is `substr` in my opinion: ``` $last = substr($words, strrpos($words, " ")+1); ``` `strrpos` returns the offset of last space. That's all you need.
you may try ``` $text = "100 r St Lazare, 75009 PARIS"; $exploded = explode(" ",$text); echo $exploded[count($exploded)-1] ```
21,401,891
Can somebody help me to getting the last word from a text which contains only letters. I should use regex I think... For example: ``` 100 r St Lazare, 75009 PARIS ``` I need the word `PARIS`
2014/01/28
[ "https://Stackoverflow.com/questions/21401891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3243871/" ]
I'd like to suggest the following version, though it is still not perfect for all cases: ``` $input = '100 r St Lazare, 75009 PARIS 345'; // pass, returns "PARIS" $input = '100 r St Lazare, 75009 PARIS'; // pass, returns "PARIS" $input = 'this just a Ðöæ 75009'; // pass, returns "Ðöæ" $input = 'this just a Ðöæ'; // pass, returns "Ðöæ" $input = 'this just a tes1t 75009'; // fail, returns "t" $output = array(); preg_match( '/([^\s\d]+)[\s\d]*$/i', $input, $output ); $lastWordThatConsistsOnlyOfLetters = array_pop( $output ); var_dump( $lastWordThatConsistsOnlyOfLetters ); ``` (@naveengoyal The test string you've posted is a hard one…)
Regular expressions and `explode` are possible solutions, however, the fastest one is `substr` in my opinion: ``` $last = substr($words, strrpos($words, " ")+1); ``` `strrpos` returns the offset of last space. That's all you need.
21,401,891
Can somebody help me to getting the last word from a text which contains only letters. I should use regex I think... For example: ``` 100 r St Lazare, 75009 PARIS ``` I need the word `PARIS`
2014/01/28
[ "https://Stackoverflow.com/questions/21401891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3243871/" ]
If you want a **pure** regex solution, you can use ``` ([a-z]+)$|^.*\b([a-z]+)\b ``` as your regex. (Again, replace `[a-z]` with `[^\s\d]` if you're dealing with non-ascii chars) [Demo @ regex101](http://regex101.com/r/yC4vK5) --- Essentially there are two cases: 1. A word consists only of letters *or* numbers. So there won't be a word like `Im1Word`. If this is the case, I'd go for ``` /([a-z]+)$|([a-z]+)[^a-z]+$/i ``` This will match `PARIS` in `100 r St Lazare, 75009 PARIS` and, for another example it will match `test` in `just a test 7509`. See the [demo @ regex101](http://regex101.com/r/pL9gU3) (the `g` and `m` flags are just to match on multiple lines, so you see everything it would match). 2. A word consists of letters *and* numbers. There may be words like `Im1Word`. The above regex won't be enough and I would do this with some more logic in the code: ``` $input = "100 r St Lazare, 75009 PARIS 123 abc123 123"; $words = explode(' ', $input); for($i = count($words)-1; $i >= 0; $i--) { if(preg_match("/\b[a-z]+\b/i",$words[$i]) == 1) { echo "Match: " . $words[$i]; break; } } ``` Essentially, we split the string by a space and iterate over each element from the end until the beginning. Whenever an element matches `\b[a-z]+\b` we found last word consisting only of letters. [Example @ ideone](http://ideone.com/TKqEQs) Now, if you have any non-ascii characters both of the above solutions will fail. You need to change both regexes: 1. `([^\s\d]+)$|([^\s\d]+)[\s\d]+$` 2. `"/\b[^\s\d]+\b/i"` This way you will match non-ascii words, too.
you may try ``` $text = "100 r St Lazare, 75009 PARIS"; $exploded = explode(" ",$text); echo $exploded[count($exploded)-1] ```
21,401,891
Can somebody help me to getting the last word from a text which contains only letters. I should use regex I think... For example: ``` 100 r St Lazare, 75009 PARIS ``` I need the word `PARIS`
2014/01/28
[ "https://Stackoverflow.com/questions/21401891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3243871/" ]
If you want a **pure** regex solution, you can use ``` ([a-z]+)$|^.*\b([a-z]+)\b ``` as your regex. (Again, replace `[a-z]` with `[^\s\d]` if you're dealing with non-ascii chars) [Demo @ regex101](http://regex101.com/r/yC4vK5) --- Essentially there are two cases: 1. A word consists only of letters *or* numbers. So there won't be a word like `Im1Word`. If this is the case, I'd go for ``` /([a-z]+)$|([a-z]+)[^a-z]+$/i ``` This will match `PARIS` in `100 r St Lazare, 75009 PARIS` and, for another example it will match `test` in `just a test 7509`. See the [demo @ regex101](http://regex101.com/r/pL9gU3) (the `g` and `m` flags are just to match on multiple lines, so you see everything it would match). 2. A word consists of letters *and* numbers. There may be words like `Im1Word`. The above regex won't be enough and I would do this with some more logic in the code: ``` $input = "100 r St Lazare, 75009 PARIS 123 abc123 123"; $words = explode(' ', $input); for($i = count($words)-1; $i >= 0; $i--) { if(preg_match("/\b[a-z]+\b/i",$words[$i]) == 1) { echo "Match: " . $words[$i]; break; } } ``` Essentially, we split the string by a space and iterate over each element from the end until the beginning. Whenever an element matches `\b[a-z]+\b` we found last word consisting only of letters. [Example @ ideone](http://ideone.com/TKqEQs) Now, if you have any non-ascii characters both of the above solutions will fail. You need to change both regexes: 1. `([^\s\d]+)$|([^\s\d]+)[\s\d]+$` 2. `"/\b[^\s\d]+\b/i"` This way you will match non-ascii words, too.
I'd like to suggest the following version, though it is still not perfect for all cases: ``` $input = '100 r St Lazare, 75009 PARIS 345'; // pass, returns "PARIS" $input = '100 r St Lazare, 75009 PARIS'; // pass, returns "PARIS" $input = 'this just a Ðöæ 75009'; // pass, returns "Ðöæ" $input = 'this just a Ðöæ'; // pass, returns "Ðöæ" $input = 'this just a tes1t 75009'; // fail, returns "t" $output = array(); preg_match( '/([^\s\d]+)[\s\d]*$/i', $input, $output ); $lastWordThatConsistsOnlyOfLetters = array_pop( $output ); var_dump( $lastWordThatConsistsOnlyOfLetters ); ``` (@naveengoyal The test string you've posted is a hard one…)
21,401,891
Can somebody help me to getting the last word from a text which contains only letters. I should use regex I think... For example: ``` 100 r St Lazare, 75009 PARIS ``` I need the word `PARIS`
2014/01/28
[ "https://Stackoverflow.com/questions/21401891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3243871/" ]
I'd like to suggest the following version, though it is still not perfect for all cases: ``` $input = '100 r St Lazare, 75009 PARIS 345'; // pass, returns "PARIS" $input = '100 r St Lazare, 75009 PARIS'; // pass, returns "PARIS" $input = 'this just a Ðöæ 75009'; // pass, returns "Ðöæ" $input = 'this just a Ðöæ'; // pass, returns "Ðöæ" $input = 'this just a tes1t 75009'; // fail, returns "t" $output = array(); preg_match( '/([^\s\d]+)[\s\d]*$/i', $input, $output ); $lastWordThatConsistsOnlyOfLetters = array_pop( $output ); var_dump( $lastWordThatConsistsOnlyOfLetters ); ``` (@naveengoyal The test string you've posted is a hard one…)
you may try ``` $text = "100 r St Lazare, 75009 PARIS"; $exploded = explode(" ",$text); echo $exploded[count($exploded)-1] ```
43,324,450
I want a button at the right corner of a div. It works fine normally, but upon adding the align="right" to the html, the button doesn't work anymore (although it does align to the right). ``` <input id="exitbutton" align="right" style="width:15px" type="image" src="images/#"/> ``` Why does this happen?
2017/04/10
[ "https://Stackoverflow.com/questions/43324450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7548189/" ]
Ideally `align="right"` is not the property of input tag if you are using HTML5. As you are already applying inline style, you can just apply `float:right` to align input button to the right. ``` <input id="exitbutton" style="width:15px; float:right" type="image" src="images/#"/> ```
For buttons instead of using inline attributes use text alignment in your css. And avoid giving style with attributes as much as you can. For form elements you should use float if you are not using flex. But keep it in mind you should clear floats in order to prevent visual errors
43,324,450
I want a button at the right corner of a div. It works fine normally, but upon adding the align="right" to the html, the button doesn't work anymore (although it does align to the right). ``` <input id="exitbutton" align="right" style="width:15px" type="image" src="images/#"/> ``` Why does this happen?
2017/04/10
[ "https://Stackoverflow.com/questions/43324450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7548189/" ]
Ideally `align="right"` is not the property of input tag if you are using HTML5. As you are already applying inline style, you can just apply `float:right` to align input button to the right. ``` <input id="exitbutton" style="width:15px; float:right" type="image" src="images/#"/> ```
`align` property is not for an input field You can use `float` like this: ```css input{float:right;} ``` ```html <input id="exitbutton" style="width:15px" type="image" src="images/#"/> ```
53,223,975
I am putting a JSON response into a variable via `requests.json()` like this: ``` response = requests.get(some_url, params=some_params).json() ``` This however converts JSON's original `"` to Python's `'`, `true` to `True`, `null` to `None`. This poses a problem when trying to save the response as text and the convert it back to JSON - sure, I can use `.replace()` for all conversions mentioned above, but even once I do that, I get other funny json decoder errors. Is there any way in Python to get JSON response and keep original JavaScript format?
2018/11/09
[ "https://Stackoverflow.com/questions/53223975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8461786/" ]
You'll need an Object array instead of a String Array to keep a record of which checkbox was checked: ``` nontrade = [ { label: 'a', selected: false }, { label: 'b', selected: false }, { label: 'c', selected: false }, { label: 'd', selected: false } ]; trade = [ { label: 'aa', selected: false }, { label: 'bb', selected: false }, { label: 'cc', selected: false }, { label: 'dd', selected: false } ]; ``` Then once either the All Traders or All Non Traders Checkbox is checked, you can make the ammendments to your `allNonTrades` and `allTrades` methods. ``` allNonTrades(event) { const checked = event.target.checked; this.nontrade.forEach(item => item.selected = checked); } allTrades(event) { const checked = event.target.checked; this.trade.forEach(item => item.selected = checked); } ``` Finally, you'll have to change the `value` to `checked` for the Attribute Binding in your template: ``` <label class="btn btn-filter"> <input type="checkbox" name="allNonTrades" [value]="nontrade" (change)="allNonTrades($event)">All NonTrades </label>&nbsp; <ng-container *ngFor="let ntrd of nontrade"> <label class="btn btn-filter"> <input type="checkbox" name="nontrades" [checked]="ntrd.selected" (change)="changeTradesByCategory($event)">{{ ntrd.label }} </label>&nbsp; </ng-container> <br> <label class="btn btn-filter"> <input type="checkbox" name="allTrades" [value]="trade" (change)="allTrades($event)">All Trades </label>&nbsp; <ng-container *ngFor="let trd of trade"> <label class="btn btn-filter"> <input type="checkbox" name="trades" [checked]="trd.selected" (change)="changeTradesByCategory($event)">{{ trd.label }} </label>&nbsp; </ng-container> ``` Here's a [**Working StackBlitz**](https://stackblitz.com/edit/angular-check-uncheck-all-checkboxes?file=src/app/app.component.html) for your ref.
In my case, I got the checkbox values from an API and the checkbox to select ALL the other checkboxes were sibling checkboxes. What happens here is if you check any of the 'ALL' checkboxes all the sibling checkboxes are also checked. ```js areasAndPermissions = [{ area: 'all', permissions: ['ALL', 'CREATE', 'UPDATE', 'DELETE', 'READ', 'EXPORT'], }, { area: 'user', permissions: ['ALL', 'CREATE', 'UPDATE', 'DELETE', 'READ', 'EXPORT'], }, { area: 'role', permissions: ['ALL', 'CREATE', 'UPDATE', 'DELETE', 'READ', 'EXPORT'], }, ]; onRolesCheckboxChange(areaName, $event) { let checkboxValue = $event.target.value; // all the sibling checkboxes have the same name let checkboxWithSameName = document.querySelectorAll(`[name='${$event.target.name}']`); if ($event.target.checked && checkboxValue === 'ALL') { checkboxWithSameName.forEach((item) => { // Only HTMLInputElement have the checked property so we cast the // element so it will transpile (item as HTMLInputElement).checked = true; }); } } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/angular/11.0.1/core.umd.js"></script> <div *ngFor="let roleArea of areasAndPermissions"> <div> <span class="mb-0"> Area: {{ roleArea.area | uppercase }} </span> </div> <div> <div *ngFor="let rolePermission of roleArea.permissions; let i = index"> <input name="{{ roleArea.area }}" type="checkbox" id="{{ roleArea.area + i }}" value="{{ rolePermission }}" (change)="onRolesCheckboxChange(roleArea.area, $event)" /> <label for="{{ roleArea.area + i }}"> {{ rolePermission }} </label> </div> </div> <br /> </div> ``` Here is a [working stackblitz](https://stackblitz.com/edit/angular-checkbox-with-same-name?devtoolsheight=33&file=src/app/app.component.ts) of the snippet for your reference
56,537,807
If I didn't initiate the iterators *i* and *j* with zero's this is what happens. The compiler does initiate them by zeros but somehow the child loop didn't proceed with iterating. Any interpretation for that? I already found the solution but I am asking about what could be the reason behind this? ``` void sortById(int *arr, int size){ for (int i; i<size; i++){ cout << "i = " << i << "\n" ; for (int j; j<size; j++){ cout << "j = " << j << "\n"; } } } int main(){ int Ids[5] = {15,3,1,10,25}; int size = 5; sortById(Ids, size); } //Output: i = 0 j = 0 j = 1 j = 2 j = 3 j = 4 i = 1 i = 2 i = 3 i = 4 ```
2019/06/11
[ "https://Stackoverflow.com/questions/56537807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5095396/" ]
You need to pass `rgb` as well with the values. Try the below solution. ``` scheme.forEach(colour => { console.log(colour) // successful data collected const column = document.createElement('div') column.setAttribute('class', 'column') app.appendChild(column) column.style.backgroundColor = `rgb(${colour})` }) ```
That's because the value you get in `colour` is an Array, not a colour code. You should parse the array into a colour code (i.e. RGB format). ``` scheme.forEach(colour => { console.log(colour) // successful data collected const column = document.createElement('div') column.setAttribute('class', 'column') const [r, g, b] = colour; const colorCode = `rgb(${r}, ${g}, ${b})`; app.appendChild(column) column.style.backgroundColor = colorCode; }) ```
56,537,807
If I didn't initiate the iterators *i* and *j* with zero's this is what happens. The compiler does initiate them by zeros but somehow the child loop didn't proceed with iterating. Any interpretation for that? I already found the solution but I am asking about what could be the reason behind this? ``` void sortById(int *arr, int size){ for (int i; i<size; i++){ cout << "i = " << i << "\n" ; for (int j; j<size; j++){ cout << "j = " << j << "\n"; } } } int main(){ int Ids[5] = {15,3,1,10,25}; int size = 5; sortById(Ids, size); } //Output: i = 0 j = 0 j = 1 j = 2 j = 3 j = 4 i = 1 i = 2 i = 3 i = 4 ```
2019/06/11
[ "https://Stackoverflow.com/questions/56537807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5095396/" ]
That's because the value you get in `colour` is an Array, not a colour code. You should parse the array into a colour code (i.e. RGB format). ``` scheme.forEach(colour => { console.log(colour) // successful data collected const column = document.createElement('div') column.setAttribute('class', 'column') const [r, g, b] = colour; const colorCode = `rgb(${r}, ${g}, ${b})`; app.appendChild(column) column.style.backgroundColor = colorCode; }) ```
Instead of passing array as a color you should create a `rgb()` string with elements from that array. You could create a function for this. ```js const div = document.querySelector('div'); const rgb = color => `rgb(${color.join(', ')})` div.style.backgroundColor = rgb([50, 200, 50]) ``` ```html <div>Div</div> ```
56,537,807
If I didn't initiate the iterators *i* and *j* with zero's this is what happens. The compiler does initiate them by zeros but somehow the child loop didn't proceed with iterating. Any interpretation for that? I already found the solution but I am asking about what could be the reason behind this? ``` void sortById(int *arr, int size){ for (int i; i<size; i++){ cout << "i = " << i << "\n" ; for (int j; j<size; j++){ cout << "j = " << j << "\n"; } } } int main(){ int Ids[5] = {15,3,1,10,25}; int size = 5; sortById(Ids, size); } //Output: i = 0 j = 0 j = 1 j = 2 j = 3 j = 4 i = 1 i = 2 i = 3 i = 4 ```
2019/06/11
[ "https://Stackoverflow.com/questions/56537807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5095396/" ]
That's because the value you get in `colour` is an Array, not a colour code. You should parse the array into a colour code (i.e. RGB format). ``` scheme.forEach(colour => { console.log(colour) // successful data collected const column = document.createElement('div') column.setAttribute('class', 'column') const [r, g, b] = colour; const colorCode = `rgb(${r}, ${g}, ${b})`; app.appendChild(column) column.style.backgroundColor = colorCode; }) ```
You can try the following way: ```js var scheme = [[122, 122, 122], [222, 122, 122], [122, 322, 122]] scheme.forEach(colour => { //console.log(colour) // successful data collected const column = document.createElement('div'); column.textContent = 'test'; column.setAttribute('class', 'column'); document.body.appendChild(column) column.style.backgroundColor = 'rgb(' + colour.join(',') + ')'; }) ```
56,537,807
If I didn't initiate the iterators *i* and *j* with zero's this is what happens. The compiler does initiate them by zeros but somehow the child loop didn't proceed with iterating. Any interpretation for that? I already found the solution but I am asking about what could be the reason behind this? ``` void sortById(int *arr, int size){ for (int i; i<size; i++){ cout << "i = " << i << "\n" ; for (int j; j<size; j++){ cout << "j = " << j << "\n"; } } } int main(){ int Ids[5] = {15,3,1,10,25}; int size = 5; sortById(Ids, size); } //Output: i = 0 j = 0 j = 1 j = 2 j = 3 j = 4 i = 1 i = 2 i = 3 i = 4 ```
2019/06/11
[ "https://Stackoverflow.com/questions/56537807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5095396/" ]
You need to pass `rgb` as well with the values. Try the below solution. ``` scheme.forEach(colour => { console.log(colour) // successful data collected const column = document.createElement('div') column.setAttribute('class', 'column') app.appendChild(column) column.style.backgroundColor = `rgb(${colour})` }) ```
Instead of passing array as a color you should create a `rgb()` string with elements from that array. You could create a function for this. ```js const div = document.querySelector('div'); const rgb = color => `rgb(${color.join(', ')})` div.style.backgroundColor = rgb([50, 200, 50]) ``` ```html <div>Div</div> ```
56,537,807
If I didn't initiate the iterators *i* and *j* with zero's this is what happens. The compiler does initiate them by zeros but somehow the child loop didn't proceed with iterating. Any interpretation for that? I already found the solution but I am asking about what could be the reason behind this? ``` void sortById(int *arr, int size){ for (int i; i<size; i++){ cout << "i = " << i << "\n" ; for (int j; j<size; j++){ cout << "j = " << j << "\n"; } } } int main(){ int Ids[5] = {15,3,1,10,25}; int size = 5; sortById(Ids, size); } //Output: i = 0 j = 0 j = 1 j = 2 j = 3 j = 4 i = 1 i = 2 i = 3 i = 4 ```
2019/06/11
[ "https://Stackoverflow.com/questions/56537807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5095396/" ]
You need to pass `rgb` as well with the values. Try the below solution. ``` scheme.forEach(colour => { console.log(colour) // successful data collected const column = document.createElement('div') column.setAttribute('class', 'column') app.appendChild(column) column.style.backgroundColor = `rgb(${colour})` }) ```
You can try the following way: ```js var scheme = [[122, 122, 122], [222, 122, 122], [122, 322, 122]] scheme.forEach(colour => { //console.log(colour) // successful data collected const column = document.createElement('div'); column.textContent = 'test'; column.setAttribute('class', 'column'); document.body.appendChild(column) column.style.backgroundColor = 'rgb(' + colour.join(',') + ')'; }) ```
8,168,447
I have a dropdownlist and it is very simple. You click the button to go further you have error if you don't select nothing from DDL. But how i do to not appear the error when the user choose something from the DDL? Here is the markup: ``` <asp:DropDownList ID="DropDownList1" runat="server" CssClass="jump"> <asp:ListItem Text="" Value="0"></asp:ListItem> <asp:ListItem Text="Coupé" Value="Coupé" /> <asp:ListItem Text="Cabriolet" Value="Cabriolet" /> <asp:ListItem Text="Pickup" Value="Pickup" /> <asp:ListItem Text="Kombi" Value="Kombi" /> <asp:ListItem Text="Kombi-Coupé" Value="Kombi-Coupé" /> <asp:ListItem Text="Minibuss" Value="Minibuss" /> <asp:ListItem Text="Sedan" Value="Sedan" /> <asp:ListItem Text="Skåpbil" Value="Skåpbil" /> <asp:ListItem Text="SUV" Value="SUV" /> <asp:ListItem Text="Övrig" Value="Övrig" /> </asp:DropDownList> <p id="err" runat="server"></p> ``` and code-behind: ``` if (DropDownList1.SelectedIndex == 0) { err.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>Du måste välja Fordonstyp!</span>"; return; } ``` Thank you so much in advance
2011/11/17
[ "https://Stackoverflow.com/questions/8168447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As simple as this: ``` err.InnerHtml = ""; if (DropDownList1.SelectedIndex == 0) { err.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>Du måste välja Fordonstyp!</span>"; return; } ``` This will hide the error by default, then show it only if needed. **Edit**: to support more than one drop down wrap it nicely with a function first: ``` private bool HandleDropDownError(DropDownList oDDL, HtmlGenericControl oErrorControl, string strErrorText) { oErrorControl.InnerHtml = ""; if (oDDL.SelectedIndex == 0) { oErrorControl.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>" + strErrorText + "</span>"; return false; } return true; } ``` Now just use the same error label to show error for any drop down, and have such code in the `Page_Load`: ``` if (!HandleDropDownError(DropDownList1, err, "Du måste välja Fordonstyp!")) return; if (!HandleDropDownError(DropDownList2, err, "Du måste välja matta!")) return; if (!HandleDropDownError(DropDownList3, err, "Du måste välja byggnad!")) return; ```
You could also use a [RequiredFieldValidator](http://msdn.microsoft.com/en-us/library/5hbw267h%28v=VS.100%29.aspx) : ``` <asp:RequiredFieldValidator id="rfvFavoriteCar" Text="Du måste välja Fordonstyp!" ControlToValidate="DropDownList1" Runat="server" /> ```
8,168,447
I have a dropdownlist and it is very simple. You click the button to go further you have error if you don't select nothing from DDL. But how i do to not appear the error when the user choose something from the DDL? Here is the markup: ``` <asp:DropDownList ID="DropDownList1" runat="server" CssClass="jump"> <asp:ListItem Text="" Value="0"></asp:ListItem> <asp:ListItem Text="Coupé" Value="Coupé" /> <asp:ListItem Text="Cabriolet" Value="Cabriolet" /> <asp:ListItem Text="Pickup" Value="Pickup" /> <asp:ListItem Text="Kombi" Value="Kombi" /> <asp:ListItem Text="Kombi-Coupé" Value="Kombi-Coupé" /> <asp:ListItem Text="Minibuss" Value="Minibuss" /> <asp:ListItem Text="Sedan" Value="Sedan" /> <asp:ListItem Text="Skåpbil" Value="Skåpbil" /> <asp:ListItem Text="SUV" Value="SUV" /> <asp:ListItem Text="Övrig" Value="Övrig" /> </asp:DropDownList> <p id="err" runat="server"></p> ``` and code-behind: ``` if (DropDownList1.SelectedIndex == 0) { err.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>Du måste välja Fordonstyp!</span>"; return; } ``` Thank you so much in advance
2011/11/17
[ "https://Stackoverflow.com/questions/8168447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As simple as this: ``` err.InnerHtml = ""; if (DropDownList1.SelectedIndex == 0) { err.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>Du måste välja Fordonstyp!</span>"; return; } ``` This will hide the error by default, then show it only if needed. **Edit**: to support more than one drop down wrap it nicely with a function first: ``` private bool HandleDropDownError(DropDownList oDDL, HtmlGenericControl oErrorControl, string strErrorText) { oErrorControl.InnerHtml = ""; if (oDDL.SelectedIndex == 0) { oErrorControl.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>" + strErrorText + "</span>"; return false; } return true; } ``` Now just use the same error label to show error for any drop down, and have such code in the `Page_Load`: ``` if (!HandleDropDownError(DropDownList1, err, "Du måste välja Fordonstyp!")) return; if (!HandleDropDownError(DropDownList2, err, "Du måste välja matta!")) return; if (!HandleDropDownError(DropDownList3, err, "Du måste välja byggnad!")) return; ```
If you need to have a field selected, why not remove the empty selection line? ``` <asp:ListItem Text="" Value="0"></asp:ListItem> ```
8,168,447
I have a dropdownlist and it is very simple. You click the button to go further you have error if you don't select nothing from DDL. But how i do to not appear the error when the user choose something from the DDL? Here is the markup: ``` <asp:DropDownList ID="DropDownList1" runat="server" CssClass="jump"> <asp:ListItem Text="" Value="0"></asp:ListItem> <asp:ListItem Text="Coupé" Value="Coupé" /> <asp:ListItem Text="Cabriolet" Value="Cabriolet" /> <asp:ListItem Text="Pickup" Value="Pickup" /> <asp:ListItem Text="Kombi" Value="Kombi" /> <asp:ListItem Text="Kombi-Coupé" Value="Kombi-Coupé" /> <asp:ListItem Text="Minibuss" Value="Minibuss" /> <asp:ListItem Text="Sedan" Value="Sedan" /> <asp:ListItem Text="Skåpbil" Value="Skåpbil" /> <asp:ListItem Text="SUV" Value="SUV" /> <asp:ListItem Text="Övrig" Value="Övrig" /> </asp:DropDownList> <p id="err" runat="server"></p> ``` and code-behind: ``` if (DropDownList1.SelectedIndex == 0) { err.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>Du måste välja Fordonstyp!</span>"; return; } ``` Thank you so much in advance
2011/11/17
[ "https://Stackoverflow.com/questions/8168447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As simple as this: ``` err.InnerHtml = ""; if (DropDownList1.SelectedIndex == 0) { err.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>Du måste välja Fordonstyp!</span>"; return; } ``` This will hide the error by default, then show it only if needed. **Edit**: to support more than one drop down wrap it nicely with a function first: ``` private bool HandleDropDownError(DropDownList oDDL, HtmlGenericControl oErrorControl, string strErrorText) { oErrorControl.InnerHtml = ""; if (oDDL.SelectedIndex == 0) { oErrorControl.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>" + strErrorText + "</span>"; return false; } return true; } ``` Now just use the same error label to show error for any drop down, and have such code in the `Page_Load`: ``` if (!HandleDropDownError(DropDownList1, err, "Du måste välja Fordonstyp!")) return; if (!HandleDropDownError(DropDownList2, err, "Du måste välja matta!")) return; if (!HandleDropDownError(DropDownList3, err, "Du måste välja byggnad!")) return; ```
``` if (DropDownList1.SelectedIndex == 0) { err.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>Du måste välja Fordonstyp!</span>"; err.visible = true; return; } else err.visible = false; ```
8,168,447
I have a dropdownlist and it is very simple. You click the button to go further you have error if you don't select nothing from DDL. But how i do to not appear the error when the user choose something from the DDL? Here is the markup: ``` <asp:DropDownList ID="DropDownList1" runat="server" CssClass="jump"> <asp:ListItem Text="" Value="0"></asp:ListItem> <asp:ListItem Text="Coupé" Value="Coupé" /> <asp:ListItem Text="Cabriolet" Value="Cabriolet" /> <asp:ListItem Text="Pickup" Value="Pickup" /> <asp:ListItem Text="Kombi" Value="Kombi" /> <asp:ListItem Text="Kombi-Coupé" Value="Kombi-Coupé" /> <asp:ListItem Text="Minibuss" Value="Minibuss" /> <asp:ListItem Text="Sedan" Value="Sedan" /> <asp:ListItem Text="Skåpbil" Value="Skåpbil" /> <asp:ListItem Text="SUV" Value="SUV" /> <asp:ListItem Text="Övrig" Value="Övrig" /> </asp:DropDownList> <p id="err" runat="server"></p> ``` and code-behind: ``` if (DropDownList1.SelectedIndex == 0) { err.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>Du måste välja Fordonstyp!</span>"; return; } ``` Thank you so much in advance
2011/11/17
[ "https://Stackoverflow.com/questions/8168447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As simple as this: ``` err.InnerHtml = ""; if (DropDownList1.SelectedIndex == 0) { err.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>Du måste välja Fordonstyp!</span>"; return; } ``` This will hide the error by default, then show it only if needed. **Edit**: to support more than one drop down wrap it nicely with a function first: ``` private bool HandleDropDownError(DropDownList oDDL, HtmlGenericControl oErrorControl, string strErrorText) { oErrorControl.InnerHtml = ""; if (oDDL.SelectedIndex == 0) { oErrorControl.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>" + strErrorText + "</span>"; return false; } return true; } ``` Now just use the same error label to show error for any drop down, and have such code in the `Page_Load`: ``` if (!HandleDropDownError(DropDownList1, err, "Du måste välja Fordonstyp!")) return; if (!HandleDropDownError(DropDownList2, err, "Du måste välja matta!")) return; if (!HandleDropDownError(DropDownList3, err, "Du måste välja byggnad!")) return; ```
I took your code modified it to work. (at least what I think you are looking for) ``` <asp:DropDownList ID="DropDownList1" runat="server" CssClass="jump" AutoPostBack="true"> ``` and here ``` if (DropDownList1.SelectedIndex == 0) { err.InnerHtml = "<span style='font: normal bold 11px/100% Arial, Verdana, Sans-Serif; color: Red'>Du måste välja Fordonstyp!</span>"; return; }else {err.InnerHtml = ""} ```
3,803,356
An AJAX response is returning the full HTML page. I need to extract the fragment between the body (`<body>` and `</body>`) tags. This is required to be done on the client side using JavaScript. Any help will be appreciated.
2010/09/27
[ "https://Stackoverflow.com/questions/3803356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459416/" ]
The simplest but kind-of worst way would be simple string hacking on the response text. ``` var bodyhtml= html.split('<body>').pop().split('</body>')[0]; ``` This is unsatisfactory in the general case, but can be feasible if you know the exact format of the HTML being returned (eg. that there's no attributes on the `<body>`, that the sequences `<body>` and `</body>` isn't used in a comment in the middle of the page, etc). Another still-quite-bad way is to write the whole document to the `innerHTML` of a newly-created `<div>` and fish out the elements you want, not caring that writing `<html>` or `<body>` inside a `<div>` is broken. You'll be unable to reliably separate the child elements of `<head>` from those in `<body>` this way, but this is what eg jQuery does. A more robust but more painful way would be to use a separate HTML document: ``` var iframe= document.createElement('iframe'); iframe.style.display= 'none'; document.body.insertBefore(iframe, document.body.firstChild); var idoc= 'contentDocument' in iframe? iframe.contentDocument : iframe.contentWindow.document; idoc.write(htmlpage); idoc.close(); alert(idoc.body.innerHTML); document.body.removeChild(iframe); ``` though this would also execute all scripts inside the document, potentially changing it, so that might not be satisfactory either.
If your HTML Page is on Web then You can use YQL. e.g if your page url is <http://xyz.com/page.html> and you want everything in body element do like this ``` select * from html where url="http://xyz.com/page.html" and xpath='//body' ``` If you are new to YQL read this <http://en.wikipedia.org/wiki/YQL_Page_Scraping> There is also simple way to do it using Chromyqlip Extension <https://chrome.google.com/extensions/detail/bkmllkjbfbeephbldeflbnpclgfbjfmn> Hope this will help You!!!
3,803,356
An AJAX response is returning the full HTML page. I need to extract the fragment between the body (`<body>` and `</body>`) tags. This is required to be done on the client side using JavaScript. Any help will be appreciated.
2010/09/27
[ "https://Stackoverflow.com/questions/3803356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459416/" ]
The simplest but kind-of worst way would be simple string hacking on the response text. ``` var bodyhtml= html.split('<body>').pop().split('</body>')[0]; ``` This is unsatisfactory in the general case, but can be feasible if you know the exact format of the HTML being returned (eg. that there's no attributes on the `<body>`, that the sequences `<body>` and `</body>` isn't used in a comment in the middle of the page, etc). Another still-quite-bad way is to write the whole document to the `innerHTML` of a newly-created `<div>` and fish out the elements you want, not caring that writing `<html>` or `<body>` inside a `<div>` is broken. You'll be unable to reliably separate the child elements of `<head>` from those in `<body>` this way, but this is what eg jQuery does. A more robust but more painful way would be to use a separate HTML document: ``` var iframe= document.createElement('iframe'); iframe.style.display= 'none'; document.body.insertBefore(iframe, document.body.firstChild); var idoc= 'contentDocument' in iframe? iframe.contentDocument : iframe.contentWindow.document; idoc.write(htmlpage); idoc.close(); alert(idoc.body.innerHTML); document.body.removeChild(iframe); ``` though this would also execute all scripts inside the document, potentially changing it, so that might not be satisfactory either.
``` // Get the XML object for the "body" tag from the XMLHttpRequest/ActiveXObject // object (requestObj). // NOTE: This assumes there is only one "body" tag in your HTML document. var body = requestObj.responseXML.getElementsByTagName("body")[0]; // Get the "body" tag as an XML string. var bodyXML; // for Internet Explorer if (body.xml) { bodyXML = body.xml; } // for every other browser if (typeof (XMLSerializer) != "undefined") { var serializer = new XMLSerializer(); bodyXML = serializer.serializeToString(body); } ``` This gets you the XML for the "body" tag, as a string. Unfortunately, it still includes the "<body>" and "</body>", so if you want only the contents of the tag you will have to strip these off. You might want to take a look at the second example ("Example HTML code 2") on [this page](http://help.dottoro.com/ljwwrcvr.php).
169,529
I'd like to know whether "the survey online" or "an online survey" should be used in the following: > > World Gym has been under new management since July 3. For the new team to better serve our members, please take a few moments and click here to fill out **the survey online / an online survey**. > > > I'd appreciate your help.
2018/06/14
[ "https://ell.stackexchange.com/questions/169529", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/3865/" ]
The chosen article reveals the speaker's thought. With **the** the speaker is indicating that he or she believes you will understand (you, being the visitor reading those words) that **a survey** is normally associated with attempts to get to know users better, and **the particular survey in this instance** can be reached by clicking the link. That thought might not even be fully conscious on the speaker's part. This "previously mentioned" rule must be understood very very very very very broadly, so that it would include under its aegis what is typical or usual under the circumstances. It is a previous *encounter* not necessarily a previous *mention*, and the encounter need not have taken place in the immediate speech context. The immediate speech context can allude to a general context where the encounter has occurred or is believed by the speaker to have occurred.
The survey is **very specific here.** How? Because it says *click here.* Anything specific i.e. *only that thing and nothing else* would have the definite article. Take another example and you may understand that - > > If you want to register, click here to go to **the registration form.** > > > So, registration here is specific for that login, for that page. Had it been an indefinite article, I would think of some other *form or feedback* which could be related to the website *but* not specific to the matter you are talking about. Finally, ask yourself, is that the **only survey** for that activity? If yes, then go for the definite article.
12,169,271
I have sets of data like this: ``` 5.3.12.0 5.3.12.1 5.3.12.2 5.3.12.3 5.3.12.4 ``` How do I structure this in a YAML file, and then load it into Ruby as a simple array? I want the data above to be loaded as an array like: ``` fileset_levels = ["5.3.12.0", "5.3.12.1", "5.3.12.2", "5.3.12.3", "5.3.12.4"] ``` I'll have multiple sets of these arrays I want to load, so I want to have files called: ``` vuln1.yml vuln2.yml ``` and have them all load as arrays I can use in my Ruby script. I've tried: ``` vuln1_array = yaml::load("vuln1.yml") ``` but it does not create the array.
2012/08/29
[ "https://Stackoverflow.com/questions/12169271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383883/" ]
A great way to learn how to do anything with a serializer is to try writing a piece of code to demo a round-trip: ``` require 'yaml' puts %w[ 5.3.12.0 5.3.12.1 5.3.12.2 5.3.12.3 5.3.12.4 ].to_yaml ``` Which outputs: ``` --- - 5.3.12.0 - 5.3.12.1 - 5.3.12.2 - 5.3.12.3 - 5.3.12.4 ``` Creating the round-trip looks like: ``` require 'pp' require 'yaml' pp YAML.load( %w[ 5.3.12.0 5.3.12.1 5.3.12.2 5.3.12.3 5.3.12.4 ].to_yaml ) ``` which now outputs: ``` => ["5.3.12.0", "5.3.12.1", "5.3.12.2", "5.3.12.3", "5.3.12.4"] ``` The advantage to this process is you see what it should look like, and learn how to parse it. I use a similar process to generate complex YAML documents used for configuration files. While we can create them from scratch, it's easier to use simple Ruby arrays and hashes, and then let YAML sort it all out as it generates its output. I redirect the output to a file and use that as the starting point.
you call this a yaml file but this is just a basic file. Yaml is like a hash structure, you have a key that match a value. Here just a list of values. What you can do is ``` >> file = File.read('vuln1.yml') => "5.3.12.0\n5.3.12.1\n5.3.12.2\n5.3.12.3 \n5.3.12.4\n" >> file.split("\n") => ["5.3.12.0", "5.3.12.1", "5.3.12.2", "5.3.12.3 ", "5.3.12.4"] ```
27,809,448
I am a beginner in Java having only limited knowledge in SQL commands say 5 or 6 commands... I tried connecting my Java project with an access database "aman.accdb" using ODBC in my laptop.. The database has a table named "tab".. I am using a windows 7 64 bit pc with Java JDK for 64 bit installed in it. And also I use ms office 2013 which is also a 64 bit product. When I executed the code an error " java.sql.SQLException No suitable drivers found for jdbc:odbc:man" I am posting the sample code which caused an error below. I have removed the unwanted lines such as layout setting and all as it runs for pages. Please provide a solution to this! ``` package sample; import java.sql.*; import javax.swing.JOptionPane; public class als extends javax.swing.JFrame { public als() throws SQLException { initComponents(); try { con=DriverManager.getConnection("jdbc:odbc:man") ; }catch(Exception e) { JOptionPane.showMessageDialog(null, e); } } private void initComponents() { jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jButton1.setText("Check"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { st=con.createStatement(); String s=("insert into tab ('senthil',12)"); st.execute(s); JOptionPane.showMessageDialog(rootPane,"Saved"); this.setVisible(false); }catch(Exception e) { JOptionPane.showMessageDialog(rootPane,e); } } static Connection con; static Statement st; static ResultSet rs; private javax.swing.JButton jButton1; } ``` I came to know that this problem occurs in 64 bit OS oly.. Will this not happen if I install a 32 bit OS. Note : The error I got is an exception which I displayed through a message box in `catch()` part in constructor `als()`.
2015/01/07
[ "https://Stackoverflow.com/questions/27809448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4411184/" ]
> > I am using JDK 1.8.0 > > > The JDBC-ODBC Bridge has been removed from Java 8. Consider using the [UCanAccess](http://ucanaccess.sourceforge.net/site.html) JDBC driver instead. For details. see [Manipulating an Access database from Java without ODBC](https://stackoverflow.com/q/21955256/2144390)
Try this, i believe its because you have not specified the driver. This is for `MS Access` database. ``` public als() throws SQLException { initComponents(); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:man") ; }catch(Exception e) { JOptionPane.showMessageDialog(null, e); } } ```
66,578,376
i have a android app of version 4.20 inside 10M sqlitedb, now i have a app of version 4.21 inside 100M sqlitedb,i want upgrade 4.20 to 4.21, when it upgrade have completed, i find the sqlite size still keep 10M in 4.21 app. so the question is how to override sqlitedb when upgrade app 4.20 -> 4.21 。 --- My business is: app will have a lot of data synchronization. In order to optimize, every app will fill in initialization data into SQLite when it is published. Therefore, after each app have upgraded, I hope to completely overwrite SQLite。 any help is very apprecated.
2021/03/11
[ "https://Stackoverflow.com/questions/66578376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2552241/" ]
> > I dont have a user created in IAM but have a role created and assigned. > > > If you have only IAM role for RDS, you still need IAM user or some other role (e.g. instance role) which can **assume** (`iam:AssumeRole`) the RDS's role. Then, you have to use boto3' [assume\_role](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts.html#STS.Client.assume_role) to get temp credentials which you can then use to create new boto3 session for your RDS.
You should check the role of your User first. Then, it should be .aws/credentials ``` cat credential [default] aws_access_key_id = ***** aws_secret_access_key = **** ```
32,682,228
Suppose I have a method: ``` std::vector<double> minimize(double (*f)(const std::vector<double>& x)) ``` that takes a function *f(x)* and finds *x* that minimizes it. Suppose I want to minimize a function *g(x, a)* (with respect to *x*) which also takes a parameter *a* as an argument: ``` double g(const std::vector<double>& x, const double a) ``` How can I do this (in c++11) using the method *minimize* if the value of *a* is known only at runtime?
2015/09/20
[ "https://Stackoverflow.com/questions/32682228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4297373/" ]
You can easily use a lambda. ``` minimize([=](const std::vector<double>& x) { return g(x, a); }); ``` This is assuming that you change your function to use `std::function` instead of a function pointer. Function pointers are terribly limited and can't do anything interesting at all, like this, so it's best to forget they exist.
Use [labda](http://www.drdobbs.com/cpp/lambdas-in-c11/240168241) as Puppy suggested, but additinally update `minimize` to be a function template. Using template parameter instead of std::function will dramatically speed up `minimize` ``` //somewhere in header file template<class Function> std::vector<double> minimize(const Function& f){ ... } ... //in any place where minimize is visible minimize([=](const std::vector<double>& x) { return g(x, a); }); ```
25,943,160
I have an array as follows: ``` my_array = [ [value_1, value_2, value_3, value_4], [value_n1, value_n2, value_n3, value_n4], [value_x1, value_x2, value_x3, value_x4], [value_y1, value_y2, value_y3, value_y4], [value_z1, value_z2, value_z3, value_z4] ] ``` I find the array that has some value and then affect their values. For example: ``` some_value = 'xyz' if my_array.map(&:first).include? some_value # I always compare 'some_value' with the first element of each array # find the array my_array.select{ |s| s.include? some_value } # affect the values with position [1], [2], [3] # ... end ``` Is there a simple way to extract the array and affect their values​​? EXAMPLE ------- I have an array: ``` array = [ ['abc', 4, 5], ['xyz', 2, 10], ['ubf', 40, 9] ] ``` And a value: `x = 'abc'` When my variable 'x' begins to compare with the arrays that I have and find the array that contain this value. Then, should add 1 to the other other values​​. So, my expected result is: ``` array = [ ['abc', **5**, **6**], ['xyz', 2, 10], ['ubf', 40, 9] ] ``` Other value: `x = 'ubf'` Result: `array = [ ['abc', 5, 6], ['xyz', 2, 10], ['ubf', **41**, **10**] ]`
2014/09/19
[ "https://Stackoverflow.com/questions/25943160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162811/" ]
In light of the edit of your question, I believe this is what you want. ``` my_array = [[5, 3, 1], [1, 2, 3], [4, 5, 6], [7, 8, 9]] val = 4 (ndx = my_array.transpose.first.index(val)) ? ((1..my_array[ndx].size-1).each { |i| my_array[ndx][i] += 1 }; my_array) : nil #=> [[5, 3, 1], [1, 2, 3], [4, 6, 7], [7, 8, 9]] val = 7 (ndx = my_array.transpose.first.index(val)) ? ((1..my_array[ndx].size-1).each { |i| my_array[ndx][i] += 1 }; my_array) : nil #=> [[5, 3, 1], [1, 2, 3], [4, 5, 6], [7, 9, 10]] val = 6 (ndx = my_array.transpose.first.index(val)) ? ((1..my_array[ndx].size-1).each { |i| my_array[ndx][i] += 1 }; my_array) : nil #=> nil ```
Maybe something along these lines: ``` my_array.map{|a| a.include?(some_value) ? transform(a) : a } def transform array #return your modified array end ``` If you fed that `[[1,2],[2,3],[3,4]]` and you had `some_value` set to 3, you could use ``` def transform array do array.map{|k| k + 1} end ``` to get `[[1,2], [3,4], [4,5]]`
25,943,160
I have an array as follows: ``` my_array = [ [value_1, value_2, value_3, value_4], [value_n1, value_n2, value_n3, value_n4], [value_x1, value_x2, value_x3, value_x4], [value_y1, value_y2, value_y3, value_y4], [value_z1, value_z2, value_z3, value_z4] ] ``` I find the array that has some value and then affect their values. For example: ``` some_value = 'xyz' if my_array.map(&:first).include? some_value # I always compare 'some_value' with the first element of each array # find the array my_array.select{ |s| s.include? some_value } # affect the values with position [1], [2], [3] # ... end ``` Is there a simple way to extract the array and affect their values​​? EXAMPLE ------- I have an array: ``` array = [ ['abc', 4, 5], ['xyz', 2, 10], ['ubf', 40, 9] ] ``` And a value: `x = 'abc'` When my variable 'x' begins to compare with the arrays that I have and find the array that contain this value. Then, should add 1 to the other other values​​. So, my expected result is: ``` array = [ ['abc', **5**, **6**], ['xyz', 2, 10], ['ubf', 40, 9] ] ``` Other value: `x = 'ubf'` Result: `array = [ ['abc', 5, 6], ['xyz', 2, 10], ['ubf', **41**, **10**] ]`
2014/09/19
[ "https://Stackoverflow.com/questions/25943160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162811/" ]
Finding sub-array by its first element is a job of [`Array#assoc`](http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-assoc) method. Increasing value of following elements is a straightforward task. Possible implementation: ``` array = [ ['abc', 4, 5], ['xyz', 2, 10], ['ubf', 40, 9] ] x = 'abc' marr = array.assoc(x) marr[1..-1] = marr.drop(1).map {|v| v+1} if marr p array # [["abc", 5, 6], ["xyz", 2, 10], ["ubf", 40, 9]] ```
Maybe something along these lines: ``` my_array.map{|a| a.include?(some_value) ? transform(a) : a } def transform array #return your modified array end ``` If you fed that `[[1,2],[2,3],[3,4]]` and you had `some_value` set to 3, you could use ``` def transform array do array.map{|k| k + 1} end ``` to get `[[1,2], [3,4], [4,5]]`
25,943,160
I have an array as follows: ``` my_array = [ [value_1, value_2, value_3, value_4], [value_n1, value_n2, value_n3, value_n4], [value_x1, value_x2, value_x3, value_x4], [value_y1, value_y2, value_y3, value_y4], [value_z1, value_z2, value_z3, value_z4] ] ``` I find the array that has some value and then affect their values. For example: ``` some_value = 'xyz' if my_array.map(&:first).include? some_value # I always compare 'some_value' with the first element of each array # find the array my_array.select{ |s| s.include? some_value } # affect the values with position [1], [2], [3] # ... end ``` Is there a simple way to extract the array and affect their values​​? EXAMPLE ------- I have an array: ``` array = [ ['abc', 4, 5], ['xyz', 2, 10], ['ubf', 40, 9] ] ``` And a value: `x = 'abc'` When my variable 'x' begins to compare with the arrays that I have and find the array that contain this value. Then, should add 1 to the other other values​​. So, my expected result is: ``` array = [ ['abc', **5**, **6**], ['xyz', 2, 10], ['ubf', 40, 9] ] ``` Other value: `x = 'ubf'` Result: `array = [ ['abc', 5, 6], ['xyz', 2, 10], ['ubf', **41**, **10**] ]`
2014/09/19
[ "https://Stackoverflow.com/questions/25943160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162811/" ]
In light of the edit of your question, I believe this is what you want. ``` my_array = [[5, 3, 1], [1, 2, 3], [4, 5, 6], [7, 8, 9]] val = 4 (ndx = my_array.transpose.first.index(val)) ? ((1..my_array[ndx].size-1).each { |i| my_array[ndx][i] += 1 }; my_array) : nil #=> [[5, 3, 1], [1, 2, 3], [4, 6, 7], [7, 8, 9]] val = 7 (ndx = my_array.transpose.first.index(val)) ? ((1..my_array[ndx].size-1).each { |i| my_array[ndx][i] += 1 }; my_array) : nil #=> [[5, 3, 1], [1, 2, 3], [4, 5, 6], [7, 9, 10]] val = 6 (ndx = my_array.transpose.first.index(val)) ? ((1..my_array[ndx].size-1).each { |i| my_array[ndx][i] += 1 }; my_array) : nil #=> nil ```
If you have an array but want it to behave in a special way, you may want to think about creating a class. ``` class EGC < Array def increment(val) self.map do |sub| if sub.first == val [val, sub[1..-1].map(&:next)].flatten else sub end end end end ``` Then you can do this: ``` e = EGC.new([["foo", 1, 2], ["bar", 3, 4]]) #=> [["foo", 1, 2], ["bar", 3, 4]] e.increment("foo") #=> [["foo", 2, 3], ["bar", 3, 4]] ``` Of course, you should change the names to better reflect your problem domain. That being said, it seems that you would be better off starting with a Hash instead of a 2D Array.
25,943,160
I have an array as follows: ``` my_array = [ [value_1, value_2, value_3, value_4], [value_n1, value_n2, value_n3, value_n4], [value_x1, value_x2, value_x3, value_x4], [value_y1, value_y2, value_y3, value_y4], [value_z1, value_z2, value_z3, value_z4] ] ``` I find the array that has some value and then affect their values. For example: ``` some_value = 'xyz' if my_array.map(&:first).include? some_value # I always compare 'some_value' with the first element of each array # find the array my_array.select{ |s| s.include? some_value } # affect the values with position [1], [2], [3] # ... end ``` Is there a simple way to extract the array and affect their values​​? EXAMPLE ------- I have an array: ``` array = [ ['abc', 4, 5], ['xyz', 2, 10], ['ubf', 40, 9] ] ``` And a value: `x = 'abc'` When my variable 'x' begins to compare with the arrays that I have and find the array that contain this value. Then, should add 1 to the other other values​​. So, my expected result is: ``` array = [ ['abc', **5**, **6**], ['xyz', 2, 10], ['ubf', 40, 9] ] ``` Other value: `x = 'ubf'` Result: `array = [ ['abc', 5, 6], ['xyz', 2, 10], ['ubf', **41**, **10**] ]`
2014/09/19
[ "https://Stackoverflow.com/questions/25943160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162811/" ]
Finding sub-array by its first element is a job of [`Array#assoc`](http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-assoc) method. Increasing value of following elements is a straightforward task. Possible implementation: ``` array = [ ['abc', 4, 5], ['xyz', 2, 10], ['ubf', 40, 9] ] x = 'abc' marr = array.assoc(x) marr[1..-1] = marr.drop(1).map {|v| v+1} if marr p array # [["abc", 5, 6], ["xyz", 2, 10], ["ubf", 40, 9]] ```
If you have an array but want it to behave in a special way, you may want to think about creating a class. ``` class EGC < Array def increment(val) self.map do |sub| if sub.first == val [val, sub[1..-1].map(&:next)].flatten else sub end end end end ``` Then you can do this: ``` e = EGC.new([["foo", 1, 2], ["bar", 3, 4]]) #=> [["foo", 1, 2], ["bar", 3, 4]] e.increment("foo") #=> [["foo", 2, 3], ["bar", 3, 4]] ``` Of course, you should change the names to better reflect your problem domain. That being said, it seems that you would be better off starting with a Hash instead of a 2D Array.
110,430
In a song I am learning, there is a section of the song that has the chord progression G#m | A#m7b5 | B6 I sometimes get the fingerings wrong and use dimished 7th chords on guitar instead of m7b5 chords and in this case I actually think the dimished7th chord sounds good too. So I wanted to ask, what is the difference functionally between the two? They both seem to work in most situations as leading tone chords to a tonic chord one semitone above (B in this case).
2021/02/02
[ "https://music.stackexchange.com/questions/110430", "https://music.stackexchange.com", "https://music.stackexchange.com/users/35708/" ]
vii7b5 = (me),se,te,re => V7 without root tone VIIdim7 = (me),se,te,re,fa => Vb9 **me or mi** in brackets as it can be considered as dropped root tone of the dom7 respectively dom7b9. Critical point to decide which chord will better fit is the melody: if it contains the b9 (in F#,**A#,C#,E,G**) this would be **G** - then the **A#dim7** sounds better, if there is a **G#** you play the 7b5 chord:**A#m7b5**
I don't have much to add to other posts concerning the analysis, however I'd like to point another point. In some cases indeed either diminished and half-diminished chords might provide good harmonization of a melody, however they sound substantially different. If you play one or another randomly, due to mistakes, it might be very confusing for the rest of the band. It is very different from substituting e.g. Cmaj7 with C6, which can be innocent 90% of times.
110,430
In a song I am learning, there is a section of the song that has the chord progression G#m | A#m7b5 | B6 I sometimes get the fingerings wrong and use dimished 7th chords on guitar instead of m7b5 chords and in this case I actually think the dimished7th chord sounds good too. So I wanted to ask, what is the difference functionally between the two? They both seem to work in most situations as leading tone chords to a tonic chord one semitone above (B in this case).
2021/02/02
[ "https://music.stackexchange.com/questions/110430", "https://music.stackexchange.com", "https://music.stackexchange.com/users/35708/" ]
In this case it's a "safe" substitution, because the pitches are within the key (`G# minor`) and have contextually appropriate functions within the key. `A#m7b5` and `A#dim7` differ only in the presence of `G#` or `G`, respectively, both of which are present in `G# minor`. (Technically `G` is `Fx`, but the distinction isn't important in this context.) The voice-leading works nicely in either case: ``` X: 1 T: half dim vs. full dim K: G# minor M: none L: 1/1 "G#min"[GBd] "A#min7b5""inverted"[GAce] "B6""inverted"[GB^df] | "G#min"[GBd] "A#dim7""inverted"[=GAce] "B6""inverted"[^GBdf] | ``` Some points of interest: * In both cases, there is an upward progression of triads: `G#min A#dim B`. In the `min7b5` case, the progression occurs over a `G#` pedal tone; whereas, in the `dim7` case, the `G` serves as a leading tone. * `B6` and `Gmin7` contain exactly the same pitches, which allows for flexibility of interpretation. * The `dim7` case allows for a descending chromatic line of `G# G F#`. --- The `min7b5` is most common as the `ii` chord in a minor key. The `dim7` chord appears most frequently as a `vii` chord in major or minor. The progression `G#min A#[min7b5 or dim7] B6`, allowing for the interpretation `G#min A#[min7b5 or dim7] G#min7`, can be interpreted as: * `i ii III` * `i vii i` * `i vii III` All of which are viable according to the precepts of functional harmony.
Taking Bm7-5 vs Bdim7 as examples. If you want to see the chords as working in the same roles as simpler more common chords in the key of A minor: * **Bm7-5** (alias B half-diminished alias Dm6/B) works roughly as a **substitute for Dm**, so it works as **Am's subdominant**. Bm7-5 contains all the notes of a Dm. * **Bdim7** (alias B fully diminished) works roughly as a **substitute for E7**, so it works as **Am's dominant**. This is because of the D and G# notes. But as you already noticed, they're quite similar and the difference isn't very big. The functionality of a chord comes as a sum of its parts and the chords share 75% of the same notes.
110,430
In a song I am learning, there is a section of the song that has the chord progression G#m | A#m7b5 | B6 I sometimes get the fingerings wrong and use dimished 7th chords on guitar instead of m7b5 chords and in this case I actually think the dimished7th chord sounds good too. So I wanted to ask, what is the difference functionally between the two? They both seem to work in most situations as leading tone chords to a tonic chord one semitone above (B in this case).
2021/02/02
[ "https://music.stackexchange.com/questions/110430", "https://music.stackexchange.com", "https://music.stackexchange.com/users/35708/" ]
In this case it's a "safe" substitution, because the pitches are within the key (`G# minor`) and have contextually appropriate functions within the key. `A#m7b5` and `A#dim7` differ only in the presence of `G#` or `G`, respectively, both of which are present in `G# minor`. (Technically `G` is `Fx`, but the distinction isn't important in this context.) The voice-leading works nicely in either case: ``` X: 1 T: half dim vs. full dim K: G# minor M: none L: 1/1 "G#min"[GBd] "A#min7b5""inverted"[GAce] "B6""inverted"[GB^df] | "G#min"[GBd] "A#dim7""inverted"[=GAce] "B6""inverted"[^GBdf] | ``` Some points of interest: * In both cases, there is an upward progression of triads: `G#min A#dim B`. In the `min7b5` case, the progression occurs over a `G#` pedal tone; whereas, in the `dim7` case, the `G` serves as a leading tone. * `B6` and `Gmin7` contain exactly the same pitches, which allows for flexibility of interpretation. * The `dim7` case allows for a descending chromatic line of `G# G F#`. --- The `min7b5` is most common as the `ii` chord in a minor key. The `dim7` chord appears most frequently as a `vii` chord in major or minor. The progression `G#min A#[min7b5 or dim7] B6`, allowing for the interpretation `G#min A#[min7b5 or dim7] G#min7`, can be interpreted as: * `i ii III` * `i vii i` * `i vii III` All of which are viable according to the precepts of functional harmony.
The basic triad (which is what usually gives the main "color" to the chord) is the same, and being a diminshed fifth it creates a lots of tension towards the next one - usually a half tone above, and usually the tonic. They *are* similar and often interchangeable. While they are not diatonic on both major and minor mode, they can "exist" in those modes: * in minor mode, the root and seventh of m7b5 are the seventh and sixth melodic degrees ("augmented"); * in major mode, the seventh of dim7 is the harmonic ("lowered") sixth; The lowered sixth "sounds good" in both modes because it creates a big tension that leads to the fifth, and also due to the fact that it creates another tritone with the third of the chord. The m7b5 chord is usually considered less powerful than the dim7, as the seventh has less tension towards any resolution, but it can still create interesting effects. The choice depends on the composer/arranger/performer, but it obviously should not collide with any other voice (the melody) and should consider the overall harmony and current harmonic progression.
110,430
In a song I am learning, there is a section of the song that has the chord progression G#m | A#m7b5 | B6 I sometimes get the fingerings wrong and use dimished 7th chords on guitar instead of m7b5 chords and in this case I actually think the dimished7th chord sounds good too. So I wanted to ask, what is the difference functionally between the two? They both seem to work in most situations as leading tone chords to a tonic chord one semitone above (B in this case).
2021/02/02
[ "https://music.stackexchange.com/questions/110430", "https://music.stackexchange.com", "https://music.stackexchange.com/users/35708/" ]
> > Do m7b5 chords function the same as dim7 chords? > > > If talking about function, it seems better to not use jazz chord symbols and switch to using Roman numeral analysis (RNA.) The two chord types are *half-diminished seventh* and *diminished seventh*. The diminished seventh chord is easier to describe first. Usually it is rooted on the *leading tone* or a *secondary* leading tone. Its RNA symbols is `viio7`. Relative to a tonic of `C` the chord would be spelled `B♮ D F A♭` (I used the natural to show that in `C` minor you would raise the `B♭` of the key signature.) The chord's basic *function* is a dominant and in that regard some people conceive of the chord as a dominant flat ninth chord with the root omitted. The half diminished seventh chord is a bit more complicated. In major keys it is the *diatonic* seventh chord built on the leading tone. In `C` major it would be `B♮ D F A♮` and the RNA symbol would be `viiø7`. If that chord were used in a major key, its function would be a dominant. But, the chord is actually much more common in minor keys where it is the *diatonic* chord build on the second scale degree. In `C` minor is would be `D F A♭ C` and its RNA would be `iiø7`. The function of `iiø7` is a *subdominant*. The typical function of these chords is *not* the same. `viio7` is a dominant. `iiø7` is a subdominant. Those roles also apply to basic jazz harmony. The diminished seventh chord can appear as a dominant or as a passing chord. The song *Bewitched* uses the chord both ways. It starts with `C C♯dim7 Dm7` or in RNA `C: I viio7/ii ii7`. The half diminished seventh chord appears in minor, like `iim7♭5 V7alt im6`. *Autumn Leaves* is an example.
The basic triad (which is what usually gives the main "color" to the chord) is the same, and being a diminshed fifth it creates a lots of tension towards the next one - usually a half tone above, and usually the tonic. They *are* similar and often interchangeable. While they are not diatonic on both major and minor mode, they can "exist" in those modes: * in minor mode, the root and seventh of m7b5 are the seventh and sixth melodic degrees ("augmented"); * in major mode, the seventh of dim7 is the harmonic ("lowered") sixth; The lowered sixth "sounds good" in both modes because it creates a big tension that leads to the fifth, and also due to the fact that it creates another tritone with the third of the chord. The m7b5 chord is usually considered less powerful than the dim7, as the seventh has less tension towards any resolution, but it can still create interesting effects. The choice depends on the composer/arranger/performer, but it obviously should not collide with any other voice (the melody) and should consider the overall harmony and current harmonic progression.
110,430
In a song I am learning, there is a section of the song that has the chord progression G#m | A#m7b5 | B6 I sometimes get the fingerings wrong and use dimished 7th chords on guitar instead of m7b5 chords and in this case I actually think the dimished7th chord sounds good too. So I wanted to ask, what is the difference functionally between the two? They both seem to work in most situations as leading tone chords to a tonic chord one semitone above (B in this case).
2021/02/02
[ "https://music.stackexchange.com/questions/110430", "https://music.stackexchange.com", "https://music.stackexchange.com/users/35708/" ]
I don't have much to add to other posts concerning the analysis, however I'd like to point another point. In some cases indeed either diminished and half-diminished chords might provide good harmonization of a melody, however they sound substantially different. If you play one or another randomly, due to mistakes, it might be very confusing for the rest of the band. It is very different from substituting e.g. Cmaj7 with C6, which can be innocent 90% of times.
Do m7ba and Do dim7 are exactly the same chord: ``` Do m7b5 = Do dim7 Do (root) Mib (minor third) Solb (flat fifth) Sib (seventh) La# m7b5 = La# dim7 La# (root) Do (minor third) Mi (flat fifth) (perfect fifth would be Mi#) Sol# (seventh) (mjor seventh would be Sol##) ``` Anyway, it sounds weird to call A# dim7 and Gm#, are you sure it wouldn't be Abm and Bb dim7 instead? What geometry for both chords are you using on guitar?
110,430
In a song I am learning, there is a section of the song that has the chord progression G#m | A#m7b5 | B6 I sometimes get the fingerings wrong and use dimished 7th chords on guitar instead of m7b5 chords and in this case I actually think the dimished7th chord sounds good too. So I wanted to ask, what is the difference functionally between the two? They both seem to work in most situations as leading tone chords to a tonic chord one semitone above (B in this case).
2021/02/02
[ "https://music.stackexchange.com/questions/110430", "https://music.stackexchange.com", "https://music.stackexchange.com/users/35708/" ]
> > Do m7b5 chords function the same as dim7 chords? > > > If talking about function, it seems better to not use jazz chord symbols and switch to using Roman numeral analysis (RNA.) The two chord types are *half-diminished seventh* and *diminished seventh*. The diminished seventh chord is easier to describe first. Usually it is rooted on the *leading tone* or a *secondary* leading tone. Its RNA symbols is `viio7`. Relative to a tonic of `C` the chord would be spelled `B♮ D F A♭` (I used the natural to show that in `C` minor you would raise the `B♭` of the key signature.) The chord's basic *function* is a dominant and in that regard some people conceive of the chord as a dominant flat ninth chord with the root omitted. The half diminished seventh chord is a bit more complicated. In major keys it is the *diatonic* seventh chord built on the leading tone. In `C` major it would be `B♮ D F A♮` and the RNA symbol would be `viiø7`. If that chord were used in a major key, its function would be a dominant. But, the chord is actually much more common in minor keys where it is the *diatonic* chord build on the second scale degree. In `C` minor is would be `D F A♭ C` and its RNA would be `iiø7`. The function of `iiø7` is a *subdominant*. The typical function of these chords is *not* the same. `viio7` is a dominant. `iiø7` is a subdominant. Those roles also apply to basic jazz harmony. The diminished seventh chord can appear as a dominant or as a passing chord. The song *Bewitched* uses the chord both ways. It starts with `C C♯dim7 Dm7` or in RNA `C: I viio7/ii ii7`. The half diminished seventh chord appears in minor, like `iim7♭5 V7alt im6`. *Autumn Leaves* is an example.
While m7♭5 chords and dim7 chords are fairly interchangeable as dominant-function chords (don't interchange them if the melody note is the 7th), the dim7 chord is a much better **pivot chord** between keys than the m7♭5 chord, as any given dim7 chord is an enharmonic re-spelling of 3 other dim7 chords, while a m7♭5 chord cannot be enharmonically re-spelled into any other m7♭5 chords. When a dim7 chord is acting as a pivot chord, interchanging it is unwise.
110,430
In a song I am learning, there is a section of the song that has the chord progression G#m | A#m7b5 | B6 I sometimes get the fingerings wrong and use dimished 7th chords on guitar instead of m7b5 chords and in this case I actually think the dimished7th chord sounds good too. So I wanted to ask, what is the difference functionally between the two? They both seem to work in most situations as leading tone chords to a tonic chord one semitone above (B in this case).
2021/02/02
[ "https://music.stackexchange.com/questions/110430", "https://music.stackexchange.com", "https://music.stackexchange.com/users/35708/" ]
While m7♭5 chords and dim7 chords are fairly interchangeable as dominant-function chords (don't interchange them if the melody note is the 7th), the dim7 chord is a much better **pivot chord** between keys than the m7♭5 chord, as any given dim7 chord is an enharmonic re-spelling of 3 other dim7 chords, while a m7♭5 chord cannot be enharmonically re-spelled into any other m7♭5 chords. When a dim7 chord is acting as a pivot chord, interchanging it is unwise.
Do m7ba and Do dim7 are exactly the same chord: ``` Do m7b5 = Do dim7 Do (root) Mib (minor third) Solb (flat fifth) Sib (seventh) La# m7b5 = La# dim7 La# (root) Do (minor third) Mi (flat fifth) (perfect fifth would be Mi#) Sol# (seventh) (mjor seventh would be Sol##) ``` Anyway, it sounds weird to call A# dim7 and Gm#, are you sure it wouldn't be Abm and Bb dim7 instead? What geometry for both chords are you using on guitar?
110,430
In a song I am learning, there is a section of the song that has the chord progression G#m | A#m7b5 | B6 I sometimes get the fingerings wrong and use dimished 7th chords on guitar instead of m7b5 chords and in this case I actually think the dimished7th chord sounds good too. So I wanted to ask, what is the difference functionally between the two? They both seem to work in most situations as leading tone chords to a tonic chord one semitone above (B in this case).
2021/02/02
[ "https://music.stackexchange.com/questions/110430", "https://music.stackexchange.com", "https://music.stackexchange.com/users/35708/" ]
The basic triad (which is what usually gives the main "color" to the chord) is the same, and being a diminshed fifth it creates a lots of tension towards the next one - usually a half tone above, and usually the tonic. They *are* similar and often interchangeable. While they are not diatonic on both major and minor mode, they can "exist" in those modes: * in minor mode, the root and seventh of m7b5 are the seventh and sixth melodic degrees ("augmented"); * in major mode, the seventh of dim7 is the harmonic ("lowered") sixth; The lowered sixth "sounds good" in both modes because it creates a big tension that leads to the fifth, and also due to the fact that it creates another tritone with the third of the chord. The m7b5 chord is usually considered less powerful than the dim7, as the seventh has less tension towards any resolution, but it can still create interesting effects. The choice depends on the composer/arranger/performer, but it obviously should not collide with any other voice (the melody) and should consider the overall harmony and current harmonic progression.
While m7♭5 chords and dim7 chords are fairly interchangeable as dominant-function chords (don't interchange them if the melody note is the 7th), the dim7 chord is a much better **pivot chord** between keys than the m7♭5 chord, as any given dim7 chord is an enharmonic re-spelling of 3 other dim7 chords, while a m7♭5 chord cannot be enharmonically re-spelled into any other m7♭5 chords. When a dim7 chord is acting as a pivot chord, interchanging it is unwise.
110,430
In a song I am learning, there is a section of the song that has the chord progression G#m | A#m7b5 | B6 I sometimes get the fingerings wrong and use dimished 7th chords on guitar instead of m7b5 chords and in this case I actually think the dimished7th chord sounds good too. So I wanted to ask, what is the difference functionally between the two? They both seem to work in most situations as leading tone chords to a tonic chord one semitone above (B in this case).
2021/02/02
[ "https://music.stackexchange.com/questions/110430", "https://music.stackexchange.com", "https://music.stackexchange.com/users/35708/" ]
The basic triad (which is what usually gives the main "color" to the chord) is the same, and being a diminshed fifth it creates a lots of tension towards the next one - usually a half tone above, and usually the tonic. They *are* similar and often interchangeable. While they are not diatonic on both major and minor mode, they can "exist" in those modes: * in minor mode, the root and seventh of m7b5 are the seventh and sixth melodic degrees ("augmented"); * in major mode, the seventh of dim7 is the harmonic ("lowered") sixth; The lowered sixth "sounds good" in both modes because it creates a big tension that leads to the fifth, and also due to the fact that it creates another tritone with the third of the chord. The m7b5 chord is usually considered less powerful than the dim7, as the seventh has less tension towards any resolution, but it can still create interesting effects. The choice depends on the composer/arranger/performer, but it obviously should not collide with any other voice (the melody) and should consider the overall harmony and current harmonic progression.
I don't have much to add to other posts concerning the analysis, however I'd like to point another point. In some cases indeed either diminished and half-diminished chords might provide good harmonization of a melody, however they sound substantially different. If you play one or another randomly, due to mistakes, it might be very confusing for the rest of the band. It is very different from substituting e.g. Cmaj7 with C6, which can be innocent 90% of times.
110,430
In a song I am learning, there is a section of the song that has the chord progression G#m | A#m7b5 | B6 I sometimes get the fingerings wrong and use dimished 7th chords on guitar instead of m7b5 chords and in this case I actually think the dimished7th chord sounds good too. So I wanted to ask, what is the difference functionally between the two? They both seem to work in most situations as leading tone chords to a tonic chord one semitone above (B in this case).
2021/02/02
[ "https://music.stackexchange.com/questions/110430", "https://music.stackexchange.com", "https://music.stackexchange.com/users/35708/" ]
The tritone A♯ and E resolves nicely to B and D♯. Other notes in the chords are less important. That tritone is found in F♯7 (the standard dominant of B major). It's also found in A♯m7♭5 and in A♯dim7. (Also in C7, if we want to play with ♭5 substitutions.) So they'll all resolve in a nice functionally harmonic way to B major. There are other ways to approach B major. You can 'plane' up from A♯ major or A major. Don't struggle to analyse this as functional - being the same chord shape and being adjacent are sufficient. So does this mean a major triad, a dom7 chord, a dim7 and a half-dim7 all 'function the same'? No, that's far too general a statement.
While m7♭5 chords and dim7 chords are fairly interchangeable as dominant-function chords (don't interchange them if the melody note is the 7th), the dim7 chord is a much better **pivot chord** between keys than the m7♭5 chord, as any given dim7 chord is an enharmonic re-spelling of 3 other dim7 chords, while a m7♭5 chord cannot be enharmonically re-spelled into any other m7♭5 chords. When a dim7 chord is acting as a pivot chord, interchanging it is unwise.
64,811,703
I'm coding MERN app and I'm almost done with it. However, I am having problems displaying a single customer page with data. My App.js ``` import React from 'react'; import { BrowserRouter as Router, Route } from "react-router-dom"; import CustomersList from "./components/customers-list"; import customerRewards from './components/customerRewards'; import "bootstrap/dist/css/bootstrap.min.css"; function App() { return ( <Router> <div className="container"> <div className="header"> <h1>Wow Rewards Program</h1> </div> <Route path="/" exact component={CustomersList} /> <Route path='/:id' component={customerRewards} /> </div> </Router> ); } export default App; ``` My Customer list Component to list customers in main page ``` import React, { Component } from 'react'; import axios from 'axios'; import CustomerCard from "./customerCard"; class CustomersList extends Component { constructor(props) { super(props); this.state = { customers: [] } } componentDidMount() { axios.get('http://localhost:5000/customers/') .then(response => { this.setState({ customers: response.data }); }) .catch((error) => { console.log(error); }) } render() { const customers = this.state.customers; console.log("customerList", customers); let customersList; if(!customers) { customersList = "there is no customer record!"; } else { customersList = customers.map((customer, k) => <CustomerCard customer={customer} key={k} /> ); } return ( <div> <h2>Customers List</h2> <div> <table> <thead> <tr> <th>Account</th> <th>Name</th> <th>Actions</th> </tr> </thead> <tbody> {customersList} </tbody> </table> </div> </div> ) } } export default CustomersList; ``` My CustomerCard Component to display each customer ``` import React from 'react'; import { Link } from 'react-router-dom'; const CustomerCard = (props) => { const customerCard = props.customer; return ( <tr> <td>{customerCard.account}</td> <td>{customerCard.name}</td> <td> <Link to={`/${customerCard.account}`}>view</Link> </td> </tr> ) } export default CustomerCard; ``` My Customer Rewards Component to list customer details ``` import React, { Component } from 'react'; import { Link} from 'react-router-dom'; import '../App.css'; import axios from 'axios'; class customerRewards extends Component { constructor(props) { super(props); this.state = { customerRewards: {} }; } componentDidMount() { // const { accountId } = this.props.match.params; console.log("Print id: " + this.props.match.params.id); axios .get('http://localhost:5000/customers/'+this.props.match.params.id) .then(res => { // console.log("Print-customerRewards-API-response: " + res.data); this.setState({ customerRewards: res.data }) }) .catch(err => { console.log("Error from customerRewards"); }) }; render() { const customerRewards = this.state.customerRewards; console.log("customerID", customerRewards); let CustomerItem = <div> {customerRewards.purchase_history} </div> return ( <div > <div className="container"> <div className="row"> <div className="col-md-10 m-auto"> <br /> <br /> <Link to="/" className="btn btn-outline-warning float-left"> Back </Link> </div> <br /> <div className="col-md-8 m-auto"> <h1 className="display-4 text-center">Hello {customerRewards.name}</h1> <p className="lead text-center"> {customerRewards.account} </p> <hr /> <br /> </div> </div> <div> { CustomerItem } </div> </div> </div> ); } } export default customerRewards; ``` this is my .json sample that I uploaded to MongoDB Atlas: ``` [ { "account": "BCE456", "name": "JohnDoe", "purchase_history": [ { "month": "Month01", "transitions": [ { "date": "01/01/2010", "purchase": 120 }, { "date": "01/01/2010", "purchase": 120 }, { "date": "01/01/2010", "purchase": 120 } ] }, { "month": "Month02", "transitions": [ { "date": "01/01/2010", "purchase": 120 }, { "date": "01/01/2010", "purchase": 120 }, { "date": "01/01/2010", "purchase": 120 } ] } ] }, { "account": "ABC123", "name": "JohnDoe", "purchase_history": [ { "month": "Month01", "transitions": [ { "date": "01/01/2010", "purchase": 120 }, { "date": "01/01/2010", "purchase": 120 }, { "date": "01/01/2010", "purchase": 120 } ] }, { "month": "Month02", "transitions": [ { "date": "01/01/2010", "purchase": 120 }, { "date": "01/01/2010", "purchase": 120 }, { "date": "01/01/2010", "purchase": 120 } ] } ] } ] ``` I can see that I was able to download the customer details in `console.log("customerID", customerRewards);` However, when I tried to access `{customerRewards.name}`, it won't display the name at all.... [![enter image description here](https://i.stack.imgur.com/xg7yb.png)](https://i.stack.imgur.com/xg7yb.png) What am I missing? Could it have something to do with the params that I'm trying to link to? I tried to link by `account` instead of `_id`
2020/11/12
[ "https://Stackoverflow.com/questions/64811703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1088949/" ]
Your piece of state, `customerRewards` is an array when it comes from the API. So even when you declare your initial state with an object `{}`, `customerRewards` is always going to be an array with one element in this case. Could be an issue in your API response - I'm not familiar with MongoDB Atlas or if it creates access patterns for you but you should be able to configure to return a singular object with a unique ID rather than an array of 1 element. For now you could do: ``` this.setState({ customerRewards: res.data[0] /** could do res.data.shift() as well */ }) ``` I would figure out why you are returning an array if there is only supposed to be one element coming back.
just select the element which name you want to get: ``` customerRewards[0].name ```
69,539,215
I am asking for help for an issue i've been trying to solve for hours and hours, in vain. I am working with google query() on google spreadsheets. So i have this kind of table (lets say A1:E3) | Client | Bank receipt | Start Date | End date | Value | | --- | --- | --- | --- | --- | | John | #1 | 14/10/2021 | 31/10/2021 | 500 | | John | #2 | 14/10/2021 | 31/12/2021 | 500 | To make it clearer, the bank receipts are values that have a start date and an end date. So that bank receipt #2 covers 500 for october, november and december. What i am trying to do is a chronological table (with months in columns) that shows me the amount of bank receipt coverage for john during the year, so that to get this kind of result: | | | October | November | December | | --- | --- | --- | --- | --- | | John | Bank receipts | 1000 | 500 | 500 | This is the first step of a longer query but i need to get data returned this way to be able to go on. I tried to look for ways to return every month of date range but only founds posts talking abount google scripts i can't play with. I also tried using SEQUENCE() which seemed to work with some tricks until i put from 2021/12/15 to 2022/03/31 and it returned like 14 because of the year changing. So i am quite out of solutions. I precise that i am new to using google queries so i might miss some obvious things. Thanks a lot to who might help
2021/10/12
[ "https://Stackoverflow.com/questions/69539215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17133713/" ]
Try like this (in composition API you use ref or reactive instead data function, and you return your functions/reactive data): ``` <template> <div class="hamburger-toggle" @click="toggle" :class="{ nav__open: isActive }"> </template> <script> import { ref } from "@vue/reactivity"; export default { name: "navbar", setup() { const isActive = ref(true) const toggle = () => { isActive.value = !isActive.value } return { isActive, toggle } } </script> ```
Also, it will work with a little less code: ``` <template> <div @click="isActive = !isActive"> ... </div> </template> <script setup> import { ref } from "vue"; const isActive = ref(true) </script> ``` you can read here about the [`<script setup>`](https://blog.vuejs.org/posts/vue-3.2.html)
38,015
Whenever I'm trying to close a file that has been changed, I get the save file dialog ![save file dialog](https://i.stack.imgur.com/tsjeG.png) I remember that the *Don't Save* button used to have focus, so I could press it using Spacebar, while pressing Enter would click on *Save*. But now on Lion, I'm unable to find a way to press the *Don't Save* using keyboard only, since `Tab` doesn't change focus to anything, and space doesn't work either. This is the same for all file save dialogs in the system. **Is there any way I can press the *Don't Save* button using keyboard only?**
2012/01/23
[ "https://apple.stackexchange.com/questions/38015", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/2288/" ]
Go to... 1. **System Preferences→Keyboard→Keyboard Shortcuts** 2. and select **All controls** under **Full Keyboard Access** * Now you can use `⇥` (tab) to switch between the dialog boxes. * **Note**: Unlike in Windows, you need to hit `space` to trigger a highlighted box that is not the default one! (If this is not natural to you, here's something that helps many to remember tab and space rather than just enter. The space bar is the keyboard version of a one button mouse with the tab moving the mouse's pointer for you.) ![enter image description here](https://i.stack.imgur.com/YVBVZ.png)
On version 10.15.6, the previous answer didn't work as is. If you want to switch with Tab or "don't save" directly with the Space key, you'll need to go to **System Preferences** → **Keyboard** and toggle this option: [![printscreen of the toggled option](https://i.stack.imgur.com/TWiP0.png)](https://i.stack.imgur.com/TWiP0.png) —- **Update** With macOS Ventura, the exact place for this setting has been changed as follows: [![screenshot of the toggled option on on macOS 13.1](https://i.stack.imgur.com/AJ1co.png)](https://i.stack.imgur.com/AJ1co.png)
48,616
I have a simple product with custom options. After popup, I select custom options of this product, and click add to cart. I get params like that: `product=167&options%5B4%5D=10&qty=1`. Now I want to add product to cart programmatically, how can I do it?
2014/12/17
[ "https://magento.stackexchange.com/questions/48616", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/17279/" ]
please check the Mage\_Checkout\_CartController and addAction() inside, you will find everything you need ;) ``` $cart = $this->_getCart(); $params = $this->getRequest()->getParams(); try { if (isset($params['qty'])) { $filter = new Zend_Filter_LocalizedToNormalized( array('locale' => Mage::app()->getLocale()->getLocaleCode()) ); $params['qty'] = $filter->filter($params['qty']); } $product = $this->_initProduct(); $related = $this->getRequest()->getParam('related_product'); /** * Check product availability */ if (!$product) { $this->_goBack(); return; } $cart->addProduct($product, $params); if (!empty($related)) { $cart->addProductsByIds(explode(',', $related)); } $cart->save(); $this->_getSession()->setCartWasUpdated(true); /** * @todo remove wishlist observer processAddToCart */ Mage::dispatchEvent('checkout_cart_add_product_complete', array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()) ); if (!$this->_getSession()->getNoCartRedirect(true)) { if (!$cart->getQuote()->getHasError()){ $message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->htmlEscape($product->getName())); $this->_getSession()->addSuccess($message); } $this->_goBack(); } ```
Haven't tested the code below so might need some debugging but I guess it would be something like this ``` $productid = Mage::app()->getRequest()->getParam('product'); $qty = Mage::app()->getRequest()->getParam('qty'); $options = array(); foreach (Mage::app()->getRequest()->getParams() as $key => $value) { if (!strstr($key, 'options')) continue; $options[preg_replace('/([^0-9]+)/', '', $key)] = Mage::app()->getRequest()->getParam($key); } product=167&options[4]=10&qty=1 $_product = Mage::getModel('catalog/product')->load($productid); $_cart = Mage::getModel('checkout/cart'); $_cart->init(); $_cart->addProduct($_product, array( 'product' => $productid, 'qty' => $qty, 'options' => $options )); $_cart->save(); Mage::getSingleton('checkout/session')->setCartWasUpdated(true); ```
34,387
Can lower stages of current rockets be replaced to reusable and more efficient boosters with parachutes? Would reusable rocket stages save money?
2019/02/22
[ "https://space.stackexchange.com/questions/34387", "https://space.stackexchange.com", "https://space.stackexchange.com/users/18879/" ]
At [12 launches per year](https://spacenews.com/ariane-6-could-use-reusable-prometheus-engine-designer-says/), Arianespace does not see a business case for a reusable first stage. > > “We still have not understood, would we save money by reusing? At least with our launch rate?” he asked. “We hope to launch 12 times a year. If we reuse 12 times, that means we only manufacture one time per year. It is difficult for us to have that.” > > > Bonguet said reusability would essentially erase the production efficiencies ArianeGroup is striving for, starving the Ariane 6 industrial base of the work upon which it relies. > > > Now this is fairly specific to Arianespace's situation, where they have existing production facilities designed to build 12 stages a year, and no easy way to repurpose these for other work. SpaceX solved that problem: * they use 9 engines on the first stage (instead of just one) * they designed the first and second stage to be as similar as possible, so the same facilities can be used, and a reduction in work on first stages is mostly compensated by work on second stages. * they aim for much higher launch rates Arianespace is hamstrung by lack of available capital to develop more radical changes, instead of the minimum-change Ariane 6 we have now.
Reusable first stages are already saving SpaceX money. Parachute recovery has the drawback that your stage is going to splash down in corrosive salt water, requiring some cleaning and refurbishment before it's ready to fly again. Falcon 9 style powered-landing boosters have to reserve a lot of fuel mass for landing and optionally flyback. ULA is proposing parachute & helicopter recovery for just the first-stage engines of their next-generation Vulcan launcher.
1,553,916
I have a N-dimensional vector, X and 'n' equidistant points along each dimension and a parameter 'delta'. I need a way to find the total of n^N vectors enclosed by the Hypercube defined with the vector X at the center and each side of Hypercube being of size 2\*delta. For example: Consider a case of N=3, so we have a Cube of size (2\*delta) enclosing the point X. ``` ------------\ |\--------|--\ | | X | | ----------- | \ |_2*del___\| ``` Along each dimension I have 'n' points. So, I have a total of n^3 vectors around X. I need to find all the vectors. Is there any standard algorithm/method for the same? If you have done anything similar, please suggest. If the problem is not clear, let me know. This is what I was looking at: Considering one dimension, length of a side is 2\*delta and I have n divisions. So, each sub-division is of size (2\*delta/n). So I just move to the origin that is (x-delta) (since x is the mid point of the side) and obtain the 'n' points by {(x-delta) + 1\*(2\*delta/n),(x-delta) + 2\*(2\*delta/n)....+ (x-delta) + 1\*(n\*delta/n) } . I do this for all the N-dimensions and then take a permutation of the co-ordinates. That way I have all the points. *(I would like to close this)*
2009/10/12
[ "https://Stackoverflow.com/questions/1553916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If i understand your problem correctly, you have an axis-aligned hypercube centred around a point X, and you have subdivided the interior of this hypercube into a regular lattice where the lattice points and spacing are in the coordinate system of the hypercube. All you have to do is let X = 0, find the vectors to each of the lattice points, and then go back and translate them by X. Edit: let me add an example let x = (5,5,5), delta = 1 and n = 3 then, moving x to the origin, your lattice points are (-1, -1, -1), (0, -1, -1), (1, -1, -1) and so on for a total of 27. translating back, we have (4, 4, 4), (5, 4, 4), (6, 4, 4) and so on.
Ok, I didn't fully understand your question. There are total of `2^(N-1)*N` "lines" about a point in an N-dimensional hypercube. If you just want to create n points on lines which look like the axis, but translated at a distance of delta from the origin, here's some (poorly written, for clarity) MATLAB code: ``` n = 10; delta = 10; N = 3; step = (2*delta)/(n-1); P = zeros(n,N,N); X = [20 30 25]; for line_dim = 1:N for point = 1:n for point_dim = 1:N if(point_dim ~= line_dim) P(point,point_dim,line_dim) = X(point_dim)-delta; else P(point,point_dim,line_dim) = X(point_dim)-delta+step*(point-1); end end end end ``` The code's for a cube, but it should work for any N. All I've done is: 1. Draw those n equidistant points on the axes. 2. Translate the axes by (X-delta) **Display:** ``` % Display stuff PP = reshape(permute(P,[1 3 2]),[n*N N]); plot3(X(1),X(2),X(3),'r*',PP(:,1),PP(:,2),PP(:,3),'.') axis([0 Inf 0 Inf 0 Inf]); grid on; ```
17,176
What was the concept behind the staff that Loki used in the Avengers movie? It contained a blue crystal (presumably a part of the tesseract?) He uses it to put people like Hawkeye under a spell of sorts and also used it to blast stuff. I assumed that the tesseract could only be used as an energy source. It is evidently not true if the tesseract is used to hypnotize people. Can humans also use the tesseract for such purposes or was Loki the only one who could harness these powers? What additional uses can a tesseract have?
2012/05/24
[ "https://scifi.stackexchange.com/questions/17176", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/2288/" ]
### Loki is an [Asgardian](https://scifi.stackexchange.com/a/16815/2765). In the Marvel Cinematic Universe, he is a member of a super-advanced race of beings that live on other planets far from Earth, but connected via technological tools. Loki's staff was believed to be one of those tools. **UPDATE:** It appears Loki's Staff (or the Chitari Staff) does house the Infinity Mind Gem. Revealed in a recent trailer and expounded upon by **[ScreenRant](http://screenrant.com/thor-3-tom-hiddleston-loki-scepter-infinity-mind-gem/):** > > * **During the Avengers Infinity War teaser that was shown at the event, it was also confirmed that Loki’s scepter is one of the [Infinity Gems](https://scifi.stackexchange.com/a/43755/2765) Thanos (Josh Brolin) will have in his Gauntlet.** > > > --- 1. Loki's staff is an alien device used to focus his power. The Asgardians use tools similar to the staff that appear to be a form of magic (but are just another super-advanced science hidden behind mummery and gestures) to augment their physical, mental or psychic abilities, of which Loki appears to have all three in abundance. If we use the meme of sorcery, the staff was nothing more than a focus for his power, allowing him to tap into and lock onto **The Tesseract/[Cosmic Cube](http://en.wikipedia.org/wiki/Cosmic_Cube)**. 2. There is no canon relationship between the crystal in the staff and the Tesseract/Cosmic cube. Since Cosmic Cubes have never needed any other tools to perform their powers, perhaps the similarity in color signified a synchronization process between the two devices. Perhaps the designers of the movie wanted to show there was a relationship between the two devices, especially since the staff is later used to disrupt the Cosmic Cube's dimensional doorway. 3. Later, it was mentioned by Professor Erik Selvig that he had encoded a shutdown sequence inside of the crystal by an as yet undisclosed means. All previous canon regarding the Cosmic Cube says they cannot be easily destroyed and pieces cannot be shaved off. So it is more another sign of a technological synchronization between the Cube and the staff. 4. The hypnosis power was more likely an aspect of Loki's psychic ability and as a well known trickster, a tool he was likely to employ in the presence of minds able to be dominated by his own. If he was using a linkage to the Cube, he may have opened the minds of his victims to the dimension inside of the Cosmic Cube making them more vulnerable to Loki's powers.
The staff is a magic weapon from Asgard and the crystal he uses is different from the gems from the infinity gauntlet. It is the mind gem, not part of the tesseract.
33,094,033
I'm pretty sure I'm doing things the wrong way and I'd like to know the right way. The problem I face is: * I have a distributed batch job * I use AWS spot instances to fulfill it * always a one-off request (so I'm after simple solutions) * The instances need some configuration and setup, and they need to be sent tasks to do I typically solve it like this: * Bring up one worker and configure it * Save an image of it * Then bring up all the other instances * Then I'll do a big, annoying, copy paste job, to basically create a shell script like this: `$HOST=123.123.123.1 $TASK=task1 ssh ubuntu@$HOST task_runner $TASK & $HOST=123.123.123.2 $TASK=task2 ssh ubuntu@$HOST task_runner $TASK & $HOST=123.123.123.3 $TASK=task3 ssh ubuntu@$HOST task_runner $TASK & ...` I'd like to do this better, so I'm after ways to make it easier to: 1. Set up AWS instances. Sometimes there's a boot-time code that needs to be run, and this means more big tasks like the one above 2. Get the instance list. No more copy-pasting! 3. Run all the tasks on all the instances. 4. Shut them down when I'm done Ideally I'd like to cover the whole lifecycle, end to end. Lastly, I want something pretty simple. Because it's a one off task, I don't really want to have to deal with a whole lot of config options and wiring.
2015/10/13
[ "https://Stackoverflow.com/questions/33094033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/617026/" ]
You could use [Ansible](http://www.ansible.com/) to do this reasonably simply. Your Ansible playbook would look something like: ``` - name: Stage instance(s) hosts: local connection: local gather_facts: false vars: keypair: mykeypair instance_type: m1.small security_group: sg-123456abc image: ami-123456abc vpc_subnet_id: subnet-123456abc count: 5 tasks: - name: Create spot instance ec2: spot_price: 0.24 spot_wait_timeout: 600 keypair: {{ keypair }} group_id: {{ security_group }} instance_type: {{ instance_type }} image: {{ image }} vpc_subnet_id: {{ vpc_subnet_id }} assign_public_ip: no count: {{ count }} wait: yes register: ec2 - name: Add new instances to host group add_host: hostname={{item.private_ip}} groupname=task_minions with_items: ec2.instances - name: Wait for the instances to boot by checking the ssh port wait_for: host={{item.private_dns_name}} port=22 delay=60 timeout=320 state=started with_items: ec2.instances - name: Configure instance(s) hosts: task_minions remote_user: ec2-user tasks: - name: Some configuration yum: ... - name: Run tasks hosts: task_minions remote_user: ec2-user tasks: - name: Run all tasks on all task_minions command: task_runner {{ item }} with_items: - task_1 - task_2 ... - name: Terminate instance(s) hosts: localhost connection: local tasks: - name: Terminate instances that were previously launched ec2: state: 'absent' instance_ids: '{{ ec2.instance_ids }}' ``` I have less experience with other configuration management tools but I'm sure they could also be used as well.
couple of things to try / think about: 1) you should look into building an AMI with everything you need from the image + the hook that runs the boot time code. This should allow you to just boot up images with this AMI and not having to worry about building it 2) use an SQS queue to dispatch the tasks. this way the workers can just pull from that queue and you can tell pretty easily when they're done. (queue goes to 0 with no messages in flight). 3) For extra awesomeness. Combine the SQS dispatching with autoscalling: <http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/as-using-sqs-queue.html> This way you can have autoscalling spin up/spin down your instances whenever there is work. The only thing you need to do is to push things to the queue. 4) For mega extra awesomeness. Do all 3 above + put everything in a CloudFormation template and spin up a Cloudformation Stack. If you ever need to tinker with the setup (change images, queues, config, etc) you can simply tweak the template and redeploy. Hope this helps.
15,539
There are many movies and TV episodes in which a character "crosses his own timeline", sometimes even meeting his past or future self (e.g. *The Day of the Doctor*). Technically, I should say meeting his past self *and* meeting his future self, I suppose, since this is actually what happens. When they supposedly alter their own future resulting in their never having travelled in time (as in *Back to The Future* or *Looper*), or narrowly avoid doing so, this is known as the "grandfather paradox". How are we, the audience, supposed to make sense of this, if we actually think it through logically? If you perform an action which has an effect that you never survived or were never ever born, then how did you travel in time in the first place? (Although it's not really "in the first place", if you travelled backwards in time...) I know that there is some quantum mechanics theory relevant to this but the average cinema-goer doesn't know about all that stuff, surely...
2013/12/01
[ "https://movies.stackexchange.com/questions/15539", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/729/" ]
There are two logical ways of dealing with time travel paradoxes: * [**Stable time loop**](http://tvtropes.org/pmwiki/pmwiki.php/Main/StableTimeLoop). When you travel to the past, whatever you do, you won't actually change anything (which pretty much implies there is no free will). In fiction, the way this is often done is that the time traveller attempts to change the past, but doesn't succeed, because it was him who caused the final outcome in the first place. Or something like that. * [**Alternate timelines**](http://tvtropes.org/pmwiki/pmwiki.php/Main/AlternateTimeline). When you travel back in time, you cause the creation of an alternate timeline. So there are now two timelines: the one where you left and the one where you arrived. This means that you can do anything and it won't change the original timeline, so no paradoxes are possible. Though many films and TV shows (including BTTF and Doctor Who) don't use any of the two approaches and instead use approach that doesn't make sense (people slowly vanishing, monsters killing people because change occured, but only sometimes).
My belief is that the audience is guided towards the nonsensical belief that there are two dimensions of time - ordinary time, and "meta-time" - that is, that before "now" in "meta-time", the universe had such-and-such a history, but one second later in "meta-time", history was "changed", and the past became a different past. This doesn't actually make sense from a physics point of view, and they are usually careful not to be explicit about it. I am not talking about "personal time" - how time subjectively appears to a character - although it is easy to get confused between "personal time" and this idea of meta-time, because they are usually coterminous from the point of view of a particular protagonist. The only way to make it really consistent is if the protagonist who "changes the past" is really God, and everything else is effectively just a figment of his imagination, or a dream in other words. Otherwise, as soon as you start thinking about what would happen if someone else also "changed the past", it all falls apart, because the "personal time" theory doesn't fit.
15,539
There are many movies and TV episodes in which a character "crosses his own timeline", sometimes even meeting his past or future self (e.g. *The Day of the Doctor*). Technically, I should say meeting his past self *and* meeting his future self, I suppose, since this is actually what happens. When they supposedly alter their own future resulting in their never having travelled in time (as in *Back to The Future* or *Looper*), or narrowly avoid doing so, this is known as the "grandfather paradox". How are we, the audience, supposed to make sense of this, if we actually think it through logically? If you perform an action which has an effect that you never survived or were never ever born, then how did you travel in time in the first place? (Although it's not really "in the first place", if you travelled backwards in time...) I know that there is some quantum mechanics theory relevant to this but the average cinema-goer doesn't know about all that stuff, surely...
2013/12/01
[ "https://movies.stackexchange.com/questions/15539", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/729/" ]
My belief is that the audience is guided towards the nonsensical belief that there are two dimensions of time - ordinary time, and "meta-time" - that is, that before "now" in "meta-time", the universe had such-and-such a history, but one second later in "meta-time", history was "changed", and the past became a different past. This doesn't actually make sense from a physics point of view, and they are usually careful not to be explicit about it. I am not talking about "personal time" - how time subjectively appears to a character - although it is easy to get confused between "personal time" and this idea of meta-time, because they are usually coterminous from the point of view of a particular protagonist. The only way to make it really consistent is if the protagonist who "changes the past" is really God, and everything else is effectively just a figment of his imagination, or a dream in other words. Otherwise, as soon as you start thinking about what would happen if someone else also "changed the past", it all falls apart, because the "personal time" theory doesn't fit.
If the time travel is branching, then it needs no explanation, but if it's linear, then I'd imagine it's because time travelling protected them? For example, and I hope this is not just in the CW show, the Reverse Flash, mortal enemy of the Flash (I hope you could've figured that one out on your own), is able to basically exist in every time period because the Speed Force protects him and there's versions of him... everywhen? But Marty began to disappear in BTTF, whereas Reverse Flash isn't affected at all in his time travelling. Different worlds have different rules so it depends on the specific universe.
15,539
There are many movies and TV episodes in which a character "crosses his own timeline", sometimes even meeting his past or future self (e.g. *The Day of the Doctor*). Technically, I should say meeting his past self *and* meeting his future self, I suppose, since this is actually what happens. When they supposedly alter their own future resulting in their never having travelled in time (as in *Back to The Future* or *Looper*), or narrowly avoid doing so, this is known as the "grandfather paradox". How are we, the audience, supposed to make sense of this, if we actually think it through logically? If you perform an action which has an effect that you never survived or were never ever born, then how did you travel in time in the first place? (Although it's not really "in the first place", if you travelled backwards in time...) I know that there is some quantum mechanics theory relevant to this but the average cinema-goer doesn't know about all that stuff, surely...
2013/12/01
[ "https://movies.stackexchange.com/questions/15539", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/729/" ]
My belief is that the audience is guided towards the nonsensical belief that there are two dimensions of time - ordinary time, and "meta-time" - that is, that before "now" in "meta-time", the universe had such-and-such a history, but one second later in "meta-time", history was "changed", and the past became a different past. This doesn't actually make sense from a physics point of view, and they are usually careful not to be explicit about it. I am not talking about "personal time" - how time subjectively appears to a character - although it is easy to get confused between "personal time" and this idea of meta-time, because they are usually coterminous from the point of view of a particular protagonist. The only way to make it really consistent is if the protagonist who "changes the past" is really God, and everything else is effectively just a figment of his imagination, or a dream in other words. Otherwise, as soon as you start thinking about what would happen if someone else also "changed the past", it all falls apart, because the "personal time" theory doesn't fit.
This is a variation of Flater's answer about the universe "preventing" the paradox. At first I was going to comment that it requires a sort of "God" or "Deus Ex Machina" to intervene on behalf of the plot. But think of it slightly differently: Quantum physics tells us that there is an inherent randomness in the universe. Maybe someone with more knowledge of it can explain it better, but essentially each action and object is actually the average of zillions of probabilities. So while two things might appear identical, at a subatomic level they are completely different. Now at first glance, the Grandfather paradox is an infinite loop. But what if because of the quantum randomness, each iteration is actually different at a quantum level if not at a macro level. This means that there is an infinitesimal, but non-zero chance that you will fail to kill your grandfather. (Or fail to travel back in time) But with infinity, even the ridiculously improbable will eventually happen. So even if it takes a gazillion journeys through the time loop, one will eventually occur where you fail to kill your grandfather. And since this one does not prompt a recurrence of the loop, this is the one that will "stick". You'll forget all the iterations of the loop that have been replaced by this one. This will only happen with paradoxes of course, because if there isn't a paradox there isn't an infinite time loop. Because it's a *time* loop, all occurrences of the loop happen at the same time so you don't notice the bazillions of epochs that the loop has been through. So it will appear that the universe or some power does intervene to prevent paradoxes.
15,539
There are many movies and TV episodes in which a character "crosses his own timeline", sometimes even meeting his past or future self (e.g. *The Day of the Doctor*). Technically, I should say meeting his past self *and* meeting his future self, I suppose, since this is actually what happens. When they supposedly alter their own future resulting in their never having travelled in time (as in *Back to The Future* or *Looper*), or narrowly avoid doing so, this is known as the "grandfather paradox". How are we, the audience, supposed to make sense of this, if we actually think it through logically? If you perform an action which has an effect that you never survived or were never ever born, then how did you travel in time in the first place? (Although it's not really "in the first place", if you travelled backwards in time...) I know that there is some quantum mechanics theory relevant to this but the average cinema-goer doesn't know about all that stuff, surely...
2013/12/01
[ "https://movies.stackexchange.com/questions/15539", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/729/" ]
There are two logical ways of dealing with time travel paradoxes: * [**Stable time loop**](http://tvtropes.org/pmwiki/pmwiki.php/Main/StableTimeLoop). When you travel to the past, whatever you do, you won't actually change anything (which pretty much implies there is no free will). In fiction, the way this is often done is that the time traveller attempts to change the past, but doesn't succeed, because it was him who caused the final outcome in the first place. Or something like that. * [**Alternate timelines**](http://tvtropes.org/pmwiki/pmwiki.php/Main/AlternateTimeline). When you travel back in time, you cause the creation of an alternate timeline. So there are now two timelines: the one where you left and the one where you arrived. This means that you can do anything and it won't change the original timeline, so no paradoxes are possible. Though many films and TV shows (including BTTF and Doctor Who) don't use any of the two approaches and instead use approach that doesn't make sense (people slowly vanishing, monsters killing people because change occured, but only sometimes).
The highest voted answer makes sense, but it seems to omit a third possibility, which happens to be the theory I subscribe to. There are many theories. I like this one the most because it makes sense (to me) and is consistent with how the (real world) universe tries to solve similar paradoxes, e.g. when two objects try to occupy the same space at the same time. First of all, I think we can agree that **if there is no paradox, there is no problem**. In other words, everything that's not a paradox can be assumed to work, since it doesn't create any problems. We only need to consider how the universe handles near-paradoxical situations. **The universe will do everything it can (including breaking its own rules) in order to avoid a paradox. However, the universe will always favor using the path of least resistance (= the option which requires the least amount of breaking the rules).** ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Let's use the grandfather paradox. I go back in time, and try to kill my grandfather (before my father was born) by using a sword. The universe cannot allow that, since it could create a paradox. Therefore, I am unable to lethally wound my grandfather. * When you try to force two objects to occupy the same space at the same time (by pushing really hard), you simply cannot do this. The objects will break long before you'll be able to have them occupy the same space. * When you try to bring two very strong magnets (with the same polarity) together, they will not allow you to do that. Whenever you bring them close, the magnetic force tends to make you veer off. * If you use **tremendous** force, you can bring the magnets together, as long as this tremendous force is (1) bigger than the magnetic repulsion force, (2) smaller than the force needed for the magnets to break and (3) continuously applied. Therefore, if I try to stab my grandfather, the universe will make my sword veer off course, missing my grandfather. As much as I try to stab him, the universe will provide a counterforce. Just like how a magnet uses force to repel a magnet of the same polarity, the universe will use a force to repel the action that **invariably** introduces a paradox. Suppose I don't intend to lethally wound my grandfather, I only stab him on the hand. Then the universe has several options to deal with this: * If this wound does not change my grandfather's future (he will still end up having my father, my father will still end up having me), then the universe **allows** it. There is no paradox. * If this wound precludes my grandfather from having my father (e.g. his injury makes him use his other hand, therefore not spilling the drink that he's supposed to spill on my grandmother when he is supposed to meet her), then the paradox should be **equally disallowed** (similar to when I try to lethally wound my grandfather). Note that I mentioned how the universe favors **the path of least resistance**. Since the universe is "inventing" a force that would make my sword veer off course, that requires X amount of force. But if the universe has a way to avoid the paradox using less force (less than X), then it will favor this alternate route. If the force needed to veer the sword off course is greater than the force needed to knock over that drink and spill it on my grandmother (thus introducing my grandparents, even if he wasn't the one who spilled the drink), then the paradox can be resolved this way and the universe will favor knocking over the glass as it is the path of least resistance. **This is consistent with Back To The Future**. * Marty mistakenly intervenes in how his parents fell in love, thus endangering his future. However, the universe has allowed this to happen, as no (unavoidable) paradox has yet been created. * Marty does start fading away at the end of the movie, because the paradox is getting closer and closer to becoming **unavoidable**. For example, if Marty took several years to get his parents to fall in love, then they probably would have had Marty at a later stage in life (thus creating a paradox). * However, so long as Marty's parents are still able to fall in love, on time to give birth to Marty at the right time, the universe has not yet deleted Marty, as he is still **possible**. * Marty ends up fixing the problem by getting them to fall in love in a different way. Marty has changed the past, but in a way that **the future is unaffected**. Changes have been introduced, but no paradox, and therefore the universe does not intervene. This is the same as the drink that gets spilt on my grandmother. Both the spilt drink and Marty's parents falling in love **invariably** leads to my grandparents giving birth to my father, and Marty's parents giving birth to Marty. *Minor note: In my example, the glass gets knocked over by the universe. In BTTF, Marty is the driving force behind the correction. However, it's possible to argue that the universe helped Marty along in order to achieve his goal (e.g. making him run faster just so he gets to his destination on time, if being late causes the paradox to become unavoidable). This possibility only applies if helping Marty costs less effort than the universe fixing it by itself.* **This is also consistent with Doctor Who**. * In the episode where they are trapped inside a dying TARDIS, the Doctor, Clara and three guests are being chased by monsters (who look like burnt zombies). * It is revealed that these burnt zombies are actually **future Clara and the future guests**, who have been burnt by the TARDIS' main reactor. * Two zombies are attached to eachother. The Doctor realizes that these are the two remaining guests (the third one was already dead). * The Doctor tells the alive guests to **never touch eachother again**, because not touching eachother makes it impossible for them to fuse together, thus creating a paradox (the Doctor **wants** to create a paradox here). * As long as they never touch, their future selves (the merged zombie) is **impossible**. And if it is impossible, then the universe should delete that future (similar to how Marty fades once he becomes an impossible future). * This works for a while, and the future seems to be rewritten. However, the guests forget about not touching eachother, and touch eachother. **As if by force**, they are **immediately** joined together and burnt, becoming the burnt zombies. This force was supplied by the universe. Rather than deleting the future zombies (which takes a lot of effort to rewrite the future), the universe favors **bumping the two guests together**, as this requires less force and it ensures that the future is actually correct and therefore does not need to be deleted. Note that **Clara** has managed to avoid her burnt future. Because the guests have managed to *stall* the inevitable (touching eachother) long enough, they have changed the future enough to delete burnt Clara (as she is no longer possible), but they did not stall long enough for their **own** futures to be rewritten. I can't speak to Looper, as I haven't seen it. Conclusion ---------- **That's proof of how it should work, according to me.** We've seen both cases: trying to prevent changes to the future (BTTF) and trying to create changes to the future (Doctor Who). In both cases, the universe applies the same rules: it maintained logical consistency at all costs, even if that means it has to invent a "phantom force" (which breaks the rules of the universe, specifically [the first law of thermodynamics](https://en.wikipedia.org/wiki/First_law_of_thermodynamics)). In order to **minimize** how much it breaks its own rules, the universe tries to apply the least amount of "phantom force" (= the path of least resistance).
15,539
There are many movies and TV episodes in which a character "crosses his own timeline", sometimes even meeting his past or future self (e.g. *The Day of the Doctor*). Technically, I should say meeting his past self *and* meeting his future self, I suppose, since this is actually what happens. When they supposedly alter their own future resulting in their never having travelled in time (as in *Back to The Future* or *Looper*), or narrowly avoid doing so, this is known as the "grandfather paradox". How are we, the audience, supposed to make sense of this, if we actually think it through logically? If you perform an action which has an effect that you never survived or were never ever born, then how did you travel in time in the first place? (Although it's not really "in the first place", if you travelled backwards in time...) I know that there is some quantum mechanics theory relevant to this but the average cinema-goer doesn't know about all that stuff, surely...
2013/12/01
[ "https://movies.stackexchange.com/questions/15539", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/729/" ]
There are two logical ways of dealing with time travel paradoxes: * [**Stable time loop**](http://tvtropes.org/pmwiki/pmwiki.php/Main/StableTimeLoop). When you travel to the past, whatever you do, you won't actually change anything (which pretty much implies there is no free will). In fiction, the way this is often done is that the time traveller attempts to change the past, but doesn't succeed, because it was him who caused the final outcome in the first place. Or something like that. * [**Alternate timelines**](http://tvtropes.org/pmwiki/pmwiki.php/Main/AlternateTimeline). When you travel back in time, you cause the creation of an alternate timeline. So there are now two timelines: the one where you left and the one where you arrived. This means that you can do anything and it won't change the original timeline, so no paradoxes are possible. Though many films and TV shows (including BTTF and Doctor Who) don't use any of the two approaches and instead use approach that doesn't make sense (people slowly vanishing, monsters killing people because change occured, but only sometimes).
If the time travel is branching, then it needs no explanation, but if it's linear, then I'd imagine it's because time travelling protected them? For example, and I hope this is not just in the CW show, the Reverse Flash, mortal enemy of the Flash (I hope you could've figured that one out on your own), is able to basically exist in every time period because the Speed Force protects him and there's versions of him... everywhen? But Marty began to disappear in BTTF, whereas Reverse Flash isn't affected at all in his time travelling. Different worlds have different rules so it depends on the specific universe.
15,539
There are many movies and TV episodes in which a character "crosses his own timeline", sometimes even meeting his past or future self (e.g. *The Day of the Doctor*). Technically, I should say meeting his past self *and* meeting his future self, I suppose, since this is actually what happens. When they supposedly alter their own future resulting in their never having travelled in time (as in *Back to The Future* or *Looper*), or narrowly avoid doing so, this is known as the "grandfather paradox". How are we, the audience, supposed to make sense of this, if we actually think it through logically? If you perform an action which has an effect that you never survived or were never ever born, then how did you travel in time in the first place? (Although it's not really "in the first place", if you travelled backwards in time...) I know that there is some quantum mechanics theory relevant to this but the average cinema-goer doesn't know about all that stuff, surely...
2013/12/01
[ "https://movies.stackexchange.com/questions/15539", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/729/" ]
There are two logical ways of dealing with time travel paradoxes: * [**Stable time loop**](http://tvtropes.org/pmwiki/pmwiki.php/Main/StableTimeLoop). When you travel to the past, whatever you do, you won't actually change anything (which pretty much implies there is no free will). In fiction, the way this is often done is that the time traveller attempts to change the past, but doesn't succeed, because it was him who caused the final outcome in the first place. Or something like that. * [**Alternate timelines**](http://tvtropes.org/pmwiki/pmwiki.php/Main/AlternateTimeline). When you travel back in time, you cause the creation of an alternate timeline. So there are now two timelines: the one where you left and the one where you arrived. This means that you can do anything and it won't change the original timeline, so no paradoxes are possible. Though many films and TV shows (including BTTF and Doctor Who) don't use any of the two approaches and instead use approach that doesn't make sense (people slowly vanishing, monsters killing people because change occured, but only sometimes).
This is a variation of Flater's answer about the universe "preventing" the paradox. At first I was going to comment that it requires a sort of "God" or "Deus Ex Machina" to intervene on behalf of the plot. But think of it slightly differently: Quantum physics tells us that there is an inherent randomness in the universe. Maybe someone with more knowledge of it can explain it better, but essentially each action and object is actually the average of zillions of probabilities. So while two things might appear identical, at a subatomic level they are completely different. Now at first glance, the Grandfather paradox is an infinite loop. But what if because of the quantum randomness, each iteration is actually different at a quantum level if not at a macro level. This means that there is an infinitesimal, but non-zero chance that you will fail to kill your grandfather. (Or fail to travel back in time) But with infinity, even the ridiculously improbable will eventually happen. So even if it takes a gazillion journeys through the time loop, one will eventually occur where you fail to kill your grandfather. And since this one does not prompt a recurrence of the loop, this is the one that will "stick". You'll forget all the iterations of the loop that have been replaced by this one. This will only happen with paradoxes of course, because if there isn't a paradox there isn't an infinite time loop. Because it's a *time* loop, all occurrences of the loop happen at the same time so you don't notice the bazillions of epochs that the loop has been through. So it will appear that the universe or some power does intervene to prevent paradoxes.
15,539
There are many movies and TV episodes in which a character "crosses his own timeline", sometimes even meeting his past or future self (e.g. *The Day of the Doctor*). Technically, I should say meeting his past self *and* meeting his future self, I suppose, since this is actually what happens. When they supposedly alter their own future resulting in their never having travelled in time (as in *Back to The Future* or *Looper*), or narrowly avoid doing so, this is known as the "grandfather paradox". How are we, the audience, supposed to make sense of this, if we actually think it through logically? If you perform an action which has an effect that you never survived or were never ever born, then how did you travel in time in the first place? (Although it's not really "in the first place", if you travelled backwards in time...) I know that there is some quantum mechanics theory relevant to this but the average cinema-goer doesn't know about all that stuff, surely...
2013/12/01
[ "https://movies.stackexchange.com/questions/15539", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/729/" ]
The highest voted answer makes sense, but it seems to omit a third possibility, which happens to be the theory I subscribe to. There are many theories. I like this one the most because it makes sense (to me) and is consistent with how the (real world) universe tries to solve similar paradoxes, e.g. when two objects try to occupy the same space at the same time. First of all, I think we can agree that **if there is no paradox, there is no problem**. In other words, everything that's not a paradox can be assumed to work, since it doesn't create any problems. We only need to consider how the universe handles near-paradoxical situations. **The universe will do everything it can (including breaking its own rules) in order to avoid a paradox. However, the universe will always favor using the path of least resistance (= the option which requires the least amount of breaking the rules).** ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Let's use the grandfather paradox. I go back in time, and try to kill my grandfather (before my father was born) by using a sword. The universe cannot allow that, since it could create a paradox. Therefore, I am unable to lethally wound my grandfather. * When you try to force two objects to occupy the same space at the same time (by pushing really hard), you simply cannot do this. The objects will break long before you'll be able to have them occupy the same space. * When you try to bring two very strong magnets (with the same polarity) together, they will not allow you to do that. Whenever you bring them close, the magnetic force tends to make you veer off. * If you use **tremendous** force, you can bring the magnets together, as long as this tremendous force is (1) bigger than the magnetic repulsion force, (2) smaller than the force needed for the magnets to break and (3) continuously applied. Therefore, if I try to stab my grandfather, the universe will make my sword veer off course, missing my grandfather. As much as I try to stab him, the universe will provide a counterforce. Just like how a magnet uses force to repel a magnet of the same polarity, the universe will use a force to repel the action that **invariably** introduces a paradox. Suppose I don't intend to lethally wound my grandfather, I only stab him on the hand. Then the universe has several options to deal with this: * If this wound does not change my grandfather's future (he will still end up having my father, my father will still end up having me), then the universe **allows** it. There is no paradox. * If this wound precludes my grandfather from having my father (e.g. his injury makes him use his other hand, therefore not spilling the drink that he's supposed to spill on my grandmother when he is supposed to meet her), then the paradox should be **equally disallowed** (similar to when I try to lethally wound my grandfather). Note that I mentioned how the universe favors **the path of least resistance**. Since the universe is "inventing" a force that would make my sword veer off course, that requires X amount of force. But if the universe has a way to avoid the paradox using less force (less than X), then it will favor this alternate route. If the force needed to veer the sword off course is greater than the force needed to knock over that drink and spill it on my grandmother (thus introducing my grandparents, even if he wasn't the one who spilled the drink), then the paradox can be resolved this way and the universe will favor knocking over the glass as it is the path of least resistance. **This is consistent with Back To The Future**. * Marty mistakenly intervenes in how his parents fell in love, thus endangering his future. However, the universe has allowed this to happen, as no (unavoidable) paradox has yet been created. * Marty does start fading away at the end of the movie, because the paradox is getting closer and closer to becoming **unavoidable**. For example, if Marty took several years to get his parents to fall in love, then they probably would have had Marty at a later stage in life (thus creating a paradox). * However, so long as Marty's parents are still able to fall in love, on time to give birth to Marty at the right time, the universe has not yet deleted Marty, as he is still **possible**. * Marty ends up fixing the problem by getting them to fall in love in a different way. Marty has changed the past, but in a way that **the future is unaffected**. Changes have been introduced, but no paradox, and therefore the universe does not intervene. This is the same as the drink that gets spilt on my grandmother. Both the spilt drink and Marty's parents falling in love **invariably** leads to my grandparents giving birth to my father, and Marty's parents giving birth to Marty. *Minor note: In my example, the glass gets knocked over by the universe. In BTTF, Marty is the driving force behind the correction. However, it's possible to argue that the universe helped Marty along in order to achieve his goal (e.g. making him run faster just so he gets to his destination on time, if being late causes the paradox to become unavoidable). This possibility only applies if helping Marty costs less effort than the universe fixing it by itself.* **This is also consistent with Doctor Who**. * In the episode where they are trapped inside a dying TARDIS, the Doctor, Clara and three guests are being chased by monsters (who look like burnt zombies). * It is revealed that these burnt zombies are actually **future Clara and the future guests**, who have been burnt by the TARDIS' main reactor. * Two zombies are attached to eachother. The Doctor realizes that these are the two remaining guests (the third one was already dead). * The Doctor tells the alive guests to **never touch eachother again**, because not touching eachother makes it impossible for them to fuse together, thus creating a paradox (the Doctor **wants** to create a paradox here). * As long as they never touch, their future selves (the merged zombie) is **impossible**. And if it is impossible, then the universe should delete that future (similar to how Marty fades once he becomes an impossible future). * This works for a while, and the future seems to be rewritten. However, the guests forget about not touching eachother, and touch eachother. **As if by force**, they are **immediately** joined together and burnt, becoming the burnt zombies. This force was supplied by the universe. Rather than deleting the future zombies (which takes a lot of effort to rewrite the future), the universe favors **bumping the two guests together**, as this requires less force and it ensures that the future is actually correct and therefore does not need to be deleted. Note that **Clara** has managed to avoid her burnt future. Because the guests have managed to *stall* the inevitable (touching eachother) long enough, they have changed the future enough to delete burnt Clara (as she is no longer possible), but they did not stall long enough for their **own** futures to be rewritten. I can't speak to Looper, as I haven't seen it. Conclusion ---------- **That's proof of how it should work, according to me.** We've seen both cases: trying to prevent changes to the future (BTTF) and trying to create changes to the future (Doctor Who). In both cases, the universe applies the same rules: it maintained logical consistency at all costs, even if that means it has to invent a "phantom force" (which breaks the rules of the universe, specifically [the first law of thermodynamics](https://en.wikipedia.org/wiki/First_law_of_thermodynamics)). In order to **minimize** how much it breaks its own rules, the universe tries to apply the least amount of "phantom force" (= the path of least resistance).
If the time travel is branching, then it needs no explanation, but if it's linear, then I'd imagine it's because time travelling protected them? For example, and I hope this is not just in the CW show, the Reverse Flash, mortal enemy of the Flash (I hope you could've figured that one out on your own), is able to basically exist in every time period because the Speed Force protects him and there's versions of him... everywhen? But Marty began to disappear in BTTF, whereas Reverse Flash isn't affected at all in his time travelling. Different worlds have different rules so it depends on the specific universe.
15,539
There are many movies and TV episodes in which a character "crosses his own timeline", sometimes even meeting his past or future self (e.g. *The Day of the Doctor*). Technically, I should say meeting his past self *and* meeting his future self, I suppose, since this is actually what happens. When they supposedly alter their own future resulting in their never having travelled in time (as in *Back to The Future* or *Looper*), or narrowly avoid doing so, this is known as the "grandfather paradox". How are we, the audience, supposed to make sense of this, if we actually think it through logically? If you perform an action which has an effect that you never survived or were never ever born, then how did you travel in time in the first place? (Although it's not really "in the first place", if you travelled backwards in time...) I know that there is some quantum mechanics theory relevant to this but the average cinema-goer doesn't know about all that stuff, surely...
2013/12/01
[ "https://movies.stackexchange.com/questions/15539", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/729/" ]
The highest voted answer makes sense, but it seems to omit a third possibility, which happens to be the theory I subscribe to. There are many theories. I like this one the most because it makes sense (to me) and is consistent with how the (real world) universe tries to solve similar paradoxes, e.g. when two objects try to occupy the same space at the same time. First of all, I think we can agree that **if there is no paradox, there is no problem**. In other words, everything that's not a paradox can be assumed to work, since it doesn't create any problems. We only need to consider how the universe handles near-paradoxical situations. **The universe will do everything it can (including breaking its own rules) in order to avoid a paradox. However, the universe will always favor using the path of least resistance (= the option which requires the least amount of breaking the rules).** ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Let's use the grandfather paradox. I go back in time, and try to kill my grandfather (before my father was born) by using a sword. The universe cannot allow that, since it could create a paradox. Therefore, I am unable to lethally wound my grandfather. * When you try to force two objects to occupy the same space at the same time (by pushing really hard), you simply cannot do this. The objects will break long before you'll be able to have them occupy the same space. * When you try to bring two very strong magnets (with the same polarity) together, they will not allow you to do that. Whenever you bring them close, the magnetic force tends to make you veer off. * If you use **tremendous** force, you can bring the magnets together, as long as this tremendous force is (1) bigger than the magnetic repulsion force, (2) smaller than the force needed for the magnets to break and (3) continuously applied. Therefore, if I try to stab my grandfather, the universe will make my sword veer off course, missing my grandfather. As much as I try to stab him, the universe will provide a counterforce. Just like how a magnet uses force to repel a magnet of the same polarity, the universe will use a force to repel the action that **invariably** introduces a paradox. Suppose I don't intend to lethally wound my grandfather, I only stab him on the hand. Then the universe has several options to deal with this: * If this wound does not change my grandfather's future (he will still end up having my father, my father will still end up having me), then the universe **allows** it. There is no paradox. * If this wound precludes my grandfather from having my father (e.g. his injury makes him use his other hand, therefore not spilling the drink that he's supposed to spill on my grandmother when he is supposed to meet her), then the paradox should be **equally disallowed** (similar to when I try to lethally wound my grandfather). Note that I mentioned how the universe favors **the path of least resistance**. Since the universe is "inventing" a force that would make my sword veer off course, that requires X amount of force. But if the universe has a way to avoid the paradox using less force (less than X), then it will favor this alternate route. If the force needed to veer the sword off course is greater than the force needed to knock over that drink and spill it on my grandmother (thus introducing my grandparents, even if he wasn't the one who spilled the drink), then the paradox can be resolved this way and the universe will favor knocking over the glass as it is the path of least resistance. **This is consistent with Back To The Future**. * Marty mistakenly intervenes in how his parents fell in love, thus endangering his future. However, the universe has allowed this to happen, as no (unavoidable) paradox has yet been created. * Marty does start fading away at the end of the movie, because the paradox is getting closer and closer to becoming **unavoidable**. For example, if Marty took several years to get his parents to fall in love, then they probably would have had Marty at a later stage in life (thus creating a paradox). * However, so long as Marty's parents are still able to fall in love, on time to give birth to Marty at the right time, the universe has not yet deleted Marty, as he is still **possible**. * Marty ends up fixing the problem by getting them to fall in love in a different way. Marty has changed the past, but in a way that **the future is unaffected**. Changes have been introduced, but no paradox, and therefore the universe does not intervene. This is the same as the drink that gets spilt on my grandmother. Both the spilt drink and Marty's parents falling in love **invariably** leads to my grandparents giving birth to my father, and Marty's parents giving birth to Marty. *Minor note: In my example, the glass gets knocked over by the universe. In BTTF, Marty is the driving force behind the correction. However, it's possible to argue that the universe helped Marty along in order to achieve his goal (e.g. making him run faster just so he gets to his destination on time, if being late causes the paradox to become unavoidable). This possibility only applies if helping Marty costs less effort than the universe fixing it by itself.* **This is also consistent with Doctor Who**. * In the episode where they are trapped inside a dying TARDIS, the Doctor, Clara and three guests are being chased by monsters (who look like burnt zombies). * It is revealed that these burnt zombies are actually **future Clara and the future guests**, who have been burnt by the TARDIS' main reactor. * Two zombies are attached to eachother. The Doctor realizes that these are the two remaining guests (the third one was already dead). * The Doctor tells the alive guests to **never touch eachother again**, because not touching eachother makes it impossible for them to fuse together, thus creating a paradox (the Doctor **wants** to create a paradox here). * As long as they never touch, their future selves (the merged zombie) is **impossible**. And if it is impossible, then the universe should delete that future (similar to how Marty fades once he becomes an impossible future). * This works for a while, and the future seems to be rewritten. However, the guests forget about not touching eachother, and touch eachother. **As if by force**, they are **immediately** joined together and burnt, becoming the burnt zombies. This force was supplied by the universe. Rather than deleting the future zombies (which takes a lot of effort to rewrite the future), the universe favors **bumping the two guests together**, as this requires less force and it ensures that the future is actually correct and therefore does not need to be deleted. Note that **Clara** has managed to avoid her burnt future. Because the guests have managed to *stall* the inevitable (touching eachother) long enough, they have changed the future enough to delete burnt Clara (as she is no longer possible), but they did not stall long enough for their **own** futures to be rewritten. I can't speak to Looper, as I haven't seen it. Conclusion ---------- **That's proof of how it should work, according to me.** We've seen both cases: trying to prevent changes to the future (BTTF) and trying to create changes to the future (Doctor Who). In both cases, the universe applies the same rules: it maintained logical consistency at all costs, even if that means it has to invent a "phantom force" (which breaks the rules of the universe, specifically [the first law of thermodynamics](https://en.wikipedia.org/wiki/First_law_of_thermodynamics)). In order to **minimize** how much it breaks its own rules, the universe tries to apply the least amount of "phantom force" (= the path of least resistance).
This is a variation of Flater's answer about the universe "preventing" the paradox. At first I was going to comment that it requires a sort of "God" or "Deus Ex Machina" to intervene on behalf of the plot. But think of it slightly differently: Quantum physics tells us that there is an inherent randomness in the universe. Maybe someone with more knowledge of it can explain it better, but essentially each action and object is actually the average of zillions of probabilities. So while two things might appear identical, at a subatomic level they are completely different. Now at first glance, the Grandfather paradox is an infinite loop. But what if because of the quantum randomness, each iteration is actually different at a quantum level if not at a macro level. This means that there is an infinitesimal, but non-zero chance that you will fail to kill your grandfather. (Or fail to travel back in time) But with infinity, even the ridiculously improbable will eventually happen. So even if it takes a gazillion journeys through the time loop, one will eventually occur where you fail to kill your grandfather. And since this one does not prompt a recurrence of the loop, this is the one that will "stick". You'll forget all the iterations of the loop that have been replaced by this one. This will only happen with paradoxes of course, because if there isn't a paradox there isn't an infinite time loop. Because it's a *time* loop, all occurrences of the loop happen at the same time so you don't notice the bazillions of epochs that the loop has been through. So it will appear that the universe or some power does intervene to prevent paradoxes.
15,539
There are many movies and TV episodes in which a character "crosses his own timeline", sometimes even meeting his past or future self (e.g. *The Day of the Doctor*). Technically, I should say meeting his past self *and* meeting his future self, I suppose, since this is actually what happens. When they supposedly alter their own future resulting in their never having travelled in time (as in *Back to The Future* or *Looper*), or narrowly avoid doing so, this is known as the "grandfather paradox". How are we, the audience, supposed to make sense of this, if we actually think it through logically? If you perform an action which has an effect that you never survived or were never ever born, then how did you travel in time in the first place? (Although it's not really "in the first place", if you travelled backwards in time...) I know that there is some quantum mechanics theory relevant to this but the average cinema-goer doesn't know about all that stuff, surely...
2013/12/01
[ "https://movies.stackexchange.com/questions/15539", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/729/" ]
This is a variation of Flater's answer about the universe "preventing" the paradox. At first I was going to comment that it requires a sort of "God" or "Deus Ex Machina" to intervene on behalf of the plot. But think of it slightly differently: Quantum physics tells us that there is an inherent randomness in the universe. Maybe someone with more knowledge of it can explain it better, but essentially each action and object is actually the average of zillions of probabilities. So while two things might appear identical, at a subatomic level they are completely different. Now at first glance, the Grandfather paradox is an infinite loop. But what if because of the quantum randomness, each iteration is actually different at a quantum level if not at a macro level. This means that there is an infinitesimal, but non-zero chance that you will fail to kill your grandfather. (Or fail to travel back in time) But with infinity, even the ridiculously improbable will eventually happen. So even if it takes a gazillion journeys through the time loop, one will eventually occur where you fail to kill your grandfather. And since this one does not prompt a recurrence of the loop, this is the one that will "stick". You'll forget all the iterations of the loop that have been replaced by this one. This will only happen with paradoxes of course, because if there isn't a paradox there isn't an infinite time loop. Because it's a *time* loop, all occurrences of the loop happen at the same time so you don't notice the bazillions of epochs that the loop has been through. So it will appear that the universe or some power does intervene to prevent paradoxes.
If the time travel is branching, then it needs no explanation, but if it's linear, then I'd imagine it's because time travelling protected them? For example, and I hope this is not just in the CW show, the Reverse Flash, mortal enemy of the Flash (I hope you could've figured that one out on your own), is able to basically exist in every time period because the Speed Force protects him and there's versions of him... everywhen? But Marty began to disappear in BTTF, whereas Reverse Flash isn't affected at all in his time travelling. Different worlds have different rules so it depends on the specific universe.
37,876,455
I want to build an application that will receive user-defined Strings of unknown size and identify them as either being simple Strings or dates. What I want to do is to find a way to extract the date pattern of the String **without** knowing if the String that the program will receive will actually be a date. More precisely, if the String that will be received is going to be ``` "2014-05-07_0533" //valid date ``` the program will return ``` "yyyy-MM-dd_HHmm" ``` But if the String that is going to be received is ``` "2014-05_667788" //not a valid date ``` the program will raise an Exception or otherwise inform the user that the supplied String does not follow a known date pattern, thus it's not a date. One way that I can think of implementing the previous problem is declaring a predefined `List` of available date patterns which the program will accept and then exhaustively trying to match the supplied String with each one of these patterns. When there is a match, the program will return the matched pattern. If none of the available patterns are matched, `null` or a message will be returned. The problem with the above thought is that the Strings that the program will receive are going to be scaled up to tens or hundreds of thousands, so I'm starting to think that this method will have significant impact on the application's speed and overall memory footprint. Is there a better solution? **EDIT** There is no code so far, as I am in the early stages of development and I'm just running some ideas on how to implement it. **EDIT2** For those of you who request a code sample, this is what I have thought so far: ``` public class DateMatching { public List<String> datePatterns = new ArrayList<>(); public DateMatching() { initializePatterns(); } private void initializePatterns() { datePatterns.add("yyyy-MM-dd_HH:mm"); datePatterns.add("yyyy/MM/dd_HH:mm"); datePatterns.add("yyyy.MM.dd_HH:mm"); //and so on... } public final String getDatePattern(String supplied) { DateFormat format; for(String datePattern : datePatterns) { format = new SimpleDateFormat(datePattern); try { format.parse(supplied); return datePattern; } catch(ParseException e) { continue; } } return null; //No matched pattern } } ``` As the `datePatterns` list could contain up to 50 or more patterns and the Strings that the application will receive may be more than tens or hundreds of thousands, I'm trying to find a way to reduce the amount of time the matching process will require for all these Strings -assuming that there is one, to begin with.
2016/06/17
[ "https://Stackoverflow.com/questions/37876455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1860791/" ]
10s of thousands is not a huge amount. I would just try to parse it and catch exceptions: ``` private static final DateTimeFormatter FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmm"); public static boolean isValidDate(String input) { try { FMT.parse(input); return true; } catch (DateTimeParseException e) { return false; } } ``` Running the method 10,000 times takes less than 100 ms on my machine (without even allowing the JVM to warmup etc.).
As the others have suggested, there is no way of implementing what I'm asking for. The application needs to know what are the patterns that is going to seek in the received String, ab initio; it cannot just magically guess that a String is a date without the prior knowledge of how a date is actually assembled. So, I will declare a `List` of predefined date patterns and every time a String arrives, I will try to match it against the aforementioned `List`. I am closing the issue, thanks for all the answers!
37,364
I have to reverse the string "He is the one" to "one the is He". I have written some programs in Java but am looking for other best solutions. Suggest any possible ways to minimize the current program. First approach: ``` class StringRev{ public static void main(String args[]){ String str = "He is the one"; String temp = ""; String finalString = ""; for(int i =str.length()-1;i>=0;i--){ temp +=i!=0?str.charAt(i):str.charAt(i)+" "; if(str.charAt(i) == ' '||i==0){ for(int j=temp.length()-1;j>=0;j--){ finalString += temp.charAt(j); } temp = ""; } } System.out.println(finalString); } } ``` Second approach: ``` class StringRev2{ public static void main(String args[]){ String str[] = "He is the one".split(" "); String finalStr=""; for(int i = str.length-1; i>= 0 ;i--){ finalStr += str[i]+" "; } System.out.println(finalStr); } } ```
2013/12/14
[ "https://codereview.stackexchange.com/questions/37364", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33463/" ]
"Minimize" is a really bad word to use when trying to consider the quality of your code. It's vague, and it can lead to undesirable outcomes, such as broken or unusable code. For example, is your goal to minimize the number of bytes used storing the source code on a hard drive? That might have been important when paper tape was a popular storage medium, but it's irrelevant today. It's so irrelevant that the difference between these two files is less than the size of a sector, so both actually occupy the same amount of storage space. Is your goal to reduce the number of CPU cycles spent? Given that cell phones have 100MHz processors these days, you need to do more work to figure out if the effort you expend thinking about the problem will ever be made up for in efficiency experienced by your users. If this is run once or twice, efficiency simply is not important. On the other hand, if it could ever become part of a networking protocol, efficiency is extremely important. Quite honestly, English word reversal seems to be too specialized to fit the test of practicality for efficiency. In general, what most people should be striving for in their code is "correctness" and "clarity". You want to know that it works correctly in all situations. The answer to that is to write unit tests. For clarity, you want the code to be readable, understandable, and usable. Make sure you have chosen good names. Modularize the functions. For example, you should consider extracting the dependency on System.out.println, as outputting the string has nothing to do with reversing the string.
There are many ways to do this, depending on what you're going for. If you're stuck with Java, then probably look to Apache commons: ``` StringUtils.reverseDelimited(st, ' '); ``` Try using Scala if you can, which is nicer in so many ways: ``` st.split(" ").reverse.mkString(" ") ```
37,364
I have to reverse the string "He is the one" to "one the is He". I have written some programs in Java but am looking for other best solutions. Suggest any possible ways to minimize the current program. First approach: ``` class StringRev{ public static void main(String args[]){ String str = "He is the one"; String temp = ""; String finalString = ""; for(int i =str.length()-1;i>=0;i--){ temp +=i!=0?str.charAt(i):str.charAt(i)+" "; if(str.charAt(i) == ' '||i==0){ for(int j=temp.length()-1;j>=0;j--){ finalString += temp.charAt(j); } temp = ""; } } System.out.println(finalString); } } ``` Second approach: ``` class StringRev2{ public static void main(String args[]){ String str[] = "He is the one".split(" "); String finalStr=""; for(int i = str.length-1; i>= 0 ;i--){ finalStr += str[i]+" "; } System.out.println(finalStr); } } ```
2013/12/14
[ "https://codereview.stackexchange.com/questions/37364", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33463/" ]
In your first approach you have the right idea of starting at the end of the String and working backwards. The issues you have are: * you should use StringBuilder instead of String concatenation.... * using a `temp` string which you add-to in reverse order, then reverse again in to the result is a slow approach .... but effective. * you should be doing it more than 1 character at a time. In your second approach, I don't like: * you have string concatenation again **use** a `StringBuilder()` * you assume all spaces are 'equal'... what about multi-space breaks `"Hello There"` with this code will become `"There Hello"` So, with a small adjustment to your regular expression (perhaps `"\\b"` ...) and conversion to StringBuilder, I think the second option is good. The first option, if written right, will be faster than the split one (although the code is longer).... Here's an attempt at doing it by first principles: ``` private static String reverse(String string) { if (string.isEmpty()) { return string; } int last = string.length(); StringBuilder sb = new StringBuilder(string.length()); boolean contextspace = ' ' == string.charAt(string.length() - 1); for (int i = string.length() - 1; i >= 0; i--) { if (contextspace != (string.charAt(i) == ' ')) { sb.append(string.substring(i + 1, last)); last = i + 1; contextspace = !contextspace; } } sb.append(string.substring(0, last)); return sb.toString(); } ```
**Approach 1:** JDK provides `java.util.StringTokenizer` to do the split or tokenizing a given text. This API helps avoid going character by character. No external jar/libraries required. Tokenizing gives you each separated word as an array element that you could print in reverse. ``` import java.util.ArrayList; import java.util.StringTokenizer; public class reverseString { public static void main(String args[]) { StringTokenizer st = new StringTokenizer("this is a string"); ArrayList<String> arrLstStrings = new ArrayList<>(); while (st.hasMoreTokens()) { arrLstStrings.add(st.nextToken()); } for(int loop=arrLstStrings.size()-1;loop>=0;loop--) System.out.println(arrLstStrings.get(loop)); } } ``` **Approach 2:** ``` import java.util.regex.*; public class reverseString { public static void main(String args[]) { String strSource = "This is a string"; // give a max int as limit in next stmt. String[] tokens = Pattern.compile(" ").split(strSource,15) ; for (int loop=tokens.length-1;loop>=0;loop--) System.out.println(tokens[loop]); } } ```
37,364
I have to reverse the string "He is the one" to "one the is He". I have written some programs in Java but am looking for other best solutions. Suggest any possible ways to minimize the current program. First approach: ``` class StringRev{ public static void main(String args[]){ String str = "He is the one"; String temp = ""; String finalString = ""; for(int i =str.length()-1;i>=0;i--){ temp +=i!=0?str.charAt(i):str.charAt(i)+" "; if(str.charAt(i) == ' '||i==0){ for(int j=temp.length()-1;j>=0;j--){ finalString += temp.charAt(j); } temp = ""; } } System.out.println(finalString); } } ``` Second approach: ``` class StringRev2{ public static void main(String args[]){ String str[] = "He is the one".split(" "); String finalStr=""; for(int i = str.length-1; i>= 0 ;i--){ finalStr += str[i]+" "; } System.out.println(finalStr); } } ```
2013/12/14
[ "https://codereview.stackexchange.com/questions/37364", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33463/" ]
"Minimize" is a really bad word to use when trying to consider the quality of your code. It's vague, and it can lead to undesirable outcomes, such as broken or unusable code. For example, is your goal to minimize the number of bytes used storing the source code on a hard drive? That might have been important when paper tape was a popular storage medium, but it's irrelevant today. It's so irrelevant that the difference between these two files is less than the size of a sector, so both actually occupy the same amount of storage space. Is your goal to reduce the number of CPU cycles spent? Given that cell phones have 100MHz processors these days, you need to do more work to figure out if the effort you expend thinking about the problem will ever be made up for in efficiency experienced by your users. If this is run once or twice, efficiency simply is not important. On the other hand, if it could ever become part of a networking protocol, efficiency is extremely important. Quite honestly, English word reversal seems to be too specialized to fit the test of practicality for efficiency. In general, what most people should be striving for in their code is "correctness" and "clarity". You want to know that it works correctly in all situations. The answer to that is to write unit tests. For clarity, you want the code to be readable, understandable, and usable. Make sure you have chosen good names. Modularize the functions. For example, you should consider extracting the dependency on System.out.println, as outputting the string has nothing to do with reversing the string.
In your first approach you have the right idea of starting at the end of the String and working backwards. The issues you have are: * you should use StringBuilder instead of String concatenation.... * using a `temp` string which you add-to in reverse order, then reverse again in to the result is a slow approach .... but effective. * you should be doing it more than 1 character at a time. In your second approach, I don't like: * you have string concatenation again **use** a `StringBuilder()` * you assume all spaces are 'equal'... what about multi-space breaks `"Hello There"` with this code will become `"There Hello"` So, with a small adjustment to your regular expression (perhaps `"\\b"` ...) and conversion to StringBuilder, I think the second option is good. The first option, if written right, will be faster than the split one (although the code is longer).... Here's an attempt at doing it by first principles: ``` private static String reverse(String string) { if (string.isEmpty()) { return string; } int last = string.length(); StringBuilder sb = new StringBuilder(string.length()); boolean contextspace = ' ' == string.charAt(string.length() - 1); for (int i = string.length() - 1; i >= 0; i--) { if (contextspace != (string.charAt(i) == ' ')) { sb.append(string.substring(i + 1, last)); last = i + 1; contextspace = !contextspace; } } sb.append(string.substring(0, last)); return sb.toString(); } ```
37,364
I have to reverse the string "He is the one" to "one the is He". I have written some programs in Java but am looking for other best solutions. Suggest any possible ways to minimize the current program. First approach: ``` class StringRev{ public static void main(String args[]){ String str = "He is the one"; String temp = ""; String finalString = ""; for(int i =str.length()-1;i>=0;i--){ temp +=i!=0?str.charAt(i):str.charAt(i)+" "; if(str.charAt(i) == ' '||i==0){ for(int j=temp.length()-1;j>=0;j--){ finalString += temp.charAt(j); } temp = ""; } } System.out.println(finalString); } } ``` Second approach: ``` class StringRev2{ public static void main(String args[]){ String str[] = "He is the one".split(" "); String finalStr=""; for(int i = str.length-1; i>= 0 ;i--){ finalStr += str[i]+" "; } System.out.println(finalStr); } } ```
2013/12/14
[ "https://codereview.stackexchange.com/questions/37364", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33463/" ]
Re-use existing code. --------------------- Libraries allow for maximum re-use. Use them! If you don't like libraries, try to re-use as much as Java offers. Look up documentation, examples, etc. * Splitting strings is java default `split()` * Reversing can be done with the excellent `Collections` class * Java8 has some nice String join stuff. I also try to make the code as readable as possible by having short statements and avoiding loops (for, while, etc) when you don't need them. My approach: ``` public static String reverseWords (String s) { String delimiter = " "; List<String> words = Arrays.asList(s.split(delimiter)); Collections.reverse(words); return String.join(delimiter, words); } public static void main(String[] args) { System.out.println(reverseWords("He is the one")); } ```
Here is a clean approach to reverse a string by its parts: ``` public class Main { // ReverseParts: reverses a string by words as opposed to characters. public static String ReverseParts(String input, String splitBy, String joinBy) { StringBuilder built = new StringBuilder(); // Note: String.split uses regex. See its definition String[] list = input.split(splitBy); // Rejoin all the characters into a StringBuilder. for ( String part: list ) { built.insert(0, part); built.insert(0, joinBy); } // Remove the unnecessary 'joinBy bit'. built.delete(0, 1); // Get back the final string. return built.toString(); } public static void main(String[] args) { final String input = "Hello Johnny's World!"; System.out.println("Result: '" + ReverseParts(input, " +", " ")+"'"); // Output: // Result: 'World! Johnny's Hello' } } ```
37,364
I have to reverse the string "He is the one" to "one the is He". I have written some programs in Java but am looking for other best solutions. Suggest any possible ways to minimize the current program. First approach: ``` class StringRev{ public static void main(String args[]){ String str = "He is the one"; String temp = ""; String finalString = ""; for(int i =str.length()-1;i>=0;i--){ temp +=i!=0?str.charAt(i):str.charAt(i)+" "; if(str.charAt(i) == ' '||i==0){ for(int j=temp.length()-1;j>=0;j--){ finalString += temp.charAt(j); } temp = ""; } } System.out.println(finalString); } } ``` Second approach: ``` class StringRev2{ public static void main(String args[]){ String str[] = "He is the one".split(" "); String finalStr=""; for(int i = str.length-1; i>= 0 ;i--){ finalStr += str[i]+" "; } System.out.println(finalStr); } } ```
2013/12/14
[ "https://codereview.stackexchange.com/questions/37364", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33463/" ]
In your first approach you have the right idea of starting at the end of the String and working backwards. The issues you have are: * you should use StringBuilder instead of String concatenation.... * using a `temp` string which you add-to in reverse order, then reverse again in to the result is a slow approach .... but effective. * you should be doing it more than 1 character at a time. In your second approach, I don't like: * you have string concatenation again **use** a `StringBuilder()` * you assume all spaces are 'equal'... what about multi-space breaks `"Hello There"` with this code will become `"There Hello"` So, with a small adjustment to your regular expression (perhaps `"\\b"` ...) and conversion to StringBuilder, I think the second option is good. The first option, if written right, will be faster than the split one (although the code is longer).... Here's an attempt at doing it by first principles: ``` private static String reverse(String string) { if (string.isEmpty()) { return string; } int last = string.length(); StringBuilder sb = new StringBuilder(string.length()); boolean contextspace = ' ' == string.charAt(string.length() - 1); for (int i = string.length() - 1; i >= 0; i--) { if (contextspace != (string.charAt(i) == ' ')) { sb.append(string.substring(i + 1, last)); last = i + 1; contextspace = !contextspace; } } sb.append(string.substring(0, last)); return sb.toString(); } ```
Here is a clean approach to reverse a string by its parts: ``` public class Main { // ReverseParts: reverses a string by words as opposed to characters. public static String ReverseParts(String input, String splitBy, String joinBy) { StringBuilder built = new StringBuilder(); // Note: String.split uses regex. See its definition String[] list = input.split(splitBy); // Rejoin all the characters into a StringBuilder. for ( String part: list ) { built.insert(0, part); built.insert(0, joinBy); } // Remove the unnecessary 'joinBy bit'. built.delete(0, 1); // Get back the final string. return built.toString(); } public static void main(String[] args) { final String input = "Hello Johnny's World!"; System.out.println("Result: '" + ReverseParts(input, " +", " ")+"'"); // Output: // Result: 'World! Johnny's Hello' } } ```
37,364
I have to reverse the string "He is the one" to "one the is He". I have written some programs in Java but am looking for other best solutions. Suggest any possible ways to minimize the current program. First approach: ``` class StringRev{ public static void main(String args[]){ String str = "He is the one"; String temp = ""; String finalString = ""; for(int i =str.length()-1;i>=0;i--){ temp +=i!=0?str.charAt(i):str.charAt(i)+" "; if(str.charAt(i) == ' '||i==0){ for(int j=temp.length()-1;j>=0;j--){ finalString += temp.charAt(j); } temp = ""; } } System.out.println(finalString); } } ``` Second approach: ``` class StringRev2{ public static void main(String args[]){ String str[] = "He is the one".split(" "); String finalStr=""; for(int i = str.length-1; i>= 0 ;i--){ finalStr += str[i]+" "; } System.out.println(finalStr); } } ```
2013/12/14
[ "https://codereview.stackexchange.com/questions/37364", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33463/" ]
There are many ways to do this, depending on what you're going for. If you're stuck with Java, then probably look to Apache commons: ``` StringUtils.reverseDelimited(st, ' '); ``` Try using Scala if you can, which is nicer in so many ways: ``` st.split(" ").reverse.mkString(" ") ```
Here is a clean approach to reverse a string by its parts: ``` public class Main { // ReverseParts: reverses a string by words as opposed to characters. public static String ReverseParts(String input, String splitBy, String joinBy) { StringBuilder built = new StringBuilder(); // Note: String.split uses regex. See its definition String[] list = input.split(splitBy); // Rejoin all the characters into a StringBuilder. for ( String part: list ) { built.insert(0, part); built.insert(0, joinBy); } // Remove the unnecessary 'joinBy bit'. built.delete(0, 1); // Get back the final string. return built.toString(); } public static void main(String[] args) { final String input = "Hello Johnny's World!"; System.out.println("Result: '" + ReverseParts(input, " +", " ")+"'"); // Output: // Result: 'World! Johnny's Hello' } } ```
37,364
I have to reverse the string "He is the one" to "one the is He". I have written some programs in Java but am looking for other best solutions. Suggest any possible ways to minimize the current program. First approach: ``` class StringRev{ public static void main(String args[]){ String str = "He is the one"; String temp = ""; String finalString = ""; for(int i =str.length()-1;i>=0;i--){ temp +=i!=0?str.charAt(i):str.charAt(i)+" "; if(str.charAt(i) == ' '||i==0){ for(int j=temp.length()-1;j>=0;j--){ finalString += temp.charAt(j); } temp = ""; } } System.out.println(finalString); } } ``` Second approach: ``` class StringRev2{ public static void main(String args[]){ String str[] = "He is the one".split(" "); String finalStr=""; for(int i = str.length-1; i>= 0 ;i--){ finalStr += str[i]+" "; } System.out.println(finalStr); } } ```
2013/12/14
[ "https://codereview.stackexchange.com/questions/37364", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33463/" ]
Stuffing all your code into `main()` is bad practice. This functionality belongs in a function of its own. When doing multiple string concatenations, you really want to use a `StringBuilder`. If you don't, the compiler will make one for you anyway, *every time you concatenate two strings using +*. It's better to do it explicitly, then, and control how many of those temporary objects are created. --- Your first approach works a character at a time. I suggest the following character-at-a-time approach, which allocates just one large temporary buffer. ``` private static void reverse(char[] buf, int start, int end) { for (int i = start, j = end - 1; i < j; i++, j--) { char swap = buf[i]; buf[i] = buf[j]; buf[j] = swap; } } public static String reverseWords1(String sentence) { char[] buf = sentence.toCharArray(); // Reverse the string, character-wise reverse(buf, 0, buf.length); // Within each word, reverse the characters again int wordEnd = 0; for (int wordStart = 0; wordStart < buf.length; wordStart = wordEnd + 1) { for (wordEnd = wordStart; wordEnd < buf.length && buf[wordEnd] != ' '; wordEnd++) {} // wordStart is at the start of a word. // wordEnd is just past the end of the word. reverse(buf, wordStart, wordEnd); } return new String(buf); } ``` --- I prefer your second approach, which is more succinct. Here it is, cleaned up by using a `StringBuilder`. ``` public static String reverseWords2(String sentence) { StringBuilder sb = new StringBuilder(sentence.length() + 1); String[] words = sentence.split(" "); for (int i = words.length - 1; i >= 0; i--) { sb.append(words[i]).append(' '); } sb.setLength(sb.length() - 1); // Strip trailing space return sb.toString(); } ```
Here is a clean approach to reverse a string by its parts: ``` public class Main { // ReverseParts: reverses a string by words as opposed to characters. public static String ReverseParts(String input, String splitBy, String joinBy) { StringBuilder built = new StringBuilder(); // Note: String.split uses regex. See its definition String[] list = input.split(splitBy); // Rejoin all the characters into a StringBuilder. for ( String part: list ) { built.insert(0, part); built.insert(0, joinBy); } // Remove the unnecessary 'joinBy bit'. built.delete(0, 1); // Get back the final string. return built.toString(); } public static void main(String[] args) { final String input = "Hello Johnny's World!"; System.out.println("Result: '" + ReverseParts(input, " +", " ")+"'"); // Output: // Result: 'World! Johnny's Hello' } } ```
37,364
I have to reverse the string "He is the one" to "one the is He". I have written some programs in Java but am looking for other best solutions. Suggest any possible ways to minimize the current program. First approach: ``` class StringRev{ public static void main(String args[]){ String str = "He is the one"; String temp = ""; String finalString = ""; for(int i =str.length()-1;i>=0;i--){ temp +=i!=0?str.charAt(i):str.charAt(i)+" "; if(str.charAt(i) == ' '||i==0){ for(int j=temp.length()-1;j>=0;j--){ finalString += temp.charAt(j); } temp = ""; } } System.out.println(finalString); } } ``` Second approach: ``` class StringRev2{ public static void main(String args[]){ String str[] = "He is the one".split(" "); String finalStr=""; for(int i = str.length-1; i>= 0 ;i--){ finalStr += str[i]+" "; } System.out.println(finalStr); } } ```
2013/12/14
[ "https://codereview.stackexchange.com/questions/37364", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33463/" ]
Here is a clean approach to reverse a string by its parts: ``` public class Main { // ReverseParts: reverses a string by words as opposed to characters. public static String ReverseParts(String input, String splitBy, String joinBy) { StringBuilder built = new StringBuilder(); // Note: String.split uses regex. See its definition String[] list = input.split(splitBy); // Rejoin all the characters into a StringBuilder. for ( String part: list ) { built.insert(0, part); built.insert(0, joinBy); } // Remove the unnecessary 'joinBy bit'. built.delete(0, 1); // Get back the final string. return built.toString(); } public static void main(String[] args) { final String input = "Hello Johnny's World!"; System.out.println("Result: '" + ReverseParts(input, " +", " ")+"'"); // Output: // Result: 'World! Johnny's Hello' } } ```
**Approach 1:** JDK provides `java.util.StringTokenizer` to do the split or tokenizing a given text. This API helps avoid going character by character. No external jar/libraries required. Tokenizing gives you each separated word as an array element that you could print in reverse. ``` import java.util.ArrayList; import java.util.StringTokenizer; public class reverseString { public static void main(String args[]) { StringTokenizer st = new StringTokenizer("this is a string"); ArrayList<String> arrLstStrings = new ArrayList<>(); while (st.hasMoreTokens()) { arrLstStrings.add(st.nextToken()); } for(int loop=arrLstStrings.size()-1;loop>=0;loop--) System.out.println(arrLstStrings.get(loop)); } } ``` **Approach 2:** ``` import java.util.regex.*; public class reverseString { public static void main(String args[]) { String strSource = "This is a string"; // give a max int as limit in next stmt. String[] tokens = Pattern.compile(" ").split(strSource,15) ; for (int loop=tokens.length-1;loop>=0;loop--) System.out.println(tokens[loop]); } } ```
37,364
I have to reverse the string "He is the one" to "one the is He". I have written some programs in Java but am looking for other best solutions. Suggest any possible ways to minimize the current program. First approach: ``` class StringRev{ public static void main(String args[]){ String str = "He is the one"; String temp = ""; String finalString = ""; for(int i =str.length()-1;i>=0;i--){ temp +=i!=0?str.charAt(i):str.charAt(i)+" "; if(str.charAt(i) == ' '||i==0){ for(int j=temp.length()-1;j>=0;j--){ finalString += temp.charAt(j); } temp = ""; } } System.out.println(finalString); } } ``` Second approach: ``` class StringRev2{ public static void main(String args[]){ String str[] = "He is the one".split(" "); String finalStr=""; for(int i = str.length-1; i>= 0 ;i--){ finalStr += str[i]+" "; } System.out.println(finalStr); } } ```
2013/12/14
[ "https://codereview.stackexchange.com/questions/37364", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33463/" ]
"Minimize" is a really bad word to use when trying to consider the quality of your code. It's vague, and it can lead to undesirable outcomes, such as broken or unusable code. For example, is your goal to minimize the number of bytes used storing the source code on a hard drive? That might have been important when paper tape was a popular storage medium, but it's irrelevant today. It's so irrelevant that the difference between these two files is less than the size of a sector, so both actually occupy the same amount of storage space. Is your goal to reduce the number of CPU cycles spent? Given that cell phones have 100MHz processors these days, you need to do more work to figure out if the effort you expend thinking about the problem will ever be made up for in efficiency experienced by your users. If this is run once or twice, efficiency simply is not important. On the other hand, if it could ever become part of a networking protocol, efficiency is extremely important. Quite honestly, English word reversal seems to be too specialized to fit the test of practicality for efficiency. In general, what most people should be striving for in their code is "correctness" and "clarity". You want to know that it works correctly in all situations. The answer to that is to write unit tests. For clarity, you want the code to be readable, understandable, and usable. Make sure you have chosen good names. Modularize the functions. For example, you should consider extracting the dependency on System.out.println, as outputting the string has nothing to do with reversing the string.
Here is a clean approach to reverse a string by its parts: ``` public class Main { // ReverseParts: reverses a string by words as opposed to characters. public static String ReverseParts(String input, String splitBy, String joinBy) { StringBuilder built = new StringBuilder(); // Note: String.split uses regex. See its definition String[] list = input.split(splitBy); // Rejoin all the characters into a StringBuilder. for ( String part: list ) { built.insert(0, part); built.insert(0, joinBy); } // Remove the unnecessary 'joinBy bit'. built.delete(0, 1); // Get back the final string. return built.toString(); } public static void main(String[] args) { final String input = "Hello Johnny's World!"; System.out.println("Result: '" + ReverseParts(input, " +", " ")+"'"); // Output: // Result: 'World! Johnny's Hello' } } ```
37,364
I have to reverse the string "He is the one" to "one the is He". I have written some programs in Java but am looking for other best solutions. Suggest any possible ways to minimize the current program. First approach: ``` class StringRev{ public static void main(String args[]){ String str = "He is the one"; String temp = ""; String finalString = ""; for(int i =str.length()-1;i>=0;i--){ temp +=i!=0?str.charAt(i):str.charAt(i)+" "; if(str.charAt(i) == ' '||i==0){ for(int j=temp.length()-1;j>=0;j--){ finalString += temp.charAt(j); } temp = ""; } } System.out.println(finalString); } } ``` Second approach: ``` class StringRev2{ public static void main(String args[]){ String str[] = "He is the one".split(" "); String finalStr=""; for(int i = str.length-1; i>= 0 ;i--){ finalStr += str[i]+" "; } System.out.println(finalStr); } } ```
2013/12/14
[ "https://codereview.stackexchange.com/questions/37364", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/33463/" ]
In your first approach you have the right idea of starting at the end of the String and working backwards. The issues you have are: * you should use StringBuilder instead of String concatenation.... * using a `temp` string which you add-to in reverse order, then reverse again in to the result is a slow approach .... but effective. * you should be doing it more than 1 character at a time. In your second approach, I don't like: * you have string concatenation again **use** a `StringBuilder()` * you assume all spaces are 'equal'... what about multi-space breaks `"Hello There"` with this code will become `"There Hello"` So, with a small adjustment to your regular expression (perhaps `"\\b"` ...) and conversion to StringBuilder, I think the second option is good. The first option, if written right, will be faster than the split one (although the code is longer).... Here's an attempt at doing it by first principles: ``` private static String reverse(String string) { if (string.isEmpty()) { return string; } int last = string.length(); StringBuilder sb = new StringBuilder(string.length()); boolean contextspace = ' ' == string.charAt(string.length() - 1); for (int i = string.length() - 1; i >= 0; i--) { if (contextspace != (string.charAt(i) == ' ')) { sb.append(string.substring(i + 1, last)); last = i + 1; contextspace = !contextspace; } } sb.append(string.substring(0, last)); return sb.toString(); } ```
Re-use existing code. --------------------- Libraries allow for maximum re-use. Use them! If you don't like libraries, try to re-use as much as Java offers. Look up documentation, examples, etc. * Splitting strings is java default `split()` * Reversing can be done with the excellent `Collections` class * Java8 has some nice String join stuff. I also try to make the code as readable as possible by having short statements and avoiding loops (for, while, etc) when you don't need them. My approach: ``` public static String reverseWords (String s) { String delimiter = " "; List<String> words = Arrays.asList(s.split(delimiter)); Collections.reverse(words); return String.join(delimiter, words); } public static void main(String[] args) { System.out.println(reverseWords("He is the one")); } ```
50,941
In this sentence: 做乜唔叫埋我? What is the function of 埋? I understood this sentence to be: "why didn't you call me?" (perhaps to an outing or a party). What is the difference with the sentence "做乜唔叫我"? Insights please.
2022/04/12
[ "https://chinese.stackexchange.com/questions/50941", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/20355/" ]
1. [V + **埋**] = [**也** + V] = [V + **too**] Example: * 叫**埋**佢去 = **也**叫他去 = ask him to go **too** * 殺**埋**佢隻狗 = **也**殺了他的狗 = kill his dog **too** * 連你都打**埋** = 連你**也一起**打 = beat even you **too** 2. [V + 埋] = [V + 完] = [finish + V] Example: * 執**埋**啲手尾 = 辦**完**那些收尾工作 = **finish** those finishing work * 計**埋**條數就走 = 計算**完**那筆賬就走 = leave after **finish** calculating the account * 食**埋**飯先至睇電視 = 吃**完**飯才看電視 = watch T.V. only after **finish** eating dinner 3. [V + 埋] = [V + result particle that means 'conceal' Example: * 收**埋**你把手槍 = 收**起**你的手槍 = put away (**and conceal**) your handgun * 快啲匿**埋** = 快些躲**起來** = hurry up and hide (**and conceal yourself**) 4. [V + 埋] = [V + 貼/ 近] = [V + close] Example: * 企**埋啲** = 站**近些** = stand **closer** * 閂**埋**門打仔 = 關**上**門打兒子 = close the door (**shut**) and beat the son To answer your question: > > 做乜唔叫**埋**我? = 為什麼不**也一起**叫我? (Why not call me **too**?) > > > > > "做乜唔叫我"? = 為什麼不叫我? (Why not call me?) > > >
做乜唔叫埋我? What is the function of 埋? First the sentence reads as:- 做乜 = why, (for what reason) 唔叫 = didn't call, (didn't include) 埋我? = me as well? The function of 埋 in this context of Cantonese speech is not "bury" but to mean "as well" So, 埋我 means "me as well" Of course in Cantonese 埋 also means "bury" in some other context. Another example of 埋 is 請埋位食饭 = please take a seat for (food, dinner, etc), where 埋位 means "take a seat", and not "bury a seat" in this context. From these basic examples, it could be seen that 埋 has multifarious usages in Cantonese speech, and only the context would ferret out the applicable meanings and usages. Finally, Quote:- "What is the difference with the sentence "做乜唔叫我"?" The "difference" between 做乜唔叫埋我? and 做乜唔叫我? is the "tone", meaning the intention behind the question. In 做乜唔叫我?, it is more a straight forward, neutral inquiry. In 做乜唔叫埋我?, the 埋我, "as well", has an "accusative" element, a certain covert unhappiness of "being left out" This accusative element could also be implied in the equivalent English sentences -- "Why didn't you call me"? and "Why didn't you call me as well"? This accusative element is more pronounced if 唔叫 is translated as "not include" rather than "not call" because in Cantonese 叫 in certain context does not always mean "call", (as in call someone on the phone)
50,941
In this sentence: 做乜唔叫埋我? What is the function of 埋? I understood this sentence to be: "why didn't you call me?" (perhaps to an outing or a party). What is the difference with the sentence "做乜唔叫我"? Insights please.
2022/04/12
[ "https://chinese.stackexchange.com/questions/50941", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/20355/" ]
1. [V + **埋**] = [**也** + V] = [V + **too**] Example: * 叫**埋**佢去 = **也**叫他去 = ask him to go **too** * 殺**埋**佢隻狗 = **也**殺了他的狗 = kill his dog **too** * 連你都打**埋** = 連你**也一起**打 = beat even you **too** 2. [V + 埋] = [V + 完] = [finish + V] Example: * 執**埋**啲手尾 = 辦**完**那些收尾工作 = **finish** those finishing work * 計**埋**條數就走 = 計算**完**那筆賬就走 = leave after **finish** calculating the account * 食**埋**飯先至睇電視 = 吃**完**飯才看電視 = watch T.V. only after **finish** eating dinner 3. [V + 埋] = [V + result particle that means 'conceal' Example: * 收**埋**你把手槍 = 收**起**你的手槍 = put away (**and conceal**) your handgun * 快啲匿**埋** = 快些躲**起來** = hurry up and hide (**and conceal yourself**) 4. [V + 埋] = [V + 貼/ 近] = [V + close] Example: * 企**埋啲** = 站**近些** = stand **closer** * 閂**埋**門打仔 = 關**上**門打兒子 = close the door (**shut**) and beat the son To answer your question: > > 做乜唔叫**埋**我? = 為什麼不**也一起**叫我? (Why not call me **too**?) > > > > > "做乜唔叫我"? = 為什麼不叫我? (Why not call me?) > > >
做乜唔叫我? => Why didn't (you) notify me? 做乜唔叫**埋**我? = 做乜唔預我? = 做乜唔邀請我? => Why didn't (you) **also** count me **in**? = Why was I kept out? = Why ain't I **also in**vited? In English, "**also** count (somebody) **in**" means "**in**vite (somebody) **too**", but "count (somebody)" alone has no such clear meaning. While both questions sounds accusing, 埋 emphasizes that at lease one person is included in an event yet the asker was kept out.
50,941
In this sentence: 做乜唔叫埋我? What is the function of 埋? I understood this sentence to be: "why didn't you call me?" (perhaps to an outing or a party). What is the difference with the sentence "做乜唔叫我"? Insights please.
2022/04/12
[ "https://chinese.stackexchange.com/questions/50941", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/20355/" ]
1. [V + **埋**] = [**也** + V] = [V + **too**] Example: * 叫**埋**佢去 = **也**叫他去 = ask him to go **too** * 殺**埋**佢隻狗 = **也**殺了他的狗 = kill his dog **too** * 連你都打**埋** = 連你**也一起**打 = beat even you **too** 2. [V + 埋] = [V + 完] = [finish + V] Example: * 執**埋**啲手尾 = 辦**完**那些收尾工作 = **finish** those finishing work * 計**埋**條數就走 = 計算**完**那筆賬就走 = leave after **finish** calculating the account * 食**埋**飯先至睇電視 = 吃**完**飯才看電視 = watch T.V. only after **finish** eating dinner 3. [V + 埋] = [V + result particle that means 'conceal' Example: * 收**埋**你把手槍 = 收**起**你的手槍 = put away (**and conceal**) your handgun * 快啲匿**埋** = 快些躲**起來** = hurry up and hide (**and conceal yourself**) 4. [V + 埋] = [V + 貼/ 近] = [V + close] Example: * 企**埋啲** = 站**近些** = stand **closer** * 閂**埋**門打仔 = 關**上**門打兒子 = close the door (**shut**) and beat the son To answer your question: > > 做乜唔叫**埋**我? = 為什麼不**也一起**叫我? (Why not call me **too**?) > > > > > "做乜唔叫我"? = 為什麼不叫我? (Why not call me?) > > >
As verbal suffix, 埋 can function as a verb complement with a lexical meaning somewhat like "close, tight". In this case, it can be used together with an adverb of degree (such as 好,太) and 咗. For example: 1. 唔好企太埋。(Don't stand too close.) 2. 佢关埋咗度门。(He has closed the door (tightly).) In a sentence like 做乜唔叫埋我?, 埋 functions as an aspect marker. In this case, it cannot be used together with an adverb of degree (such as 好,太) and 咗. And like many other aspect markers in Cantonese (e.g. 住,到,紧,亲...), 埋 "has lost" its lexical meaning through abstraction and become an aspect marker. The interpretation of the process where 埋 is used is a function of it's underlying value and the context. As an aspect marker, 埋 is used in contexts where we have a class of possible values constructed as fragmentable or dissociable. For example: 3. 唔准玩,做埋啲功课先。(You are not allowed to play. Finish your homework first.) 4. 今日下午我地踢波,叫埋阿民啦。(We are playing soccer this afternoon. Let Ah Min join us.) In (3), "homework" is constructed as a "fragmentable amount of work". You have already started, but there is still a fragment that remains to be done. In (4), there are a group of people who can play soccer together. 阿民 is singled out in the beginning as the one who may or may not play together. In these examples, 埋 serves to cancel the fragmentation and return the class as a whole.
50,941
In this sentence: 做乜唔叫埋我? What is the function of 埋? I understood this sentence to be: "why didn't you call me?" (perhaps to an outing or a party). What is the difference with the sentence "做乜唔叫我"? Insights please.
2022/04/12
[ "https://chinese.stackexchange.com/questions/50941", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/20355/" ]
做乜唔叫埋我? What is the function of 埋? First the sentence reads as:- 做乜 = why, (for what reason) 唔叫 = didn't call, (didn't include) 埋我? = me as well? The function of 埋 in this context of Cantonese speech is not "bury" but to mean "as well" So, 埋我 means "me as well" Of course in Cantonese 埋 also means "bury" in some other context. Another example of 埋 is 請埋位食饭 = please take a seat for (food, dinner, etc), where 埋位 means "take a seat", and not "bury a seat" in this context. From these basic examples, it could be seen that 埋 has multifarious usages in Cantonese speech, and only the context would ferret out the applicable meanings and usages. Finally, Quote:- "What is the difference with the sentence "做乜唔叫我"?" The "difference" between 做乜唔叫埋我? and 做乜唔叫我? is the "tone", meaning the intention behind the question. In 做乜唔叫我?, it is more a straight forward, neutral inquiry. In 做乜唔叫埋我?, the 埋我, "as well", has an "accusative" element, a certain covert unhappiness of "being left out" This accusative element could also be implied in the equivalent English sentences -- "Why didn't you call me"? and "Why didn't you call me as well"? This accusative element is more pronounced if 唔叫 is translated as "not include" rather than "not call" because in Cantonese 叫 in certain context does not always mean "call", (as in call someone on the phone)
做乜唔叫我? => Why didn't (you) notify me? 做乜唔叫**埋**我? = 做乜唔預我? = 做乜唔邀請我? => Why didn't (you) **also** count me **in**? = Why was I kept out? = Why ain't I **also in**vited? In English, "**also** count (somebody) **in**" means "**in**vite (somebody) **too**", but "count (somebody)" alone has no such clear meaning. While both questions sounds accusing, 埋 emphasizes that at lease one person is included in an event yet the asker was kept out.
50,941
In this sentence: 做乜唔叫埋我? What is the function of 埋? I understood this sentence to be: "why didn't you call me?" (perhaps to an outing or a party). What is the difference with the sentence "做乜唔叫我"? Insights please.
2022/04/12
[ "https://chinese.stackexchange.com/questions/50941", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/20355/" ]
做乜唔叫埋我? What is the function of 埋? First the sentence reads as:- 做乜 = why, (for what reason) 唔叫 = didn't call, (didn't include) 埋我? = me as well? The function of 埋 in this context of Cantonese speech is not "bury" but to mean "as well" So, 埋我 means "me as well" Of course in Cantonese 埋 also means "bury" in some other context. Another example of 埋 is 請埋位食饭 = please take a seat for (food, dinner, etc), where 埋位 means "take a seat", and not "bury a seat" in this context. From these basic examples, it could be seen that 埋 has multifarious usages in Cantonese speech, and only the context would ferret out the applicable meanings and usages. Finally, Quote:- "What is the difference with the sentence "做乜唔叫我"?" The "difference" between 做乜唔叫埋我? and 做乜唔叫我? is the "tone", meaning the intention behind the question. In 做乜唔叫我?, it is more a straight forward, neutral inquiry. In 做乜唔叫埋我?, the 埋我, "as well", has an "accusative" element, a certain covert unhappiness of "being left out" This accusative element could also be implied in the equivalent English sentences -- "Why didn't you call me"? and "Why didn't you call me as well"? This accusative element is more pronounced if 唔叫 is translated as "not include" rather than "not call" because in Cantonese 叫 in certain context does not always mean "call", (as in call someone on the phone)
As verbal suffix, 埋 can function as a verb complement with a lexical meaning somewhat like "close, tight". In this case, it can be used together with an adverb of degree (such as 好,太) and 咗. For example: 1. 唔好企太埋。(Don't stand too close.) 2. 佢关埋咗度门。(He has closed the door (tightly).) In a sentence like 做乜唔叫埋我?, 埋 functions as an aspect marker. In this case, it cannot be used together with an adverb of degree (such as 好,太) and 咗. And like many other aspect markers in Cantonese (e.g. 住,到,紧,亲...), 埋 "has lost" its lexical meaning through abstraction and become an aspect marker. The interpretation of the process where 埋 is used is a function of it's underlying value and the context. As an aspect marker, 埋 is used in contexts where we have a class of possible values constructed as fragmentable or dissociable. For example: 3. 唔准玩,做埋啲功课先。(You are not allowed to play. Finish your homework first.) 4. 今日下午我地踢波,叫埋阿民啦。(We are playing soccer this afternoon. Let Ah Min join us.) In (3), "homework" is constructed as a "fragmentable amount of work". You have already started, but there is still a fragment that remains to be done. In (4), there are a group of people who can play soccer together. 阿民 is singled out in the beginning as the one who may or may not play together. In these examples, 埋 serves to cancel the fragmentation and return the class as a whole.
50,941
In this sentence: 做乜唔叫埋我? What is the function of 埋? I understood this sentence to be: "why didn't you call me?" (perhaps to an outing or a party). What is the difference with the sentence "做乜唔叫我"? Insights please.
2022/04/12
[ "https://chinese.stackexchange.com/questions/50941", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/20355/" ]
As verbal suffix, 埋 can function as a verb complement with a lexical meaning somewhat like "close, tight". In this case, it can be used together with an adverb of degree (such as 好,太) and 咗. For example: 1. 唔好企太埋。(Don't stand too close.) 2. 佢关埋咗度门。(He has closed the door (tightly).) In a sentence like 做乜唔叫埋我?, 埋 functions as an aspect marker. In this case, it cannot be used together with an adverb of degree (such as 好,太) and 咗. And like many other aspect markers in Cantonese (e.g. 住,到,紧,亲...), 埋 "has lost" its lexical meaning through abstraction and become an aspect marker. The interpretation of the process where 埋 is used is a function of it's underlying value and the context. As an aspect marker, 埋 is used in contexts where we have a class of possible values constructed as fragmentable or dissociable. For example: 3. 唔准玩,做埋啲功课先。(You are not allowed to play. Finish your homework first.) 4. 今日下午我地踢波,叫埋阿民啦。(We are playing soccer this afternoon. Let Ah Min join us.) In (3), "homework" is constructed as a "fragmentable amount of work". You have already started, but there is still a fragment that remains to be done. In (4), there are a group of people who can play soccer together. 阿民 is singled out in the beginning as the one who may or may not play together. In these examples, 埋 serves to cancel the fragmentation and return the class as a whole.
做乜唔叫我? => Why didn't (you) notify me? 做乜唔叫**埋**我? = 做乜唔預我? = 做乜唔邀請我? => Why didn't (you) **also** count me **in**? = Why was I kept out? = Why ain't I **also in**vited? In English, "**also** count (somebody) **in**" means "**in**vite (somebody) **too**", but "count (somebody)" alone has no such clear meaning. While both questions sounds accusing, 埋 emphasizes that at lease one person is included in an event yet the asker was kept out.
5,060,583
I'm looking for something like flex/bison that works with C# code. I want to be able to provide some language descriptors and a parser should be generated.
2011/02/20
[ "https://Stackoverflow.com/questions/5060583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616840/" ]
[ANTLR](http://www.antlr.org/) is a very common parser generator with output bindings for many languages (including c#), but it is LLR which might make it a little more cumbersome than flex/bison if that's what you are accustomed to.
I've had my best luck with ANTLR, it can generate C# code as well. Good Language design support as well with ANTLR Works, an IDE for designing and testing your grammars, and quite a few tutorials to explain the whole thing. Other option is the F# powerpack that has fsLex and fsYacc. Only brielfy poked at it, seems powerful but very little documentation. For C# that's the two first thing to look at i think. GJ
5,060,583
I'm looking for something like flex/bison that works with C# code. I want to be able to provide some language descriptors and a parser should be generated.
2011/02/20
[ "https://Stackoverflow.com/questions/5060583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616840/" ]
There are several options. I've found Irony to be good. It's powerful, and it has a novel syntax utilizing C# operator overloads to convey the syntax of your grammars directly in C#. Irony - .NET Language Implementation Kit. <http://irony.codeplex.com/>
I've had my best luck with ANTLR, it can generate C# code as well. Good Language design support as well with ANTLR Works, an IDE for designing and testing your grammars, and quite a few tutorials to explain the whole thing. Other option is the F# powerpack that has fsLex and fsYacc. Only brielfy poked at it, seems powerful but very little documentation. For C# that's the two first thing to look at i think. GJ
74,284
Is the phrase "I'm glad it helped" grammatically correct? And if it is, does it express correctly that I am more than happy that I could help someone?
2012/07/12
[ "https://english.stackexchange.com/questions/74284", "https://english.stackexchange.com", "https://english.stackexchange.com/users/20713/" ]
"I'm glad it helped" is grammatically correct. But it doesn't mean that you're glad *you* helped, it means you're glad that something helped. It might, from context, be clear that it was something you said, did, or gave them. But "I'm glad it helped" alone doesn't say that. You can say "I'm glad I helped" or "I'm glad I was able to help" to indicate what you want. But you can't say "I'm glad it helped" unless it's clear what it is you are referring to -- some specific thing that helped.
*I'm glad it helped* is certainly grammatical, and it expresses the meaning you indicate. There are variations including, for example, *I’m glad I was able to help*. More briefly, you can say *My pleasure*.
74,284
Is the phrase "I'm glad it helped" grammatically correct? And if it is, does it express correctly that I am more than happy that I could help someone?
2012/07/12
[ "https://english.stackexchange.com/questions/74284", "https://english.stackexchange.com", "https://english.stackexchange.com/users/20713/" ]
*I'm glad it helped* is certainly grammatical, and it expresses the meaning you indicate. There are variations including, for example, *I’m glad I was able to help*. More briefly, you can say *My pleasure*.
This is very much comprehensible and commonly used, but it is not grammatically correct as the word "that" has been omitted. I know that it's pedantic but don't tell the guy that his sentence is absolutely correct. Of course, I would definitely advise a foreigner in England to use this phrase as it is polite and idiomatic.
74,284
Is the phrase "I'm glad it helped" grammatically correct? And if it is, does it express correctly that I am more than happy that I could help someone?
2012/07/12
[ "https://english.stackexchange.com/questions/74284", "https://english.stackexchange.com", "https://english.stackexchange.com/users/20713/" ]
"I'm glad it helped" is grammatically correct. But it doesn't mean that you're glad *you* helped, it means you're glad that something helped. It might, from context, be clear that it was something you said, did, or gave them. But "I'm glad it helped" alone doesn't say that. You can say "I'm glad I helped" or "I'm glad I was able to help" to indicate what you want. But you can't say "I'm glad it helped" unless it's clear what it is you are referring to -- some specific thing that helped.
This is very much comprehensible and commonly used, but it is not grammatically correct as the word "that" has been omitted. I know that it's pedantic but don't tell the guy that his sentence is absolutely correct. Of course, I would definitely advise a foreigner in England to use this phrase as it is polite and idiomatic.
278,574
How do you polymorph? What is the command or key I must use?
2016/08/01
[ "https://gaming.stackexchange.com/questions/278574", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/159680/" ]
You can't really polymorph at will. =================================== There are 6 different types of things that can polymorph you. * Stepping on a polymorph trap will turn you into a random monster (magic-resistance will block this) * The spell of polymorph, cast at you (at yourself or possibly by a monster, though I don't think they cast that spell) * Wand of polymorph, zapped at you. Monsters can't do this, but you can also zap yourself. * Wearing the ring of polymorph (*not* polymorph control) will cause you to polymorph at random intervals and into random monsters (beware, you can just as easily turn into a dragon as a lichen). * Drinking (and maybe thrown at you) a polymorph potion. * Eating a chameleon or doppelganger (both natural shape-shifters) corpse. Note the doppelganger corpse counts as cannibalism for humans. * Becoming a werecreature, either wererat, werewolf, or werejackal, will randomly polymorph you into your animal/human form. Praying, eating wolfsbane, or quaffing holy water will fix you however. * In wizard mode, the extended command `#polyself` also works. Note if you are already polymorphed into a magic-resistant monster (most common is grey dragon), some of these methods won't polymorph you. For more information about the effects of polymorphing, see the [Nethack wiki page on polymorph](https://nethackwiki.com/wiki/Polymorph). All forms of polymorph other than being a werecreature and `#polyself` in wizard mode don't let you control what you turn into. In addition, ring of polymorph and being a werecreature don't let you control when you polymorph. Eating a shapeshifter corpse, being cast at/zapped, and drinking polymorph potions apply immediately, and only polymorph you once. While a werecreature, you can only polymorph to and from your wereform and normal form. Finally, with a ring of polymorph control you can always control the result of a polymorph, including not changing at all. This will also stop transforming into/from your wereform if applicable, but will not stop you from gaining lycanthropy in the first place.
Doppelganger corpses will polymorph you, as well. And, if you happen to be a lycan (werecreature), you will polymorph into that particular creature at random (often, inconveniently or worse) or you can quaff unholy water to change at will. Regardless of how you polymorph, changing back still takes an unspecified amount of time between 500 and 1500 turns of the time counter or dying in monster form. As a lycan, you might be able to pray out or eat wolfsbane or quaff holy water (all of which "cure" you of the affliction). Be sure to summon some pets before curing yourself, you may get a pack of winter wolves orbe able to poly your pack of rats/jackals into something really formidable later.
501,559
In a statistics textbook I saw that the linear simple regression model is defined as \begin{equation} Y = \alpha + \beta x + e \end{equation} where $x$ is a value of the independent variable, $Y$ is the response, $\alpha$ and $\beta$ are the parameters, and $e$ is a random error with a mean of 0. Then this textbook talks about estimators. It says $A$ is an estimator of $\alpha$, and $B$ is an estimator of $\beta$. Also, $A+Bx$ is an estimator of $\alpha+\beta x$. However, according to the textbook, $A+Bx$ is an estimator of $Y$. I don't understand that $A+Bx$ can be an estimator of $Y$, since $Y$ is a random variable but not a parameter. Am I wrong? To me it makes sense only to say that $A+Bx$ is an estimator of the 'mean' of the random variable $Y$. Then, given that the mean of $e$ is zero, $A+Bx$ is an estimator of the mean of $\alpha + \beta x + e$.
2020/12/19
[ "https://stats.stackexchange.com/questions/501559", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/243929/" ]
You are right\*, we are *estimating* parameters but not (realizations of) random variables. We would *predict* those instead. \*Except for the last bit where you say > > Then, given that the mean of $e$ is zero, $A+Bx$ is an estimator of $\alpha + \beta x + e$. > > > Note that $\alpha+\beta x+e$ is a random variable and it equals $Y$. If you oppose to calling $A+Bx$ and estimator of $Y$, you should oppose calling it an estimator of $\alpha+\beta x+e$ for the sake of internal consistency.
When we say $A$ is an estimator of $\alpha$ it means that $\mathbb{E}(A)=\alpha$. Since $A+Bx$ is a random variable(because of $\alpha$ and $\beta$) we can write: $$\mathbb{E}(A+Bx)=\mathbb{E}(A)+\mathbb{E}(Bx)+0=\mathbb{E}(A)+\mathbb{E}(B)x+\mathbb{E}(e)=\mathbb{E}(Y)$$ Hope it helps.
36,884,146
I have a sample dataset 'a' like this: ``` > a group marks upd class 1 T 2 up A 2 C 3 up <NA> 3 C 4 down B 4 T 5 up <NA> 5 T 6 down D 6 C 7 up <NA> 7 T 1 down <NA> 8 T 0 down G ``` Here for each group (T or C) there are records in 'class' variable with values and null. Now for each group where ever the class is null ,I want that group to be renamed as T-NULL or C-NULL respectively. If the group (T or c) has some value in 'class' ,the group name should be as it is. How can we write a code in R for this?
2016/04/26
[ "https://Stackoverflow.com/questions/36884146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6199075/" ]
Your `id.value` is not a HTML element. You are trying to get an access to `value` property of id variable... Something like this `"ename".value` Try this: ``` document.getElementById(id).value = 'VALUE'; ``` ```js function myFunction(id) { var x = parseInt(document.getElementById(id).value); if (!(x === parseInt(x, 10))) { alert("Empployee ID can be integer numbers only."); document.getElementById(id).value = ""; } else { } } ``` ```html <div class="header1"> <input type="text" id="ename" onblur="myFunction('ename')" name="name" placeholder="Enter Employee ID" required="" /> </div> ```
You are setting empty string in the value property of `id`. `id` is a `string`. Hence, it won't work you need to put an empty string somewhere in the document where the id attribute is equal to the function argument. you need to use : ``` document.getElementById(id).value = ""; ```
36,884,146
I have a sample dataset 'a' like this: ``` > a group marks upd class 1 T 2 up A 2 C 3 up <NA> 3 C 4 down B 4 T 5 up <NA> 5 T 6 down D 6 C 7 up <NA> 7 T 1 down <NA> 8 T 0 down G ``` Here for each group (T or C) there are records in 'class' variable with values and null. Now for each group where ever the class is null ,I want that group to be renamed as T-NULL or C-NULL respectively. If the group (T or c) has some value in 'class' ,the group name should be as it is. How can we write a code in R for this?
2016/04/26
[ "https://Stackoverflow.com/questions/36884146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6199075/" ]
Your `id.value` is not a HTML element. You are trying to get an access to `value` property of id variable... Something like this `"ename".value` Try this: ``` document.getElementById(id).value = 'VALUE'; ``` ```js function myFunction(id) { var x = parseInt(document.getElementById(id).value); if (!(x === parseInt(x, 10))) { alert("Empployee ID can be integer numbers only."); document.getElementById(id).value = ""; } else { } } ``` ```html <div class="header1"> <input type="text" id="ename" onblur="myFunction('ename')" name="name" placeholder="Enter Employee ID" required="" /> </div> ```
You cannot use `id.value` because the `id` passed in you function was a string. Since you already passed the `id` then maybe you can use: `document.getElementById(id).value = "";` **Answer Explained**
52,937,262
I keep on having this error > > ActionView::Template::Error (undefined method `each' for nil:NilClass): > > > Here's my show.html.erb ``` <% @bookings.each do |booking| %> <% if booking.checkin_on > Date.today %> <% if booking.status == "Confirmed" %> <li class="dashboard"> <%= cl_image_tag(booking.bed.photo.path, width: 400, height: 300, crop: :fill, class: "pdt-image hidden-xs" ) %> <div class='product-body'> <h2><%= booking.bed.title %></h2> <p>City: <strong><%= booking.bed.city %></strong></p> <p>Address: <strong><%= booking.bed.address %></strong></p> <p>Total price: <strong><%= booking.value %> €</strong></p> </div> <div> <ul class="list-unstyled hidden-sm hidden-xs padded"> <li><strong>Your booking is confirmed !</strong></li> <li class="text-right"><%= link_to "Delete this booking", booking_path(booking), method: :delete, class:"btn btn-default", data: {confirm: "Are you sure"} %> </li> </ul> </div> </li> <% end %> <% if booking.status == "Canceled" %> <li class="dashboard"> <%= cl_image_tag(booking.bed.photo.path, width: 400, height: 300, crop: :fill, class: "pdt-image hidden-xs" ) %> <div class='product-body'> <h2><%= booking.bed.title %></h2> <p>City: <strong><%= booking.bed.city %></strong></p> <p>Address: <strong><%= booking.bed.address %></strong></p> <p>Total price: <strong><%= booking.value %> €</strong></p> </div> <div> <ul class="list-unstyled hidden-sm hidden-xs padded"> <li><p><%= booking.bed.user.first_name%> canceled your booking </p></li> </ul> </div> </li> <% end %> <% end %> <% end %> ``` And here's my my\_bookings controller ``` class My::BookingsController < ApplicationController def index @bookings = Booking.where(user_id: current_user.id) @bookings = Booking.all @beds = Bed.all end def show set_booking @bed = @booking.bed end private def set_booking @booking = Booking.find(params[:id]) end end ``` Any suggestions? Or anything I can't see? I have tried almost everything I can think of at the moment. Thanks!
2018/10/22
[ "https://Stackoverflow.com/questions/52937262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10161978/" ]
You are not declairing the @bookings variable on your `show` method, which explains the crash. It appears you are declaring it as you wanted it on the first line of your `index` method. Just change where you declare it, and it shall be alright. Also, to avoid further headaches, you should refactor the `set_booking` method to: ``` def set_booking @booking = Booking.find_by(id: params[:id]) end ``` by deafult `.find()` will crash your view if it doesn't find anything `.find_by`, on the other hand, will return an empty answer, so it won't crash. Also, it's more versatile, since this way you can search from innumerous other variables set in your model, i.e. `name`.
By convention in Rails controller actions (`index` and `show` in your case) render views with same names, in your case those might be `intex.html.erb` and `show.html.erb`. In your show method you define two variables: `@bed` and `@booking` and in your view (`show.html.erb`) you try to loop variable `@bookings` which you have not defined in your controller action. Thus, you are getting this error. Looks like you need to rename `show.html.erb` to `index.html.erb` as you are listing bookings and their information in it.