text
stringlengths
70
452k
dataset
stringclasses
2 values
Dotless on Appharbor I am having a huge issues with DotLess on AppHarbor. I have setup my web.config correctly according to dotless but my .less files are always giving a 404 error. I have made sure that the files are built as content, that there is a mime-type and that all settings are according to dotless. But it is still not working... is anyone else having the same issue? Has anyone else been able to resolve it? Can you get the logs? Is it getting as far as asp? I had to set the Build Action value to Content and then set the Copy To Output DIrectory value to Copy always. After doing that, it seems to work correctly! WOOHOOOO! This is so exciting. It's been a big issues of the last few days. This solution also helped me when doing font files...brilliant!
common-pile/stackexchange_filtered
Sql Error:A network-related or instance-specific error while establising connection I have developed a c# winforms application. On my developement system the application is working correctly. I created the setup and installed the application on the test system. On the test computer I installed sql server express and the services of the testing computer the sql server and sql browser are running. But when opening the application. It is showing the following error A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) connection string i have given is <add name="JaithramConnectionString" connectionString="Data Source=.\SQLExpress;Initial Catalog=EasyCab;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> on testing computer the sql express is installed as Use the Built in Account - local system and instance default instance Sql surface is configured to accept remote connection.with named and tcp/ip pipes. I am Confused with this. Thanks in advance. If you remote into the test machine, can you access the sql server via SSMS or Visual Studio or something along those lines? Basically, are you sure the problem is with your code and not the instance of SQL on the test box? .\SQLExpress doesn't look right to me - you may need to qualify the source, AFAIK: ServerName\SQLExpress. I'm no expert though, and the string might well be valid. Have you tried "Data Source=." ? Please check the file wall settings for this computer. Even though you're using .\SQLExpress or (local)\SQLExpress it attempt to resolve the port which when closed...
common-pile/stackexchange_filtered
Linking ID in a table to data in another table - but in a many-to-many relationship I've been looking at foreign keys and things because I have an assignment coming up so I'm trying to get a grasp on everything so I'm ready. I was looking at Linking ID from one table to data in another table and the answer mentions a way to do it in a many-to-many relationship but I can't see it anywhere, so I'd like to know how to do this. When looking at the linked question, an example I'd like would be many ContactPerson could work for many Company. I'm not sure if asking a question in this format is correct, but I thought it easier to link to the existing question rather than rewriting it. Thanks in advance for any help. You'll want a many-to-many relationship, which consists of 3 tables: Company ContactPerson Company2ContactPerson Example here: http://sqlrelationship.com/many-to-many-relationship/ Yes, this is the correct answer, but that's a terrible table name (personally, I'm a little leery of using 'To' as a relationship specifier, much less substituting the numeric value). Additionally, to protect from link-rot, perhaps you could show the minimum expected fields for the cross-reference table? Just to answer my own question, there's an in-depth explanation and examples which can be found here: http://www.singingeels.com/Articles/Understanding_SQL_Many_to_Many_Relationships.aspx
common-pile/stackexchange_filtered
WPF Binding relational ComboBox's from L2S with filtering on all of them in a WPF project with Linq to SQL, if you use the O/R - designer to create a simple structure with 3 that are all tied with forgin key relataions like so: Customer <-- Orders <-- Items, and say i want a simpe window with 3 syncronized comboboxes when you select a customer you see only his orders and when you select an Order you see only the Items for that Order. all of this is simple.... Lets say i want to add filtering capablities to all the comboboxes. how would i do that if i want to use the entity objects from the LINQ dbml file? Edit - Elaborating on filtering. i would like to filter the in memory collection without the need to query the database again, the filter can be a textbox that is over the combobox, that doest matter, my problem is that i cant filter the comboboxes because the are bound to an EntitySet through the L2S and dont implement filtering. Thanks, Eric can you elaborate on filtering capabilities you're interested in ? I would look into using CollectionViewSource. Bea Stollnitz has a good primer on it here and I used this blog post to show me how to filter. This will let you filter and sort without having to use the database and is pretty fast. This isnt what im looking for EntitySet implemetetion of IBindingLisView cannot filter. thats exactly the problem.
common-pile/stackexchange_filtered
Magento 2: Safest way to delete spam customers specific date/email using MySQL? what is the safest way to delete spam customers specific date/email using MySQL? For example delete all customers with email example.com and from 9/15/2018 to 9/28/2018 I cant use back-end UI to delete the records because hosting limitation resources and its gives. Warning: Error while sending QUERY packet. PID=28451 in /home/got52/public_html/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php on line 228 So anyone have the mysql query doing that? Thanks Do you want to delete it directly from the database ? Using sql query ? @AdityaShah Yes, but in safest way. Yeah try select query first to see if it will delete the correct rows please mark as right if it solves your query. Hello are you there? [Note]: Please take database backup prior to executing these queries. First check Query using SELECT - to see if it will delete the correct rows SELECT * from customers WHERE email like '%example.com' and date_created between CAST('2018-09-15' AS DATE) AND CAST('2018-09-28' AS DATE); Then DELETE customers where email like '%example.com' and date_created between CAST('2018-09-15' AS DATE) AND CAST('2018-09-28' AS DATE); Customer tables `customer_address_entity`; `customer_address_entity_datetime`; `customer_address_entity_decimal`; `customer_address_entity_int`; `customer_address_entity_text`; `customer_address_entity_varchar`; `customer_entity`; `customer_entity_datetime`; `customer_entity_decimal`; `customer_entity_int`; `customer_entity_text`; `customer_entity_varchar`; `customer_grid_flat`; `customer_log`; `customer_log`; `customer_visitor`; Just run query ONLY - which table has email address field. What about if there is another tables stored same data for deleted customers?
common-pile/stackexchange_filtered
getting local host name as destination using getaddrinfo/getnameinfo I am looking through some out-of-date code which uses getaddrinfo and getnameinfo to determine host name information and then falls back to gethostname and gethostbyname if getnameinfo fails. Now, this seems wrong to me. I am trying to understand the intent of the code so that I can make a recommendation. I don't want to repost the entire code here because it is long and complicated, but I'll try to summarize: As far as I can tell, the point of this code is to generate a string which can be used by another process to connect to a listening socket. This seems to be not just for local processes, but also for remote hosts to connect back to this computer. So the code in question is basically doing the following: getaddrinfo(node = NULL, service = port, hints.ai_flags = AI_PASSIVE, ai); -- this gets a list of possible arguments for socket() that can be used with bind(). go through the list of results and create a socket. first time a socket is successfully created, this is selected as the "used" addrinfo. for the ai_addr of the selected addrinfo, call getnameinfo() to get the associated host name. if this fails, call gethostname(), then look up gethostbyname() on the result. There are a few reasons I think this is wrong, but I want to verify my logic. Firstly, it seems from some experiments that getnameinfo() pretty much always fails here. I suppose that the input address is unknown, since it is a listening socket, not a destination, so it doesn't need a valid IP from this point of view. Then, calling gethostname() and passing the result to gethostbyname() pretty much always returns the same result as gethostname() by itself. In other words, it's just verifying the local host name, and seems pointless to me. This is problematic because it's not even necessarily usable by remote hosts, is it? Somehow I think it's possible that the whole idea of trying to determine your own host name on the subnet is not that useful, but rather you must ping a message to another host and see what IP address they see it as. (Unfortunately in this context that doesn't make sense, since I don't know other peers at this level of the program.) For instance, the local host could have more than one NIC and therefore multiple IP addresses, so trying to determine a single host-address pair is nonsensical. (Is the correct resolution to just bind() and simultaneously listen on all addrinfo results?) I also noticed that one can get names resolved by just passing them in to getaddrinfo() and setting the AI_CANONNAME flag, meaning the getnameinfo() step may be redundant. However, I guess this is not done here because they are trying to determine some kind of unbiased view of the hostname without supplying it apriori. Of course, it fails, and they end up using gethostname() anyways! I also tried supplying "localhost" to getaddrinfo(), and it reports in ai_canonname` the host name under Linux, but just results in "localhost" on OS X, so not so useful since this is supposed to be cross-platform. I guess to summarize, my question is, what is the correct way, if one exists, to get a local hostname that can be announced to subnet peers, in modern socket programming? I am leaning towards replacing this code with simply returning the results of gethostname(), but I'm wondering if there's a more appropriate solution using modern calls like getaddrinfo(). If the answer is that there's no way to do this, I'll just have to use gethostname() anyways since I must return something here, or it would break the API. If I read this correctly, you just want to get a non-localhost socket address that is likely to succeed for creating a local socket, and for a remote host to connect back on. I have a function that I wrote that you can reference called "GetBestAddressForSocketBind". You can get it off my GitHub project page here. You may need to reference some of the code in the parent directory. The code essentially just uses getifaddrs to enumerate adapters and picks the first one that is "up", not a loopback/local and has an IP address of the desired address family (AF_INET or AF_INET6). Hope this helps. This is similar to an approach I took on another project, but eventually I realized that it's problematic in situations where the computer is a laptop that can potentially have both a wired and wireless connection. When picking the "first" reported IP, often what happened was that the wrong one was selected, and not available as a destination for remote hosts. It also seemed to conflict badly with some copy protection software that installed "fake" NICs on some machines. It seemed better to just send a UDP message to the remote, and have it check the UDP datagram origin using recvfrom(). Is this Windows or Linux? In any case, both platform allow you to inspect the routing table to discover which IP/adapter has the default route. For multiple adapter scenarios, the one with the lowest metric is the likely default. But the only sure fire way to know for sure is to just bind to INADDR_ANY, and have the other side tell you what IP it sees you as. Hey, that sounds like STUN. Same link as above in my answer. I think that you should look at Ulrich Drepper's article about IPv6 programming. It is relatively short and may answer on some of your concerns. I found it really useful. I'm posting this link, because it is very difficult to answer to your question(s) without (at least) pseudo-code. It doesn't seem to address the question of how to relate to peers what the host name is. However, the mention of getifaddrs maybe leads to the idea of scanning the local IP list and calling getnameinfo on each one, to get a list of possible names. I'll try it.
common-pile/stackexchange_filtered
soapui - print testing I am new in SOAPUI. I'm trying to write automatic test which will check more than 300 prints (PDF) in browser. Currently I execute this manually. I enter template_id in SoapUI (e.g EUEAI000010001), then I have PrntId (eg. 132100) and at the end I generate link to the page www where can I check my print - correct or not. I'll be very grateful if someone can give me some tips/support how to begin this process with automatic test. Template_id I have in xml file - more than 300. you may use input file to enter your template_id (soapui pro) otherwise try to do the same within a groovy script. Place the 300 values in an array. pick first value a[0] in a groovy script.Set a test Caseproperty to a[0].Use this value in your api '${#testCase#Property1}'. Now run your request 300 times with each time different values. Also save the PrntId in some file.. so at the end you will have 300 prntid
common-pile/stackexchange_filtered
JBoss WildFly 15.0.1 Final not starting on ubuntu 14.04 vServer with 2 GB: insufficient memory for JRE I am trying to get JBoss WildFly 15.0.1 Final to start on a rather small ubuntu 14.04 vServer. The server has only 2 GB of RAM. I tried to start WildFly many times without success. The JVM seems to require a lot more RAM than I had ever expected. Here's the console output: root@t2g55:~# service wildfly start * Starting WildFly Application Server wildfly * WildFly Application Server failed to start within the timeout allowed. root@t2g55:~# cat /var/log/wildfly/console.log ========================================================================= JBoss Bootstrap Environment JBOSS_HOME: /opt/wildfly JAVA: /usr/bin/java JAVA_OPTS: -server -Xms768m -Xmx1536m -XX:MetaspaceSize=96M -XX:MaxMetaspaceSize=256m -Djava.net.preferIPv4Stack=true -Djboss.modules.system.pkgs=org.jboss.byteman -Djava.awt.headless=true ========================================================================= OpenJDK 64-Bit Server VM warning: INFO: os::commit_memory(0x00000000a0000000, 536870912, 0) failed; error='Cannot allocate memory' (errno=12) # # There is insufficient memory for the Java Runtime Environment to continue. # Native memory allocation (mmap) failed to map 536870912 bytes for committing reserved memory. # An error report file with more information is saved as: # /opt/wildfly-15.0.1.Final/hs_err_pid1379.log 1379 root@t2g55:~# free total used free shared buffers cached Mem: 2097152 258748 1838404 64 0 38644 -/+ buffers/cache: 220104 1877048 Swap: 2097152 0 2097152 root@t2g55:~# java -version openjdk version "1.8.0_222" OpenJDK Runtime Environment (build 1.8.0_222-8u222-b10-1~14.04-b10) OpenJDK 64-Bit Server VM (build 25.222-b10, mixed mode) root@t2g55:~# As you can see I specified JAVA_OPTS: -server -Xms768m -Xmx1536m ..., which I thought should suffice for a WildFly server to start. Please not, that the standalone.xml has a datasource defined to a MySQL DB. Here's the start of the dump .log: root@t2g55:~# cat /opt/wildfly-15.0.1.Final/hs_err_pid1379.log # # There is insufficient memory for the Java Runtime Environment to continue. # Native memory allocation (mmap) failed to map 536870912 bytes for committing reserved memory. # Possible reasons: # The system is out of physical RAM or swap space # The process is running with CompressedOops enabled, and the Java Heap may be blocking the growth of the native heap # Possible solutions: # Reduce memory load on the system # Increase physical memory or swap space # Check if swap backing store is full # Decrease Java heap size (-Xmx/-Xms) # Decrease number of Java threads # Decrease Java thread stack sizes (-Xss) # Set larger code cache with -XX:ReservedCodeCacheSize= # This output file may be truncated or incomplete. # # Out of Memory Error (os_linux.cpp:2757), pid=1379, tid=0x00007f62486c6700 # # JRE version: (8.0_222-b10) (build ) # Java VM: OpenJDK 64-Bit Server VM (25.222-b10 mixed mode linux-amd64 compressed oops) # Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again # --------------- T H R E A D --------------- . . . QUESTION: Can this be solved with this amount of memory or do I simply have too few RAM? What else could I probably try? I don't really want my provider to go up with the mem successively only to find there's some other problem with Java, the JVM or anything... Thanks EDIT 1: The vServer provider uses OpenVZ for its virtualization. Info: they just pushed my to 4GB, then once, I got JBoss up and running. After reboot WildFly again refuses to start: same thing, not enough memory (even though I switch between Java 8 and Java 11 runtimes). CMD to start JBoss WildFly: sh /opt/wildfly/bin/standalone.sh &, standalone.xml appears to be OK. I removed the ExampleDS, three entries commented. https://developers.redhat.com/blog/2017/03/14/java-inside-docker/ Something in that direction maybe? WildFly will start fine with 64M heap, so if you run with something like -Xmx128M should be fine for wildfly itself, question is how much do applications you run on it need. It was indeed a server virtualization issue with OpenVZ. Quote (in German): Hi, das Problem nach bei den user_beancounters, genauer gesagt bei privvmpages, diese waren > zu gering eingestellt. https://wiki.openvz.org/UBC_secondary_parameters#privvmpages Mit freundlichen Grüßen Mr X Translation: Hi, the problem was with the user_beancounters, that is with the privvmpages, these were set too low. https://wiki.openvz.org/UBC_secondary_parameters#privvmpages Best regards Mr X I don't know exactly what he did in detail, but that resolved it. I now run on a 2GB machine without any problems and memory usage of mysqld + standalone.sh (WildFly + webapp) is around 800 MB.
common-pile/stackexchange_filtered
Running AWS Command Line Interface using Jenkins installed through Docker: command not found? When running aws from Jenkins pipeline I have the following error message: command not found - which aws returns command not found. By other hand, when running aws from a single job it works - which aws returns /usr/local/bin/aws. Do you have any idea why this is happening? Thank you. You still need to install the AWS CLI inside the docker container. # Swap to root user to install pip and aws cli then go back to jenkins user USER root RUN apt-get update RUN apt install python3-pip -y RUN pip3 install awscli --upgrade USER jenkins Thank you @Loaf :) It fixed my problem! In my case the problem simply was that I was running the Jenkins in a docker container while my AWS-CLI was installed on the host. The temporal workaround was I logged in the Jenkins container through "docker exec" and installed the AWS-CLI in that container too. Probably if my container restarts I have to install the AWS-CLI again. Better way is to create a docker image which contains the AWS-CLI beside Jenkins or using an AWS-CLI jenkins agent for running those steps/jobs. Solution 1: Install aws-cli in Jenkins container using a Dockerfile and use the credentials already stored on your host. Working example: Dockerfile: FROM jenkins/jenkins:lts USER root # Set timezone ENV TZ="UTC" RUN apt-get -y update --fix-missing # Install useful tools RUN apt-get -y install nano wget ntp git curl libcurl4 libcurl4-openssl-dev zip unzip jq # Install AWS Cli: # https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html RUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" RUN unzip awscliv2.zip RUN ./aws/install docker-compose.yml: Version: '3.3' services: jenkins: container_name: jenkins build: context: ./ dockerfile: Dockerfile hostname: jenkinslocal user: root ports: - 8500:8080 volumes: # local persistent storage for docker to keep plugins, jobs, workspaces, etc - ./jenkins-data:/var/jenkins_home # mount the source file for project for easy access in pipeline # and in project pipeline -> configure SCM -> GIT url can be: # file:///projects/project1 - /Users/bogdan/docker/project1:/projects/project1 # make docker available in container - /var/run/docker.sock:/var/run/docker.sock - /usr/bin/docker:/usr/bin/docker #provide AWS CLI credentials from host - /Users/bogdan/.aws:/root/.aws Solution 2: Use docker image with aws-cli provided by aws with credentials from host. In this case, if you don't have other tools to install, you don't need a Dockerfile, just the docker-compose.yml file Working example: Version: '3.3' services: jenkins: container_name: jenkins # image from docker hub image: jenkins/jenkins:lts hostname: jenkinslocal user: root ports: - 8500:8080 volumes: # local persistent storage for docker to keep plugins, jobs, workspaces, etc - ./jenkins-data:/var/jenkins_home # mount the source file for project for easy access in pipeline # and in project pipeline -> configure SCM -> GIT url can be: # file:///projects/project1 - /Users/bogdan/docker/project1:/projects/project1 # make docker available in container - /var/run/docker.sock:/var/run/docker.sock - /usr/bin/docker:/usr/bin/docker Documentation can be found here: https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-docker.html After Jenkins is up and running you can login to Jenkins container: docker exec -it jenkins bash and run AWS-CLI like this: docker run --rm -it -v ~/.aws:/root/.aws amazon/aws-cli --version Using this command in Jenkins pipeline will be difficult and the script will not run on a real production server, so you need to create an alias to use the command "aws" : alias aws='docker run --rm -it -v ~/.aws:/root/.aws -v amazon/aws-cli' now you can test: aws --version For avoid login to Jenkins container you can add the command to docker-compose.yml file: command: sh -c "alias aws='docker run --rm -it -v ~/.aws:/root/.aws -v amazon/aws-cli'" Important! Solution 2 can be difficult to use in some situations because aliases are not available, by default, in bash scripts.
common-pile/stackexchange_filtered
Used Avocent advice I want to purchase a used Avocent KVM-over-IP device on eBay to manage some servers out-of-band in a data center. I have seen many older ones on eBay in good working condition for a couple hundred bucks, including the cable dongles. Like model 2000 and the like. Seems like a good deal. Assuming I am willing to take the risk and purchase a working unit from a reputable seller, is there anything I need to beware of? I have seen some references to DSView software. Assuming the used unit does not come with software, is the software needed for Avocent built into the box, or is a separate purchase? Or free download? Other out-of-band KVM-over-IP that I've used like IPMI from Supermicro the software was in firmware and it was web-based. That's really what would be ideal. Assign an IP to the KVM-over-IP and then control via a browser. How old are these servers? Pretty much every server I've purchased in the past 5 years has had some sort of OOB management card installed as shipped from the factory. Dell has their DRAC cards, HP has iLO, Sun, has iLOM, etc. If your servers have those, using that would be far superior to a KVM switch. Most are crippled from the factory unless you paid for the upgraded license and/or dedicate module though. The Avocent can integrate with the ILO/DRAC/etc. it's a good product. The dongles can be pricey, but some of them even allow you to mount an ISO over the KVM. Personally I like as few cables in back of my rack as possible and agree with you, go with the built-in units. @SpacemanSpiff - yep, very true. It's so nice to not have to deal with a separate KVM device, though, for the cabling reason you mentioned, and several others. these supermicro servers about 2-4 years old and they do not have any kvm-over-ip built in nor is it available on the models i have. so i need an external unit. We've purchased the Dell-branded Avocent units used from eBay over the years and had success. The last time I checked the Dell KVM client was a free download from Dell's web site. It may well work with the Avocent units (non-Dell branded) too but I've never tried it. hi thank you. can you tell me some of the model numbers you have had success with and if they worked with usb kvm over ip (not just ps2). thank you
common-pile/stackexchange_filtered
Is one mutable reference in Rust really enforced? I just started on Rust couple days ago and work through concept of ownership now. So ok - you can't have more than one mutable reference - I dig that - so this fails: let mut s4= String::from("ZOOT"); let s5 = &mut s4; let s6 = &mut s4; //error here - second mutable borrow occurs here s5.push_str(" suit"); //added this line to force error on s6 but why is this allowed??? let mut s4= String::from("ZOOT"); let s5 = &mut s4; s5.push_str(" suit"); let s6 = &mut s4; //but WHY NOT here? and yes println!("s6 = {} ", s6); prints ZOOT suit. PS. I do understand that after the line let s6 = &mut s4; the s5 is no longer accessible - if you try then suddenly compiler wakes up and throws error on s6 declaration. But should it throw fit - on the second reference to s4 with or without s5 being used to modify content of s4? you can't have more than one mutable reference - I dig that - so this fails: no it doesn't. Actually you are right - it fails only if I try to use reference to s5. Lemme upgrade the question. Very complete and interesting answer to my borderline trivial observation. Thank you very much - great read!
common-pile/stackexchange_filtered
Nsis installer get file size I am using NSIS installer. I want to unzip file, but before, I wont to get it's size. Is it possible? Thanks! Basicaly, you can use FileSeek to get the position of the 0th byte from the end. FileOpen $0 somefile.txt r ;open somefile in read mode FileSeek $0 0 END $1 ;ask for the 0th byte from the end, and put the value in $1 FileClose $0 ;here you have the size in $1 This is used in a more convenient way that preserves the variables in the FileSizeNew function that get the filename and returns the result via the stack. You can use the GetSize macro, it comes pre-installed with NSIS
common-pile/stackexchange_filtered
The opencv code for face recognition does not predict correctly in visual c++ This is my code for face recognition in videos. It runs without any error but it's prediction is wrong most of the time.I am using LBPH face recognizer to recognize the faces. I tried using haar cascades but it does not load. so i switched to LBHP.please help me to improve the prediction. I am using gray scale cropped images of size 500 x 500 (pixels) for training the cascade classifier. #include <opencv2/core/core.hpp> #include <opencv2/contrib/contrib.hpp #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/objdetect/objdetect.hpp> #include <iostream> #include <fstream> #include <sstream> using namespace cv; using namespace std; static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') { std::ifstream file(filename.c_str(), ifstream::in); if (!file) { string error_message = "No valid input file was given, please check the given filename."; CV_Error(CV_StsBadArg, error_message); } string line, path, classlabel; while (getline(file, line)) { stringstream liness(line); getline(liness, path, separator); getline(liness, classlabel); if(!path.empty() && !classlabel.empty()) { images.push_back(imread(path, 0)); labels.push_back(atoi(classlabel.c_str())); } } } string g_listname_t[]= { "ajay","Aasai","famiz" }; int main(int argc, const char *argv[]) { // Check for valid command line arguments, print usage // if no arguments were given. //if (argc != 4) { // cout << "usage: " << argv[0] << " </path/to/haar_cascade> </path/to/csv.ext> </path/to/device id>"<<endl; // cout << "\t </path/to/haar_cascade> -- Path to the Haar Cascade for face detection." << endl; // cout << "\t </path/to/csv.ext> -- Path to the CSV file with the face database." << endl; // cout << "\t <device id> -- The webcam device id to grab frames from." << endl; // exit(1); //} //// Get the path to your CSV: //string fn_haar = string(argv[1]); //string fn_csv = string(argv[2]); //int deviceId = atoi(argv[3]); //// Get the path to your CSV: // please set the correct path based on your folder string fn_haar = "lbpcascade_frontalface.xml"; string fn_csv = "reader.ext "; int deviceId = 0; // here is my webcam Id. // These vectors hold the images and corresponding labels: vector<Mat> images; vector<int> labels; // Read in the data (fails if no valid input filename is given, but you'll get an error message): try { read_csv(fn_csv, images, labels); } catch (cv::Exception& e) { cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl; // nothing more we can do exit(1); } // Get the height from the first image. We'll need this // later in code to reshape the images to their original // size AND we need to reshape incoming faces to this size: int im_width = images[0].cols; int im_height = images[0].rows; // Create a FaceRecognizer and train it on the given images: Ptr<FaceRecognizer> model = createLBPHFaceRecognizer(); model->train(images, labels); cout<<("Facerecognizer created"); // That's it for learning the Face Recognition model. You now // need to create the classifier for the task of Face Detection. // We are going to use the haar cascade you have specified in the // command line arguments: CascadeClassifier lbp_cascade; if ( ! lbp_cascade.load(fn_haar) ) { cout<<("\nlbp cascade not loaded"); } else { cout<<("\nlbp cascade loaded"); } // Get a handle to the Video device: VideoCapture cap(deviceId); cout<<("\nvideo device is opened"); // Check if we can use this device at all: if(!cap.isOpened()) { cerr << "Capture Device ID " << deviceId << "cannot be opened." << endl; return -1; } // Holds the current frame from the Video device: Mat frame; for(;;) { cap >> frame; // Clone the current frame: Mat original = frame.clone(); cout<<("\nframe is cloned"); // Convert the current frame to grayscale: Mat gray; //gray = imread("G:\Picture\003.jpg",0); cvtColor(original, gray, CV_BGR2GRAY); imshow("gray image", gray); // And display it: char key1 = (char) waitKey(50); // Find the faces in the frame: cout<<("\ncolor converted"); vector< Rect_<int> > faces; cout<<("\ndetecting faces"); lbp_cascade.detectMultiScale(gray, faces); // At this point you have the position of the faces in // faces. Now we'll get the faces, make a prediction and // annotate it in the video. Cool or what? cout<<("\nfaces detected\n"); cout<<faces.size(); for(int i = 0; i < faces.size(); i++) { // Process face by face: cout<<("\nprocessing faces"); Rect face_i = faces[i]; // Crop the face from the image. So simple with OpenCV C++: Mat face = gray(face_i); // Resizing the face is necessary for Eigenfaces and Fisherfaces. You can easily // verify this, by reading through the face recognition tutorial coming with OpenCV. // Resizing IS NOT NEEDED for Local Binary Patterns Histograms, so preparing the // input data really depends on the algorithm used. // // I strongly encourage you to play around with the algorithms. See which work best // in your scenario, LBPH should always be a contender for robust face recognition. // // Since I am showing the Fisherfaces algorithm here, I also show how to resize the // face you have just found: /*Mat face_resized; cv::resize(face, face_resized, Size(im_width, im_height), 1.0, 1.0, INTER_CUBIC); // Now perform the prediction, see how easy that is: cout<<("\nface resized"); imshow("resized face image", face_resized);*/ int prediction = model->predict(face); cout<<("\nface predicted"); // And finally write all we've found out to the original image! // First of all draw a green rectangle around the detected face: cout<<("\nnow writing to original"); rectangle(original, face_i, CV_RGB(0, 255,0), 1); // Create the text we will annotate the box with: string box_text; box_text = format( "Prediction =",prediction); // Get stringname if ( prediction >= 0 && prediction <=1 ) { box_text.append( g_listname_t[prediction] ); } else box_text.append( "Unknown" ); // Calculate the position for annotated text (make sure we don't // put illegal values in there): int pos_x = std::max(face_i.tl().x - 10, 0); int pos_y = std::max(face_i.tl().y - 10, 0); // And now put it into the image: putText(original, box_text, Point(pos_x, pos_y), FONT_HERSHEY_PLAIN, 1.0, CV_RGB(0,255,0), 2.0); } // Show the result: imshow("face_recognizer", original); // And display it: char key = (char) waitKey(50); // Exit this loop on escape: if(key == 27) break; } return 0; } 500x500 pixels for training the face classifier is huge... You should try with 100x100 or 50x50 images. In my experience with opencv face recognition, the lighting is very important. Make sure the faces are well lit from the front, with no bright lights or other distractions in the background. @AldurDisciple, image size does not matter with lbph ( featuresize is only dependant on num_patches and num_neighbours ) I tried using 100 x 100 images also.still not working. also tried to work in a environmentwith well lit faces and plain background but no use That is an expected result if you ask me, the code which you showed is the basic one to do recognition, there are some backdrops which we need to take care of before implementing. 1) the quality of training images, how did you crop them ? do they contain any extra information apart from face, if you used haar classifier in our opencv data to crop faces, then, the images tend to contain extra information than the face, as the rectangles are a bit large in size when compared to face. 2) there might be a chance that, even the rotated faces might be trained, so, its tough to classify with the features of rotated faces. 3) how many images, you trained the recognizer with ?, it playes a crucial role. Answer for the first question, is most likely to be out of opencv, we cant do much about it, as there is very less probability that, we ll find a face detector which is as good and as simple as haar detector, so, we could make this as an exemption, if we can adjust with an accuracy around 70 %. the second problem could be solved with some preprocessing techniques on training and testing dataset. Like., aligning faces which are being rotated follow this link, very good suggestions for face alignment are being suggested. How to align face images c++ opencv the third problem is solved with good number of samples which is not a hard task to achieve, take care of alignment before training, so that correct features could be extracted to classify. there might be other factors that can improve the accuracy which I might have missed.
common-pile/stackexchange_filtered
Medical Marijuana I read a couple of posts about the legality and so on related to growing marijuana but I don't think they were specific to the fact that in many states, including California, consumption and even growing it is not illegal as long as it fits within the limitations set by the law governing it. Patients are allowed to obtain it for medical use from dispensaries or co-ops and even are limited to having two mature plants and up to 4 new plants for a total of 6 total (which actually have red label stickers on them identifying them as medically permitted plants). However, not everyone who is a patient who needs it or has the legal permission to grow it know how to do it, everything from germination, planting, lighting, pruning, and ultimately harvesting. So would questions regarding manners to help such people become self sufficient in this matter be allowed? Even the federal government has acknowledged that the DEA will no longer go after people/dispensaries inside states where medical use of marijuana is legalized. SO if a patient who wants to do this asks for help with seeds, growing tips and so on, is that allowed? Also, obviously people replying are not all patients but may have expertise to help them, is that also allowed? I personally think it should be allowed as we are not police and what people do with information provided is their responsibility and legal liability, not ours. As an attorney I also highly disagree with the statement that government can ask for the users' information and we are required to provide it to them. While not strictly a duplicate, this is answered on the linked post. Questions on sourcing probably aren't OK as questions on sourcing in general aren't good fits for SE. Questions about cultivation are fine. This is in no way about illegal activity and for you to mark it as duplicate of illegal activity is offensive. Its also not about sourcing but rather helping people with legal right to grow for themselves to get help doing so. I believe this marking is inaccurate. To be clear. It's illegal in some places and not in another. Indignation that it's classified with a question about other sometimes illegal activity isn't helpful to the dialogue here. Fact: growing marijuana for any purpose is still illegal under federal law. Fact: growing marijuana for any purpose is still illegal in New York where SEI is located. That makes this question identical to the question asked. I've asked another mod to take a look at my decision here, but I'm not seeing the issue. I have to agree with @waxeagle: growing marijuana is illegal in a lot of places. You may not be breaking California law by growing 6 red-tagged plants, but you certainly would be if you grew 60,000 in the Mendocino National Forest. Answers to the duplicate offer a reasonable policy which allows for questions about their cultivation. Also related: http://meta.gardening.stackexchange.com/questions/337/are-questions-about-a-marijuana-garden-allowed 20 states in which it is either legal for medical use or outright legal for personal use and we are splitting hair about NY? We are not suggesting people should break the law where its illegal, but help those where it IS legal. Just about any subject can have the implication of being illegal somewhere, doesn't mean it should't be discussed? Even the federal government has suspended messing with states where there is legal statutes on the books, so as long as you are not promoting illegal activity, answering questions to a legal matter is hardly a violation of anything. This seems wrong. Did you read the top answer to the duplicate? It argues for allowing these questions. And we agree. There's not argument that they are allowed. Yes I did and I agree with Daniel Bingham's answer and believe its the most enlightened one I have heard so far. But to link my question to one being labeled illegal activity is inappropriate. I am not advocating illegal activity, never have, but rather the legal and supportive mechanism by which we can support the greater good without letting the potentiality of illegal activity by a minority to overshadow it. The asker wants to know how to respond to illegal activity, I am specifically asking about LEGAL activity, see? not duplicate.
common-pile/stackexchange_filtered
Air Android app crashes when phone changes orientation ... or at various settings in the app xml (<appName>-app.xml or application.xml) when holding the phone in Portrait-orientation instead of landscape-orientation. Depending on various settings our testphone, Samsung Galaxy s3, crashes right at launch when we do debug on the phone in FlashDevelop. Actually we are debugging with a release so we don't get any traces, but all the same we are running the app on the phone. For instance if we set <aspectRatio>landscape</aspectRatio> <autoOrients>true</autoOrients> and hold the phone in landscape orientation when we start the debug, then the app runs as should be. However if we with the same settings hold the phone in portrait orientation when starting the debug, then the app crashes on startup. The exact same happens if we set auto orient to false and/or remove the Aspect Ratio. It also doesn't matter what we set stage.scaleMode to in my Main class... or at least i've not been able to figure out any combo with aspectRatio/autoOrients/ that works. I read something at a glance here at Stack Overflow in another thread about something that seemed similar was a bug in earlier Android versions, but that it should be fixed in ICS (which we have on the test devices). And I may also have seen something at a glance about it being related to the virtual keyboard and to add some code in the xml Manifest at various actions.. Does anyone have a clue for sure please? :-) edit: The App is built to only ever be shown in Landscape orientation. It can't work in portrait. Reference this http://stackoverflow.com/questions/10679255/android-memory-leak-no-static-variables/10679370#10679370 and this http://stackoverflow.com/questions/456211/activity-restart-on-rotation-android So far for us it seems the bad guy is stage.addEventListener(Event.DEACTIVATE, someFunc); private function someFunc(e:Event):void { NativeApplication.nativeApplication.exit(); } This gets called for a reason we don't know as of yet, so by removing it the app stops crashing. I have also encountered same problem; app crashes everytime orientation changes. What I did was very simple: FIRST, create two folders for your layout: layout layout-land Then, put your portait layouts in layout and landscape layouts in layout-land. This will do the trick. Hope you can get idea from my experience. Ah well that might work somehow :-) However we're only using the landscape orientation, so it really shouldn't rotate to portrait at all....
common-pile/stackexchange_filtered
Tomcat + MySQL docker container outputting utf8 text with wrong encoding Experiencing incorrect encoding on UTF8 text output from a tomcat:8.0 container retrieved from a mysql:5.6 container. Connecting to the MySQL container directly and querying on the shell proves the text is stored in the database correctly. Also UTF8 content within templates is output from the tomcat container fine. The JDBC connector string reads: nfc.jdbc.mysql.url=jdbc:mysql://mysql:3306/mydatabase?autoReconnect=yes&useUnicode=yes&characterEncoding=UTF-8 Here's the tomcat Dockerfile I'm using: FROM tomcat:8.0 RUN apt-get update && \ apt-get -y install libmysql-java RUN echo 'CLASSPATH=/usr/share/java/mysql.jar' >> /usr/local/tomcat/bin/setenv.sh And the MySQL Dockerfile: FROM mysql:5.6 RUN { \ echo '[mysqld]'; \ echo 'character-set-server = utf8'; \ echo 'collation-server = utf8_unicode_ci'; \ echo '[client]'; \ echo 'default-character-set=utf8'; \ echo '[mysql]'; \ echo 'default-character-set=utf8'; \ } > /etc/mysql/conf.d/charset.cnf VOLUME /var/lib/mysql The Tomcat run command is: docker run \ --rm \ --name tomcat-server \ --volume $(pwd)/../../webapp:/usr/local/tomcat/webapps/mywebapp \ --volume $(pwd)/../../tomcat-users.xml:/usr/local/tomcat/conf/tomcat-users.xml:ro \ --link mysql-server:mysql \ --publish 8088:8080 \ --tty \ --interactive \ tomcat-server I'm using the same MySQL image to provide content to other docker container web servers (python/django) which is being pulled and output with the correct encoding. I have no real understanding of the contents of the tomcat webapp and don't really know Java. The developer has demonstrated the application running from a Windows server producing the correctly encoded data, however they have no understanding of Docker, and so we're currently spinning our wheels not getting anywhere! You have an UTF-8 configured linux environment on one side and a Java developer that uses Windows on the other. The default encoding under Windows is CP-1252. Every Java component including your server is by default using system encoding when not explicitly set to UTF-8. Every property-, database-, source-file can be CP when the IDE if not configured right. So where actually breaks your encoding? Where do you enter the character into the system and where do you see a broken character? From UI? Property file? External services? A database script? The developer also advised on the JDBC connection string component characterEncoding=UTF-8 so it they must also expect the MySQL database to provide UTF8 encoded data. The point at which content is broken is when viewing the web interface, the sidebar menu items are retrieved from the database and presented seemingly as is. The output of these sidebar menu items is incorrectly encoded in contrast to the db table whose contents output correctly via MySQL shell. The tomcat container is not configured correctly, according to the comments in https://registry.hub.docker.com/_/tomcat/ the container is not configured to UTF-8 by default. You will have to build your own docker image extending the default tomcat container and appropriately set the Encoding. Someone wrote that RUN locale-gen en_US.UTF-8 ENV LANG en_US.UTF-8 ENV LANGUAGE en_US:en ENV LC_ALL en_US.UTF-8 should work. Thanks for the link. I did as suggested and rebuilt the Tomcat Dockerfile using Ubuntu:14.04 base with the language env vars but no change. I also used http://www.tutorialspoint.com/jsp/jsp_database_access.htm to write a basic JDBC query and output to ensure the webapp wasn't doing anything funny and it that too reproduced the problem. I tried both the tomcat8 from apache as per the tomcat8 Dockerfile, as well as tomcat7 from ubuntu repo, no change. Well someone isn't taking the medicine and denies UTF-8. Try this cli for accessing the database and query the database: http://quuxo.com/products/jdbctool/. Start the cli with java -Dfile.encoding=UTF-8. Hope the MySQL is at least working right and the tables are all in UTF-8. Thanks, I've already been tinkering with this; CLASSPATH=/usr/share/java/mysql.jar bin/jdbctool -u root -p pass jdbc:mysql://mysql:3306/nfcapi?characterEncoding=UTF-8 connects and queries, but the encoding is still bad. Also the JDBC string won't accept multiple parameters, anything from & onwards causes an error, e.g. ?characterEncoding=UTF-8&useUnicode=yes, and visa versa. How might I run this via java binary though? Thanks again. Well at least it's narrowed down between the database and JDBC. You sure your database, tables and columns are really in UTF-8? According to http://stackoverflow.com/a/1049958/698289 the database/table/column are all utf8 Very good, then take squirrel sql. A nice SQL client written in java. I have good experience with it but currently not installed. http://squirrel-sql.sourceforge.net/ Then take this to access your data with squirrel sql in a proper utf-8 way: http://zaharov.info/notes/3_316_1.html Looks like SQuirreL is also returning wrongly encoded data. Also, I tried injecting chinese characters into the table from within SQuirreL and those characters output as ???? when viewed from the MySQL client shell (the only client so far able to return original text as desired). The injected data returns to SQuirreL as it was input however. Sorry, I do not understand that sentence. Do we now have two applications both correctly configured for UTF-8? And the encoding still breaks? Sorry, let me clarify with a single sample string 综合管理, from the original data import from the developer, MySQL CLI client returns correct text 综合管理, but Tomcat/SQuirreL return weird text e.g. 综åˆç®¡ç†. However if I insert via SQuirreL the text 综合管理, then it outputs fine in SQuirreL/Tomcat, but instead retrieves strangely in MySQL as simply ????. Now who is not running in UTF-8? As far as I can tell, all are configured to do so, so I'm very confused as to which one is lying. I can't see any way of telling any of the clients to report their effective setting. I'm wondering if the character replacements of 综åˆç®¡ç† or ???? are telling in this situation? I've also analyzed the original SQL import, it is definitely UTF8 encoded. Loading it into a text editor with ISO-8859-1 encoding shows the same 综åˆç®¡ç† text as JDBC clients are showing. Im lost but i have read this: utf8mb4 is MySQL's UTF-8. If you use utf8 in MySQL, you're missing out on an important portion of Unicode (the astral symbols). Switch everything, tables, database, to utf8mb4 or you may lose data. Can you please check the database again reading this? https://mathiasbynens.be/notes/mysql-utf8mb4 They say full chinese does not work in mysql utf-8 Thanks very much for that article. In fact the solution to everything seems to be setting [mysqld] character-set-client-handshake = FALSE. With that, even the original utf8 is now working, no need for utf8mb4. For the record, utf8mb4 WITHOUT setting the handshake var did not help. Feel free to post an answer and I'll accept :) I assume the error is that jdbc says UTF-8 and mysql has internally utf8? Well, running SHOW VARIABLES LIKE '%char%'; reveals that even MySQL CLI is not respecting the server charset in terms of result/client charset. But setting character-set-client-handshake = FALSE appears to force the client to apply the server defined charset across all other charset variables.
common-pile/stackexchange_filtered
openx banner delivery How do I display a single banner on a page by using its ID with OpenX? I cannot get banners to display without using zones. From a quick reading of the OpenX Documentation, it appears that a banner must be associated with a zone in order to be provided with the invocation code. You want to look at http://www.openx.org/support/direct-selection to create a special invocation code that sidesteps publishers and zones.
common-pile/stackexchange_filtered
Tab Navigator in a Title window : issue I am adding a tab navigator to a title window here. Once the title window is closed, it can be reopened using the button.But on opening the title window second time in this manner ,the content of the children of the Tab navigator(here, a label) is not visible. <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()" <mx:TabNavigator x="68" y="68" width="200" height="200" id="tabNavig" historyManagementEnabled="false"> </mx:TabNavigator> <mx:Script> <![CDATA[ import mx.events.CloseEvent; import mx.managers.PopUpManager; public function init():void{ tabNavig.removeAllChildren(); tabNavig.addChild(canvas1); tabNavig.addChild(canvas2); tabNavig.addChild(canvas3); expenseTitle.showCloseButton = true; expenseTitle.addChild(tabNavig); PopUpManager.addPopUp(expenseTitle,this,false); expenseTitle.addEventListener(CloseEvent.CLOSE,titleWindow_close); } private function titleWindow_close(evt:CloseEvent):void { expenseTitle.removeAllChildren(); PopUpManager.removePopUp(expenseTitle); } ]]> </mx:Script> <mx:TitleWindow id="expenseTitle" > </mx:TitleWindow> <mx:Canvas id="canvas1" x="476" y="117" width="200" height="200" > <mx:Label x="64" y="93" text="Label1"/> </mx:Canvas> <mx:Canvas id="canvas2" x="244" y="310" width="200" height="200" > <mx:Label x="111.5" y="29" text="Label2"/> </mx:Canvas> <mx:Canvas id="canvas3" x="697" y="117" width="200" height="200" > <mx:Label x="59" y="79" text="Label3"/> </mx:Canvas> <mx:Button x="78" y="310" label="Button" click="init()"/> </mx:Application> The structure of your MXML is completely wrong. You need to keep MXML components (e.g. a TitleWindow that you plan on using as a popup) separate from your main application markup. For example, create a separate MXML component, called MyForm.mxml. This component should be a TitleWindow with a Tab Navigator. The Tab Navigator should have the 3 Canvas components as children. Then, in your main application logic, the Button should launch the pop up, MyForm.mxml like so: var form:MyForm = MyForm(PopUpManager.createPopUp(this, MyForm, true)); PopUpManager.centerPopUp(MyForm); Finally, in your MyForm.mxml component, add the event listener for closing. The method should only need to call: PopUpManager.removePopUp(this);
common-pile/stackexchange_filtered
How to politely ask coworker to check their results? I work with a fairly large team across departments. One of my coworkers, whom I've never met in person, is polite and responsive. However, the data that they send to me for analysis is rarely accurate. The problems include out-of-date spreadsheets, data for the wrong projects, and most often data that is just wrong (numbers aren't correct for whatever reason). I generally like this person but their requests take me days instead of hours since I have to correct my results so often - twice on average and on this task 3-4 times. I'm not worried about budgeting since their project budgets are high but re-doing my work constantly is irritating and takes me away from other tasks. How can I politely ask this coworker to ensure that they're sending me the correct data? Edit: I should add that I don't have any way of verifying this data. Think of someone reporting rainfall from their back yard - but they don't tell me where their yard is. So the only way that I know something is wrong is when they tell me that they made a mistake and I need to do the analysis again. Edit2: I requested a double-check of their data and they assured me that they triple-checked it. However, they sent me an email this morning correcting their triple-checked results. Why can't you just highlight errors and send it back for correction/clarification? Good question. I don't know where the errors are. I get a list of numbers that represent chemical concentrations from specific wells, so I don't have a way of verifying if data is correct. Then how do you know the data is wrong? Out of scope? They tell me that they made a mistake... Such as using outdated data or giving me the "wrong values". How much time elapses between the time your colleague sends you the results and the time he send the updated/corrected results? Is the elapsed time constant (e.g. he always send you the correct data 5 hours later)? I think it depends on when they review my work. Sometimes it takes an hour, other times several weeks. @wakanda_official_tourism, You can tell politely him that every time he makes a mistake that causes you to re-do your analysis it takes lots of time and may cause a delay for your whole team. If his mistakes impact your delivery timeline, then you should let your manager know. What is causing them to revisit it over and over? Are they OCD and keep re-doing the work a dozen times, or do they have some other provider upstream modifying data the same way? Why are they not moving to another task after they do it the one time? @DanielR.Collins that's a good question and I have no idea. The datasets are based on elevations, which are determined from values obtained in the field. So I don't know where the changes are coming from. Thanks. You (maybe in cooperation with your manager) should ask. Suggest that you want to learn more about their process, and ask if they could walk you through it a few times. They may find their errors more easily if they have to explain their process to someone. Think "rubber duck debugging"… they may become more aware of what they are doing and thus catch the errors. Just request that they doublecheck their data before submitting it to you. Rinse and repeat every time. This gives you some metrics to cover your back and show what is happening. If it's a persistent problem I'd ask my manager what should be done. Theoretically the manager will then sort it out, or at least give a guideline. You shouldn't engage in a potential conflict with a colleague, it can be handled easily enough at a higher level. The problems include out-of-date spreadsheets, data for the wrong projects, and most often data that is just wrong (numbers aren't correct for whatever reason). Is it clear to them what data they should be using? In a past job, it was quite common for someone on the finance team to ask a dev to write some SQL for a report. The problem was that they were not always clear on what data the report should be run. For example, the request "please get me summary data for city usage" could be interpreted to mean any number of things, many of which hinged on how you defined "city." Did they mean the city, as in the municipal government? Did they mean the city, as in the municipal public works business unit inside the city (if often meant this). I worked for the city, but not for the city as a business unit. Did they mean the city, as in all the units in the city? Which city did they mean? Sometimes it referred to all the cities and they wanted a summary of each city we operated in. Often the Finance team had updated data. The problem was that we needed to be informed of that for the reporting to work. It did not always happen. It is hard to say if this is the problem you face, but in my example it would have been no use telling the engineer to check his work, as the problem was what work should be done and which data sources should be used, not anything wrong with the code itself.
common-pile/stackexchange_filtered
Material UI Select not showing label correctly I am trying to show my label for Select with material UI but it's showing option value instead of label... here is the image of it: here is my code base: const [inputFields, setInputFields] = useState([ { id: uuidv4(), relationship: '', initiatorMessage: '', email: '' }]); inputFields?.map(inputField => { return ( ... <FormControl className={classes.formControl} id="relationship-select" select name="relationship" inputprops={{ classes: { root: classes.root, }, }} > <Select name="relationship" label="relationship" value={inputField.relationship} onChange={e => handleChangeInput(inputField.id, e)} inputProps={{ classes: { root: classes.root, }, }} > {relationships.map(option => ( <MenuItem key={option.value} value={option.value}> {option.value} </MenuItem> ))} </Select> </FormControl> }) } I want it to show relationship but it's showing my option value.. Could you also post the code where you set inputField and relationships? Sure I will add it in right now @AhmetEmreKılınç added According to this code, in the first element of the inputFields, parent should not be shown. There might be a problem where you handle add another recipient button. Can you also post that code too?
common-pile/stackexchange_filtered
Program for trigrams I'm trying to make a program in python which is supposed to output the frequency of those trigrams from examens.txt that occur more than 3 times. The uppercase and lowercase of the words and special characters is to be ignored, and the output should be sorted by frequency. My teacher told me that i have to change only two lines! But im getting python blind. For me the code looks correct, but it doesent work. with open("examen.txt") as f: data = f.read() text = data.replace("\xad", "") words = [] for word in data.lower().split(): word = word.strip("‚‘!,.:«»-()'_#-–„“*?") if word != "": if not word[-1].isalnum(): print(repr(word)) words.append(word) trigrams = {} for i in range(len(words)): word = words[i] nextword = words[i + 1] nextnextword = words[i + 2] key = (word, nextword, nextnextword) trigrams[key] = trigrams.get(key, 0) + 1 l = list(trigrams.items()) l.sort(key=lambda x: (x[1], x[0])) l.reverse() for key, count in trigrams: if count < 3: break word = key[0] nextword = key[1] nextnextword = key[2] print(word, nextword, nextnextword, count) Have you tried executing it, do any errors show up? What does the program output? How does this differ from your expectation? A sample of your examens.txt would also be helpful and a much more detailed explanation of does not work. Does it crash? Does it produce wrong results? As a first hint, str.strip() returns a copy of the string with the leading and trailing characters removed. So all special chars inside words will stay. As an alternative, you could use str.translate(str.maketrans("", "", "‚‘!,.:«»-()'_#-–„“*?"). Also list.sort() can be used with the argument reverse=True. There are actually 3 issues with your code. Revisit range(len(words)) which results into an IndexError. Also look into iteration over dictionary keys/values and break vs. continue. You traverse too deep into words when you build the trigrams and you don't print the right data structure in the final loop. Changing just two lines I would write - with open("examen.txt") as f: data = f.read() text = data.replace("\xad", "") words = [] for word in data.lower().split(): word = word.strip("‚‘!,.:«»-()'_#-–„“*?") if word != "": if not word[-1].isalnum(): print(repr(word)) words.append(word) trigrams = {} for i in range(len(words) - 2): word = words[i] nextword = words[i + 1] nextnextword = words[i + 2] key = (word, nextword, nextnextword) trigrams[key] = trigrams.get(key, 0) + 1 l = list(trigrams.items()) l.sort(key=lambda x: (x[1], x[0])) l.reverse() for key, count in l: if count < 3: continue word = key[0] nextword = key[1] nextnextword = key[2] print(word, nextword, nextnextword, count)
common-pile/stackexchange_filtered
Cannot make remote connection with PyMySQL (pymysql.err.InternalError: Packet sequence number wrong) update: Problem solved, solution posted below I am new to the process of making remote database connections, but it seems that there tends not to be an obvious solution for this error. pymysql.err.InternalError: Packet sequence number wrong - got 80 expected 0 arises when attempting to make the following pymysql connection I'm running MacOS 10.12.5, Python 2.7.10 in PyCharm (also tried with Terminal), and PyMySQL 0.7.11 (also tried 0.7.9) update: also tried on Windows 10, Python 2.7.13 with the same result The database is hosted on cPanel. Perhaps there are additional settings to change before I can connect. The connecting user has full privileges. My IP was added to the host "access" list. other notes: As might be expected, if the port number or host IP is randomly changed, it immediately refuses the connection. Otherwise, it takes about 30 seconds before the 'packet sequence' error to arise. import pymysql.cursors import pymysql connection = pymysql.connect(host = hostIPaddress, port = 2083, user = username, passwd = password, db = dbName, charset = 'utf8mb4', # also tried 'utf8' cursorclass=pymysql.cursors.DictCursor) While the port 2083 is used by the host, each database uses the default port 3306 in this case. When tested with 3306, access was denied until I added the denied IP to the host "access" list in Remote MySQL on cPanel.
common-pile/stackexchange_filtered
C++: How to add a library in Netbeans (DarkGDK + DirectX SDK) I'm trying to learn how to make games with DarkGDK. But I have to write in Visual Studio. I don't like Visual Studio. Its suggestions (Ctrl-Space for Completion) are bad (in my opinion) and the compiler is broken (See my previous questions). So I want to migrate to Netbeans, with MSys and MinGW. But I'm not able to use the DarkGDK library in Netbeans. I added two include folders: C:\Program Files\The Game Creators\Dark GDK\Include C:\Program Files\Microsoft DirectX SDK (August 2007)\Include After adding this include directories, I can #include <DarkGDK.h>. But he shows a warning: "There are unresolved includes inside <DarkGDK.h>" And when I try to compile: main.cpp:9:21: warning: DarkGDK.h: No such file or directory In Visual Studio are Include files and Library files. And in Netbeans, there is only Include Directories when I go to Tools -> Options -> C/C++ -> Code Assistance. So, my question is: "How can I add the Library files in Netbeans"? Or does any-one did this yet and knows how to do this. Personally I found the include directories in Tools -> Options don't work. You need to right click on your project and go to properties -> C++ Compiler and add your include directories. Then from properties -> Linker to add your library directories and libraries. Thanks for aswering, but it seems unpossible to use DarkGDK in another IDE.
common-pile/stackexchange_filtered
Visual calculation puzzle Below are some objects and numbers. Try figure out what they represent and finally replace the question mark. It is 117649 because: 7 is the value for g, which is the first letter of "green", the sum of the values of the letters in the word is 49, and "3" is for "cube", 49^3=117649. Just like "19" is for "square" refering to squaring "[red]" and "[yellow]" Yes this is correct :)
common-pile/stackexchange_filtered
Meshing of polygons I need to generate a sequence of increasingly denser high-quality triangular meshes for some pentagons in MATLAB. I want to supply as my input The coordinates of the 5 vertices of the pentagon The desired (approximate) mesh-node spacing or the number of mesh-faces in the output mesh. The output should be A high-quality mesh The list of points on the mesh-boundary (ie the boundary of the pentagon) Are there any softwares to do this, preferably in MATLAB or elsewhere? Triangular or quadrilateral meshes? @ Bill Barth Triangular meshes. Made the edit http://geuz.org/gmsh/ This program is called gmsh it should be able to do exactly what your looking for. I recently posted an answer similar to this which can be found here (http://tinyurl.com/n6avzsz). Once you have the program downloaded the way it works is by coding the .geo file. You can do this by hand, or code it into the .geo file. See this post for a sample of that (http://tinyurl.com/lme57dk). Good luck! There is also Jonathan Shewchuck's triangle package that should be able to do the same for you. If you have the MATLAB PDE Toolbox it has the necessary tools built in.
common-pile/stackexchange_filtered
Implementing an application using angular and angular material cdk drag and drop I'm trying to implement an app where images can be dragged and dropped and change position with each other freely, without overlapping. I am using play.grafana.org but I can't seem to tackle this problem. Any ideas? Using the new Angular CDK this should be straight forward. A wrapper div using CSS flex will make your images float inside. Add the cdkDrag on the elements containing the images will give you possibility to drag them around. To reorganize the position use the moveItemInArray-function in the drop-event. The CDK got examples that you can follow and is almost what you are looking for, I guess..
common-pile/stackexchange_filtered
TypeError when trying to open a workbook using openpyxl I'm trying to use openpyxl to open and modify an existing excel workbook, but I can't even open the file without getting an error. from openpyxl import load_workbook ws = load_workbook('PO-Copy.xlsx') I get a long TypeError as a result: Traceback (most recent call last): File "<module1>", line 6, in <module> File "C:\Python27\Lib\site-packages\openpyxl\reader\excel.py", line 151, in load_workbook _load_workbook(wb, archive, filename, read_only, keep_vba) File "C:\Python27\Lib\site-packages\openpyxl\reader\excel.py", line 224, in _load_workbook keep_vba=keep_vba) File "C:\Python27\Lib\site-packages\openpyxl\reader\worksheet.py", line 308, in read_worksheet fast_parse(ws, xml_source, shared_strings, style_table, color_index) File "C:\Python27\Lib\site-packages\openpyxl\reader\worksheet.py", line 296, in fast_parse parser.parse() File "C:\Python27\Lib\site-packages\openpyxl\reader\worksheet.py", line 84, in parse dispatcher[tag_name](element) File "C:\Python27\Lib\site-packages\openpyxl\reader\worksheet.py", line 282, in parse_data_validation dv = parser(tag) File "C:\Python27\Lib\site-packages\openpyxl\worksheet\datavalidation.py", line 179, in parser dv = DataValidation(**element.attrib) TypeError: __init__() got an unexpected keyword argument 'errorStyle' Has anyone else ran into this error? is there a fix I can use to keep going? The ability to read DataValidation in existing files was added in openpyxl 2.1 but was limited to what DataValidation in Python supported. Work has started on supporting DataValidation fully and is available in the 2.2 branch at https://bitbucket.org/habub68/openpyxl I downloaded & installed the 2.2 version here, but that didn't work. However, the 2.0 version did, so that's what I'll go with. Thanks! 2.0 completely ignores DataValidations so go with that if you don't need them. If we can finish up the work soonish it will get backported to a 2.1 patch release. Can you file a bug report? Helps keep track of it. I don't know if installing from a download actually works. Pardon my ignorance, but what is the correct way to do it? I know of no other way to gain the functionality of openpyxl other then downloading and installing onto the machine. You need to do a checkout of the source with Mercurial or SourceTree and then switch to the 2.2 branch and install in development mode python setup.py develop in a virtual environment to avoid your existing Python being affected. The download contains an archive of the whole project but at the current state (2.1 release). We do not recommend using this to install the library ever. As the documentation says openpyxl should be installed using pip install openpyxl We now have a bug that is related: https://bitbucket.org/openpyxl/openpyxl/issue/366/error-datavalidation-and-unicode-symbols
common-pile/stackexchange_filtered
MongoDB document delete and fragmentation I've a MongoDB collection that works like a queue: new documents are insert and old documents (after 60days) are removed. I can see a rapid grown of the datafile size, too rapid. I can be reasonable because we remove old data after 60 days, but I was thinking, are my deletes effective without execute the defragmentation? (in few words, what's a good way to manage disk space in MongoDB) What is a correct defragment / clean collection politics? It's a production database and version is 2.6.9 thanks. Maybe the following conversation can help you some more: http://dba.stackexchange.com/questions/106736/why-does-mongodb-extend-filesize-if-it-is-already-5x-larger-than-datasize Basicaly : 1. for 100% fixed collection size, use capped collection 2. use latest version of Mongodb where space is reused as good as possible 3. do some maintenance every few weeks (compact/repair/...) 4. if there is constant timeout on the function that is responsible on allocating free space 5. some more rare issues mentioned in that article What specific version of MongoDB are you using (and if >3.0, what storage engine)? Updated question with DB version (2.6.9) Capped collections are limited to size and not to date so you might lose data if you don't do the maths well. What is your average document size? Reasons for unexpected data growth of data files. "Data fragmentation" and data file preallocation When a document is deleted, it's space is used right away if the new document fits into that space. Let's say you delete a document which takes 1kb of disk space and a new document requiring 0.9 Kb of disk space is synced to disk, then the first free space (the deleted document's in our example) will be used. Now let's assume the new document would need 1.1k. In a worst case scenario, a new datafile of 2GB had to be provisioned although only 0.1kb of space was missing. The reasons for datafiles being preallocated are rather good ones, btw: it would simply take too long during a disk sync. Padding When a document is written, some space is added to allow the document grow in size without triggering a rather expensive document migration each time. Documents are migrated when they do not fit into their position in the data file any more since Documents are never fragmented So if your documents grow, they have to be migrated and a new padding is applied, it might well be that millions of places in the data files would provide enough space for a 1k document, but still a new data file has to be preallocated. Another "problem" is the way padding is calculated. As of MongoDB 2.6, documents are by default by using power of 2 sizes. So let's assume your document is 513 bytes in size. However, since the next power of 2 would be 1kb, almost half of the space allocated for the document would not be in use until it grows in size. So in a worst case scenario, half of the space allocated for your data files -1 byte might be "wasted". Increased usage Your application might well be getting momentum and there simply is more data stored than you expect. Congratulations! What to do Usually, one of three ways of dealing with data file growth is suggested. the compact command the repair command Forcing a resync from replica set members I'll go over them with their Pros and Cons from my point of view and explain why I think all of them are improper ways of dealing with that data file growth. The compact command How it works The compact command defragments the data files of a collection. It does it by creating a new data file of 2GB and moves the documents back and forth until there are no gaps between the documents any more. Pros The compact command is relatively fast when compared to the other solutions. The defragmentation helps a bit to prevent unnecessary data file preallocation. Cons The database containing the target collection is locked during the execution. No disk space is reclaimed You really should have a backup of the target collection before using the compact command. So in order to have said backup, you need to over provision your disks with 2Gb (the additional data file) plus the size of your largest collection (for the backup). But with over provisioned disks, space will not be a problem in the first place. It doesn't help at all when space really is a problem: if you are in a critical situation, the problems detailed above prevent you from using the compact command. Why I don't think it is a proper solution Well, it's kind of obvious - you lock your database, which means downtime. For really large databases, this means a lot of downtime, and all this for the relatively small gain of potentially preventing one or two data files to be created (which means 4Gb disk space at max). The repairDatabase command How it works Simplified, the repairDatabase command creates a second instance of your database, iterates over the documents in the original database, verifies them and writes them into the new database in consecutive order. In the last step, the old database is deleted and the new database is renamed. Pros With a proper planning, you can reclaim disk space with very little downtime, since the repairDatabase command can be run against secondaries. So you can do the following Run the repairDatabase command against all secondaries Have the primary step down. This might lead to 3-5 seconds of downtime during the election of the new primary. Run the repairDatabase command against the recently stepped down primary Sounds nice, right? However, there a huge Cons You need to massively over provision your disks, since basically a copy of your database is made. So now let's assume you run this command against a database which is in an optimal state. So to make sure the command is successfully executed you need at least the same amount of free disk space as your database uses when you issue the repair command. Since the repair command is potentially even more critical than the compact command, you should make a backup beforehand or use the backupOriginalFiles option. Why I don't think it is a proper solution The cons detailed above show that you have to over provision your disks by at least 200% of your payload data. With that massive amount of disk space, you would not have a problem in the first place. Forcing a resync from replica set members How it works You shut down a secondary, delete its data files and restart it. The node notices that it is basically a new member added to a replica set and forces an initial sync with the replica set. Since the initial resync is document oriented, only necessary datafiles are allocated, potentially freeing formerly used disk space. Like with the repair command, you do this for all secondaries (of course one after another), have the primary step down and delete its datafiles and let it resync. Pros You do not need to over provision the disks of an individual node There is just very little downtime It is a relatively straightforward process Cons This process takes a while, may well have some impact on performance and reduces your planned level of redundancy. Let me explain this in a bit more detail: When planning a replica set, you choose how many replicas you want to have, ranging from one (two data bearing nodes plus an arbiter) to 50 as the time of this writing. You have a good reason for this redundancy, whatever it may be. When arbitrarily shutting down replica set members in order to reclaim disk space, you effectively reduce or even eliminate failover capabilities. So it is safe to say that in order to keep your desired level of redundancy during the resync, you need one additional node to maintain it. Why I don't think it is a proper solution Put plainly: putting half the money you spend for the additional node into additional disk space should solve any space problem in the first place. However, this might not be in your case (although that might well be through under dimensioned hardware) and thus the resync might be a viable solution in some cases Ok, smarty pants: What to do? Frankly, from my experience, the need of reclaiming disk space is a sure sign of a badly planned cluster. Granted, MongoDB is not the most efficient when it comes to disk space consumption, but after a while, it levels out. So when MongoDB constantly adds new datafiles, you can be sure that you simply need more disk space. This can be either achieved through vertical or horizontal scaling. If you still can scale vertically and get an adequate bang for your buck, your hardware was underprovisioned until now. Go for it, problem solved! If you already get the most bang for the buck and the size of your data (not only the number of your data files) constantly grows, it is time to scale horizontally, read to shard your cluster. As a rule of thumb: when more than 80% of your disk space is used and the size of your data didn't show a massive spike but is constantly growing, I'd add a shard or start sharding. It requires some experience and knowledge to determine the exact threshold and how to do it exactly is out of scope even for this long answer. With this approach, the decision when to shard is based on emprirical information, is started early enough to prevent serious problems, it reduces maintenance effort and risks and it enables you to scale properly. One last word: Often people say that adding a shard is too expensive or they are not up to paying three config servers in addition to the data bearing nodes and start to shard their data manually. The reason for that is plainly wrong calculation of their own prices and a wrong understanding of how to do things sustainably. In the long run, it's going to bite you in the neck to reinvent the wheel. Sharding won't solve the fragmentation issue. In fact the chunk moves will create additional fragmentation to source shard. In the end one of the methods that removes frag should be applied. @Antonis Fragmentation isn't really an issue at all. It only becomes an issue when disk space is getting really tight or spinning disks are used (which is discouraged for good reasons), hence the question was narrowed down to a "good way to among disk space in MongoDB". For the reasons above, using repair or compact really isn't a viable solution. To shorten my answer into a single sentence and make my approach a bit more clear: When using MongoDB you should take data file fragmentation into account when planning the dimensions of your hardware, with all the consequences. Mongo is using MM files (at least in v2.6) and the disk fragmentation will cause fragmentation in RAM as well. @Antonis Well, that is correct. But: Fragmented Memory is hardly an issue. We are talking of access times to the random access memory of somewhere in the range of 75 nanoseconds (give and take). The process of reading the documents from disk (mmapped basically means that pointers to the individual documents are stored in RAM) will take orders of magnitude (around 5 x 102 for even the fastest (and extremely expensive) SSDs. Mind you, a nanosecond is a billionth of a second - and the response time of an average human is 100,000,000 nanoseconds. Plenty of time. I am not disagreeing with you I am just concern about the memory footprint. With fragmentation you load unnecessary stuff to RAM and you might remove frequently access data. @Antonis HM, fragmented or not, the working set keeps the same. Iirc, indices have preference, then the 1MB stack/connection and the remaining RAM is filled with the working set, with documents being evicted using LRU if necessary. So, only loaded documents should be in the working set from the beginning, with the most used documents staying there. I can't see where unnecessary documents should be loaded into RAM (much less stay there). Nah, the memory footprint seems rather optimal for me. The best approach is to use a 3 member replica set. Periodically you will stop one of the secondaries, wipe the data directory and start it. The secondary will begin an initial sync which will remove all fragmentation since it will re-write all datafiles from scratch. Then do the same for the other secondary and perform a stepdown. The stepdown will require 15 secs of downtime or even less and one of the defragmented secondaries will become the new primary. In the end do an initial sync for the ex-primary. When a secondary is removed from the replica set, there should not be any downtime at all. Its not removed from the replica set (like rs.remove), its shutdown so no downtime will occur. The only downtime is during stepdown Primary until a new primary gets elected, but can handled gracefully from the driver.
common-pile/stackexchange_filtered
Why solving this limit like this is wrong and how to correctly solve it I am taking a Calculus 1 class and one exercise asks to solve the following limit: $$ \lim_{x \to 0} \frac{\sin(\tan x) - \tan(\sin x)}{\arcsin(\arctan x) - \arctan(\arcsin x)} $$ Seeing as both parts of the division go to $0$, I decided to try L'Hopital, but after deriving everything twice (and still getting $\frac{0}{0}$) I gave up (it didn't seem like it would get me anywhere). After that I tried the following: $$ g(x) = \arcsin(\arctan x) - \arctan(\arcsin x) $$ $$ \lim_{x \to 0} \frac{\sin(\tan x)}{g(x)} - \frac{\tan (\sin x)}{g(x)} $$ $$ \lim_{x \to 0} \frac{\sin(\tan x)}{\tan x} \frac{\tan x}{g(x)} - \frac{\tan (\sin x)}{\sin x} \frac{\sin x}{g(x)} $$ And since $\lim_{x \to 0} \frac{\sin(\tan x)}{\tan x} = 1$ and $\lim_{x \to 0} \frac{\tan (\sin x)}{\sin x} = 1$: $$ \lim_{x \to 0} \frac{\tan x}{g(x)} - \frac{\sin x}{g(x)} $$ $$ \lim_{x \to 0} \frac{\tan x}{x} \frac{x}{g(x)} - \frac{\sin x}{x} \frac{x}{g(x)} $$ $$ \lim_{x \to 0} \frac{x}{g(x)} - \frac{x}{g(x)} = \lim_{x \to 0} 0 = 0 $$ But the bad part is that this is wrong, the answer should be 1 and not 0. I have no clue where I went wrong, and worse still, I have no clue how to solve this exercise another way. Where did I go wrong? How could I solve this? Here's a video where professor Borcherds discuss this limit https://youtu.be/lov2nhJdPqw Without those replacements by $1$, the limit would be $$\lim_{x\to0}\left[\frac{\sin(\operatorname{tg}(x))}{\operatorname{tg}(x)}\cdot\frac{\operatorname{tg}(x)}x-\frac{\operatorname{tg}(\sin(x))}{\sin(x)}\cdot\frac{\sin(x)}x\right]\frac{x}{g(x)}$$ The difference tends to $0$, but $\frac x{g(x)}$ tends to $-\infty$ when $x\to 0$. Compose Taylor series from inside to outside Refer to the duplicate here https://math.stackexchange.com/q/80364
common-pile/stackexchange_filtered
Regex Only one special character at a time from allowed special characters Javascript I want to allow 3 characters 1st Underscore (_) , 2nd hyphen (-) 3rd Dot (.) but i want to put conditions that only one character is allowed at a time from all of them, and also only one time. e.g allowed usernames = abc.def , abc-def , abc_def not allowed usernames = abc.de.f alert here(only one special character is allowed in a username) not allowed usernames = abc.de-f , abc.de_f , ab-cd_ef What should i do. There are lots of resources for learning about regular expressions. Give it a try yourself and come back and post some code when you have issues more specific than "how do I do it?" So alpha-characters a hyphen, underscore, or dot, then more alpha characters? ^[a-zA-Z]+[-._][a-zA-Z]+$ @chris85 I am sorry i forgot to mention, letters and numbers both allowed @AtifSheikh Okay so add 0-9 with the alpha character classes. Does that work? @chris85 Yes i got and i did it but there is an issue with that, if i put one dot, it gives an error, but if i put more than one dot then it works. i am using this code: 'if(/^[a-zA-Z0-9]+[-._][a-zA-Z0-9]+$/.test(x)){ document.getElementById("errmsg").innerHTML = "Only One - _ or . can be used in Usernames"; return false; }' @AtifSheikh Can you provide samples? Try /^[a-z]*[-._]?[a-z]*$/ var tests = ['abc.def', 'abc-def', 'abc_def', 'abc.de.f','abc.de-f' , 'abc.de_f', 'ab-cd_ef']; $.each(tests, function(a,b) { $('body').append('<div>' + b + ' = ' + regIt(b) + '</div>'); }); function regIt(str) { return /^[a-z]*[-._]?[a-z]*$/.test(str); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> The dot doesn't need to be escaped in the character class. If you put - first it also doesn't need to be escaped. This also will allow for empty usernames. @chris85 , thank you @br3t it worked perfectly fine what i was looking for. i just used if(!/^[a-zA-Z0-9][-._]?[a-zA-Z0-9]$/.test(x)) Thanks br3t and chris85. Love you seniors :) ^[a-z]*([-._]?)(?:[a-z]|\1)*$ This regex will match letters until it reaches the end of the string. If it reaches a symbol (- . or _) it will store that symbol as group 1, and keep matching for letters or that same symbol until the end of the string. The following are matching examples: an empty string _something something-something foo_bar_baz foo. And here are some invalid strings: my_file.txt alpha.bravo_charlie not-working_ OP wants only one special character. foo_bar_baz is not allowed because there are 2 underscores. @Toto Indeed, I misread. br3t's answer is the right one want then.
common-pile/stackexchange_filtered
PHP Zip method - need advice http://pastebin.com/AreCLL5W Could anyone help me with this, I've been trying all day to get a file to compress for email but for some reason it's failing to compress ? I have a feeling I'm doing something wrong (it's probably staring me in the face) yet another question with "I have a problem" without saying which is the problem/error lol :) It's just not producing a file, I have a feeling it's to do with my variable usage. I have with no variable usage (e.g "test.zip") and it works fine ? That pastebin is pretty much useless as it does not show the code you are using to zip the file. If you are having problems with that function, i would suggest the function from this answer. I personally have used that function before and it works like a dream and is easy to understand. It works for both files and folders. From the above linked answer, the original asker's problem might be because they do not have the zip extension installed. Make sure that "if (extension_loaded('zip') === true)" is true. The problem was actually down to incorrect capture of the download code.
common-pile/stackexchange_filtered
Angular Routing duplicating same content twice and when click button Routing content alone should show So the same content is repeating twice and onclick of New Admin button routing is happening to newadmin html page but because of duplicate there showing New Admin content as well as practice component content also. Duplicate should not happen and onclick of New Admin button show only new admin content alone. Please modify your post to include the code instead of linking an image. Also check out https://stackoverflow.com/help/how-to-ask Issue here is two fold: A) your app component also has a component it is loading. The app component is the wrapper around your entire application. So anything in the app component will display. That is why it looks like it is duplicating. So remove the call to your practice component. B) Wrong usage of your router. You have two blank paths leading to two separate components. Think about it, how would you know where togo if you have two blank routes? Remove the line that also calls AppComponent, app component is always loaded as I mentioned in point A. Working stackblitz: https://stackblitz.com/edit/angular-ogmfj5?file=src/app/app.module.ts In essence though, your app component html should look like this: <router-outlet> </router-outlet> And your app.module.ts should look like this: const routes: Routes = [ { path: '', component: PracticeComponent, pathMatch: 'full' }, { path: 'newadmin', component: NewAdmin }, ]; @NgModule({ imports: [RouterModule.forRoot(routes), BrowserModule, FormsModule], declarations: [AppComponent, PracticeComponent, NewAdmin], exports: [RouterModule], bootstrap: [AppComponent], }) export class AppModule {} Of course change the corresponding components to match the ones you have. Hi it is working fine..Thanks for your answer.. Please mark it as accepted answer if it is the one you went with
common-pile/stackexchange_filtered
win7 boost::asio::windows::stream_handle constructor throws error The following code gets an error when trying to execute the last line boost::shared_ptr<boost::asio::io_service> ioServicePtr(new boost::asio::io_service()); //setup the terminal with stdin and stdout int inFD = ::dup(STDIN_FILENO); int outFD = ::dup(STDOUT_FILENO); HANDLE osfhandle = (HANDLE)_get_osfhandle(inFD);//osfhandle is valid boost::asio::windows::stream_handle inputStream(*ioServicePtr, osfhandle); //error the error is: uncaught exception of type N5boost16exception_detail10clone_implINS0_19error_info_injectorINS_6system12system_errorEEEEE - assign: The parameter is incorrect Appreciate your input. @sehe I tried hstdhandle = GetStdHandle(STD_OUTPUT_HANDLE); and got the same error So then I tried HANDLE handle= CreateFile( "CONIN$", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); boost::asio::windows::stream_handle inputStream(*ioServicePtr, handle); and the error was -assign handle invalid You might use GetStdHandle, so: HANDLE isfhandle = GetStdHandle(STD_INPUT_HANDLE); However, I don't think consoles support asynchronous IO in windows: The handle must be to an object that supports overlapped I/O. If a handle is provided, it has to have been opened for overlapped I/O completion. For example, you must specify the FILE_FLAG_OVERLAPPED flag when using the CreateFile function to obtain the handle But further the docs for CreateFile say that CreateFile ignores file flags when creating a handle to a console buffer. So, you will need to emulate stdin/stdout async IO. Note that on Linux, asynchronous IO to the standard IO handles is only possible in certain situations anyway - depending on the input/output being redirected: Strange exception throw - assign: Operation not permitted
common-pile/stackexchange_filtered
Execution Plan in SQL Server? In which situation estimated number of executions and actual number of execution differs? Could anybody list out the occasions? Thanks In Advance In general, distribution statistics are responsible for cardinality estimates. In addition to said by TomTom, until very recently SQL Server has always assumed that table variables contain exactly 1 row. Needless to say, sometimes this resulted in an execution plan being horribly wrong - ganz falsch, practically. If you use table variables that have a lot of rows, switch to at least 2012 and set a special trace flag that enables correct estimate: http://support.microsoft.com/kb/2952444 Shitty statistics which simply do not match reality because they are outdated. Complex queries where the math behind assumptions goes wrong. Statistics entries are always simplified (A histogram) and some values may not fit into it. Both can have part in it.
common-pile/stackexchange_filtered
How to change product template for bundle products? Is the any way to have separate view.phtml for simple and bundled products? Yes, absolutely. Magento already deals them separately. Check these template files: For simple: template/catalog/product/view.phtml For bundle: template/bundle/catalog/product/view.phtml Now if you want to change bundle template then have this in your local.xml <PRODUCT_TYPE_bundle translate="label" module="bundle"> <reference name="product.info"> <action method='setTemplate'><template>path/to/your/template/view.phtml</template></action> </reference> </PRODUCT_TYPE_bundle> You would want to copy the content from template/catalog/product/view.phtml to path/to/your/template/view.phtml. I tried same as you suggested, but bundle product page is blank , except header and footer. can you check https://magento.stackexchange.com/questions/194755/change-product-page-layout-and-design-for-the-bundle-product-in-magento-1-9
common-pile/stackexchange_filtered
iOS QuickLook framework alternative I'm developing client for http://sparkleshare.org, OSS Dropbox alternative. For previewing of files I'm using QuickLook framework, but it seems it previews only PDF (maybe I do something wrong). What uses iOS dropbox client for previewing files? Is any QuickLook alternatives? Should I use it? QuickLook handles a half-dozen or so file types, not just PDF. There are no quick look alternatives. If you want to be able to read all those formats, you've got to get down and dirty.
common-pile/stackexchange_filtered
C++ function vs template with an integer parameter? Reading the Wikibook Optimizing C++, in this paragraph there is the following suggestion: If an integer value is a constant in the application code, but is a variable in library code, make it a template parameter. So if I have a function like void myfunction(int param) { switch(param) { case 1: do_something_1(); break; case 2: do_something_2(); break; ... case 100: // 100 is taken as example do_something_100(); break; } } Is convenient to replace it with the following? template<int param> void myfunction() { switch(param) { case 1: do_something_1(); break; case 2: do_something_2(); break; ... case 100: // 100 is taken as example do_something_100(); break; } } Or is completely unnecessary? Could you please explain to me the reason? If the compiler knows the value of "param" at compile-time, it may completely remove the switch to keep the only code that can be reached. Not very useful. If it is a constant, and you let the compiler inline the code, I guess the result will be the same. Reasons are already given on that page you have mentioned. If an integer value is a constant in the application code, but is a variable in library code, make it a template parameter. The tweak you have in mind only works if the parameter is known at compile time. In your quote, there is an assumption about the application code which you can't make when writing a library. If your function calls in the application code used to be const int x = 3; myfunction(1); myfunction(2); myfunction(x); //etc... They can be rewritten as follows. const int x = 3; myfunction<1>(); myfunction<2>(); myfunction<x>(); //etc... But if x is a variable, it's not possible: int x = ...; // unknown at compile-time! myfunction<x>(); // will fail to compile! As stated above, there are cases where you shouldn't make assumptions about the application when writing a library. Sometimes you want or need to do. Let's consider the case where you expect the application to use a constant, but you don't want to force it to do so. You want to optimize for the case it will use a constant, but still allow the use of a variable. For this, I suggest two options: Make two alternatives, one with a template parameter and one with a function parameter. Inline the function, so when compiling the application code the function's definition is seen by the compiler and can be used to optimize it to a single do_something_*() call if the parameter was constant. Note that both options require exposing the function's definition to the application's code. I'd prefer to use the second option. Both a template and an inlined function needs to expose function definition (unless you dare entering the dungeons of now-deprecated and never-really-supported C++03 exported template) That's what I said in my last sentence (note the "also"). I'll rewrite it a bit. I doubt you would actually see a performance advantage in real situations here. If the call is inlined, there is no difference between the two approaches - as long as the parameter is known at compile time (which it must be), a decent compiler will remove the unnecessary switch in both cases. The only case where you would see a difference is if inlining does not occur - in this case the templated approach would allow the switch to be removed, while the other would not. However, the function call overhead is likely to dwarf the cost of the switch in this case anyway.
common-pile/stackexchange_filtered
How to execute delete raw query in codeigniter I have sql query for delete multiple record from database $sql="delete from users where id IN(4,5,6..)"; How to run this query in codeigniter Possible duplicate of How to execute my SQL query in CodeIgniter Per the documents, you can use the query builder, or you can run a direct query on the database. The query() function returns a database result object when “read” type queries are run, which you can use to show your results. When “write” type queries are run it simply returns TRUE or FALSE depending on success or failure. When retrieving data you will typically assign the query to your own variable, like this: $query = $this->db->query('delete from users where id IN(4,5,6..)'); Or you can use the query builder class which allows you to do the following: $this->db->where_in('id', array(4,5,6)); $this->db->delete('users'); Create a function in you model function rowDelete($ids) { $this->db->where_in('id', $ids); $this->db->delete('testimonials'); } And call that in your controller $this->your_model->rowDelete($ids) // $ids = array(4,5,6); You can also execute query like this $delete = "id IN('4','5','6')"; $this->db->where($delete); $this->db->delete("user"); In this you can also execure your core query.
common-pile/stackexchange_filtered
I have an error in vscode when trying to install flame under pubspec.yaml I'm trying to install flame but whenever I run the pub get it gives me a really long error "Because every version of flutter_test from sdk depends on xml 3.6.1 and tiled >=0.4.0 depends on xml ^4.2.0, flutter_test from sdk is incompatible with tiled >=0.4.0." And then under it is a version solving failed error message. [√] Flutter (Channel stable, v1.17.5, on Microsoft Windows [Version 10.0.18363.900], locale en-US) • Flutter version 1.17.5 at C:\Users\marci\Downloads\flutter • Framework revision 8af6b2f038 (7 days ago), 2020-06-30 12:53:55 -0700 • Engine revision ee76268252 • Dart version 2.8.4 [√] Android toolchain - develop for Android devices (Android SDK version 30.0.0) • Android SDK at C:\Users\marci\AppData\Local\Android\sdk • Platform android-30, build-tools 30.0.0 • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01) • All Android licenses accepted. [√] Android Studio (version 4.0) • Android Studio at C:\Program Files\Android\Android Studio • Flutter plugin version 47.1.2 • Dart plugin version 193.7361 • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01) [√] VS Code (version 1.46.1) • VS Code at C:\Users\marci\AppData\Local\Programs\Microsoft VS Code • Flutter extension version 3.12.1 [!] Connected device ! No devices available ! Doctor found issues in 1 category. name: ggg description: A new Flutter project. publish_to: 'none' version: 1.0.0+1 environment: sdk: ">=2.7.0 <3.0.0" dependencies: flutter: sdk: flutter cupertino_icons: ^0.1.3 flame: ^0.24.0 dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true Can you provide the pubspec.yaml file, and also result from running flutter doctor -v inside your terminal? @hisam I just updated it I had the same problem today and checked on the Flame Discord channel. They told me they have a conflict with their lib with stable flutter channel. Recommendation is to change to Flutter Channel Beta. I did that, then did Flutter Upgrade, then finally Flutter Pub Get and it worked. Terminal Commands To check which channel you are currently on Flutter Channel To change to the beta channel Flutter Channel Beta To get the beta version Flutter Upgrade Thank you so much, I was going crazy trying to fix it. Now I can finally work! Ya, i hear you. I've been going somewhat nutty trying to learn Dart, Flutter and now Flame. Starting to get the hang of it. Thier Discord channel has been a blessing. So, when I have the same problem with you when I tried it. Here's my solution: In your dependencies: section inside the pubspec.yaml file, change the flame section without any version tag: dependencies: flutter: sdk: flutter cupertino_icons: ^0.1.3 flame:
common-pile/stackexchange_filtered
Transition to GameScene from GameOverScene I'm trying to transition back to my GameScene from my GameOverScene. I have the following touchesBegan function but when I press the 'Replay Game' button it does not transition. override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first! as UITouch let touchLocation = touch.locationInNode(self) let touchedNode = self.nodeAtPoint(touchLocation) if let name = touchedNode.name { if name == "replay"{ print("Touching Replay") let reveal : SKTransition = SKTransition.flipHorizontalWithDuration(0.5) let scene = GameScene(size: self.size) scene.scaleMode = .AspectFill self.view?.presentScene(scene, transition: reveal) } } } I also have the following used to create my replay node: let replayMessage = "Replay Game" var replayButton = SKLabelNode(fontNamed: "Chalkduster") replayButton.text = replayMessage replayButton.fontColor = SKColor.blackColor() replayButton.position = CGPointMake(self.size.width/2, 50) replayButton.name = "replay" self.addChild(replayButton) I get the following output: Touching Replay 2016-02-03 01:11:08.102 Test [1010:196002] CUICatalog: Invalid Request: requesting subtype without specifying idiom It is probably because you are not touching the "replay" node. If I try your code on empty project, it works. About that warning...You should not be worried...Read more here. could be there's another view or sprite above it. if so, you can disable user interaction for that node or view. Hi , try this : override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first! as UITouch let touchLocation = touch.locationInNode(self) let touchedNode = self.nodeAtPoint(touchLocation) if let name = touchedNode.name { if name == "replay"{ let transition = SKTransition.fadeWithColor(UIColor.whiteColor(), duration:1.0) let GameOver = MainScene(size: scene!.size) GameOver.scaleMode = scaleMode view!.presentScene(GameOver, transition: transition) print("Game Over!") } } }
common-pile/stackexchange_filtered
how to execute commands stored in various bash arrays, based on input array name from command line I'm using bash script. I'm trying to execute commands stored in different arrays, based on the input of the array name and the range/index of the array. For example, I have a script commands.sh below and I'd like to execute the command like: ./commands.sh b 1 3 I like the output would display: cmd_b1 cmd_b2 cmd_b3 Ultimately, I like to execute those commands. #!/bin/bash array=$1 begin=$2 end=$3 declare -a $array a[0]="cmd_a0" a[1]="cmd_a1" a[2]="cmd_a2" b[0]="cmd_b0" b[1]="cmd_b1" b[2]="cmd_b2" b[3]="cmd_b3" for (( i=$begin; i<=$end; i++ )) do cmd=${array}[$i] echo "$cmd" done exit 0 I ran the script, but the output I got was: b[1] b[2] b[3] which aren't what I like to see. Any help would be appreciated. Thank you. Aside from the incorrect syntax ${array}[$i] (array indexing would be ${array[$i]}, your array named array was initialized to a scalar first, and later re-declared as array. Therefore it contains only one element. You could get at this element by ${array[0]}. Another oddity is that your code defines arrays named a and b, but never actually uses them. Honestly I have no clue what this script is supposed to do. If you want to pass a variable name as the first argument, you can say: declare -n ref=$1 then would you try: #!/bin/bash declare -n array=$1 begin=$2 end=$3 declare -a a=("cmd_a0" "cmd_a1" "cmd_a2") declare -a b=("cmd_b0" "cmd_b1" "cmd_b2" "cmd_b3") for (( i=begin; i<=end; i++ )) do cmd=${array[$i]} echo "$cmd" done Output for ./commands.sh b 1 3 cmd_b1 cmd_b2 cmd_b3 Output for ./commands.sh a 0 2 cmd_a0 cmd_a1 cmd_a2 Thank you for your answer. I forgot to mention that actual commands I have are very long and they already stored in the form as I posted, line by line like that. It's very hard to re-arrange them into form declare -a a=("cmd_a0" "cmd_a1" "cmd_a2"). Moreover, sometimes I need to execute command "cmd_dbd" of array a[] that I don't know what index it has, just an example. I simplified the problem to make it easy to understand. I think I still can make your solution works. I can just split the declare -a a=( ) line into multiple lines. My modification of the array assignments is trivial just to shorten the code. If you want to assign the arrays one by one, it is absolutely okay and it's up to you. BR. #!/bin/bash declare -n array=$1 begin=$2 end=$3 a[0]="cmd_a0" a[1]="cmd_a1" a[2]="cmd_a2" b[0]="cmd_b0" b[1]="cmd_b1" b[2]="cmd_b2" b[3]="cmd_b3" for (( i=begin; i<=end; i++ )) do cmd=${array[$i]} echo "$cmd" done exit 0 use declare -n to make array a reference to its value delete the no-longer needed declare -a fix the dereferencing: [...] must appear inside ${...}, not after it remove unneeded $ inside ((...)) It will be safer to make each array element be the name of a function, rather than attempting to store complex command-lines in the strings. For example: a[0]="cmd_a0" #... cmd_a0(){ # actual command here (which can access $1,$2,etc) } Yes, your solution simply worked!! Fantastic, I don't need to re-arrange my arrays. Thanks a lot. You can combine the (a,b) arrays in one associative array #!/bin/bash prefix=$1 begin=$2 end=$3 declare -A cmds=( [a0]=cmd_a0 [a1]=cmd_a1 [a2]=cmd_a2 [b0]=cmd_b0 [b1]=cmd_b1 [b2]=cmd_b2 [b3]=cmd_b3 ) for (( i=begin; i<=end; i++ )) do cmd=${cmds[${prefix}${i}]} echo "$cmd" done ./commands.sh b 0 3 cmd_b0 cmd_b1 cmd_b2 cmd_b3 $ ./commands.sh a 0 1 cmd_a0 cmd_a1 A simple way to do it is: #!/bin/bash -p array=$1 begin=$2 end=$3 a[0]="cmd_a0" a[1]="cmd_a1" a[2]="cmd_a2" b[0]="cmd_b0" b[1]="cmd_b1" b[2]="cmd_b2" b[3]="cmd_b3" case $array in a) tmparr=( "${a[@]}" );; b) tmparr=( "${b[@]}" );; *) printf 'ERROR: invalid array name: %s\n' "$array" >&2 exit 1;; esac for (( i=begin; i<=end; i++ )); do cmd=${tmparr[i]} printf '%s\n' "$cmd" done exit 0 Compared to some alternatives, this has the advantage that it won't do something inappropriate if an invalid array name is provided. See the accepted, and excellent, answer to Why is printf better than echo? for an explanation of why I replaced echo with printf.
common-pile/stackexchange_filtered
Framed boxed text with "continued" text on page break I need to write a boxed text as like as: Currently, I am using \documentclass{book} \usepackage{framed} \begin{document} \begin{framed} \section{Box 15...} ... \end{framed} \end{document} Please advise. Do you need an automatic page break or do you can break the text manually? @MartinScharrer It is better, if I get auto pagebreak, please... Well, framed text with page break can be done easily with the mdframed package. Do you need the "continued" markers or can you do without them? @MartinScharrer Sorry to trouble you, I require the auto pagebreak with "continued" marked also too by auto. able to understand the pain, but pl help... No problem, just needed to clarify that. Based on egregs answer to "Breakable vboxes" I coded the following environment. It collects its vertical input and then breaks it using plainTeX's internal breaking mechanism (\vsplit) and places both part in an \fbox. This will not work for large material which break across three pages, but this feature could be added. \documentclass{article} \usepackage{blindtext}% just for example text \newbox\totalbox \newbox\partialbox \newdimen\partialboxdim \newenvironment{continueframe}{% \advance\linewidth-2\fboxsep \advance\linewidth-2\fboxrule \hsize=\linewidth \partialboxdim=\dimexpr\pagegoal-\pagetotal-\pageshrink-6pt-\baselineskip\relax \setbox\totalbox=\vbox\bgroup\begingroup }{% \endgraf\endgroup\egroup \setbox\partialbox=\vsplit\totalbox to\partialboxdim \par\smallskip \hbox{\fbox{\vbox{\unvbox\partialbox}}}\nopagebreak \par\smallskip\mbox{}\hfill\textbf{Continued on next page}\par\pagebreak% \hbox{\fbox{\vbox{\noindent\textbf{Contuined from last page}\par\smallskip\unvbox\totalbox}}}% \par\medskip } \begin{document} \blindtext \blindtext \blindtext \begin{continueframe} \blindtext \blindtext \blindtext \end{continueframe} \blindtext \blindtext \blindtext \end{document} Thanks for the nice solution...it's work absolutely fine for me... @MadyYuvi: Glad I could help you. Please note that my code might be less stable or supported by features of some packages as a released package like tcolorbox or similar. As long as it works for you it is fine, however. Another solution with tcolorbox package. \documentclass{article} \usepackage{lipsum} \usepackage[most]{tcolorbox} \usepackage{lmodern} \newtcolorbox[auto counter]{mybox}[2][]{% breakable, enhanced, sharp corners, colback=white, fonttitle=\bfseries, title=Box~\thetcbcounter:\ #2, enlarge bottom at break by=5mm, enlarge top at break by=5mm, overlay first={% \draw[black, line width=0.5mm](frame.south west)--(frame.south east); \node[anchor=north east] at (frame.south east) {continued on next page}; }, overlay middle={% \draw[black, line width=0.5mm](frame.south west)--(frame.south east); \draw[black, line width=0.5mm](frame.north west)--(frame.north east); \node[anchor=north east] at (frame.south east) {continued on next page}; \node[anchor=south west] at (frame.north west) {continued from next page}; }, overlay last={% \draw[black, line width=0.5mm](frame.north west)--(frame.north east); \node[anchor=south west] at (frame.north west) {continued from next page};}, #1 } \begin{document} \lipsum[1-2] \begin{mybox}{Combined off-springs size theories} \lipsum[3-16] \end{mybox} \end{document} This may be of some help to you. The continue package prints "continuation" marks on pages of multipage documents. The marks can be defined as you wish and started and stopped at any point. To read the manual > texdoc continue. Thanks for the continue package, will look into this, and use the same...
common-pile/stackexchange_filtered
Remove paragraph mark when copying from excel cell Please help me copy a string from a listbox when a user hits ctrl+c. I was using the dataobject but for some reason this worked perfectly some times and gave me an error message other times. If you know why this is, stop reading, as the rest of this question is not necessary. Now I am putting this in a worksheet cell and using range.copy, however, when the string is pasted into a textbox, it retains the paragraph mark that excel seems to put at the end of every cell! Just to make things fun, the paragraph mark cannot be removed by using Left() - it takes everything but the paragraph mark. (Paragraph mark below is represented by P). s = "stringP" s = Left(s,len(s)-1) print s returns: strinP Has to be something simple I'm missing. By paragraph mark, do you mean this guy ¶ a.k.a. pilcrow? Just to disambiguate from a line feed or carriage return... s = "hello¶" followed by s = Left(s, Len(s) - 1) works fine for me... returns s = "hello" as expected. Have you tried trim() function ? And why do you have to use Range.copy? Can't you just assign textbox1.value = Range("A1") ? It works fine without any bugs. I haven't tested this but have you tried chopping two characters? I'm sure it's \r\n or carriage-return + line feed, not just \n you need to chop.
common-pile/stackexchange_filtered
Why will Swift not accept this NSCalendar method call? let dateComponents = NSCalendar.currentCalendar().components(.MonthCalendarUnit, fromDate: dateCreated, toDate: NSDate(), options: 0) I'm trying to find the difference between two NSDates in months, but this function will not cooperate. It keeps complaining about "extra argument 'toDate' in call", but it's definitely supposed to be there. By the way, .MonthCalendarUnit is deprecated in favor of .CalendarUnitMonth. Swift doesn't accept 0 as a value for options, like Objective-C. Use nil instead: let dateComponents = NSCalendar.currentCalendar().components(.MonthCalendarUnit, fromDate: dateCreated, toDate: NSDate(), options: nil) Then all you have to do is get the number of months by doing dateComponents.month. extension NSDate { func monthsFrom(date:NSDate) -> Int{ return NSCalendar.currentCalendar().components(.CalendarUnitMonth, fromDate: date, toDate: self, options: nil).month } } let dateX = NSCalendar.currentCalendar().dateWithEra(1, year: 2014, month: 11, day: 28, hour: 5, minute: 9, second: 0, nanosecond: 0)! let dateY = NSCalendar.currentCalendar().dateWithEra(1, year: 2015, month: 1, day: 1, hour: 22, minute: 51, second: 0, nanosecond: 0)! let months = dateY.monthsFrom(dateX) // 1
common-pile/stackexchange_filtered
error: Cannot find module '/app/app,js' heroku My web works perfectly on my local machine and all that, but in Heroku I deployed my app and nothing is working, and when: $ heroku logs --tail State changed from crashed to starting Starting process with command `node app.js` internal/modules/cjs/loader.js:883 throw err; ^ Error: Cannot find module 'express' Require stack: - /app/app.js at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15) at Function.Module._load (internal/modules/cjs/loader.js:725:27) at Module.require (internal/modules/cjs/loader.js:952:19) at require (internal/modules/cjs/helpers.js:88:18) at Object.<anonymous> (/app/app.js:1:17) at Module._compile (internal/modules/cjs/loader.js:1063:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10) at Module.load (internal/modules/cjs/loader.js:928:32) at Function.Module._load (internal/modules/cjs/loader.js:769:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) { code: 'MODULE_NOT_FOUND', requireStack: [ '/app/app.js' ] } directory structure: -app -css -files -js -logo -views -index.html -app.js -composer.json -package-lock.json -package.json -Procfile Procfile: web: node app.js package.json: { "name": "app", "version": "1.0.0", "engines": { "node": "14.15.3" }, "private": "true", "main": "app.js", "scripts": { "start": "node app.js", "dev": "nodemon app.js" }, "keywords": [], "author": "me", "repository": "appRep", "license": "ISC", "devDependencies": { "chokidar": "^3.5.2", "express": "^4.17.2", "fs": "0.0.1-security", "nodemailer": "^6.7.2", "nodemon": "^2.0.15", "path": "^0.12.7" } } .env: (even before the .env file everything was the same) PORT = 8081 Do you guys have any idea? Thank you in advance!! Did you try putting app.js in the app folder? yes I did, that did not work at all, and plus that way my localserver can't find my files Your express package is listed in devDependencies in package.json, try moving it to dependencies like so "dependencies": { "express": "^4.17.2" } devDependencies should list only packages which are not essential for app deployed in production (Heroku). It might be necessary to move more packages to dependencies not only express. This worked!!!!!!!!!!!!!!!!!!!!!!!!!!! thank you good sir, can you explain why express should be in dependencies and not devDependencies? I am really curious... @Liemannenloop devDependencies are packages you need to use only during development, for example nodemon, so Heroku doesn't need to install it in production build; read more here https://stackoverflow.com/questions/18875674/whats-the-difference-between-dependencies-devdependencies-and-peerdependencies Make sure the express installed on Heroku. You should add express to the dependencies object in package.json file Can you explain why this works? I hope I could upvote your comment but I have little reputation lol, but this is 100% correct answer as the previous gentlemen stated too. No problem :), best wishes to you.
common-pile/stackexchange_filtered
solidity function functionCall from openzeppelin-contracts-accounts reverted I was calling flashLoan function using following parameters for hardhat testing expect( await this.pool.flashLoan(100, attacker.address, this.token.address, 0x00) ).to.be.not.reverted; This is the function written in solidity function flashLoan( uint256 borrowAmount, address borrower, address target, bytes calldata data ) external nonReentrant { uint256 balanceBefore = damnValuableToken.balanceOf(address(this)); require(balanceBefore >= borrowAmount, "Not enough tokens in pool"); damnValuableToken.transfer(borrower, borrowAmount); target.functionCall(data); uint256 balanceAfter = damnValuableToken.balanceOf(address(this)); require(balanceAfter >= balanceBefore, "Flash loan hasn't been paid back"); } Click HERE for Entire Solidity code This is my entire test script const { ethers } = require("hardhat"); const { expect } = require("chai"); describe("[Challenge] Truster", function () { let deployer, attacker; const TOKENS_IN_POOL = ethers.utils.parseEther("1000000"); before(async function () { /** SETUP SCENARIO - NO NEED TO CHANGE ANYTHING HERE */ [deployer, attacker] = await ethers.getSigners(); const DamnValuableToken = await ethers.getContractFactory( "DamnValuableToken", deployer ); const TrusterLenderPool = await ethers.getContractFactory( "TrusterLenderPool", deployer ); this.token = await DamnValuableToken.deploy(); this.pool = await TrusterLenderPool.deploy(this.token.address); await this.token.transfer(this.pool.address, TOKENS_IN_POOL); expect(await this.token.balanceOf(this.pool.address)).to.equal( TOKENS_IN_POOL ); expect(await this.token.balanceOf(attacker.address)).to.equal("0"); it("Flash load will successfull", async function () { /** CODE YOUR EXPLOIT HERE */ expect( await this.pool.flashLoan(100, attacker.address, this.token.address, 0x00) ).to.be.not.reverted; }); it("Exploit", async function () { /** CODE YOUR EXPLOIT HERE */ this.hack = await ( await ethers.getContractFactory("TrusterAttack", attacker) ).deploy(this.token.address, this.pool.address, attacker.address); this.hack.attack(); }); after(async function () { /** SUCCESS CONDITIONS */ // Attacker has taken all tokens from the pool expect(await this.token.balanceOf(attacker.address)).to.equal( TOKENS_IN_POOL ); expect(await this.token.balanceOf(this.pool.address)).to.equal("0"); }); }); When i run this script it shows Error: VM Exception while processing transaction: reverted with reason string 'Address: low-level call failed' Noteed* basically i was trying to execute the flashLoan for https://www.damnvulnerabledefi.xyz/challenges/3.html problem - Truster i was able to solve this. the issue was functionCall requires a bytes String of an function. So here i was in need of approve function byte string. bytes memory data = abi.encodeWithSignature( "approve(address,uint256)", address(this), type(uint256).max ); So i passed this data as a parameter of target.functionCall(data) Here target is the token address. Noted bytes string of the data holds this value 0x095ea7b30000000000000000000000008464135c8f25da09e49bc8782676a84730c318bcffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
common-pile/stackexchange_filtered
Do we still need the haveged daemon with versions of linux after 5.10.119? Per kernel 5.10.119 caused the values of /proc/sys/kernel/random/entropy_avail and poolsize to be 256 Linux locks the value of /proc/sys/kernel/random/entropy_avail to 256. Do we still need haveged?
common-pile/stackexchange_filtered
How to reassign a type to a variable in typescript How to reassign a different type to a variable in typescript without creating a new variable? let variable: string | number; //somewhat like one of those not working examples declare let variable: string; varaible: string; Not possible directly, control flow analysis will narrow the type on assignments (https://www.typescriptlang.org/play/#code/DYUwLgBAbghgTgSxgI1ALggZzIgdgcwgB8JcBXAW2RDgG4AoWRFUCCAXggCIuGmlUIAHTIE+ABQBKCAHoZEBJiw4EBCEA)/ type guards (https://www.typescriptlang.org/play/#code/DYUwLgBAbghgTgSxgI1ALggZzIgdgcwgB8JcBXAW2RDggF4IBZGMACwDo4ZcATAewoAKAJQQAfBAAM7AKwQA-BABESiGgCMAbgBQCAGaCwATwAOIPnujwkqEPToMl2PPiWiA3tojeriFKHZkBHwRCAB6MIgETCwcBAIIbQBfCBBgTDtPH18bALA+AFEADxM+XBBcMCRgUIiomPIqGmSgA): If you use the any variable type, you will achieve the result you mentioned - the variable will change type at runtime depending on the assigned value. if you control the values and ensured that everything is correct, you can use simple javascript's type convertation: let variable: string | number = "1"; variable = Number(variable) // here your type will be number My question provides a simplified problem, ofc I know how to parse primitives in js, but this does not narrow the type of variable as shown here: https://www.typescriptlang.org/play/index.html#code/DYUwLgBAbgXBDOYBOBLAdgcwgHwmgrgLYBGISA3AFCUD0NAAmPALQoZoD2SIlUEAvBAByRUkgAUUAJTU6KeAjApgwCBwDWvARABEAQ3gATHUA
common-pile/stackexchange_filtered
CSS positioning a rectangle after rotated with transform matrix I am using CSS transform matrix in order to rotate a div. After rotation is applied, I want to position the div using css 'left' and 'top'. The problem is that the css positioning is ignoring the rotation, and treats the rectangle like it is not rotated. For example, if I rotate the rectangle 90 deg and then set it to left 0px and top 0px, it wont show up in the upper-left corner of the container. It will be the same result as if I position the original rectangle in 0,0 and only then rotate it (it will look like it is in 10px,-5px or so). All the answers online talk only about getting the position of rotated rectangle but not setting. Thanks. use margin instead or cover with a div or span and then do that to the same.... margin is creating the same results. try contain your html structure into a div or span, then position it... Eventually I solved it with simple logic: newX = x - (originalWidth - boundedW) / 2; newY = y - (originalHeight - boundedH) / 2; There is no way that you can position the div after the rotation. What you can do is position the corner that you really want, and then set this position as the rotation center. If you give an specific example then I can give you a more detailed answer.
common-pile/stackexchange_filtered
Java regular expression for validating a number greater than 20000 I have a requirement where I want to validate a number which should be greater than 20000 and less than 100000. Please help in providing the regex. I am very new to regular expressions. I have a regular expression for checking whether a number is less than 20000 [1-9]\d{0,3}|1\d{4}|20000 Why do you need regex? (value > min) && (value < max) ^I'm with @hwnd you don't need regex for this sort of thing [2-9]{1}(?!0000)[0-9]{4} ^(?!20000)[2-9][0-9]{4}$ All the numbers you need are 5 digit long. First digit could be from 2-9, every other digit could be anything, just you can't have 20000 in your list in this range. Let's rule out that 1 number with negative look-ahead (?!20000) and let's say first digit could be only 2-9, should follow 4 digits, but those digits could be anything. https://regex101.com/r/wY6lA9/1 If this is for a school assignment, then you shouldn't be asking on here. If you're doing this for a real program, it's much better to parse it to an int (or perhaps a double if you're allowing non-integer values), and just check if it's in the range you want: try { int x = Integer.parseInt(in) if (x <= 20000 || x >= 100000) { //do what you want here for when it's not valid } else { //do what you want for a valid input here } } catch (NumberFormatException e) { //Do something in case it's not a valid number here } Now, this assumes you have an input of type String. If it's already a numeric type, then you don't need to parse it - just do the if-else clause.
common-pile/stackexchange_filtered
lilo: Fatal: raid_setup: stat("/dev/nvme0n1") I have booted Debian Live CD, and I am trying to create lilo boot record on my disk The disk partition is mounted as /mnt/root and has the linux kernel and /etc/lilo.conf: boot=/dev/nvme0n1 root=/dev/nvme0n1p1 map=/boot/map lba32 prompt timeout=30 default=linux image=/boot/vmlinuz label=linux read-only append="rootfstype=ext4 net.ifnames=0 loglevel=4 3" the mounted partition has all the system files and the kernel image. I am not using any raid, although the debian live CD for some reason loads all md_raid modules. How can I create boot record on my disk? Trying to setup your system to boot via Lilo is a bit surprising in 2023; the Lilo developers asked to stop using it in 2015. I'm honestly a bit surprised it still works, nice! So the question here becomes, seeing your system correctly handles NVMe as nvme and not just some disk emulation, whether your system still supports the forty years old legacy MBR Boot with boot records, or whether just dropping the UEFI shim file that loads Lilo into the fat32 ESP is enough.
common-pile/stackexchange_filtered
KeyDown preventing text appearing in TextBox [UWP] I have the current UWP app targeting 10240: <Page x:Class="App8.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid> <ContentControl KeyDown="ContentControl_KeyDown"> <TextBox TextChanged="TextBox_TextChanged"/> </ContentControl> </Grid> </Page> And: namespace App8 { public sealed partial class MainPage : Page { public MainPage() => InitializeComponent(); private void ContentControl_KeyDown(object sender, KeyRoutedEventArgs e) => e.Handled = true; private void TextBox_TextChanged(object sender, TextChangedEventArgs e) => Debug.WriteLine("NEVER RUNNING CODE"); } } When I write in the textbox I want to avoid any key events going to the main screen. In order to do that I have the KeyDown in the parent element of the textbox, and I handle the event. But If I do that the textbox doesn't write anything. I'd like to end any key events going in the ContentControl going to the Page, but allowing the textbox to work normally. Any ideas? What about adding a KeyDown Event handler to the textbox?? Already tried it, and doesn't work. It avoids the textbox from writing text. This looks like a case for routing, bubbling and tunneling: https://www.codeproject.com/Articles/464926/To-bubble-or-tunnel-basic-WPF-events Yes, the KeyDown event is going up before the TextChanged event, but I still want the textbox to work. and this is a UWP project so mouse preview and those events are not available. Why would you not want any keys to be shown to the user? In the keydown event you could modify the Text-Value of your textbox? I have some doubts with your design, why you want to handle the KeyDown in the ContentControl ? Is there some hotkey on your main screen? the textbox is in a popup, and I don't want keys strokes like up, left, down, up arrow traverse up to the parent, Because it triggers some events. hi @etragu Does it work in your side? I made a patch, but I don't thinkg the behavior of the textbox should rely on other UI elements handling keydown events Could you share more about your patch? I handle some specific keys I don't want to propagate Up in the UI tree, and when I detect those VirtualKeys I set e.Handled = true. I'd like to end any key events going in the ContentControl going to the Page, but allowing the textbox to work normally. Any ideas? For your requirement, you could make bool flag to tell main screen fire some events or not when the TextBox is focused or not. private bool IsFocus; private void MyTextBox_GettingFocus(UIElement sender, GettingFocusEventArgs args) { IsFocus = true; } private void MyTextBox_LostFocus(object sender, RoutedEventArgs e) { IsFocus = false; } Usage public MainPage() { this.InitializeComponent(); Window.Current.Dispatcher.AcceleratorKeyActivated += Dispatcher_AcceleratorKeyActivated; } private void Dispatcher_AcceleratorKeyActivated(Windows.UI.Core.CoreDispatcher sender, Windows.UI.Core.AcceleratorKeyEventArgs args) { if (IsFocus) { System.Diagnostics.Debug.WriteLine("Do Not Fire Your Event "); return; } else { System.Diagnostics.Debug.WriteLine(" Fire Your Event "); } }
common-pile/stackexchange_filtered
How to dynamically add sheet reference in a range in Googlesheet I'm trying to fetch the sheet name from another column and put in inside the formula. Here is picture Welcome to Stackoverflow! Please take this opportunity to take the Tour and learn how to How to Ask, format code, minimal reproducible example and Learn More Try this: =COUNTA(INDIRECT(A2&"!G2:G1000")) Reference: INDIRECT()
common-pile/stackexchange_filtered
Error in onSaveInstanceState method For one of the user(motorola motorola XT1068) i am getting exception for onSaveInstanceState. I am using ACRA for crash report. Here is the complete stack trace: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1438) at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1456) at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634) at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613) at android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.java:282) at android.view.View.dispatchAttachedToWindow(View.java:13424) at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2709) at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2716) at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2716) at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2716) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1315) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1077) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5884) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767) at android.view.Choreographer.doCallbacks(Choreographer.java:580) at android.view.Choreographer.doFrame(Choreographer.java:550) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5312) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) But nowhere my application source is mentioned and this is the only place where i am using savedinstance method. @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBundle("CONFIG", (savedState != null) ? savedState : saveState()); } private Bundle saveState() { Bundle state = new Bundle(); state.putCharSequence("SUCCESS", result.getText()); state.putCharSequence("FAILURE", error.getText()); return state; } So what could be the issue over here? Edit: Here is the ViewPagerAdapter code public class ViewPagerAdapter extends FragmentPagerAdapter { private final int PAGES = 3; private FragmentManager mFragmentManager; private Context mContext; private String[] title = new String[]{"Frag1", "Frag2", "Frag3"}; public ViewPagerAdapter(FragmentManager fm, Context context) { super(fm); mContext = context; } @Override public Fragment getItem(int position) { switch (position) { case 0: return new Fragment1(); case 1: return new Fragment2(); case 2: return new Fragment3(); default: throw new IllegalArgumentException( "The item position should be less or equal to:" + PAGES); } } @Override public int getCount() { return PAGES; } @Override public int getItemPosition(Object object) { return POSITION_NONE; } @Override public CharSequence getPageTitle(int position) { return title[position]; } } Call from Activity viewPageAdapter = new ViewPagerAdapter(getSupportFragmentManager(), getApplicationContext()); swap super and outState lines. @activesince93 Thanks but I am not getting this error every time or in a while. I want how to reproduce in my app. :) duplicate http://stackoverflow.com/questions/7469082/getting-exception-illegalstateexception-can-not-perform-this-action-after-onsa It's not your onSaveInstanceState problem. The issue comes from adding/replacing Fragment. You should post or check the adding/replacing fragment code! @KingfisherPhuoc I am using ViewPageAdapter which is extending FragmentPagerAdapter. I am not doing anything much with viewpager. @MadhukarHebbar you should post your FragmentPagerAdapter here. maybe it will help! @KingfisherPhuoc Updated code. I think that I need your Activity code also... Call the super method at the end. @Override public void onSaveInstanceState(Bundle outState) { outState.putBundle("CONFIG", (savedState != null) ? savedState : saveState()); super.onSaveInstanceState(outState); } his problem isn't with saving instance, his problem is that he is commiting a fragment after saving instance, like for example, onresume, onActivityForResult.
common-pile/stackexchange_filtered
Finite-dimensional subgroups of diffeomorphism groups This question is a generalization of my previous question about the circle to arbitrary manifolds. Is there a smooth manifold M with the following property. There exists a sequence of connected finite-dimensional subgroups Gi of M's diffeomorphism group G such that (a) Gi is contained in Gj for i < j (b) The union of Gi is dense in G To remove doubt, "finite dimensional subgroup of M's diffeomorphism group" means a Lie group H with smooth faithful action on M. The answer to my previous question established that S1 is not such a manifold. I suspect that the answer to the general question is still "no". However, the proof would have to be more sophisticated since in the case of S1 we had essentially a closed list of possible "Hs". There is another closely related question. Fix a smooth manifold M. Consider connected Lie groups H with faithful and transitive smooth action on M. Is there an upper bound of H's dimension? For S1 the answer was "yes, 3". Clearly, the answer is "no" (just like the case of the circle), but I guess, you're really asking for a proof... I guess that the answer to your first question is no, based on the following: If the union of the $G_i$ were dense in $G=\mathrm{Diff}(M)$, then, presumably, for $i$ sufficiently large, the action of $G_i$ would be primitive (i.e., it would not preserve any nontrivial foliation) and locally transitive. The list of the effective, primitive, transitive Lie group actions is known, and, by examining this list, one sees that the dimension of such a group acting on an $n$-manifold is at most $n^2{+}2n$. The answer to your second question depends on the manifold. First, I suppose you have to restrict to the case in which $M$ actually has a transitive smooth action of a finite dimensional Lie group. (For example, any compact orientable surface $M^2$ of genus $2$ or more is not a homogeneous space.) It is not hard to come up with cases for which there is no upper bound. For example, let $M = \mathbb{R}^2$ and consider the group $G_d$ that consists of transformations of the form $\phi(x,y) = \bigl(x{+}a,\ y{+}p(x)\bigr)$ where $a$ is any constant and $p$ is any polynomial of degree $d$ or less. Then $G_d$ acts transitively on $M$ for all $d\ge0$ while $\dim G_d = d+2$. Thus, for $M=\mathbb{R}^2$ the dimension of such $H$ can be arbitrarily high. A similar argument with trig polynomials will provide such an example on the torus, which is compact. (N.B.: The action of $G_d$ is not primitive since it preserves the foliation by the lines $x=c$; thus, this example does not contradict my first paragraph.) On the other hand, for $M=S^2$, there is an upper bound for the dimension of a connected Lie group that acts faithfully and transitively on $M$. That upper bound is 8 ($=2^2+2\cdot2$) and is achieved by $SL(3,\mathbb{R})$ acting on $S^2$ regarded as the space of oriented lines in $\mathbb{R}^3$. In fact, you can say more: Any connected, transitive finite dimensional Lie subgroup of the diffeomorphism group of $S^2$ is conjugate to one of $SO(3)$, $PSL(2,C)$, or $SL(3,\mathbb{R})$. The latter two are maximal and contain the first one as maximal compact. (The easiest proof that I know of these statements uses the classification of primitive actions, at least in dimension $2$.) Lie's classification of Lie group actions on surfaces is explained in great detail in Mostow, George Daniel, The extensibility of local Lie groups of transformations and groups on surfaces. Ann. of Math. (2) 52, (1950). 606–636. The classification is explained more briefly, but perhaps in manner that is easier to survey, in the appendices of Olver, Peter J.(1-MN) Equivalence, invariants, and symmetry. (English summary) Cambridge University Press, Cambridge, 1995. EDIT: Correctly state Zimmer's conjecture. This does not really answer the question, but the question of which (higher rank) Lie groups act by diffeomorphism on which smooth manifolds is called the "Zimmer Program". In particular, Zimmer conjectured that if $n \geq 3$ and $\Gamma \subset SL(n,\mathbb{R})$ is a lattice, and $\Gamma$ acts by diffeomorphisms on a compact manifold $M$ then the dimension of $M$ is at least $n-1$. There is a close connection between actions of Lie groups, and actions of their lattices. In particular if $\Gamma$ acts on $X$, then you can let $Y = G \times X$ mod the diagonal action of $\Gamma$. The space $Y$ looks like a fiber bundle with base $G/\Gamma$ and fiber $X$. Then we have an natural action of $G$ on $Y$ (by acting on the first factor); this is called the induced action. There is an enormous amount of literature on various aspects of the Zimmer program, but in particular, as far as I know, the above conjecture is still open. For a fairly recent survey of what is known, see this paper by David Fisher: http://arxiv.org/abs/0809.4849v2 (For details on the induction construction, see section 2.3 of the survey) There is no hope to understand the actions of $SO(n,1)$, because you can find lattices in $SO(n,1)$ which surject onto free groups. Then you can choose an arbitrary action of the free group on $X$ and do the induction construction, see Theorem 2.7 in the survey. The best question is for actions of Lie groups of real rank at least 2.
common-pile/stackexchange_filtered
How to direct web traffic via php throuh a specific interface? How would I direct specific traffic to an interface? For example each interface is assigned a different ip-address, I would like to call http traffic via php to eth0 for some traffic and eth1 for other traffic. using using curl(using curl_init($url) ) What function are you running? curl? file_get_contents? etc? using curl_init($url) looks like the answer is: curl_setopt($curlh, CURLOPT_INTERFACE, "eth0");
common-pile/stackexchange_filtered
Haskell QuickCheck for testing n-ary tree eval I have a n-ary tree defined as follows: data Tree = Leaf1 | Leaf2 | Tree ([Tree]) and I have a function eval :: Tree -> int which returns the winner (Leaf1 indicates that player one won, Leaf2 indicates that player two won) I've been trying to write a test for eval using QuickCheck but I can't seem to understand how it works for recursive data types and how to write tests for this function
common-pile/stackexchange_filtered
MongoDB lookup when foreign field and local field are array of objects I have two collections 'questions' and 'answers'. questions document is like this: [ { _id: "8326ccbn73487290nc", questions: [ {id: "12345", question: "Test", correct_answer: '0'}, {id: "123456", question: "Test 2", correct_answer: '1'}, {id: "1234567", question: "Test 3", correct_answer: '1'}, ] }, { _id: "8326ccbn734872ytruy90nclk", questions: [ {id: "345", question: "Test", correct_answer: '0'}, {id: "3456", question: "Test 2", correct_answer: '1'}, {id: "34567", question: "Test 3", correct_answer: '1'}, ] } ] answers document is like this: { id: '327rhrne7fr873', user_id: '43757fn574057fnf', question_id: '8326ccbn73487290nc', answers: [ { id: '12345', student_answer: '1'}, { id: '123456', student_answer: '0'}, ] } so i want to return something like this: [ { _id: '8326ccbn73487290nc', questions: [ {id: "12345", question: "Test", correct_answer: '0', student_answers: '1'}, {id: "123456", question: "Test 2", correct_answer: '1', , student_answers: '0'}, {id: "1234567", question: "Test 3", correct_answer: '1'}, ] }, { _id: "8326ccbn734872ytruy90nclk", questions: [ {id: "345", question: "Test", correct_answer: '0'}, {id: "3456", question: "Test 2", correct_answer: '1'}, {id: "34567", question: "Test 3", correct_answer: '1'}, ] } ] Can anyone help me how can i do something like that. Is there only one question object in the entire collection?, can a question be in multiple questions objects with different _id ? There can be multiple questions on the entire collection. No, a question can't be on multiple questions with different _id. One more question, can an answer object be matched to 2 question objects? No, it can't be matched on two question objects Shouldn't it be possible to have multiple answers to a question (from different students)? Or do you focus only one student? I want only one answer, because i make get request with user_id. Although it's possible to get your desired structure in MongoDB. If you do not need extra aggregation steps, I would suggest to query only the data you need, and do the data mapping in your application layer, because it's much easier and we don't want to put too much work on the database. However, you can use the following approach to get (close to) your expected output, I have kept the field student_answer, from answers collection and did not rename it to student_answers, you can do the extra steps if needed. db.questions.aggregate([ { $lookup: { from: "answers", let: { question_id: "$_id" }, as: "answer", pipeline: [ { $match: { $expr: { $and: [ { $eq: [ "$question_id", "$$question_id" ] }, { $eq: [ "$user_id", userId // insert user id variable here ] } ] } } } ] } }, { $unwind: { path: "$answer", preserveNullAndEmptyArrays: true } }, // up until this step, you already got all the data you need. You can stop here and do the extra steps in your application layer { $set: { questions: { $map: { input: "$questions", in: { $mergeObjects: [ "$$this", { $arrayElemAt: [ { $filter: { input: "$answer.answers", as: "answer", cond: { $eq: [ "$$this.id", "$$answer.id" ] } } }, 0 ] } ] } } } } }, { $unset: "answer" // cleanup by removing temporary field answer } ]) Mongo Playground You have done great job. Thank you a lot. I have to solve why i got " "Unrecognized pipeline stage name: '$set'" ", when i implement it on my code . My structure looks fine, like yours. You might be on an older MongoDB version, try $addFields instead of $set and { $project: { answer: false } } instead of $unset: "answer" Thank you a lot. This is what i wanted You can use this pipeline under the assumption that an answer object is matched to a single question object. db.answers.aggregate([ { $lookup: { from: "questions", let: {answerIds: {$map: {input: "$answers", as: "answer", in: "$$answer.id"}}}, pipeline: [ { $match: { $expr: { $gt: [ { $size: { $filter: { input: "$questions", as: "question", cond: { $setIsSubset: [["$$question.id"], "$$answerIds"] } } } }, 0 ] } } } ], as: "questions" } }, { $unwind: "$questions" }, { $project: { _id: "$questions._id", questions: { $map: { input: "$questions.questions", as: "question", in: { $mergeObjects: [ "$$question", { $ifNull: [ { $arrayElemAt: [ { $filter: { input: "$answers", as: "answer", cond: {$eq: ["$$answer.id", "$$question.id"]} } } , 0 ] }, {} ] } ] } } } } } ]) Sorry Tom, maybe i wasn't clear. What i wanted on my response is the same JSON like on questions document, but only to add 'student_answer' (if have value). That response i want when i call to get all my questions. Yes, is the response coming back not the case? did you try it? Yes. i try it. I get only that questions that have value on answer collections (in my case i want all questions, and if they don't have value on answer collection), and i don't have correct_answer on my response I think that query will be on question collection, not on answers Can't one question have multiple answers? multiple students ..? it makes more sense to do it from the answers but in theory you can just reverse the $lookup and the rest is pretty much the same. Sure it can have multiple answers. But i want to display all questions, not only that question with value on answers. This is where i have stuck now
common-pile/stackexchange_filtered
PHP. What is the best way to initialize a variable, FALSE, NULL, 0 OR ''? Taking into account boolean, strings and integers. What is the best all purpose way to initialize a variable that is going to cause the least amount of problems. it all depends on what you want to do with the variable and the rest of your algorithm It depends if you know where you are going to use the variable. What its data type is going to be. For instance, array variables: $test = []; If you don't know exactly for what you are going to use the variable then i advise to don't initialize it at all. In my experience, i never met the scenario where I had to necessary initialize a variable if I wasnt sure whats its nature gonna be. We do need arrays to be initialized sometimes and for that i gave the example of initializing empty array. Although initializing a variable with NULL might not serve your purpose if you are planning to use isset() function later on for some reason, and for rest options you mentioned, empty() function will always return true for them so maybe clear your question a bit to exactly what scenario you are talking for. I was wanting initialize variable when starting session that may or may not be used depending what page the user is on. The value is an invoice number selected from the database to be used in different queries on different pages of the website. But my question was meant to be more generic. I was wondering whether there is a basic rule of thumb in PHP? In that case, you can initialize it with NULL and later on can check with condition: if($var !== NULL) but as i said in my answer, you cant generalize this idea. One other reason for that is that if you initialize a variable then memory will get located and it will just slow you down in big applications, PHP converts datatype automatically for you for a reason so that it can be faster. You cant treat it like classic C. NULL make sense. I take on board the memory reason, I can delete it after testing. yes in your case NULL is best option as it doesnt take memory allocation but again in some cases you might need !empty() to actually see if variable is set and it will return false even if variable has NULL value. This is why you cannot generalize this idea. TRUE/FALSE, only use if you want to declare a Boolean variable, like if you want to check if a variable has something then declare another variable with bool $var = "hello"; if ($var == "hello") { $new_var = TRUE; } else { $new_var = FALSE; } NULL variable is use when you want to check if some variable is NULL or not $var = NULL; if ($var != NULL { echo "something"; } sometimes a variable can have value 0 so we cannot check for the empty variable if we assigned it a 0 value $var = 0; if ($var != 0) { echo "something"; } '' is mostly used to initialize a variable so that if i want to check whether a variable is empty or not and works for string or integer etc $var = ''; if ($var != '') { echo "something"; }
common-pile/stackexchange_filtered
How to get rid of value error showing could not convert string to float in python I was running the following code lr=LinearRegression() lr.fit(x_train,y_train) print(lr.coef_) But I was getting error like Value Error: could not convert string to float: '20140527T000000' How can I solve this? Get rid of that string :) or just don't try to do numeric calculations with that data. That strings looks like a date with time. That needs special parsing. It's look like you tried to convert a string that does not contain a float number to a float. If the python string is not formatted as a floating point number, you could not convert string to float. Try to find which column is throwing this error and review the column to find the outliers. If the column only contains numerical and null values, then your code will run without the given error
common-pile/stackexchange_filtered
Android ICS bug: programmatically showing a screen which contains a ListView, results in list becoming unfocusable We have 2 screens: The first screen contains a button for displaying the next screen and a ListView. The ListView items are focusable at first. But when returning from the second screen to the first one ( calling setContentView( ) ), it seems that the list cannot be focused anymore. I'm pretty sure this an Android 4.0 bug, just checking if anyone else has encountered it. Here's the code snippet: public class ListTestActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); createFirstScreen(); createSecondScreen(); setContentView(mFirstScreen); } public void createFirstScreen() { mFirstScreen = new LinearLayout(this); mNextBtn = new Button(this); mNextBtn.setText("Next"); mNextBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { setContentView(mSecondScreen); } }); mListView = new ListView(this); String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" }; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values); mListView.setAdapter(adapter); mFirstScreen.addView(mNextBtn); mFirstScreen.addView(mListView); } public void createSecondScreen() { mSecondScreen = new LinearLayout(this); mBackBtn = new Button(this); mBackBtn.setText("Back"); mBackBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setContentView(mFirstScreen); } }); mSecondScreen.addView(mBackBtn); } private LinearLayout mFirstScreen; private ListView mListView; private Button mNextBtn; private Button mBackBtn; private LinearLayout mSecondScreen; }
common-pile/stackexchange_filtered
Merge and Print Distinct Dictionaries I'm new to Python and I'm learning about dictionaries and I'd like to clarify something. Let's say I have two dicts: d1 = {'id1' : '1', 'id2' : '2', 'id3' : '3', 'id4' : '4'} and d2 = {'fruit1': 'Apple', 'fruit2': 'Banana', 'fruit3': 'Strawberry', 'fruit4': 'Kiwi'}. I'd like to create a new dictioanry d3 with the following content: { 1 : Apple, 2 : Banana, 3 : Strawberry, 4 : Kiwi}. I've read this post How to merge two dictionaries in a single expression? but it's not exactly what I'm looking for. What's the best way to create this new dictionary? Thanks! Use dict and zip: This will work as long as both dicts are aligned Modern python dict order is guaranteed to be insertion order as of v3.7, but should also be the case for v3.6. The values of d1 are str type, so when they are made into keys of d3, they will be str, not int. d1 = {'id1' : '1', 'id2' : '2', 'id3' : '3', 'id4' : '4'} d2 = {'fruit1': 'Apple', 'fruit2': 'Banana', 'fruit3': 'Strawberry', 'fruit4': 'Kiwi'} d3 = dict(zip(d1.values(), d2.values())) print(d3) >>> {'1': 'Apple', '2': 'Banana', '3': 'Strawberry', '4': 'Kiwi'} If you want the keys to be int type: map int to the d1.values() d3 = dict(zip(map(int, d1.values()), d2.values())) print(d3) >>> {1: 'Apple', 2: 'Banana', 3: 'Strawberry', 4: 'Kiwi'} As mentioned in this answer, this only works if the dicts are aligned. In some versions of python, there is no guarantee on the order of keys/values. https://stackoverflow.com/questions/1867861/how-to-keep-keys-values-in-same-order-as-declared
common-pile/stackexchange_filtered
Jest throws TypeError: Cannot read properties of undefined (reading 'isFake') When I run in NX monorepo jest unit tests, In some tests (not in all test files) jest >= 28 throws the error: TypeError: Cannot read properties of undefined (reading 'isFake') 150 | 151 | beforeEach(() => { > 152 | jest.useFakeTimers(); what is an issue in the fake-timers lib on the line: if (_global.Date.isFake === true) { When I downgraded jest to version 27.5.1 all tests are passing. Seems like issue in initialisation of the tests. What could be the issue ? I was able to resolve this issue using legacy fake timers. jest.useFakeTimers({ legacyFakeTimers: true }); In my case, I just solved this by using the fakeTimers Jest config, like so: fakeTimers: { enableGlobally: true, }, Then I removed the individual jest.useFakeTimers(); from my specs. This got rid of the TypeError: Cannot read property 'isFake' of undefined error. Reference: https://jest-archive-august-2023.netlify.app/docs/28.x/upgrading-to-jest28/#fake-timers A colleague and I figured out that fakeAsync and jest.useFakeTimers collide with each other. So this minimal example will break: describe('test', () => { beforeEach(() => { jasmine.clock().install(); jasmine.clock().mockDate(new Date('2023-12-04T00:00:00.000Z')); }); afterEach(() => jasmine.clock().uninstall()); it('should whatever', fakeAsync(() => { expect(42).toBe(42); })); it('2', () => { expect(2).toBe(2); }); it('3', () => { expect(3).toBe(3); }); }); (mind that the first it-block will pass, every other one will fail) Our guess is that jest.useFakeTimers adds the isFake property to the Date object, but fakeAsync then also tampers with the Date object, ultimately removing isFake. In our case we were able to get rid of fakeAsync altogether, others may have to try what h0b0 and Chris Collins wrote. This should be the accepted answer as nor global settings nor legacy ones address the issue of conflict between fakeAsync and useFakeTimers. Thanks for your answer, saved me lot of time / headache.
common-pile/stackexchange_filtered
passing URL variables to php when the link clicked I have URL in this from: locahhost/index1.php?option=com_lsh&view=lsh&event_id=xxxxx&tv_id=xxx&tid=xxxx&channel=x when the user click this link, the file index1.php should process this the URL then produce new URL in this form localhost/static/popups/xxxxxxxxxxx.html wher xxxxxxxxxxxxx is the event_id, tv_id, tid and chanel. to do this I am using parse url function in the file index1.php as following : <?php $url = 'http://localhost/index1.php?option=com_lsh&view=lsh&event_id=&tv_id=&tid=&channel='; $parsed = parse_url( $url ); parse_str( $parsed['query'], $data ); $newurl = 'http://localhost.eu/static/popups/'.$data['event_id'].$data['tv_id'].$data['tid'].$data['channel'].'.html'; header("Location: $newurl"); ?> but its not working i think this is due to something wrong in $url = 'http://localhost/index1.php?option=com_lsh&view=lsh&event_id=&tv_id=&tid=&channel='; what is wrong with this? also i want it when for example tv_id not present in the url it put instead 0 in the newurl $url = 'http://localhost/index1.php?option=com_lsh&view=lsh&event_id=&tv_id=&tid=&channel='; $parsed = parse_url( $url ); parse_str( $parsed['query'], $data ); $keys = array('event_id', 'tv_id', 'tid', 'channel'); // order does matter $newurl = 'http://localhost.eu/static/popups/'; foreach ($keys as $key) $newurl.= empty($data[$key])?0:$data[$key]; $newurl.='.html'; echo $newurl; returns: http://localhost.eu/static/popups/0000.html UPDATE: You do not need to make an $url variable and parse it into an array of values. When user clicks a link data comes with GET method. If you use GET or POST instead of $url, just use $_REQUEST['variable'] (or $_GET[''] or $_POST['']) $keys = array('event_id', 'tv_id', 'tid', 'channel'); // order does matter $newurl = 'http://localhost.eu/static/popups/'; foreach ($keys as $key) $newurl.= empty($_REQUEST[$key])?0:$_REQUEST[$key]; $newurl.='.html'; echo $newurl; @ Andrey volk your code is very good, but one problem is there, how to transfer these values event_id', 'tv_id', 'tid', 'channel from the link that user click on to the $url. very good it works awsome and the job done thank u . another help from u sir assuming the new url will be http://remotesite.com/static/popups/xxxxxxxxxxxx.html and instead of echo that url i need to get the source code of it and create new html file with the same name of xxxxxxxxxxxx.html in the following path mydomain/static/popups and redirect the user to this file Take a look at http://www.php.net/manual/ru/function.file-get-contents.php http://www.php.net/manual/ru/function.file-put-contents.php yes i am confused how to use file put contents but i use its identical fopen(), fwrite() and fclose() but my problem is about the file name as you know it will be differnet every time xxxxxxxxx.html i dont know how to write this in the code ? but thank u at last you have solved my probelm that was distrubing me for three days as ia m newbie $newUrl is malformed. you're missing a close-bracket ] after $data['tv_id'. $newurl = 'http://localhost.eu/static/popups/'.$data['event_id'].$data['tv_id'.$data['tid'].$data['channel'].'.html'; you forgot to close the tv_id array tag in $new_url $newurl = 'http://localhost.eu/static/popups /'.$data['event_id'].$data['tv_id'].$data['tid'].$data['channel'].'.html'; The parse_url function is to take a given URL and turn it into its constituent parts. What you're looking for is to access variables from the $_GET array. I'll assume your event ID is an integer $event_id=(int)$_GET['event_id']; $new_url=''http://localhost.eu/static/'.$event_id // and so forth If you expect text instead of numbers in one of your variables, do some more sanitzation on it. everyone this just missed here when posting the question but i already closed the bracket when trying my question is whole about the $url i think the code miss something the pull the variables from the url clicked by the user to transfer him the the correct new url In the popoup url, are there any seperators between the values? @user2338253 you might want to edit your question to include the missing bracket, so we're not thrown off the track by it. here is where i went with your code <?php $event_id=(int)$_GET['event_id']; $tv_id=(int)$_GET['tv_id']; $tid=(int)$_GET['tid']; $channel=(int)$_GET['channel']; $new_url=''http://localhost.eu/static/'.$event_id.$tv_id.$t1id.$channel.'.html'' echo $new_url ?> but not working is this right?
common-pile/stackexchange_filtered
TypeScript: Create typed Record without explicitly defining the keys What I'd like to do is to create an object which is a Record of a certain interface and have TypeScript be able to infer the keys based on what's in my object. I've tried a few things, none of which do exactly what I'm looking for. interface Person { firstName:string } const peopleObj = { Jason: { firstName: "Jason" }, Tim: { firstName: "Tim" } } as const; console.log(peopleObj); Here, if you look at peopleObj, TypeScript knows the exact keys because of the as const. The problem here is I'm not enforcing each object to be a Person. So I tried this next: const peopleObj: Record<string, Person> = { Jason: { firstName: "Jason" }, Tim: { firstName: "Tim" } } as const; Here, each object has to be a Person because of the Record defined, but TypeScript loses its ability to know all of the keys because now they are just string instead of the constants 'Jason' | 'Tim', and this is the crux of the issue. I know I could explicitly use 'Jason' | 'Tim' in place of my string type, but this is a fairly large object in real life and updating that type explicitly every time I add to it or remove from it is getting to be tedious. Is there a way to have the best of both worlds, where I can have TypeScript infer the keys in the object just based solely on what's in the object? I have found a way, although it's not super clean and I feel like there's likely a better way: interface Person { firstName:string } type PeopleType<T extends string> = Record<T, Person>; const peopleObj: Record<string, Person> = { Jason: { firstName: "Jason" }, Tim: { firstName: "Tim" } } as const; const People:Record<keyof typeof peopleObj, Person> = peopleObj; console.log(People.Jason); For the "pure interface" problem and solution, see https://stackoverflow.com/questions/64641417 Your third method doesn't actually work I believe - as you can access People.foo without error. This is because when you construct peopleObj as Record<string, Person>, its type is now that. You then do keyof Record<string, Person>, which evaluates to string. The only way I'm aware of to achieve this is via using a function with generics. This allows you to apply a constraint on the input parameter, and then return the original type. const createPeople = <T extends Record<string, Person>>(people: T) => people; const myPeople = createPeople({ Jason: { firstName: "Jason" }, Tim: { firstName: "Tim" } }); console.log(myPeople.Jason); console.log(myPeople.foo); // error You have a catch 22 situation otherwise - i.e - I want to enforce that my keys are of type Person, but I don't know what my keys are. One other way that you may prefer - which is basically the same thing but without the function: interface Person { firstName:string } // Force evaluation of type to expanded form type EvaluateType<T> = T extends infer O ? { [K in keyof O]: O[K] } : never; type PeopleType<T extends Record<string, Person>> = EvaluateType<{[key in keyof T]: Person }>; const peopleLookup = { Jason: { firstName: "Jason" }, Tim: { firstName: "Tim" } }; const people: PeopleType<typeof peopleLookup> = peopleLookup; console.log(people.Jason); console.log(people.foo); It is a bit of a contrived example for simplicity's sake. The function method does work for what I need, I just wonder if there's a way to do it without the need for a function. If not, this works, thanks! yep - can't argue with that. I've realised there is an alternative - it involves duplicating the type though, see what you think I'm expanding on @mbdavis's answer because there seems to be an additional constraint, which is that the key for each Person in the record is that Person's firstName property. This allows us to use mapped types. A PeopleRecord should be an object such that for every key name, the value is either a Person object with {firstName: name} or undefined; type PeopleRecord = { [K in string]?: Person & {firstName: K} } Unfortunately it doesn't work the way we want it to if we just apply this type to peopleObj, since it doesn't see the names as anything more specific than string. Maybe another user can figure out how to make it work, but I can't. Like @mbdavis, I need to reassign the object to enforce that it matches a more specific constraint. I use the mapped type ValidateRecord<T> which takes a type T and forces that every key on that type is a Person with that first name. type ValidateRecord<T> = { [P in keyof T]: Person & {firstName: P} } Now we can reassign your peopleObj, which should only work if the object is valid, and will throw errors otherwise. const validatedObj: ValidateRecord<typeof peopleObj> = peopleObj; But it's a lot cleaner to do this assertion through a function. Note that the function itself merely returns the input. You could do any other validation checking on the JS side of things here. const asValid = <T extends {}>( record: T & ValidateRecord<T> ): ValidateRecord<T> => record; const goodObj = { Jason: { firstName: "Jason" }, Tim: { firstName: "Tim" } } as const; // should be ok const myRecordGood = asValid(goodObj); // should be a person with {firstName: "Tim"} const A = myRecordGood["Tim"] // should be a problem const B = myRecordGood["Missing"] const badObj = { Jason: { firstName: "Bob" }, Tim: { firstName: "John" } } as const; // should be a problem const myRecordBad = asValid(badObj); Playground Link
common-pile/stackexchange_filtered
Is it possible to update a field with the result of mysql concat and join? Is it possible to update a field with the result of mysql concat and join? select CONCAT_WS(' - ', r.spare, r.assembly, r.model) reemplazos from TblPartes p left join TblReemplazos r on p.codigo1 = r.Option where p.codigo1 = 'V4-VS07-040' I get 3 rows of results with multiple columns. reemplazos 005050748 - 005050148 - 005050749 005050149 - 005050552- 005050953 005052065 - 005052064 but if I use update, the result of the update its only the first row. 005050748 - 005050148 - 005050749 update TblPartes As p left JOIN TblReemplazos As r On p.codigo1 = r.Option Set p.stock_reemp = CONCAT_WS(' - ', r.spare, r.assembly, r.model) How can make the update using the result of the first select? (concat all rows) I need something like this update TblPartes As p left JOIN TblReemplazos As r On p.codigo1 = r.Option Set p.stock_reemp = select CONCAT_WS(' - ', r.spare, r.assembly, r.model) reemplazos from TblPartes p left join TblReemplazos r on p.codigo1 = r.Option TblReemplazos id option spare assembly model 1 V4-VS07-040 005050748 005050148 005050749 2 V4-VS07-040 005050149 005050552 005050953 3 V4-VS07-040 005052065 005052064 4 V8-VS08-080 8811uu33 8811uu44 8811uu55 TblPartes id codigo1 stock_reemp 1 V4-VS07-040 2 V8-VS08-080 TblPartes(desired result) id codigo1 stock_reemp 1 V4-VS07-040 005050748 - 005050148 - 005050749 - 005050149 -005050552 -005050953 - 005052065 - 005052064 2 V8-VS08-080 8811uu33 - 8811uu44 - 8811uu55 Thanks. Please add the original data, not just the results, so I can try to run the query myself. GROUP BY without any aggregation functions is usually a mistake. Unless you've disabled the ONLY_FULL_GROUP_BY SQL mode, or option is the primary key, your original query should have gotten an error. If you're only getting one row updated, it means that none of the other rows have a matching codigo1 = option The original query was just an example of what I was trying to do. It is not a functional query. What I want is to Update the TblPartes.stock_reemp Field With the Result of the CONCAT_WS The relationship makes it TblPartes.codigo1 with TblReemplazos.option I have updated the original post again. Why do you think you need TWO left joins of the same thing? If you want to use a subquery as a value, you have to put it in parentheses. But the correlated subquery should produce the same result as a join,. Your latest update still doesn't show the original contents of the two tables. And your output doesn't show the value of the tblPartes.codigo1. Sorry, I'm new to the site. I have reflected example of the tables and the desired result You need to use GROUP_CONCAT() to combine the values from multiple rows. This means you need to join with a subquery that uses GROUP_CONCAT(). Also, option shouldn't be in the CONCAT_WS(). update TblPartes AS p left join ( SELECT `option`, GROUP_CONCAT(CONCAT_WS(" - ", spare, assembly, model) SEPARATOR ' - ') AS stock_reemp FROM TblReemplazos GROUP BY `option` ) AS r on p.codigo1 = r.`option` set p.stock_reemp = r.stock_reemp; DEMO I've updated the answer now that you showed that it needs to use GROUP_CONCAT(). Magnificent. So easy for you, and it took me all day. I really appreciate the time you gave me. So there was a reason why you were using GROUP BY in the original query! Yes, the only thing I don't know how to do now is how to avoid repeated registrations in the CONCAT_WS fields(" ", option, assembly, model) it's possible? If not it does not matter. You mean you're getting duplicates? You can use GROUP_CONCAT(DISTINCT CONCAT_WS(...)) I tried that before, but it didn't work. I think it's because sometimes there are repeated fields in different places at the same time. I'm not really sure what kind of repeated registrations you're referring to. If spare is repeated with different assembly or model, is it really a repetition? You can ask a new question where you show sample data that has the duplicates you want to avoid, and the expected result. thanks again Barmar, i made a new question. I can't find it. Did you delete it?
common-pile/stackexchange_filtered
Change <div> background image with javascript I've this in my html file <div class="change"> <div id="changed" onclick="change_DImage()">New Upload...</div> <input id="browse" type="file" onchange="ImagLoc()"> </div> and this in javascript file function change_DImage(){ document.getElementById("browse").click(); } function ImagLoc(){ var x = (document.getElementById("browse").value).toString(); var ImgId = x.substr(12,6); var NewImg = "url('./image/MyAlbum/" + ImgId + "')"; document.getElementById("dailyPic").style.backgroundImage = NewImg; } it's work pretty well but when I refresh my browser it'll change back to the default for this in css file background-image: url("../image/smokebird.jpg"); try with local storage or server side script php Welcome to SO. JavaScript is client side scripting which will do what have described just above. However there is a way to make it stick. Check this link out https://stackoverflow.com/questions/16206322/how-to-get-js-variable-to-retain-value-after-page-refresh Possible duplicate of How to get JS variable to retain value after page refresh? On page reload obviously image is going to reset to the original image. To keep it as it is even after page refresh you can do, Save the image in Cookie (base 64 format), but there is a size limit since you can save small size images only. On image select, you can save the image file remotely on your server asynchronously (using AJAX) and you can recall the image using the server session. Javascript manipulates the only current state of the Html, not the file on server side. To handle it, you have to store state on server side, and change it both client and server side on button click. Storing changed value on browser's cookie or local storage, and get stored one on page load is another option. localStorage example:jsfiddle However localStorage can be easily cleaned by user, even by mistake. I have found this answer useful about how it can be cleaned: SO link. Other drawback (if your really care about it) is a need of use Inline styling. There is attr css function but other than content usage is currently limited so I would stick to Inline styling. I made more understandable version including your code, here: jsfiddle, however I am not sure what this line and function suppose to do so I have removed it: <div id="changed" onclick="change_DImage()">New Upload...</div> Edit: obviously second jsfiddle code will not work on jsfiddle, you need to inject it to your code.
common-pile/stackexchange_filtered
What does $\frac{dx}{dt}$ mean? If $x = 3t-2$, with $x$ in units of meters and $t$ in units of seconds then the velocity is $$V = \frac{dx}{dt} = 3\,\text{m}/\text{s}$$ How is the answer $3$ m/s? What does $\frac{dx}{dt}$ mean? It stands for the derivative of $x$ with respect to $t$. It's a very widely used concept in mathematics, but I suggest against learning about it through physics. Grab a math textbook instead. I've been trying that. I still don't understand. If you don't know about derivatives then it does not make much sense to ask this question. You need to go back and learn what derivatives are and how to take derivatives of simple functions like $3t-2$. Well, it took me several months to learn derivatives when I first heard of them, so don't panic. Isn't 3t-2 just 1? @user366783 You have a long way to go if you think $3\cdot t - 2$ is equal to $1$... And I don't mean to be insulting. I want to say you need to slow down - you can't learn to run unless you first learn how to walk. It should be 1. Look, (1) 3 t 1-0 - 2. That's 1. "$3t-2$" is a function, specifically a line. It has slope $3$ and $y$-intercept $2$. It is not constant. (To be constant, it must have slope $0$.) So this line is not constantly $1$. SO how would I manipulate the #s to get 3 m/s? Are you familiar with limits? Could you, for instance, compute $\lim_{t \rightarrow 2} 3t - 2$? I took calculus last semester, but I don't remember it at all. Was it 3(t) -2 = 4? Assuming that's an innocent typo, do you recall/have available the definition of the derivative? A bar of expensive chocolate says user366783 is trolling. You wouldn't believe how often I get accused of being a troll. Why do you think that's the case? @user366783, you sure you are not trolling? Why do you think I'm trolling? $x$ is the way in $m$ and $t$ is the time in $s$ . $d$ means infinitesimal small differenz $\frac{dx}{dt}=\frac{d}{dt}(3t-2)=\lim\limits_{h\to\pm 0}(\frac{[3(t+h)-2]-[3t-2]}{[t+h]-[t]})\frac{m}{s}=\frac{3h}{h}|_{h\to 0}\frac{m}{s}=3\frac{m}{s}$ If $x= 3t -2$ describes a coordinate, $x$, in function of time $t$, then $\frac{dx}{dt}$ represents the rate of change of the coordinate, $x$, in time $t$, i.e. velocity. $\frac{dx}{dt}$ is sometimes called instantaneous rate (as opposed of average rate of change $\frac{\Delta x}{\Delta t}$) of change of $x$ with respect of $t$. If the same equation represents a line on the 2D plane, then the ratio $\frac{dx}{dt}$ represents the slope of line tangent to the line represented by the original equation. To understand the result better check the rules for differentiation.
common-pile/stackexchange_filtered
How to add a conditions in V-select? hi every one i want to filter my property like min. bedroom and max bedroom here i have two listbox one is minimum bedroom listbox and another one is maximum bedroom listbox if i select 3 from minimum bedroom as well as 5 from maximum bedroom list this time i want to filter only 3 - 5 range bedrooms properties export default { data() { return { blogs: [], minbed: "", maxbed: "", }; }, selectOptionsBedroom() { return _.uniqBy(this.blogs.map(g => g.Bedrooms)); } }; <v-select :items="blogs" v-model="minbed" :options=" selectOptionsBedroom" label="Bedrooms" item-value="Bedrooms" placeholder="Min.Bed" ></v-select> How to create a condition here? minimum and maximum exactly for what? minmum bedroom and maximum bed room https://snag.gy/5AXZqV.jpg it's answered sooner if you more clarify you question :) i updated the description can you check now Use filter with a computed property: new Vue({ el: '#app', data() { return { blogs: [], minbed: 0, maxbed: 0, } }, computed: { min: { get() { return this.minbed }, set(value) { this.minbed = value } }, max: { get() { return this.minbed >= this.maxbed ? parseInt(this.minbed, 10) + 1 : this.maxbed }, set(value) { this.maxbed = this.minbed >= value ? parseInt(value, 10) + 1 : value } }, selectOptionsBedroom() { return !!this.blogs.length ? this.blogs.filter(g => { return (g.Bedrooms >= this.min) && (g.Bedrooms <= this.max) }) : [] } }, mounted() { this.blogs = Array.from(Array(20), (x, i) => { return { Name: `Blog ${i + 1}`, Bedrooms: Math.ceil(Math.random() * 5) } }) this.minbed = 0 this.maxbed = this.blogs.reduce((max, blog) => { return (blog.Bedrooms > max) ? blog.Bedrooms : max }, 0) } }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.js"></script> <div id="app"> <label>Min</label> <input type="number" step="1" min="0" v-model="min"> <label>Max</label> <input type="number" step="1" min="1" v-model="max"> <ul v-if="selectOptionsBedroom.length"> <li v-for="item in selectOptionsBedroom" :key="item.Name">{{ item.Name }} - {{ item.Bedrooms }} {{ item.Bedrooms > 1 ? 'rooms' : 'room' }}</li> </ul> <p v-else-if="!!minbed && !!maxbed">No Results</p> <p v-else>Search for blogs</p> </div> thanks you but above code its dosnt work i changed this code like ' .filter(blog => blog.Bedrooms >= this.minbed ) ' its working for minimum if i using maximum filter code that time its dosnt work ; i think one filter at the time ; how can i fix this for maximim '.filter(blog => blog.Bedrooms <= this.maxbed )" It just needs some parentheses wrapping the comparisons. The filter callback can contain any kind of logic provided it returns a boolean value. Have a look at the updated answer. its working but the page loading time only showing zero bedrooms Properties - loading time i want see all properties - i try to changed minbed value but its not working that much Updated the answer. its working in here - i have one field like 'ST' Its mean STUDIO Apartment how to filter this one '"Bedrooms": "ST",' how to add place holder i try it this one ' placeholder="Quantity" ' its not working
common-pile/stackexchange_filtered
Would like to do a previousquarter calculation but for the first quarter show the value without the calculation I have dax written that returns the sales by subtracting the sales ytd by sales ytd in the previous quarter, this is to show on a pie chart or donut chart. I would like some help as I would also like to show the first quarter without the calculation. My current dax is shown below: Measure = VAR RESULT = CALCULATE( [Sale YTD], PREVIOUSQUARTER(dimSalesDate[DATE]) ) RETURN [Sale YTD] - RESULT my data: quarter no sales ytd 1 50,000 2 70,000 3 150,000 4 280,000 what I want to show in a pie/donut chart quarter no sales ytd 1 50,000 (no calculation) 2 20,000 (calculation: 70,000 - 20,000) 3 80,000 (calculation: 150,000 - 70,000) 4 130,000 (calculation: 280,000 - 150,000) I think you may be looking for something like this: Sales YTD Less Prior Quarter = VAR RESULT = IF ( SELECTEDVALUE(dimSalesDate[Quarter]) = 1, [Sale YTD], [Sale YTD] - CALCULATE ( [Sale YTD], PREVIOUSQUARTER ( dimSalesDate[DATE] ) ) ) RETURN RESULT I am guessing it has to be a calculated column and not a measure No, this should be a measure so that it can adjust to active filters and dynamic time ranges. I used the above dax but for quarter no: 1 I am getting a minus number -111,072. The code is almost the same only difference being I put SUM around the dimSalesDate[Quarter] field as it was not recognising it oh, sorry, I did not test this. It should use SELECTEDVALUE. I'll update it and please see if that makes a difference Thanks for that, the above code worked :)
common-pile/stackexchange_filtered
Is load balancing or HA setup recommended? I have an application which is running on a webserver(ws1) and connected to a app server(as1). I have the same application running on another webserver(ws2) and another appserver(as2). But I have only one reverse proxy server. So my setup is something like So currently I am load balancing between these servers. My Nginx configuration looks like this: http { upstream myapp1 { server ws1.example.com; server ws2.example.com; } server { listen 80; location / { proxy_pass http://myapp1; } } } But is it better to load balance by Nginx or to make the HA setup. If I make HA setup should the web server and app server be clustered? It's fine. You can add another identical server that can take it's place with keepalived. My question is the load balancing with one nginx is good or should I have another nginx server and do the HA setup? Your current setup leaves the Nginx load balancer as the single point of failure. If you want to eliminate that you could potentially do it with DNS. Remove the reverse proxy (or create another), have A records for either the web servers directly or the reverse proxies if you keep them. Clients should load balance across both - you'd clearly want to research and test that thoroughly before doing anything similar in production. Using AWS Route53 could help with that, as it randomises the order of A records returned for each query. It's all very good to load balance the servers, but if the server providing the load balancing was to fall over, neither of the other two servers would be accessible. One way to resolve that is to set up an HA arrangement so that if the load balancer was to drop out, another server would immediately take it's place. To provide the HA you can use a service like keepalived which uses the VRRP protocol to provide a highly available Internet Address. In fact, it works very well. A configuration similar to the following would work. Lets say you want a service to be visible at <IP_ADDRESS> Create 2 machines with one with IP <IP_ADDRESS> and the other with IP <IP_ADDRESS> Install keepalived service on both. Remember to set: net.ipv4.ip_nonlocal_bind = 1 In sysctl.conf on both machines. Set up with nginx config as described. First Nodes keepalived.conf: vrrp_instance VI_1 { state MASTER interface eth0 virtual_router_id 51 priority 150 advert_int 1 authentication { auth_type PASS auth_pass secretpass } virtual_ipaddress { <IP_ADDRESS> } } Second Node: vrrp_instance VI_1 { state BACKUP interface eth0 virtual_router_id 51 priority 150 advert_int 1 authentication { auth_type PASS auth_pass secretpass } virtual_ipaddress { <IP_ADDRESS> } } Now what'll happen is when the master machine is running, it will provide the virtual ip <IP_ADDRESS> If you stop this machine, the other will take over the IP. Fuller example: Simple keepalived failover setup on Ubuntu 14.04 So byt the method you are suggesting do i need a seperate nginx server or not? Could you please clarify this? Correct. A separate phydical machine. Although if you were to host this on amazon or Google they have a loadbalancer service and all that ha stuff is handled for you. That might be a better long term plan rather than self hosting. I might vote to close your question... is not clear what you are asking. I'm guessing. @Ronak, Mat in his answer offer you solution, how to make failover for your revers-proxy. Keepalived could be installed on revers-proxy machines, so you'll have two reverse-proxy machines with one shared IP-address.
common-pile/stackexchange_filtered
Uniform bound of an integral of a sum of cosines Let's define an integral $$\int_{\epsilon}^{\eta} \cos(2\pi Rr |x'\cdot y'|) - \cos(2 \pi R r) \frac{dr}{r} $$ where $0<\epsilon<\eta < \infty$, $R>0$ and $x',y'\in \mathbb{R^n}$ (not really important since $|x'\cdot y'|$ is just a positive real number). This integral comes up in a proof on singular integrals commuting with dilations in Steins book "Singular Integrals and Differentiability Properties of Functions" by Stein on page 40f if anyone is interested. The claim is that this integral is uniformly bounded in $\epsilon$ and $\eta$ by $$ C + C\log\frac{1}{|x'\cdot y'|} $$ (where $\log$ is the natural logarithm) "as an integration by part shows" (Stein is known for his notorious understatement of not-so-trivial observations). Can anyone help me out how to see this?
common-pile/stackexchange_filtered
Laravel prevent updated_at from updating for specific query I am using the standard updated_at and created_at on a table. My results are ordered by updated_at since they can be edited. However, on a page I am updating a row counter (views). This means that the updated_at will be updated with the new date/time but I want to prevent this. Is there any way to do this? Or am I going to have to use created_at to order my results? I would rather not use my own manual created_at and updated_at class ModelName extends Eloquent { public static $timestamps = false; } That would just remove them, I want to keep them but prevent updating the updated_at for a specific query Never mind, found the answer here http://stackoverflow.com/questions/18904853/update-without-touching-timestamps-laravel For single model queries: $product->timestamps = false; $product->save(); For multiple model queries use DB::table('products')->...->update(...) instead of Product::...->update(...) You can do $product->fill($fields); $product->save(['timestamps' => false]); and encapsulates this into a utilities class (e.g. \App\Utils\Models\Products::saveProductNoUpdateAt(\App\Models\Product $product, array $fields)). Then you have no DB (no model abstraction) but still a single place for deactivating auto-update of updated_at. Remove "on update current timestamp" from DB
common-pile/stackexchange_filtered
$\{(x,y): x, y \in \mathbb{Z} \}$ is closed?? Is the set $\{(x,y): x, y \in \mathbb{Z} \}$ open, closed, both, or neither? My believe is that this is a closed set. However, I do not know how to prove it. Can someone give some light into this problem? Thanks. Open/closed in which space? Which definitions of "open" and "closed" do you prefer? Whichever ones you choose are likely to be quite straightforward to check. I'll assume you are using the standard topology on $\mathbb{R}^2$. Hint: what limit points does your set have? Likewise @Boris, I assume your topology is the usual one. Now use this fact that $\mathbb Z\subset\mathbb R$ has no any limit point in $\mathbb R$. In fact if $a\in\mathbb R$, we can find (or choose) $\delta>0$ so small that $(a-\delta,a+\delta)\cap\mathbb Z=\{a\}$. Nice example/illustration! If you mean the usual topology of the plane, then $\mathbb{Z}\times\mathbb{Z}$ is closed, e.g., since $(\mathbb{R}\times\mathbb{R})\setminus(\mathbb{Z}\times\mathbb{Z})$ is open. Hint: The union of a locally finite collection of closed sets is closed.
common-pile/stackexchange_filtered
how display text depending on an observable value with knockout i am having some issue displaying a text based on the value of a select Tag here is how my viewModel looks like : viewmodel ={ myValues: ["1", "2", "3", "4", "5", "6", "7", "8", "9"], quantityWanted: ko.observable("2") } and here is my View <select data-bind="options: myValues, value: quantityWanted"></select> now i want to display this span only when the selected value egual 1 something like this <span data-bind="visible: viewmodel.quantityWanted == 1">is on</span> i tried viewmodel.quantitywanted.subscribe(function(){}); but it works only when i am on the same view. how can i change the visibility depending on the select value? can anyone help me on this thx When writing expressions in your data-bind attribute you'll need to add () for any observables. <span data-bind="visible: quantityWanted() == 1">is on</span> Should work. Try it without viewmodel. (See my edit.) Also please be more specific with how it's not working. Is it always displayed? Always hidden? Are there any console errors? an other question how do you deal with strings? let say i use word in myValues this wont work data-bind="visible: quantityWanted() != one" quantityWanted() == 1 works in this case because you are doing a loose comparison with == comparing the integer 1 to the the string '1' data-bind="visible: quantityWanted() != 'one'" works fine :-)
common-pile/stackexchange_filtered
Rank for symbol table How would I return the number of keys that is less than the given key? I just don't know where to start. I have the base start but other than that I dont know where to begin public class LinkedListST<Key extends Comparable<Key>, Value> { private Node first; // the linked list of key-value pairs // a helper linked list data type private class Node { private Key key; private Value val; private Node next; public Node(Key key, Value val, Node next) { this.key = key; this.val = val; this.next = next; } } public int rank (Key key) { if(key == null) return 0; //TODO } EDIT: This is what I have so far but my for loop is wrong and is giving me errors public int rank (Key key) { int count = 0; for(Node x = first; x != null; x = x.next){ if(x.next < key){ count++; } return count; } } As you can see in my answer, I have x.key < key, not x.next, because x.next is a Node, not a Key. Your { } are not in the right place, for one. You are returning in the middle of each loop pass. Perusing Comparable will also help you with the correct method of comparing Comparable objects. Hint: it isn't <. Oh thank you, I didn't realize I had put my counter there. and would it be if (current.key.compareTo(key) > 0) count++; ? By current, I assume you mean x? Then no, I think you've got your comparison backwards. But can current.key be null? You originally tested if the key being passed in was null. So writing key.compareTo(x.key) > 0 might be a better test. Thank you for the help, it is now working fine! Pseudo code: initialize counter to zero loop over all nodes, starting at first: if node's key < key: increment count return count That should get you started. EDIT Ok, so you've actually posted a real attempt at writing the code, which is the secret to getting real help on Stack Overflow. Your code, with proper indentation, ... public int rank (Key key) { int count = 0; for(Node x = first; x != null; x = x.next){ if (x.next < key){ count++; } return count; // <-- Note! } } ... shows a return statement inside the loop. Not exactly what you wanted. The if (x.next < key) is also giving you grief, because you need to compare Key with Key, not Node with Key. Finally, the Comparable interface requires the the Key to implement the compareTo(Key other) method. Used like: key.compareTo(x.key) This returns a -1, 0, or 1 depending on which is larger or if they are the same. So you really want: if (key.compareTo(x.key) < 0) { or if (key.compareTo(x.key) > 0) { Exercise left to student. I have added my code but my for loop is wrong and is giving me errors by the way this is an unordered symbol table Neither my nor @engineer's pseudo code assumed the list was sorted. Your code is almost there, but you have three issues: The return statement is inside the for loop. If you corrected the indentation, you'd see that. Move it outside. You don't want to compare x.next to key. You want to compare x.key to the key parameter. You cannot compare using the < operator. Since Key is Comparable, you can compare by calling compareTo(). Here is the updated code: public int rank (Key key) { int count = 0; for (Node x = first; x != null; x = x.next) { if (x.key.compareTo(key) < 0){ count++; } } return count; } I had fixed the return statement, I didn't realize i had put it there. And thank you, do you know an easier way to approach these types of data structures? Ive been having a hard time with nodes and linked lists @yenyen Nope, that's it. @yenyen , don't reinvent the wheel (you already have some data structures in Java). Otherwise, this is the way.
common-pile/stackexchange_filtered
Configure Same offset for Kafka consumers from different groups I have ServiceA which produces DomainChangeEvents and commits them into topic in kafka, then ServiceB consumes this events from kafka topic and applies changes to a read model stored in memory. Some of DomainChangeEvent's are reset events and those reset domain to starting point. On restart of ServiceB i want to read ChangeEvents from last reset and re-build domain afterwards. ServiceB is lunched in docker as replicated service. As i want all ChangeEvents in each replica of ServiceB i cannot give them same group.id or messages will be loadbalanced and i won't get all events in all replicas. How can i configure ServiceB to continue from latest reset event after restart? I tried setting random group.id on ServiceB and committing reset message after i consume it but after restart i have different group.id so all messages are consumed from the start again. Thought about giving different configuration to docker replicas but as i read docker service is configured to be identical in all replicas and thats not an option. Do you need to keep all DomainchangeEvents, i.e. those prior to the last reset event? To me it sounds like instead of reset events you really want to clear your topic and start anew. A possible solution would be storing those points you want your different consumers to start from, by manually committing the offset to, for example, a database. A table that would look like: Topic Partition Offset topicA 0 112 topicA 1 125 topicB 0 2313 topicB 1 2984 topicB 2 2554 Those would be your "latest reset" points, or positions your consumers want to start from. The problem with the subscribe() method , as you correctly said, is that it depends on the group.id parameter, and plays the consumer rebalancing and coordination game. In order to consume from a fixed point (or set of points in different partitions), you should make a call to assign() instead. With this method, you'll be able to manually specify a list of partitions to your consumers. No group.id, no dynamic partition assignment nor offset loading, which is what you seem to need. After assigning the partitions, you should make a call to seek(). With seek, you are telling the consumer from which offset you want to start reading from the partition that was specified on the assign() method. For example, to start reading from the "latest resets" from any topic, you should do something like: //seeking the last offset of topicA's partition0 public void setStartPosition(TopicPartition partition, long offset) { consumer.assign(Collections.singletonList(partition)); //f.e-> partition0 consumer.seek(partition, offset); //f.e -> 112 } Calling this method will position your consumer exactly in the desired position in each partition. I'm not really sure if I'm answering your issue, but hope it helps! You can also start reading from Kafka's __consumer_offsets topic, which persists the committed offsets. This effectively replaces the database in this design.
common-pile/stackexchange_filtered
Angular JS Data table - Alphanumeric sorting I'm currently using angular-datatables and I'm not able to sort the rows correctly. I have an alphanumeric field to be sorted as follows: 1 2 3 4a 4b 11 13a 13b. But when I use datatable sorting, it sorts in the following manner: 1 11 13a 13b 2 3 4a. I tried using the natural sort plug-in for datatables but still getting the same output. How can I sort alphanumeric values in datatables using angularjs? From the official close reasons: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. That is the alphanumerical order what you are getting, JavaScript sort function it's comparing the values (text) letter by letter, so 11 > 2 because the first letter were compared and the 1 is grater than the 2. So if you want another order I think you have to write your own algorithm (function).
common-pile/stackexchange_filtered
STM32F031 - Code runs in line-by-line debugging but not otherwise. Some functions only run if defined as macros I am writing code for the STM32F031K6T6 MCU using the Keil uVision. The IDE information is shown in the image below: enter image description here The C/C++ options for Target are configured as shown here: enter image description here I started a new project, selected the chip, and configured the run-time environment as below: enter image description here I initialized the clock and configured the Flash registers for the appropriate latency. I tested the frequency using MCO and it seems correct. I also initialized some GPIOs, UART, and the SysTick. The peripheral registered is modified as expected as seen on the System View for the respective peripheral in the debugging mode. The problem is that some functions, such as functions for sending and receiving data via UART and some functions that use GPIO ports only work in debugging mode when I run the code line-by-line. If I click the run button the code gets stuck and the chip stops responding. I still see the VAL and CURRENT registers of the SysTick updating. This is an example of a function that works: void System_Clock_init(void){ FLASH->ACR &= ~FLASH_ACR_LATENCY; FLASH->ACR |= FLASH_ACR_LATENCY | 0x01; RCC->CR |= RCC_CR_HSION; while((RCC->CR & RCC_CR_HSIRDY) == 0); RCC->CR &= ~RCC_CR_HSITRIM; RCC->CR |= 16UL << 3; RCC->CR &= ~RCC_CR_PLLON; while((RCC->CR & RCC_CR_PLLRDY) == RCC_CR_PLLRDY); RCC->CFGR &= ~RCC_CFGR_PLLSRC; RCC->CFGR |= 10UL << 18; RCC->CFGR &= ~RCC_CFGR_HPRE; RCC->CFGR &= ~RCC_CFGR_PPRE; RCC->CR |= RCC_CR_PLLON; while((RCC->CR & RCC_CR_PLLRDY) == 0); RCC->CFGR &= ~RCC_CFGR_SW; RCC->CFGR |= RCC_CFGR_SW_PLL; while((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL); } This is an example of a function that doesn’t work: void UV_LED_Driver(uint32_t d){ for(uint32_t i = 0; i<16; i++){ if(d&(((uint32_t)0x8000)>>i)){ SDI2_ON; } else { SDI2_OFF; } CLK2 } LATCH2 } The macros used in the function above are defined as below: // CLK2 -> PA5 // LE2 -> PA4 // SDI2 -> PA6 #define CLK2_OFF GPIOA->ODR |= (1UL << 5) #define CLK2_ON GPIOA->ODR &= ~(1UL << 5) #define LE2_OFF GPIOA->ODR |= (1UL << 4) #define LE2_ON GPIOA->ODR &= ~(1UL << 4) #define SDI2_ON GPIOA->ODR &= ~(1UL << 6) #define SDI2_OFF GPIOA->ODR |= (1UL << 6) #define CLK2 {CLK2_ON; us_Delay(1); CLK2_OFF;} #define LATCH2 {LE2_ON; us_Delay(1); LE2_OFF;} The GPIO pins used in the function above are initialized as follows: // CLK2 -> PA5 // LE2 -> PA4 // SDI2 -> PA6 void UV_LED_Driver_Init(void){ RCC->AHBENR |= RCC_AHBENR_GPIOAEN; GPIOA->MODER &= ~((3UL << 8) | (3UL << 10) | (3UL << 12)); GPIOA->MODER |= ((1UL << 8) | (1UL << 10) | (1UL << 12)); GPIOA->OTYPER &= ~(0x70UL); GPIOA->PUPDR &= ~((1UL << 8) | (1UL << 10) | (1UL << 12)); GPIOA->OSPEEDR &= ~((3UL << 8) | (3UL << 10) | (3UL << 12)); GPIOA->OSPEEDR |= ((1UL << 8) | (1UL << 10) | (1UL << 12)); GPIOA->ODR |= (0x70UL); } And the us_Delay() function is based on SysTick. These are defined as: static uint32_t usDelay = 0; void SysTick_init(uint32_t ticks){ SysTick->CTRL = 0; SysTick->LOAD = ticks - 1; NVIC_SetPriority(SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); SysTick->VAL = 0; SysTick->CTRL |= SysTick_CTRL_CLKSOURCE_Msk; SysTick->CTRL |= SysTick_CTRL_TICKINT_Msk; SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk; } void SysTick_Handler(void){ if(usDelay > 0){ usDelay--; } } void us_Delay(uint32_t us){ usDelay = us; while(usDelay != 0); } Now, this is the same UV_LED_Driver(uint32_t d) function defined as a macro (Runs as expected): #define UV_LED_DRIVER(d) {for(int i = 0; i<16; i++){if(d&(0x000F>>i)){SDI2_ON;}else {SDI2_OFF;}CLK2}LATCH2} This is the main(): #include <stm32f031x6.h> #include "clock.h" #include "LED_Driver.h" #include "UART.h" int main(void){ System_Clock_init(); Color_LED_Driver_Init(); UV_LED_Driver_Init(); Nucleo_Green_LED_Init(); UART_init(); SysTick_init(47); //MCO_Init(); // Check PIN 18 (PA8) for the frequency of the MCO using an Oscilloscope while(1){ UV_LED_DRIVER(~(0x0000)) // This runs well //UV_LED_Driver((uint32_t)~(0x0000)); // If I run this line //the debugger gets stuck here. It works if I run line-by-line ms_Delay(100); UV_LED_DRIVER(~(0xFFFF)) // This runs well //UV_LED_Driver((uint32_t)~(0xFFFF)); // If I run this line //the debugger gets stuck here. It works if I run line-by-line ms_Delay(100); } } Interestingly, if I define the functions as macros, they behave as desired. I finally tested the code on a STM32F429ZIT chip and it worked well, given the needed modifications in the initialization of the main clock and the GPIO. Has anyone ever experienced anything similar or happens to know what could be causing this issue? I know that I could walk around this issue using CubeMX but I would like to find out what is causing this problem. Thank you. Have you tried making usDelay volatile? Function and macro code is not identical. There's no such error as "functions stop working". What you describe sounds very much like a stack overflow however. There's a difference between functions and function-like macros, namely the stacking of parameters and return address. If your stack is toast, the symptom occurring when you call a function may be crashes or run-away code etc. So you'll need to monitor the stack to rule out stack overflows before anything else. Also please don't invent your own private, evil macro language with abominations like #define CLK2 {CLK2_ON; us_Delay(1); CLK2_OFF;}. Either use static inline functions or spell out those items in the macro explicitly. "Do not repeat yourself" is a pox when taken beyond what's reasonable - it causes very bad and dangerous programs. "Keep it simple" wins over "Do not repeat yourself" 10 times out of 10. @alagner I haven't tried that initially, but the user that gave me the answer at the ST community forum made the same remark. @Armandas Right. But the macro code is how I first wrote the function. I tried changing the types to see if that would be the cause of the problem. But it wasn't. I asked the same question at the ST Community forum and the user waclawek.jan answered it. The problem is that I was calling the SysTick interrupt too often, not leaving any time for the main() to run. To fix the code, I just called the SysTick_init() function passing "479" as an argument instead of "47". Thank you!
common-pile/stackexchange_filtered
Send push notification directly from nodejs backend to react-native/expo App I am working on a mobile app using react native/expo. Now I need to perform the task of sending notifications. I'm thinking of using a NodeJS backend (this one is connected to a MongoDB database to store the tokens) to send notifications to all users. I have found that you can use Firebase or also the expo push notification tool. But those are external services. Does anyone know of a way to send notifications directly from your own server made in nodeJS (without the need to use firebase). I appreciate your responses. I have never used react-native but does using socketio for features like live notificationa work for you ? Thanks @Halil , Interesting point. I am going to investigate if it is possible to connect socketio with react native, because I know socketio is usefull for webs.
common-pile/stackexchange_filtered
How to structure a flow graph with a blocking input source What is a good way to modify Michael Voss' Feature Detection flow graph example when the source filter providing input images is blocking waiting for another image? This is a required modification if one wants to implement this graph for a continuous real-time input source like a video camera. I know that if the source filter function body is blocking waiting to pull an image from an input device, then one of the tbb threads will be wasted because it is idle. I appreciate any guidance. There is async_node that is released in the TBB 4.3 Update 6 as a preview feature. The goal of this node is exactly fit for your needs. Here is the link to documentation https://www.threadingbuildingblocks.org/docs/help/reference/appendices/community_preview_features/flow_graph/async_node_cls.htm You can create your own thread that will retrieve images from some source and using async_node::async_gateway push this messages to the graph. The advantage of such approach is that image retrieval will be done outside of TBB threads. This allows to execute other TBB tasks while your threads will wait for next image.
common-pile/stackexchange_filtered
SignalR cross domain and IIS 7.5 path to hub only works locally on the server, how to access it externally? I am self hosting a SignalR Hubs server within my C# WinForms application: string url = "http://localhost:8081/"; m_signalrServer = new Microsoft.AspNet.SignalR.Hosting.Self.Server(url); // Map the default hub url (/signalr) m_signalrServer.MapHubs(); // Start the SignalRserver m_signalrServer.Start(); My ASP.NET web application is acting as the SignalR Hubs JavaScript client: <script type="text/javascript" src="/Scripts/jquery.signalR-1.0.0-alpha2.min.js"></script> <script type="text/javascript" src="http://localhost:8081/signalr/hubs"></script> <script type="text/javascript" language="javascript"> $(document).ready(function() { $.connection.hub.url = 'http://localhost:8081/signalr' var myHub = $.connection.myHub; $.connection.hub.error(function () { console.log("Error!"); }); $.connection.hub.start() .done(function () { console.log("Connected!"); }) .fail(function () { console.log("Could not connect!"); }); }); </script> This code works properly when I am using the Server's web browser as it can access http://localhost:8081/signalr/hubs. However, when you browse the site externally via http://serverip, the SignalR fails because the JQuery script is looking for a http://localhost:8081/signalr (which I believe it looks for on your local computer). I have changed: $.connection.hub.url = 'http://serverip:8081/signalr' and I enabled browsing of the website on 8081 and can browse to the website via http://serverip:8081. However, browsing to http://serverip:8081/SignalR/Hubs can not find the hub file that is available from http://localhost:8081/siganlr/hubs. Also, as a test I enabled SignalR within the ASP.NET web application via the App_Start folder -> RegisterHubs.cs file : RouteTable.Routes.MapHubs(); Doing this allows me to browse to http://serverip:8081/signalr/hubs or http://serverip/signalr/hubs and I can see the hubs being generated by the ASP.NET website. This is not what I want because this is not the hubs I am hosting from my C# WinForms application. Once again, browsing to http://serverip:8081/signalr/hubs does not find signalr or the hubs file that exists on http://localhost:8081/signalr/hubs. Does anyone know how I can make this file available to my ASP.NET web application so that I can make SignalR work externally? EDIT: I forgot to mention 8081 is open on the server firewall. Change it to: string url = "http://*:8081/"; m_signalrServer = new Microsoft.AspNet.SignalR.Hosting.Self.Server(url); Thank-you. This has fixed my issue. After lots of searching, yesterday I also found this post which has to do with your answer as well as the issue I was having: https://github.com/SignalR/SignalR/issues/684 (in case anyone else runs into this).
common-pile/stackexchange_filtered
C++ looping through a vector of structure say I have struct S { double A; double B; double C; }; and std::vector<S> vecS(10); I am trying to write a generic function void F(std::vector<S> vecS,structure S.x) such that the following computation can happen F(std::vector<S> vecS, structure S.x) { for(i=1;i<10;i++) vecS[0].x += vecS[i].x; // note the structure does not have memeber "x" // I want to give that as a generic input to access A,B or C } The above code is not correct code, but I am just trying to demonstrate what I am trying to compute. What I am trying to compute is loop over the vector of structs for a specific element. Is this possible in a simple nice way? Can someone please give me some pointers how to access a member of a structure in a generic way (maybe that is what I need to write this function). Thanks in advance. This is a bit like http://stackoverflow.com/a/3205057/667798 - I'd suggest doing an accumulate over the vector using a lambda expression that extracts the member variable you want. What you need is a pointer to member: void F( std::vector<S> &vecS, double S::*ptr ) { for(i=1;i<10;i++) vecS[0].*ptr += vecS[i].*ptr; } // now call for A F( vec, &S::A ); If you need it to work with different types, not only double as in this case, use template. PS I did not notice first, but you have to pass vector as reference, as you modifying element in it. Well, it's not generic in the sense that you have a vector hardcoded, but let's ignore that for a second. What you want is a pointer-to-member: template <typename T, typename M> F(std::vector<S> vecS, M T::* member) { for(i=1;i<10;i++) vecS[0].*member += vecS[i].*member; } Call as F(vec, &myClass::A) The concept you are looking for is called a pointer to member. You can't use the exact syntax as you have written, and pointer to member syntax is rather ugly and not commonly used. But here's the basics. double S::*x = &S::A; vecS[0]->*x += vecS[i]->*x See the following for more details: http://en.cppreference.com/w/cpp/language/operator_member_access#Built-in_pointer-to-member_access_operators http://en.cppreference.com/w/cpp/language/pointer Also, unrelated to your question, but you need to declare the type of your loop variable i. Currently, it is undefined.
common-pile/stackexchange_filtered
Mounted ExFat Disk: No such file or directory I'm using an ExFat external disk on Ubuntu 18.04.4 with auto-mount but after a while I can't copy or edit items on the disk anymore but the items are still accessible. After a system-restart I can write to the drive again. Followed steps: 1 - sudo apt install exfat-fuse exfat-utils 2 - sudo mkdir /home/user-folder/NETWORK-HDD 3 - Edit sudo nano /etc/fstab 4 - Add line: UUID=****-**** /home/user-folder/NETWORK-HDD auto defaults 0 0 5 - sudo mount -a Be advised that I'm not an expert in Linux, just started using it. Are you seeing an error message when you try to edit / copy files to the disk? Check that you are the owner of those files (right click and see properties, or chown in terminal) Yes, shows me the following error: No such file or directory and yes I'm the owner Well I found the culprit. Filenames with a colon are the issue. Whenever I tried to copy a file with a colon in the name to or from the mounted disk it failed. Removing the colons fixed the issue.
common-pile/stackexchange_filtered
What kind of metadata does a file actually contain? What kind of metadata does a file actually contain? I realize that this varies by the type of format, but I am specifically talking about the metadata universal for all files on a UNIX filesystem. Hence I will use plaintext as an example, since I'm not aware of any file specific metadata that would be in a plaintext file. If I have a plaintext file, and I transfer it to another computer via a flash drive, is the inode for the file copied? I know you can get things from the inode like the last modification time, permissions, etc. But are there any types of metadata separate from the inode? Is it possible to figure out anything about the computer it came from? What about in the case of an image file? I will use plaintext as an example... A plain text file does not contain any meta data, i.e. it is only an octet stream without structure. The only thing meta on this octet stream is its size. But, if stored on a UNIX file system there are several meta data associated with this octet stream, like the file name, modification time, owner, group, permissions, maybe ACL's etc. ... I transfer it to another computer via a flash drive, is the inode for the file copied? The inode itself is specific to the instance of the underlying file system. It will not be copied over to the flash drive. But some of the information contained in the inode might be, like the modification time. But the details depend on the capabilities of the underlying file system of the target, i.e. different file systems support different kind of information in the inode (or similar data structures). For example a (V)FAT file system which is usually used of flash drives does not support UNIX file permissions. It also depends on the way the copying was done, i.e. simply calling cp will not copy over the modification time but set it to the current time in the target. And even if the target system supports UNIX file permissions and owner, the original owner cannot be copied over unless the user doing the copy has the permissions to set the owner (i.e. is root). ... But are there any types of metadata separate from the inode? The file name itself and the directory are not contained in the inode. In UNIX you could even have different file names or some file names within different directories point to the same inode, which essentially means that some same data can be accessed from different path. What about in the case of an image file? There are a variety of file formats for images with different capabilities. For example JPEG files can contain EXIF, IPTC or XMP blocks which are contains for a variety of meta data, like creation time of the photo, camera used, location where the photo was taken, copyright information and much much more. Since these information are contained in the octet stream of the image file these will be implicitly copied too when the file is copied. Just a complement to the detailed @Steffen's answer. A file is normally nothing more than a sequence of bytes and may contains its own meta data. BUT meta data is also contained in the file system. For example in Unix filesystems, the name is contained in the directory and the size, last read an write access time, owner, etc. are contained in the inode. In that case when you copy the file only the data is copy, and not the meta data - even if you can ask the system to copy the times and owner and group ids. But Windows NTFS is much richer. Any file is composed of data streams. The main one (the only one you normally access) contains the file data, but you can add as many streams as you want to store arbitrary meta data (or hidden data). They will not be accessible by normal accesses, but I can confirm that they are transported by (some) Microsoft tools like command line copy when the file is copied to another NTFS disk - simply they are discarded when you use another file system, upload them in an email or via any network protocol, because only the main data stream is concerned here. In that case, a mere text file could transport arbitrary meta data. Example: > echo foo > bar.txt > echo bad > bar.txt:mood > copy bar.txt bar2.txt > type bar.txt foo > type bar2.txt foo > more < bar2.txt:mood bad I think this question should be moved to the server fault section. This has nothing to do with information security. You are mixing up file system and file format. File system usually deal with the file access, it has nothing to do with the content. While the file format define how the contents can be interpreted/parsed by program that read it. Universally speaking, a file meta is always refer to file format. To quickly identify a file, standard is enacted to assign specific "signature" to a file. You can check out wikipedia file signature entry to learn about this. Apparently, the question is about file transfer between file system. In fact, file system access right stayed with the assigned storage of the file system, it cannot cross the border. When file transfer from a Unix system to another unix system , the file will follow the destination file system access write assign with the user access. If If you happens to take out the whole Linux hard drive and mount it from another OS without encryption, the host OS actually able to access everything with little trouble, regardless of the access right constraints of the files rights assign in the mounted hard drive.
common-pile/stackexchange_filtered
Dilemma with window.onbeforeunload and image The following is my main JS file: window.onbeforeunload = function () { showME(); } var ShowMe = function(){ $('<img src="http://cdn.sstatic.net/stackoverflow/img/sprites.png" style="position:fixed;left:0;top:0" />').appendTo('body'); } When window.onbeforeunload gets called (i.e user navigating away from the page) ShowMe() gets executed but I do not see the image on the page. However if you run showMe() in your console the image will show. This is happening in all non-FireFox Browsers. Firefox seems to work fine. maybe it is happening due to the fact that on window unload the request to the image is stopped? how about trying to to an alert before / after the image to see what of that code piece is really executed as an alert stops the browser Thanks for your reply. Yes I did a console.log('before') and console.log('after') and both get called. In fact, when I look at the DOM i see the image get attached to the body, it just doesn't get rendered for some reason. is it in action somewhere so I can take a deeper look? I know I'm a bit late to the party, but the problem can be solved by performing the image insertion in an event instead, using setTimeout with a time of 0 (or leave it out, as 0 is default).
common-pile/stackexchange_filtered
Select programmatically front first button to last button I am finishing software for disabled people with muscular dystrophy. How to programmatically select the first button, after second select second button, after second next button. This select first button to last button in the loop with the second delay. I am a beginner in c#, please for working examples. I tried below code: Count++; Cursor.point = pointtoscreen(button[Count]); The above code is not working. Does pointtoscreen do anything if you call it like this pointtoscreen(0);? If not, you need to get that working expressly before we can get it working procedurally I am beginner, can't create working code. I am need examples To do anything repeatedly with some time between you would use a timer. To select a button, or any other control you would call 'focus' to 'select' it. To move focus between different controls you would need some kind of list to iterate over, but there is also a tabIndex that may be used to provide a order for all controls. So create a timer and an index. When the timer elapses you increment the index, find the control with the corresponding tabIndex, and focus it. You might also need some logic to wrap around to zero index. An alternative would be to simulate pressing the tab-key. Thx, you solution is beter, like main solution
common-pile/stackexchange_filtered
Installing Ubuntu and problem with boot loader (Trying with Try Ubuntu 14.04 version) [Currently there is no operating system installed in the PC] I have been trying to install ubuntu 14.04 in my PC. The problem I'm having is that problem in installing grub in software. [ What I think the problem is in my hard-disk file system. I tried to wipe it out using G-Parted but, some of the file named "RIOD" wasn't go disappear. I have tried to fix the boot loader problem but each time it's showing the same problem. Do you have any idea how I can reformat the hard rive and install a ubuntu? I don't care about previous memory of my hard drive. jpg There is a direct command bcdedit /set "{bootmgr}" path \EFI\ubuntu\grubx64.efi to show grub menu on boot, but to execute, you need access to Windows OS. The steps are: Boot into Windows OS Combine Windows + r together and type cmd to open command prompt. Type bcdedit /set "{bootmgr}" path \EFI\ubuntu\grubx64.efi and hit Enter P.S : To get dual boot working fine on my dell laptop, I took help of this link dual boot windows and ubuntu and I followed above steps too for setting up the grub menu and it worked. I would advice you to crosscheck your process with the above mentioned link. It will help you understand if you are missing something during the installation process just in case. So what you are saying is that, formatting hard disk using windows operating system, and then install the ubuntu? First check the link to see if you have performed every step given there. If you are sure that you installed Ubuntu properly, then Boot into Windows. 2) Press Ctrl + r keys and type cmd] . 3) Once you are in command prompt window, just type bcdedit /set "{bootmgr}" path \EFI\ubuntu\grubx64.efi and hit Enter key. The command will execute. Once done, restart your system and you will be presented with Grub menu (if Ubuntu got installed successfully in the first step). We will format the Ubuntu partition using Windows OS if we have to reinstall Ubuntu all over again. The problem is that, I couldn't install the ubuntu successfully. That was the "try ubuntu" version then in that case brother, you need to first install Ubuntu on a separate partition. Once you have installed it, then you can follow the steps for setting up grub menu. Just follow the link I gave and the steps I mentioned, all will be fine. Still if you encounter any issues, let us know. But the hard drive is not taking the ubuntu installation. The first picture is added here where the installation failed each time. Take a complete backup of your Windows OS data on a separate portable hard disk. Boot into Gparted and wipe out your hard disk completely deleting all Windows and other partitions. Reinstall Windows afresh using bootable USB recreating all partitions. . Once done, then initiate Ubuntu installation using a bootable USB. Use Universal USB Installer software for creating bootable USB in both the cases.
common-pile/stackexchange_filtered
How do I dereference a pointer that is an element of an array that is passed into a function So I am working on a homework assignment that requires us to take an integer array and create a parallel array of pointers that will then point to the corresponding element in the original array. We are then to sort the array of pointers into numerical order, and use a bubble sort in a function to do so. My question is, once the array of pointers is passed to the function, how do I dereference back to the value that the element pointer points to so that i can use comparisons in the bubble sort, switch values, and output the sorted arrays? Am i right to pass the array of pointers into a pointer, or should I pass the actual array into the function? Code as it is currently below. #include <stdio.h> void sort(int *[], int); void swapvalues(int *, int *); int main() { int dataarray[] = { 0, 0, 0, 0, 123, 124, 125, 3000, 3000, 82, 876, 986, 345, 1990, 2367, 98, 2, 444, 993, 635, 283, 544, 923, 18, 543, 777, 234, 549, 864, 39, 97, 986, 986, 1, 2999, 473, 776, 9, 23, 397, 15, 822, 1927, 1438, 1937, 1956, 7, 29, -1 }; int *ptrarray[100]; int flag1 = 0; int flag2 = 0; int flag3 = 0; int i = 0; int j = 0; int k = 0; const int size = sizeof(dataarray) / sizeof(int); for (i; i <= size; i++) { ptrarray[i] = &dataarray[i]; } sort(ptrarray, size); return 0; } void sort(int ptrarray[], int size) { int i = 0; int j; for (i; i < size; i++) { j = 0; for (j; j < (size-1); j++) { if ((*(ptrarray + j)) == (*(ptrarray + (j + 1)))) { swapvalues(ptrarray, j); } else continue; } } } void swapvalues(int *ptrarray, int j) { int holder; holder = *(ptrarray + j); *(ptrarray + j) = *(ptrarray + (j + 1)); *(ptrarray + (j + 1)) = holder; } Please format your code in a readable way. downvote: you asked this question because you didn't listen to a single word of your CS lectures. What's the purpose of ptrarray ? Just call your sort function directly on dataarray. The assignment says we are supposed to leave dataarray untouched and make an array of pointers that point to dataarray to be sorted. And I do listen, sir, the explanation of this topic just left a lot to be desired. @RussellDavis Did you even compile it ? Not yet since the logic I'm using is unworkable/won't compile. @RussellDavis What exactly is your question? Title is bit confusing. for (j; j < (size-1); j) what is this supposed to do ? If it won't even compile then asking how to solve the problem is getting ahead of yourself. Get what you have to compile first then ask how to fix it. You should just pass the array in, not a pointer to it as C will not actually copy the array it will use a pointer to it anyway. Then, to dereference the pointers you could use *(ptrarray[j]) where j iterates from 0 to the size of the array. It would also be valid to do **(ptrarray+j), which would first dereference the array pointer to get the element pointed at, and then dereference that element to get the original value. Hmm, I don't think thats correct. In the statement *(ptrarray+j) the array pointer is dereferenced, but the pointer that's stored there is not. Also, the poster wasn't asking what was wrong with his code involving the for loop, he just wanted to know how to dereference the array correctly. That's still wrong. *(ptrarray[j]) does not equal *(ptrarry+j). One performs one dereference, the other performs two... I updated my code, and tried implementing what you suggested, but it did not appear to work, as the program does basically nothing (the array of pointers does not sort). Something that seems somewhat confusing about your original solution is the line if (((ptrarray + j)) == ((ptrarray + (j + 1)))). If you wanted it to sort, I think you would need to be doing some kind of > or < comparison, not checking to see if they are equal. Swapping two equivalent values will not actually change the array. First of all this code will not compile as you function sort - void sort(int *[], int); ^array of pointers void sort(int *ptrarray, int size) ^pointer So compiler will give error. Declare function as - void sort(int **ptrarray, int size) And also increment j in this for loop- for (j; j < (size-1); j) ^ You can't call this: void sort(int ptrarray[], int size) With this: int *ptrarray[100]; sort(ptrarray, size); As sort is expecting an array of int, while you're passing it an array of int *. sort should be declared as: void sort(int *ptrarray[], int size) Also, this: if ((*(ptrarray + j)) == (*(ptrarray + (j + 1)))) Is comparing the pointers themselves, not the values they point to, which is what you really want to compare, and it's not the right comparison. You instead want this: if (*(ptrarray[j]) > *(ptrarray[j + 1])) I'd recommend sticking with the a[i] syntax rather than the *(a + i) syntax as it's more clear. Your swap function should also change to take pointers to two ints: void swapvalues(int *a, int *b) { int holder; holder = *a; *a = *b; *b = holder; } Then you call it like this: swapvalues(ptrarray[j], ptrarray[j+1]); Your loop initialization is also off. Here's the full sort function: void sort(int *ptrarray[], int size) { int i,j; for (i = 0; i < size - 1; i++) { for (j = i; j < (size-1); j++) { if (*(ptrarray[j]) > *(ptrarray[j + 1])) { swapvalues(ptrarray[j], ptrarray[j+1]); } else continue; } } }
common-pile/stackexchange_filtered
AVAssest initialisation with url from youtube adaptive formats is taking time to load video AVasset is taking time to load(For only video formats). But simple formats is not taking time(Merged video and audio). The issue was even reproduced in AVPlayer(url: URL(string:*The url retrieved from YouTube api/ as! String)!)* func mergeFilesWithUrl(videoUrl:URL, audioUrl:URL, completion: @escaping (Bool) -> (Void)) { let mixComposition : AVMutableComposition = AVMutableComposition() var mutableCompositionVideoTrack : [AVMutableCompositionTrack] = [] var mutableCompositionAudioTrack : [AVMutableCompositionTrack] = [] let totalVideoCompositionInstruction : AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction() let aVideoAsset : AVAsset = AVAsset(url: videoUrl) //Here is the issue let key = "playable" DispatchQueue.main.async { aVideoAsset.loadValuesAsynchronously(forKeys: [key], completionHandler: { let status = aVideoAsset.statusOfValue(forKey: key, error: nil) if status == AVKeyValueStatus.loaded { let aAudioAsset : AVAsset = AVAsset(url: audioUrl) aAudioAsset.loadValuesAsynchronously(forKeys: [key], completionHandler: { let status1 = aAudioAsset.statusOfValue(forKey: key, error: nil) if status1 == AVKeyValueStatus.loaded { mutableCompositionVideoTrack.append(mixComposition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)!) mutableCompositionAudioTrack.append( mixComposition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid)!) let aVideoAssetTrack : AVAssetTrack = aVideoAsset.tracks(withMediaType: AVMediaType.video)[0] let aAudioAssetTrack : AVAssetTrack = aAudioAsset.tracks(withMediaType: AVMediaType.audio)[0] do{ try mutableCompositionVideoTrack[0].insertTimeRange(CMTimeRangeMake(kCMTimeZero, aVideoAssetTrack.timeRange.duration), of: aVideoAssetTrack, at: kCMTimeZero) try mutableCompositionAudioTrack[0].insertTimeRange(CMTimeRangeMake(kCMTimeZero, aAudioAssetTrack.timeRange.duration), of: aAudioAssetTrack, at: kCMTimeZero) } catch{ } totalVideoCompositionInstruction.timeRange = CMTimeRangeMake(kCMTimeZero,aVideoAssetTrack.timeRange.duration ) let mutableVideoComposition : AVMutableVideoComposition = AVMutableVideoComposition() mutableVideoComposition.frameDuration = CMTimeMake(1, 30) mutableVideoComposition.renderSize = CGSize(width: 1280,height: 720) self.mixComposition = mixComposition _ = completion(true) } }) } }) } } merged audio and video is very likely to be loading from the disk, the youtube video will need to be at least part downloaded to play. This then depends on your network speed, usage etc Only video is also taking time. If I load already merged url than it is not taking time
common-pile/stackexchange_filtered
Use Font Awesome with "background: url" css I have a dream ! This 'star' is generated with Font Awesome. star1 I wan't to replace the green color with an image like this : star2 This is a Fiddle with what i have try: http://jsfiddle.net/jmcpeak/M6N24 background: url(https://paperpackagingplace.com/wp-content/uploads/2016/01/yellow-2.jpg) -100px -40px no-repeat; -webkit-background-clip: text; -webkit-text-fill-color: transparent; Do know how i can do this ? Have you checked This Article. Also, in this case the i elements work a little differently. In the i elements the text is used in the content definition for the ::before element. You could play with that definition specifically. You can use the following example, you just have to play with the background positioning and size. .fa-star { font-size: 5rem !important; } .fa-star::before { color: white; background: url(https://ktfnews.com/wp-content/uploads/2017/10/World-512x360.jpg) no-repeat left center; -webkit-background-clip: text; -webkit-text-fill-color: transparent; } <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <i class="fa fa-star"></i> What you could do otherwise is copy the character from FontAwesome 4.7's cheatsheet as text and just make a class that uses FontAwesome as a font. Something like this (the square in the h1 element is a copied icon from the cheatsheet, it appears like that since it's not a standard character: .awesome { font-family: "FontAwesome"; font-size: 10rem; color: white; text-align: center; background: url(https://ktfnews.com/wp-content/uploads/2017/10/World-512x360.jpg) center center no-repeat; -webkit-background-clip: text; -webkit-text-fill-color: transparent; } <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <h1 class="awesome"></h1> Thanks you very much and sorry for have link bad Fiddle Depends on which icon you want to change, you just need to target specific class or all i elements. .fa-star:before { background: url(https://ktfnews.com/wp-content/uploads/2017/10/World-512x360.jpg) -100px -40px no-repeat; background-clip: text; -webkit-background-clip: text; color: transparent; } <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <i class="fa fa-star fa-stack-2x"></i> Thanks you very much and sorry for have link bad Fiddle
common-pile/stackexchange_filtered
What is the easiest way to change windows with Sikulix? If I am within a GUI, interacting with said GUI using python 2.7 and sikulix API. If I click on something from within that GUI that opens another window in full screen, sikulix is currently having difficulty interacting with the newly opened window, it can still for some reason only see the old window even though it is underneath. I am able to make the newly opened window smaller, then take the original window and drag it down to a lower place in the screen, then re-maximize the new window and this will allow me to interact with the new window. --- Is there a better way to do this? (using CentOS) If you already know the process exe name of the application you will be running form the gui, you can create an App reference linked to that app, such as: yourApp = App("yourApp.exe") From here, if you would like to click on something that belongs only to this window, you can create a region off of the new window which should be focused automatically after launching. This can be done like: yourReg = Region(yourApp.focusedWindow()) From here, you can use this region to click items on the window such like: yourReg.click(CancelButton.png) Sikuli "sees" whatever there is on the screen so if there is a window, Sikuli can't ignore it. What probably happens in your case is that you progress too fast and Sikuli is still observing the previous screen. What you need to do is to wait sufficient time to ensure the new window has actually opened. I have added a "safewait" command to wait until whatever I am looking for on said screen has come up and opened, but no matter how long I wait (times out after 20 seconds, 19 of which the window is open) I am still unable to interact with the new window. There is some issue with your screenshot then. Ensure there aren't even tiniest differences between the actual screen and your pattern. It must be similar on pixel level. I have made sure the screenshot is fine, once I drag the initial window down and remaximize the new one the same screenshots work just fine.
common-pile/stackexchange_filtered
WinRT Acessing GridView in a Listview in a Grid I have a Grid with a GridView and a ListView in it. I would like to change the datatemplate of the GridView while the program is running by using GridView.ItemTemplate, but the problem is I cannot access the name of the GridView. The sample of the code: <Grid> ... Some Grid properties, etc <Text> ...Some Text above to accompany the desciprition of listview <ListView x:Name = "somethinginthemiddle" ... ListView properties, location in grid, etc.> ... <Grid> <GridView x:Name = "IWantToAccessThis" </GridView> </ListView> </Grid> </Grid> Edit: Might worth noting that there may be more than one gridview generated. Should I attempt to go through ListView children? Do you mean you want to access the x:Name property of that GridView? Or is it you cannot access the GridView with its name? The gridview has its Name, in this case IWantToAccessThis, however, I cannot access it from the code. Like IWantToAccessThis.Name? You can't do that, or at least no easy way. I can explain more if this is your question. IWantToAccessThis.ItemTemplate would be my target. I'm not sure but your code seems to be a little messy, how can you place a GridView under a Grid? If your code became: <ListView.View> </ListView.View> you can definitely access "IWantToAccessThis". Sadly you cant access the gridview directly using name property as now your gridview is an ItemTemplate of your Listview. You would need to access the itemtemplate of your listview firt then typecast it as gridview and access that itemtemplate How would I go about casting itemtemplate to gridview? It doesn't allow me to do it directly. This might be helpful. In the xaml file: <Page.Resources> <DataTemplate x:Key="TestTemplate"> <Grid> <Border Background="LightGray" Height="200" Width="200"> <TextBlock Text="{Binding}" FontSize="48" Foreground="Green"/> </Border> </Grid> </DataTemplate> </Page.Resources> <Grid Background="White"> <TextBlock>Header</TextBlock> <ListView x:Name = "somethinginthemiddle"> <Grid> <GridView x:Name = "IWantToAccessThis"> <GridView.Items> <x:String>One</x:String> <x:String>Two</x:String> </GridView.Items> </GridView> </Grid> </ListView> </Grid> In the xaml.cs file: public MainPage() { this.InitializeComponent(); IWantToAccessThis.ItemTemplate = Resources["TestTemplate"] as DataTemplate; } Here you can see how to get access to IWantToAccessThis and how to set the ItemTemplate on this control.
common-pile/stackexchange_filtered
How to convert timestamp in the form of yyyy-mm-dd hh:MM:SS.mil to epoch time in Athena I have a table that has a timestamp attribute of the form 2022-01-01 01:09:23.500. this needs to be converted to epoch time of the form<PHONE_NUMBER>0000. Do we have anything like this in Athena? If I understood right your question, Have you tried this exemple SELECT CAST(DATEDIFF(s, '1970-01-01 00:00:00', your date) AS BIGINT) Thanks for your approach. What is "s" here. Let me be more specific: Lets' say the table we have is ABC and the column we have is XYZ. If I query this column, I get the following: XYZ 2021-06-17 00:51:43.432; 2021-06-17 00:00:16.755; 2021-06-17 00:00:27.195; 2021-06-17 00:00:28.262; I need to convert this into their equivalent epoch time. Anyways, after a few hit and trial, I got the solution: cast(cast(to_unixtime(CAST(date_col AS timestamp)) as bigint) * 1000000 as varchar) This converts the timestamp into epoch time.
common-pile/stackexchange_filtered
How to get in one query an item and another item having one of its value nearest of the former one? Imagine I have the following table : ID || Order ----------- 1 || 1 2 || 2 3 || 5 4 || 20 5 || 100 6 || 4000 (no specific rule applies to the order value). I want to "move up" ou "move down" items by swapping order values. Ex: a call to MoveItemUp(4) will results in this new table values : ID || Order ----------- 1 || 1 2 || 2 3 || 20 <-- swapped order value 4 || 5 <-- swapped order value 5 || 100 6 || 4000 I want to do this in a single query, but I was not yet successful. The following query works if items order are sequential, with no "hole" (steps of 1 :) UPDATE dbo.ITEMS set ORDER = case when c.ORDER = c2.ORDER then c.ORDER +1 else c.ORDER -1 end from dbo.ITEMS c inner join dbo.ITEMS c2 on c.ORDER = c2.ORDER or c.ORDER = c2.ORDER + 1 where c2.ID=4 However, I was not able to change this query to support hole. I'm trying to do : UPDATE dbo.ITEMS set case when c.ORDER = c2.ORDER then min(c2.ORDER ) else c2.ORDER end FROM dbo.ITEMS c inner join ITEMS c2 on c2.ORDER >= c.ORDER where c2.ID=4 group by c.CAT_ID, c.ORDER having c.ORDER = min(c2.ORDER ) or c.ORDER = c2.ORDER However, this does not works as expected (the query updates all items having a greater order instead of the two orders to swap). PS: I'm working with C# 2.0 on Sybase ASE 4.5, but I assume this question is not specific to this platform. If you have a MSSQL, MySql or Oracle equivalent, I'll put effort to convert it ;) Can there be holes in the sequence of ID? Chances are yes, but if not, change the join criteria to c2.ORDER = c.ORDER + 1. Unfortunately, yes... actually, I have logically deleted items (a flag to exclude from all queries, to be simple), and categories. NOTE All below solutions assume that ItemOrder is unique EDIT Adding a solution that is more like what OP was trying, and may be more portable to Sybase, this time on Microsoft SQL Server 2008. (See below for solutions using Oracle's analytic functions, that may be more efficient if available.) First the select to get our row selection criteria correct: declare @MoveUpId int set @MoveUpId = 4 select current_row.Id , current_row.ItemOrder , prior_row.id as PriorRowId , prior_row.ItemOrder as PriorItemOrder , next_row.id as NextRowId , next_row.ItemOrder as NextItemOrder from #Items current_row left outer join #Items prior_row on prior_row.ItemOrder = (select max(ItemOrder) from #Items where ItemOrder < current_row.ItemOrder) left outer join #Items next_row on next_row.ItemOrder = (select min(ItemOrder) from #Items where ItemOrder > current_row.ItemOrder) where @MoveUpId in (current_row.id, next_row.id) Then the update based on the above: update current_row set ItemOrder = case when current_row.Id = @MoveUpId then prior_row.ItemOrder else next_row.ItemOrder end from #Items current_row left outer join #Items prior_row on prior_row.ItemOrder = (select max(ItemOrder) from #Items where ItemOrder < current_row.ItemOrder) left outer join #Items next_row on next_row.ItemOrder = (select min(ItemOrder) from #Items where ItemOrder > current_row.ItemOrder) where @MoveUpId in (current_row.id, next_row.id) Id ItemOrder 1 1 2 2 3 20 4 5 5 100 6 4000 10 -1 20 -2 Set @MoveUpId to 20 and rerun above query results in: Id ItemOrder 1 1 2 2 3 20 4 5 5 100 6 4000 10 -2 20 -1 but I assume this question is not specific to this platform. The question may not be specific, but the answer probably is. For example, using Oracle, first, a table and some test data: create table Items (Id number(38) not null , ItemOrder number); insert into items values (1, 1); insert into items values (2, 2); insert into items values (3, 5); insert into items values (4, 20); insert into items values (5, 100); insert into items values (6, 4000); insert into items values (10, -1); insert into items values (20, -2); commit; Next create a query that returns just the rows we want to update with their new values for Order. (Which I named ItemOrder, Order being a reserved word and all.) In Oracle this is simpliest using the analytic functions lag and lead: select * from (select Id , ItemOrder , lead(Id) over (order by Id) as LeadId , lead(ItemOrder) over (order by Id) as LeadItemOrder , lag(ItemOrder) over (order by Id) as LagItemOrder from Items) where 4 in (Id, LeadId) order by Id; ID ITEMORDER LEADID LEADITEMORDER LAGITEMORDER ---------- ---------- ---------- ------------- ------------ 3 5 4 20 2 4 20 5 100 5 Convert that into an update statement. However the above query will not create an updateable view (in Oracle), so use merge instead: merge into Items TRGT using (select Id , ItemOrder , lead(Id) over (order by Id) as LeadId , lead(ItemOrder) over (order by Id) as LeadItemOrder , lag(ItemOrder) over (order by Id) as LagItemOrder from Items) SRC on (SRC.Id = TRGT.Id) when matched then update set ItemOrder = case TRGT.Id when 4 then SRC.LagItemOrder else SRC.LeadItemOrder end where 4 in (SRC.Id, SRC.LeadId); select * from Items order by Id; ID ITEMORDER ---------- ---------- 1 1 2 2 3 20 4 5 5 100 6 4000 10 -1 20 -2 Unfortunately, I do not believe lag and lead are widely implemented. Microsoft SQL Server, as far as I know, has yet to implement them. No experience with ASE, it they have them great. Row_number() is more widely implemented. Row_number() can be used to get something that is gap free. (Row_number() is refered to as an analytic function on Oracle and a windowed function on SQL Server.) First the query: with t as (select Id , ItemOrder , row_number() over (order by Id) as RN from Items) select current_row.id , current_row.ItemOrder , next_row.Id as NextId , next_row.ItemOrder NextItemOrder , prior_row.ItemOrder PriorItemOrder from t current_row left outer join t next_row on next_row.RN = current_row.RN + 1 left outer join t prior_row on prior_row.RN = current_row.RN - 1 where 4 in (current_row.id, next_row.id); ID ITEMORDER NEXTID NEXTITEMORDER PRIORITEMORDER ---------- ---------- ---------- ------------- -------------- 3 5 4 20 2 4 20 5 100 5 Doing the update, again with merge instead of update. (Oracle does allow the update ... from ... join ... syntax, one may be able to get away with update instead of merge on other platforms.) merge into Items TRGT using (with t as (select Id , ItemOrder , row_number() over (order by Id) as RN from Items) select current_row.id , current_row.ItemOrder , next_row.Id as NextId , next_row.ItemOrder as NextItemOrder , prior_row.ItemOrder as PriorItemOrder from t current_row left outer join t next_row on next_row.RN = current_row.RN + 1 left outer join t prior_row on prior_row.RN = current_row.RN - 1 where 4 in (current_row.id, next_row.id)) SRC on (TRGT.Id = SRC.Id) when matched then update set ItemOrder = case when TRGT.Id = 4 then SRC.PriorItemOrder else SRC.NextItemOrder end; select * from Items order by Id; ID ITEMORDER ---------- ---------- 1 1 2 2 3 20 4 5 5 100 6 4000 10 -1 20 -2 NOTE Note the solutions above will write null over OrderItems if matching against the Id for the first row.
common-pile/stackexchange_filtered
Workflow for modelling the final prodcut of a chemical reaction I have done some DFT simulations before in cp2k and siesta but the kind of systems I am about to study is new to me so I would appreciate it if I got helpful suggestions from the experts. The system is experimentally synthesized starting from an aqueous solution of two polymers which is then drop-cast on a surface. The surface is heated afterwards to remove water. I am only interested in studying the properties of the final product (such as the geometry, the energy levels, etc). What is the best workflow to study such a system using DFT (Due to limitations on resources I have access only to DFT packages)? I am thinking of optimizing each polymer separately, optimizing the surface, then put them together in one run. Thanks. er Why do you think the surface matters? Is that part of the reaction? Do you already know the identity and/or structure of the product? If you do that will remove you first big hurdle :) The surface matter a lot and I do not exactly know the molecular structure of the product. I only have SEM images and I want to see how exactly the atoms are bonded.
common-pile/stackexchange_filtered
When using Windows Deployment Services asks to reauthenticate We Use WDS to reimage computers over the network. When starting the install over the network it asks us to associate with the domain and user and password. However towards the end it makes us enter our domain username and password again. Is there anyway I can get it to install all the way through without asking to re authenticate? You could try using Windows System Image Manager (apart of the Automated Install Kit) to create an unattend file, that specifies the domain and credentials with in it.
common-pile/stackexchange_filtered
Control volume using right click and wheel, like volumemouse and volume2 Ubuntu 18.04: Coming from Windows, I had these 2 apps I could use (volumemouse, volume2) to control the volume using this gesture: right click + wheel is there anything like that for ubuntu? Thanks what is your OS?? ubuntu 18.04 19.04 16.04 etc?? @PRATAP 18.04, I updated the question I did not try yet.. but seems possible with xbindkeys.. will try in a while.. meanwhile you can study man xbindkeys
common-pile/stackexchange_filtered
technology to switch html to php in a website after some days learning html and css i have got used to programming in html, my skills are improving and i could program a site with css which looks very good... now my next step is to learn using a current technology for web2.0 like php all my pages end in html extension but i want to change them to php extension so the site will be more current and work with better technology. i have read many manuals but i cannot find how to switch my work from html into php technology link to the work http://preferredmerchantservices.net/ thanks php code does not work by setting the php extension.you really have to do some research on what is php HTML and CSS are not programming languages. PHP is, though, and understanding the difference is pretty key to your 'problem'. well technically PHP is a scripting language right? PHP dynamically generates HTML and what HTML it creates depends on what you want your website to do. First, please tell us why you want to convert your site to using PHP and what features you want to implement on it. That will help us give you better responses. scripted or compiled, both are programming, FYI PHP is a programming language. HTML and CSS are markup languages. You don't convert HTML to PHP. PHP can be used to generate HTML, like it can be used to generate many other formats. Changing your file extensions from *.html to *.php is not going to magically make your "current." Also, another thing to consider is that many programmers will name their PHP documents differently based on the content contained within them. For example, any files I write that contain nothing but PHP and don't directly output to the browser, I will use the *.php extension. However, if a script contains a mixture of PHP and HTML, I will use the *.phtml extension. This behavior is not "standardized," and the PHP parser will treat both files exactly the same (barring your server is configured to recognize both as PHP files). It's more of a personal preference of the developer. Really, what you should do is check out the PHP manual, get an introduction to PHP book, or do a few Google searches on getting started with PHP. it did work by changing extension and i have got php now, sorry but bad answer. No, you do not. Changing the extension to PHP doesn't mean you have a PHP application, unless you have written PHP code in the file. Taking an HTML file with absolutely no PHP in the file and changing the extension does not make it a PHP application. Please read about PHP and how it works before you make accusations of a "bad answer." (Source of Knowledge: I'm a Zend PHP Certified Engineer.) well i am sorry but it worked for me. i dont care how much certified you are when you cannot explain why it worked. greetings Just switch the ending of your files to .php - now you have a php program, although a very boring one that just outputs static HTML. Go anywhere inside that HTML and insert: <?php echo 'This is php, which is ' . (6*7) . ' times cooler than HTML!'; ?> Now, reload the page and watch the output php generated. One more thing: For php code to be executed on the server, you need a server in the first place. If your current URLs start with file://, you'll need to install a webserver(for example apache) with php and let your URLs start with http://localhost/. You can find more about how to configure php (and your webserver) in the php manual. PHP is actually only about 1.857142857 times as cool as HTML. Switch the * to a /. boss ,very little chance OP has web server installed @ajreal Since the OP is linking to his website (or one he created), I wouldn't necessarily say so.
common-pile/stackexchange_filtered
Why does PNG include NLEN (one's complement of LEN)? In the PNG spec, uncompressed blocks include two pieces of header information: LEN is the number of data bytes in the block. NLEN is the one's complement of LEN Why would the file include the one's complement of a value? How would this be used and/or for what purpose? Rather than inventing a new compression type for PNG, its authors decided to use an existing industry standard: zlib. The link you provide does not point to the official PNG specifications at http://www.w3.org/TR/PNG/ but only to this part: the DEFLATE compression scheme. NLEN is not mentioned in the official specs; it only says the default compression is done according to zlib (https://www.rfc-editor.org/rfc/rfc1950), and therefore DEFLATE (https://www.rfc-editor.org/rfc/rfc1951). As to "why": zlib precedes current day high-speed internet connections, and at the time it was invented, private internet communication was still done using audio line modems. Only few institutions could afford dedicated landlines for just data; the rest of the world was connected via dial-up. Due to this, data transmission was highly susceptible to corruption. For simple text documents, a corrupted file might still be usable, but in compressed data literally every single bit counts. Apart from straight-on data corruption, a dumb (or badly configured) transmission program might try to interpret certain bytes, for instance changing Carriage Return (0x0D) into Newline (0x0A), which was a common option at the time. "One's complement" is the inversion of every single bit for 0 to 1 and the reverse. If either LEN or NLEN happened to be garbled or changed by the transmission software, then its one's complement would not match anymore. Effectively, the presence of both LEN and NLEN doubles the level of protection against transmission errors: if they do not match, there is an error. It adds another layer of error checking over zlib's ADLER32, and PNGs own per-block checksum. Super helpful, thanks! Is the idea then that you'd look at LEN and NLEN and, if they weren't the same, you could assume there was an error in transmission somewhere? Is this something that would have been super obvious to someone in 1995 reading the spec? It's a chain of specifications. When working on my own PNG decoder, I worked back from the oldest part – the raw DEFLATE specs. In that sense it's "obvious" as it's "just another part". Thanks – I saw it in the zlib/DEFLATE docs but there's no explanation as to why or how the values are used. Lots of carryover from old tech even today! Yep. But unless you plan to re-make zlib from the ground up (in itself a worthwhile exercise -- but no more than that, an exercise), you can just use Python's built-in zlib for examining PNGs. If this says something cannot be extracted, it's kinda superfluous to examine whether it's due to a bad Huffmann tree (the DEFLATE part), a wrong bit set in CFINFO or a bad Adler32 (both in zlib), or elsewhere. All you really need is the superstructure of PNG, which is fully described in its own specs. If you are concerned about PNG integrity, use pngcheck first. Basically yes, I'm building a zlib decoder from scratch and want to understand all the pieces, both from an historical and technical standpoint. This was super helpful.
common-pile/stackexchange_filtered